paracosm 0.9.1114 → 0.9.1115
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.
- package/dist/dashboard/dist/assets/{index-D3_eknIb.js → index-DZKYPCBt.js} +17 -17
- package/dist/dashboard/dist/index.html +1 -1
- package/dist/server/routes/quickstart.d.ts +14 -2
- package/dist/server/routes/quickstart.d.ts.map +1 -1
- package/dist/server/routes/quickstart.js +13 -5
- package/dist/server/routes/quickstart.js.map +1 -1
- package/dist/server/server-app.d.ts +35 -0
- package/dist/server/server-app.d.ts.map +1 -1
- package/dist/server/server-app.js +295 -54
- package/dist/server/server-app.js.map +1 -1
- package/package.json +1 -1
|
@@ -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 Hp(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 Up(){return(0,x.jsxs)(`section`,{className:Ai.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:Ai.guideHead,children:[(0,x.jsx)(`h3`,{className:Ai.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:Ai.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:Ai.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:Ai.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:Hp,className:Ai.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:Ai.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:Ai.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:Ai.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:Ai.guideExampleCode,children:(0,x.jsx)(`code`,{children:Vp})}),(0,x.jsxs)(`p`,{className:Ai.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 Wp(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:Ai.artifactView,children:[(0,x.jsxs)(`header`,{className:Ai.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ai.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:Ai.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:Ai.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ai.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:Ai.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:Ai.artifactBody,children:s===`turn-loop`?(0,x.jsx)(Rr,{artifact:t}):(0,x.jsx)(Ir,{artifact:t,metricSpecs:u})})]})}function Gp(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:Ai.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(Wp,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:Ai.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:Ai.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ai.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:Ai.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:Ai.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:Ai.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:Ai.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:Ai.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}var Kp=5242880,qp=`/api/v1/library/import`,Jp=new TextEncoder,Yp=e=>Jp.encode(e).length,Xp=Yp(JSON.stringify({addToBundle:`bundle_00000000-0000-0000-0000-000000000000`,artifacts:[]}));function Zp(e){return Xp+e.reduce((e,t)=>e+t.bytes,0)+Math.max(0,e.length-1)}function Qp(e,t){let n=Xp,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 $p(e,t){return`${t===void 0?`{"artifacts":[`:`{"addToBundle":${JSON.stringify(t)},"artifacts":[`}${e.map(e=>e.json).join(`,`)}]}`}function em(e){let t=typeof e==`string`?/Maximum (\d+) bytes/.exec(e):null;return t?Number(t[1]):void 0}function tm(){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`,rm=e=>/[.!?]$/.test(e.trim())?e.trim():`${e.trim()}.`;async function im(e,t={}){let n=e.map(e=>{let t=JSON.stringify(e);return{runId:e.metadata.runId,json:t,bytes:Yp(t)}}),r=[],i=[],a=t.addToBundle??tm(),o=0,s=Kp,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(`, `)}. ${rm(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=>Zp([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:Qp(e,s),f;try{f=await fetch(qp,{method:`POST`,headers:{"Content-Type":`application/json`},body:$p(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=em(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 am(){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(qp,{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 im(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 om(){let e=rT();return(0,b.useMemo)(()=>de(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function sm(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function cm(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=sm(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 lm(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 um={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 dm(){let{state:e}=gn(),t=om(),n=sT();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:um.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:um.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(fm,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:um.branchList,children:e.branches.map(r=>(0,x.jsx)(pm,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function fm({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:um.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:um.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:um.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:um.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:um.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:um.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:mm(t)})]},e))})]})}function pm({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?cm(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:um.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:um.cardHeader,children:[(0,x.jsxs)(`div`,{className:um.branchMeta,children:[(0,x.jsxs)(`span`,{className:um.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:um.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:um.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${um.status} ${um[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:um.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${um.delta} ${um[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:lm(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:um.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:um.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:um.error,role:`alert`,children:e.errorMessage})]})}function mm(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var hm={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function gm({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:hm.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${hm.tab} ${hm.tabActive}`:hm.tab;return(0,x.jsx)(`button`,{role:`tab`,"aria-selected":r,onClick:()=>n(e.id),type:`button`,className:i,children:e.label},e.id)})})}var _m=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],vm={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function ym(e){return!!e&&_m.includes(e)}function bm(e){let{tab:t}=xm(e);return t}function xm(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&vm[n])return vm[n];if(ym(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&vm[i]?vm[i]:ym(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function Sm(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function Cm(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 wm(e,t){if(!t)return Sm(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 Tm=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function Em({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),Cm(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=am(),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:Ai.tab,children:[(0,x.jsx)(gm,{options:Tm,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(dm,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Up,{}),(0,x.jsx)(Bp,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Ai.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:Ai.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:Ai.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(Wp,{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)(Gp,{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)(Ei,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function Dm(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 Om(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 km(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 Am(e,t,n=`viz`){return ut(e,t,n)}function jm(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 Mm=`/assets/pdf.worker.min-CIqJB0yW.mjs`,Nm=`modulepreload`,Pm=function(e){return`/`+e},Fm={},Im=function(e){return e.pathname.endsWith(`.css`)},Lm=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},Rm=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=Pm(t,n);let r=s(t),i=Im(r);return Lm(Fm,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`:Nm,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 zm(){if(typeof window>`u`)return Mm;try{return new URL(Mm,window.location.origin).toString()}catch{return Mm}}var Bm=null;async function Vm(){if(Bm)return Bm;let e=await Rm(()=>import(`./pdf-YwugTw7Y.js`),[]);return e.GlobalWorkerOptions.workerSrc=zm(),Bm=e,e}async function Hm(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 Vm(),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 Hp(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 Up(){return(0,x.jsxs)(`section`,{className:Ai.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:Ai.guideHead,children:[(0,x.jsx)(`h3`,{className:Ai.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:Ai.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:Ai.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:Ai.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:Hp,className:Ai.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:Ai.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:Ai.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:Ai.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:Ai.guideExampleCode,children:(0,x.jsx)(`code`,{children:Vp})}),(0,x.jsxs)(`p`,{className:Ai.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 Wp(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:Ai.artifactView,children:[(0,x.jsxs)(`header`,{className:Ai.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ai.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:Ai.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:Ai.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ai.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:Ai.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:Ai.artifactBody,children:s===`turn-loop`?(0,x.jsx)(Rr,{artifact:t}):(0,x.jsx)(Ir,{artifact:t,metricSpecs:u})})]})}function Gp(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:Ai.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(Wp,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:Ai.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:Ai.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ai.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:Ai.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:Ai.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:Ai.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:Ai.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:Ai.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}var Kp=5242880,qp=`/api/v1/library/import`,Jp=new TextEncoder,Yp=e=>Jp.encode(e).length,Xp=Yp(JSON.stringify({addToBundle:`bundle_00000000-0000-0000-0000-000000000000`,artifacts:[]}));function Zp(e){return Xp+e.reduce((e,t)=>e+t.bytes,0)+Math.max(0,e.length-1)}function Qp(e,t){let n=Xp,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 $p(e,t){return`${t===void 0?`{"artifacts":[`:`{"addToBundle":${JSON.stringify(t)},"artifacts":[`}${e.map(e=>e.json).join(`,`)}]}`}function em(e){let t=typeof e==`string`?/Maximum (\d+) bytes/.exec(e):null;return t?Number(t[1]):void 0}function tm(){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`,rm=e=>/[.!?]$/.test(e.trim())?e.trim():`${e.trim()}.`;async function im(e,t={}){let n=e.map(e=>{let t=JSON.stringify(e);return{runId:e.metadata.runId,json:t,bytes:Yp(t)}}),r=[],i=[],a=t.addToBundle??tm(),o=0,s=Kp,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(`, `)}. ${rm(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=>Zp([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:Qp(e,s),f;try{f=await fetch(qp,{method:`POST`,headers:{"Content-Type":`application/json`},body:$p(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=em(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 am(){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(qp,{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 im(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 om(){let e=iT();return(0,b.useMemo)(()=>de(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function sm(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function cm(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=sm(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 lm(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 um={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 dm(){let{state:e}=gn(),t=om(),n=cT();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:um.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:um.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(fm,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:um.branchList,children:e.branches.map(r=>(0,x.jsx)(pm,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function fm({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:um.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:um.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:um.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:um.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:um.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:um.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:mm(t)})]},e))})]})}function pm({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?cm(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:um.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:um.cardHeader,children:[(0,x.jsxs)(`div`,{className:um.branchMeta,children:[(0,x.jsxs)(`span`,{className:um.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:um.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:um.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${um.status} ${um[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:um.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${um.delta} ${um[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:lm(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:um.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:um.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:um.error,role:`alert`,children:e.errorMessage})]})}function mm(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var hm={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function gm({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:hm.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${hm.tab} ${hm.tabActive}`:hm.tab;return(0,x.jsx)(`button`,{role:`tab`,"aria-selected":r,onClick:()=>n(e.id),type:`button`,className:i,children:e.label},e.id)})})}var _m=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],vm={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function ym(e){return!!e&&_m.includes(e)}function bm(e){let{tab:t}=xm(e);return t}function xm(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&vm[n])return vm[n];if(ym(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&vm[i]?vm[i]:ym(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function Sm(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function Cm(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 wm(e,t){if(!t)return Sm(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 Tm=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function Em({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),Cm(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=am(),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:Ai.tab,children:[(0,x.jsx)(gm,{options:Tm,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(dm,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Up,{}),(0,x.jsx)(Bp,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Ai.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:Ai.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:Ai.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(Wp,{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)(Gp,{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)(Ei,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function Dm(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 Om(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 km(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 Am(e,t,n=`viz`){return ut(e,t,n)}function jm(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 Mm=`/assets/pdf.worker.min-CIqJB0yW.mjs`,Nm=`modulepreload`,Pm=function(e){return`/`+e},Fm={},Im=function(e){return e.pathname.endsWith(`.css`)},Lm=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},Rm=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=Pm(t,n);let r=s(t),i=Im(r);return Lm(Fm,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`:Nm,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 zm(){if(typeof window>`u`)return Mm;try{return new URL(Mm,window.location.origin).toString()}catch{return Mm}}var Bm=null;async function Vm(){if(Bm)return Bm;let e=await Rm(()=>import(`./pdf-YwugTw7Y.js`),[]);return e.GlobalWorkerOptions.workerSrc=zm(),Bm=e,e}async function Hm(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 Vm(),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 Um(e){let t=Wm(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('${Gm(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 Wm(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Gm(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Km(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 qm={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 Jm(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)(()=>Um(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Km(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:qm.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:qm.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:qm.panel,children:[(0,x.jsxs)(`div`,{className:qm.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:qm.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:qm.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:qm.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:qm.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Ym={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 Xm(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 Zm({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=rT(),i=!aT()||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?(re(),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`,ee=()=>{s||i||(c(!0),e(a))},E=`${a} ${a===1?`actor`:`actors`}`,D=s?`Launching...`:`Run ${E} against ${y}`,O=s?`Launching...`:`${D} ->`,te=s?`Launching...`:`Run ${E}`,k=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Ym.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Ym.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Ym.tagline,children:S}),(0,x.jsx)(`div`,{className:Ym.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:Ym.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Ym.scenarioPickerLabel,htmlFor:k,children:`Scenario`}),(0,x.jsx)(`select`,{id:k,className:Ym.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=Xm(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:Ym.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Ym.actorRow,children:[(0,x.jsx)(`label`,{className:Ym.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:Ym.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Ym.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Ym.runButton,onClick:ee,disabled:i||s,"aria-busy":s,"aria-label":D,children:[(0,x.jsx)(`span`,{className:Ym.runButtonFull,"aria-hidden":`true`,children:O}),(0,x.jsx)(`span`,{className:Ym.runButtonCompact,"aria-hidden":`true`,children:te})]}),(0,x.jsxs)(`div`,{className:Ym.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 V={backdrop:`_backdrop_19o8q_1`,backdropFadeIn:`_backdropFadeIn_19o8q_1`,drawer:`_drawer_19o8q_17`,open:`_open_19o8q_34`,header:`_header_19o8q_38`,closeBtn:`_closeBtn_19o8q_50`,sourceBadge:`_sourceBadge_19o8q_63`,summary:`_summary_19o8q_86`,nameRow:`_nameRow_19o8q_94`,name:`_name_19o8q_94`,nameEditBtn:`_nameEditBtn_19o8q_110`,nameEditForm:`_nameEditForm_19o8q_129`,nameEditInput:`_nameEditInput_19o8q_135`,nameEditActions:`_nameEditActions_19o8q_150`,nameEditSave:`_nameEditSave_19o8q_155`,nameEditCancel:`_nameEditCancel_19o8q_173`,nameEditError:`_nameEditError_19o8q_195`,description:`_description_19o8q_202`,metaGrid:`_metaGrid_19o8q_209`,meta:`_meta_19o8q_209`,sectionHeading:`_sectionHeading_19o8q_235`,seedSection:`_seedSection_19o8q_245`,seedHint:`_seedHint_19o8q_250`,seedBody:`_seedBody_19o8q_257`,presetsSection:`_presetsSection_19o8q_273`,departmentsSection:`_departmentsSection_19o8q_274`,sectionHint:`_sectionHint_19o8q_279`,sectionCount:`_sectionCount_19o8q_287`,presetList:`_presetList_19o8q_294`,presetCard:`_presetCard_19o8q_303`,presetHeader:`_presetHeader_19o8q_313`,presetName:`_presetName_19o8q_320`,presetArchetype:`_presetArchetype_19o8q_327`,presetUnit:`_presetUnit_19o8q_340`,hexacoList:`_hexacoList_19o8q_347`,hexacoRow:`_hexacoRow_19o8q_356`,hexacoAxis:`_hexacoAxis_19o8q_364`,hexacoBar:`_hexacoBar_19o8q_372`,hexacoFill:`_hexacoFill_19o8q_380`,hexacoValue:`_hexacoValue_19o8q_386`,presetInstructions:`_presetInstructions_19o8q_393`,deptChips:`_deptChips_19o8q_401`,deptChip:`_deptChip_19o8q_401`,deptIcon:`_deptIcon_19o8q_423`,deptRole:`_deptRole_19o8q_427`,recentSection:`_recentSection_19o8q_431`,statusLine:`_statusLine_19o8q_438`,error:`_error_19o8q_445`,recentList:`_recentList_19o8q_449`,recentRow:`_recentRow_19o8q_458`,recentTitle:`_recentTitle_19o8q_468`,recentArchetype:`_recentArchetype_19o8q_475`,recentMeta:`_recentMeta_19o8q_480`,footer:`_footer_19o8q_486`,actorRow:`_actorRow_19o8q_497`,actorLabel:`_actorLabel_19o8q_505`,actorSlider:`_actorSlider_19o8q_514`,actorValue:`_actorValue_19o8q_519`,runButton:`_runButton_19o8q_527`,deleteButton:`_deleteButton_19o8q_549`,deleteError:`_deleteError_19o8q_572`};function Qm(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 $m(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function eh(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 th(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 nh(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,ee]=(0,b.useState)(null),[E,D]=(0,b.useState)(!1),[O,te]=(0,b.useState)(``),[k,ne]=(0,b.useState)(!1),[re,A]=(0,b.useState)(null),[j,ie]=(0,b.useState)(null);(0,b.useEffect)(()=>{ie(null),D(!1),A(null)},[t?.id]);let ae=t?.source===`compiled`,[M,oe]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)try{let e=localStorage.getItem(`paracosm:adminToken`);oe(e&&e.length>0?e:null)}catch{oe(null)}},[c]);let N=!!M&&t?.source===`compiled`,se=(0,b.useRef)(null),ce=(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?(ce.current=document.activeElement,requestAnimationFrame(()=>{(se.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ce.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=th(se.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!se.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 le=`scenario-detail-actor-count`,ue=()=>{t&&ae&&(te(j??t.name),D(!0),A(null))},de=()=>{D(!1),te(``),A(null)},fe=async()=>{if(!t||k)return;let e=O.trim();if(e.length===0)A(`Name cannot be empty.`);else if(e===(j??t.name))D(!1);else{ne(!0),A(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e})});if(!n.ok){let e=await n.json().catch(()=>({}));A(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ie(r),D(!1),te(``),s?.(t.id,r)}catch(e){A(e instanceof Error?e.message:String(e))}finally{ne(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:V.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:se,className:`${V.drawer} ${c?V.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:V.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:V.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:V.sourceBadge,"data-source":t.source??`other`,children:rh(t.source)})]}),(0,x.jsxs)(`section`,{className:V.summary,children:[E?(0,x.jsxs)(`form`,{className:V.nameEditForm,onSubmit:e=>{e.preventDefault(),fe()},children:[(0,x.jsx)(`input`,{type:`text`,value:O,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),de())},disabled:k,maxLength:100,autoFocus:!0,className:V.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:V.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:V.nameEditSave,disabled:k||O.trim().length===0,children:k?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:V.nameEditCancel,onClick:de,disabled:k,children:`Cancel`})]}),re&&(0,x.jsx)(`p`,{className:V.nameEditError,role:`alert`,children:re})]}):(0,x.jsxs)(`div`,{className:V.nameRow,children:[(0,x.jsx)(`h2`,{className:V.name,children:j??t.name}),ae&&(0,x.jsx)(`button`,{type:`button`,className:V.nameEditBtn,onClick:ue,"aria-label":`Rename ${j??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:V.description,children:t.description}),(0,x.jsxs)(`dl`,{className:V.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:V.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:V.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:V.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Qm(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:V.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:rh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:V.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:V.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:V.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:V.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:V.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:V.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:V.presetCard,children:[(0,x.jsxs)(`div`,{className:V.presetHeader,children:[(0,x.jsx)(`span`,{className:V.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:V.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:V.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:V.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:V.hexacoRow,children:[(0,x.jsx)(`span`,{className:V.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:V.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:V.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:V.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:V.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:V.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:V.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:V.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:V.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:V.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:V.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:V.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:V.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:V.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:V.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${V.statusLine} ${V.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:V.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:V.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:V.recentRow,children:[(0,x.jsxs)(`span`,{className:V.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:V.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:V.recentMeta,children:[Qm(e.createdAt),` · `,$m(e.costUSD),` · `,eh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:V.footer,children:[(0,x.jsxs)(`div`,{className:V.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:le,className:V.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:le,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:V.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:V.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:V.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`,` →`]}),N&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:V.deleteButton,onClick:async()=>{if(t&&M&&!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.`)){w(!0),ee(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{"X-Admin-Token":M}});if(e.status===401){try{localStorage.removeItem(`paracosm:adminToken`)}catch{}ee(`Admin token rejected. The stored token has been cleared; re-paste it via dev-tools localStorage to retry.`),oe(null);return}if(!e.ok){let t=await e.json().catch(()=>({}));ee(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){ee(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:V.deleteError,role:`alert`,children:T})]})]})]})]})}function rh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var H={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 ih(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 ah(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function oh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function sh(e){let{disabled:t=!1,onRunScenario:n}=e,r=rT(),i=!aT()||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:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:H.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${H.statusLine} ${H.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let ee=`scenario-catalog-actor-count`,E=`scenario-catalog-search`,D=g.trim().length>0||v!==`all`,O=g.trim().toLowerCase(),te=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:O.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(O))].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)}),k=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:H.header,children:[(0,x.jsxs)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:H.count,children:[`· `,D?`${te.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:H.actorRow,children:[(0,x.jsx)(`label`,{className:H.actorLabel,htmlFor:ee,children:`Actors`}),(0,x.jsx)(`input`,{id:ee,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:H.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:H.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:H.filterRow,children:[(0,x.jsxs)(`label`,{className:H.searchLabel,htmlFor:E,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:E,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:H.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:H.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:k[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:`${H.chip} ${n?H.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:H.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:H.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:H.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`})]})]})]}),te.length===0?(0,x.jsxs)(`div`,{className:H.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:H.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:H.grid,role:`list`,children:te.map(e=>{let t=ah(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${H.card} ${H[`tone_${t}`]??``} ${r?H.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:H.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:H.cardHeader,children:[(0,x.jsx)(`span`,{className:`${H.sourceBadge} ${H[`badge_${t}`]??``}`,children:oh(e.source)}),r&&(0,x.jsx)(`span`,{className:H.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:H.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:H.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:H.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:H.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:H.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:H.statValue,children:ih(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:H.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)(nh,{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 ch=[{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 lh(e){return .1+.6*e}var uh={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 dh(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function fh({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(dh),[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=Om(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=Dm(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 Hm(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)}}},[]),ee={paste:`WRITE`,url:`URL`,pdf:`PDF`},E=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:uh.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[E&&(0,x.jsx)(`p`,{className:uh.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)(Zm,{onRunStart:t,disabled:r||g||E}),n&&(0,x.jsx)(sh,{onRunScenario:n,disabled:r||g||E}),(0,x.jsxs)(`div`,{className:uh.dividerWrap,children:[(0,x.jsx)(`span`,{className:uh.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:uh.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:uh.templatePicker,children:[(0,x.jsx)(`span`,{className:uh.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:uh.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=ch.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…`}),ch.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:uh.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${uh.tab} ${i===e?uh.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:ee[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:uh.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:uh.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:uh.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:uh.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:uh.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:uh.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:uh.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:uh.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:uh.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:uh.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:uh.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:uh.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:uh.actorCountPreview,"aria-live":`polite`,children:[`~$`,lh(v).toFixed(2),` · `,ph(v)]})]}),(0,x.jsx)(Jm,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:uh.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,lh(v).toFixed(2),`)`]})]})}function ph(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 U={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`},mh={id:``,name:``,description:``,profileJson:`{}`},hh={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},gh={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 _h(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function vh(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function yh({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(mh),[a,o]=(0,b.useState)(hh),[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=gh[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(mh),o(hh),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:U.card,children:[(0,x.jsxs)(`div`,{className:U.heading,children:[(0,x.jsx)(`h3`,{className:U.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:U.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:U.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:U.presetRow,children:[(0,x.jsx)(`span`,{className:U.presetLabel,children:`Examples`}),Object.entries(gh).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${U.presetButton} ${p===e?U.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:U.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:U.presetBlurb,children:gh[p].blurb}),(0,x.jsxs)(`div`,{className:U.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:U.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:U.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:`${U.textarea} ${U.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${U.textarea} ${U.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:U.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:U.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:U.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:U.input})]}),(0,x.jsxs)(`label`,{className:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:U.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:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:U.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=_h(r.profileJson,{}),o=_h(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=vh();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`}})});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();O(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:U.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:U.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:U.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:U.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function bh(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function xh(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Sh={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 Ch(){let[e,t]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1;return(async()=>{try{let n=await fetch(`/sessions`);if(!n.ok)return;let r=(await n.json().catch(()=>null))?.sessions?.[0];if(e||!r?.id)return;t(r)}catch{}})(),()=>{e=!0}},[]),!e)return null;let n=typeof window<`u`?xh(window.location.href,e.id):`?replay=${encodeURIComponent(e.id)}`,r=e.seedText?e.seedText.length>70?`${e.seedText.slice(0,70).trim()}…`:e.seedText.trim():null,i=ln(e,3),a=e.title||e.scenarioName||i||r||e.id,o=[e.scenarioName&&e.scenarioName!==a?e.scenarioName:null,typeof e.eventCount==`number`?`${e.eventCount} events`:null,typeof e.durationMs==`number`?`${Math.round(e.durationMs/1e3)}s`:null,typeof e.createdAt==`number`?new Date(e.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Sh.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Sh.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Sh.row,children:[(0,x.jsx)(`span`,{className:Sh.actor,children:a}),(0,x.jsx)(`span`,{className:Sh.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Sh.meta,children:o})]})}var wh={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`},Th={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Eh({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`?wh.statusDone:n===`active`?wh.statusActive:wh.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${wh.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:wh.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:wh.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:wh.label,children:t}),i&&(0,x.jsx)(`span`,{className:wh.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:wh.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${wh.chevron} ${o?wh.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:wh.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${wh.actorChip} ${wh[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:wh.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:wh.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Th[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:wh.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:`${wh.line} ${wh.tonePending}`,children:[(0,x.jsx)(`span`,{className:wh.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:wh.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:wh.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${wh.line} ${wh[`tone${Dh(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:wh.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:wh.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:wh.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:wh.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:wh.lineBody,children:e.body})]},t))]})]})}function Dh(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Oh(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 kh(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 Ah(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 jh(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 Mh(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=jh(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`:Ah(e.type),body:r,tone:kh(e.type),actor:typeof n==`string`?n:void 0}}function Nh(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Oh(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:Oh(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Ph(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Oh(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:Oh(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Fh(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Oh(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:Oh(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Ih(e){return e.events.map(e=>Mh(e)).filter(e=>!!e)}function Lh(e,t){switch(e){case`compile`:return Nh(t);case`research`:return Ph(t);case`actors`:return Fh(t);case`running`:return Ih(t);case`done`:return[]}}function Rh(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 zh={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`},Bh=[`compile`,`research`,`actors`,`running`,`done`];function Vh(e,t){let n=Bh.indexOf(e),r=Bh.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Hh({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=sT(),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:zh.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:zh.heading,children:[(0,x.jsx)(`span`,{className:zh.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:zh.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:zh.stageList,children:m.map(n=>{let r=Vh(e,n.id);return(0,x.jsx)(`li`,{className:zh.stageItem,children:(0,x.jsx)(Eh,{stageId:n.id,label:n.label,status:r,logLines:Lh(n.id,p),duration:Rh(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:zh.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:zh.cancel,onClick:a,children:`Cancel run`})]})}var Uh=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}}}),Wh={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 Gh({onSelect:e,onClose:t}){let n=ht(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Wh.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Wh.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Wh.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:Wh.list,children:Object.values(Uh).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Wh.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Wh.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Wh.description,children:t.description})]})},t.id))})]})})}var Kh={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`},qh=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function Jh({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=gn(),a=sT(),o=om(),[s,c]=(0,b.useState)(null),[l,u]=(0,b.useState)(null),d=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},f=async e=>{if(!n)return;let t=Am(window.location.origin,n);try{await navigator.clipboard.writeText(t),u(e),setTimeout(()=>u(null),1500)}catch{}},p=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;jm(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},m=(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:Kh.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:Kh.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:m.totalCitations}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:Kh.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one in a sandboxed node:vm at runtime. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:Kh.summaryNum,children:m.totalTools}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:Kh.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:Kh.summaryNum,children:m.totalDecisions}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:m.totalTurns}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`turns simulated`})]}),m.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:[`$`,m.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:Kh.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(Yh,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,copiedHere:l===r,shareEnabled:!!n,onDownload:()=>p(r),onShare:()=>f(r),onFork:()=>d(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)(Gh,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function Yh({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,copiedHere:a,shareEnabled:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>km(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:Kh.card,children:[(0,x.jsxs)(`header`,{className:Kh.cardHeader,children:[(0,x.jsx)(`h4`,{className:Kh.actorName,children:e.name}),(0,x.jsx)(`span`,{className:Kh.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:Kh.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:Kh.hexaco,children:qh.map(t=>(0,x.jsxs)(`div`,{className:Kh.trait,children:[(0,x.jsx)(`span`,{className:Kh.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:Kh.traitBarOuter,children:(0,x.jsx)(`div`,{className:Kh.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:Kh.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:Kh.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Kh.delta} ${Kh[`direction_${e.direction}`]}`,children:lm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:Kh.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!o,title:`Copy a deep link that opens this run on the visualization tab`,children:a?`Copied!`:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:Kh.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 →`})]}),(0,x.jsx)(`div`,{className:Kh.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var Xh=`paracosm:lastLaunchConfig`,Zh=`paracosm:keyOverrides`,Qh=`paracosm:activeRunActors`,$h=`paracosm:activeRunScenarioId`,eg=950;function tg(e){try{let t=e.getItem(Xh);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function ng(e,t){return e.scenarioId===t}function rg(e,t){try{e.setItem(Xh,JSON.stringify(t))}catch{}}function ig(e,t,n){try{e.setItem(Qh,JSON.stringify(t)),n?e.setItem($h,n):e.removeItem?.($h)}catch{}}function ag(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function og(e){try{let t=e.getItem(Qh);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 sg(e){try{let t=e.getItem(Zh);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function cg(e,t){let n=(typeof e.seed==`number`?e.seed:eg)+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}var lg=2e3,ug=3e5;function dg(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 fg(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 pg(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??lg,i=t.timeoutMs??ug,a=t.waitImpl??dg,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 fg(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 fg(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 mg={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 hg(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 gg({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=rT(),s=aT(),{toast:c}=St(),[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`?sg(window.localStorage):{},i=typeof window<`u`?tg(window.localStorage):null,a={};r.openai&&(a.apiKey=r.openai),r.anthropic&&(a.anthropicKey=r.anthropic),r.serper&&(a.serperKey=r.serper),r.firecrawl&&(a.firecrawlKey=r.firecrawl),r.tavily&&(a.tavilyKey=r.tavily),r.cohere&&(a.cohereKey=r.cohere),i?.provider&&(a.provider=i.provider),i?.models&&typeof i.models==`object`&&(a.models=i.models),i?.economics&&typeof i.economics==`object`&&(a.economics=i.economics);let s=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(s.length>=t){u({kind:`progress`,stage:`running`});let n=s.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&ig(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...a,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=wm(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=hg(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})});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`&&ig(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...a,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 s=await i.json().catch(()=>({}));if(s.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=wm(window.location.href,s.redirect);return}}catch(e){u({kind:`input`});let t=hg(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}`)}re(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=hg(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{scenario:n,scenarioId:r}=await pg(t);u({kind:`progress`,stage:`research`,scenario:n});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:r})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:n});let i=Math.max(1,Math.min(300,t.actorCount??2)),a=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:r,count:i})});if(!a.ok){let e=await a.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${a.status}`)}let o=(await a.json().catch(()=>null))?.actors;if(!o||o.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:n,actors:o}),await e.reset(),typeof window<`u`&&ig(window.localStorage,o,r);let s=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:o,turns:n.setup.defaultTurns,seed:n.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:r}})});if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${s.status}`)}let c=await s.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=wm(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=hg(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,ee=(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:mg.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:mg.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:mg.howItWorks,children:[(0,x.jsx)(`summary`,{className:mg.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:mg.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:mg.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:mg.errorBanner,role:`alert`,children:d}),(0,x.jsx)(Ch,{}),(0,x.jsx)(fh,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(yh,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Hh,{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:mg.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:mg.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)(Jh,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:ee}),p&&h&&(0,x.jsx)(Ei,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var _g={getNumber:()=>0,getEntry:()=>void 0,list:[]};function vg(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 yg=(0,b.createContext)(_g);function bg(){return(0,b.useContext)(yg)}var xg={getNumber:()=>0,getEntry:()=>void 0,list:[]};function Sg(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=e.data?._filteredTools||[],o=String(e.data?.department||``);for(let s of a){let a=String(s.name||``).trim();if(!a||a===`unnamed`)continue;let c=t.get(a);c?(typeof s.output==`string`&&s.output&&(c.sampleOutput=s.output),typeof s.confidence==`number`&&s.confidence>c.confidence&&(c.confidence=s.confidence),s.approved!==!1&&(c.approved=!0),!c.inputSchema&&s.inputSchema&&(c.inputSchema=s.inputSchema),!c.outputSchema&&s.outputSchema&&(c.outputSchema=s.outputSchema),c.approved?c.errorReason=void 0:typeof s.errorReason==`string`&&s.errorReason&&(c.errorReason=s.errorReason)):(c={n:r++,name:a,description:String(s.description||a),mode:String(s.mode||`sandbox`),firstForgedTurn:typeof s.firstForgedTurn==`number`?s.firstForgedTurn:e.turn??0,firstForgedDepartment:String(s.firstForgedDepartment||o),departments:new Set,actorNames:new Set,reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:typeof s.confidence==`number`?s.confidence:s.approved===!1?0:.85,approved:s.approved!==!1,inputSchema:s.inputSchema,outputSchema:s.outputSchema,sampleOutput:typeof s.output==`string`?s.output:null,errorReason:typeof s.errorReason==`string`?s.errorReason:void 0,inputFields:Array.isArray(s.inputFields)?s.inputFields:[],outputFields:Array.isArray(s.outputFields)?s.outputFields:[],history:[]},t.set(a,c),n.push(c)),o&&c.departments.add(o),c.actorNames.add(i);let l=s.history||null;Array.isArray(l)&&(c.history=l.map(e=>({...e,actorName:i})),c.reuseCount=Math.max(0,l.length-1),c.reforgeCount=l.filter(e=>e.isReforge).length,c.rejectedReforges=l.filter(e=>e.isReforge&&e.rejected).length)}}}for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`forge_attempt`)continue;let a=e.data||{},o=String(a.name||``).trim();if(!o||o===`unnamed`||t.has(o)||a.approved===!0)continue;let s={n:r++,name:o,description:String(a.description||o),mode:String(a.mode||`sandbox`),firstForgedTurn:Number(a.turn??e.turn??0),firstForgedDepartment:String(a.department||``),departments:new Set(typeof a.department==`string`&&a.department?[a.department]:[]),actorNames:new Set([i]),reuseCount:0,reforgeCount:0,rejectedReforges:1,confidence:typeof a.confidence==`number`?a.confidence:0,approved:!1,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:typeof a.errorReason==`string`?a.errorReason:void 0,inputFields:Array.isArray(a.inputFields)?a.inputFields:[],outputFields:Array.isArray(a.outputFields)?a.outputFields:[],history:[{turn:Number(a.turn??e.turn??0),time:Number(a.time??0),eventIndex:Number(a.eventIndex??0),eventTitle:``,department:String(a.department||``),output:null,isReforge:!1,rejected:!0,confidence:typeof a.confidence==`number`?a.confidence:void 0,actorName:i}]};t.set(o,s),n.push(s)}}return{getNumber:e=>t.get(e)?.n??0,getEntry:e=>t.get(e),list:n}},[e])}var Cg=(0,b.createContext)(xg);function wg(){return(0,b.useContext)(Cg)}var Tg=m(),Eg=420,Dg=260;function Og({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(Eg,window.innerWidth-20),r=t.left,i=t.top-Dg-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+Dg>window.innerHeight-10&&(i=window.innerHeight-Dg-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:`${Eg}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,Tg.createPortal)(p,document.body):null]})}function kg(){let[e,t]=(0,b.useState)([]),[n,r]=(0,b.useState)(`loading`),[i,a]=(0,b.useState)(0),o=(0,b.useCallback)(()=>a(e=>e+1),[]);return(0,b.useEffect)(()=>{let e=!1;return r(`loading`),fetch(`/sessions`).then(async n=>{if(e)return;if(n.status===503){r(`unavailable`),t([]);return}if(!n.ok){r(`error`),t([]);return}let i=await n.json();e||(t(i.sessions??[]),r(`ready`))}).catch(()=>{e||(r(`error`),t([]))}),()=>{e=!0}},[i]),{sessions:e,status:n,refresh:o}}var Ag={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`},jg=Ag;function Mg(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 Ng(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 Pg(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Fg({s:e,onPick:t}){let n=ln(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()} (${Mg(e.createdAt)}) · ${Ng(e.durationMs)} · ${Pg(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Ag.sessionCard,children:[(0,x.jsx)(`div`,{className:Ag.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Ag.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Ag.sessionCardLine3,children:o})]})}function Ig({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}=kg(),g=p.length>0,_=aT();(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=>{let t=xh(window.location.href,e);window.location.assign(wm(t,`sim`))},C=()=>{v(),t?.()},w=bh(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Ag.root,children:[(0,x.jsx)(Og,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ag.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:Ag.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Ag.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Ag.runNewButton,children:[(0,x.jsxs)(`span`,{className:Ag.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Ag.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Ag.runSavedButton,g?``:Ag.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Ag.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Ag.runSavedBadge,g?``:Ag.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Ag.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Fg,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Ag.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Ag.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Ag.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:jg.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:jg.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:jg.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:jg.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=`${Mg(t)} · ${e.summary.eventCount} ev · ${Pg(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:jg.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:jg.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:jg.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:jg.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:jg.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:jg.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. Server data untouched — use Wipe All in the ⋯ menu for that.`,onClick:()=>{window.confirm(`Clear all local browser state?
|
|
113
|
+
`)}var qm={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 Jm(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)(()=>Um(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Km(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:qm.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:qm.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:qm.panel,children:[(0,x.jsxs)(`div`,{className:qm.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:qm.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:qm.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:qm.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:qm.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Ym={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 Xm(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 Zm({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=iT(),i=!oT()||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?(re(),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`,ee=()=>{s||i||(c(!0),e(a))},E=`${a} ${a===1?`actor`:`actors`}`,D=s?`Launching...`:`Run ${E} against ${y}`,O=s?`Launching...`:`${D} ->`,te=s?`Launching...`:`Run ${E}`,k=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Ym.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Ym.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Ym.tagline,children:S}),(0,x.jsx)(`div`,{className:Ym.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:Ym.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Ym.scenarioPickerLabel,htmlFor:k,children:`Scenario`}),(0,x.jsx)(`select`,{id:k,className:Ym.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=Xm(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:Ym.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Ym.actorRow,children:[(0,x.jsx)(`label`,{className:Ym.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:Ym.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Ym.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Ym.runButton,onClick:ee,disabled:i||s,"aria-busy":s,"aria-label":D,children:[(0,x.jsx)(`span`,{className:Ym.runButtonFull,"aria-hidden":`true`,children:O}),(0,x.jsx)(`span`,{className:Ym.runButtonCompact,"aria-hidden":`true`,children:te})]}),(0,x.jsxs)(`div`,{className:Ym.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 V={backdrop:`_backdrop_19o8q_1`,backdropFadeIn:`_backdropFadeIn_19o8q_1`,drawer:`_drawer_19o8q_17`,open:`_open_19o8q_34`,header:`_header_19o8q_38`,closeBtn:`_closeBtn_19o8q_50`,sourceBadge:`_sourceBadge_19o8q_63`,summary:`_summary_19o8q_86`,nameRow:`_nameRow_19o8q_94`,name:`_name_19o8q_94`,nameEditBtn:`_nameEditBtn_19o8q_110`,nameEditForm:`_nameEditForm_19o8q_129`,nameEditInput:`_nameEditInput_19o8q_135`,nameEditActions:`_nameEditActions_19o8q_150`,nameEditSave:`_nameEditSave_19o8q_155`,nameEditCancel:`_nameEditCancel_19o8q_173`,nameEditError:`_nameEditError_19o8q_195`,description:`_description_19o8q_202`,metaGrid:`_metaGrid_19o8q_209`,meta:`_meta_19o8q_209`,sectionHeading:`_sectionHeading_19o8q_235`,seedSection:`_seedSection_19o8q_245`,seedHint:`_seedHint_19o8q_250`,seedBody:`_seedBody_19o8q_257`,presetsSection:`_presetsSection_19o8q_273`,departmentsSection:`_departmentsSection_19o8q_274`,sectionHint:`_sectionHint_19o8q_279`,sectionCount:`_sectionCount_19o8q_287`,presetList:`_presetList_19o8q_294`,presetCard:`_presetCard_19o8q_303`,presetHeader:`_presetHeader_19o8q_313`,presetName:`_presetName_19o8q_320`,presetArchetype:`_presetArchetype_19o8q_327`,presetUnit:`_presetUnit_19o8q_340`,hexacoList:`_hexacoList_19o8q_347`,hexacoRow:`_hexacoRow_19o8q_356`,hexacoAxis:`_hexacoAxis_19o8q_364`,hexacoBar:`_hexacoBar_19o8q_372`,hexacoFill:`_hexacoFill_19o8q_380`,hexacoValue:`_hexacoValue_19o8q_386`,presetInstructions:`_presetInstructions_19o8q_393`,deptChips:`_deptChips_19o8q_401`,deptChip:`_deptChip_19o8q_401`,deptIcon:`_deptIcon_19o8q_423`,deptRole:`_deptRole_19o8q_427`,recentSection:`_recentSection_19o8q_431`,statusLine:`_statusLine_19o8q_438`,error:`_error_19o8q_445`,recentList:`_recentList_19o8q_449`,recentRow:`_recentRow_19o8q_458`,recentTitle:`_recentTitle_19o8q_468`,recentArchetype:`_recentArchetype_19o8q_475`,recentMeta:`_recentMeta_19o8q_480`,footer:`_footer_19o8q_486`,actorRow:`_actorRow_19o8q_497`,actorLabel:`_actorLabel_19o8q_505`,actorSlider:`_actorSlider_19o8q_514`,actorValue:`_actorValue_19o8q_519`,runButton:`_runButton_19o8q_527`,deleteButton:`_deleteButton_19o8q_549`,deleteError:`_deleteError_19o8q_572`};function Qm(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 $m(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function eh(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 th(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 nh(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,ee]=(0,b.useState)(null),[E,D]=(0,b.useState)(!1),[O,te]=(0,b.useState)(``),[k,ne]=(0,b.useState)(!1),[re,A]=(0,b.useState)(null),[j,ie]=(0,b.useState)(null);(0,b.useEffect)(()=>{ie(null),D(!1),A(null)},[t?.id]);let ae=t?.source===`compiled`,[M,oe]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)try{let e=localStorage.getItem(`paracosm:adminToken`);oe(e&&e.length>0?e:null)}catch{oe(null)}},[c]);let N=!!M&&t?.source===`compiled`,se=(0,b.useRef)(null),ce=(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?(ce.current=document.activeElement,requestAnimationFrame(()=>{(se.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ce.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=th(se.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!se.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 le=`scenario-detail-actor-count`,ue=()=>{t&&ae&&(te(j??t.name),D(!0),A(null))},de=()=>{D(!1),te(``),A(null)},fe=async()=>{if(!t||k)return;let e=O.trim();if(e.length===0)A(`Name cannot be empty.`);else if(e===(j??t.name))D(!1);else{ne(!0),A(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e})});if(!n.ok){let e=await n.json().catch(()=>({}));A(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ie(r),D(!1),te(``),s?.(t.id,r)}catch(e){A(e instanceof Error?e.message:String(e))}finally{ne(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:V.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:se,className:`${V.drawer} ${c?V.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:V.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:V.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:V.sourceBadge,"data-source":t.source??`other`,children:rh(t.source)})]}),(0,x.jsxs)(`section`,{className:V.summary,children:[E?(0,x.jsxs)(`form`,{className:V.nameEditForm,onSubmit:e=>{e.preventDefault(),fe()},children:[(0,x.jsx)(`input`,{type:`text`,value:O,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),de())},disabled:k,maxLength:100,autoFocus:!0,className:V.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:V.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:V.nameEditSave,disabled:k||O.trim().length===0,children:k?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:V.nameEditCancel,onClick:de,disabled:k,children:`Cancel`})]}),re&&(0,x.jsx)(`p`,{className:V.nameEditError,role:`alert`,children:re})]}):(0,x.jsxs)(`div`,{className:V.nameRow,children:[(0,x.jsx)(`h2`,{className:V.name,children:j??t.name}),ae&&(0,x.jsx)(`button`,{type:`button`,className:V.nameEditBtn,onClick:ue,"aria-label":`Rename ${j??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:V.description,children:t.description}),(0,x.jsxs)(`dl`,{className:V.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:V.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:V.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:V.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Qm(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:V.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:rh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:V.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:V.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:V.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:V.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:V.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:V.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:V.presetCard,children:[(0,x.jsxs)(`div`,{className:V.presetHeader,children:[(0,x.jsx)(`span`,{className:V.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:V.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:V.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:V.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:V.hexacoRow,children:[(0,x.jsx)(`span`,{className:V.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:V.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:V.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:V.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:V.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:V.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:V.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:V.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:V.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:V.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:V.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:V.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:V.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:V.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:V.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:V.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${V.statusLine} ${V.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:V.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:V.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:V.recentRow,children:[(0,x.jsxs)(`span`,{className:V.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:V.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:V.recentMeta,children:[Qm(e.createdAt),` · `,$m(e.costUSD),` · `,eh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:V.footer,children:[(0,x.jsxs)(`div`,{className:V.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:le,className:V.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:le,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:V.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:V.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:V.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`,` →`]}),N&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:V.deleteButton,onClick:async()=>{if(t&&M&&!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.`)){w(!0),ee(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{"X-Admin-Token":M}});if(e.status===401){try{localStorage.removeItem(`paracosm:adminToken`)}catch{}ee(`Admin token rejected. The stored token has been cleared; re-paste it via dev-tools localStorage to retry.`),oe(null);return}if(!e.ok){let t=await e.json().catch(()=>({}));ee(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){ee(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:V.deleteError,role:`alert`,children:T})]})]})]})]})}function rh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var H={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 ih(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 ah(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function oh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function sh(e){let{disabled:t=!1,onRunScenario:n}=e,r=iT(),i=!oT()||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:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:H.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${H.statusLine} ${H.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let ee=`scenario-catalog-actor-count`,E=`scenario-catalog-search`,D=g.trim().length>0||v!==`all`,O=g.trim().toLowerCase(),te=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:O.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(O))].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)}),k=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:H.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:H.header,children:[(0,x.jsxs)(`h3`,{className:H.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:H.count,children:[`· `,D?`${te.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:H.actorRow,children:[(0,x.jsx)(`label`,{className:H.actorLabel,htmlFor:ee,children:`Actors`}),(0,x.jsx)(`input`,{id:ee,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:H.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:H.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:H.filterRow,children:[(0,x.jsxs)(`label`,{className:H.searchLabel,htmlFor:E,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:E,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:H.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:H.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:k[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:`${H.chip} ${n?H.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:H.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:H.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:H.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`})]})]})]}),te.length===0?(0,x.jsxs)(`div`,{className:H.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:H.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:H.grid,role:`list`,children:te.map(e=>{let t=ah(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${H.card} ${H[`tone_${t}`]??``} ${r?H.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:H.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:H.cardHeader,children:[(0,x.jsx)(`span`,{className:`${H.sourceBadge} ${H[`badge_${t}`]??``}`,children:oh(e.source)}),r&&(0,x.jsx)(`span`,{className:H.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:H.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:H.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:H.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:H.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:H.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:H.stat,children:[(0,x.jsx)(`dt`,{className:H.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:H.statValue,children:ih(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:H.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)(nh,{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 ch=[{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 lh(e){return .1+.6*e}var uh={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 dh(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function fh({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(dh),[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=Om(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=Dm(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 Hm(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)}}},[]),ee={paste:`WRITE`,url:`URL`,pdf:`PDF`},E=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:uh.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[E&&(0,x.jsx)(`p`,{className:uh.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)(Zm,{onRunStart:t,disabled:r||g||E}),n&&(0,x.jsx)(sh,{onRunScenario:n,disabled:r||g||E}),(0,x.jsxs)(`div`,{className:uh.dividerWrap,children:[(0,x.jsx)(`span`,{className:uh.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:uh.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:uh.templatePicker,children:[(0,x.jsx)(`span`,{className:uh.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:uh.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=ch.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…`}),ch.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:uh.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${uh.tab} ${i===e?uh.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:ee[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:uh.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:uh.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:uh.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:uh.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:uh.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:uh.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:uh.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:uh.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:uh.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:uh.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:uh.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:uh.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:uh.actorCountPreview,"aria-live":`polite`,children:[`~$`,lh(v).toFixed(2),` · `,ph(v)]})]}),(0,x.jsx)(Jm,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:uh.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,lh(v).toFixed(2),`)`]})]})}function ph(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 U={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`},mh={id:``,name:``,description:``,profileJson:`{}`},hh={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},gh={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 _h(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function vh(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function yh({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(mh),[a,o]=(0,b.useState)(hh),[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=gh[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(mh),o(hh),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:U.card,children:[(0,x.jsxs)(`div`,{className:U.heading,children:[(0,x.jsx)(`h3`,{className:U.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:U.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:U.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:U.presetRow,children:[(0,x.jsx)(`span`,{className:U.presetLabel,children:`Examples`}),Object.entries(gh).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${U.presetButton} ${p===e?U.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:U.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:U.presetBlurb,children:gh[p].blurb}),(0,x.jsxs)(`div`,{className:U.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:U.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:U.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:`${U.textarea} ${U.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${U.textarea} ${U.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:U.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:U.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]}),(0,x.jsxs)(`label`,{className:U.field,children:[(0,x.jsx)(`span`,{className:U.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:U.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:U.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:U.input})]}),(0,x.jsxs)(`label`,{className:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:U.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:`${U.field} ${U.fieldThird}`,children:[(0,x.jsx)(`span`,{className:U.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:U.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:U.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=_h(r.profileJson,{}),o=_h(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=vh();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`}})});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();O(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:U.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:U.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:U.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:U.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function bh(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function xh(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Sh={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 Ch(){let[e,t]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1;return(async()=>{try{let n=await fetch(`/sessions`);if(!n.ok)return;let r=(await n.json().catch(()=>null))?.sessions?.[0];if(e||!r?.id)return;t(r)}catch{}})(),()=>{e=!0}},[]),!e)return null;let n=typeof window<`u`?xh(window.location.href,e.id):`?replay=${encodeURIComponent(e.id)}`,r=e.seedText?e.seedText.length>70?`${e.seedText.slice(0,70).trim()}…`:e.seedText.trim():null,i=ln(e,3),a=e.title||e.scenarioName||i||r||e.id,o=[e.scenarioName&&e.scenarioName!==a?e.scenarioName:null,typeof e.eventCount==`number`?`${e.eventCount} events`:null,typeof e.durationMs==`number`?`${Math.round(e.durationMs/1e3)}s`:null,typeof e.createdAt==`number`?new Date(e.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Sh.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Sh.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Sh.row,children:[(0,x.jsx)(`span`,{className:Sh.actor,children:a}),(0,x.jsx)(`span`,{className:Sh.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Sh.meta,children:o})]})}var wh={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`},Th={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Eh({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`?wh.statusDone:n===`active`?wh.statusActive:wh.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${wh.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:wh.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:wh.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:wh.label,children:t}),i&&(0,x.jsx)(`span`,{className:wh.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:wh.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${wh.chevron} ${o?wh.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:wh.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${wh.actorChip} ${wh[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:wh.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:wh.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Th[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:wh.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:`${wh.line} ${wh.tonePending}`,children:[(0,x.jsx)(`span`,{className:wh.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:wh.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:wh.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${wh.line} ${wh[`tone${Dh(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:wh.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:wh.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:wh.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:wh.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:wh.lineBody,children:e.body})]},t))]})]})}function Dh(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Oh(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 kh(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 Ah(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 jh(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 Mh(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=jh(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`:Ah(e.type),body:r,tone:kh(e.type),actor:typeof n==`string`?n:void 0}}function Nh(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Oh(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:Oh(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Ph(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Oh(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:Oh(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Fh(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Oh(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:Oh(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Ih(e){return e.events.map(e=>Mh(e)).filter(e=>!!e)}function Lh(e,t){switch(e){case`compile`:return Nh(t);case`research`:return Ph(t);case`actors`:return Fh(t);case`running`:return Ih(t);case`done`:return[]}}function Rh(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 zh={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`},Bh=[`compile`,`research`,`actors`,`running`,`done`];function Vh(e,t){let n=Bh.indexOf(e),r=Bh.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Hh({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=cT(),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:zh.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:zh.heading,children:[(0,x.jsx)(`span`,{className:zh.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:zh.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:zh.stageList,children:m.map(n=>{let r=Vh(e,n.id);return(0,x.jsx)(`li`,{className:zh.stageItem,children:(0,x.jsx)(Eh,{stageId:n.id,label:n.label,status:r,logLines:Lh(n.id,p),duration:Rh(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:zh.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:zh.cancel,onClick:a,children:`Cancel run`})]})}var Uh=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}}}),Wh={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 Gh({onSelect:e,onClose:t}){let n=ht(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Wh.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Wh.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Wh.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:Wh.list,children:Object.values(Uh).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Wh.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Wh.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Wh.description,children:t.description})]})},t.id))})]})})}var Kh={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`},qh=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function Jh({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=gn(),a=cT(),o=om(),[s,c]=(0,b.useState)(null),[l,u]=(0,b.useState)(null),d=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},f=async e=>{if(!n)return;let t=Am(window.location.origin,n);try{await navigator.clipboard.writeText(t),u(e),setTimeout(()=>u(null),1500)}catch{}},p=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;jm(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},m=(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:Kh.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:Kh.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:m.totalCitations}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:Kh.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one in a sandboxed node:vm at runtime. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:Kh.summaryNum,children:m.totalTools}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:Kh.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:Kh.summaryNum,children:m.totalDecisions}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:m.totalTurns}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`turns simulated`})]}),m.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:Kh.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:Kh.summaryNum,children:[`$`,m.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Kh.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:Kh.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(Yh,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,copiedHere:l===r,shareEnabled:!!n,onDownload:()=>p(r),onShare:()=>f(r),onFork:()=>d(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)(Gh,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function Yh({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,copiedHere:a,shareEnabled:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>km(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:Kh.card,children:[(0,x.jsxs)(`header`,{className:Kh.cardHeader,children:[(0,x.jsx)(`h4`,{className:Kh.actorName,children:e.name}),(0,x.jsx)(`span`,{className:Kh.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:Kh.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:Kh.hexaco,children:qh.map(t=>(0,x.jsxs)(`div`,{className:Kh.trait,children:[(0,x.jsx)(`span`,{className:Kh.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:Kh.traitBarOuter,children:(0,x.jsx)(`div`,{className:Kh.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:Kh.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:Kh.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Kh.delta} ${Kh[`direction_${e.direction}`]}`,children:lm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:Kh.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!o,title:`Copy a deep link that opens this run on the visualization tab`,children:a?`Copied!`:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:Kh.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 →`})]}),(0,x.jsx)(`div`,{className:Kh.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var Xh=`paracosm:lastLaunchConfig`,Zh=`paracosm:keyOverrides`,Qh=`paracosm:activeRunActors`,$h=`paracosm:activeRunScenarioId`,eg=950;function tg(e){try{let t=e.getItem(Xh);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function ng(e,t){return e.scenarioId===t}function rg(e,t){try{e.setItem(Xh,JSON.stringify(t))}catch{}}function ig(e,t,n){try{e.setItem(Qh,JSON.stringify(t)),n?e.setItem($h,n):e.removeItem?.($h)}catch{}}function ag(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function og(e){try{let t=e.getItem(Qh);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 sg(e){try{let t=e.getItem(Zh);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function cg(e,t){let n=(typeof e.seed==`number`?e.seed:eg)+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}var lg=2e3,ug=3e5;function dg(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 fg(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 pg(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??lg,i=t.timeoutMs??ug,a=t.waitImpl??dg,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 fg(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 fg(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 mg={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 hg(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 gg({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=iT(),s=oT(),{toast:c}=St(),[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`?sg(window.localStorage):{},i=typeof window<`u`?tg(window.localStorage):null,a={};r.openai&&(a.apiKey=r.openai),r.anthropic&&(a.anthropicKey=r.anthropic),r.serper&&(a.serperKey=r.serper),r.firecrawl&&(a.firecrawlKey=r.firecrawl),r.tavily&&(a.tavilyKey=r.tavily),r.cohere&&(a.cohereKey=r.cohere),i?.provider&&(a.provider=i.provider),i?.models&&typeof i.models==`object`&&(a.models=i.models),i?.economics&&typeof i.economics==`object`&&(a.economics=i.economics);let s=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(s.length>=t){u({kind:`progress`,stage:`running`});let n=s.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&ig(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...a,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=wm(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=hg(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})});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`&&ig(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...a,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 s=await i.json().catch(()=>({}));if(s.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=wm(window.location.href,s.redirect);return}}catch(e){u({kind:`input`});let t=hg(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}`)}re(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=hg(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{scenario:n,scenarioId:r}=await pg(t);u({kind:`progress`,stage:`research`,scenario:n});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:r})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:n});let i=Math.max(1,Math.min(300,t.actorCount??2)),a=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:r,count:i})});if(!a.ok){let e=await a.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${a.status}`)}let o=(await a.json().catch(()=>null))?.actors;if(!o||o.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:n,actors:o}),await e.reset(),typeof window<`u`&&ig(window.localStorage,o,r);let s=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:o,turns:n.setup.defaultTurns,seed:n.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:r}})});if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${s.status}`)}let c=await s.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=wm(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=hg(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,ee=(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:mg.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:mg.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:mg.howItWorks,children:[(0,x.jsx)(`summary`,{className:mg.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:mg.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:mg.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:mg.errorBanner,role:`alert`,children:d}),(0,x.jsx)(Ch,{}),(0,x.jsx)(fh,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(yh,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Hh,{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:mg.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:mg.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)(Jh,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:ee}),p&&h&&(0,x.jsx)(Ei,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var _g={getNumber:()=>0,getEntry:()=>void 0,list:[]};function vg(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 yg=(0,b.createContext)(_g);function bg(){return(0,b.useContext)(yg)}var xg={getNumber:()=>0,getEntry:()=>void 0,list:[]};function Sg(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=e.data?._filteredTools||[],o=String(e.data?.department||``);for(let s of a){let a=String(s.name||``).trim();if(!a||a===`unnamed`)continue;let c=t.get(a);c?(typeof s.output==`string`&&s.output&&(c.sampleOutput=s.output),typeof s.confidence==`number`&&s.confidence>c.confidence&&(c.confidence=s.confidence),s.approved!==!1&&(c.approved=!0),!c.inputSchema&&s.inputSchema&&(c.inputSchema=s.inputSchema),!c.outputSchema&&s.outputSchema&&(c.outputSchema=s.outputSchema),c.approved?c.errorReason=void 0:typeof s.errorReason==`string`&&s.errorReason&&(c.errorReason=s.errorReason)):(c={n:r++,name:a,description:String(s.description||a),mode:String(s.mode||`sandbox`),firstForgedTurn:typeof s.firstForgedTurn==`number`?s.firstForgedTurn:e.turn??0,firstForgedDepartment:String(s.firstForgedDepartment||o),departments:new Set,actorNames:new Set,reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:typeof s.confidence==`number`?s.confidence:s.approved===!1?0:.85,approved:s.approved!==!1,inputSchema:s.inputSchema,outputSchema:s.outputSchema,sampleOutput:typeof s.output==`string`?s.output:null,errorReason:typeof s.errorReason==`string`?s.errorReason:void 0,inputFields:Array.isArray(s.inputFields)?s.inputFields:[],outputFields:Array.isArray(s.outputFields)?s.outputFields:[],history:[]},t.set(a,c),n.push(c)),o&&c.departments.add(o),c.actorNames.add(i);let l=s.history||null;Array.isArray(l)&&(c.history=l.map(e=>({...e,actorName:i})),c.reuseCount=Math.max(0,l.length-1),c.reforgeCount=l.filter(e=>e.isReforge).length,c.rejectedReforges=l.filter(e=>e.isReforge&&e.rejected).length)}}}for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`forge_attempt`)continue;let a=e.data||{},o=String(a.name||``).trim();if(!o||o===`unnamed`||t.has(o)||a.approved===!0)continue;let s={n:r++,name:o,description:String(a.description||o),mode:String(a.mode||`sandbox`),firstForgedTurn:Number(a.turn??e.turn??0),firstForgedDepartment:String(a.department||``),departments:new Set(typeof a.department==`string`&&a.department?[a.department]:[]),actorNames:new Set([i]),reuseCount:0,reforgeCount:0,rejectedReforges:1,confidence:typeof a.confidence==`number`?a.confidence:0,approved:!1,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:typeof a.errorReason==`string`?a.errorReason:void 0,inputFields:Array.isArray(a.inputFields)?a.inputFields:[],outputFields:Array.isArray(a.outputFields)?a.outputFields:[],history:[{turn:Number(a.turn??e.turn??0),time:Number(a.time??0),eventIndex:Number(a.eventIndex??0),eventTitle:``,department:String(a.department||``),output:null,isReforge:!1,rejected:!0,confidence:typeof a.confidence==`number`?a.confidence:void 0,actorName:i}]};t.set(o,s),n.push(s)}}return{getNumber:e=>t.get(e)?.n??0,getEntry:e=>t.get(e),list:n}},[e])}var Cg=(0,b.createContext)(xg);function wg(){return(0,b.useContext)(Cg)}var Tg=m(),Eg=420,Dg=260;function Og({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(Eg,window.innerWidth-20),r=t.left,i=t.top-Dg-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+Dg>window.innerHeight-10&&(i=window.innerHeight-Dg-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:`${Eg}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,Tg.createPortal)(p,document.body):null]})}function kg(){let[e,t]=(0,b.useState)([]),[n,r]=(0,b.useState)(`loading`),[i,a]=(0,b.useState)(0),o=(0,b.useCallback)(()=>a(e=>e+1),[]);return(0,b.useEffect)(()=>{let e=!1;return r(`loading`),fetch(`/sessions`).then(async n=>{if(e)return;if(n.status===503){r(`unavailable`),t([]);return}if(!n.ok){r(`error`),t([]);return}let i=await n.json();e||(t(i.sessions??[]),r(`ready`))}).catch(()=>{e||(r(`error`),t([]))}),()=>{e=!0}},[i]),{sessions:e,status:n,refresh:o}}var Ag={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`},jg=Ag;function Mg(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 Ng(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 Pg(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Fg({s:e,onPick:t}){let n=ln(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()} (${Mg(e.createdAt)}) · ${Ng(e.durationMs)} · ${Pg(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Ag.sessionCard,children:[(0,x.jsx)(`div`,{className:Ag.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Ag.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Ag.sessionCardLine3,children:o})]})}function Ig({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}=kg(),g=p.length>0,_=oT();(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=>{let t=xh(window.location.href,e);window.location.assign(wm(t,`sim`))},C=()=>{v(),t?.()},w=bh(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Ag.root,children:[(0,x.jsx)(Og,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ag.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:Ag.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Ag.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Ag.runNewButton,children:[(0,x.jsxs)(`span`,{className:Ag.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Ag.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Ag.runSavedButton,g?``:Ag.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Ag.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Ag.runSavedBadge,g?``:Ag.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Ag.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Fg,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Ag.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Ag.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Ag.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:jg.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:jg.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:jg.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:jg.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=`${Mg(t)} · ${e.summary.eventCount} ev · ${Pg(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:jg.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:jg.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:jg.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:jg.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:jg.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:jg.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. Server data untouched — use Wipe All in the ⋯ menu for that.`,onClick:()=>{window.confirm(`Clear all local browser state?
|
|
114
114
|
|
|
115
115
|
• Saved-runs ring (this dropdown)
|
|
116
116
|
• Event cache (Sim / Constellation / Log)
|
|
@@ -119,11 +119,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
119
119
|
Server-stored runs are NOT affected (use Wipe All in the ⋯ menu for that).
|
|
120
120
|
|
|
121
121
|
Cannot be undone.`)&&i()},children:`Clear local data`})]})]}),t&&(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:C,className:Ag.loadFileButton,children:[(0,x.jsxs)(`span`,{className:Ag.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ag.menuButtonIcon,children:`📁`}),(0,x.jsx)(`span`,{children:`Load from file…`})]}),(0,x.jsx)(`span`,{className:Ag.loadFileBadge,children:`json export`})]})]})]})}var W={bar:`_bar_1xhvr_1`,logoLink:`_logoLink_1xhvr_7`,logoSpan:`_logoSpan_1xhvr_14`,logoImg:`_logoImg_1xhvr_21`,logoGlow:`_logoGlow_1xhvr_25`,brand:`_brand_1xhvr_33`,brandAccent:`_brandAccent_1xhvr_42`,agentosTag:`_agentosTag_1xhvr_46`,divider:`_divider_1xhvr_55`,scenarioName:`_scenarioName_1xhvr_60`,center:`_center_1xhvr_67`,meta:`_meta_1xhvr_71`,tokenInline:`_tokenInline_1xhvr_78`,tokenLabel:`_tokenLabel_1xhvr_83`,tokenValue:`_tokenValue_1xhvr_87`,progressTrack:`_progressTrack_1xhvr_91`,progressFill:`_progressFill_1xhvr_95`,tooltipTitle:`_tooltipTitle_1xhvr_100`,fallbackBlock:`_fallbackBlock_1xhvr_107`,fallbackRow:`_fallbackRow_1xhvr_113`,fallbackRowMeta:`_fallbackRowMeta_1xhvr_122`,fallbackPill:`_fallbackPill_1xhvr_126`,tagline:`_tagline_1xhvr_140`,github:`_github_1xhvr_146`,githubIcon:`_githubIcon_1xhvr_169`,tourBtn:`_tourBtn_1xhvr_173`,launchingChip:`_launchingChip_1xhvr_186`,toolBtn:`_toolBtn_1xhvr_199`,overflowAnchor:`_overflowAnchor_1xhvr_211`,overflowTrigger:`_overflowTrigger_1xhvr_215`,overflowMenu:`_overflowMenu_1xhvr_224`,overflowItem:`_overflowItem_1xhvr_241`,overflowItemDanger:`_overflowItemDanger_1xhvr_254`,statusPill:`_statusPill_1xhvr_267`,statusText:`_statusText_1xhvr_278`,themeBtn:`_themeBtn_1xhvr_282`};function Lg({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:W.logoSpan,style:{"--logo-size":`${e}px`,"--logo-glow":n},children:[(0,x.jsx)(`img`,{src:`/favicon.svg`,width:e,height:e,alt:`Paracosm`,className:W.logoImg}),(0,x.jsx)(`span`,{className:`pc-logo-glow ${W.logoGlow}`})]})}function Rg({scenario:e,sse:t,gameState:n,onSave:r,onLoad:i,onClear:a,onRun:o,onTour:s,onCopy:c,onShareViz:l,launching:u=!1,history:d,onRestoreHistory:f,onClearHistory:p}){let{resolved:m,setTheme:h}=C(),g=Object.values(n.actors).some(e=>e.events.length>0),[_,v]=(0,b.useState)(!1),y=(0,b.useRef)(null),S=ht(_);(0,b.useEffect)(()=>{if(!_)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),v(!1))},t=e=>{let t=y.current;t&&(t.contains(e.target)||v(!1))};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,t)}},[_]);let w=t.isAborted?`var(--amber)`:t.isComplete?`var(--green)`:t.status===`connected`?`var(--color-success)`:`var(--text-3)`,T=t.isAborted?`Interrupted`:t.isComplete?`Complete`:t.status===`connected`?`Live`:t.status===`error`?`Reconnecting`:`Connecting`,ee=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}},E=t.isAborted?(()=>{if(t.providerError)return`Run interrupted: ${t.providerError.message}. Click Clear to reset.`;let e=t.abortReason;return e?`${`Run interrupted: ${ee(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.`,D=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 ${W.bar}`,role:`banner`,children:[(0,x.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,x.jsxs)(`a`,{href:`/`,className:`${W.logoLink} ${W.brand}`,"aria-label":`Paracosm home`,children:[(0,x.jsx)(Lg,{size:20}),(0,x.jsxs)(`span`,{children:[`PARA`,(0,x.jsx)(`span`,{className:W.brandAccent,children:`COSM`})]})]}),(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:`topbar-agentos ${W.agentosTag}`,"aria-label":`AgentOS Runtime (opens in new tab)`,title:`AgentOS Runtime`,children:`AGENTOS`}),(0,x.jsx)(`span`,{className:`topbar-agentos ${W.divider}`,"aria-hidden":`true`,children:`|`}),(0,x.jsx)(`span`,{className:`topbar-scenario ${W.scenarioName}`,children:e.labels.name})]}),(0,x.jsxs)(`div`,{className:`flex items-center gap-3 flex-1 justify-center ${W.center}`,children:[n.turn>0&&(0,x.jsxs)(`div`,{className:`topbar-meta flex items-center gap-2 shrink-0 ${W.meta}`,children:[(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:W.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:W.tokenInline,children:[(0,x.jsx)(`span`,{className:W.tokenLabel,children:`T`}),(0,x.jsx)(`strong`,{className:W.tokenValue,children:n.turn}),(0,x.jsxs)(`span`,{className:W.tokenLabel,children:[`/`,n.maxTurns]})]})}),(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:W.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:W.tokenInline,children:[(0,x.jsx)(`span`,{className:W.tokenLabel,children:`Y`}),(0,x.jsx)(`strong`,{className:W.tokenValue,children:n.time})]})}),(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:W.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:W.tokenInline,children:[(0,x.jsx)(`span`,{className:W.tokenLabel,children:`S`}),(0,x.jsx)(`strong`,{className:W.tokenValue,children:n.seed})]})}),(0,x.jsx)(`div`,{className:`topbar-progress w-20 h-1.5 rounded-full overflow-hidden ${W.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 ${W.progressFill}`,style:{"--progress-pct":D}})}),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:W.fallbackBlock,children:e.map(e=>(0,x.jsxs)(`div`,{className:W.fallbackRow,children:[(0,x.jsx)(`span`,{children:e.schemaName}),(0,x.jsxs)(`span`,{className:W.fallbackRowMeta,children:[e.count,`× `,e.lastSite?`(last: ${e.lastSite})`:``]})]},e.schemaName))});return(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[r>0&&(0,x.jsxs)(`div`,{style:{marginBottom:i>0?8:0},children:[(0,x.jsxs)(`div`,{className:W.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:W.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:W.fallbackPill,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),a]})})})()]}),(0,x.jsx)(`div`,{className:`topbar-center hidden md:block truncate ${W.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 ${W.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:W.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`})]}),s&&(0,x.jsxs)(`button`,{onClick:s,className:`topbar-tour ${W.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:`?`})]}),o&&!n.isRunning&&!u&&(0,x.jsx)(Ig,{onRun:o,onLoadFromFile:i,history:d,onRestoreHistory:f,onClearHistory:p,liveStateHasEvents:t.events.length>0}),u&&!n.isRunning&&(0,x.jsx)(`span`,{className:W.launchingChip,role:`status`,"aria-live":`polite`,children:`LAUNCHING…`}),(g&&(r||c||l)||a)&&(0,x.jsxs)(`div`,{ref:y,className:W.overflowAnchor,children:[(0,x.jsx)(`button`,{type:`button`,onClick:()=>v(e=>!e),"aria-haspopup":`menu`,"aria-expanded":_,"aria-label":_?`Close run actions`:`Open run actions menu`,title:`Save · Share · Copy · Wipe`,className:`${W.toolBtn} ${W.overflowTrigger}`,children:`⋯`}),_&&(0,x.jsxs)(`div`,{ref:S,role:`menu`,tabIndex:-1,className:W.overflowMenu,children:[g&&r&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),r()},className:W.overflowItem,title:`Export simulation data as .json`,children:`Save`}),g&&l&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),l()},className:W.overflowItem,title:`Copy a deep link that opens this run on the visualization tab`,children:`Share viz link`}),g&&c&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),c()},className:W.overflowItem,title:`Copy simulation summary to clipboard`,children:`Copy`}),a&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),a()},className:W.overflowItemDanger,title:`Clear in-browser simulation buffer + cached events. Server-stored runs are kept.`,children:`Clear local data`})]})]}),(0,x.jsx)(`span`,{className:W.divider,"aria-hidden":`true`,children:`|`}),(0,x.jsxs)(`span`,{className:W.statusPill,style:{"--status-color":w},role:`status`,"aria-live":`polite`,"aria-label":`${T}. ${E}`,title:E,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:t.status===`connected`&&!t.isComplete?`●`:`○`}),(0,x.jsx)(`span`,{className:`topbar-status-text ${W.statusText}`,children:T})]}),(0,x.jsx)(`button`,{onClick:()=>h(m===`dark`?`light`:`dark`),className:`px-2 py-0.5 rounded cursor-pointer transition-colors ${W.themeBtn}`,title:`Switch to ${m===`dark`?`light`:`dark`} mode`,"aria-label":`Switch to ${m===`dark`?`light`:`dark`} mode`,children:m===`dark`?`☀`:`☽`})]})]})}var zg={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 Bg({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 Vg=[{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 Hg({active:e,onTabChange:t,scenario:n}){let r=Vg.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 ${zg.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:[zg.tab,o<r.length-1?zg.withDivider:``,s?zg.active:zg.inactive].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:zg.icon,"aria-hidden":`true`,children:(0,x.jsx)(Bg,{id:n.id,size:18})}),(0,x.jsx)(`span`,{className:zg.label,"aria-hidden":`true`,children:n.label})]},n.id)})})}var Ug={banner:`_banner_1eqcj_1`,icon:`_icon_1eqcj_17`,body:`_body_1eqcj_30`,heading:`_heading_1eqcj_35`,message:`_message_1eqcj_40`,messageActor:`_messageActor_1eqcj_46`,actionLink:`_actionLink_1eqcj_50`,dismissBtn:`_dismissBtn_1eqcj_61`};function Wg({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`?`${Gg(e.provider)} credits exhausted`:e.kind===`auth`?`${Gg(e.provider)} API key invalid`:e.kind===`rate_limit`?`${Gg(e.provider)} rate-limited`:e.kind===`network`?`Network error contacting ${Gg(e.provider)}`:`Provider error`,i={"--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:Ug.banner,style:i,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ug.icon,children:`!`}),(0,x.jsxs)(`div`,{className:Ug.body,children:[(0,x.jsx)(`div`,{className:Ug.heading,children:r}),(0,x.jsxs)(`div`,{className:Ug.message,children:[e.message,e.leader?(0,x.jsxs)(`span`,{className:Ug.messageActor,children:[` (hit by `,e.leader,`)`]}):null]})]}),e.actionUrl?(0,x.jsx)(`a`,{href:e.actionUrl,target:`_blank`,rel:`noreferrer noopener`,className:Ug.actionLink,children:e.kind===`quota`?`Add credits →`:`Fix key →`}):null,t?(0,x.jsx)(`button`,{onClick:t,"aria-label":`Dismiss banner`,className:Ug.dismissBtn,children:`Dismiss`}):null]})}function Gg(e){return e===`openai`?`OpenAI`:e===`anthropic`?`Anthropic`:e===`openrouter`?`OpenRouter`:e===`gemini`?`Gemini`:`Provider`}var G={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`},Kg={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`},qg=[`hba1c`,`weight`,`exerciseAdherence`],Jg={hba1c:`#ef6f5d`,weight:`#ffd970`,exerciseAdherence:`#34d399`,bmi:`#a78bfa`,qualityOfLife:`#7cb6ff`,mortalityRisk:`#ef6f5d`,alignmentBench:`#7cb6ff`,specGamingRate:`#ef6f5d`,releaseReadiness:`#ffd970`,morale:`#ffd970`,runwayMonths:`#5fd49a`,marketShare:`#7cb6ff`},Yg=new Set([`hba1c`,`fastingGlucose`,`weight`,`bmi`,`exerciseAdherence`,`sleepHours`,`qualityOfLife`,`mortalityRisk`,`cardioFitness`,`sideEffectBurden`]);function Xg(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 Zg(e,t){let n=t-e;return Math.abs(n)<1e-6?{text:`·`,direction:`flat`}:{text:`${n>0?`+`:``}${Xg(n)}`,direction:n>0?`up`:`down`}}function Qg(e){return e==null?`—`:typeof e==`number`?Xg(e):typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?e:JSON.stringify(e)}var $g={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 e_(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 t_({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:qg.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=>Yg.has(e))?Array.from(e).filter(e=>Yg.has(e)):Array.from(e)).slice(0,12)},[d,u]),h=c?Object.entries(c).slice(0,6):[];return(0,x.jsxs)(`div`,{className:G.root,children:[(0,x.jsxs)(`div`,{className:G.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h2`,{className:G.title,children:`Digital Twin · Intervention Result`}),(0,x.jsxs)(`span`,{className:G.subTitle,children:[l?.scenario?.name??`scenario`,` · seed `,l?.seed??`?`,` · `,o?.timepoints?.length??0,` turns`]})]}),(0,x.jsxs)(`div`,{className:G.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:G.cardsRow,children:[(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.cardHeader,children:[(0,x.jsx)(`span`,{className:G.cardLabel,children:`Subject`}),(0,x.jsx)(`span`,{className:G.cardId,children:r?.id})]}),(0,x.jsx)(`div`,{className:G.cardName,children:r?.name}),f.length>0&&(0,x.jsx)(`div`,{className:G.kvList,children:f.map(([e,t])=>(0,x.jsxs)(`div`,{className:G.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:Qg(t)})]},e))}),r?.signals&&r.signals.length>0&&(0,x.jsx)(`div`,{className:G.signalList,children:r.signals.slice(0,4).map((e,t)=>(0,x.jsxs)(`div`,{className:G.signal,children:[(0,x.jsx)(`span`,{className:G.signalLabel,children:e.label}),(0,x.jsxs)(`span`,{className:G.signalValue,children:[typeof e.value==`number`?Xg(e.value):String(e.value),e.unit?` ${e.unit}`:``]})]},t))})]}),(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.cardHeader,children:[(0,x.jsx)(`span`,{className:G.cardLabel,children:`Intervention`}),(0,x.jsx)(`span`,{className:G.cardId,children:i?.id})]}),(0,x.jsx)(`div`,{className:G.cardName,children:i?.name}),i?.description&&(0,x.jsx)(`p`,{className:G.description,children:i.description}),(0,x.jsxs)(`div`,{className:G.kvList,children:[i?.duration&&(0,x.jsxs)(`div`,{className:G.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:G.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:G.section,children:[(0,x.jsx)(`h3`,{className:G.sectionTitle,children:`Final state · delta vs initial`}),(0,x.jsx)(`div`,{className:G.metricsGrid,children:m.map(e=>{let t=u[e],n=d[e];if(typeof n!=`number`)return null;let r=typeof t==`number`?Zg(t,n):null;return(0,x.jsxs)(`div`,{className:G.metric,children:[(0,x.jsx)(`span`,{className:G.metricLabel,children:Kg[e]??e}),(0,x.jsx)(`span`,{className:G.metricValue,children:Xg(n)}),r&&(0,x.jsx)(`span`,{className:`${G.metricDelta} ${r.direction===`up`?G.metricDeltaUp:r.direction===`down`?G.metricDeltaDown:``}`,children:r.text})]},e)})})]}),p&&p.series.length>0&&(0,x.jsxs)(`div`,{className:G.section,children:[(0,x.jsx)(`h3`,{className:G.sectionTitle,children:`Trajectory`}),(0,x.jsxs)(`div`,{className:G.chartWrap,children:[(0,x.jsxs)(`svg`,{className:G.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:Jg[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:Jg[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:G.chartLegend,children:p.series.map(e=>(0,x.jsxs)(`span`,{className:G.legendItem,children:[(0,x.jsx)(`span`,{className:`${G.legendSwatch} ${G.legendSwatchInline}`,style:{"--swatch-color":Jg[e.metric]}}),Kg[e.metric]??e.metric]},e.metric))})]})]}),h.length>0&&(0,x.jsxs)(`div`,{className:G.section,children:[(0,x.jsx)(`h3`,{className:G.sectionTitle,children:`Fingerprint`}),(0,x.jsx)(`div`,{className:G.fingerprintList,children:h.map(([e,t])=>(0,x.jsxs)(`span`,{className:G.fingerprintChip,children:[e,(0,x.jsx)(`b`,{children:String(t)})]},e))})]}),(0,x.jsx)(n_,{state:t}),n&&(0,x.jsx)(`div`,{className:G.dismissBar,children:(0,x.jsx)(`button`,{onClick:n,className:G.dismissButton,children:`Clear · run another`})})]})}function n_({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:G.section,children:[(0,x.jsxs)(`h3`,{className:G.sectionTitle,children:[`Playback · `,r,` / `,n,` events`]}),(0,x.jsxs)(`div`,{className:G.playbackControls,children:[(0,x.jsx)(`button`,{onClick:()=>o(!a),className:G.playbackPlayBtn,children:a?`Pause`:r>=n?`Replay`:`Play`}),(0,x.jsx)(`button`,{onClick:()=>{i(0),o(!1)},className:G.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:G.playbackSlider})]}),(0,x.jsx)(`div`,{className:G.playbackList,children:c.length===0?(0,x.jsx)(`div`,{className:G.playbackHint,children:`Drag the slider or press Play to step through the run.`}):c.map(e=>(0,x.jsxs)(`div`,{className:G.playbackEvent,children:[(0,x.jsx)(`span`,{className:G.playbackTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:G.playbackType,children:$g[e.type]??e.type}),(0,x.jsx)(`span`,{className:G.playbackBody,children:e_(e)})]},e.id))})]})}var r_={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`},i_={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 a_(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 o_(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 s_({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:r_.root,children:[(0,x.jsxs)(`div`,{className:r_.headerRow,children:[(0,x.jsxs)(`h2`,{className:r_.title,children:[(0,x.jsx)(`span`,{className:r_.spinner,"aria-hidden":`true`}),`Digital Twin · Running`]}),(0,x.jsxs)(`span`,{className:r_.timer,children:[r,`s elapsed · streaming live · `,f,` `,f===1?`turn`:`turns`,` × LLM decisions`]})]}),(0,x.jsxs)(`div`,{className:r_.cardsRow,children:[(0,x.jsxs)(`div`,{className:r_.card,children:[(0,x.jsxs)(`div`,{className:r_.cardHeader,children:[(0,x.jsx)(`span`,{className:r_.cardLabel,children:`Subject`}),(0,x.jsx)(`span`,{className:r_.cardId,children:t.id})]}),(0,x.jsx)(`div`,{className:r_.cardName,children:t.name}),y.length>0&&(0,x.jsx)(`div`,{className:r_.kvList,children:y.map(([e,t])=>(0,x.jsxs)(`div`,{className:r_.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:typeof t==`number`?a_(t):String(t)})]},e))})]}),(0,x.jsxs)(`div`,{className:r_.card,children:[(0,x.jsxs)(`div`,{className:r_.cardHeader,children:[(0,x.jsx)(`span`,{className:r_.cardLabel,children:`Intervention`}),(0,x.jsx)(`span`,{className:r_.cardId,children:n.id})]}),(0,x.jsx)(`div`,{className:r_.cardName,children:n.name}),(0,x.jsx)(`p`,{className:r_.description,children:n.description}),n.duration&&(0,x.jsx)(`div`,{className:r_.kvList,children:(0,x.jsxs)(`div`,{className:r_.kv,children:[(0,x.jsx)(`span`,{children:`Duration`}),(0,x.jsxs)(`span`,{children:[n.duration.value,` `,n.duration.unit]})]})})]})]}),(0,x.jsxs)(`div`,{className:r_.statsBar,children:[(0,x.jsxs)(`div`,{className:r_.stat,children:[(0,x.jsx)(`span`,{className:r_.statLabel,children:`Turn`}),(0,x.jsxs)(`span`,{className:r_.statValue,children:[d,` / `,f]}),(0,x.jsx)(`div`,{className:r_.progressBar,children:(0,x.jsx)(`div`,{className:r_.progressFill,style:{width:`${p}%`}})})]}),(0,x.jsxs)(`div`,{className:r_.stat,children:[(0,x.jsx)(`span`,{className:r_.statLabel,children:`LLM Calls`}),(0,x.jsx)(`span`,{className:r_.statValue,children:h})]}),(0,x.jsxs)(`div`,{className:r_.stat,children:[(0,x.jsx)(`span`,{className:r_.statLabel,children:`Cost`}),(0,x.jsxs)(`span`,{className:r_.statValue,children:[`$`,m.toFixed(4)]})]}),(0,x.jsxs)(`div`,{className:r_.stat,children:[(0,x.jsx)(`span`,{className:r_.statLabel,children:`Tools forged`}),(0,x.jsx)(`span`,{className:r_.statValue,children:g})]}),(0,x.jsxs)(`div`,{className:r_.stat,children:[(0,x.jsx)(`span`,{className:r_.statLabel,children:`Citations`}),(0,x.jsx)(`span`,{className:r_.statValue,children:_})]})]}),(0,x.jsxs)(`div`,{className:r_.eventLog,children:[(0,x.jsxs)(`div`,{className:r_.eventLogHeader,children:[(0,x.jsx)(`span`,{className:r_.eventLogTitle,children:`Live event log · streaming from /events`}),(0,x.jsxs)(`span`,{className:r_.timer,children:[u.length,` events`]})]}),(0,x.jsx)(`div`,{ref:o,onScroll:v,className:r_.eventLogScroll,children:u.length===0?(0,x.jsx)(`div`,{className:r_.eventEmpty,children:`Waiting for the first server event…`}):u.map(e=>(0,x.jsxs)(`div`,{className:r_.eventRow,children:[(0,x.jsx)(`span`,{className:r_.eventTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:r_.eventType,children:i_[e.type]??e.type}),(0,x.jsx)(`span`,{className:r_.eventBody,children:o_(e)})]},e.id))})]})]})}var c_=`▁▂▃▄▅▆▇█`;function l_({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=>c_[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 K={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 u_(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 d_(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:f_(r),value:e}),n.length>=t)break}return n}function f_(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 p_(e,t){let n=Math.round(t*4);return`${e} ${`█`.repeat(n)+`░`.repeat(4-n)} ${t.toFixed(2)}`}function m_({actorIndex:e,leader:t,popHistory:n,moraleHistory:r,verdictPlacement:i,compact:a=!1,event:o,statuses:s,pendingDecision:c,nameFallback:l}){let u=ve(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:u_(i),s=t?.archetype?.replace(/^The\s+/i,``).toUpperCase()||``;return(0,x.jsxs)(`div`,{className:K.compact,style:{"--actor-color":u,"--actor-bg":d,"--actor-border":f},"aria-label":`${m} compact summary`,children:[(0,x.jsx)(`span`,{className:K.compactBand,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:K.compactSlot,"aria-hidden":`true`,title:`Slot ${h}`,children:h}),(0,x.jsx)(`span`,{className:K.compactName,children:m}),s&&(0,x.jsx)(`span`,{className:K.compactArchetype,title:t?.archetype,children:s}),e!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.compactSep,children:`·`}),(0,x.jsxs)(`span`,{className:K.compactStat,children:[`POP `,Math.round(e)]})]}),i!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.compactSep,children:`·`}),(0,x.jsxs)(`span`,{className:K.compactStat,children:[`MORALE `,Math.round(i),`%`]})]}),a&&(0,x.jsxs)(`span`,{className:`${K.compactMood} ${K[`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:K.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:K.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)=>p_(e,v[b[t]]??0)).join(` `):``,C=i?`${K.verdictChip} ${K[i]??``}`.trim():``;return(0,x.jsxs)(`div`,{className:K.root,style:{"--actor-color":u,"--actor-bg":d,"--actor-border":f},children:[(0,x.jsxs)(`div`,{className:K.headerRow,children:[(0,x.jsx)(`span`,{className:K.slot,"aria-hidden":`true`,title:`Slot ${h}`,children:h}),g&&(0,x.jsx)(`span`,{className:K.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)(Og,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:K.tooltipHeading,children:[g?`${g}: `:``,m]}),_&&(0,x.jsxs)(`div`,{children:[`Unit: `,_]}),t?.instructions&&(0,x.jsx)(`div`,{className:K.tooltipInstructions,children:t.instructions}),y&&(0,x.jsx)(`div`,{className:K.tooltipTraitBlock,children:b.map(e=>(0,x.jsxs)(`div`,{className:K.tooltipTraitRow,children:[(0,x.jsx)(`span`,{className:K.tooltipTraitLabel,children:e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g,` $1`)}),(0,x.jsx)(`span`,{className:K.tooltipTraitValue,children:(v[e]??0).toFixed(2)})]},e))})]}),children:(0,x.jsx)(`span`,{className:K.name,children:m})}),_&&(0,x.jsx)(`span`,{className:K.unitTag,children:_}),S&&(0,x.jsxs)(`span`,{className:`leader-traits ${K.traits}`,children:[(0,x.jsx)(`span`,{className:K.traitsSep,children:`|`}),(0,x.jsx)(`span`,{className:K.traitsLine,children:S})]})]}),(0,x.jsxs)(`div`,{className:K.subRow,children:[(0,x.jsx)(`span`,{className:K.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:K.awaiting,children:`Awaiting first turn…`}):``})()}),(0,x.jsxs)(`span`,{className:`leader-sparklines ${K.sparklines}`,children:[(0,x.jsx)(l_,{data:n,label:`POP`,color:u}),` `,(0,x.jsx)(l_,{data:r,label:`MORALE`,suffix:`%`,color:`var(--amber)`})]})]}),(0,x.jsx)(h_,{moraleHistory:r,event:o,statuses:s,pendingDecision:c})]})}function h_({moraleHistory:e,event:t,statuses:n,pendingDecision:r}){let i=e.length>0?e[e.length-1]:null,a=i===null?null:u_(i),o=d_(n,2);return a||t?.title||r||o.length>0?(0,x.jsxs)(`div`,{className:K.dynamicRow,role:`status`,"aria-live":`polite`,"aria-atomic":`false`,"aria-relevant":`additions text`,children:[a&&(0,x.jsxs)(`span`,{className:`${K.chip} ${K[`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:K.chipLabel,children:`Mood`}),(0,x.jsx)(`span`,{className:K.chipValue,children:a.label})]}),t?.title&&(0,x.jsxs)(`span`,{className:`${K.chip} ${K.chipCrisis}`,title:t.description??t.title,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),(0,x.jsx)(`span`,{className:K.chipLabel,children:f_(t.category)||`Event`}),(0,x.jsx)(`span`,{className:K.chipValue,children:t.title.length>32?`${t.title.slice(0,32)}…`:t.title})]}),r&&(0,x.jsxs)(`span`,{className:`${K.chip} ${K.chipDeciding}`,title:r,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⏳`}),(0,x.jsx)(`span`,{className:K.chipLabel,children:`Deciding`})]}),o.map(({key:e,label:t,value:n})=>(0,x.jsxs)(`span`,{className:`${K.chip} ${K.chipStatus}`,title:`${t}: ${n}`,children:[(0,x.jsx)(`span`,{className:K.chipLabel,children:t}),(0,x.jsx)(`span`,{className:K.chipValue,children:n})]},e))]}):null}function g_(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(`
|
|
122
|
-
`)}function __(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function v_(e,t){if(t.format===`percent`)return`${Math.round(__(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 y_={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 b_(e){return e===`foodMonthsReserve`?`mo`:``}var x_={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},S_={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function C_(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function w_(e,t){return e?t===`neutral`?y_.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?y_.deltaPositive:y_.deltaNegative:e.startsWith(`+`)?y_.deltaPositive:y_.deltaNegative:``}function T_(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 E_({actors:e,crisisText:t,toolRegistry:n}){let r=rT(),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,ee=o?.environment,E=s?.environment,{reuseA:D,reuseB:O}=(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]),te=(0,b.useRef)({toolsA:g,toolsB:_,reuseA:D,reuseB:O,citationsA:v,citationsB:y,deathsA:f,deathsB:p}),k=te.current,ne=C_(g,k.toolsA),re=C_(_,k.toolsB),A=C_(D,k.reuseA),j=C_(O,k.reuseB),ie=C_(v,k.citationsA),ae=C_(y,k.citationsB),M=C_(f,k.deathsA),oe=C_(p,k.deathsB);if((0,b.useEffect)(()=>{te.current={toolsA:g,toolsB:_,reuseA:D,reuseB:O,citationsA:v,citationsB:y,deathsA:f,deathsB:p}},[g,_,D,O,v,y,f,p]),!c&&!l)return null;let N=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),se=ve(0),ce=ve(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${y_.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":se,"--actor-color-b":ce},children:[t&&(0,x.jsx)(`span`,{className:y_.crisis,children:t}),N.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:__(t,e),i=C_(__(t,e),r(u?.[e.id])),a=C_(__(n,e),r(d?.[e.id])),o=v_(t,e),s=v_(n,e),f=b_(e.id),p=x_[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=S_[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:w_(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:y_.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:y_.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:w_(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.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}),M&&(0,x.jsx)(`span`,{className:w_(M,`lossIsRed`),children:M}),(0,x.jsx)(`span`,{className:y_.sep,children:`vs`}),(0,x.jsx)(`span`,{className:y_.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}),oe&&(0,x.jsx)(`span`,{className:w_(oe,`lossIsRed`),children:oe}),(()=>{let e=T_(m),t=T_(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:y_.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:g}),ne&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:ne}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:_}),re&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:re})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:D}),A&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:A}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:O}),j&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:j})]}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:v}),ie&&(0,x.jsx)(`span`,{className:w_(ie,`neutral`),children:ie}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:y}),ae&&(0,x.jsx)(`span`,{className:w_(ae,`neutral`),children:ae})]}),(w||T)&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${g_(w)||`(none)`}\n\nLeader B:\n${g_(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:T?Object.keys(T).length:0})]}),(ee||E)&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${g_(ee)||`(none)`}\n\nLeader B:\n${g_(E)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:ee?Object.keys(ee).length:0}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:E?Object.keys(E).length:0})]})]})}var D_={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 O_(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 k_(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 A_(e){if(!e)return null;let{color:t}=k_(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:D_.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function j_({t:e,sideColor:t}){let{label:n,color:r}=k_(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:D_.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:D_.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:D_.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:D_.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:D_.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:D_.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:D_.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:D_.tooltipDecision,children:[(0,x.jsx)(`span`,{className:D_.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:D_.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function M_({turns:e,actorIndex:t}){let n=ve(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:D_.side,children:e.map(e=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsx)(j_,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[D_.entry,e.current?D_.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:D_.entryHead,children:[(0,x.jsxs)(`span`,{className:D_.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:D_.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:D_.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:D_.entryEmergent,children:`EMERGENT`}),A_(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:D_.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:D_.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:D_.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:D_.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:D_.entryDecision,children:e.decision})]})},e.turn))})}function N_({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?O_(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 ${D_.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=ve(e.idx);return(0,x.jsxs)(`div`,{className:D_.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:D_.sideHeader,children:[(0,x.jsxs)(`span`,{className:D_.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:D_.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:D_.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(M_,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var P_={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 F_({outcome:e}){let t=P_[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 I_={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 L_({citations:e,label:t=`sources`,inline:n=!1}){let r=bg();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:[I_.row,n?I_.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:I_.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(R_,{n:e,entry:t},e))]})}function R_({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:I_.popoverWrap,children:[(0,x.jsxs)(`div`,{className:I_.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:I_.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:I_.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:I_.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:I_.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:I_.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:I_.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(Og,{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:I_.pill,children:[`[`,e,`]`]})})}var q={eventStartRow:`_eventStartRow_1j8hl_1`,notFirst:`_notFirst_1j8hl_9`,eventNumber:`_eventNumber_1j8hl_14`,eventStartTitle:`_eventStartTitle_1j8hl_21`,eventCategoryPill:`_eventCategoryPill_1j8hl_26`,promotionTooltipTitle:`_promotionTooltipTitle_1j8hl_35`,promotionTooltipRow:`_promotionTooltipRow_1j8hl_42`,promotionTooltipKey:`_promotionTooltipKey_1j8hl_46`,promotionTooltipValue:`_promotionTooltipValue_1j8hl_50`,promotionTooltipReason:`_promotionTooltipReason_1j8hl_55`,promotionRow:`_promotionRow_1j8hl_60`,promotionArrow:`_promotionArrow_1j8hl_70`,promotionRole:`_promotionRole_1j8hl_75`,promotionReason:`_promotionReason_1j8hl_81`,forgeBtn:`_forgeBtn_1j8hl_90`,forgeSlide:`_forgeSlide_1j8hl_1`,forgeRow:`_forgeRow_1j8hl_110`,forgeBadge:`_forgeBadge_1j8hl_117`,forgeDept:`_forgeDept_1j8hl_130`,forgeDescription:`_forgeDescription_1j8hl_136`,forgeName:`_forgeName_1j8hl_141`,forgeVerdictPass:`_forgeVerdictPass_1j8hl_147`,forgeVerdictFail:`_forgeVerdictFail_1j8hl_159`,forgeFieldsRow:`_forgeFieldsRow_1j8hl_171`,fieldsLabelIn:`_fieldsLabelIn_1j8hl_181`,fieldsLabelOut:`_fieldsLabelOut_1j8hl_185`,forgeError:`_forgeError_1j8hl_189`,specWrap:`_specWrap_1j8hl_196`,specCard:`_specCard_1j8hl_200`,specHeader:`_specHeader_1j8hl_209`,specHeaderDept:`_specHeaderDept_1j8hl_217`,specToolCount:`_specToolCount_1j8hl_225`,severityBadge:`_severityBadge_1j8hl_231`,specSummary:`_specSummary_1j8hl_241`,specSummaryEmpty:`_specSummaryEmpty_1j8hl_248`,specRisks:`_specRisks_1j8hl_256`,specRisksLabel:`_specRisksLabel_1j8hl_260`,specRiskRow:`_specRiskRow_1j8hl_269`,specRiskSeverity:`_specRiskSeverity_1j8hl_278`,specRecs:`_specRecs_1j8hl_287`,specRecsLabel:`_specRecsLabel_1j8hl_291`,specRecRow:`_specRecRow_1j8hl_300`,toolDetail:`_toolDetail_1j8hl_309`,newTool:`_newTool_1j8hl_320`,forgeGlow:`_forgeGlow_1j8hl_1`,reused:`_reused_1j8hl_324`,toolSummary:`_toolSummary_1j8hl_328`,toolSummaryMain:`_toolSummaryMain_1j8hl_336`,toolSummaryHead:`_toolSummaryHead_1j8hl_341`,toolNewBadge:`_toolNewBadge_1j8hl_348`,toolReusedBadge:`_toolReusedBadge_1j8hl_361`,toolFirstForged:`_toolFirstForged_1j8hl_374`,toolSchemaBadge:`_toolSchemaBadge_1j8hl_380`,toolDescription:`_toolDescription_1j8hl_390`,toolNameLine:`_toolNameLine_1j8hl_397`,toolPassPill:`_toolPassPill_1j8hl_405`,toolFailPill:`_toolFailPill_1j8hl_418`,toolInspectBtn:`_toolInspectBtn_1j8hl_431`,toolBody:`_toolBody_1j8hl_449`,toolMetaRow:`_toolMetaRow_1j8hl_454`,toolMetaLabel:`_toolMetaLabel_1j8hl_459`,toolRawSummary:`_toolRawSummary_1j8hl_466`,toolRawPre:`_toolRawPre_1j8hl_474`,toolEmpty:`_toolEmpty_1j8hl_489`,outcomeCard:`_outcomeCard_1j8hl_494`,decisionPulse:`_decisionPulse_1j8hl_1`,outcomeHead:`_outcomeHead_1j8hl_505`,outcomeLabel:`_outcomeLabel_1j8hl_512`,outcomeMeta:`_outcomeMeta_1j8hl_520`,outcomeText:`_outcomeText_1j8hl_527`,outcomeDeltas:`_outcomeDeltas_1j8hl_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_1j8hl_540`,outcomeBar:`_outcomeBar_1j8hl_544`,outcomeBarDeparts:`_outcomeBarDeparts_1j8hl_552`,outcomeReasoningSummary:`_outcomeReasoningSummary_1j8hl_556`,outcomeReasoningBody:`_outcomeReasoningBody_1j8hl_563`,outcomeReasoningPre:`_outcomeReasoningPre_1j8hl_570`,outcomeRationale:`_outcomeRationale_1j8hl_582`,outcomePolicyLine:`_outcomePolicyLine_1j8hl_587`,driftRow:`_driftRow_1j8hl_591`,driftLabel:`_driftLabel_1j8hl_599`,driftName:`_driftName_1j8hl_607`,reactionsCard:`_reactionsCard_1j8hl_611`,reactionsHead:`_reactionsHead_1j8hl_620`,reactionsLabel:`_reactionsLabel_1j8hl_627`,reactionsBar:`_reactionsBar_1j8hl_636`,reactionsBarSegment:`_reactionsBarSegment_1j8hl_645`,reactionsLegend:`_reactionsLegend_1j8hl_650`,reactionsLegendItem:`_reactionsLegendItem_1j8hl_657`,reactionsLegendSwatch:`_reactionsLegendSwatch_1j8hl_663`,reactionsQuotesSummary:`_reactionsQuotesSummary_1j8hl_671`,reactionsQuotesList:`_reactionsQuotesList_1j8hl_679`,reactionTooltipName:`_reactionTooltipName_1j8hl_686`,reactionTooltipMeta:`_reactionTooltipMeta_1j8hl_692`,reactionTooltipHexaco:`_reactionTooltipHexaco_1j8hl_697`,reactionTooltipHealth:`_reactionTooltipHealth_1j8hl_704`,reactionTooltipQuote:`_reactionTooltipQuote_1j8hl_709`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_1j8hl_717`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_1j8hl_724`,reactionRow:`_reactionRow_1j8hl_730`,notLast:`_notLast_1j8hl_739`,reactionRowName:`_reactionRowName_1j8hl_743`,reactionRowQuote:`_reactionRowQuote_1j8hl_750`,reactionRowMoodPill:`_reactionRowMoodPill_1j8hl_761`,bulletinWrap:`_bulletinWrap_1j8hl_773`,bulletinTooltipName:`_bulletinTooltipName_1j8hl_777`,bulletinTooltipRole:`_bulletinTooltipRole_1j8hl_781`,bulletinTooltipBody:`_bulletinTooltipBody_1j8hl_786`,bulletinTooltipMood:`_bulletinTooltipMood_1j8hl_792`,bulletinRow:`_bulletinRow_1j8hl_798`,bulletinName:`_bulletinName_1j8hl_807`,bulletinPost:`_bulletinPost_1j8hl_813`,bulletinLikes:`_bulletinLikes_1j8hl_822`,turnDone:`_turnDone_1j8hl_828`,fallbackBox:`_fallbackBox_1j8hl_841`,fallbackTitle:`_fallbackTitle_1j8hl_853`,fallbackSite:`_fallbackSite_1j8hl_859`,fallbackPreviewWrap:`_fallbackPreviewWrap_1j8hl_864`,fallbackPreviewSummary:`_fallbackPreviewSummary_1j8hl_868`,fallbackPreviewPre:`_fallbackPreviewPre_1j8hl_874`,modalBackdrop:`_modalBackdrop_1j8hl_885`,modalDialog:`_modalDialog_1j8hl_896`,modalHeader:`_modalHeader_1j8hl_912`,modalHeaderLeft:`_modalHeaderLeft_1j8hl_919`,modalKicker:`_modalKicker_1j8hl_924`,modalTitle:`_modalTitle_1j8hl_934`,modalDescription:`_modalDescription_1j8hl_942`,modalCloseBtn:`_modalCloseBtn_1j8hl_948`,modalScroll:`_modalScroll_1j8hl_959`,modalPills:`_modalPills_1j8hl_965`,modalEmpty:`_modalEmpty_1j8hl_974`,usageList:`_usageList_1j8hl_980`,usageItem:`_usageItem_1j8hl_989`,usageHeader:`_usageHeader_1j8hl_1000`,usageTurn:`_usageTurn_1j8hl_1007`,usageTime:`_usageTime_1j8hl_1012`,usageDept:`_usageDept_1j8hl_1016`,usageEvent:`_usageEvent_1j8hl_1021`,usageStatus:`_usageStatus_1j8hl_1025`,usageStatusBadge:`_usageStatusBadge_1j8hl_1031`,usageConf:`_usageConf_1j8hl_1040`,usageOutput:`_usageOutput_1j8hl_1045`,codePre:`_codePre_1j8hl_1053`,fieldsBlock:`_fieldsBlock_1j8hl_1069`,pill:`_pill_1j8hl_1077`,modalSection:`_modalSection_1j8hl_1088`,modalSectionTitle:`_modalSectionTitle_1j8hl_1092`,schemaBlock:`_schemaBlock_1j8hl_1102`,schemaFieldsLabel:`_schemaFieldsLabel_1j8hl_1106`,schemaFieldsList:`_schemaFieldsList_1j8hl_1114`,schemaTitle:`_schemaTitle_1j8hl_1119`,schemaTable:`_schemaTable_1j8hl_1128`,schemaRow:`_schemaRow_1j8hl_1136`,schemaKeyCell:`_schemaKeyCell_1j8hl_1140`,schemaRequired:`_schemaRequired_1j8hl_1148`,schemaTypeCell:`_schemaTypeCell_1j8hl_1153`,schemaDescCell:`_schemaDescCell_1j8hl_1160`,forgeDetails:`_forgeDetails_1j8hl_1168`,forgeSummary:`_forgeSummary_1j8hl_1180`,forgeInspectAbs:`_forgeInspectAbs_1j8hl_1197`,forgeBody:`_forgeBody_1j8hl_1215`,specDetails:`_specDetails_1j8hl_1220`,specSummaryRow:`_specSummaryRow_1j8hl_1229`,specBody:`_specBody_1j8hl_1246`,reactionsDetails:`_reactionsDetails_1j8hl_1252`,reactionsSummary:`_reactionsSummary_1j8hl_1260`,reactionsTopMood:`_reactionsTopMood_1j8hl_1277`,reactionsBody:`_reactionsBody_1j8hl_1285`,bulletinDetails:`_bulletinDetails_1j8hl_1290`,bulletinSummary:`_bulletinSummary_1j8hl_1294`,bulletinSummaryLabel:`_bulletinSummaryLabel_1j8hl_1312`,bulletinSummaryNames:`_bulletinSummaryNames_1j8hl_1322`,bulletinBody:`_bulletinBody_1j8hl_1332`,fallbackDetails:`_fallbackDetails_1j8hl_1336`,fallbackSummary:`_fallbackSummary_1j8hl_1347`},z_={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`},B_={positive:`#6aad48`,negative:`#e06530`,anxious:`#e8b44a`,defiant:`#e06530`,hopeful:`#6aad48`,resigned:`#a89878`,neutral:`#a89878`};function V_({event:e,actorIndex:t}){let n=rT(),r=wg(),[i,a]=(0,b.useState)(null),o=ve(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`,{className:[q.eventStartRow,e>0?q.notFirst:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:q.eventNumber,children:[`EVENT `,e+1,`/`,t]}),(0,x.jsx)(`span`,{className:q.eventStartTitle,children:n}),r&&(0,x.jsx)(`span`,{className:q.eventCategoryPill,children:r})]})}case`promotion`:{let e=String(c.reason||``),t=String(c.name||``),n=String(c.role||``);return(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:q.promotionTooltipTitle,style:s,children:[`Promotion: `,n]}),t&&(0,x.jsxs)(`div`,{className:q.promotionTooltipRow,children:[(0,x.jsx)(`span`,{className:q.promotionTooltipKey,children:`Agent:`}),` `,(0,x.jsx)(`span`,{className:q.promotionTooltipValue,children:t})]}),e&&(0,x.jsx)(`div`,{className:q.promotionTooltipReason,children:e})]}),children:(0,x.jsxs)(`div`,{className:q.promotionRow,children:[(0,x.jsx)(`span`,{className:q.promotionArrow,children:`→`}),(0,x.jsx)(`span`,{className:q.promotionRole,style:s,children:n}),(0,x.jsx)(`span`,{className:q.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),s=String(c.mode||`sandbox`),l=c.approved!==!1,u=typeof c.confidence==`number`?c.confidence:.85,d=c.errorReason?String(c.errorReason):``,f=l?o:`var(--rust)`,p=Array.isArray(c.inputFields)?c.inputFields:[],m=Array.isArray(c.outputFields)?c.outputFields:[],h={"--accent":f,"--bg-tint":l?`color-mix(in srgb, ${o} 7%, transparent)`:`rgba(224,101,48,0.04)`,"--border-tint":l?`color-mix(in srgb, ${o} 25%, transparent)`:`rgba(224,101,48,0.2)`,"--shadow-tint":l?`0 0 0 1px color-mix(in srgb, ${o} 10%, transparent)`:`var(--card-shadow)`,"--badge-color":l?`var(--bg-deep)`:`#fff`,"--badge-bg":f,"--badge-shadow":l?`0 0 8px rgba(232,180,74,0.4)`:`none`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`details`,{className:q.forgeDetails,style:h,children:[(0,x.jsx)(`summary`,{className:q.forgeSummary,children:(0,x.jsxs)(`span`,{className:q.forgeRow,children:[(0,x.jsx)(`span`,{className:q.forgeBadge,children:l?`✦ FORGED TOOL`:`↻ FORGE RETRY`}),(0,x.jsx)(`span`,{className:q.forgeDept,children:e}),(0,x.jsx)(`span`,{className:q.forgeDescription,children:n}),(0,x.jsxs)(`span`,{className:q.forgeName,children:[t,` (`,s,`)`]}),(0,x.jsx)(`span`,{className:l?q.forgeVerdictPass:q.forgeVerdictFail,children:l?`PASS ${u.toFixed(2)}`:`RETRY`})]})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Inspect forged tool ${t}`,className:q.forgeInspectAbs,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:q.forgeBody,children:[(p.length>0||m.length>0)&&(0,x.jsxs)(`div`,{className:q.forgeFieldsRow,children:[p.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelIn,children:`in:`}),` `,p.join(`, `)]}),m.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelOut,children:`out:`}),` `,m.join(`, `)]})]}),!l&&d&&(0,x.jsx)(`div`,{className:q.forgeError,children:d})]})]}),i&&(0,x.jsx)(U_,{entry:r.getEntry(i),fallbackName:i,onClose:()=>a(null)})]})}case`specialist_done`:{let e=String(c.department||``),t=c._filteredTools||[],s=t.filter(e=>e?.isNew!==!0),l=Array.isArray(c.risks)?c.risks:[],u=Array.isArray(c.recommendedActions)?c.recommendedActions.map(String):[],d=l.some(e=>e.severity===`critical`)?`critical`:l.some(e=>e.severity===`high`)?`high`:``,f=String(c.summary||``),p=Number(c.citations)||0;if(!f&&l.length===0&&u.length===0&&t.length===0&&p===0)return null;let m={"--card-bg":d===`critical`?`rgba(224,101,48,.08)`:d===`high`?`rgba(232,180,74,.06)`:`var(--bg-card)`,"--card-border":d===`critical`?`rgba(224,101,48,.25)`:d===`high`?`rgba(232,180,74,.2)`:`var(--border)`,"--card-accent":d===`critical`?`var(--rust)`:d===`high`?`var(--amber)`:`var(--teal)`},h=d?{"--sev-color":d===`critical`?`var(--rust)`:`var(--amber)`,"--sev-bg":d===`critical`?`rgba(224,101,48,.15)`:`rgba(232,180,74,.1)`}:void 0;return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:q.specWrap,children:[(0,x.jsxs)(`details`,{className:q.specDetails,style:m,children:[(0,x.jsxs)(`summary`,{className:q.specSummaryRow,children:[(0,x.jsxs)(`span`,{className:q.specHeaderDept,children:[n.ui.departmentIcons[e]||``,` `,e]}),t.length>0&&(0,x.jsxs)(`span`,{className:q.specToolCount,children:[`+`,t.length,` tool`,t.length===1?``:`s`,s.length<t.length&&` (${s.length} reused)`]}),d&&(0,x.jsxs)(`span`,{className:q.severityBadge,style:h,children:[d.toUpperCase(),` RISK`]}),(0,x.jsx)(L_,{citations:c.citationList||[],inline:!0,label:``})]}),(0,x.jsxs)(`div`,{className:q.specBody,children:[f?(0,x.jsx)(`div`,{className:q.specSummary,children:f}):l.length===0&&u.length===0&&(p>0||t.length>0)?(0,x.jsxs)(`div`,{className:q.specSummaryEmpty,children:[`Department analysis complete — no narrative summary returned, but`,p>0&&` ${p} source${p===1?``:`s`} surveyed`,p>0&&t.length>0&&` and `,t.length>0&&` ${t.length} tool${t.length===1?``:`s`} forged`,`.`]}):null,l.length>0&&(0,x.jsxs)(`div`,{className:q.specRisks,children:[(0,x.jsx)(`div`,{className:q.specRisksLabel,children:`RISKS`}),l.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:q.specRiskRow,children:[(0,x.jsx)(`span`,{className:q.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))]}),u.length>0&&(0,x.jsxs)(`div`,{className:q.specRecs,children:[(0,x.jsx)(`div`,{className:q.specRecsLabel,children:`RECOMMENDATIONS`}),u.slice(0,3).map((e,t)=>(0,x.jsx)(`div`,{className:q.specRecRow,children:e},t))]})]})]}),s.map((e,t)=>{let n=e.approved!==!1,r=e.isNew===!0,i=n?r?o:`var(--green)`:`var(--rust)`,s=n?r?`color-mix(in srgb, ${o} 10%, transparent)`:`rgba(106,173,72,.06)`:`rgba(224,101,48,.04)`,c=n?r?`color-mix(in srgb, ${o} 40%, transparent)`:`rgba(106,173,72,.2)`:`rgba(224,101,48,.15)`,l=r?`0 0 0 1px color-mix(in srgb, ${o} 15%, transparent), var(--card-shadow)`:`var(--card-shadow)`,u=e.inputSchema,d=e.outputSchema,f=!!u||!!d,p={"--tool-bg":s,"--tool-border":c,"--tool-accent":i,"--tool-shadow":l,"--side-color":o},m=[q.toolDetail,r?q.newTool:q.reused].join(` `);return(0,x.jsxs)(`details`,{className:m,style:p,children:[(0,x.jsxs)(`summary`,{className:q.toolSummary,children:[(0,x.jsxs)(`div`,{className:q.toolSummaryMain,children:[(0,x.jsxs)(`div`,{className:q.toolSummaryHead,children:[r?(0,x.jsx)(`span`,{className:q.toolNewBadge,children:`FORGED TOOL`}):(0,x.jsx)(`span`,{className:q.toolReusedBadge,children:`REUSED`}),!r&&e.firstForgedTurn!=null&&(0,x.jsxs)(`span`,{className:q.toolFirstForged,children:[`first forged T`,e.firstForgedTurn,e.firstForgedDepartment&&e.firstForgedDepartment!==e.department?` · ${e.firstForgedDepartment}`:``]}),f&&(0,x.jsx)(`span`,{className:q.toolSchemaBadge,children:`SCHEMA`})]}),(0,x.jsx)(`span`,{className:q.toolDescription,children:String(e.description||e.name||``)}),(0,x.jsxs)(`span`,{className:q.toolNameLine,children:[e.name,` `,e.mode?`(${e.mode})`:``]})]}),(0,x.jsx)(`span`,{className:n?q.toolPassPill:q.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(),a(e.name||``)},"aria-label":`Inspect tool ${e.name||``}`,className:q.toolInspectBtn,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:q.toolBody,children:[e.crisis&&(0,x.jsxs)(`div`,{className:q.toolMetaRow,children:[(0,x.jsx)(`span`,{className:q.toolMetaLabel,children:`CRISIS: `}),String(e.crisis)]}),e.department&&(0,x.jsxs)(`div`,{className:q.toolMetaRow,children:[(0,x.jsx)(`span`,{className:q.toolMetaLabel,children:`DEPT: `}),String(e.department)]}),(u||Array.isArray(e.inputFields)&&e.inputFields.length>0)&&(0,x.jsx)(K_,{label:`INPUT`,color:`var(--teal)`,schema:u,fields:e.inputFields}),(d||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(K_,{label:`OUTPUT`,color:`var(--green)`,schema:d,fields:e.outputFields}),e.output&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:q.toolRawSummary,style:{"--side-color":o},children:`Raw Output`}),(0,x.jsx)(`pre`,{className:q.toolRawPre,children:typeof e.output==`object`?JSON.stringify(e.output,null,2):String(e.output)})]}),!e.output&&!u&&!d&&(!e.inputFields||e.inputFields.length===0)&&(0,x.jsx)(`div`,{className:q.toolEmpty,children:`Tool forged but no output captured. The tool will be available for subsequent turns.`})]})]},t)})]}),i&&(0,x.jsx)(U_,{entry:r.getEntry(i),fallbackName:i,onClose:()=>a(null)})]})}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:q.outcomeCard,style:p,children:[(0,x.jsxs)(`div`,{className:q.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:q.outcomeLabel,children:[`DECISION #`,u]}),(0,x.jsxs)(`span`,{className:q.outcomeMeta,children:[d,` tools · `,f,` citations`]})]}),(0,x.jsx)(F_,{outcome:e})]}),(0,x.jsx)(`div`,{className:q.outcomeText,children:n}),s&&(0,x.jsx)(`div`,{className:s.departs?`${q.outcomeBar} ${q.outcomeBarDeparts}`:q.outcomeBar,children:H_(s)}),Object.keys(l).length>0&&(0,x.jsx)(`div`,{className:q.outcomeDeltas,children:Object.entries(l).map(([e,t])=>(0,x.jsxs)(`span`,{className:q.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:q.outcomeReasoningSummary,children:`Full reasoning & policies`}),(0,x.jsxs)(`div`,{className:q.outcomeReasoningBody,children:[i&&(0,x.jsx)(`div`,{className:q.outcomeReasoningPre,children:i}),n&&(0,x.jsx)(`div`,{children:n}),r&&(0,x.jsx)(`div`,{className:q.outcomeRationale,children:r}),a.map((e,t)=>(0,x.jsxs)(`div`,{className:q.outcomePolicyLine,children:[`→ `,e]},t))]})]})]})}case`personality_drift`:{let e=Object.values(c.agents||{});return e.length?(0,x.jsxs)(`div`,{className:q.driftRow,children:[(0,x.jsx)(`span`,{className:q.driftLabel,children:`DRIFT `}),e.slice(0,3).map((t,n)=>(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.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:B_[t]||`#a89878`}));return(0,x.jsxs)(`details`,{className:q.reactionsDetails,children:[(0,x.jsxs)(`summary`,{className:q.reactionsSummary,children:[(0,x.jsxs)(`span`,{className:q.reactionsLabel,style:s,children:[t,` VOICES`]}),(0,x.jsx)(`div`,{className:q.reactionsBar,children:r.map(e=>(0,x.jsx)(`div`,{className:q.reactionsBarSegment,style:{"--seg-flex":String(e.pct),"--seg-bg":e.bg},title:`${e.pct}% ${e.mood}`},e.mood))}),(0,x.jsx)(`span`,{className:q.reactionsTopMood,children:r[0]?`${r[0].pct}% ${r[0].mood}`:``})]}),(0,x.jsxs)(`div`,{className:q.reactionsBody,children:[(0,x.jsx)(`div`,{className:q.reactionsLegend,children:r.slice(0,3).map(e=>(0,x.jsxs)(`span`,{className:q.reactionsLegendItem,children:[(0,x.jsx)(`span`,{className:q.reactionsLegendSwatch,style:{"--swatch-bg":e.bg}}),e.pct,`% `,e.mood]},e.mood))}),(0,x.jsxs)(`details`,{children:[(0,x.jsxs)(`summary`,{className:q.reactionsQuotesSummary,style:s,children:[`quotes (`,e.length,`)`]}),(0,x.jsx)(`div`,{className:q.reactionsQuotesList,children:e.slice(0,4).map((t,n)=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:q.reactionTooltipName,style:s,children:t.name}),(0,x.jsxs)(`div`,{className:q.reactionTooltipMeta,children:[t.role,` in `,t.department,` `,t.age?`· Age ${t.age}`:``]}),(0,x.jsxs)(`div`,{className:q.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:q.reactionTooltipHealth,children:[`Bone: `,t.boneDensity,`% · Radiation: `,t.radiation,`mSv · Psych: `,t.psychScore]}),(0,x.jsxs)(`div`,{className:q.reactionTooltipQuote,children:[`“`,t.quote,`”`]}),(0,x.jsxs)(`div`,{className:q.reactionTooltipMoodLine,style:{"--mood-color":z_[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:q.reactionTooltipBeliefs,children:[`Beliefs: `,t.memory.beliefs.slice(0,2).join(`; `)]})]}),children:(0,x.jsxs)(`div`,{className:[q.reactionRow,n<Math.min(e.length,4)-1?q.notLast:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:q.reactionRowName,style:s,children:t.name}),(0,x.jsxs)(`span`,{className:q.reactionRowQuote,children:[`“`,String(t.quote||``),`”`]}),(0,x.jsx)(`span`,{className:q.reactionRowMoodPill,style:{"--mood-color":z_[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:q.bulletinDetails,children:[(0,x.jsxs)(`summary`,{className:q.bulletinSummary,children:[(0,x.jsxs)(`span`,{className:q.bulletinSummaryLabel,children:[e.length,` POSTS`]}),(0,x.jsxs)(`span`,{className:q.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:q.bulletinBody,children:e.slice(0,3).map((e,t)=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:q.bulletinTooltipName,style:s,children:e.name}),` `,(0,x.jsxs)(`span`,{className:q.bulletinTooltipRole,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:q.bulletinTooltipBody,children:e.post}),(0,x.jsxs)(`div`,{className:q.bulletinTooltipMood,style:{"--mood-color":z_[e.mood]||`var(--text-3)`},children:[String(e.mood||``).toUpperCase(),` · `,e.likes||0,` likes · `,e.replies||0,` replies`]})]}),children:(0,x.jsxs)(`div`,{className:q.bulletinRow,children:[(0,x.jsx)(`span`,{className:q.bulletinName,style:s,children:e.name}),(0,x.jsx)(`span`,{className:q.bulletinPost,children:String(e.post||``)}),(0,x.jsxs)(`span`,{className:q.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:q.fallbackDetails,style:s,children:[(0,x.jsxs)(`summary`,{className:q.fallbackSummary,children:[(0,x.jsxs)(`span`,{className:q.fallbackTitle,children:[`⚠ `,r?`SCHEMA SALVAGE`:`SCHEMA FALLBACK`,` — `,e]}),(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`site: `,t||`n/a`]}),r&&(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`kept without: `,i.length>0?i.join(`, `):`n/a`]})]}),n&&(0,x.jsxs)(`details`,{className:q.fallbackPreviewWrap,children:[(0,x.jsx)(`summary`,{className:q.fallbackPreviewSummary,children:`Raw output preview`}),(0,x.jsx)(`pre`,{className:q.fallbackPreviewPre,children:n})]})]})}default:return null}}function H_(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 U_({entry:e,fallbackName:t,onClose:n}){return(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Tool detail · ${e?.name||t}`,onClick:n,className:q.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:q.modalDialog,children:[(0,x.jsxs)(`div`,{className:q.modalHeader,children:[(0,x.jsxs)(`div`,{className:q.modalHeaderLeft,children:[(0,x.jsxs)(`div`,{className:q.modalKicker,children:[`FORGED TOOL [`,e?.n??`?`,`]`]}),(0,x.jsx)(`div`,{className:q.modalTitle,children:e?.name||t}),e?.description&&e.description!==e.name&&(0,x.jsx)(`div`,{className:q.modalDescription,children:e.description})]}),(0,x.jsx)(`button`,{onClick:n,"aria-label":`Close`,className:q.modalCloseBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:q.modalScroll,children:e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:q.modalPills,children:[(0,x.jsx)(W_,{label:`${e.mode}`,color:`var(--text-3)`}),(0,x.jsx)(W_,{label:e.approved?`PASS ${e.confidence.toFixed(2)}`:`RETRY`,color:e.approved?`var(--green)`:`var(--amber)`}),(0,x.jsx)(W_,{label:`first forged T${e.firstForgedTurn} · ${e.firstForgedDepartment}`,color:`var(--amber)`}),e.reuseCount>0&&(0,x.jsx)(W_,{label:`reused ${e.reuseCount}×`,color:`var(--green)`}),e.departments.size>0&&(0,x.jsx)(W_,{label:`used by ${[...e.departments].join(`, `)}`,color:`var(--teal)`})]}),e.inputSchema&&(0,x.jsx)(G_,{title:`INPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.inputSchema,null,2)})}),e.outputSchema&&(0,x.jsx)(G_,{title:`OUTPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.outputSchema,null,2)})}),!e.inputSchema&&!e.outputSchema&&(e.inputFields.length>0||e.outputFields.length>0)&&(0,x.jsx)(G_,{title:`FIELDS (DERIVED)`,children:(0,x.jsxs)(`div`,{className:q.fieldsBlock,children:[e.inputFields.length>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelIn,children:`in:`}),` `,e.inputFields.join(`, `)]}),e.outputFields.length>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelOut,children:`out:`}),` `,e.outputFields.join(`, `)]})]})}),e.history&&e.history.length>0&&(0,x.jsx)(G_,{title:`USAGE HISTORY · ${e.history.length} invocation${e.history.length===1?``:`s`}`,children:(0,x.jsx)(`ol`,{className:q.usageList,children:e.history.map((e,t)=>{let n=e.rejected?`var(--rust)`:e.isReforge?`var(--amber)`:`var(--green)`;return(0,x.jsxs)(`li`,{className:q.usageItem,style:{"--usage-accent":n},children:[(0,x.jsxs)(`div`,{className:q.usageHeader,children:[(0,x.jsxs)(`span`,{className:q.usageTurn,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:q.usageTime,children:e.time}),(0,x.jsx)(`span`,{className:q.usageDept,children:e.department}),(0,x.jsxs)(`span`,{className:q.usageEvent,children:[`· `,e.eventTitle]}),(0,x.jsxs)(`span`,{className:q.usageStatus,children:[(0,x.jsx)(`span`,{className:q.usageStatusBadge,style:{"--status-color":n},children:e.rejected?`JUDGE REJECTED`:e.isReforge?`RE-FORGE`:t===0?`FORGE`:`REUSE`}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:q.usageConf,children:[`conf `,e.confidence.toFixed(2)]})]})]}),e.output&&(0,x.jsx)(`div`,{className:q.usageOutput,children:e.output.length>200?e.output.slice(0,200)+`…`:e.output})]},t)})})}),e.sampleOutput&&(0,x.jsx)(G_,{title:`LATEST OUTPUT`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:e.sampleOutput})})]}):(0,x.jsx)(`div`,{className:q.modalEmpty,children:`Tool entry not yet in the registry — the specialist_done summary for this forge hasn't arrived yet. Try again in a moment.`})})]})})}function W_({label:e,color:t}){return(0,x.jsx)(`span`,{className:q.pill,style:{"--pill-color":t},children:e})}function G_({title:e,children:t}){return(0,x.jsxs)(`div`,{className:q.modalSection,children:[(0,x.jsx)(`div`,{className:q.modalSectionTitle,children:e}),t]})}function K_({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:q.schemaBlock,children:[(0,x.jsxs)(`span`,{className:q.schemaFieldsLabel,style:{"--field-color":t},children:[e,` FIELDS:`,` `]}),(0,x.jsx)(`span`,{className:q.schemaFieldsList,children:r.join(`, `)})]});let o=Object.entries(i).slice(0,12);return(0,x.jsxs)(`div`,{className:q.schemaBlock,children:[(0,x.jsxs)(`div`,{className:q.schemaTitle,style:{"--field-color":t},children:[e,` SCHEMA`]}),(0,x.jsx)(`table`,{className:q.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:q.schemaRow,children:[(0,x.jsxs)(`td`,{className:q.schemaKeyCell,children:[e,o&&(0,x.jsx)(`span`,{className:q.schemaRequired,children:`*`})]}),(0,x.jsx)(`td`,{className:q.schemaTypeCell,style:{"--field-color":t},children:r}),(0,x.jsx)(`td`,{className:q.schemaDescCell,children:i})]},e)})})})]})}var q_={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},J_={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},Y_={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`},X_={same:q_.same,"different-outcome":q_.differentOutcome,"different-event":q_.differentEvent,pending:q_.pending,"one-sided":q_.oneSided};function Z_({classification:e}){return(0,x.jsx)(`span`,{className:`${q_.badge} ${X_[e]}`,"aria-label":Y_[e],children:J_[e]})}var Q_={row:`_row_n6v23_1`,differentOutcome:`_differentOutcome_n6v23_9`,differentEvent:`_differentEvent_n6v23_13`,header:`_header_n6v23_17`,headerTurn:`_headerTurn_n6v23_30`,headerTitle:`_headerTitle_n6v23_36`,headerTitleSplit:`_headerTitleSplit_n6v23_45`,headerTitleA:`_headerTitleA_n6v23_52`,headerTitleB:`_headerTitleB_n6v23_61`,cells:`_cells_n6v23_70`,cell:`_cell_n6v23_70`,cellBand:`_cellBand_n6v23_82`,cellEmpty:`_cellEmpty_n6v23_92`,cellPending:`_cellPending_n6v23_99`,cellPendingSpinner:`_cellPendingSpinner_n6v23_110`},$_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function ev(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 tv({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${Q_.row} ${e.classification===`different-outcome`?Q_.differentOutcome:e.classification===`different-event`?Q_.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:Q_.header,children:[(0,x.jsxs)(`span`,{className:Q_.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(Z_,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:Q_.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:Q_.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:Q_.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:Q_.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:Q_.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!$_.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:Q_.cell,style:{"--cell-color":ve(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:Q_.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:Q_.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 ${Q_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:Q_.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:Q_.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:Q_.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:Q_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Q_.cellPendingSpinner}`}),ev(t)]}):a.map(e=>(0,x.jsx)(V_,{event:e,actorIndex:n},e.id))]},n)})})]})}function nv(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 rv(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=nv(e,t,n);r&&i.set(n,r)}return i}var iv={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function av({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)(()=>rv(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>ov(a),[a]),u=(0,b.useMemo)(()=>ov(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 ${iv.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:iv.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:iv.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(tv,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function ov(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 sv={row:`_row_bsqb3_1`,header:`_header_bsqb3_9`,headerTurn:`_headerTurn_bsqb3_22`,headerTitle:`_headerTitle_bsqb3_28`,headerTitleSplit:`_headerTitleSplit_bsqb3_37`,headerTitlePerActor:`_headerTitlePerActor_bsqb3_45`,cells:`_cells_bsqb3_53`,cell:`_cell_bsqb3_53`,cellBand:`_cellBand_bsqb3_69`,cellEmpty:`_cellEmpty_bsqb3_79`,cellPending:`_cellPending_bsqb3_87`,cellPendingSpinner:`_cellPendingSpinner_bsqb3_97`},cv=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function lv(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 uv(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 dv({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(uv),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:sv.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:sv.header,children:[(0,x.jsxs)(`span`,{className:sv.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:sv.headerTitle,children:s}):(0,x.jsx)(`span`,{className:sv.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:sv.headerTitlePerActor,style:{"--cell-color":ve(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:sv.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!cv.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:sv.cell,style:{"--cell-color":ve(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:sv.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:sv.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:sv.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 ${sv.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:sv.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:sv.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${sv.cellPendingSpinner}`}),lv(o)]}):s.map(e=>(0,x.jsx)(V_,{event:e,actorIndex:a%2},e.id))]},t)})})]})}var fv={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},pv=360;function mv({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>hv(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":`${pv}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:fv.grid,style:c,children:(0,x.jsxs)(`div`,{className:fv.scrollX,children:[(0,x.jsx)(`header`,{className:fv.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:fv.headerCell,children:(0,x.jsx)(m_,{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:fv.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:fv.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(dv,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function hv(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 gv={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 _v(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:gv.item,children:[(0,x.jsxs)(`span`,{className:gv.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:gv.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:gv.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:gv.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 vv(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function yv(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 bv({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:gv.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:gv.filterField,children:[(0,x.jsx)(`label`,{className:gv.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:gv.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:gv.filterField,children:[(0,x.jsx)(`label`,{className:gv.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:gv.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:gv.filterStats,children:[`Showing `,s,` of `,o]})]})}function xv({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)(()=>yv(e.list),[e.list]),d=(0,b.useMemo)(()=>vv(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)(bv,{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:gv.list,children:d.map(_v)}):(0,x.jsx)(`div`,{className:gv.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:gv.wrap,children:[(0,x.jsxs)(`summary`,{className:gv.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:gv.wrap,children:[(0,x.jsxs)(`h3`,{className:gv.title,children:[t,` · `,e.list.length]}),f,p]})}function Sv({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:gv.list,children:e.list.map(_v)})}var J={list:`_list_166gg_1`,item:`_item_166gg_10`,rejected:`_rejected_166gg_23`,itemNumber:`_itemNumber_166gg_27`,itemHead:`_itemHead_166gg_34`,itemName:`_itemName_166gg_42`,passPill:`_passPill_166gg_48`,failPill:`_failPill_166gg_59`,itemMode:`_itemMode_166gg_70`,logBtn:`_logBtn_166gg_76`,itemDescription:`_itemDescription_166gg_94`,metaRow:`_metaRow_166gg_99`,metaReuse:`_metaReuse_166gg_108`,metaReforge:`_metaReforge_166gg_112`,metaRejected:`_metaRejected_166gg_116`,metaInput:`_metaInput_166gg_120`,metaOutput:`_metaOutput_166gg_124`,tooltipTitle:`_tooltipTitle_166gg_128`,detailsBlock:`_detailsBlock_166gg_135`,detailsBlockTight:`_detailsBlockTight_166gg_139`,detailsSummary:`_detailsSummary_166gg_143`,pass:`_pass_166gg_48`,fail:`_fail_166gg_59`,history:`_history_166gg_159`,amber:`_amber_166gg_163`,verdictBody:`_verdictBody_166gg_167`,historyList:`_historyList_166gg_178`,historyItem:`_historyItem_166gg_187`,reforge:`_reforge_166gg_191`,historyActor:`_historyActor_166gg_195`,historyEventTitle:`_historyEventTitle_166gg_199`,codeBlock:`_codeBlock_166gg_203`,codeBlockShort:`_codeBlockShort_166gg_219`,collapsibleWrap:`_collapsibleWrap_166gg_235`,collapsibleSummary:`_collapsibleSummary_166gg_241`,title:`_title_166gg_252`,verdictWrap:`_verdictWrap_166gg_262`,verdictPassHeader:`_verdictPassHeader_166gg_266`,verdictFailHeader:`_verdictFailHeader_166gg_274`,verdictAdds:`_verdictAdds_166gg_282`,verdictAddsLabel:`_verdictAddsLabel_166gg_288`,verdictRejection:`_verdictRejection_166gg_292`,verdictMissing:`_verdictMissing_166gg_306`,verdictCost:`_verdictCost_166gg_312`,verdictCostLabel:`_verdictCostLabel_166gg_317`};function Cv({registry:e,title:t=`Forged Toolbox`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let a=sT();if(e.list.length===0)return null;let o=e=>{try{window.location.hash=`log=${encodeURIComponent(e)}`}catch{}a(`settings`)},s=(0,x.jsx)(`ol`,{className:J.list,children:e.list.map(e=>{let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `),r=wv(e.inputSchema,e.inputFields),i=wv(e.outputSchema,e.outputFields);return(0,x.jsxs)(`li`,{id:`tool-${e.n}`,className:[J.item,e.approved?``:J.rejected].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:J.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`div`,{className:J.itemHead,children:[(0,x.jsx)(`span`,{className:J.itemName,children:e.name}),(0,x.jsx)(`span`,{className:e.approved?J.passPill:J.failPill,children:e.approved?`PASS ${e.confidence.toFixed(2)}`:`FAIL`}),(0,x.jsx)(`span`,{className:J.itemMode,children:e.mode}),(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:J.tooltipTitle,children:`Open in sim log`}),(0,x.jsxs)(`div`,{children:[`Jumps to the Log tab and filters the event stream to `,(0,x.jsx)(`code`,{children:e.name}),` — showing every forge_attempt, specialist_done, and reuse event this tool fired in. Useful for tracing the exact moment a tool was created and every downstream department that reused it.`]})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o(e.name),"aria-label":`Open ${e.name} in simulation log`,className:J.logBtn,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`↗`}),`log`]})})]}),e.description&&e.description!==e.name&&(0,x.jsx)(`div`,{className:J.itemDescription,children:e.description}),(0,x.jsxs)(`div`,{className:J.metaRow,children:[(0,x.jsxs)(`span`,{children:[`first forged T`,e.firstForgedTurn,` · `,e.firstForgedDepartment]}),e.reuseCount>0&&(0,x.jsxs)(`span`,{className:J.metaReuse,children:[`reused `,e.reuseCount,`×`]}),e.reforgeCount>0&&(0,x.jsxs)(`span`,{className:J.metaReforge,children:[e.reforgeCount,` re-forge`,e.reforgeCount===1?``:`s`,e.rejectedReforges>0&&(0,x.jsxs)(`span`,{className:J.metaRejected,children:[` (`,e.rejectedReforges,` rejected)`]})]}),t&&(0,x.jsxs)(`span`,{children:[`used by `,t]}),(0,x.jsxs)(`span`,{children:[`leader `,n]}),r>0&&(0,x.jsxs)(`span`,{className:J.metaInput,children:[r,` input field`,r===1?``:`s`]}),i>0&&(0,x.jsxs)(`span`,{className:J.metaOutput,children:[i,` output field`,i===1?``:`s`]})]}),(0,x.jsxs)(`details`,{className:J.detailsBlock,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,e.approved?J.pass:J.fail].join(` `),children:e.approved?`WHY IT PASSED`:`WHY IT FAILED`}),(0,x.jsx)(`div`,{className:J.verdictBody,children:(0,x.jsx)(Tv,{entry:e})})]}),e.history.length>0&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsxs)(`summary`,{className:[J.detailsSummary,J.history].join(` `),children:[`USE HISTORY · `,e.history.length]}),(0,x.jsx)(`ol`,{className:J.historyList,children:e.history.map((e,t)=>{let n=e.rejected?J.rejected:e.isReforge?J.reforge:``;return(0,x.jsxs)(`li`,{className:[J.historyItem,n].filter(Boolean).join(` `),children:[`T`,e.turn,` · `,e.department,` · `,(0,x.jsx)(`span`,{className:J.historyActor,children:e.actorName}),` · `,t===0?`first forge`:e.isReforge?e.rejected?`re-forge rejected`:`re-forge accepted`:`reuse`,typeof e.confidence==`number`&&` · conf ${e.confidence.toFixed(2)}`,e.eventTitle&&(0,x.jsxs)(`span`,{className:J.historyEventTitle,children:[` · "`,e.eventTitle,`"`]})]},t)})})]}),!!(e.inputSchema||e.outputSchema)&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,J.amber].join(` `),children:`SCHEMA`}),(0,x.jsx)(`pre`,{className:J.codeBlock,children:JSON.stringify({input:e.inputSchema??null,output:e.outputSchema??null},null,2)})]}),e.sampleOutput&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,J.pass].join(` `),children:`LATEST OUTPUT`}),(0,x.jsx)(`pre`,{className:J.codeBlockShort,children:e.sampleOutput})]})]})]},e.n)})});return n?(0,x.jsxs)(`details`,{open:r,onToggle:i?e=>i(e.currentTarget.open):void 0,className:J.collapsibleWrap,children:[(0,x.jsxs)(`summary`,{className:J.collapsibleSummary,children:[t,` · `,e.list.length]}),s]}):(0,x.jsxs)(`div`,{className:J.collapsibleWrap,children:[(0,x.jsxs)(`h3`,{className:J.title,children:[t,` · `,e.list.length]}),s]})}function wv(e,t){return e&&typeof e==`object`&&e.properties?Object.keys(e.properties).length:t.length}function Tv({entry:e}){return e.approved?(0,x.jsxs)(`div`,{className:J.verdictWrap,children:[(0,x.jsxs)(`div`,{className:J.verdictPassHeader,children:[`✓ judge confidence `,e.confidence.toFixed(2)]}),(0,x.jsx)(`div`,{children:`The LLM judge reviewed this tool's source code, test outputs, and sandbox allowlist, and approved it across safety, correctness, determinism, and bounded execution.`}),(0,x.jsxs)(`div`,{className:J.verdictAdds,children:[(0,x.jsx)(`b`,{className:J.verdictAddsLabel,children:`What this adds to the run:`}),` `,`+0.04 outcome bonus for this event · the dept's report cites the tool's computed result · the tool is now reusable by any dept at near-zero cost (+0.02 per reuse).`]})]}):(0,x.jsxs)(`div`,{className:J.verdictWrap,children:[(0,x.jsx)(`div`,{className:J.verdictFailHeader,children:`✗ judge rejected`}),e.errorReason?(0,x.jsx)(`div`,{className:J.verdictRejection,children:e.errorReason}):(0,x.jsx)(`div`,{className:J.verdictMissing,children:`(No rejection reason captured. The judge blocked the tool before it could execute.)`}),(0,x.jsxs)(`div`,{className:J.verdictCost,children:[(0,x.jsx)(`b`,{className:J.verdictCostLabel,children:`Cost of a failed forge:`}),` `,`−0.06 outcome bonus on this event · −0.015 morale per failure (crew confidence eroded) · −1.2\xA0kW power (sandbox compute consumed) · no quantitative grounding in the dept's report · the dept retries or moves on without the insight this tool would have provided.`]})]})}var Ev={bar:`_bar_petji_1`,label:`_label_petji_13`,spacer:`_spacer_petji_22`,hint:`_hint_petji_26`,cta:`_cta_petji_51`,ctaCount:`_ctaCount_petji_74`,exportBtn:`_exportBtn_petji_83`,modalBackdrop:`_modalBackdrop_petji_96`,modalDialog:`_modalDialog_petji_107`,modalHeader:`_modalHeader_petji_123`,modalTitle:`_modalTitle_petji_132`,modalClose:`_modalClose_petji_144`,modalBody:`_modalBody_petji_154`};function Dv({citationRegistry:e,toolRegistry:t,layoutToggle:n}){let[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(()=>i(null),[]);(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 o=e.list.length,s=t.list.length;return o===0&&s===0&&!n?null:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{role:`region`,"aria-label":`Simulation evidence`,className:Ev.bar,children:[(0,x.jsx)(`span`,{className:Ev.label,children:`Evidence`}),o>0&&(0,x.jsx)(kv,{label:`References`,count:o,onClick:()=>i(`refs`),ariaLabel:`Open References list (${o} sources)`}),s>0&&(0,x.jsx)(kv,{label:`Forged Toolbox`,count:s,onClick:()=>i(`tools`),ariaLabel:`Open Forged Toolbox (${s} tools)`}),n,(0,x.jsx)(`span`,{className:Ev.spacer}),(0,x.jsx)(`span`,{className:Ev.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(Av,{title:`References · ${o}`,onClose:a,extraActions:(0,x.jsx)(Ov,{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)(Sv,{registry:e})}),r===`tools`&&(0,x.jsx)(Av,{title:`Forged Toolbox · ${s}`,onClose:a,extraActions:(0,x.jsx)(Ov,{label:`EXPORT JSON`,filename:`paracosm-toolbox.json`,data:t.list.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}))}),children:(0,x.jsx)(Cv,{registry:t,title:``,collapsible:!1})})]})}function Ov({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:Ev.exportBtn,children:e})}function kv({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:Ev.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:Ev.ctaCount,children:t})]})}function Av({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:Ev.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:Ev.modalDialog,children:[(0,x.jsxs)(`div`,{className:Ev.modalHeader,children:[(0,x.jsx)(`h2`,{className:Ev.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:Ev.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:Ev.modalBody,children:n})]})})}var jv={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function Mv({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=rT(),i=aT(),a=lT(),o=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=tg(window.localStorage);if(!e||!ng(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=cg(e,sg(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){O(window,i.visitorId),a(),rg(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&ig(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=wm(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:jv.panel,children:[(0,x.jsx)(`span`,{className:jv.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:jv.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:jv.button,onClick:o,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var Nv={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 Pv({hideWhenUnavailable:e=!0}={}){let{sessions:t,status:n,refresh:r}=kg(),i=(0,b.useRef)(null),a=(0,b.useMemo)(()=>[...t].sort((e,t)=>(t.createdAt??0)-(e.createdAt??0)).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=[Nv.card,c?Nv.empty:``].filter(Boolean).join(` `),u=[Nv.kicker,c?Nv.empty:``].filter(Boolean).join(` `),d=[Nv.lead,c?Nv.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:Nv.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:Nv.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:Nv.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:Nv.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:Nv.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:Nv.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:Nv.tile,children:[(0,x.jsx)(`span`,{className:Nv.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:Nv.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,ln(e)?`${ln(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:Nv.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Nv.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:Nv.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 Fv={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`},Iv={...Fv,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function Lv({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`?Iv:Fv,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`?Iv:Fv,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var Rv={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`},zv=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function Bv(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 zv){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 Vv(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 Hv=`Unknown`;function Uv(e){return e?e.trim():``}function Wv(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=Uv(i?.leader?.archetype),o=a||`__unknown__`,s=a||Hv,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 Gv={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 Kv({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:Gv.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:Gv.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:Gv.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${Gv.pill} ${r?Gv.pillFocused:``} ${a?Gv.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:Gv.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:Gv.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var qv=18,Jv=80,Yv=9;function Xv(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+Jv,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 Zv(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+Jv)*2}function Qv({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>Xv(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(()=>Bv(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=rT(),l=b.useMemo(()=>n.map(t=>Vv(e,t)),[n,e]),u=(0,b.useMemo)(()=>Wv(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:Rv.empty,children:`Constellation will appear when actors are launched.`});let h=Zv(n.length);return(0,x.jsxs)(`div`,{className:Rv.wrap,children:[(0,x.jsx)(Kv,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:Rv.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<Yv&&(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:Rv.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:Rv.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=ve(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:Rv.node,cx:a.cx,cy:a.cy,r:qv,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:Rv.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`?Rv.outcomeSuccess:e.latestOutcome===`failure`?Rv.outcomeFailure:Rv.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:Rv.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:Rv.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${Rv.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:Rv.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:Rv.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:Rv.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:Rv.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function $v(e){return e.length>0?e[e.length-1]:0}function ey(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:$v(t.popHistory),morale:$v(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function ty(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?ey(t,n):null}).filter(e=>e!==null)}function ny(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function ry(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 iy(e,t,n){return[...e].sort((e,r)=>ry(e,r,t,n))}var ay={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`},oy=[{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 sy(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function cy({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(ny(e)),e))},[]),s=(0,b.useMemo)(()=>ty(e),[e]),c=(0,b.useMemo)(()=>iy(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:ay.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:ay.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:ay.scroll,children:(0,x.jsxs)(`table`,{className:ay.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:ay.colorCell}),oy.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":sy(t,i),className:`${ay.th} ${e.numeric?ay.numeric:``} ${t?ay.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:ay.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:ay.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?ve(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${ay.row} ${t?ay.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:ay.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:ay.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:ay.nameCell,children:[(0,x.jsx)(`span`,{className:ay.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:ay.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:ay.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:ay.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.population}),(0,x.jsx)(`td`,{className:ay.numCell,children:(0,x.jsxs)(`span`,{className:ay.moraleWrap,children:[(0,x.jsx)(`span`,{className:ay.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:ay.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:ay.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.tools})]},n.id)})})]})})})}function ly(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 uy(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:ly(r,.25),median:ly(r,.5),q3:ly(r,.75),max:r[r.length-1]})}return i}var dy=e=>e.popHistory,fy=e=>e.moraleHistory;function py(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 my(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 hy={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`},gy=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:fy,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:dy}],_y=360,vy=90,yy=8,by=6;function xy({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:hy.empty,role:`status`,children:`No turns recorded yet.`});let r=t??my(e),i=e.map(e=>py(e,r.lo,r.hi)),a=t=>e.length===1?180:yy+t/(e.length-1)*344,o=e=>by+(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:hy.chart,viewBox:`0 0 ${_y} ${vy}`,width:_y,height:vy,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:hy.envelope,d:s}),(0,x.jsx)(`path`,{className:hy.iqr,d:c}),(0,x.jsx)(`path`,{className:hy.median,d:l})]})}function Sy({state:e}){let t=(0,b.useMemo)(()=>gy.map(t=>({def:t,bands:uy(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:hy.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:hy.heading,children:[(0,x.jsx)(`span`,{className:hy.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:hy.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:hy.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:hy.chartWrap,children:[(0,x.jsxs)(`div`,{className:hy.chartHeader,children:[(0,x.jsx)(`span`,{className:hy.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:hy.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)(xy,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var Cy={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 wy(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function Ty({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=ht(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?Cy.dockOverlay:Cy.overlay,p=d?Cy.dock:Cy.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:Cy.head,children:[(0,x.jsx)(`div`,{className:Cy.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:Cy.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:Cy.body,children:[(0,x.jsx)(m_,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:Cy.section,children:[(0,x.jsxs)(`h3`,{className:Cy.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:Cy.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:Cy.decisionItem,children:[(0,x.jsxs)(`div`,{className:Cy.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:Cy.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:Cy.section,children:[(0,x.jsxs)(`h3`,{className:Cy.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:Cy.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:Cy.turnArticle,children:[(0,x.jsxs)(`header`,{className:Cy.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:Cy.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:Cy.turnEvent,children:[(0,x.jsx)(`span`,{className:Cy.turnEventType,children:e.type}),` `,wy(e)]},e.id))})]},e))]})]})]})})}var Ey={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 Dy({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:Ey.introBar,children:[(0,x.jsxs)(`div`,{className:Ey.introBody,children:[(0,x.jsx)(`b`,{className:Ey.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 V8 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:Ey.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:Ey.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function Oy({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,launching:a,interventionArtifact:o,interventionRunning:s,interventionState:c=e,onInterventionDismiss:l,forceLayout:u}){let d=rT(),f=aT();if(o)return(0,x.jsx)(`div`,{className:Ey.root,children:(0,x.jsx)(`div`,{className:Ey.scrollableBody,children:(0,x.jsx)(t_,{artifact:o,state:c,onDismiss:l})})});if(s)return(0,x.jsx)(`div`,{className:Ey.root,children:(0,x.jsx)(`div`,{className:Ey.scrollableBody,children:(0,x.jsx)(s_,{state:c,subject:s.subject,intervention:s.intervention})})});let p=bg(),m=wg(),[h,g]=(0,b.useState)(!1),_=a??h,[v,y]=(0,b.useState)(`side-by-side`),S=(0,b.useRef)(!1),C=(0,b.useCallback)(e=>{S.current=!0,y(e)},[]);(0,b.useEffect)(()=>{S.current||e.actorIds.length>50&&v!==`constellation`&&y(`constellation`)},[e.actorIds.length,v]);let w=u??v,[T,ee]=(0,b.useState)(null),E=T?e.actorIds.indexOf(T):0,D=e.actorIds[0],O=e.actorIds[1],te=D?e.actors[D]:null,k=O?e.actors[O]:null,ne=Object.values(e.actors).some(e=>e.events.length>0),re=e.isRunning&&!ne;(0,b.useEffect)(()=>{(ne||e.isRunning)&&a===void 0&&g(!1)},[ne,e.isRunning,a]);let A=(0,b.useCallback)(()=>{a===void 0&&g(!0),n?.()},[n,a]),j=d.presets.find(e=>e.id==="default"),ie=j?.leaders??j?.actors,ae=(0,b.useMemo)(()=>typeof window>`u`?null:og(window.localStorage),[]),M=ie?.[0]??ae?.[0],oe=ie?.[1]??ae?.[1],N=M?.name?{name:M.name,archetype:M.archetype??``,unit:M.unit??ue(d,0),hexaco:M.hexaco??{},instructions:M.instructions??``,quote:``}:null,se=oe?.name?{name:oe.name,archetype:oe.archetype??``,unit:oe.unit??ue(d,1),hexaco:oe.hexaco??{},instructions:oe.instructions??``,quote:``}:null,[ce,le]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),de=()=>{le(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},fe=te?.event,pe=fe?`T${fe.turn} \u2014 ${fe.time}: ${fe.title}`:``,me=(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]),he=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,ge=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(Ey.flashOn),window.setTimeout(()=>e.classList.remove(Ey.flashOn),1200))},[]),P=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),F=e.isRunning||e.isComplete||ne||t===`connected`;return(0,x.jsxs)(`div`,{className:Ey.root,children:[(0,x.jsxs)(`div`,{className:Ey.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(tn,{verdict:i}):null,w===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Qv,{state:e,onActorClick:e=>ee(e)}),(0,x.jsx)(Sy,{state:e}),(0,x.jsx)(cy,{state:e,onActorClick:e=>ee(e)})]}):e.actorIds.length>=3?(0,x.jsx)(E_,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:pe,toolRegistry:m}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${Ey.leadersRow}`,children:[(0,x.jsx)(m_,{actorIndex:0,leader:te?.leader||N,popHistory:te?.popHistory||[],moraleHistory:te?.moraleHistory||[],verdictPlacement:me(`A`),event:te?.event,statuses:te?.statuses,pendingDecision:te?.pendingDecision}),(0,x.jsx)(m_,{actorIndex:1,leader:k?.leader||se,popHistory:k?.popHistory||[],moraleHistory:k?.moraleHistory||[],verdictPlacement:me(`B`),event:k?.event,statuses:k?.statuses,pendingDecision:k?.pendingDecision})]}),(0,x.jsx)(E_,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:pe,toolRegistry:m})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:Ey.progressBar,children:[(0,x.jsxs)(`span`,{className:Ey.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:Ey.progressTrack,children:(0,x.jsx)(`div`,{className:Ey.progressFill,style:{width:`${he}%`}})}),(0,x.jsxs)(`span`,{className:Ey.progressPercent,children:[Math.round(he),`%`]})]}),ce&&(te?.events.length??0)>0&&(0,x.jsx)(Dy,{onDismiss:de}),re&&!ne&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),_&&!ne&&!e.isRunning&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!ne&&!e.isComplete&&!_&&t===`connecting`&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!ne&&t===`connected`&&!_&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!ne&&t===`connected`&&!_&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:Ey.centerState,children:[(0,x.jsx)(`div`,{className:Ey.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:Ey.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:Ey.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:A,disabled:_||!f,className:Ey.buttonRun,children:_?`Launching…`:f?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:ge,className:Ey.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:P,className:Ey.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:Ey.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:Ey.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:Ey.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${Ey.replayCtaWrap} ${Ey.flashCard}`,children:(0,x.jsx)(Pv,{})})]}),F&&w===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)(av,{state:e}),F&&w===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(mv,{state:e}),(0,x.jsx)(N_,{state:e})]}),(0,x.jsx)(Dv,{citationRegistry:p,toolRegistry:m,layoutToggle:(0,x.jsx)(Lv,{layout:w,actorCount:e.actorIds.length,onChange:C})}),(0,x.jsx)(Mv,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(Ty,{actorName:T,actorIndex:E>=0?E:0,state:e,onClose:()=>ee(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function ky(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 Ay({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=ky(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 jy={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 My(){return(0,x.jsxs)(`div`,{className:jy.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:jy.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:jy.body,children:[(0,x.jsx)(`div`,{className:jy.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:jy.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:jy.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:jy.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:jy.link,children:`Trait-model cookbook`})]})]})]})}var Ny={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`},Py=[{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`}],Fy=[{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 Iy({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:Ny.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:Ny.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Ny.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:Ny.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:Ny.input})]}),(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:Ny.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:Ny.input})]}),(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:Ny.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:Ny.input})]})]}),(0,x.jsxs)(`div`,{className:Ny.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:Ny.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:Ny.textarea})]}),(0,x.jsx)(My,{}),(0,x.jsxs)(`div`,{className:Ny.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:Ny.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${Ny.presetSelect}`,onChange:e=>{let t=Fy.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...`}),Fy.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Ny.hexacoGrid}`,children:Py.map(e=>(0,x.jsx)(Ay,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function Ly(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}var Ry={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},zy={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},By={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`},Vy={card:`_card_1vcu2_1`,header:`_header_1vcu2_10`,title:`_title_1vcu2_20`,lead:`_lead_1vcu2_28`,btnRow:`_btnRow_1vcu2_34`,btn:`_btn_1vcu2_34`,amber:`_amber_1vcu2_53`,fileInput:`_fileInput_1vcu2_58`,editorWrap:`_editorWrap_1vcu2_62`,editor:`_editor_1vcu2_62`,statusBar:`_statusBar_1vcu2_83`,seedDetails:`_seedDetails_1vcu2_93`,seedSummary:`_seedSummary_1vcu2_97`,seedBody:`_seedBody_1vcu2_105`,input:`_input_1vcu2_112`,textarea:`_textarea_1vcu2_123`,checkboxLabel:`_checkboxLabel_1vcu2_136`,fineprint:`_fineprint_1vcu2_144`,progressWrap:`_progressWrap_1vcu2_151`,progressRow:`_progressRow_1vcu2_157`,progressStatus:`_progressStatus_1vcu2_166`,result:`_result_1vcu2_170`,actions:`_actions_1vcu2_178`,actionBtn:`_actionBtn_1vcu2_186`,primary:`_primary_1vcu2_203`,spacer:`_spacer_1vcu2_214`,memCount:`_memCount_1vcu2_218`},Hy={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:[]},Uy=`paracosm:editorCompileResult`;function Wy(){try{let e=window.sessionStorage.getItem(Uy);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 Gy(){let[e,t]=(0,b.useState)({adminWrite:!1,memoryScenarios:[]}),[n,r]=(0,b.useState)(``),[i,a]=(0,b.useState)(``),[o,s]=(0,b.useState)(``),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(`5`),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``),[v,y]=(0,b.useState)(!1),[S,C]=(0,b.useState)(!1),[w,T]=(0,b.useState)([]),[D,O]=(0,b.useState)(()=>Wy()),te=(0,b.useRef)(null),k=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t).catch(()=>{});try{window.sessionStorage.removeItem(Uy)}catch{}},[]);let ne=(0,b.useCallback)(()=>{fetch(`/scenario`).then(e=>e.ok?e.json():null).then(e=>{e?.id&&r(JSON.stringify(e,null,2))}).catch(()=>{})},[]);(0,b.useEffect)(()=>(ne(),E(window,ne)),[ne]),(0,b.useEffect)(()=>{if(!n.trim())a(``);else try{JSON.parse(n),a(``)}catch(e){a(String(e).replace(`SyntaxError: `,``))}},[n]);let A=()=>r(JSON.stringify(Hy,null,2)),j=(0,b.useCallback)(async()=>{try{let e=await(await fetch(`/scenario`)).json();r(JSON.stringify(e,null,2)),O({success:!0,message:`Loaded active scenario: ${e.labels?.name||e.id}`})}catch(e){O({success:!1,message:`Failed to load: ${e}`})}},[]),ie=()=>te.current?.click(),ae=e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result;r(e);try{JSON.parse(e),O({success:!0,message:`Imported ${t.name} (${(t.size/1024).toFixed(1)}KB)`})}catch{O({success:!1,message:`Imported ${t.name} but JSON is invalid`})}},n.readAsText(t),e.target.value=``},M=()=>{if(n.trim())try{let e=JSON.parse(n),t=e.id||`scenario`,r=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=`${t}.json`,a.click(),URL.revokeObjectURL(i),O({success:!0,message:`Exported ${t}.json`})}catch{O({success:!1,message:`Fix JSON errors before exporting`})}},oe=(0,b.useCallback)(async()=>{if(n.trim()&&!i){C(!0);try{let e=JSON.parse(n),r=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!1})})).json();r.stored?(ee(window),O({success:!0,message:r.switchable?`Stored "${r.id}" in memory and added it to the scenario selector.`:`Stored "${r.id}" as draft JSON in memory. Compile it to make it runnable and switchable.`}),t(e=>({...e,memoryScenarios:[...new Set([...e.memoryScenarios,r.id])]}))):O({success:!1,message:r.error||`Store failed`})}catch(e){O({success:!1,message:String(e)})}C(!1)}},[n,i]),N=(0,b.useCallback)(async()=>{if(n.trim()&&!i&&e.adminWrite)try{let e=JSON.parse(n),t=``;try{t=localStorage.getItem(`paracosm:adminToken`)??``}catch{}let r={"Content-Type":`application/json`};t&&(r[`X-Admin-Token`]=t);let i=await fetch(`/scenario/store`,{method:`POST`,headers:r,body:JSON.stringify({scenario:e,saveToDisk:!0})}),a=await i.json();a.savedToDisk?(ee(window),O({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.`})):O({success:!1,message:a.error||`Disk write refused (HTTP ${i.status})`})}catch(e){O({success:!1,message:String(e)})}},[n,i,e.adminWrite]),se=(0,b.useCallback)(async()=>{if(!n.trim()||i)return;let e;try{e=JSON.parse(n)}catch{O({success:!1,message:`Fix JSON errors before compiling`});return}y(!0),T([]),O(null);try{let t=Ly({scenario:e,seedText:o,seedUrl:c,webSearch:u,maxSearches:f,provider:m,model:g}),n=(await fetch(`/compile`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).body?.getReader();if(!n)throw Error(`No response stream`);let r=new TextDecoder,i=``;for(;;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.split(`
|
|
123
|
-
`);
|
|
124
|
-
`).length,le=new Blob([n]).size;return(0,x.jsxs)(`div`,{className:Vy.card,children:[(0,x.jsxs)(`div`,{className:Vy.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:Vy.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:Vy.lead,children:[`Write or import a scenario JSON draft. Add seed text or a URL to ground it, then compile or export.`,!e.adminWrite&&` Disk saves are disabled on this instance.`]})]}),(0,x.jsxs)(`div`,{className:Vy.btnRow,children:[(0,x.jsx)(`button`,{onClick:j,className:[Vy.btn,Vy.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:A,className:Vy.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:ie,className:Vy.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:M,className:Vy.btn,disabled:!n.trim()||!!i,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:te,type:`file`,accept:`.json,application/json`,onChange:ae,className:Vy.fileInput})]})]}),(0,x.jsxs)(`div`,{className:Vy.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:k,value:n,onChange:e=>r(e.target.value),placeholder:`{\\n "id": "my-scenario",\\n "labels": { "name": "My World" },\\n "departments": [...]\\n}`,spellCheck:!1,"aria-label":`Scenario JSON editor`,className:Vy.editor}),(0,x.jsxs)(`div`,{className:Vy.statusBar,style:{"--status-color":i?`var(--rust)`:`var(--text-3)`},children:[(0,x.jsx)(`span`,{children:i||(n.trim()?`Valid JSON`:`Empty`)}),(0,x.jsxs)(`span`,{children:[ce,` lines, `,(le/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:Vy.seedDetails,children:[(0,x.jsx)(`summary`,{className:Vy.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:Vy.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Ry,children:`Seed Text`}),(0,x.jsx)(`textarea`,{value:o,onChange:e=>s(e.target.value),placeholder:`Paste a prompt, notes, a brief, or source text to turn into research facts and category mapping.`,className:Vy.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Ry,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:`https://example.com/article`,className:Vy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Ry,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),inputMode:`numeric`,placeholder:`5`,className:Vy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Ry,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),placeholder:`anthropic or openai (optional)`,className:Vy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Ry,children:`Compile Model Override`}),(0,x.jsx)(`input`,{value:g,onChange:e=>_(e.target.value),placeholder:`gpt-5.4-mini, claude-sonnet-4-6, etc. (optional)`,className:Vy.input})]}),(0,x.jsxs)(`label`,{className:Vy.checkboxLabel,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked)}),`Web search enrichment (requires Serper/Tavily/Firecrawl API keys)`]}),(0,x.jsx)(`p`,{className:Vy.fineprint,children:`If both seed text and a seed URL are provided, the URL takes precedence and the compiler ingests the fetched page.`})]})]}),w.length>0&&(0,x.jsx)(`div`,{className:Vy.progressWrap,children:w.map(e=>(0,x.jsxs)(`div`,{className:Vy.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:Vy.progressStatus,children:e.status})]},e.hook))}),D&&(0,x.jsx)(`div`,{className:Vy.result,style:{"--result-color":D.success?`var(--green)`:`var(--rust)`,"--result-bg":D.success?`rgba(106,173,72,.06)`:`rgba(224,101,48,.06)`},children:D.message}),(0,x.jsxs)(`div`,{className:Vy.actions,children:[(0,x.jsx)(`button`,{onClick:oe,disabled:!n.trim()||!!i||S,className:Vy.actionBtn,"aria-label":`Store scenario in memory`,children:S?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:se,disabled:!n.trim()||!!i||v,className:[Vy.actionBtn,Vy.primary].join(` `),"aria-label":`Compile scenario`,children:v?`Compiling...`:`Compile Scenario`}),e.adminWrite&&(0,x.jsx)(`button`,{onClick:N,disabled:!n.trim()||!!i,className:[Vy.actionBtn,Vy.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:Vy.spacer}),e.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:Vy.memCount,children:[e.memoryScenarios.length,` in memory`]})]})]})}function Ky(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``}}function qy(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=Jy(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!Xy(e,o)||n&&!Yy(e,n))})}function Jy(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Yy(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 Xy(e,t){let n=e.data??{},r=typeof n.name==`string`?n.name.toLowerCase():``;if(r&&r.includes(t))return!0;let i=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let e of i){let n=e&&typeof e==`object`&&typeof e.name==`string`?e.name.toLowerCase():``;if(n&&n.includes(t))return!0}return!1}function Zy(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=Jy(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function Qy(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}`:``}function $y(e,t){let n=Ky(),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).match(/(?:^|&)log=([^&]+)/);if(l)try{n.toolHash=decodeURIComponent(l[1])}catch{n.toolHash=l[1]}return n}var eb={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 tb(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function nb({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>Zy(e),[e]),i=tb(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:eb.bar,children:[(0,x.jsxs)(`div`,{className:eb.topRow,children:[(0,x.jsxs)(`div`,{className:eb.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:eb.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:eb.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:eb.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:eb.chipClear,onClick:()=>a({toolHash:``}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:eb.resetButton,disabled:!i,onClick:()=>n(Ky()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:eb.facetsRow,children:[(0,x.jsx)(`span`,{className:eb.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:eb.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[eb.checkbox,t?eb.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:eb.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:eb.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:eb.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:eb.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:eb.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:eb.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:eb.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:eb.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:eb.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var rb={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`},ib={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 ab(){return typeof window>`u`?$y(``,``):$y(window.location.search,window.location.hash)}function ob({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(ab);(0,b.useEffect)(()=>{let e=()=>i(ab());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=Qy(e),r=window.location.pathname,i=t.toolHash!==``&&e.toolHash===``?``:window.location.hash,a=r+n+(i||``);window.history.replaceState({},``,a)}catch{}return e})},[]),s=qy(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 ${rb.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:rb.header,children:(0,x.jsxs)(`h2`,{className:rb.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(nb,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:rb.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=ib[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:rb.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:rb.eventSummary,children:[(0,x.jsx)(`span`,{className:rb.index,children:t}),(0,x.jsx)(`span`,{className:rb.type,children:e.type}),(0,x.jsx)(`span`,{className:rb.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:rb.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:rb.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:rb.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:rb.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:rb.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var sb=[{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 cb(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`},lb=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],ub={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},db={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)`}]},fb={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`}},pb={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.`}},mb=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function hb(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:mb[e]??`The Strategist`,unit:ue(t,e),instructions:``,hexaco:{...ub}}}function gb(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function _b(e,t,n,r,i){let a=gb(n);return e.map((e,o)=>{let s=i[o],c=a?.[o],l=e.unit===ue(t,o);if(!c)return(a!==void 0&&r!==n.id||l)&&s?.unit===void 0?{...e,unit:ue(n,o)}:e;let u=r===n.id&&!!e.unit&&!l;return{name:c.name,archetype:c.archetype,unit:u?e.unit:c.unit??ue(n,o),instructions:c.instructions,hexaco:{...c.hexaco},...s}})}var vb=2,yb=8;function bb({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),Cm(e===`config`?null:e)},[]),a=rT(),o=aT(),s=om(),c=sT(),l=lT(),u=typeof window<`u`?og(window.localStorage):null,[d]=(0,b.useState)(()=>typeof window<`u`?ag(window.localStorage):null),[f,p]=(0,b.useState)(()=>{let e=Math.max(vb,Math.min(yb,Math.max(gb(a)?.length??0,u?.length??0)));return _b(Array.from({length:e},(e,t)=>{let n=u?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??ue(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??ub}}:hb(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=>_b(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<yb?[...e,hb(e.length,a)]:e)},[a]),v=(0,b.useCallback)(e=>{m.current.splice(e,1),p(t=>t.length>vb?t.filter((t,n)=>n!==e):t)},[]),[y,S]=(0,b.useState)(a.setup.defaultTurns),[C,w]=(0,b.useState)(a.setup.defaultSeed),[T,ee]=(0,b.useState)(a.setup.defaultStartTime),[D,te]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[k,ne]=(0,b.useState)(a.setup.defaultPopulation),A=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=A.current;e.has(`turns`)||S(a.setup.defaultTurns),e.has(`seed`)||w(a.setup.defaultSeed),e.has(`startTime`)||ee(a.setup.defaultStartTime),e.has(`timePerTurn`)||te(a.setup.defaultTimePerTurn||0),e.has(`population`)||ne(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[j,ie]=(0,b.useState)(`openai`),[ae,M]=(0,b.useState)(!1),[oe,N]=(0,b.useState)(`balanced`),[se,ce]=(0,b.useState)(!1),[le,de]=(0,b.useState)(``),[fe,pe]=(0,b.useState)([]),[me,he]=(0,b.useState)(a.id),[ge,P]=(0,b.useState)({}),[F,_e]=(0,b.useState)(!1),[ye,be]=(0,b.useState)(`local_demo`),[xe,Se]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[I,Ce]=(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(I))}catch{}},[I]);let[we,Te]=(0,b.useState)(fb[j]??fb.openai);(0,b.useEffect)(()=>{let e=j;fb[e]&&Te(fb[e])},[j]);let Ee=!!I.openai||!!I.anthropic,De=!!ge.openai||!!ge.anthropic,Oe=Ee||!F&&De,ke=Ee||!F&&De,Ae=F&&!Ee?`economy`:oe,je=cb(ye),Me=F&&!Ee,Ne=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{pe(e.scenarios||[]),he(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(Ne(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&P(e.keys),typeof e.hostedDemo==`boolean`&&_e(e.hostedDemo),typeof e.serverMode==`string`&&be(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&Se({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),E(window,Ne)),[Ne]);let Pe=async e=>{if(e!==me)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(re(),window.location.reload())}catch{}},Fe=(0,b.useCallback)(async()=>{if(o){ce(!0),de(`Starting...`);try{let e={actors:f.map(e=>({...e,hexaco:e.hexaco})),provider:j,turns:y,seed:C,startTime:T,timePerTurn:D||void 0,population:k,liveSearch:ae,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:Ae},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}ig(window.localStorage,f,a.id),I.openai&&(e.apiKey=I.openai),I.anthropic&&(e.anthropicKey=I.anthropic),I.serper&&(e.serperKey=I.serper),I.firecrawl&&(e.firecrawlKey=I.firecrawl),I.tavily&&(e.tavilyKey=I.tavily),I.cohere&&(e.cohereKey=I.cohere),ke&&(e.models={...we});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){de(`Rate limited: ${n.error||`too many simulations`}`),ce(!1);return}if(n.redirect){l(),de(`Running...`),O(window,n.visitorId);let e=bm(wm(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else de(`Error: ${n.error||`unknown`}`),ce(!1)}catch(e){de(`Failed: ${e}`),ce(!1)}}},[f,y,C,T,D,k,j,ae,c,l,a,o,I,we,ke,Ae]),Ie=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(gm,{options:lb,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(ob,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(Pv,{}),fe.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:Ry,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:me,onChange:e=>Pe(e.target.value),children:fe.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===me?`● `:``,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:me})]})]}),(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:je.label}),`. `,je.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)(Iy,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:ve(t),data:e,onChange:e=>g(t,e)}),f.length>vb&&(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<yb?(0,x.jsxs)(`button`,{type:`button`,onClick:_,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,f.length,`/`,yb,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,yb,` 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:zy,className:Y.legend,children:`Simulation`}),Me&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,xe.maxTurns,`, population to `,xe.maxPopulation,`, active departments to `,xe.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:Ry,children:[`Turns`,Me&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${xe.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,xe.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:Me?xe.maxTurns:y,onChange:e=>{A.current.add(`turns`),S(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:Me,className:Ie(Me),title:Me?`Locked at ${xe.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:Ry,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:D,onChange:e=>{A.current.add(`timePerTurn`),te(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:Ry,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:C,onChange:e=>{A.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:Ry,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:T,onChange:e=>{A.current.add(`startTime`),ee(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:Ry,children:[`Population`,Me&&(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:Me?30:k,onChange:e=>{A.current.add(`population`),ne(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:Me,className:Ie(Me),title:Me?`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.jsx)(`label`,{htmlFor:`provider-select`,style:Ry,children:`Provider`}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Y.input}`,value:j,onChange:e=>ie(e.target.value),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:Ry,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(ae),onChange:e=>M(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:Ry,children:[`Economics`,Me&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Ie(Me)}`,value:Ae,onChange:e=>N(e.target.value),disabled:Me,title:sb.find(e=>e.value===Ae)?.description,children:sb.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:sb.find(e=>e.value===Ae)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:zy,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:Ry,children:[t,ge[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:I[e],onChange:t=>Ce(n=>({...n,[e]:t.target.value})),placeholder:ge[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),Oe&&(j===`openai`||j===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:zy,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(pb).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:Ry,children:pb[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:we[e],onChange:t=>Te(n=>({...n,[e]:t.target.value})),children:db[j].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:pb[e].help})]},e))})]}),!Oe&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,F?`Runs against the host API keys are capped to ${xe.maxTurns} turns, ${xe.maxPopulation} colonists, ${xe.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.`]}),(0,x.jsx)(Gy,{}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Fe,disabled:se||!o,"aria-label":se?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:se?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),le&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:le})]})]})]})}function xb(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 Sb(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:xb(e.hexaco),instructions:e.instructions})),...t]}var Cb={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function wb(e,t,n,r){let i=Math.max(0,t-e)*Cb[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function Tb(e){let t=[];for(let n of e.split(`
|
|
125
|
-
`)){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
|
|
126
|
-
Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:jb.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:jb.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:jb.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:jb.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()?Tb(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:jb.confirmButton,children:`Fork`})]})]})})}var Nb=`/retry-stats`;function Pb(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(Nb,{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`},Fb={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 Ib(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function Lb(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Rb(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function zb(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function Bb({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=ht(!0),c=Pb(!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:Ib(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,Lb(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 ${Ib(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${Ib(-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 (`,Lb(t),` reused / `,Lb(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,Lb(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,Lb(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=Fb[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:Lb(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:Ib(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=Rb(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=Rb(t.avgAttempts),r=zb(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:Lb(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:Lb(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:Ib(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:Ib(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,Lb(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:Ib(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,Lb(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:Ib(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,Lb(n.totalTokens),` tok`]})]})]})]})]})})}var Vb={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`},Hb=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],Ub={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},Wb={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function Gb(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function Kb(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 qb({events:e,actorName:t,baselineHexaco:n}){let r=Gb(n),i=Kb(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:Vb.card,children:[(0,x.jsxs)(`div`,{className:Vb.headerRow,children:[(0,x.jsx)(`span`,{className:Vb.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:Vb.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`}),Hb.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:Ub[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:Vb.legend,children:Hb.map(e=>(0,x.jsxs)(`span`,{className:Vb.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Vb.legendSwatch,style:{"--trait-color":Ub[e]}}),(0,x.jsx)(`span`,{className:Vb.legendLabel,children:Wb[e]}),(0,x.jsx)(`span`,{className:Vb.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var Jb={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},Yb={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},Xb=[`crisis`,`departments`,`decision`,`outcome`],Zb=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function Qb(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function $b(e){return e!==`quotes`}function ex(e){let t=[];for(let n of e??[])Qb(n)&&!t.includes(n)&&t.push(n);return t}function tx(e){let t=ex(e.configuredSections),n=t.length>0?t:Xb,r=n.filter($b);for(let t of Zb)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 nx={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`},rx=[{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 ix(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function ax({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:nx.bar,children:[(0,x.jsx)(`div`,{className:nx.barLeftWrap,children:(0,x.jsx)(`div`,{className:nx.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:nx.barRightWrap,children:(0,x.jsx)(`div`,{className:nx.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function ox(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=Wt(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:Gt(e),a:e.a,b:e.b,text:t=>Kt(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=>ix(e??0,`int`)}]:rx.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>ix(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:nx.section,children:[(0,x.jsxs)(`div`,{className:nx.header,children:[(0,x.jsx)(`div`,{className:nx.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:nx.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:nx.headline,children:r}),i&&(0,x.jsx)(`div`,{className:nx.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:nx.body,children:[(0,x.jsxs)(`div`,{className:nx.bodyHeader,children:[(0,x.jsx)(`span`,{className:nx.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:nx.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Jt(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:nx.statRow,children:[(0,x.jsxs)(`div`,{className:nx.statRowHead,children:[(0,x.jsx)(`span`,{className:nx.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:nx.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:nx.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(ax,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:nx.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:nx.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:nx.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var sx={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function cx(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 lx(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 ux(e,t,n){let r=n??sx[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>lx(e,t))].sort((e,t)=>e-t),a=cx(i,.25),o=cx(i,.75),s=cx(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=lx(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 dx(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=lx(e,n),i=lx(t,n);return sx[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=lx(e,n),i=lx(t,n);return sx[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 fx(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=cx([...e.map(e=>lx(e,t))].sort((e,t)=>e-t),.5),r={},i=sx[t]===`higher`?1:-1;for(let a of e){let e=(lx(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function px(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var mx={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`},hx=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],gx=[`morale`,`population`,`deaths`,`tools`],_x=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function vx({state:e}){let t=(0,b.useMemo)(()=>ty(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>hx.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:ux(t,e)})),[t]),r=(0,b.useMemo)(()=>dx(t,gx),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>_x.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:fx(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:mx.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:mx.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:mx.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:mx.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:mx.section,children:[(0,x.jsx)(`h4`,{className:mx.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:mx.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:mx.quartileBlock,children:[(0,x.jsxs)(`div`,{className:mx.metricHead,children:[(0,x.jsx)(`span`,{className:mx.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:mx.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:mx.quartileRow,children:[(0,x.jsx)(`span`,{className:mx.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:mx.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${mx.actorPill} ${mx.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:mx.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:mx.quartileRow,children:[(0,x.jsx)(`span`,{className:mx.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:mx.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${mx.actorPill} ${mx.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:mx.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:mx.section,children:[(0,x.jsx)(`h4`,{className:mx.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:mx.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:mx.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:mx.paretoItem,children:[(0,x.jsx)(`span`,{className:mx.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:mx.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:mx.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:mx.section,children:[(0,x.jsx)(`h4`,{className:mx.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:mx.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:mx.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:mx.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:mx.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:mx.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:mx.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:mx.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:mx.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:mx.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?mx.deltaPositive:n<0?mx.deltaNegative:mx.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${mx.medianMetricCol} ${r}`,role:`cell`,children:[px(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function yx(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 bx(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var xx=[{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 Sx(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 Cx(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 xx.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?Sx(a,e.id):[],b:o?Sx(o,e.id):[]}))}function wx(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 xx.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?Sx(t.events,e.id):[]}))}))}function Tx(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:bx(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}}})}function Ex(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 Dx=`(max-width: 768px)`,Ox=`(max-width: 480px)`,kx=`(prefers-reduced-motion: reduce)`,Ax={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`},jx={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},Mx={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function Nx(e,t=!1){return e?t?Mx[e]??`·`:jx[e]??e.replace(/_/g,` `).toUpperCase():`·`}function Px({outcome:e,sideColor:t,compact:n}){let r=yx(e);return(0,x.jsx)(`div`,{className:Ax.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:Nx(e,n)})}function Fx(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=Ex(Ox);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:Ax.section,children:[(0,x.jsx)(`div`,{className:Ax.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:Ax.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:[Ax.cell,e.diverged?Ax.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Ax.cellHead,children:[(0,x.jsxs)(`span`,{className:Ax.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(Px,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(Px,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:Ax.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var Ix={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 Lx(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 Rx(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 zx({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:Ix.card,children:[(0,x.jsxs)(`div`,{className:Ix.cardHeader,children:[(0,x.jsx)(`span`,{className:Ix.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:Ix.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:Ix.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=Rx(n);return(0,x.jsxs)(`span`,{className:Ix.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:Ix.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:Lx(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:Ix.card,children:[(0,x.jsxs)(`div`,{className:Ix.cardHeader,children:[(0,x.jsx)(`span`,{className:Ix.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:Ix.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:Ix.cardFooter,children:[(0,x.jsx)(`span`,{className:Ix.lastA,children:h==null?`·`:Lx(h,e.unit)}),(0,x.jsx)(`span`,{className:Ix.lastB,children:g==null?`·`:Lx(g,e.unit)})]})]})}function Bx(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:Ix.section,style:c,children:[(0,x.jsxs)(`div`,{className:Ix.sectionHeader,children:[(0,x.jsx)(`span`,{className:Ix.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:Ix.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:Ix.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:Ix.legendCohortSlot,"aria-hidden":`true`,children:Rx(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:Ix.legend,children:[(0,x.jsx)(`span`,{className:Ix.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:Ix.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Ix.grid}`,children:s.map(e=>(0,x.jsx)(zx,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function Vx(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 Hx(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=Vx(`(min-width: 1024px)`,!0),o=Vx(`(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 Ux(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 Wx(){return{events:new Map,reactions:[],totalReactions:0}}function Gx(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 Kx(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=Wx(),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=Gx(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=Gx(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=Gx(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=Gx(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 qx(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function Jx({state:e,verdict:t,reportSections:n}){let r=bg(),i=wg(),[a,o]=Ux(`paracosm-reports-refs-open`,!1),[s,c]=Ux(`paracosm-reports-tools-open`,!1),[l,u]=(0,b.useState)(!1),{state:d,dispatch:f}=gn(),p=sT(),m=lT(),h=om(),[g,_]=(0,b.useState)(null),v=d.parent,y=rT(),S=aT(),C=v?.metadata?.scenario,w=typeof C?.id==`string`&&C.id!==y.id,T=(0,b.useCallback)(t=>!v||e.isRunning||!S||w?!1:Ab(v,t),[v,e.isRunning,S,w]),ee=(0,b.useCallback)(async e=>{_(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;f({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=kb(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:Db(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));f({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));O(window,a.visitorId),m(),p(`studio`)}catch(e){f({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[f,p,m]),E=e.actorIds[0]??null,D=e.actorIds[1]??null,[te,k]=(0,b.useState)(E),[ne,re]=(0,b.useState)(D);(0,b.useEffect)(()=>{te&&!e.actorIds.includes(te)&&k(E),ne&&!e.actorIds.includes(ne)&&re(D)},[e.actorIds,te,ne,E,D]);let A=te??E,j=ne??D,ie=e.actorIds.length>2,[ae,M]=(0,b.useState)(!ie);(0,b.useEffect)(()=>{M(!ie)},[ie]);let oe=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,Kx(e.actors[n]?.events));return t},[e]),N=(0,b.useMemo)(()=>{let e=A&&oe.get(A)||new Map,t=j&&oe.get(j)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??Wx(),b:t.get(n)??Wx()}])},[oe,A,j]),se=(0,b.useMemo)(()=>{if(!ie)return[];let t=new Set;for(let e of oe.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,oe.get(r)?.get(t)??Wx());return[t,n]})},[ie,oe,e.actorIds]),ce=A,le=j,ue=ce?e.actors[ce]:null,de=le?e.actors[le]:null,fe=ue?.leader?.name||`Leader A`,pe=de?.leader?.name||`Leader B`,me=(ue?.events.some(e=>e.type===`personality_drift`)??!1)||(de?.events.some(e=>e.type===`personality_drift`)??!1),he=N.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),ge=N.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),P=(0,b.useMemo)(()=>tx({configuredSections:n,hasQuotes:he,hasCausality:ge,hasVerdict:!!t,hasTrajectories:me,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:i.list.length>0,hasReferences:r.list.length>0}),[n,he,ge,t,me,e.cost,i.list.length,r.list.length]),F=(0,b.useMemo)(()=>Tx(N),[N]),_e=(0,b.useMemo)(()=>Cx(e,A,j),[e,A,j]),ye=(0,b.useMemo)(()=>ie?wx(e,ve):null,[ie,e]),be=(0,b.useMemo)(()=>{let e=[];F.length>0&&e.push({id:`strip`,label:`Strip`}),_e.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),me&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of N)e.push({id:`turn-${t}`,label:`Turn ${t}`});return i.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),r.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,F.length,_e,me,N,i.list.length,r.list.length]),xe=(0,b.useRef)(null),Se=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{Se.current&&xe.current&&N.length>0&&xe.current.scrollTo({top:xe.current.scrollHeight,behavior:`smooth`})},[N.length]),!(ue?.events.length??0)&&!(de?.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:xe,onScroll:()=>{let e=xe.current;e&&(Se.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[S&&w&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,C?.name??C?.id,`, and a fork runs in its parent's scenario. Switch to `,C?.name??C?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&N.length===0)return null;let i=N.length,a=N[N.length-1],o=N[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=ue?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=de?.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":qx(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`})]}),ie&&(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:ae,onChange:e=>M(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),ae?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:A??``,onChange:e=>k(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===j,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:j??``,onChange:e=>re(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===A,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.`]})]}),(!ie||ae)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(Fx,{turns:F,leaderAName:fe,leaderBName:pe})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!ie||ae?(0,x.jsx)(Bx,{metrics:_e,leaderAName:fe,leaderBName:pe}):ye&&(0,x.jsx)(Bx,{metrics:ye,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[me&&ae&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(qb,{events:ue?.events??[],actorName:fe,baselineHexaco:ue?.leader?.hexaco}),(0,x.jsx)(qb,{events:de?.events??[],actorName:pe,baselineHexaco:de?.leader?.hexaco})]}),me&&!ae&&(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)(qb,{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:()=>u(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),l&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(Bb,{combined:e.cost,leaderA:(ce?e.costByActor[ce]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(le?e.costByActor[le]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ue?.leader?.name,leaderBName:de?.leader?.name,actors:ie?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:()=>u(!1)}),!ie&&N.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`}),T(e)&&(0,x.jsxs)(`button`,{type:`button`,className:jb.forkButton,onClick:()=>_(e),"aria-label":`Fork at ${h.time} ${e}`,children:[`↳ Fork at `,h.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)(Xx,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:fe,sideColor:`var(--vis)`,sections:P.eventSections}),(0,x.jsx)(Xx,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:pe,sideColor:`var(--eng)`,sections:P.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(Zx,{data:n,name:fe,sideColor:`var(--vis)`,showQuotes:P.footerSections.includes(`quotes`)}),(0,x.jsx)(Zx,{data:r,name:pe,sideColor:`var(--eng)`,showQuotes:P.footerSections.includes(`quotes`)})]})]},e)}),ie&&se.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`}),T(t)&&(0,x.jsxs)(`button`,{type:`button`,className:jb.forkButton,onClick:()=>_(t),"aria-label":`Fork at ${h.time} ${t}`,children:[`↳ Fork at `,h.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)(Xx,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:P.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)(Zx,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:P.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:i.list.length>0&&(0,x.jsx)(Cv,{registry:i,title:`Forged Toolbox`,collapsible:!0,defaultOpen:s,onToggle:c})}),(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)(ox,{verdict:t,leaderAName:fe,leaderBName:pe}),(0,x.jsx)(vx,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(tn,{verdict:t})})]}),(0,x.jsx)(`section`,{id:`references`,children:r.list.length>0&&(0,x.jsx)(xv,{registry:r,title:`References`,collapsible:!0,defaultOpen:a,onToggle:o})}),(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:P.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:Jb[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:P.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:Yb[e]},e))})]})]})]})]}),(0,x.jsx)(Hx,{items:be,scrollRoot:xe.current}),g!==null&&v&&(0,x.jsx)(Mb,{parentArtifact:v,atTurn:g,maxTurns:kb(v),costPreset:`economy`,provider:`openai`,onConfirm:ee,onClose:()=>_(null)})]})}var Yx={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Xx({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)(F_,{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)(L_,{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 Zx({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":Yx[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`},Qx={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function $x(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function eS({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":$x(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 tS({state:e,onChatUsage:t}){let n=rT(),[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 ee=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),E=ee.find(e=>e.name===r),D=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},O=e=>{let t=D(e);return t?`${t}\u0000${e}`:e},te=r?a.get(O(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[te,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&ee.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[ee]);let k=e=>{i(e);let t=O(e);o(n=>{if(n.has(t))return n;let r=ee.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})},ne=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},re=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},A=async()=>{if(!l.trim()||!r||d)return;let e=r,n=D(e),i=O(e),a=l.trim();u(``),f(!0),ne(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];re(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){ne(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),re(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ne(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ne(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:ee.length?`${ee.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:ee.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)})]})]}),ee.map(e=>(0,x.jsxs)(`button`,{onClick:()=>k(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":Qx[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[E?.memory&&(E.memory.beliefs?.length>0||E.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),E.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),E.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&&E?.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=E.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 E.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(E.psychScore*100).toFixed(0),`%`]}),typeof E.boneDensity==`number`&&E.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,E.boneDensity.toFixed(0),`%`]}),typeof E.radiation==`number`&&E.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,E.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":E?.name?`Messages with ${E.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:ee.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:ee.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&&E?.memory&&(0,x.jsx)(eS,{memory:E.memory,events:e,scenario:n}),te.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":`${E?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:E?.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`&&A(),disabled:!r||d,"aria-label":r?`Message ${E?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${E?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:A,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_hm7af_2`,kbdKey:`_kbdKey_hm7af_8`,kbdLabel:`_kbdLabel_hm7af_18`,empty:`_empty_hm7af_22`,emptySpinner:`_emptySpinner_hm7af_34`,emptySpinnerRotate:`_emptySpinnerRotate_hm7af_1`,root:`_root_hm7af_54`,toolbarStrip:`_toolbarStrip_hm7af_62`,toolbarTopRow:`_toolbarTopRow_hm7af_71`,modePillsWrap:`_modePillsWrap_hm7af_78`,overflowToggle:`_overflowToggle_hm7af_83`,overflowToggleOpen:`_overflowToggleOpen_hm7af_97`,helpBtn:`_helpBtn_hm7af_102`,toolsRow:`_toolsRow_hm7af_118`,paletteBtn:`_paletteBtn_hm7af_127`,toolBtn:`_toolBtn_hm7af_141`,settingsBtn:`_settingsBtn_hm7af_154`,settingsBtnOpen:`_settingsBtnOpen_hm7af_167`,modeHint:`_modeHint_hm7af_172`,diffLine:`_diffLine_hm7af_180`,phoneTabRow:`_phoneTabRow_hm7af_189`,phoneTab:`_phoneTab_hm7af_189`,phoneTabActive:`_phoneTabActive_hm7af_216`,leadersRow:`_leadersRow_hm7af_222`,leadersRowNarrow:`_leadersRowNarrow_hm7af_231`,sideWrap:`_sideWrap_hm7af_236`,sideWrapHidden:`_sideWrapHidden_hm7af_243`,footerKeys:`_footerKeys_hm7af_247`,srOnly:`_srOnly_hm7af_260`,jumpLatest:`_jumpLatest_hm7af_272`,"paracosm-jump-pulse":`_paracosm-jump-pulse_hm7af_1`,jumpLatestBehind:`_jumpLatestBehind_hm7af_295`,toast:`_toast_hm7af_300`,"paracosm-toast-in":`_paracosm-toast-in_hm7af_1`,toastKicker:`_toastKicker_hm7af_321`,toastKickerMeta:`_toastKickerMeta_hm7af_333`,toastBody:`_toastBody_hm7af_337`,toastBodyMd:`_toastBodyMd_hm7af_342`,vignette:`_vignette_hm7af_347`,"paracosm-vignette":`_paracosm-vignette_hm7af_1`,cohortViewBar:`_cohortViewBar_hm7af_363`,cohortViewModeToggle:`_cohortViewModeToggle_hm7af_374`,cohortViewModeButton:`_cohortViewModeButton_hm7af_383`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_hm7af_414`,cohortPairPicker:`_cohortPairPicker_hm7af_423`,cohortPairPickerLabel:`_cohortPairPickerLabel_hm7af_431`,cohortPairPickerSelect:`_cohortPairPickerSelect_hm7af_440`,cohortPairPickerVs:`_cohortPairPickerVs_hm7af_463`,cohortPairPickerHint:`_cohortPairPickerHint_hm7af_471`};function nS(e){return(0,b.useMemo)(()=>{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)}}for(let e=0;e<r.agentSnapshots.length;e++){let a=r.agentSnapshots[e],o=r.events.find(t=>t.type===`systems_snapshot`&&t.data?.turn===e+1)?.data||{},s=o.turn||e+1,c=a.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:s,time:o.time||0,cells:c,population:o.population||c.filter(e=>e.alive).length,morale:o.morale||0,foodReserve:typeof o.foodReserve==`number`?o.foodReserve:void 0,deaths:o.deaths||0,births:o.births||0,eventCategories:i.get(s)??[]})}}return t},[e])}var rS={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 iS(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 aS(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 oS(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 sS(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function cS(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 lS(e,t,n){let r=cS(t,n,sS(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=iS(aS(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,oS(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function uS(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=iS(aS(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,oS(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=iS(aS(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,oS(o,c,t,n))}),r}function dS(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=iS(aS(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,oS(s,c,t,n))}return i}function fS(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=iS(aS(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,oS(o,s,t,n))}return r}function pS(e,t,n,r){return t===`families`?uS(e,n,r):t===`mood`?dS(e,n,r):t===`age`?fS(e,n,r):lS(e,n,r)}function mS(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 hS={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)`},gS=6;function _S(e,t){e.save();for(let n of t){let t=hS[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<gS;t++){let r=t/gS*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 vS={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 yS(e){return vS[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function bS(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=yS(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=yS(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 xS(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,wS(i,d)),f.addColorStop(.6,wS(i,d*.4)),f.addColorStop(1,wS(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=wS(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 SS(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=t,s=a(o.foodReserve),c=a(o.waterLitersPerDay),l=a(o.powerKw),u=a(o.pressurizedVolumeM3);if(s==null&&c==null&&l==null&&u==null)return;let d=(e,t,n)=>e==null?0:e<=t?1:e>=n?0:1-(e-t)/(n-t),f=d(s,3,18),p=d(c,200,1200),m=d(l,150,600),h=d(u,1500,4e3),g=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})`,_=n/2,v=r/2;e.save(),e.fillStyle=g(f),e.fillRect(0,0,_,v),e.fillStyle=g(p),e.fillRect(_,0,_,v),e.fillStyle=g(m),e.fillRect(0,v,_,v),e.fillStyle=g(h),e.fillRect(_,v,_,v),e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,s!=null&&e.fillText(`FOOD ${s.toFixed(1)}mo`,8,8),c!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(c)}L/d`,n-8,8)),l!=null&&(e.textAlign=`left`,e.textBaseline=`bottom`,e.fillText(`POWER ${Math.round(l)}kW`,8,r-8)),u!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(u)}m³`,n-8,r-8)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function CS(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 wS(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 TS(){return{items:[]}}function ES(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function DS(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 OS(e){return e.items}function kS(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 AS=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function jS(e,t,n,r){let i=(0,b.useRef)(TS()),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=Ex(kx);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}=kS(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&ES(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&&ES(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(!AS.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),ES(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&&ES(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&&ES(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,DS(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:OS(i.current),tickClock:o}}function MS(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 NS={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function PS(e){return NS[(e||``).toLowerCase()]??`#a89878`}function FS({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:PS(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 IS={"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 V8 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.`},LS={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 RS({snapshot:e,sideColor:t}){let n=Ex(Dx),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:[LS.strip,n?LS.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[LS.col,LS.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:LS.rowBaseline,children:[(0,x.jsx)(`span`,{className:LS.label,title:IS[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:LS.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:LS.bar,children:(0,x.jsx)(`div`,{className:LS.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:LS.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:LS.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:LS.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:LS.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:LS.col,children:[(0,x.jsxs)(`div`,{className:LS.moodHeader,children:[(0,x.jsx)(`span`,{className:LS.label,title:IS[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:LS.value2,title:IS[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:LS.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:LS.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:LS.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:LS.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:LS.col,children:[(0,x.jsx)(`div`,{className:LS.label,title:IS[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:LS.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:LS.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:LS.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:LS.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:[LS.col,LS.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:LS.row,children:[(0,x.jsx)(`span`,{className:LS.label,title:IS[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:LS.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:LS.row,children:[(0,x.jsx)(`span`,{title:IS[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:LS.value2,children:d})]}),(0,x.jsxs)(`div`,{className:LS.row,children:[(0,x.jsx)(`span`,{title:IS[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:LS.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:LS.deptBlock,"aria-label":`Department breakdown`,title:IS[`stat.depts`],children:[(0,x.jsx)(FS,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:LS.deptLabel,children:`Depts`})]})]})}var zS={cols:12,rows:6,seedRadius:2},BS=[[1,0],[2,1],[0,2],[1,2],[2,2]],VS=[[0,1],[1,1],[2,1]],HS=[[0,0],[1,0],[0,1],[1,1]],US=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],WS=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],GS=[[1,0],[2,0],[0,1],[1,1],[1,2]];function KS(e){switch(e){case`positive`:case`hopeful`:return HS;case`neutral`:return US;case`anxious`:return VS;case`resigned`:return WS;case`defiant`:case`negative`:return BS;default:return VS}}function qS(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 JS(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 YS(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 XS(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 ZS(e){switch(e){case`birth`:return HS;case`forge`:return BS;case`crisis`:return GS;case`death`:return[];default:return null}}function QS(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function $S(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=ZS(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??KS(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 eC(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=HS;break;case`forge_approved`:l=BS;break;case`forge_rejected`:l=VS;break;case`reuse`:l=WS;break;case`crisis`:l=GS;break;default:l=VS}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 tC(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 nC(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 rC(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 iC=[`O`,`C`,`E`,`A`,`Em`,`HH`];function aC(e,t){let n=t/2,r=t/2,i=t/2-8;return iC.map((t,a)=>{let o=Math.PI*2*a/iC.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 oC(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/iC.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function sC({profile:e,colonyMean:t,size:n=160}){let r=aC(e,n),i=t?aC(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)),iC.map((e,t)=>{let r=oC(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 cC={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`},lC={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function uC(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])=>`${lC[e]} ${t.toFixed(2)}`).join(` · `)}function dC(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=Ex(Ox);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:cC.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:cC.popover,style:C,children:[(0,x.jsxs)(`div`,{className:cC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:cC.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:cC.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:cC.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:cC.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:cC.section,children:(0,x.jsxs)(`div`,{className:cC.statsGrid,children:[(0,x.jsx)(`span`,{className:cC.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:cC.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:cC.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:cC.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:cC.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:cC.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:cC.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:cC.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:cC.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:cC.statValue,children:y}),(0,x.jsx)(`span`,{className:cC.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:cC.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:cC.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:cC.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:cC.section,children:[(0,x.jsx)(`div`,{className:cC.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:cC.hexacoRow,children:[(0,x.jsx)(`div`,{className:cC.hexacoRadarWrap,children:(0,x.jsx)(sC,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:cC.hexacoTopAxes,children:uC(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:cC.section,children:[(0,x.jsx)(`div`,{className:cC.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:cC.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:cC.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:cC.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:cC.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var fC={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`},pC={animSpeed:1,deptRings:!1,deptLabels:!1,lines:!1,dust:!0,crosshair:!0,ghostTrail:!1,alerts:!0,sound:!1};function mC({open:e,settings:t,onChange:n,onClose:r}){let i=ht(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:fC.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:fC.drawer,children:[(0,x.jsxs)(`div`,{className:fC.header,children:[(0,x.jsx)(`span`,{style:zy,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:fC.closeBtn,children:`×`})]}),(0,x.jsx)(hC,{label:`Animation speed`,children:[.5,1,2].map(e=>(0,x.jsx)(gC,{active:t.animSpeed===e,onClick:()=>a(`animSpeed`,e),label:`${e}x`},e))}),(0,x.jsxs)(hC,{label:`Dept rings`,children:[(0,x.jsx)(gC,{active:t.deptRings,onClick:()=>a(`deptRings`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.deptRings,onClick:()=>a(`deptRings`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Dept labels`,children:[(0,x.jsx)(gC,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Family lines`,children:[(0,x.jsx)(gC,{active:t.lines,onClick:()=>a(`lines`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.lines,onClick:()=>a(`lines`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Star dust bg`,children:[(0,x.jsx)(gC,{active:t.dust,onClick:()=>a(`dust`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.dust,onClick:()=>a(`dust`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Crosshair`,children:[(0,x.jsx)(gC,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Ghost trail`,children:[(0,x.jsx)(gC,{active:t.ghostTrail,onClick:()=>a(`ghostTrail`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.ghostTrail,onClick:()=>a(`ghostTrail`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Alert toasts`,children:[(0,x.jsx)(gC,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(hC,{label:`Sound cues`,children:[(0,x.jsx)(gC,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(gC,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(pC),style:By,className:fC.resetBtn,children:`Reset defaults`})]})]})}function hC({label:e,children:t}){return(0,x.jsxs)(`div`,{className:fC.row,children:[(0,x.jsx)(`span`,{style:Ry,className:fC.rowLabel,children:e}),(0,x.jsx)(`div`,{className:fC.pillRow,children:t})]})}function gC({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[fC.pill,e?fC.pillActive:``].filter(Boolean).join(` `),children:n})}var _C={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`},vC={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)`},yC=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function bC({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=om(),{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:_C.drawer,children:[(0,x.jsxs)(`div`,{className:_C.header,style:v,children:[(0,x.jsxs)(`span`,{className:_C.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:_C.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:_C.sortRow,children:yC.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[_C.sortChip,t?_C.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:_C.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:_C.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:_C.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:_C.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:_C.swatch,style:{"--swatch-bg":vC[e.mood]??vC.neutral}}),(0,x.jsx)(`span`,{className:_C.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:_C.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:_C.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:[_C.row,_C.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:_C.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:_C.rowName,children:e.name})]},e.agentId)})]})]})]})}function xC({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 SC(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 CC(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=pC,focusedSide:T=null,onToggleFocus:ee,onOpenChat:E,eventFilter:D=`all`,chronicleHover:O=null,isLiveRun:te=!0}=e,k=T===c,ne=Ex(Dx),re=Ex(kx),A=om(),j=(0,b.useRef)(null),ie=(0,b.useRef)(null),ae=(0,b.useRef)(null),[M,oe]=(0,b.useState)({w:0,h:0}),[N,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,pe]=(0,b.useState)(!1),[me,he]=(0,b.useState)(null),[ge,P]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(re){P(!0);return}let e=requestAnimationFrame(()=>P(!0));return()=>cancelAnimationFrame(e)},[re]);let F=(0,b.useRef)(QS(zS.cols,zS.rows)),_e=(0,b.useRef)(-1),ve=(0,b.useRef)(``),ye=(0,b.useRef)(``),be=(0,b.useRef)(null),xe=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=ie.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(1,Math.round(t.contentRect.width)),n=Math.max(1,Math.round(t.contentRect.height));oe(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ae.current;if(!e||M.w===0||M.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(M.w*t),e.height=Math.round(M.h*t),e.style.width=`${M.w}px`,e.style.height=`${M.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[M.w,M.h]);let Se=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),I=(0,b.useMemo)(()=>!t||M.w===0?new Map:pS(t.cells,Se,M.w,M.h),[t,Se,M.w,M.h]),Ce=(0,b.useMemo)(()=>t?MS(t.cells,I):new Map,[t,I]),we=jS({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},ie,()=>I,()=>Ce),Te=f===`forge`?.7:f===`ecology`?0:1,Ee=(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=ae.current;if(!e||!t)return;let r=e.getContext(`2d`);if(!r)return;let c=we.flares.filter(e=>D===`all`?!0:D===`birth`?e.kind===`birth`:D===`death`?e.kind===`death`:D===`crisis`?e.kind===`crisis`:D!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=SC(s,j.current),d=j.current?getComputedStyle(j.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)`,ee=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,M.w,M.h);let E=F.current,O=f!==ve.current,k=t.turn!==_e.current,ne=D!==ye.current;if(k||O||ne){_e.current=t.turn,ve.current=f,ye.current=D,$S(E,t.cells,I,M.w,M.h,D);let e;e=re?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)tC(E);be.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!==be.current&&(be.current=e,eC(E,c[0],M.w,M.h),re||tC(E))}let ie=typeof document<`u`&&document.documentElement.classList.contains(`light`);if(te&&nC(r,E,M.w,M.h,u,ie?.22:.65),D===`death`?JS(r,t.cells,I,M.w,M.h,zS.cols,zS.rows,C,T):D===`birth`&&qS(r,t.cells,I,M.w,M.h,zS.cols,zS.rows),_S(r,c),f!==`ecology`&&mS(r,t.cells,I,u,Te,_,f===`divergence`,re?0:performance.now(),S,!0,g,te?m:`transparent`),f===`forge`&&h&&h.length>0&&xS(r,t.cells,I,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&SS(r,t,M.w,M.h,ee),f===`divergence`&&CS(r,t.cells,I,_,re?0:performance.now(),u),bS(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:M.w,height:M.h,lagTurns:l,cells:t.cells,positions:I,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:A.Time}),N){let e=I.get(N.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(ce&&!N&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,ce.y),r.lineTo(M.w,ce.y),r.moveTo(ce.x,0),r.lineTo(ce.x,M.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=I.get(n.agentId);if(!t)continue;let r=t.x-ce.x,i=t.y-ce.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(ce.x,ce.y),r.lineTo(ce.x+e.dx,ce.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]}`,ce.x+6,ce.y+6),r.restore())}if(v&&v!==N?.cell.agentId){let e=I.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())}},[we.tickClock,t,I,M.w,M.h,s,i,l,we.flares,f,Te,N,_,v,re,S,ce,w,a,o,h,D,te]);let De=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;le({x:r,y:i});let a=rC(t.cells,I,r,i);if(a){se(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),he(null),y?.(a.agentId);return}N&&(se(null),y?.(null));let o=zS.cols,s=zS.rows,c=D===`death`||D===`birth`?(()=>{let e=Math.floor(r/Math.max(1,M.w)*o),n=Math.floor(i/Math.max(1,M.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(D===`death`&&r.alive||D===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=I.get(r.agentId);if(!t)continue;let i=XS(t,M.w,M.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:D===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=YS(F.current,r,i,M.w,M.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=I.get(r.agentId);if(!t)continue;let i=XS(t,M.w,M.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?he({x:r,y:i,...c}):me&&he(null)},[t,I,N,y,D,M.w,M.h,me]),Oe=(0,b.useCallback)(()=>{se(null),he(null),le(null),y?.(null)},[y]),ke=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=rC(t.cells,I,r,i);a?(de({cell:a,x:r,y:i}),se(null),he(null),xe.current={id:a.agentId,intensity:1}):me?.nearest&&(de({cell:me.nearest,x:r,y:i}),se(null),he(null))},[t,I,me]),Ae=(0,b.useRef)(null),je=(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=rC(t.cells,I,i,a);o?Ae.current===o.agentId?(de({cell:o,x:i,y:a}),se(null),Ae.current=null,xe.current={id:o.agentId,intensity:1}):(se({cell:o,x:i,y:a}),le({x:i,y:a}),Ae.current=o.agentId,y?.(o.agentId)):(se(null),le(null),Ae.current=null,y?.(null))},[t,I,y]);(0,b.useEffect)(()=>{ue&&t&&(t.cells.find(e=>e.agentId===ue.cell.agentId)||de(null))},[ue,t]),(0,b.useEffect)(()=>{ue||(Ae.current=null)},[ue]);let Me=SC(f===`mood`?Ee:s,j.current),Ne={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)`},Pe={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)`},Fe=O&&O.side===c?Ne[O.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`,Ie=O&&O.side===c?`0 0 24px ${Pe[O.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:j,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${A.place} viz`,className:[rS.region,ne?rS.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(RS,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:ie,className:rS.canvasWrap,style:{"--tint-color":te?Me:`transparent`,"--wrap-border":Fe,"--wrap-glow":Ie},children:[(0,x.jsx)(`canvas`,{ref:ae,role:`img`,"aria-label":t?`${i} ${A.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${typeof t.foodReserve==`number`?`, food reserve ${t.foodReserve.toFixed(1)} months`:``}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${A.person} glyph for drilldown.`:`${i} ${A.place} — waiting for first turn.`,onMouseMove:De,onMouseLeave:Oe,onClick:ke,onTouchStart:je,className:rS.canvas,style:{"--canvas-cursor":N?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:rS.revealCover,style:{"--reveal-opacity":ge?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>pe(e=>!e),"aria-label":fe?`Close roster`:`Open roster`,title:fe?`Close roster`:`Open roster`,className:rS.cornerBtn,style:{"--right-offset":ee?`36px`:`8px`,"--btn-color":fe?`var(--amber)`:`var(--text-3)`,"--btn-border":fe?`var(--amber)`:`var(--border)`},children:`☰`}),ee&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>ee(c),"aria-label":k?`Restore split view`:`Focus this panel`,title:k?`Restore split view`:`Focus this panel`,className:`${rS.cornerBtn} ${rS.focusBtn}`,style:{"--btn-color":k?`var(--amber)`:`var(--text-3)`,"--btn-border":k?`var(--amber)`:`var(--border)`},children:k?`⤡`:`⤢`}),(0,x.jsx)(xC,{snapshot:t,previousSnapshot:n,sideColor:SC(s,j.current),onSelect:e=>{let t=I.get(e.agentId);t&&de({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(bC,{open:fe,cells:t?.cells??[],actorName:i,sideColor:SC(s,j.current),searchQuery:S,hoveredId:N?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?I.get(e):null;if(n&&r){se({cell:n,x:r.x,y:r.y}),y?.(e);return}}se(null),y?.(null)},onSelect:e=>{let t=I.get(e.agentId);t&&de({cell:e,x:t.x,y:t.y})},onClose:()=>pe(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:rS.divergenceEmpty,children:(0,x.jsx)(`div`,{className:rS.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),me&&!N&&!ue&&(()=>{let e=Math.min(Math.max(8,me.x+12),Math.max(8,M.w-220-8)),t=Math.max(8,me.y-84),n=me.kind===`birth`?`+ BIRTH MARKER`:me.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=me.kind===`birth`?`rgba(154, 205, 96, 0.95)`:me.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:rS.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:rS.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:rS.tileCoords,children:[`tile (`,me.col,`, `,me.row,`)`]}),me.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:rS.tileNearestName,children:me.nearest.name}),(0,x.jsxs)(`div`,{className:rS.tileNearestRole,children:[me.nearest.role,` · `,me.nearest.department.toUpperCase()]}),me.kind===`death`?(0,x.jsxs)(`div`,{className:rS.tileNearestDeath,children:[`deceased · mood at death: `,me.nearest.mood]}):me.kind===`birth`?(0,x.jsxs)(`div`,{className:rS.tileNearestBirth,children:[`native-born · generation `,me.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:rS.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,me.nearest.mood]})]}):(0,x.jsx)(`div`,{className:rS.tileAmbient,children:`ambient CA cell`}),me.kind===`life`&&(()=>{let e=F.current,t=e.cols,n=e.rows,r=e.grid[me.row*t+me.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=me.row+r,s=me.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:rS.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),N&&!ue&&(()=>{let e=Math.min(Math.max(8,N.x+12),Math.max(8,M.w-200-8)),t=Math.min(Math.max(8,N.y-80-8),Math.max(8,M.h-80-8));return(0,x.jsxs)(`div`,{className:rS.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:rS.hoverHeader,children:[N.cell.name,N.cell.featured&&(0,x.jsx)(`span`,{className:rS.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:rS.hoverRole,children:[N.cell.department.toUpperCase(),` · `,N.cell.role,typeof N.cell.age==`number`?` · age ${N.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:rS.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:rS.hoverMoodValue,children:N.cell.mood}),typeof N.cell.psychScore==`number`?` · psych ${Math.round(N.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===N.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:rS.psychBlock,children:[(0,x.jsx)(`div`,{className:rS.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:rS.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:rS.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(dC,{payload:ue,containerW:M.w,containerH:M.h,sideColor:SC(s,j.current),hexacoById:p,snapshots:r,onClose:()=>de(null),onOpenChat:E})]})]})}var wC={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 TC(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 EC(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=typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`),g=(0,b.useRef)(null),[_,v]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(_)return;let e=g.current;if(!e)return;if(typeof IntersectionObserver>`u`){v(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){v(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[_]);let y=r.actors[n]??null,S=y?.leader??null,C=i[a],w=a>0?i[a-1]:void 0,T=ve(t),ee=S?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>y?TC(y.events):{attempts:[],reuses:[]},[y]),D=S?.hexaco?{O:S.hexaco.O??S.hexaco.openness??.5,C:S.hexaco.C??S.hexaco.conscientiousness??.5,E:S.hexaco.E??S.hexaco.extraversion??.5,A:S.hexaco.A??S.hexaco.agreeableness??.5,Em:S.hexaco.Em??S.hexaco.emotionality??.5,HH:S.hexaco.HH??S.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:g,className:wC.column,style:{"--actor-color":T},"aria-label":`Living swarm grid for actor ${t+1}: ${ee}`,children:[(0,x.jsxs)(`header`,{className:wC.columnHeader,children:[(0,x.jsxs)(`span`,{className:wC.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:wC.columnHeaderText,children:[(0,x.jsx)(`span`,{className:wC.columnHeaderName,children:ee}),S?.archetype&&(0,x.jsx)(`span`,{className:wC.columnHeaderArchetype,children:S.archetype})]}),(0,x.jsxs)(`span`,{className:wC.columnHeaderPop,title:`Population alive · morale`,children:[C?.population??`—`,` · `,C?Math.round(C.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:wC.columnBody,children:_?(0,x.jsx)(CC,{snapshot:C,isLiveRun:r.isRunning&&!h,previousSnapshot:w,snapshotHistory:i,actorName:ee,actorArchetype:S?.archetype??``,leaderUnit:S?.unit??``,sideColor:T,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:wC.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:wC.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:wC.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function DC({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:wC.track,role:`region`,"aria-label":`Cohort swarm grid: ${f.length} actors`,children:(0,x.jsx)(`div`,{className:wC.trackInner,children:f.map((f,p)=>(0,x.jsx)(EC,{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 OC(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+$/,``);return`${o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`}${e.deaths>0&&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 kC={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 AC(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=0,o=null,s=0,c=``,l=``,u=0;for(let n of e.events)(n.data?.turn??-1)===t+1&&((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===`decision_made`&&(r=String(n.data?.decision??r)),n.type===`outcome`&&(i=String(n.data?.outcome??i),a=Number(n.data?.deaths??a),o=n.data?.dominantCause??o,s=Number(n.data?.moraleDelta??s)));return{actorName:n,decision:r,outcome:i,deaths:a,dominantCause:o,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}var jC=6;function MC({state:e,currentTurn:t}){let n=e.actorIds.length>2,[r,i]=(0,b.useState)(n),a=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?AC(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),o=a.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,s=a.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,c=a.find(e=>e.summary.time)?.summary.time||0;if(!o)return null;let l=a.slice(0,jC),u=a.length-l.length,d=!r,f=a.length>0;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:kC.banner,children:[(0,x.jsxs)(`div`,{className:kC.headline,children:[(0,x.jsxs)(`span`,{className:kC.turnLabel,children:[`T`,t+1,c?` \u00b7 ${c}`:``]}),(0,x.jsx)(`span`,{className:kC.title,children:o}),s&&(0,x.jsx)(`span`,{className:kC.categoryPill,children:s}),f&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":!r,"aria-label":r?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:kC.collapseBtn,children:r?`\u25be ${a.length} actors`:`▴ hide`})]}),d&&l.map((e,t)=>(0,x.jsxs)(`div`,{className:a.length<=2?t===0?kC.lineA:kC.lineB:kC.line,children:[(0,x.jsx)(`span`,{className:kC.lineLabel,children:a.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:kC.lineBody,children:[`: `,OC(e.summary)]})]},e.actorId)),d&&u>0&&(0,x.jsxs)(`div`,{className:kC.lineMore,children:[`+`,u,` more \\u00b7 see cohort grid below for the rest`]})]})}var NC=[.5,1,2,4];function PC({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:NC.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var FC=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + family lines + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths / partner arcs`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; metrics strip + crisis shockwaves lead`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function IC(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 LC(e,t){return IC(FC.find(t=>t.key===e)?.hint??``,t)}function RC({mode:e,onChange:t,counts:n,labels:r}){return Ex(`(max-width: 480px)`)?(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:IC(FC.find(t=>t.key===e)?.hint??``,r),style:{width:`100%`,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:FC.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)})}):(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:FC.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=IC(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===FC.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 zC={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 BC({open:e,onClose:t}){let n=Ex(Ox),r=om();if(!e)return null;let i=[zC.dialog,n?zC.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:zC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:zC.header,children:[(0,x.jsxs)(`h2`,{className:zC.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:zC.closeBtn,children:`×`})]}),(0,x.jsxs)(VC,{title:`Modes`,children:[(0,x.jsx)(HC,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + family lines + event flares`}),(0,x.jsx)(HC,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(HC,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(HC,{k:`ECOLOGY`,v:`Hides glyphs; metrics strip + crisis flares lead`}),(0,x.jsx)(HC,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(VC,{title:`Grid elements`,children:[(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(HC,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(HC,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(HC,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(HC,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(VC,{title:`Event flares`,children:[(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(HC,{k:(0,x.jsx)(UC,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(VC,{title:`Family lines`,children:[(0,x.jsx)(HC,{k:`— side color, bowed`,v:`Partner link`}),(0,x.jsx)(HC,{k:`– teal, dashed`,v:`Parent → child link`})]}),(0,x.jsxs)(VC,{title:`Keyboard`,children:[(0,x.jsx)(HC,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(HC,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(HC,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(HC,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(HC,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(HC,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:zC.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:zC.kbd,children:`?`}),` anytime to reopen.`]})]})})}function VC({title:e,children:t}){return(0,x.jsxs)(`div`,{className:zC.section,children:[(0,x.jsx)(`div`,{className:zC.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:zC.rows,children:t})]})}function HC({k:e,v:t}){return(0,x.jsxs)(`div`,{className:zC.row,children:[(0,x.jsx)(`span`,{className:zC.rowKey,children:e}),(0,x.jsx)(`span`,{className:zC.rowVal,children:t})]})}function UC({color:e}){return(0,x.jsx)(`span`,{className:zC.swatchWrap,children:(0,x.jsx)(`span`,{className:zC.swatch,style:{"--swatch-color":e}})})}var WC={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 GC({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:WC.wrap,children:[(0,x.jsxs)(`div`,{className:WC.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:WC.legendRight,children:[(0,x.jsx)(`span`,{className:WC.legendA,children:`A`}),(0,x.jsx)(`span`,{className:WC.legendB,children:`B`}),(0,x.jsx)(`span`,{className:WC.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:WC.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:WC.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:WC.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:WC.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:WC.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:WC.tooltipRowA,children:[(0,x.jsx)(`span`,{className:WC.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:WC.tooltipRowB,children:[(0,x.jsx)(`span`,{className:WC.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 KC={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`},qC=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],JC={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)`},YC={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function XC({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()}) — click for lineage`,toolName:i})}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:KC.bar,children:[(0,x.jsxs)(`span`,{className:KC.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:KC.filterRow,children:qC.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[KC.filterChip,t?KC.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:KC.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[KC.dot,c?KC.current:``,d?KC.hovered:``].filter(Boolean).join(` `),p={"--kind-color":JC[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):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:YC[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var ZC={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 QC(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 $C({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>QC(e),[e]),i=(0,b.useMemo)(()=>QC(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:ZC.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:ZC.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:ZC.track,children:(0,x.jsx)(`div`,{className:ZC.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:ZC.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:ZC.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var ew={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 tw({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=om();(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:ew.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:ew.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:ew.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:ew.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:ew.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:ew.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:ew.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:ew.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:ew.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:ew.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:ew.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:ew.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:ew.clearBtn,children:`clear`})]})]})}function nw(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 rw(e,t){switch(t){case`birth`:nw(e,880,.18,.05,`triangle`),setTimeout(()=>nw(e,1320,.12,.03,`triangle`),70);break;case`death`:nw(e,160,.35,.05,`sine`);break;case`forge`:nw(e,660,.12,.04,`sine`);break;case`crisis`:nw(e,220,.22,.05,`sawtooth`),setTimeout(()=>nw(e,180,.18,.045,`sawtooth`),120)}}function iw(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=kS(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&&rw(o,`birth`),l>0&&setTimeout(()=>rw(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),rw(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var aw={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 ow(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 sw(e){let{open:t,onClose:n}=e,r=om();(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)(()=>ow(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>ow(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:aw.cell,children:[(0,x.jsx)(`span`,{className:aw.cellLabel,children:e}),(0,x.jsx)(`span`,{className:aw.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:aw.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:aw.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:aw.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:aw.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:aw.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:aw.dialog,children:[(0,x.jsxs)(`div`,{className:aw.header,children:[(0,x.jsxs)(`h2`,{className:aw.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:aw.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:aw.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:aw.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:aw.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:aw.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:aw.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 cw={backdrop:`_backdrop_lye46_1`,dialog:`_dialog_lye46_12`,headerRow:`_headerRow_lye46_28`,kicker:`_kicker_lye46_35`,title:`_title_lye46_42`,closeBtn:`_closeBtn_lye46_49`,firstForged:`_firstForged_lye46_62`,firstDept:`_firstDept_lye46_71`,section:`_section_lye46_76`,sectionLabel:`_sectionLabel_lye46_80`,empty:`_empty_lye46_89`,list:`_list_lye46_95`,attemptItem:`_attemptItem_lye46_104`,statusLabel:`_statusLabel_lye46_115`,jumpBtn:`_jumpBtn_lye46_124`,clickable:`_clickable_lye46_133`,deptLabel:`_deptLabel_lye46_138`,confLabel:`_confLabel_lye46_144`,reuseItem:`_reuseItem_lye46_150`};function lw({payload:e,forgeAttemptsA:t,forgeAttemptsB:n,reuseCallsA:r,reuseCallsB:i,onClose:a,onJumpToTurn:o}){(0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),a())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,a]);let s=(0,b.useMemo)(()=>{if(!e)return null;let a=e.side===`a`?t:n,o=e.side===`a`?r:i,s=a.filter(t=>t.name===e.toolName);s.sort((e,t)=>e.turn-t.turn||e.eventIndex-t.eventIndex);let c=o.filter(t=>t.name===e.toolName);return c.sort((e,t)=>e.turn-t.turn),{mine:s,mineReuses:c,firstApproved:s.find(e=>e.approved)}},[e,t,n,r,i]),c=ht(!!e);if(!e||!s)return null;let l={"--side-color":e.sideColor};return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Forge lineage for ${e.toolName}`,onClick:a,className:cw.backdrop,children:(0,x.jsxs)(`div`,{ref:c,tabIndex:-1,onClick:e=>e.stopPropagation(),className:cw.dialog,style:l,children:[(0,x.jsxs)(`div`,{className:cw.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:cw.kicker,children:[`Forge Lineage · `,e.side.toUpperCase()]}),(0,x.jsx)(`div`,{className:cw.title,children:e.toolName})]}),(0,x.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close lineage`,className:cw.closeBtn,children:`×`})]}),s.firstApproved&&(0,x.jsxs)(`div`,{className:cw.firstForged,children:[`First forged in`,` `,(0,x.jsx)(`span`,{className:cw.firstDept,children:s.firstApproved.department.toUpperCase()}),` `,`on T`,s.firstApproved.turn,typeof s.firstApproved.confidence==`number`?` · confidence ${s.firstApproved.confidence.toFixed(2)}`:``]}),(0,x.jsxs)(`div`,{className:cw.section,children:[(0,x.jsxs)(`div`,{className:cw.sectionLabel,children:[`Attempts (`,s.mine.length,`)`]}),s.mine.length===0?(0,x.jsx)(`div`,{className:cw.empty,children:`no forge records`}):(0,x.jsx)(`ul`,{className:cw.list,children:s.mine.map((e,t)=>{let n={"--status-color":e.approved?`var(--green)`:`var(--rust)`};return(0,x.jsxs)(`li`,{className:cw.attemptItem,style:n,children:[(0,x.jsx)(`span`,{className:cw.statusLabel,children:e.approved?`✓ Forged`:`✗ Rejected`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[cw.jumpBtn,o?cw.clickable:``].filter(Boolean).join(` `),title:o?`Jump to T${e.turn}`:void 0,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:cw.deptLabel,children:e.department}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:cw.confLabel,children:[`conf `,e.confidence.toFixed(2)]})]},`${e.turn}-${e.eventIndex}-${t}`)})})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:cw.sectionLabel,children:[`Cross-dept reuses (`,s.mineReuses.length,`)`]}),s.mineReuses.length===0?(0,x.jsx)(`div`,{className:cw.empty,children:`never reused across departments`}):(0,x.jsx)(`ul`,{className:cw.list,children:s.mineReuses.map((e,t)=>(0,x.jsxs)(`li`,{className:cw.reuseItem,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[cw.jumpBtn,o?cw.clickable:``].filter(Boolean).join(` `),children:[`T`,e.turn]}),(0,x.jsxs)(`span`,{className:cw.deptLabel,children:[e.originDept,` → `,e.callingDept]})]},`${e.turn}-${e.callingDept}-${t}`))})]})]})})}var uw={anchor:`_anchor_ze1xr_1`,trigger:`_trigger_ze1xr_5`,triggerOpen:`_triggerOpen_ze1xr_21`,recDot:`_recDot_ze1xr_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ze1xr_1`,menu:`_menu_ze1xr_36`,item:`_item_ze1xr_52`,itemRecording:`_itemRecording_ze1xr_72`,itemKey:`_itemKey_ze1xr_76`,itemKeyRecording:`_itemKeyRecording_ze1xr_82`,itemDesc:`_itemDesc_ze1xr_86`};function dw({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!i)return;let e=e=>{o.current&&!o.current.contains(e.target)&&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]),(0,x.jsxs)(`div`,{ref:o,className:uw.anchor,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[uw.trigger,i?uw.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:uw.recDot}),`EXPORT ▼`]}),i&&(0,x.jsxs)(`div`,{role:`menu`,className:uw.menu,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),t()},className:uw.item,children:[(0,x.jsx)(`span`,{className:uw.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:uw.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),r()},className:[uw.item,e?uw.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[uw.itemKey,e?uw.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:uw.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),n()},className:uw.item,children:[(0,x.jsx)(`span`,{className:uw.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:uw.itemDesc,children:`Replay snapshot`})]})]})]})}var fw={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},pw=120;function mw({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>pw,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:fw.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:fw.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:fw.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var hw={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 gw({departments:e}){let[t,n]=(0,b.useState)(!1),r=ht(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:hw.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:hw.glyphRow,children:[(0,x.jsx)(_w,{type:`band`}),(0,x.jsx)(`span`,{className:hw.label,children:`Department band`}),(0,x.jsx)(_w,{type:`agent`}),(0,x.jsx)(`span`,{className:hw.label,children:`Agent`}),(0,x.jsx)(_w,{type:`featured`}),(0,x.jsx)(`span`,{className:hw.label,children:`Featured agent`}),(0,x.jsx)(_w,{type:`turn`}),(0,x.jsx)(`span`,{className:hw.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:hw.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:hw.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:hw.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:hw.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:hw.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:hw.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:hw.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function _w({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${hw.glyph} ${hw.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${hw.glyph} ${hw.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${hw.glyph} ${hw.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${hw.glyph} ${hw.turn}`,"aria-hidden":`true`,children:`T`})}}var vw={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`},yw=8;function bw({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,yw);return n.length===0?(0,x.jsxs)(`div`,{className:vw.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:vw.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:vw.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:vw.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:vw.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:vw.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:`${vw.chip} ${i?vw.chipStrong:vw.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:vw.chipDept,children:r}),(0,x.jsxs)(`span`,{className:vw.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var xw=.2;function Sw(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths-(t?.deaths??0),birthsThisTurn:e.births-(t?.births??0),eventCategories:e.eventCategories??[],year:e.time}}function Cw(e,t,n){if(!e||!t)return`Awaiting first turn snapshot.`;let r=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let i=e.deathsThisTurn>t.deathsThisTurn?`A`:`B`,a=Math.max(e.deathsThisTurn,t.deathsThisTurn),o=Math.min(e.deathsThisTurn,t.deathsThisTurn);return`Turn ${n}, year ${r}: Leader ${i} lost ${a} ${a===1?`colonist`:`colonists`}; the other lost ${o}.`}if(Math.abs(e.morale-t.morale)>=xw){let i=e.morale<t.morale?`A`:`B`,a=e.morale<t.morale?e.morale:t.morale,o=e.morale<t.morale?t.morale:e.morale;return`Turn ${n}, year ${r}: Leader ${i}'s morale collapsed to ${ww(a)}; the other held ${ww(o)}.`}let i=e.eventCategories.join(`|`),a=t.eventCategories.join(`|`);return i&&a&&i!==a?`Turn ${n}, year ${r}: the leaders faced different events — A: ${e.eventCategories.join(`, `)}; B: ${t.eventCategories.join(`, `)}.`:n===1&&i&&i===a?`Turn 1, year ${r}: identical first event (${e.eventCategories.join(`, `)}). Both colonies start from the same state.`:`Turn ${n}, year ${r}: A and B tracked closely. See sub-tabs for details.`}function ww(e){return`${Math.round(e*100)}%`}function Tw(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)??Ew(e),a=i.get(e)??Ew(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 Ew(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var Dw={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function Ow(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 kw(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 Aw({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 jw({state:e,onNavigateToChat:t}){let n=nS(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,ee]=(0,b.useState)(1),E=typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`),D=e.isRunning&&!E,[O,te]=(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=>{te(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:ne}=St(),re=(0,b.useRef)(0),A=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=A.current;A.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return re.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(re.current)},[C,T,v]);let j=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),ie=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),ae=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),M=(0,b.useCallback)(e=>{w(!1),S(e)},[]),oe=sT(),N=(0,b.useCallback)(e=>{oe(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[oe]),[se,ce]=(0,b.useState)(!1),le=rT(),de=om(),[fe,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(null),[ge,P]=(0,b.useState)(null),[F,_e]=(0,b.useState)(`all`),[ve,ye]=(0,b.useState)(null),[be,xe]=(0,b.useState)(``),[Se,I]=(0,b.useState)(null),[Ce,we]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3){let{__v:e,...n}=t;return{...pC,...n}}localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return pC}),Te=(0,b.useCallback)(e=>{we(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ce.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),I(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,Ce.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!Se)return;let e=Se.expiresAt-performance.now();if(e<=0){I(null);return}let t=setTimeout(()=>I(null),e);return()=>clearTimeout(t)},[Se]);let[Ee,De]=(0,b.useState)(null),Oe=`paracosm:seenThresholdAlerts`,ke=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Oe);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),Ae=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Oe,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ce.alerts||!e.isRunning)return;let t=ke(),n=(e,n)=>{t.has(e)||(t.add(e),De({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),Ae(t)},[d,f,Ce.alerts,ke,Ae,e.isRunning]),(0,b.useEffect)(()=>{if(!Ee)return;let e=Ee.expiresAt-performance.now();if(e<=0){De(null);return}let t=setTimeout(()=>De(null),e);return()=>clearTimeout(t)},[Ee]);let[je,Me]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),Ne=(0,b.useCallback)(e=>{Me(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Pe=(0,b.useCallback)(()=>{Ne(je===`amber`?`cool`:je===`cool`?`mono`:`amber`)},[je,Ne]),[Fe,Ie]=(0,b.useState)(!1),[Le,Re]=(0,b.useState)(!1),[ze,Be]=(0,b.useState)(!1),[Ve,He]=(0,b.useState)(null),[Ue,We]=(0,b.useState)(null),Ge=(0,b.useCallback)(e=>{We(t=>t===e?null:e)},[]),Ke=d[y]??d[d.length-1],qe=f[y]??f[f.length-1],Je=Ke?.turn??0,Ye=qe?.turn??0,Xe=le.presets.find(e=>e.id==="default"),Ze=Xe?.leaders??Xe?.actors,Qe=Ze?.[0]?{name:Ze[0].name,archetype:Ze[0].archetype,unit:ue(le,0),hexaco:Ze[0].hexaco,instructions:Ze[0].instructions,quote:``}:null,$e=Ze?.[1]?{name:Ze[1].name,archetype:Ze[1].archetype,unit:ue(le,1),hexaco:Ze[1].hexaco,instructions:Ze[1].instructions,quote:``}:null,et=p?.leader??Qe,tt=m?.leader??$e,nt=(0,b.useRef)(null),[rt,it]=(0,b.useState)(!1),at=(0,b.useRef)(null),ot=(0,b.useRef)([]),st=(0,b.useRef)(null),ct=(0,b.useRef)(0),lt=(0,b.useCallback)(()=>{let e=nt.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;st.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}ot.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&ot.current.push(e.data)},s.onstop=()=>{ct.current&&cancelAnimationFrame(ct.current),ct.current=0;let e=new Blob(ot.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)},at.current=s,it(!0),s.start();let c=()=>{let e=st.current,t=nt.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)}ct.current=requestAnimationFrame(c)};ct.current=requestAnimationFrame(c)},[]),ut=(0,b.useCallback)(()=>{let e=at.current;if(e){try{e.stop()}catch{}at.current=null,it(!1)}},[]);(0,b.useEffect)(()=>()=>{if(at.current)try{at.current.stop()}catch{}ct.current&&cancelAnimationFrame(ct.current)},[]);let dt=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:et?.name??`Leader A`,archetype:et?.archetype??``},leaderB:{name:tt?.name??`Leader B`,archetype:tt?.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,et,tt,d,f,p,m]),ft=(0,b.useCallback)(()=>{let e=nt.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]),[pt,mt]=(0,b.useState)(0),ht=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ht.current===-1||Math.abs(y-ht.current)>=2&&mt(e=>e+1),ht.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&(e.key===`ArrowLeft`?(e.preventDefault(),ie()):e.key===`ArrowRight`?(e.preventDefault(),ae()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),j()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),ce(e=>!e)):e.key===`Escape`&&se?(e.preventDefault(),ce(!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)},[ie,ae,j,se,k]);let gt=(0,b.useMemo)(()=>{let e=be.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[...(Ke?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:et?.name??`Leader A`,sideColor:`#e8b44a`})),...(qe?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:tt?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[be,Ke,qe,et,tt]),_t=(0,b.useMemo)(()=>Ow(Ke,qe),[Ke,qe]),vt=(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]);iw({enabled:Ce.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:vt.a.attempts,forgeAttemptsB:vt.b.attempts});let yt=(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]),bt=(0,b.useCallback)(e=>{t?.(e)},[t]),xt=Ex(Dx),Ct=Ex(Ox),wt=(0,b.useMemo)(()=>Cw(d[y]?Sw(d[y],d[y-1]):null,f[y]?Sw(f[y],f[y-1]):null,y+1),[d,f,y]),Tt=(0,b.useMemo)(()=>le.departments.map(e=>({id:e.id,label:e.label,color:Dw[e.id]??`#a89878`})),[le.departments]),Et=(0,b.useMemo)(()=>Object.fromEntries(le.departments.map(e=>[e.id,e.label])),[le.departments]),[Dt,Ot]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),kt=(0,b.useCallback)(e=>{Ot(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(),kt(!Dt))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Dt,kt]);let At=(0,b.useMemo)(()=>Dt?Tw(kw(d[y]),kw(f[y])):null,[Dt,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 `,de.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 `,de.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 `,de.place,` visualization.`]});let jt=Ke&&qe?`A vs B: ${qe.population-Ke.population>=0?`+`:``}${qe.population-Ke.population} pop, ${qe.morale-Ke.morale>=0?`+`:``}${Math.round((qe.morale-Ke.morale)*100)}% morale${typeof Ke.foodReserve==`number`&&typeof qe.foodReserve==`number`?`, ${qe.foodReserve-Ke.foodReserve>0?`+`:``}${(qe.foodReserve-Ke.foodReserve).toFixed(1)}mo food`:``}`:``,Mt=Ct?Ue??`a`:Ue,Nt=y>0?d[y-1]??d[d.length-2]:void 0,Pt=y>0?f[y-1]??f[f.length-2]:void 0,Ft=gt;return(0,x.jsxs)(`div`,{ref:nt,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)(MC,{state:e,currentTurn:y}),(0,x.jsx)(mw,{text:wt,turn:y+1}),(0,x.jsx)(gw,{departments:Tt}),Dt&&At&&(0,x.jsx)(bw,{diff:At,departmentLabels:Et}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(`div`,{className:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(RC,{mode:O,onChange:k,counts:{forge:vt.a.attempts.filter(e=>e.approved).length+vt.b.attempts.filter(e=>e.approved).length,divergence:(_t.aliveOnlyA?.size??0)+(_t.aliveOnlyB?.size??0)},labels:de})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Be(e=>!e),"aria-label":ze?`Hide advanced tools`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":ze,title:ze?`Hide tools`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,ze?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>kt(!Dt),"aria-label":Dt?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Dt,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Dt?`on`:`off`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ce(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),ze&&(0,x.jsxs)(`div`,{role:`toolbar`,"aria-label":`Viz tools`,className:$.toolsRow,children:[(0,x.jsx)(`button`,{type:`button`,onClick:Pe,"aria-label":`Palette: ${je}. Click to cycle.`,title:`Palette: ${je.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":je===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:je===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:je}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Re(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(dw,{recording:rt,onExportPng:ft,onExportJson:dt,onToggleRecording:rt?ut:lt}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":Fe,title:`Viz settings`,className:[$.settingsBtn,Fe?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:LC(O,de)})]}),(0,x.jsx)(tw,{value:be,onChange:xe,matches:Ft,onPick:e=>{xe(e.cell.name)}}),(0,x.jsx)($C,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:le.departments.length}),(0,x.jsx)(XC,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:M,hoveredTurn:ge,onHoverTurnChange:P,filter:F,onFilterChange:_e,onHoverEventChange:ye,onJumpToReports:N,onForgeSelect:(e,t)=>He({toolName:e,side:t,sideColor:t===`a`?`var(--vis)`:`var(--eng)`})}),(0,x.jsx)(GC,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:M,hoveredTurn:ge,onHoverTurnChange:P}),g===`pair`&&jt&&(0,x.jsx)(`div`,{className:$.diffLine,children:jt}),g===`pair`&&Ct&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?et?.name??`Leader A`:tt?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=Mt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>We(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsx)(DC,{state:e,snapshotMap:n,currentTurn:y,gridMode:O,palette:je===`cool`?1:je===`mono`?2:0,gridSettings:Ce,hexacoById:yt,searchQuery:be,chronicleFilter:F,chronicleHover:ve,startTime:le.setup?.defaultStartTime,onOpenChat:bt}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,xt?$.leadersRowNarrow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,Mt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(CC,{snapshot:Ke,isLiveRun:D,previousSnapshot:Nt,snapshotHistory:d,actorName:et?.name??`Leader A`,actorArchetype:et?.archetype??``,leaderUnit:et?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Je<Ye?Ye-Je:0,mode:O,hexacoById:yt,leaderHexaco:et?.hexaco?{O:et.hexaco.O??et.hexaco.openness??.5,C:et.hexaco.C??et.hexaco.conscientiousness??.5,E:et.hexaco.E??et.hexaco.extraversion??.5,A:et.hexaco.A??et.hexaco.agreeableness??.5,Em:et.hexaco.Em??et.hexaco.emotionality??.5,HH:et.hexaco.HH??et.hexaco.honestyHumility??.5}:void 0,forgeAttempts:vt.a.attempts,reuseCalls:vt.a.reuses,divergedIds:_t.aliveOnlyA,siblingHoveredId:me,onHoverChange:pe,searchQuery:be,palette:je===`cool`?1:je===`mono`?2:0,settings:Ce,startTime:le.setup?.defaultStartTime,focusedSide:Mt,onToggleFocus:Ct?void 0:Ge,onOpenChat:bt,eventFilter:F,chronicleHover:ve})}),(0,x.jsx)(`div`,{className:[$.sideWrap,Mt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(CC,{snapshot:qe,isLiveRun:D,previousSnapshot:Pt,snapshotHistory:f,actorName:tt?.name??`Leader B`,actorArchetype:tt?.archetype??``,leaderUnit:tt?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:Ye<Je?Je-Ye:0,mode:O,hexacoById:yt,leaderHexaco:tt?.hexaco?{O:tt.hexaco.O??tt.hexaco.openness??.5,C:tt.hexaco.C??tt.hexaco.conscientiousness??.5,E:tt.hexaco.E??tt.hexaco.extraversion??.5,A:tt.hexaco.A??tt.hexaco.agreeableness??.5,Em:tt.hexaco.Em??tt.hexaco.emotionality??.5,HH:tt.hexaco.HH??tt.hexaco.honestyHumility??.5}:void 0,forgeAttempts:vt.b.attempts,reuseCalls:vt.b.reuses,divergedIds:_t.aliveOnlyB,siblingHoveredId:fe,onHoverChange:he,searchQuery:be,palette:je===`cool`?1:je===`mono`?2:0,settings:Ce,startTime:le.setup?.defaultStartTime,focusedSide:Mt,onToggleFocus:Ct?void 0:Ge,onOpenChat:bt,eventFilter:F,chronicleHover:ve})})]}),(0,x.jsx)(PC,{currentTurn:y,maxTurn:v,time:Ke?.time??qe?.time??0,playing:C,speed:T,onTurnChange:M,onPlayPause:j,onStepBack:ie,onStepForward:ae,onSpeedChange:ee}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(Aw,{k:`?`,v:`help`}),(0,x.jsx)(Aw,{k:`1-5`,v:`mode`}),(0,x.jsx)(Aw,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(Aw,{k:`space`,v:`play / pause`}),(0,x.jsx)(Aw,{k:`click`,v:`${de.person} drilldown`}),(0,x.jsx)(Aw,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ke&&qe?`Turn ${Math.max(Ke.turn,qe.turn)}. ${et?.name??`A`} ${de.place}: ${Ke.cells.filter(e=>e.alive).length} alive, ${Ke.births} born, ${Ke.deaths} died, morale ${Math.round(Ke.morale*100)}%. ${tt?.name??`B`} ${de.place}: ${qe.cells.filter(e=>e.alive).length} alive, ${qe.births} born, ${qe.deaths} died, morale ${Math.round(qe.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>M(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)(BC,{open:se,onClose:()=>ce(!1)}),(0,x.jsx)(mC,{open:Fe,settings:Ce,onChange:Te,onClose:()=>Ie(!1)}),(0,x.jsx)(lw,{payload:Ve,forgeAttemptsA:vt.a.attempts,forgeAttemptsB:vt.b.attempts,reuseCallsA:vt.a.reuses,reuseCallsB:vt.b.reuses,onClose:()=>He(null),onJumpToTurn:e=>{M(e),He(null)}}),(0,x.jsx)(sw,{open:Le,onClose:()=>Re(!1),snapsA:d,snapsB:f,actorNameA:et?.name??`Leader A`,actorNameB:tt?.name??`Leader B`,forgeApprovedA:vt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:vt.b.attempts.filter(e=>e.approved).length,reuseCountA:vt.a.reuses.length,reuseCountB:vt.b.reuses.length,divergedCount:(_t.aliveOnlyA?.size??0)+(_t.aliveOnlyB?.size??0)}),Ee&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>De(null),className:$.toast,style:{"--toast-top":Se?`68px`:`8px`,"--side-color":Ee.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":Ee.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":Ee.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:Ee.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[Ee.side.toUpperCase(),` · T`,Ee.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:Ee.message})]},Ee.key),Se&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>I(null),className:$.toast,style:{"--side-color":Se.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:[Se.side.toUpperCase(),` · T`,Se.turn,` · `,Se.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:Se.title||`${Se.category} crisis unfolding`})]},Se.key),pt>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},pt),(0,x.jsx)(`style`,{children:`
|
|
122
|
+
`)}function __(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function v_(e,t){if(t.format===`percent`)return`${Math.round(__(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 y_={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 b_(e){return e===`foodMonthsReserve`?`mo`:``}var x_={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},S_={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function C_(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function w_(e,t){return e?t===`neutral`?y_.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?y_.deltaPositive:y_.deltaNegative:e.startsWith(`+`)?y_.deltaPositive:y_.deltaNegative:``}function T_(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 E_({actors:e,crisisText:t,toolRegistry:n}){let r=iT(),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,ee=o?.environment,E=s?.environment,{reuseA:D,reuseB:O}=(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]),te=(0,b.useRef)({toolsA:g,toolsB:_,reuseA:D,reuseB:O,citationsA:v,citationsB:y,deathsA:f,deathsB:p}),k=te.current,ne=C_(g,k.toolsA),re=C_(_,k.toolsB),A=C_(D,k.reuseA),j=C_(O,k.reuseB),ie=C_(v,k.citationsA),ae=C_(y,k.citationsB),M=C_(f,k.deathsA),oe=C_(p,k.deathsB);if((0,b.useEffect)(()=>{te.current={toolsA:g,toolsB:_,reuseA:D,reuseB:O,citationsA:v,citationsB:y,deathsA:f,deathsB:p}},[g,_,D,O,v,y,f,p]),!c&&!l)return null;let N=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),se=ve(0),ce=ve(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${y_.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":se,"--actor-color-b":ce},children:[t&&(0,x.jsx)(`span`,{className:y_.crisis,children:t}),N.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:__(t,e),i=C_(__(t,e),r(u?.[e.id])),a=C_(__(n,e),r(d?.[e.id])),o=v_(t,e),s=v_(n,e),f=b_(e.id),p=x_[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=S_[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:w_(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:y_.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:y_.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:w_(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.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}),M&&(0,x.jsx)(`span`,{className:w_(M,`lossIsRed`),children:M}),(0,x.jsx)(`span`,{className:y_.sep,children:`vs`}),(0,x.jsx)(`span`,{className:y_.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}),oe&&(0,x.jsx)(`span`,{className:w_(oe,`lossIsRed`),children:oe}),(()=>{let e=T_(m),t=T_(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:y_.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:g}),ne&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:ne}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:_}),re&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:re})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:D}),A&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:A}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:O}),j&&(0,x.jsx)(`span`,{className:y_.deltaPositive,children:j})]}),(0,x.jsxs)(`span`,{className:y_.pill,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:v}),ie&&(0,x.jsx)(`span`,{className:w_(ie,`neutral`),children:ie}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:y}),ae&&(0,x.jsx)(`span`,{className:w_(ae,`neutral`),children:ae})]}),(w||T)&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${g_(w)||`(none)`}\n\nLeader B:\n${g_(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:T?Object.keys(T).length:0})]}),(ee||E)&&(0,x.jsxs)(`span`,{className:y_.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${g_(ee)||`(none)`}\n\nLeader B:\n${g_(E)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:y_.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:y_.valueA,children:ee?Object.keys(ee).length:0}),(0,x.jsx)(`span`,{className:y_.sep,children:`/`}),(0,x.jsx)(`span`,{className:y_.valueB,children:E?Object.keys(E).length:0})]})]})}var D_={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 O_(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 k_(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 A_(e){if(!e)return null;let{color:t}=k_(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:D_.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function j_({t:e,sideColor:t}){let{label:n,color:r}=k_(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:D_.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:D_.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:D_.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:D_.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:D_.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:D_.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:D_.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:D_.tooltipDecision,children:[(0,x.jsx)(`span`,{className:D_.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:D_.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function M_({turns:e,actorIndex:t}){let n=ve(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:D_.side,children:e.map(e=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsx)(j_,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[D_.entry,e.current?D_.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:D_.entryHead,children:[(0,x.jsxs)(`span`,{className:D_.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:D_.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:D_.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:D_.entryEmergent,children:`EMERGENT`}),A_(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:D_.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:D_.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:D_.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:D_.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:D_.entryDecision,children:e.decision})]})},e.turn))})}function N_({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?O_(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 ${D_.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=ve(e.idx);return(0,x.jsxs)(`div`,{className:D_.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:D_.sideHeader,children:[(0,x.jsxs)(`span`,{className:D_.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:D_.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:D_.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(M_,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var P_={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 F_({outcome:e}){let t=P_[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 I_={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 L_({citations:e,label:t=`sources`,inline:n=!1}){let r=bg();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:[I_.row,n?I_.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:I_.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(R_,{n:e,entry:t},e))]})}function R_({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:I_.popoverWrap,children:[(0,x.jsxs)(`div`,{className:I_.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:I_.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:I_.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:I_.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:I_.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:I_.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:I_.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(Og,{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:I_.pill,children:[`[`,e,`]`]})})}var q={eventStartRow:`_eventStartRow_1j8hl_1`,notFirst:`_notFirst_1j8hl_9`,eventNumber:`_eventNumber_1j8hl_14`,eventStartTitle:`_eventStartTitle_1j8hl_21`,eventCategoryPill:`_eventCategoryPill_1j8hl_26`,promotionTooltipTitle:`_promotionTooltipTitle_1j8hl_35`,promotionTooltipRow:`_promotionTooltipRow_1j8hl_42`,promotionTooltipKey:`_promotionTooltipKey_1j8hl_46`,promotionTooltipValue:`_promotionTooltipValue_1j8hl_50`,promotionTooltipReason:`_promotionTooltipReason_1j8hl_55`,promotionRow:`_promotionRow_1j8hl_60`,promotionArrow:`_promotionArrow_1j8hl_70`,promotionRole:`_promotionRole_1j8hl_75`,promotionReason:`_promotionReason_1j8hl_81`,forgeBtn:`_forgeBtn_1j8hl_90`,forgeSlide:`_forgeSlide_1j8hl_1`,forgeRow:`_forgeRow_1j8hl_110`,forgeBadge:`_forgeBadge_1j8hl_117`,forgeDept:`_forgeDept_1j8hl_130`,forgeDescription:`_forgeDescription_1j8hl_136`,forgeName:`_forgeName_1j8hl_141`,forgeVerdictPass:`_forgeVerdictPass_1j8hl_147`,forgeVerdictFail:`_forgeVerdictFail_1j8hl_159`,forgeFieldsRow:`_forgeFieldsRow_1j8hl_171`,fieldsLabelIn:`_fieldsLabelIn_1j8hl_181`,fieldsLabelOut:`_fieldsLabelOut_1j8hl_185`,forgeError:`_forgeError_1j8hl_189`,specWrap:`_specWrap_1j8hl_196`,specCard:`_specCard_1j8hl_200`,specHeader:`_specHeader_1j8hl_209`,specHeaderDept:`_specHeaderDept_1j8hl_217`,specToolCount:`_specToolCount_1j8hl_225`,severityBadge:`_severityBadge_1j8hl_231`,specSummary:`_specSummary_1j8hl_241`,specSummaryEmpty:`_specSummaryEmpty_1j8hl_248`,specRisks:`_specRisks_1j8hl_256`,specRisksLabel:`_specRisksLabel_1j8hl_260`,specRiskRow:`_specRiskRow_1j8hl_269`,specRiskSeverity:`_specRiskSeverity_1j8hl_278`,specRecs:`_specRecs_1j8hl_287`,specRecsLabel:`_specRecsLabel_1j8hl_291`,specRecRow:`_specRecRow_1j8hl_300`,toolDetail:`_toolDetail_1j8hl_309`,newTool:`_newTool_1j8hl_320`,forgeGlow:`_forgeGlow_1j8hl_1`,reused:`_reused_1j8hl_324`,toolSummary:`_toolSummary_1j8hl_328`,toolSummaryMain:`_toolSummaryMain_1j8hl_336`,toolSummaryHead:`_toolSummaryHead_1j8hl_341`,toolNewBadge:`_toolNewBadge_1j8hl_348`,toolReusedBadge:`_toolReusedBadge_1j8hl_361`,toolFirstForged:`_toolFirstForged_1j8hl_374`,toolSchemaBadge:`_toolSchemaBadge_1j8hl_380`,toolDescription:`_toolDescription_1j8hl_390`,toolNameLine:`_toolNameLine_1j8hl_397`,toolPassPill:`_toolPassPill_1j8hl_405`,toolFailPill:`_toolFailPill_1j8hl_418`,toolInspectBtn:`_toolInspectBtn_1j8hl_431`,toolBody:`_toolBody_1j8hl_449`,toolMetaRow:`_toolMetaRow_1j8hl_454`,toolMetaLabel:`_toolMetaLabel_1j8hl_459`,toolRawSummary:`_toolRawSummary_1j8hl_466`,toolRawPre:`_toolRawPre_1j8hl_474`,toolEmpty:`_toolEmpty_1j8hl_489`,outcomeCard:`_outcomeCard_1j8hl_494`,decisionPulse:`_decisionPulse_1j8hl_1`,outcomeHead:`_outcomeHead_1j8hl_505`,outcomeLabel:`_outcomeLabel_1j8hl_512`,outcomeMeta:`_outcomeMeta_1j8hl_520`,outcomeText:`_outcomeText_1j8hl_527`,outcomeDeltas:`_outcomeDeltas_1j8hl_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_1j8hl_540`,outcomeBar:`_outcomeBar_1j8hl_544`,outcomeBarDeparts:`_outcomeBarDeparts_1j8hl_552`,outcomeReasoningSummary:`_outcomeReasoningSummary_1j8hl_556`,outcomeReasoningBody:`_outcomeReasoningBody_1j8hl_563`,outcomeReasoningPre:`_outcomeReasoningPre_1j8hl_570`,outcomeRationale:`_outcomeRationale_1j8hl_582`,outcomePolicyLine:`_outcomePolicyLine_1j8hl_587`,driftRow:`_driftRow_1j8hl_591`,driftLabel:`_driftLabel_1j8hl_599`,driftName:`_driftName_1j8hl_607`,reactionsCard:`_reactionsCard_1j8hl_611`,reactionsHead:`_reactionsHead_1j8hl_620`,reactionsLabel:`_reactionsLabel_1j8hl_627`,reactionsBar:`_reactionsBar_1j8hl_636`,reactionsBarSegment:`_reactionsBarSegment_1j8hl_645`,reactionsLegend:`_reactionsLegend_1j8hl_650`,reactionsLegendItem:`_reactionsLegendItem_1j8hl_657`,reactionsLegendSwatch:`_reactionsLegendSwatch_1j8hl_663`,reactionsQuotesSummary:`_reactionsQuotesSummary_1j8hl_671`,reactionsQuotesList:`_reactionsQuotesList_1j8hl_679`,reactionTooltipName:`_reactionTooltipName_1j8hl_686`,reactionTooltipMeta:`_reactionTooltipMeta_1j8hl_692`,reactionTooltipHexaco:`_reactionTooltipHexaco_1j8hl_697`,reactionTooltipHealth:`_reactionTooltipHealth_1j8hl_704`,reactionTooltipQuote:`_reactionTooltipQuote_1j8hl_709`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_1j8hl_717`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_1j8hl_724`,reactionRow:`_reactionRow_1j8hl_730`,notLast:`_notLast_1j8hl_739`,reactionRowName:`_reactionRowName_1j8hl_743`,reactionRowQuote:`_reactionRowQuote_1j8hl_750`,reactionRowMoodPill:`_reactionRowMoodPill_1j8hl_761`,bulletinWrap:`_bulletinWrap_1j8hl_773`,bulletinTooltipName:`_bulletinTooltipName_1j8hl_777`,bulletinTooltipRole:`_bulletinTooltipRole_1j8hl_781`,bulletinTooltipBody:`_bulletinTooltipBody_1j8hl_786`,bulletinTooltipMood:`_bulletinTooltipMood_1j8hl_792`,bulletinRow:`_bulletinRow_1j8hl_798`,bulletinName:`_bulletinName_1j8hl_807`,bulletinPost:`_bulletinPost_1j8hl_813`,bulletinLikes:`_bulletinLikes_1j8hl_822`,turnDone:`_turnDone_1j8hl_828`,fallbackBox:`_fallbackBox_1j8hl_841`,fallbackTitle:`_fallbackTitle_1j8hl_853`,fallbackSite:`_fallbackSite_1j8hl_859`,fallbackPreviewWrap:`_fallbackPreviewWrap_1j8hl_864`,fallbackPreviewSummary:`_fallbackPreviewSummary_1j8hl_868`,fallbackPreviewPre:`_fallbackPreviewPre_1j8hl_874`,modalBackdrop:`_modalBackdrop_1j8hl_885`,modalDialog:`_modalDialog_1j8hl_896`,modalHeader:`_modalHeader_1j8hl_912`,modalHeaderLeft:`_modalHeaderLeft_1j8hl_919`,modalKicker:`_modalKicker_1j8hl_924`,modalTitle:`_modalTitle_1j8hl_934`,modalDescription:`_modalDescription_1j8hl_942`,modalCloseBtn:`_modalCloseBtn_1j8hl_948`,modalScroll:`_modalScroll_1j8hl_959`,modalPills:`_modalPills_1j8hl_965`,modalEmpty:`_modalEmpty_1j8hl_974`,usageList:`_usageList_1j8hl_980`,usageItem:`_usageItem_1j8hl_989`,usageHeader:`_usageHeader_1j8hl_1000`,usageTurn:`_usageTurn_1j8hl_1007`,usageTime:`_usageTime_1j8hl_1012`,usageDept:`_usageDept_1j8hl_1016`,usageEvent:`_usageEvent_1j8hl_1021`,usageStatus:`_usageStatus_1j8hl_1025`,usageStatusBadge:`_usageStatusBadge_1j8hl_1031`,usageConf:`_usageConf_1j8hl_1040`,usageOutput:`_usageOutput_1j8hl_1045`,codePre:`_codePre_1j8hl_1053`,fieldsBlock:`_fieldsBlock_1j8hl_1069`,pill:`_pill_1j8hl_1077`,modalSection:`_modalSection_1j8hl_1088`,modalSectionTitle:`_modalSectionTitle_1j8hl_1092`,schemaBlock:`_schemaBlock_1j8hl_1102`,schemaFieldsLabel:`_schemaFieldsLabel_1j8hl_1106`,schemaFieldsList:`_schemaFieldsList_1j8hl_1114`,schemaTitle:`_schemaTitle_1j8hl_1119`,schemaTable:`_schemaTable_1j8hl_1128`,schemaRow:`_schemaRow_1j8hl_1136`,schemaKeyCell:`_schemaKeyCell_1j8hl_1140`,schemaRequired:`_schemaRequired_1j8hl_1148`,schemaTypeCell:`_schemaTypeCell_1j8hl_1153`,schemaDescCell:`_schemaDescCell_1j8hl_1160`,forgeDetails:`_forgeDetails_1j8hl_1168`,forgeSummary:`_forgeSummary_1j8hl_1180`,forgeInspectAbs:`_forgeInspectAbs_1j8hl_1197`,forgeBody:`_forgeBody_1j8hl_1215`,specDetails:`_specDetails_1j8hl_1220`,specSummaryRow:`_specSummaryRow_1j8hl_1229`,specBody:`_specBody_1j8hl_1246`,reactionsDetails:`_reactionsDetails_1j8hl_1252`,reactionsSummary:`_reactionsSummary_1j8hl_1260`,reactionsTopMood:`_reactionsTopMood_1j8hl_1277`,reactionsBody:`_reactionsBody_1j8hl_1285`,bulletinDetails:`_bulletinDetails_1j8hl_1290`,bulletinSummary:`_bulletinSummary_1j8hl_1294`,bulletinSummaryLabel:`_bulletinSummaryLabel_1j8hl_1312`,bulletinSummaryNames:`_bulletinSummaryNames_1j8hl_1322`,bulletinBody:`_bulletinBody_1j8hl_1332`,fallbackDetails:`_fallbackDetails_1j8hl_1336`,fallbackSummary:`_fallbackSummary_1j8hl_1347`},z_={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`},B_={positive:`#6aad48`,negative:`#e06530`,anxious:`#e8b44a`,defiant:`#e06530`,hopeful:`#6aad48`,resigned:`#a89878`,neutral:`#a89878`};function V_({event:e,actorIndex:t}){let n=iT(),r=wg(),[i,a]=(0,b.useState)(null),o=ve(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`,{className:[q.eventStartRow,e>0?q.notFirst:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:q.eventNumber,children:[`EVENT `,e+1,`/`,t]}),(0,x.jsx)(`span`,{className:q.eventStartTitle,children:n}),r&&(0,x.jsx)(`span`,{className:q.eventCategoryPill,children:r})]})}case`promotion`:{let e=String(c.reason||``),t=String(c.name||``),n=String(c.role||``);return(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:q.promotionTooltipTitle,style:s,children:[`Promotion: `,n]}),t&&(0,x.jsxs)(`div`,{className:q.promotionTooltipRow,children:[(0,x.jsx)(`span`,{className:q.promotionTooltipKey,children:`Agent:`}),` `,(0,x.jsx)(`span`,{className:q.promotionTooltipValue,children:t})]}),e&&(0,x.jsx)(`div`,{className:q.promotionTooltipReason,children:e})]}),children:(0,x.jsxs)(`div`,{className:q.promotionRow,children:[(0,x.jsx)(`span`,{className:q.promotionArrow,children:`→`}),(0,x.jsx)(`span`,{className:q.promotionRole,style:s,children:n}),(0,x.jsx)(`span`,{className:q.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),s=String(c.mode||`sandbox`),l=c.approved!==!1,u=typeof c.confidence==`number`?c.confidence:.85,d=c.errorReason?String(c.errorReason):``,f=l?o:`var(--rust)`,p=Array.isArray(c.inputFields)?c.inputFields:[],m=Array.isArray(c.outputFields)?c.outputFields:[],h={"--accent":f,"--bg-tint":l?`color-mix(in srgb, ${o} 7%, transparent)`:`rgba(224,101,48,0.04)`,"--border-tint":l?`color-mix(in srgb, ${o} 25%, transparent)`:`rgba(224,101,48,0.2)`,"--shadow-tint":l?`0 0 0 1px color-mix(in srgb, ${o} 10%, transparent)`:`var(--card-shadow)`,"--badge-color":l?`var(--bg-deep)`:`#fff`,"--badge-bg":f,"--badge-shadow":l?`0 0 8px rgba(232,180,74,0.4)`:`none`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`details`,{className:q.forgeDetails,style:h,children:[(0,x.jsx)(`summary`,{className:q.forgeSummary,children:(0,x.jsxs)(`span`,{className:q.forgeRow,children:[(0,x.jsx)(`span`,{className:q.forgeBadge,children:l?`✦ FORGED TOOL`:`↻ FORGE RETRY`}),(0,x.jsx)(`span`,{className:q.forgeDept,children:e}),(0,x.jsx)(`span`,{className:q.forgeDescription,children:n}),(0,x.jsxs)(`span`,{className:q.forgeName,children:[t,` (`,s,`)`]}),(0,x.jsx)(`span`,{className:l?q.forgeVerdictPass:q.forgeVerdictFail,children:l?`PASS ${u.toFixed(2)}`:`RETRY`})]})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Inspect forged tool ${t}`,className:q.forgeInspectAbs,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:q.forgeBody,children:[(p.length>0||m.length>0)&&(0,x.jsxs)(`div`,{className:q.forgeFieldsRow,children:[p.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelIn,children:`in:`}),` `,p.join(`, `)]}),m.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelOut,children:`out:`}),` `,m.join(`, `)]})]}),!l&&d&&(0,x.jsx)(`div`,{className:q.forgeError,children:d})]})]}),i&&(0,x.jsx)(U_,{entry:r.getEntry(i),fallbackName:i,onClose:()=>a(null)})]})}case`specialist_done`:{let e=String(c.department||``),t=c._filteredTools||[],s=t.filter(e=>e?.isNew!==!0),l=Array.isArray(c.risks)?c.risks:[],u=Array.isArray(c.recommendedActions)?c.recommendedActions.map(String):[],d=l.some(e=>e.severity===`critical`)?`critical`:l.some(e=>e.severity===`high`)?`high`:``,f=String(c.summary||``),p=Number(c.citations)||0;if(!f&&l.length===0&&u.length===0&&t.length===0&&p===0)return null;let m={"--card-bg":d===`critical`?`rgba(224,101,48,.08)`:d===`high`?`rgba(232,180,74,.06)`:`var(--bg-card)`,"--card-border":d===`critical`?`rgba(224,101,48,.25)`:d===`high`?`rgba(232,180,74,.2)`:`var(--border)`,"--card-accent":d===`critical`?`var(--rust)`:d===`high`?`var(--amber)`:`var(--teal)`},h=d?{"--sev-color":d===`critical`?`var(--rust)`:`var(--amber)`,"--sev-bg":d===`critical`?`rgba(224,101,48,.15)`:`rgba(232,180,74,.1)`}:void 0;return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:q.specWrap,children:[(0,x.jsxs)(`details`,{className:q.specDetails,style:m,children:[(0,x.jsxs)(`summary`,{className:q.specSummaryRow,children:[(0,x.jsxs)(`span`,{className:q.specHeaderDept,children:[n.ui.departmentIcons[e]||``,` `,e]}),t.length>0&&(0,x.jsxs)(`span`,{className:q.specToolCount,children:[`+`,t.length,` tool`,t.length===1?``:`s`,s.length<t.length&&` (${s.length} reused)`]}),d&&(0,x.jsxs)(`span`,{className:q.severityBadge,style:h,children:[d.toUpperCase(),` RISK`]}),(0,x.jsx)(L_,{citations:c.citationList||[],inline:!0,label:``})]}),(0,x.jsxs)(`div`,{className:q.specBody,children:[f?(0,x.jsx)(`div`,{className:q.specSummary,children:f}):l.length===0&&u.length===0&&(p>0||t.length>0)?(0,x.jsxs)(`div`,{className:q.specSummaryEmpty,children:[`Department analysis complete — no narrative summary returned, but`,p>0&&` ${p} source${p===1?``:`s`} surveyed`,p>0&&t.length>0&&` and `,t.length>0&&` ${t.length} tool${t.length===1?``:`s`} forged`,`.`]}):null,l.length>0&&(0,x.jsxs)(`div`,{className:q.specRisks,children:[(0,x.jsx)(`div`,{className:q.specRisksLabel,children:`RISKS`}),l.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:q.specRiskRow,children:[(0,x.jsx)(`span`,{className:q.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))]}),u.length>0&&(0,x.jsxs)(`div`,{className:q.specRecs,children:[(0,x.jsx)(`div`,{className:q.specRecsLabel,children:`RECOMMENDATIONS`}),u.slice(0,3).map((e,t)=>(0,x.jsx)(`div`,{className:q.specRecRow,children:e},t))]})]})]}),s.map((e,t)=>{let n=e.approved!==!1,r=e.isNew===!0,i=n?r?o:`var(--green)`:`var(--rust)`,s=n?r?`color-mix(in srgb, ${o} 10%, transparent)`:`rgba(106,173,72,.06)`:`rgba(224,101,48,.04)`,c=n?r?`color-mix(in srgb, ${o} 40%, transparent)`:`rgba(106,173,72,.2)`:`rgba(224,101,48,.15)`,l=r?`0 0 0 1px color-mix(in srgb, ${o} 15%, transparent), var(--card-shadow)`:`var(--card-shadow)`,u=e.inputSchema,d=e.outputSchema,f=!!u||!!d,p={"--tool-bg":s,"--tool-border":c,"--tool-accent":i,"--tool-shadow":l,"--side-color":o},m=[q.toolDetail,r?q.newTool:q.reused].join(` `);return(0,x.jsxs)(`details`,{className:m,style:p,children:[(0,x.jsxs)(`summary`,{className:q.toolSummary,children:[(0,x.jsxs)(`div`,{className:q.toolSummaryMain,children:[(0,x.jsxs)(`div`,{className:q.toolSummaryHead,children:[r?(0,x.jsx)(`span`,{className:q.toolNewBadge,children:`FORGED TOOL`}):(0,x.jsx)(`span`,{className:q.toolReusedBadge,children:`REUSED`}),!r&&e.firstForgedTurn!=null&&(0,x.jsxs)(`span`,{className:q.toolFirstForged,children:[`first forged T`,e.firstForgedTurn,e.firstForgedDepartment&&e.firstForgedDepartment!==e.department?` · ${e.firstForgedDepartment}`:``]}),f&&(0,x.jsx)(`span`,{className:q.toolSchemaBadge,children:`SCHEMA`})]}),(0,x.jsx)(`span`,{className:q.toolDescription,children:String(e.description||e.name||``)}),(0,x.jsxs)(`span`,{className:q.toolNameLine,children:[e.name,` `,e.mode?`(${e.mode})`:``]})]}),(0,x.jsx)(`span`,{className:n?q.toolPassPill:q.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(),a(e.name||``)},"aria-label":`Inspect tool ${e.name||``}`,className:q.toolInspectBtn,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:q.toolBody,children:[e.crisis&&(0,x.jsxs)(`div`,{className:q.toolMetaRow,children:[(0,x.jsx)(`span`,{className:q.toolMetaLabel,children:`CRISIS: `}),String(e.crisis)]}),e.department&&(0,x.jsxs)(`div`,{className:q.toolMetaRow,children:[(0,x.jsx)(`span`,{className:q.toolMetaLabel,children:`DEPT: `}),String(e.department)]}),(u||Array.isArray(e.inputFields)&&e.inputFields.length>0)&&(0,x.jsx)(K_,{label:`INPUT`,color:`var(--teal)`,schema:u,fields:e.inputFields}),(d||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(K_,{label:`OUTPUT`,color:`var(--green)`,schema:d,fields:e.outputFields}),e.output&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:q.toolRawSummary,style:{"--side-color":o},children:`Raw Output`}),(0,x.jsx)(`pre`,{className:q.toolRawPre,children:typeof e.output==`object`?JSON.stringify(e.output,null,2):String(e.output)})]}),!e.output&&!u&&!d&&(!e.inputFields||e.inputFields.length===0)&&(0,x.jsx)(`div`,{className:q.toolEmpty,children:`Tool forged but no output captured. The tool will be available for subsequent turns.`})]})]},t)})]}),i&&(0,x.jsx)(U_,{entry:r.getEntry(i),fallbackName:i,onClose:()=>a(null)})]})}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:q.outcomeCard,style:p,children:[(0,x.jsxs)(`div`,{className:q.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:q.outcomeLabel,children:[`DECISION #`,u]}),(0,x.jsxs)(`span`,{className:q.outcomeMeta,children:[d,` tools · `,f,` citations`]})]}),(0,x.jsx)(F_,{outcome:e})]}),(0,x.jsx)(`div`,{className:q.outcomeText,children:n}),s&&(0,x.jsx)(`div`,{className:s.departs?`${q.outcomeBar} ${q.outcomeBarDeparts}`:q.outcomeBar,children:H_(s)}),Object.keys(l).length>0&&(0,x.jsx)(`div`,{className:q.outcomeDeltas,children:Object.entries(l).map(([e,t])=>(0,x.jsxs)(`span`,{className:q.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:q.outcomeReasoningSummary,children:`Full reasoning & policies`}),(0,x.jsxs)(`div`,{className:q.outcomeReasoningBody,children:[i&&(0,x.jsx)(`div`,{className:q.outcomeReasoningPre,children:i}),n&&(0,x.jsx)(`div`,{children:n}),r&&(0,x.jsx)(`div`,{className:q.outcomeRationale,children:r}),a.map((e,t)=>(0,x.jsxs)(`div`,{className:q.outcomePolicyLine,children:[`→ `,e]},t))]})]})]})}case`personality_drift`:{let e=Object.values(c.agents||{});return e.length?(0,x.jsxs)(`div`,{className:q.driftRow,children:[(0,x.jsx)(`span`,{className:q.driftLabel,children:`DRIFT `}),e.slice(0,3).map((t,n)=>(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:q.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:B_[t]||`#a89878`}));return(0,x.jsxs)(`details`,{className:q.reactionsDetails,children:[(0,x.jsxs)(`summary`,{className:q.reactionsSummary,children:[(0,x.jsxs)(`span`,{className:q.reactionsLabel,style:s,children:[t,` VOICES`]}),(0,x.jsx)(`div`,{className:q.reactionsBar,children:r.map(e=>(0,x.jsx)(`div`,{className:q.reactionsBarSegment,style:{"--seg-flex":String(e.pct),"--seg-bg":e.bg},title:`${e.pct}% ${e.mood}`},e.mood))}),(0,x.jsx)(`span`,{className:q.reactionsTopMood,children:r[0]?`${r[0].pct}% ${r[0].mood}`:``})]}),(0,x.jsxs)(`div`,{className:q.reactionsBody,children:[(0,x.jsx)(`div`,{className:q.reactionsLegend,children:r.slice(0,3).map(e=>(0,x.jsxs)(`span`,{className:q.reactionsLegendItem,children:[(0,x.jsx)(`span`,{className:q.reactionsLegendSwatch,style:{"--swatch-bg":e.bg}}),e.pct,`% `,e.mood]},e.mood))}),(0,x.jsxs)(`details`,{children:[(0,x.jsxs)(`summary`,{className:q.reactionsQuotesSummary,style:s,children:[`quotes (`,e.length,`)`]}),(0,x.jsx)(`div`,{className:q.reactionsQuotesList,children:e.slice(0,4).map((t,n)=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:q.reactionTooltipName,style:s,children:t.name}),(0,x.jsxs)(`div`,{className:q.reactionTooltipMeta,children:[t.role,` in `,t.department,` `,t.age?`· Age ${t.age}`:``]}),(0,x.jsxs)(`div`,{className:q.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:q.reactionTooltipHealth,children:[`Bone: `,t.boneDensity,`% · Radiation: `,t.radiation,`mSv · Psych: `,t.psychScore]}),(0,x.jsxs)(`div`,{className:q.reactionTooltipQuote,children:[`“`,t.quote,`”`]}),(0,x.jsxs)(`div`,{className:q.reactionTooltipMoodLine,style:{"--mood-color":z_[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:q.reactionTooltipBeliefs,children:[`Beliefs: `,t.memory.beliefs.slice(0,2).join(`; `)]})]}),children:(0,x.jsxs)(`div`,{className:[q.reactionRow,n<Math.min(e.length,4)-1?q.notLast:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:q.reactionRowName,style:s,children:t.name}),(0,x.jsxs)(`span`,{className:q.reactionRowQuote,children:[`“`,String(t.quote||``),`”`]}),(0,x.jsx)(`span`,{className:q.reactionRowMoodPill,style:{"--mood-color":z_[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:q.bulletinDetails,children:[(0,x.jsxs)(`summary`,{className:q.bulletinSummary,children:[(0,x.jsxs)(`span`,{className:q.bulletinSummaryLabel,children:[e.length,` POSTS`]}),(0,x.jsxs)(`span`,{className:q.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:q.bulletinBody,children:e.slice(0,3).map((e,t)=>(0,x.jsx)(Og,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:q.bulletinTooltipName,style:s,children:e.name}),` `,(0,x.jsxs)(`span`,{className:q.bulletinTooltipRole,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:q.bulletinTooltipBody,children:e.post}),(0,x.jsxs)(`div`,{className:q.bulletinTooltipMood,style:{"--mood-color":z_[e.mood]||`var(--text-3)`},children:[String(e.mood||``).toUpperCase(),` · `,e.likes||0,` likes · `,e.replies||0,` replies`]})]}),children:(0,x.jsxs)(`div`,{className:q.bulletinRow,children:[(0,x.jsx)(`span`,{className:q.bulletinName,style:s,children:e.name}),(0,x.jsx)(`span`,{className:q.bulletinPost,children:String(e.post||``)}),(0,x.jsxs)(`span`,{className:q.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:q.fallbackDetails,style:s,children:[(0,x.jsxs)(`summary`,{className:q.fallbackSummary,children:[(0,x.jsxs)(`span`,{className:q.fallbackTitle,children:[`⚠ `,r?`SCHEMA SALVAGE`:`SCHEMA FALLBACK`,` — `,e]}),(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`site: `,t||`n/a`]}),r&&(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`kept without: `,i.length>0?i.join(`, `):`n/a`]})]}),n&&(0,x.jsxs)(`details`,{className:q.fallbackPreviewWrap,children:[(0,x.jsx)(`summary`,{className:q.fallbackPreviewSummary,children:`Raw output preview`}),(0,x.jsx)(`pre`,{className:q.fallbackPreviewPre,children:n})]})]})}default:return null}}function H_(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 U_({entry:e,fallbackName:t,onClose:n}){return(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Tool detail · ${e?.name||t}`,onClick:n,className:q.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:q.modalDialog,children:[(0,x.jsxs)(`div`,{className:q.modalHeader,children:[(0,x.jsxs)(`div`,{className:q.modalHeaderLeft,children:[(0,x.jsxs)(`div`,{className:q.modalKicker,children:[`FORGED TOOL [`,e?.n??`?`,`]`]}),(0,x.jsx)(`div`,{className:q.modalTitle,children:e?.name||t}),e?.description&&e.description!==e.name&&(0,x.jsx)(`div`,{className:q.modalDescription,children:e.description})]}),(0,x.jsx)(`button`,{onClick:n,"aria-label":`Close`,className:q.modalCloseBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:q.modalScroll,children:e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:q.modalPills,children:[(0,x.jsx)(W_,{label:`${e.mode}`,color:`var(--text-3)`}),(0,x.jsx)(W_,{label:e.approved?`PASS ${e.confidence.toFixed(2)}`:`RETRY`,color:e.approved?`var(--green)`:`var(--amber)`}),(0,x.jsx)(W_,{label:`first forged T${e.firstForgedTurn} · ${e.firstForgedDepartment}`,color:`var(--amber)`}),e.reuseCount>0&&(0,x.jsx)(W_,{label:`reused ${e.reuseCount}×`,color:`var(--green)`}),e.departments.size>0&&(0,x.jsx)(W_,{label:`used by ${[...e.departments].join(`, `)}`,color:`var(--teal)`})]}),e.inputSchema&&(0,x.jsx)(G_,{title:`INPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.inputSchema,null,2)})}),e.outputSchema&&(0,x.jsx)(G_,{title:`OUTPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.outputSchema,null,2)})}),!e.inputSchema&&!e.outputSchema&&(e.inputFields.length>0||e.outputFields.length>0)&&(0,x.jsx)(G_,{title:`FIELDS (DERIVED)`,children:(0,x.jsxs)(`div`,{className:q.fieldsBlock,children:[e.inputFields.length>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelIn,children:`in:`}),` `,e.inputFields.join(`, `)]}),e.outputFields.length>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`span`,{className:q.fieldsLabelOut,children:`out:`}),` `,e.outputFields.join(`, `)]})]})}),e.history&&e.history.length>0&&(0,x.jsx)(G_,{title:`USAGE HISTORY · ${e.history.length} invocation${e.history.length===1?``:`s`}`,children:(0,x.jsx)(`ol`,{className:q.usageList,children:e.history.map((e,t)=>{let n=e.rejected?`var(--rust)`:e.isReforge?`var(--amber)`:`var(--green)`;return(0,x.jsxs)(`li`,{className:q.usageItem,style:{"--usage-accent":n},children:[(0,x.jsxs)(`div`,{className:q.usageHeader,children:[(0,x.jsxs)(`span`,{className:q.usageTurn,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:q.usageTime,children:e.time}),(0,x.jsx)(`span`,{className:q.usageDept,children:e.department}),(0,x.jsxs)(`span`,{className:q.usageEvent,children:[`· `,e.eventTitle]}),(0,x.jsxs)(`span`,{className:q.usageStatus,children:[(0,x.jsx)(`span`,{className:q.usageStatusBadge,style:{"--status-color":n},children:e.rejected?`JUDGE REJECTED`:e.isReforge?`RE-FORGE`:t===0?`FORGE`:`REUSE`}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:q.usageConf,children:[`conf `,e.confidence.toFixed(2)]})]})]}),e.output&&(0,x.jsx)(`div`,{className:q.usageOutput,children:e.output.length>200?e.output.slice(0,200)+`…`:e.output})]},t)})})}),e.sampleOutput&&(0,x.jsx)(G_,{title:`LATEST OUTPUT`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:e.sampleOutput})})]}):(0,x.jsx)(`div`,{className:q.modalEmpty,children:`Tool entry not yet in the registry — the specialist_done summary for this forge hasn't arrived yet. Try again in a moment.`})})]})})}function W_({label:e,color:t}){return(0,x.jsx)(`span`,{className:q.pill,style:{"--pill-color":t},children:e})}function G_({title:e,children:t}){return(0,x.jsxs)(`div`,{className:q.modalSection,children:[(0,x.jsx)(`div`,{className:q.modalSectionTitle,children:e}),t]})}function K_({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:q.schemaBlock,children:[(0,x.jsxs)(`span`,{className:q.schemaFieldsLabel,style:{"--field-color":t},children:[e,` FIELDS:`,` `]}),(0,x.jsx)(`span`,{className:q.schemaFieldsList,children:r.join(`, `)})]});let o=Object.entries(i).slice(0,12);return(0,x.jsxs)(`div`,{className:q.schemaBlock,children:[(0,x.jsxs)(`div`,{className:q.schemaTitle,style:{"--field-color":t},children:[e,` SCHEMA`]}),(0,x.jsx)(`table`,{className:q.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:q.schemaRow,children:[(0,x.jsxs)(`td`,{className:q.schemaKeyCell,children:[e,o&&(0,x.jsx)(`span`,{className:q.schemaRequired,children:`*`})]}),(0,x.jsx)(`td`,{className:q.schemaTypeCell,style:{"--field-color":t},children:r}),(0,x.jsx)(`td`,{className:q.schemaDescCell,children:i})]},e)})})})]})}var q_={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},J_={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},Y_={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`},X_={same:q_.same,"different-outcome":q_.differentOutcome,"different-event":q_.differentEvent,pending:q_.pending,"one-sided":q_.oneSided};function Z_({classification:e}){return(0,x.jsx)(`span`,{className:`${q_.badge} ${X_[e]}`,"aria-label":Y_[e],children:J_[e]})}var Q_={row:`_row_n6v23_1`,differentOutcome:`_differentOutcome_n6v23_9`,differentEvent:`_differentEvent_n6v23_13`,header:`_header_n6v23_17`,headerTurn:`_headerTurn_n6v23_30`,headerTitle:`_headerTitle_n6v23_36`,headerTitleSplit:`_headerTitleSplit_n6v23_45`,headerTitleA:`_headerTitleA_n6v23_52`,headerTitleB:`_headerTitleB_n6v23_61`,cells:`_cells_n6v23_70`,cell:`_cell_n6v23_70`,cellBand:`_cellBand_n6v23_82`,cellEmpty:`_cellEmpty_n6v23_92`,cellPending:`_cellPending_n6v23_99`,cellPendingSpinner:`_cellPendingSpinner_n6v23_110`},$_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function ev(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 tv({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${Q_.row} ${e.classification===`different-outcome`?Q_.differentOutcome:e.classification===`different-event`?Q_.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:Q_.header,children:[(0,x.jsxs)(`span`,{className:Q_.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(Z_,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:Q_.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:Q_.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:Q_.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:Q_.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:Q_.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!$_.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:Q_.cell,style:{"--cell-color":ve(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:Q_.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:Q_.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 ${Q_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:Q_.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:Q_.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:Q_.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:Q_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Q_.cellPendingSpinner}`}),ev(t)]}):a.map(e=>(0,x.jsx)(V_,{event:e,actorIndex:n},e.id))]},n)})})]})}function nv(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 rv(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=nv(e,t,n);r&&i.set(n,r)}return i}var iv={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function av({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)(()=>rv(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>ov(a),[a]),u=(0,b.useMemo)(()=>ov(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 ${iv.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:iv.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:iv.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(tv,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function ov(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 sv={row:`_row_bsqb3_1`,header:`_header_bsqb3_9`,headerTurn:`_headerTurn_bsqb3_22`,headerTitle:`_headerTitle_bsqb3_28`,headerTitleSplit:`_headerTitleSplit_bsqb3_37`,headerTitlePerActor:`_headerTitlePerActor_bsqb3_45`,cells:`_cells_bsqb3_53`,cell:`_cell_bsqb3_53`,cellBand:`_cellBand_bsqb3_69`,cellEmpty:`_cellEmpty_bsqb3_79`,cellPending:`_cellPending_bsqb3_87`,cellPendingSpinner:`_cellPendingSpinner_bsqb3_97`},cv=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function lv(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 uv(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 dv({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(uv),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:sv.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:sv.header,children:[(0,x.jsxs)(`span`,{className:sv.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:sv.headerTitle,children:s}):(0,x.jsx)(`span`,{className:sv.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:sv.headerTitlePerActor,style:{"--cell-color":ve(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:sv.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!cv.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:sv.cell,style:{"--cell-color":ve(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:sv.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:sv.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:sv.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 ${sv.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:sv.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:sv.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${sv.cellPendingSpinner}`}),lv(o)]}):s.map(e=>(0,x.jsx)(V_,{event:e,actorIndex:a%2},e.id))]},t)})})]})}var fv={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},pv=360;function mv({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>hv(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":`${pv}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:fv.grid,style:c,children:(0,x.jsxs)(`div`,{className:fv.scrollX,children:[(0,x.jsx)(`header`,{className:fv.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:fv.headerCell,children:(0,x.jsx)(m_,{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:fv.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:fv.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(dv,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function hv(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 gv={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 _v(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:gv.item,children:[(0,x.jsxs)(`span`,{className:gv.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:gv.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:gv.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:gv.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 vv(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function yv(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 bv({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:gv.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:gv.filterField,children:[(0,x.jsx)(`label`,{className:gv.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:gv.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:gv.filterField,children:[(0,x.jsx)(`label`,{className:gv.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:gv.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:gv.filterStats,children:[`Showing `,s,` of `,o]})]})}function xv({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)(()=>yv(e.list),[e.list]),d=(0,b.useMemo)(()=>vv(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)(bv,{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:gv.list,children:d.map(_v)}):(0,x.jsx)(`div`,{className:gv.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:gv.wrap,children:[(0,x.jsxs)(`summary`,{className:gv.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:gv.wrap,children:[(0,x.jsxs)(`h3`,{className:gv.title,children:[t,` · `,e.list.length]}),f,p]})}function Sv({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:gv.list,children:e.list.map(_v)})}var J={list:`_list_166gg_1`,item:`_item_166gg_10`,rejected:`_rejected_166gg_23`,itemNumber:`_itemNumber_166gg_27`,itemHead:`_itemHead_166gg_34`,itemName:`_itemName_166gg_42`,passPill:`_passPill_166gg_48`,failPill:`_failPill_166gg_59`,itemMode:`_itemMode_166gg_70`,logBtn:`_logBtn_166gg_76`,itemDescription:`_itemDescription_166gg_94`,metaRow:`_metaRow_166gg_99`,metaReuse:`_metaReuse_166gg_108`,metaReforge:`_metaReforge_166gg_112`,metaRejected:`_metaRejected_166gg_116`,metaInput:`_metaInput_166gg_120`,metaOutput:`_metaOutput_166gg_124`,tooltipTitle:`_tooltipTitle_166gg_128`,detailsBlock:`_detailsBlock_166gg_135`,detailsBlockTight:`_detailsBlockTight_166gg_139`,detailsSummary:`_detailsSummary_166gg_143`,pass:`_pass_166gg_48`,fail:`_fail_166gg_59`,history:`_history_166gg_159`,amber:`_amber_166gg_163`,verdictBody:`_verdictBody_166gg_167`,historyList:`_historyList_166gg_178`,historyItem:`_historyItem_166gg_187`,reforge:`_reforge_166gg_191`,historyActor:`_historyActor_166gg_195`,historyEventTitle:`_historyEventTitle_166gg_199`,codeBlock:`_codeBlock_166gg_203`,codeBlockShort:`_codeBlockShort_166gg_219`,collapsibleWrap:`_collapsibleWrap_166gg_235`,collapsibleSummary:`_collapsibleSummary_166gg_241`,title:`_title_166gg_252`,verdictWrap:`_verdictWrap_166gg_262`,verdictPassHeader:`_verdictPassHeader_166gg_266`,verdictFailHeader:`_verdictFailHeader_166gg_274`,verdictAdds:`_verdictAdds_166gg_282`,verdictAddsLabel:`_verdictAddsLabel_166gg_288`,verdictRejection:`_verdictRejection_166gg_292`,verdictMissing:`_verdictMissing_166gg_306`,verdictCost:`_verdictCost_166gg_312`,verdictCostLabel:`_verdictCostLabel_166gg_317`};function Cv({registry:e,title:t=`Forged Toolbox`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let a=cT();if(e.list.length===0)return null;let o=e=>{try{window.location.hash=`log=${encodeURIComponent(e)}`}catch{}a(`settings`)},s=(0,x.jsx)(`ol`,{className:J.list,children:e.list.map(e=>{let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `),r=wv(e.inputSchema,e.inputFields),i=wv(e.outputSchema,e.outputFields);return(0,x.jsxs)(`li`,{id:`tool-${e.n}`,className:[J.item,e.approved?``:J.rejected].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:J.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`div`,{className:J.itemHead,children:[(0,x.jsx)(`span`,{className:J.itemName,children:e.name}),(0,x.jsx)(`span`,{className:e.approved?J.passPill:J.failPill,children:e.approved?`PASS ${e.confidence.toFixed(2)}`:`FAIL`}),(0,x.jsx)(`span`,{className:J.itemMode,children:e.mode}),(0,x.jsx)(Og,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:J.tooltipTitle,children:`Open in sim log`}),(0,x.jsxs)(`div`,{children:[`Jumps to the Log tab and filters the event stream to `,(0,x.jsx)(`code`,{children:e.name}),` — showing every forge_attempt, specialist_done, and reuse event this tool fired in. Useful for tracing the exact moment a tool was created and every downstream department that reused it.`]})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o(e.name),"aria-label":`Open ${e.name} in simulation log`,className:J.logBtn,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`↗`}),`log`]})})]}),e.description&&e.description!==e.name&&(0,x.jsx)(`div`,{className:J.itemDescription,children:e.description}),(0,x.jsxs)(`div`,{className:J.metaRow,children:[(0,x.jsxs)(`span`,{children:[`first forged T`,e.firstForgedTurn,` · `,e.firstForgedDepartment]}),e.reuseCount>0&&(0,x.jsxs)(`span`,{className:J.metaReuse,children:[`reused `,e.reuseCount,`×`]}),e.reforgeCount>0&&(0,x.jsxs)(`span`,{className:J.metaReforge,children:[e.reforgeCount,` re-forge`,e.reforgeCount===1?``:`s`,e.rejectedReforges>0&&(0,x.jsxs)(`span`,{className:J.metaRejected,children:[` (`,e.rejectedReforges,` rejected)`]})]}),t&&(0,x.jsxs)(`span`,{children:[`used by `,t]}),(0,x.jsxs)(`span`,{children:[`leader `,n]}),r>0&&(0,x.jsxs)(`span`,{className:J.metaInput,children:[r,` input field`,r===1?``:`s`]}),i>0&&(0,x.jsxs)(`span`,{className:J.metaOutput,children:[i,` output field`,i===1?``:`s`]})]}),(0,x.jsxs)(`details`,{className:J.detailsBlock,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,e.approved?J.pass:J.fail].join(` `),children:e.approved?`WHY IT PASSED`:`WHY IT FAILED`}),(0,x.jsx)(`div`,{className:J.verdictBody,children:(0,x.jsx)(Tv,{entry:e})})]}),e.history.length>0&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsxs)(`summary`,{className:[J.detailsSummary,J.history].join(` `),children:[`USE HISTORY · `,e.history.length]}),(0,x.jsx)(`ol`,{className:J.historyList,children:e.history.map((e,t)=>{let n=e.rejected?J.rejected:e.isReforge?J.reforge:``;return(0,x.jsxs)(`li`,{className:[J.historyItem,n].filter(Boolean).join(` `),children:[`T`,e.turn,` · `,e.department,` · `,(0,x.jsx)(`span`,{className:J.historyActor,children:e.actorName}),` · `,t===0?`first forge`:e.isReforge?e.rejected?`re-forge rejected`:`re-forge accepted`:`reuse`,typeof e.confidence==`number`&&` · conf ${e.confidence.toFixed(2)}`,e.eventTitle&&(0,x.jsxs)(`span`,{className:J.historyEventTitle,children:[` · "`,e.eventTitle,`"`]})]},t)})})]}),!!(e.inputSchema||e.outputSchema)&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,J.amber].join(` `),children:`SCHEMA`}),(0,x.jsx)(`pre`,{className:J.codeBlock,children:JSON.stringify({input:e.inputSchema??null,output:e.outputSchema??null},null,2)})]}),e.sampleOutput&&(0,x.jsxs)(`details`,{className:J.detailsBlockTight,children:[(0,x.jsx)(`summary`,{className:[J.detailsSummary,J.pass].join(` `),children:`LATEST OUTPUT`}),(0,x.jsx)(`pre`,{className:J.codeBlockShort,children:e.sampleOutput})]})]})]},e.n)})});return n?(0,x.jsxs)(`details`,{open:r,onToggle:i?e=>i(e.currentTarget.open):void 0,className:J.collapsibleWrap,children:[(0,x.jsxs)(`summary`,{className:J.collapsibleSummary,children:[t,` · `,e.list.length]}),s]}):(0,x.jsxs)(`div`,{className:J.collapsibleWrap,children:[(0,x.jsxs)(`h3`,{className:J.title,children:[t,` · `,e.list.length]}),s]})}function wv(e,t){return e&&typeof e==`object`&&e.properties?Object.keys(e.properties).length:t.length}function Tv({entry:e}){return e.approved?(0,x.jsxs)(`div`,{className:J.verdictWrap,children:[(0,x.jsxs)(`div`,{className:J.verdictPassHeader,children:[`✓ judge confidence `,e.confidence.toFixed(2)]}),(0,x.jsx)(`div`,{children:`The LLM judge reviewed this tool's source code, test outputs, and sandbox allowlist, and approved it across safety, correctness, determinism, and bounded execution.`}),(0,x.jsxs)(`div`,{className:J.verdictAdds,children:[(0,x.jsx)(`b`,{className:J.verdictAddsLabel,children:`What this adds to the run:`}),` `,`+0.04 outcome bonus for this event · the dept's report cites the tool's computed result · the tool is now reusable by any dept at near-zero cost (+0.02 per reuse).`]})]}):(0,x.jsxs)(`div`,{className:J.verdictWrap,children:[(0,x.jsx)(`div`,{className:J.verdictFailHeader,children:`✗ judge rejected`}),e.errorReason?(0,x.jsx)(`div`,{className:J.verdictRejection,children:e.errorReason}):(0,x.jsx)(`div`,{className:J.verdictMissing,children:`(No rejection reason captured. The judge blocked the tool before it could execute.)`}),(0,x.jsxs)(`div`,{className:J.verdictCost,children:[(0,x.jsx)(`b`,{className:J.verdictCostLabel,children:`Cost of a failed forge:`}),` `,`−0.06 outcome bonus on this event · −0.015 morale per failure (crew confidence eroded) · −1.2\xA0kW power (sandbox compute consumed) · no quantitative grounding in the dept's report · the dept retries or moves on without the insight this tool would have provided.`]})]})}var Ev={bar:`_bar_petji_1`,label:`_label_petji_13`,spacer:`_spacer_petji_22`,hint:`_hint_petji_26`,cta:`_cta_petji_51`,ctaCount:`_ctaCount_petji_74`,exportBtn:`_exportBtn_petji_83`,modalBackdrop:`_modalBackdrop_petji_96`,modalDialog:`_modalDialog_petji_107`,modalHeader:`_modalHeader_petji_123`,modalTitle:`_modalTitle_petji_132`,modalClose:`_modalClose_petji_144`,modalBody:`_modalBody_petji_154`};function Dv({citationRegistry:e,toolRegistry:t,layoutToggle:n}){let[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(()=>i(null),[]);(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 o=e.list.length,s=t.list.length;return o===0&&s===0&&!n?null:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{role:`region`,"aria-label":`Simulation evidence`,className:Ev.bar,children:[(0,x.jsx)(`span`,{className:Ev.label,children:`Evidence`}),o>0&&(0,x.jsx)(kv,{label:`References`,count:o,onClick:()=>i(`refs`),ariaLabel:`Open References list (${o} sources)`}),s>0&&(0,x.jsx)(kv,{label:`Forged Toolbox`,count:s,onClick:()=>i(`tools`),ariaLabel:`Open Forged Toolbox (${s} tools)`}),n,(0,x.jsx)(`span`,{className:Ev.spacer}),(0,x.jsx)(`span`,{className:Ev.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(Av,{title:`References · ${o}`,onClose:a,extraActions:(0,x.jsx)(Ov,{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)(Sv,{registry:e})}),r===`tools`&&(0,x.jsx)(Av,{title:`Forged Toolbox · ${s}`,onClose:a,extraActions:(0,x.jsx)(Ov,{label:`EXPORT JSON`,filename:`paracosm-toolbox.json`,data:t.list.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}))}),children:(0,x.jsx)(Cv,{registry:t,title:``,collapsible:!1})})]})}function Ov({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:Ev.exportBtn,children:e})}function kv({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:Ev.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:Ev.ctaCount,children:t})]})}function Av({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:Ev.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:Ev.modalDialog,children:[(0,x.jsxs)(`div`,{className:Ev.modalHeader,children:[(0,x.jsx)(`h2`,{className:Ev.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:Ev.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:Ev.modalBody,children:n})]})})}var jv={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function Mv({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=iT(),i=oT(),a=uT(),o=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=tg(window.localStorage);if(!e||!ng(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=cg(e,sg(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){O(window,i.visitorId),a(),rg(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&ig(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=wm(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:jv.panel,children:[(0,x.jsx)(`span`,{className:jv.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:jv.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:jv.button,onClick:o,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var Nv={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 Pv({hideWhenUnavailable:e=!0}={}){let{sessions:t,status:n,refresh:r}=kg(),i=(0,b.useRef)(null),a=(0,b.useMemo)(()=>[...t].sort((e,t)=>(t.createdAt??0)-(e.createdAt??0)).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=[Nv.card,c?Nv.empty:``].filter(Boolean).join(` `),u=[Nv.kicker,c?Nv.empty:``].filter(Boolean).join(` `),d=[Nv.lead,c?Nv.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:Nv.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:Nv.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:Nv.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:Nv.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:Nv.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:Nv.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:Nv.tile,children:[(0,x.jsx)(`span`,{className:Nv.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:Nv.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,ln(e)?`${ln(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:Nv.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Nv.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:Nv.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 Fv={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`},Iv={...Fv,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function Lv({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`?Iv:Fv,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`?Iv:Fv,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var Rv={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`},zv=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function Bv(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 zv){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 Vv(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 Hv=`Unknown`;function Uv(e){return e?e.trim():``}function Wv(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=Uv(i?.leader?.archetype),o=a||`__unknown__`,s=a||Hv,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 Gv={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 Kv({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:Gv.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:Gv.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:Gv.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${Gv.pill} ${r?Gv.pillFocused:``} ${a?Gv.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:Gv.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:Gv.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var qv=18,Jv=80,Yv=9;function Xv(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+Jv,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 Zv(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+Jv)*2}function Qv({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>Xv(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(()=>Bv(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=iT(),l=b.useMemo(()=>n.map(t=>Vv(e,t)),[n,e]),u=(0,b.useMemo)(()=>Wv(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:Rv.empty,children:`Constellation will appear when actors are launched.`});let h=Zv(n.length);return(0,x.jsxs)(`div`,{className:Rv.wrap,children:[(0,x.jsx)(Kv,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:Rv.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<Yv&&(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:Rv.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:Rv.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=ve(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:Rv.node,cx:a.cx,cy:a.cy,r:qv,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:Rv.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`?Rv.outcomeSuccess:e.latestOutcome===`failure`?Rv.outcomeFailure:Rv.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:Rv.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:Rv.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${Rv.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:Rv.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:Rv.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:Rv.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:Rv.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function $v(e){return e.length>0?e[e.length-1]:0}function ey(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:$v(t.popHistory),morale:$v(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function ty(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?ey(t,n):null}).filter(e=>e!==null)}function ny(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function ry(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 iy(e,t,n){return[...e].sort((e,r)=>ry(e,r,t,n))}var ay={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`},oy=[{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 sy(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function cy({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(ny(e)),e))},[]),s=(0,b.useMemo)(()=>ty(e),[e]),c=(0,b.useMemo)(()=>iy(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:ay.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:ay.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:ay.scroll,children:(0,x.jsxs)(`table`,{className:ay.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:ay.colorCell}),oy.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":sy(t,i),className:`${ay.th} ${e.numeric?ay.numeric:``} ${t?ay.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:ay.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:ay.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?ve(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${ay.row} ${t?ay.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:ay.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:ay.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:ay.nameCell,children:[(0,x.jsx)(`span`,{className:ay.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:ay.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:ay.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:ay.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.population}),(0,x.jsx)(`td`,{className:ay.numCell,children:(0,x.jsxs)(`span`,{className:ay.moraleWrap,children:[(0,x.jsx)(`span`,{className:ay.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:ay.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:ay.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:ay.numCell,children:n.tools})]},n.id)})})]})})})}function ly(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 uy(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:ly(r,.25),median:ly(r,.5),q3:ly(r,.75),max:r[r.length-1]})}return i}var dy=e=>e.popHistory,fy=e=>e.moraleHistory;function py(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 my(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 hy={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`},gy=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:fy,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:dy}],_y=360,vy=90,yy=8,by=6;function xy({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:hy.empty,role:`status`,children:`No turns recorded yet.`});let r=t??my(e),i=e.map(e=>py(e,r.lo,r.hi)),a=t=>e.length===1?180:yy+t/(e.length-1)*344,o=e=>by+(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:hy.chart,viewBox:`0 0 ${_y} ${vy}`,width:_y,height:vy,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:hy.envelope,d:s}),(0,x.jsx)(`path`,{className:hy.iqr,d:c}),(0,x.jsx)(`path`,{className:hy.median,d:l})]})}function Sy({state:e}){let t=(0,b.useMemo)(()=>gy.map(t=>({def:t,bands:uy(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:hy.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:hy.heading,children:[(0,x.jsx)(`span`,{className:hy.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:hy.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:hy.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:hy.chartWrap,children:[(0,x.jsxs)(`div`,{className:hy.chartHeader,children:[(0,x.jsx)(`span`,{className:hy.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:hy.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)(xy,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var Cy={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 wy(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function Ty({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=ht(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?Cy.dockOverlay:Cy.overlay,p=d?Cy.dock:Cy.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:Cy.head,children:[(0,x.jsx)(`div`,{className:Cy.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:Cy.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:Cy.body,children:[(0,x.jsx)(m_,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:Cy.section,children:[(0,x.jsxs)(`h3`,{className:Cy.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:Cy.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:Cy.decisionItem,children:[(0,x.jsxs)(`div`,{className:Cy.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:Cy.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:Cy.section,children:[(0,x.jsxs)(`h3`,{className:Cy.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:Cy.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:Cy.turnArticle,children:[(0,x.jsxs)(`header`,{className:Cy.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:Cy.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:Cy.turnEvent,children:[(0,x.jsx)(`span`,{className:Cy.turnEventType,children:e.type}),` `,wy(e)]},e.id))})]},e))]})]})]})})}var Ey={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 Dy({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:Ey.introBar,children:[(0,x.jsxs)(`div`,{className:Ey.introBody,children:[(0,x.jsx)(`b`,{className:Ey.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 V8 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:Ey.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:Ey.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function Oy({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,launching:a,interventionArtifact:o,interventionRunning:s,interventionState:c=e,onInterventionDismiss:l,forceLayout:u}){let d=iT(),f=oT();if(o)return(0,x.jsx)(`div`,{className:Ey.root,children:(0,x.jsx)(`div`,{className:Ey.scrollableBody,children:(0,x.jsx)(t_,{artifact:o,state:c,onDismiss:l})})});if(s)return(0,x.jsx)(`div`,{className:Ey.root,children:(0,x.jsx)(`div`,{className:Ey.scrollableBody,children:(0,x.jsx)(s_,{state:c,subject:s.subject,intervention:s.intervention})})});let p=bg(),m=wg(),[h,g]=(0,b.useState)(!1),_=a??h,[v,y]=(0,b.useState)(`side-by-side`),S=(0,b.useRef)(!1),C=(0,b.useCallback)(e=>{S.current=!0,y(e)},[]);(0,b.useEffect)(()=>{S.current||e.actorIds.length>50&&v!==`constellation`&&y(`constellation`)},[e.actorIds.length,v]);let w=u??v,[T,ee]=(0,b.useState)(null),E=T?e.actorIds.indexOf(T):0,D=e.actorIds[0],O=e.actorIds[1],te=D?e.actors[D]:null,k=O?e.actors[O]:null,ne=Object.values(e.actors).some(e=>e.events.length>0),re=e.isRunning&&!ne;(0,b.useEffect)(()=>{(ne||e.isRunning)&&a===void 0&&g(!1)},[ne,e.isRunning,a]);let A=(0,b.useCallback)(()=>{a===void 0&&g(!0),n?.()},[n,a]),j=d.presets.find(e=>e.id==="default"),ie=j?.leaders??j?.actors,ae=(0,b.useMemo)(()=>typeof window>`u`?null:og(window.localStorage),[]),M=ie?.[0]??ae?.[0],oe=ie?.[1]??ae?.[1],N=M?.name?{name:M.name,archetype:M.archetype??``,unit:M.unit??ue(d,0),hexaco:M.hexaco??{},instructions:M.instructions??``,quote:``}:null,se=oe?.name?{name:oe.name,archetype:oe.archetype??``,unit:oe.unit??ue(d,1),hexaco:oe.hexaco??{},instructions:oe.instructions??``,quote:``}:null,[ce,le]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),de=()=>{le(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},fe=te?.event,pe=fe?`T${fe.turn} \u2014 ${fe.time}: ${fe.title}`:``,me=(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]),he=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,ge=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(Ey.flashOn),window.setTimeout(()=>e.classList.remove(Ey.flashOn),1200))},[]),P=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),F=e.isRunning||e.isComplete||ne||t===`connected`;return(0,x.jsxs)(`div`,{className:Ey.root,children:[(0,x.jsxs)(`div`,{className:Ey.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(tn,{verdict:i}):null,w===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Qv,{state:e,onActorClick:e=>ee(e)}),(0,x.jsx)(Sy,{state:e}),(0,x.jsx)(cy,{state:e,onActorClick:e=>ee(e)})]}):e.actorIds.length>=3?(0,x.jsx)(E_,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:pe,toolRegistry:m}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${Ey.leadersRow}`,children:[(0,x.jsx)(m_,{actorIndex:0,leader:te?.leader||N,popHistory:te?.popHistory||[],moraleHistory:te?.moraleHistory||[],verdictPlacement:me(`A`),event:te?.event,statuses:te?.statuses,pendingDecision:te?.pendingDecision}),(0,x.jsx)(m_,{actorIndex:1,leader:k?.leader||se,popHistory:k?.popHistory||[],moraleHistory:k?.moraleHistory||[],verdictPlacement:me(`B`),event:k?.event,statuses:k?.statuses,pendingDecision:k?.pendingDecision})]}),(0,x.jsx)(E_,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:pe,toolRegistry:m})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:Ey.progressBar,children:[(0,x.jsxs)(`span`,{className:Ey.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:Ey.progressTrack,children:(0,x.jsx)(`div`,{className:Ey.progressFill,style:{width:`${he}%`}})}),(0,x.jsxs)(`span`,{className:Ey.progressPercent,children:[Math.round(he),`%`]})]}),ce&&(te?.events.length??0)>0&&(0,x.jsx)(Dy,{onDismiss:de}),re&&!ne&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),_&&!ne&&!e.isRunning&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!ne&&!e.isComplete&&!_&&t===`connecting`&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!ne&&t===`connected`&&!_&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:Ey.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${Ey.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:Ey.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:Ey.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!ne&&t===`connected`&&!_&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:Ey.centerState,children:[(0,x.jsx)(`div`,{className:Ey.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:Ey.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:Ey.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:A,disabled:_||!f,className:Ey.buttonRun,children:_?`Launching…`:f?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:ge,className:Ey.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:P,className:Ey.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:Ey.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:Ey.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:Ey.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${Ey.replayCtaWrap} ${Ey.flashCard}`,children:(0,x.jsx)(Pv,{})})]}),F&&w===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)(av,{state:e}),F&&w===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(mv,{state:e}),(0,x.jsx)(N_,{state:e})]}),(0,x.jsx)(Dv,{citationRegistry:p,toolRegistry:m,layoutToggle:(0,x.jsx)(Lv,{layout:w,actorCount:e.actorIds.length,onChange:C})}),(0,x.jsx)(Mv,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(Ty,{actorName:T,actorIndex:E>=0?E:0,state:e,onClose:()=>ee(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function ky(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 Ay({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=ky(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 jy={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 My(){return(0,x.jsxs)(`div`,{className:jy.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:jy.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:jy.body,children:[(0,x.jsx)(`div`,{className:jy.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:jy.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:jy.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:jy.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:jy.link,children:`Trait-model cookbook`})]})]})]})}var Ny={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`},Py=[{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`}],Fy=[{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 Iy({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:Ny.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:Ny.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Ny.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:Ny.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:Ny.input})]}),(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:Ny.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:Ny.input})]}),(0,x.jsxs)(`div`,{className:Ny.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:Ny.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:Ny.input})]})]}),(0,x.jsxs)(`div`,{className:Ny.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:Ny.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:Ny.textarea})]}),(0,x.jsx)(My,{}),(0,x.jsxs)(`div`,{className:Ny.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:Ny.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${Ny.presetSelect}`,onChange:e=>{let t=Fy.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...`}),Fy.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Ny.hexacoGrid}`,children:Py.map(e=>(0,x.jsx)(Ay,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function Ly(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 Ry(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 zy={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},By={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},Vy={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`},Hy={card:`_card_1vcu2_1`,header:`_header_1vcu2_10`,title:`_title_1vcu2_20`,lead:`_lead_1vcu2_28`,btnRow:`_btnRow_1vcu2_34`,btn:`_btn_1vcu2_34`,amber:`_amber_1vcu2_53`,fileInput:`_fileInput_1vcu2_58`,editorWrap:`_editorWrap_1vcu2_62`,editor:`_editor_1vcu2_62`,statusBar:`_statusBar_1vcu2_83`,seedDetails:`_seedDetails_1vcu2_93`,seedSummary:`_seedSummary_1vcu2_97`,seedBody:`_seedBody_1vcu2_105`,input:`_input_1vcu2_112`,textarea:`_textarea_1vcu2_123`,checkboxLabel:`_checkboxLabel_1vcu2_136`,fineprint:`_fineprint_1vcu2_144`,progressWrap:`_progressWrap_1vcu2_151`,progressRow:`_progressRow_1vcu2_157`,progressStatus:`_progressStatus_1vcu2_166`,result:`_result_1vcu2_170`,actions:`_actions_1vcu2_178`,actionBtn:`_actionBtn_1vcu2_186`,primary:`_primary_1vcu2_203`,spacer:`_spacer_1vcu2_214`,memCount:`_memCount_1vcu2_218`},Uy={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:[]},Wy=`paracosm:editorCompileResult`;function Gy(){try{let e=window.sessionStorage.getItem(Wy);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 Ky(){let[e,t]=(0,b.useState)({adminWrite:!1,memoryScenarios:[]}),[n,r]=(0,b.useState)(``),[i,a]=(0,b.useState)(``),[o,s]=(0,b.useState)(``),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(`5`),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``),[v,y]=(0,b.useState)(!1),[S,C]=(0,b.useState)(!1),[w,T]=(0,b.useState)([]),[D,O]=(0,b.useState)(()=>Gy()),te=(0,b.useRef)(null),k=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t).catch(()=>{});try{window.sessionStorage.removeItem(Wy)}catch{}},[]);let ne=(0,b.useCallback)(()=>{fetch(`/scenario`).then(e=>e.ok?e.json():null).then(e=>{e?.id&&r(JSON.stringify(e,null,2))}).catch(()=>{})},[]);(0,b.useEffect)(()=>(ne(),E(window,ne)),[ne]),(0,b.useEffect)(()=>{if(!n.trim())a(``);else try{JSON.parse(n),a(``)}catch(e){a(String(e).replace(`SyntaxError: `,``))}},[n]);let A=()=>r(JSON.stringify(Uy,null,2)),j=(0,b.useCallback)(async()=>{try{let e=await(await fetch(`/scenario`)).json();r(JSON.stringify(e,null,2)),O({success:!0,message:`Loaded active scenario: ${e.labels?.name||e.id}`})}catch(e){O({success:!1,message:`Failed to load: ${e}`})}},[]),ie=()=>te.current?.click(),ae=e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result;r(e);try{JSON.parse(e),O({success:!0,message:`Imported ${t.name} (${(t.size/1024).toFixed(1)}KB)`})}catch{O({success:!1,message:`Imported ${t.name} but JSON is invalid`})}},n.readAsText(t),e.target.value=``},M=()=>{if(n.trim())try{let e=JSON.parse(n),t=e.id||`scenario`,r=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=`${t}.json`,a.click(),URL.revokeObjectURL(i),O({success:!0,message:`Exported ${t}.json`})}catch{O({success:!1,message:`Fix JSON errors before exporting`})}},oe=(0,b.useCallback)(async()=>{if(n.trim()&&!i){C(!0);try{let e=JSON.parse(n),r=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!1})})).json();r.stored?(ee(window),O({success:!0,message:r.switchable?`Stored "${r.id}" in memory and added it to the scenario selector.`:`Stored "${r.id}" as draft JSON in memory. Compile it to make it runnable and switchable.`}),t(e=>({...e,memoryScenarios:[...new Set([...e.memoryScenarios,r.id])]}))):O({success:!1,message:r.error||`Store failed`})}catch(e){O({success:!1,message:String(e)})}C(!1)}},[n,i]),N=(0,b.useCallback)(async()=>{if(n.trim()&&!i&&e.adminWrite)try{let e=JSON.parse(n),t=``;try{t=localStorage.getItem(`paracosm:adminToken`)??``}catch{}let r={"Content-Type":`application/json`};t&&(r[`X-Admin-Token`]=t);let i=await fetch(`/scenario/store`,{method:`POST`,headers:r,body:JSON.stringify({scenario:e,saveToDisk:!0})}),a=await i.json();a.savedToDisk?(ee(window),O({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.`})):O({success:!1,message:a.error||`Disk write refused (HTTP ${i.status})`})}catch(e){O({success:!1,message:String(e)})}},[n,i,e.adminWrite]),se=(0,b.useCallback)(async()=>{if(!n.trim()||i)return;let e;try{e=JSON.parse(n)}catch{O({success:!1,message:`Fix JSON errors before compiling`});return}y(!0),T([]),O(null);try{let t=Ly({scenario:e,seedText:o,seedUrl:c,webSearch:u,maxSearches:f,provider:m,model:g}),n=await fetch(`/compile`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),r=await Ry(n);if(r!==null){O({success:!1,message:r}),y(!1);return}let i=n.body?.getReader();if(!i)throw Error(`No response stream`);let a=new TextDecoder,s=``;for(;;){let{done:e,value:t}=await i.read();if(e)break;s+=a.decode(t,{stream:!0});let n=s.split(`
|
|
123
|
+
`);s=n.pop()||``;for(let e of n)if(e.startsWith(`data: `))try{let t=JSON.parse(e.slice(6));if(t.hook&&T(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){O({success:!1,message:`Compiled ${t.id}, but switching to it failed: ${e}`});continue}try{window.sessionStorage.setItem(Wy,JSON.stringify({success:!0,message:`Compiled: ${t.id} (${t.departments} departments, ${t.hooks} hooks). Configure actors below and launch.`}))}catch{}re(),window.location.reload();return}t.error&&O({success:!1,message:t.error})}catch{}}}catch(e){O({success:!1,message:String(e)})}y(!1)},[n,i,o,c,u,f,m,g]),ce=n.split(`
|
|
124
|
+
`).length,le=new Blob([n]).size;return(0,x.jsxs)(`div`,{className:Hy.card,children:[(0,x.jsxs)(`div`,{className:Hy.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:Hy.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:Hy.lead,children:[`Write or import a scenario JSON draft. Add seed text or a URL to ground it, then compile or export.`,!e.adminWrite&&` Disk saves are disabled on this instance.`]})]}),(0,x.jsxs)(`div`,{className:Hy.btnRow,children:[(0,x.jsx)(`button`,{onClick:j,className:[Hy.btn,Hy.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:A,className:Hy.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:ie,className:Hy.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:M,className:Hy.btn,disabled:!n.trim()||!!i,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:te,type:`file`,accept:`.json,application/json`,onChange:ae,className:Hy.fileInput})]})]}),(0,x.jsxs)(`div`,{className:Hy.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:k,value:n,onChange:e=>r(e.target.value),placeholder:`{\\n "id": "my-scenario",\\n "labels": { "name": "My World" },\\n "departments": [...]\\n}`,spellCheck:!1,"aria-label":`Scenario JSON editor`,className:Hy.editor}),(0,x.jsxs)(`div`,{className:Hy.statusBar,style:{"--status-color":i?`var(--rust)`:`var(--text-3)`},children:[(0,x.jsx)(`span`,{children:i||(n.trim()?`Valid JSON`:`Empty`)}),(0,x.jsxs)(`span`,{children:[ce,` lines, `,(le/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:Hy.seedDetails,children:[(0,x.jsx)(`summary`,{className:Hy.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:Hy.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:zy,children:`Seed Text`}),(0,x.jsx)(`textarea`,{value:o,onChange:e=>s(e.target.value),placeholder:`Paste a prompt, notes, a brief, or source text to turn into research facts and category mapping.`,className:Hy.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:zy,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:`https://example.com/article`,className:Hy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:zy,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),inputMode:`numeric`,placeholder:`5`,className:Hy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:zy,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),placeholder:`anthropic or openai (optional)`,className:Hy.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:zy,children:`Compile Model Override`}),(0,x.jsx)(`input`,{value:g,onChange:e=>_(e.target.value),placeholder:`gpt-5.4-mini, claude-sonnet-4-6, etc. (optional)`,className:Hy.input})]}),(0,x.jsxs)(`label`,{className:Hy.checkboxLabel,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked)}),`Web search enrichment (requires Serper/Tavily/Firecrawl API keys)`]}),(0,x.jsx)(`p`,{className:Hy.fineprint,children:`If both seed text and a seed URL are provided, the URL takes precedence and the compiler ingests the fetched page.`})]})]}),w.length>0&&(0,x.jsx)(`div`,{className:Hy.progressWrap,children:w.map(e=>(0,x.jsxs)(`div`,{className:Hy.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:Hy.progressStatus,children:e.status})]},e.hook))}),D&&(0,x.jsx)(`div`,{className:Hy.result,style:{"--result-color":D.success?`var(--green)`:`var(--rust)`,"--result-bg":D.success?`rgba(106,173,72,.06)`:`rgba(224,101,48,.06)`},children:D.message}),(0,x.jsxs)(`div`,{className:Hy.actions,children:[(0,x.jsx)(`button`,{onClick:oe,disabled:!n.trim()||!!i||S,className:Hy.actionBtn,"aria-label":`Store scenario in memory`,children:S?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:se,disabled:!n.trim()||!!i||v,className:[Hy.actionBtn,Hy.primary].join(` `),"aria-label":`Compile scenario`,children:v?`Compiling...`:`Compile Scenario`}),e.adminWrite&&(0,x.jsx)(`button`,{onClick:N,disabled:!n.trim()||!!i,className:[Hy.actionBtn,Hy.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:Hy.spacer}),e.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:Hy.memCount,children:[e.memoryScenarios.length,` in memory`]})]})]})}function qy(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``}}function Jy(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=Yy(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!Zy(e,o)||n&&!Xy(e,n))})}function Yy(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Xy(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 Zy(e,t){let n=e.data??{},r=typeof n.name==`string`?n.name.toLowerCase():``;if(r&&r.includes(t))return!0;let i=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let e of i){let n=e&&typeof e==`object`&&typeof e.name==`string`?e.name.toLowerCase():``;if(n&&n.includes(t))return!0}return!1}function Qy(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=Yy(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function $y(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}`:``}function eb(e,t){let n=qy(),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).match(/(?:^|&)log=([^&]+)/);if(l)try{n.toolHash=decodeURIComponent(l[1])}catch{n.toolHash=l[1]}return n}var tb={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 nb(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function rb({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>Qy(e),[e]),i=nb(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:tb.bar,children:[(0,x.jsxs)(`div`,{className:tb.topRow,children:[(0,x.jsxs)(`div`,{className:tb.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:tb.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:tb.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:tb.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:tb.chipClear,onClick:()=>a({toolHash:``}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:tb.resetButton,disabled:!i,onClick:()=>n(qy()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:tb.facetsRow,children:[(0,x.jsx)(`span`,{className:tb.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:tb.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[tb.checkbox,t?tb.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:tb.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:tb.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:tb.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:tb.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:tb.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:tb.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:tb.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:tb.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:tb.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var ib={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`},ab={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 ob(){return typeof window>`u`?eb(``,``):eb(window.location.search,window.location.hash)}function sb({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(ob);(0,b.useEffect)(()=>{let e=()=>i(ob());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=$y(e),r=window.location.pathname,i=t.toolHash!==``&&e.toolHash===``?``:window.location.hash,a=r+n+(i||``);window.history.replaceState({},``,a)}catch{}return e})},[]),s=Jy(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 ${ib.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:ib.header,children:(0,x.jsxs)(`h2`,{className:ib.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(rb,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:ib.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=ab[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:ib.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:ib.eventSummary,children:[(0,x.jsx)(`span`,{className:ib.index,children:t}),(0,x.jsx)(`span`,{className:ib.type,children:e.type}),(0,x.jsx)(`span`,{className:ib.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:ib.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:ib.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:ib.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:ib.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:ib.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var cb=[{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 lb(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`},ub=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],db={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},fb={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)`}]},pb={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`}},mb={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.`}},hb=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function gb(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:hb[e]??`The Strategist`,unit:ue(t,e),instructions:``,hexaco:{...db}}}function _b(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function vb(e,t,n,r,i){let a=_b(n);return e.map((e,o)=>{let s=i[o],c=a?.[o],l=e.unit===ue(t,o);if(!c)return(a!==void 0&&r!==n.id||l)&&s?.unit===void 0?{...e,unit:ue(n,o)}:e;let u=r===n.id&&!!e.unit&&!l;return{name:c.name,archetype:c.archetype,unit:u?e.unit:c.unit??ue(n,o),instructions:c.instructions,hexaco:{...c.hexaco},...s}})}var yb=2,bb=8;function xb({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),Cm(e===`config`?null:e)},[]),a=iT(),o=oT(),s=om(),c=cT(),l=uT(),u=typeof window<`u`?og(window.localStorage):null,[d]=(0,b.useState)(()=>typeof window<`u`?ag(window.localStorage):null),[f,p]=(0,b.useState)(()=>{let e=Math.max(yb,Math.min(bb,Math.max(_b(a)?.length??0,u?.length??0)));return vb(Array.from({length:e},(e,t)=>{let n=u?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??ue(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??db}}:gb(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=>vb(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<bb?[...e,gb(e.length,a)]:e)},[a]),v=(0,b.useCallback)(e=>{m.current.splice(e,1),p(t=>t.length>yb?t.filter((t,n)=>n!==e):t)},[]),[y,S]=(0,b.useState)(a.setup.defaultTurns),[C,w]=(0,b.useState)(a.setup.defaultSeed),[T,ee]=(0,b.useState)(a.setup.defaultStartTime),[D,te]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[k,ne]=(0,b.useState)(a.setup.defaultPopulation),A=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=A.current;e.has(`turns`)||S(a.setup.defaultTurns),e.has(`seed`)||w(a.setup.defaultSeed),e.has(`startTime`)||ee(a.setup.defaultStartTime),e.has(`timePerTurn`)||te(a.setup.defaultTimePerTurn||0),e.has(`population`)||ne(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[j,ie]=(0,b.useState)(`openai`),[ae,M]=(0,b.useState)(!1),[oe,N]=(0,b.useState)(`balanced`),[se,ce]=(0,b.useState)(!1),[le,de]=(0,b.useState)(``),[fe,pe]=(0,b.useState)([]),[me,he]=(0,b.useState)(a.id),[ge,P]=(0,b.useState)({}),[F,_e]=(0,b.useState)(!1),[ye,be]=(0,b.useState)(`local_demo`),[xe,Se]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[I,Ce]=(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(I))}catch{}},[I]);let[we,Te]=(0,b.useState)(pb[j]??pb.openai);(0,b.useEffect)(()=>{let e=j;pb[e]&&Te(pb[e])},[j]);let Ee=!!I.openai||!!I.anthropic,De=!!ge.openai||!!ge.anthropic,Oe=Ee||!F&&De,ke=Ee||!F&&De,Ae=F&&!Ee?`economy`:oe,je=lb(ye),Me=F&&!Ee,Ne=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{pe(e.scenarios||[]),he(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(Ne(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&P(e.keys),typeof e.hostedDemo==`boolean`&&_e(e.hostedDemo),typeof e.serverMode==`string`&&be(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&Se({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),E(window,Ne)),[Ne]);let Pe=async e=>{if(e!==me)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(re(),window.location.reload())}catch{}},Fe=(0,b.useCallback)(async()=>{if(o){ce(!0),de(`Starting...`);try{let e={actors:f.map(e=>({...e,hexaco:e.hexaco})),provider:j,turns:y,seed:C,startTime:T,timePerTurn:D||void 0,population:k,liveSearch:ae,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:Ae},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}ig(window.localStorage,f,a.id),I.openai&&(e.apiKey=I.openai),I.anthropic&&(e.anthropicKey=I.anthropic),I.serper&&(e.serperKey=I.serper),I.firecrawl&&(e.firecrawlKey=I.firecrawl),I.tavily&&(e.tavilyKey=I.tavily),I.cohere&&(e.cohereKey=I.cohere),ke&&(e.models={...we});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){de(`Rate limited: ${n.error||`too many simulations`}`),ce(!1);return}if(n.redirect){l(),de(`Running...`),O(window,n.visitorId);let e=bm(wm(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else de(`Error: ${n.error||`unknown`}`),ce(!1)}catch(e){de(`Failed: ${e}`),ce(!1)}}},[f,y,C,T,D,k,j,ae,c,l,a,o,I,we,ke,Ae]),Ie=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(gm,{options:ub,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(sb,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(Pv,{}),fe.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:zy,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:me,onChange:e=>Pe(e.target.value),children:fe.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===me?`● `:``,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:me})]})]}),(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:je.label}),`. `,je.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)(Iy,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:ve(t),data:e,onChange:e=>g(t,e)}),f.length>yb&&(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<bb?(0,x.jsxs)(`button`,{type:`button`,onClick:_,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,f.length,`/`,bb,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,bb,` 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:By,className:Y.legend,children:`Simulation`}),Me&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,xe.maxTurns,`, population to `,xe.maxPopulation,`, active departments to `,xe.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:zy,children:[`Turns`,Me&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${xe.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,xe.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:Me?xe.maxTurns:y,onChange:e=>{A.current.add(`turns`),S(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:Me,className:Ie(Me),title:Me?`Locked at ${xe.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:zy,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:D,onChange:e=>{A.current.add(`timePerTurn`),te(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:zy,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:C,onChange:e=>{A.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:zy,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:T,onChange:e=>{A.current.add(`startTime`),ee(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:zy,children:[`Population`,Me&&(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:Me?30:k,onChange:e=>{A.current.add(`population`),ne(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:Me,className:Ie(Me),title:Me?`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.jsx)(`label`,{htmlFor:`provider-select`,style:zy,children:`Provider`}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Y.input}`,value:j,onChange:e=>ie(e.target.value),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:zy,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(ae),onChange:e=>M(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:zy,children:[`Economics`,Me&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Ie(Me)}`,value:Ae,onChange:e=>N(e.target.value),disabled:Me,title:cb.find(e=>e.value===Ae)?.description,children:cb.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:cb.find(e=>e.value===Ae)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:By,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:zy,children:[t,ge[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:I[e],onChange:t=>Ce(n=>({...n,[e]:t.target.value})),placeholder:ge[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),Oe&&(j===`openai`||j===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:By,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(mb).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:zy,children:mb[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:we[e],onChange:t=>Te(n=>({...n,[e]:t.target.value})),children:fb[j].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:mb[e].help})]},e))})]}),!Oe&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,F?`Runs against the host API keys are capped to ${xe.maxTurns} turns, ${xe.maxPopulation} colonists, ${xe.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.`]}),(0,x.jsx)(Ky,{}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Fe,disabled:se||!o,"aria-label":se?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:se?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),le&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:le})]})]})]})}function Sb(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 Cb(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:Sb(e.hexaco),instructions:e.instructions})),...t]}var wb={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function Tb(e,t,n,r){let i=Math.max(0,t-e)*wb[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function Eb(e){let t=[];for(let n of e.split(`
|
|
125
|
+
`)){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 Db=new Set([`kernelSnapshotAtStart`,`kernelSnapshotsAfterProgression`]);function Ob(e){let t=e.scenarioExtensions;if(!t||typeof t!=`object`)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>!Db.has(e)));return{...e,scenarioExtensions:n}}function kb(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function Ab(e){let t=e.trajectory?.timepoints?.length??0,n=kb(e),r=Math.max(t,...n);return r>0?r:6}function jb(e,t){return kb(e).includes(t)&&t<Ab(e)}var Mb={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 Nb(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=iT(),u=om(),d=ht(!0),f=Cb(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=Tb(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:Mb.backdrop,onClick:c,children:(0,x.jsxs)(`div`,{ref:d,tabIndex:-1,className:Mb.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Mb.header,children:[(0,x.jsxs)(`h3`,{id:`fork-modal-title`,children:[`Fork at `,u.Time,` `,n]}),(0,x.jsx)(`button`,{type:`button`,className:Mb.closeButton,onClick:c,"aria-label":`Close fork modal`,children:`×`})]}),(0,x.jsxs)(`div`,{className:Mb.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-leader-select`,children:`Override leader`}),f.length===0?(0,x.jsx)(`p`,{className:Mb.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:Mb.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:Mb.hint,children:`Leave blank to resume from the parent's RNG state.`})]}),(0,x.jsxs)(`details`,{className:Mb.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"
|
|
126
|
+
Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:Mb.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:Mb.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:Mb.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:Mb.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()?Eb(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:Mb.confirmButton,children:`Fork`})]})]})})}var Pb=`/retry-stats`;function Fb(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(Pb,{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`},Ib={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 Lb(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function Rb(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function zb(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function Bb(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function Vb({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=ht(!0),c=Fb(!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:Lb(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,Rb(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 ${Lb(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${Lb(-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 (`,Rb(t),` reused / `,Rb(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,Rb(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,Rb(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=Ib[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:Rb(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:Lb(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=zb(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=zb(t.avgAttempts),r=Bb(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:Rb(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:Rb(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:Lb(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:Lb(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,Rb(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:Lb(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,Rb(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:Lb(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,Rb(n.totalTokens),` tok`]})]})]})]})]})})}var Hb={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`},Ub=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],Wb={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},Gb={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function Kb(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function qb(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 Jb({events:e,actorName:t,baselineHexaco:n}){let r=Kb(n),i=qb(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:Hb.card,children:[(0,x.jsxs)(`div`,{className:Hb.headerRow,children:[(0,x.jsx)(`span`,{className:Hb.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:Hb.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`}),Ub.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:Wb[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:Hb.legend,children:Ub.map(e=>(0,x.jsxs)(`span`,{className:Hb.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Hb.legendSwatch,style:{"--trait-color":Wb[e]}}),(0,x.jsx)(`span`,{className:Hb.legendLabel,children:Gb[e]}),(0,x.jsx)(`span`,{className:Hb.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var Yb={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},Xb={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},Zb=[`crisis`,`departments`,`decision`,`outcome`],Qb=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function $b(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function ex(e){return e!==`quotes`}function tx(e){let t=[];for(let n of e??[])$b(n)&&!t.includes(n)&&t.push(n);return t}function nx(e){let t=tx(e.configuredSections),n=t.length>0?t:Zb,r=n.filter(ex);for(let t of Qb)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 rx={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`},ix=[{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 ax(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function ox({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:rx.bar,children:[(0,x.jsx)(`div`,{className:rx.barLeftWrap,children:(0,x.jsx)(`div`,{className:rx.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:rx.barRightWrap,children:(0,x.jsx)(`div`,{className:rx.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function sx(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=Wt(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:Gt(e),a:e.a,b:e.b,text:t=>Kt(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=>ax(e??0,`int`)}]:ix.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>ax(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:rx.section,children:[(0,x.jsxs)(`div`,{className:rx.header,children:[(0,x.jsx)(`div`,{className:rx.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:rx.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:rx.headline,children:r}),i&&(0,x.jsx)(`div`,{className:rx.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:rx.body,children:[(0,x.jsxs)(`div`,{className:rx.bodyHeader,children:[(0,x.jsx)(`span`,{className:rx.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:rx.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Jt(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:rx.statRow,children:[(0,x.jsxs)(`div`,{className:rx.statRowHead,children:[(0,x.jsx)(`span`,{className:rx.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:rx.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:rx.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(ox,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:rx.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:rx.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:rx.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var cx={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function lx(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 ux(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 dx(e,t,n){let r=n??cx[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>ux(e,t))].sort((e,t)=>e-t),a=lx(i,.25),o=lx(i,.75),s=lx(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=ux(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 fx(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=ux(e,n),i=ux(t,n);return cx[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=ux(e,n),i=ux(t,n);return cx[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 px(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=lx([...e.map(e=>ux(e,t))].sort((e,t)=>e-t),.5),r={},i=cx[t]===`higher`?1:-1;for(let a of e){let e=(ux(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function mx(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var hx={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`},gx=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],_x=[`morale`,`population`,`deaths`,`tools`],vx=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function yx({state:e}){let t=(0,b.useMemo)(()=>ty(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>gx.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:dx(t,e)})),[t]),r=(0,b.useMemo)(()=>fx(t,_x),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>vx.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:px(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:hx.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:hx.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:hx.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:hx.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:hx.section,children:[(0,x.jsx)(`h4`,{className:hx.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:hx.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:hx.quartileBlock,children:[(0,x.jsxs)(`div`,{className:hx.metricHead,children:[(0,x.jsx)(`span`,{className:hx.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:hx.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:hx.quartileRow,children:[(0,x.jsx)(`span`,{className:hx.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:hx.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${hx.actorPill} ${hx.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:hx.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:hx.quartileRow,children:[(0,x.jsx)(`span`,{className:hx.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:hx.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${hx.actorPill} ${hx.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:hx.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:hx.section,children:[(0,x.jsx)(`h4`,{className:hx.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:hx.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:hx.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:hx.paretoItem,children:[(0,x.jsx)(`span`,{className:hx.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:hx.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:hx.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:hx.section,children:[(0,x.jsx)(`h4`,{className:hx.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:hx.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:hx.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:hx.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:hx.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:hx.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:hx.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:hx.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:hx.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:hx.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?hx.deltaPositive:n<0?hx.deltaNegative:hx.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${hx.medianMetricCol} ${r}`,role:`cell`,children:[mx(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function bx(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 xx(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var Sx=[{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 Cx(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 wx(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 Sx.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?Cx(a,e.id):[],b:o?Cx(o,e.id):[]}))}function Tx(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 Sx.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?Cx(t.events,e.id):[]}))}))}function Ex(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:xx(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}}})}function Dx(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 Ox=`(max-width: 768px)`,kx=`(max-width: 480px)`,Ax=`(prefers-reduced-motion: reduce)`,jx={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`},Mx={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},Nx={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function Px(e,t=!1){return e?t?Nx[e]??`·`:Mx[e]??e.replace(/_/g,` `).toUpperCase():`·`}function Fx({outcome:e,sideColor:t,compact:n}){let r=bx(e);return(0,x.jsx)(`div`,{className:jx.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:Px(e,n)})}function Ix(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=Dx(kx);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:jx.section,children:[(0,x.jsx)(`div`,{className:jx.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:jx.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:[jx.cell,e.diverged?jx.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:jx.cellHead,children:[(0,x.jsxs)(`span`,{className:jx.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(Fx,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(Fx,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:jx.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var Lx={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 Rx(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 zx(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 Bx({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:Lx.card,children:[(0,x.jsxs)(`div`,{className:Lx.cardHeader,children:[(0,x.jsx)(`span`,{className:Lx.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:Lx.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:Lx.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=zx(n);return(0,x.jsxs)(`span`,{className:Lx.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:Lx.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:Rx(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:Lx.card,children:[(0,x.jsxs)(`div`,{className:Lx.cardHeader,children:[(0,x.jsx)(`span`,{className:Lx.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:Lx.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:Lx.cardFooter,children:[(0,x.jsx)(`span`,{className:Lx.lastA,children:h==null?`·`:Rx(h,e.unit)}),(0,x.jsx)(`span`,{className:Lx.lastB,children:g==null?`·`:Rx(g,e.unit)})]})]})}function Vx(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:Lx.section,style:c,children:[(0,x.jsxs)(`div`,{className:Lx.sectionHeader,children:[(0,x.jsx)(`span`,{className:Lx.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:Lx.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:Lx.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:Lx.legendCohortSlot,"aria-hidden":`true`,children:zx(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:Lx.legend,children:[(0,x.jsx)(`span`,{className:Lx.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:Lx.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Lx.grid}`,children:s.map(e=>(0,x.jsx)(Bx,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function Hx(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 Ux(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=Hx(`(min-width: 1024px)`,!0),o=Hx(`(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 Wx(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 Gx(){return{events:new Map,reactions:[],totalReactions:0}}function Kx(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 qx(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=Gx(),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=Kx(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=Kx(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=Kx(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=Kx(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 Jx(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function Yx({state:e,verdict:t,reportSections:n}){let r=bg(),i=wg(),[a,o]=Wx(`paracosm-reports-refs-open`,!1),[s,c]=Wx(`paracosm-reports-tools-open`,!1),[l,u]=(0,b.useState)(!1),{state:d,dispatch:f}=gn(),p=cT(),m=uT(),h=om(),[g,_]=(0,b.useState)(null),v=d.parent,y=iT(),S=oT(),C=v?.metadata?.scenario,w=typeof C?.id==`string`&&C.id!==y.id,T=(0,b.useCallback)(t=>!v||e.isRunning||!S||w?!1:jb(v,t),[v,e.isRunning,S,w]),ee=(0,b.useCallback)(async e=>{_(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;f({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=Ab(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:Ob(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));f({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));O(window,a.visitorId),m(),p(`studio`)}catch(e){f({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[f,p,m]),E=e.actorIds[0]??null,D=e.actorIds[1]??null,[te,k]=(0,b.useState)(E),[ne,re]=(0,b.useState)(D);(0,b.useEffect)(()=>{te&&!e.actorIds.includes(te)&&k(E),ne&&!e.actorIds.includes(ne)&&re(D)},[e.actorIds,te,ne,E,D]);let A=te??E,j=ne??D,ie=e.actorIds.length>2,[ae,M]=(0,b.useState)(!ie);(0,b.useEffect)(()=>{M(!ie)},[ie]);let oe=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,qx(e.actors[n]?.events));return t},[e]),N=(0,b.useMemo)(()=>{let e=A&&oe.get(A)||new Map,t=j&&oe.get(j)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??Gx(),b:t.get(n)??Gx()}])},[oe,A,j]),se=(0,b.useMemo)(()=>{if(!ie)return[];let t=new Set;for(let e of oe.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,oe.get(r)?.get(t)??Gx());return[t,n]})},[ie,oe,e.actorIds]),ce=A,le=j,ue=ce?e.actors[ce]:null,de=le?e.actors[le]:null,fe=ue?.leader?.name||`Leader A`,pe=de?.leader?.name||`Leader B`,me=(ue?.events.some(e=>e.type===`personality_drift`)??!1)||(de?.events.some(e=>e.type===`personality_drift`)??!1),he=N.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),ge=N.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),P=(0,b.useMemo)(()=>nx({configuredSections:n,hasQuotes:he,hasCausality:ge,hasVerdict:!!t,hasTrajectories:me,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:i.list.length>0,hasReferences:r.list.length>0}),[n,he,ge,t,me,e.cost,i.list.length,r.list.length]),F=(0,b.useMemo)(()=>Ex(N),[N]),_e=(0,b.useMemo)(()=>wx(e,A,j),[e,A,j]),ye=(0,b.useMemo)(()=>ie?Tx(e,ve):null,[ie,e]),be=(0,b.useMemo)(()=>{let e=[];F.length>0&&e.push({id:`strip`,label:`Strip`}),_e.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),me&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of N)e.push({id:`turn-${t}`,label:`Turn ${t}`});return i.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),r.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,F.length,_e,me,N,i.list.length,r.list.length]),xe=(0,b.useRef)(null),Se=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{Se.current&&xe.current&&N.length>0&&xe.current.scrollTo({top:xe.current.scrollHeight,behavior:`smooth`})},[N.length]),!(ue?.events.length??0)&&!(de?.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:xe,onScroll:()=>{let e=xe.current;e&&(Se.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[S&&w&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,C?.name??C?.id,`, and a fork runs in its parent's scenario. Switch to `,C?.name??C?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&N.length===0)return null;let i=N.length,a=N[N.length-1],o=N[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=ue?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=de?.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":Jx(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`})]}),ie&&(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:ae,onChange:e=>M(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),ae?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:A??``,onChange:e=>k(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===j,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:j??``,onChange:e=>re(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===A,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.`]})]}),(!ie||ae)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(Ix,{turns:F,leaderAName:fe,leaderBName:pe})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!ie||ae?(0,x.jsx)(Vx,{metrics:_e,leaderAName:fe,leaderBName:pe}):ye&&(0,x.jsx)(Vx,{metrics:ye,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[me&&ae&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(Jb,{events:ue?.events??[],actorName:fe,baselineHexaco:ue?.leader?.hexaco}),(0,x.jsx)(Jb,{events:de?.events??[],actorName:pe,baselineHexaco:de?.leader?.hexaco})]}),me&&!ae&&(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)(Jb,{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:()=>u(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),l&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(Vb,{combined:e.cost,leaderA:(ce?e.costByActor[ce]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(le?e.costByActor[le]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ue?.leader?.name,leaderBName:de?.leader?.name,actors:ie?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:()=>u(!1)}),!ie&&N.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`}),T(e)&&(0,x.jsxs)(`button`,{type:`button`,className:Mb.forkButton,onClick:()=>_(e),"aria-label":`Fork at ${h.time} ${e}`,children:[`↳ Fork at `,h.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)(Zx,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:fe,sideColor:`var(--vis)`,sections:P.eventSections}),(0,x.jsx)(Zx,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:pe,sideColor:`var(--eng)`,sections:P.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(Qx,{data:n,name:fe,sideColor:`var(--vis)`,showQuotes:P.footerSections.includes(`quotes`)}),(0,x.jsx)(Qx,{data:r,name:pe,sideColor:`var(--eng)`,showQuotes:P.footerSections.includes(`quotes`)})]})]},e)}),ie&&se.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`}),T(t)&&(0,x.jsxs)(`button`,{type:`button`,className:Mb.forkButton,onClick:()=>_(t),"aria-label":`Fork at ${h.time} ${t}`,children:[`↳ Fork at `,h.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)(Zx,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:P.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)(Qx,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:P.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:i.list.length>0&&(0,x.jsx)(Cv,{registry:i,title:`Forged Toolbox`,collapsible:!0,defaultOpen:s,onToggle:c})}),(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)(sx,{verdict:t,leaderAName:fe,leaderBName:pe}),(0,x.jsx)(yx,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(tn,{verdict:t})})]}),(0,x.jsx)(`section`,{id:`references`,children:r.list.length>0&&(0,x.jsx)(xv,{registry:r,title:`References`,collapsible:!0,defaultOpen:a,onToggle:o})}),(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:P.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:Yb[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:P.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:Xb[e]},e))})]})]})]})]}),(0,x.jsx)(Ux,{items:be,scrollRoot:xe.current}),g!==null&&v&&(0,x.jsx)(Nb,{parentArtifact:v,atTurn:g,maxTurns:Ab(v),costPreset:`economy`,provider:`openai`,onConfirm:ee,onClose:()=>_(null)})]})}var Xx={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Zx({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)(F_,{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)(L_,{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 Qx({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":Xx[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`},$x={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function eS(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function tS({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":eS(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 nS({state:e,onChatUsage:t}){let n=iT(),[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 ee=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),E=ee.find(e=>e.name===r),D=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},O=e=>{let t=D(e);return t?`${t}\u0000${e}`:e},te=r?a.get(O(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[te,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&ee.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[ee]);let k=e=>{i(e);let t=O(e);o(n=>{if(n.has(t))return n;let r=ee.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})},ne=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},re=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},A=async()=>{if(!l.trim()||!r||d)return;let e=r,n=D(e),i=O(e),a=l.trim();u(``),f(!0),ne(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];re(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){ne(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),re(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ne(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ne(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:ee.length?`${ee.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:ee.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)})]})]}),ee.map(e=>(0,x.jsxs)(`button`,{onClick:()=>k(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":$x[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[E?.memory&&(E.memory.beliefs?.length>0||E.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),E.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),E.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&&E?.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=E.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 E.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(E.psychScore*100).toFixed(0),`%`]}),typeof E.boneDensity==`number`&&E.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,E.boneDensity.toFixed(0),`%`]}),typeof E.radiation==`number`&&E.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":E.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,E.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":E?.name?`Messages with ${E.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:ee.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:ee.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&&E?.memory&&(0,x.jsx)(tS,{memory:E.memory,events:e,scenario:n}),te.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":`${E?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:E?.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`&&A(),disabled:!r||d,"aria-label":r?`Message ${E?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${E?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:A,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_hm7af_2`,kbdKey:`_kbdKey_hm7af_8`,kbdLabel:`_kbdLabel_hm7af_18`,empty:`_empty_hm7af_22`,emptySpinner:`_emptySpinner_hm7af_34`,emptySpinnerRotate:`_emptySpinnerRotate_hm7af_1`,root:`_root_hm7af_54`,toolbarStrip:`_toolbarStrip_hm7af_62`,toolbarTopRow:`_toolbarTopRow_hm7af_71`,modePillsWrap:`_modePillsWrap_hm7af_78`,overflowToggle:`_overflowToggle_hm7af_83`,overflowToggleOpen:`_overflowToggleOpen_hm7af_97`,helpBtn:`_helpBtn_hm7af_102`,toolsRow:`_toolsRow_hm7af_118`,paletteBtn:`_paletteBtn_hm7af_127`,toolBtn:`_toolBtn_hm7af_141`,settingsBtn:`_settingsBtn_hm7af_154`,settingsBtnOpen:`_settingsBtnOpen_hm7af_167`,modeHint:`_modeHint_hm7af_172`,diffLine:`_diffLine_hm7af_180`,phoneTabRow:`_phoneTabRow_hm7af_189`,phoneTab:`_phoneTab_hm7af_189`,phoneTabActive:`_phoneTabActive_hm7af_216`,leadersRow:`_leadersRow_hm7af_222`,leadersRowNarrow:`_leadersRowNarrow_hm7af_231`,sideWrap:`_sideWrap_hm7af_236`,sideWrapHidden:`_sideWrapHidden_hm7af_243`,footerKeys:`_footerKeys_hm7af_247`,srOnly:`_srOnly_hm7af_260`,jumpLatest:`_jumpLatest_hm7af_272`,"paracosm-jump-pulse":`_paracosm-jump-pulse_hm7af_1`,jumpLatestBehind:`_jumpLatestBehind_hm7af_295`,toast:`_toast_hm7af_300`,"paracosm-toast-in":`_paracosm-toast-in_hm7af_1`,toastKicker:`_toastKicker_hm7af_321`,toastKickerMeta:`_toastKickerMeta_hm7af_333`,toastBody:`_toastBody_hm7af_337`,toastBodyMd:`_toastBodyMd_hm7af_342`,vignette:`_vignette_hm7af_347`,"paracosm-vignette":`_paracosm-vignette_hm7af_1`,cohortViewBar:`_cohortViewBar_hm7af_363`,cohortViewModeToggle:`_cohortViewModeToggle_hm7af_374`,cohortViewModeButton:`_cohortViewModeButton_hm7af_383`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_hm7af_414`,cohortPairPicker:`_cohortPairPicker_hm7af_423`,cohortPairPickerLabel:`_cohortPairPickerLabel_hm7af_431`,cohortPairPickerSelect:`_cohortPairPickerSelect_hm7af_440`,cohortPairPickerVs:`_cohortPairPickerVs_hm7af_463`,cohortPairPickerHint:`_cohortPairPickerHint_hm7af_471`};function rS(e){return(0,b.useMemo)(()=>{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)}}for(let e=0;e<r.agentSnapshots.length;e++){let a=r.agentSnapshots[e],o=r.events.find(t=>t.type===`systems_snapshot`&&t.data?.turn===e+1)?.data||{},s=o.turn||e+1,c=a.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:s,time:o.time||0,cells:c,population:o.population||c.filter(e=>e.alive).length,morale:o.morale||0,foodReserve:typeof o.foodReserve==`number`?o.foodReserve:void 0,deaths:o.deaths||0,births:o.births||0,eventCategories:i.get(s)??[]})}}return t},[e])}var iS={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 aS(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 oS(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 sS(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 cS(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function lS(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 uS(e,t,n){let r=lS(t,n,cS(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=aS(oS(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,sS(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function dS(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=aS(oS(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,sS(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=aS(oS(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,sS(o,c,t,n))}),r}function fS(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=aS(oS(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,sS(s,c,t,n))}return i}function pS(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=aS(oS(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,sS(o,s,t,n))}return r}function mS(e,t,n,r){return t===`families`?dS(e,n,r):t===`mood`?fS(e,n,r):t===`age`?pS(e,n,r):uS(e,n,r)}function hS(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 gS={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)`},_S=6;function vS(e,t){e.save();for(let n of t){let t=gS[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<_S;t++){let r=t/_S*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 yS={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 bS(e){return yS[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function xS(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=bS(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=bS(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 SS(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,TS(i,d)),f.addColorStop(.6,TS(i,d*.4)),f.addColorStop(1,TS(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=TS(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 CS(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=t,s=a(o.foodReserve),c=a(o.waterLitersPerDay),l=a(o.powerKw),u=a(o.pressurizedVolumeM3);if(s==null&&c==null&&l==null&&u==null)return;let d=(e,t,n)=>e==null?0:e<=t?1:e>=n?0:1-(e-t)/(n-t),f=d(s,3,18),p=d(c,200,1200),m=d(l,150,600),h=d(u,1500,4e3),g=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})`,_=n/2,v=r/2;e.save(),e.fillStyle=g(f),e.fillRect(0,0,_,v),e.fillStyle=g(p),e.fillRect(_,0,_,v),e.fillStyle=g(m),e.fillRect(0,v,_,v),e.fillStyle=g(h),e.fillRect(_,v,_,v),e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,s!=null&&e.fillText(`FOOD ${s.toFixed(1)}mo`,8,8),c!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(c)}L/d`,n-8,8)),l!=null&&(e.textAlign=`left`,e.textBaseline=`bottom`,e.fillText(`POWER ${Math.round(l)}kW`,8,r-8)),u!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(u)}m³`,n-8,r-8)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function wS(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 TS(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 ES(){return{items:[]}}function DS(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function OS(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 kS(e){return e.items}function AS(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 jS=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function MS(e,t,n,r){let i=(0,b.useRef)(ES()),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=Dx(Ax);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}=AS(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&DS(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&&DS(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(!jS.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),DS(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&&DS(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&&DS(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,OS(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:kS(i.current),tickClock:o}}function NS(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 PS={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function FS(e){return PS[(e||``).toLowerCase()]??`#a89878`}function IS({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:FS(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 LS={"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 V8 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.`},RS={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 zS({snapshot:e,sideColor:t}){let n=Dx(Ox),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:[RS.strip,n?RS.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[RS.col,RS.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:RS.rowBaseline,children:[(0,x.jsx)(`span`,{className:RS.label,title:LS[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:RS.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:RS.bar,children:(0,x.jsx)(`div`,{className:RS.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:RS.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:RS.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:RS.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:RS.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:RS.col,children:[(0,x.jsxs)(`div`,{className:RS.moodHeader,children:[(0,x.jsx)(`span`,{className:RS.label,title:LS[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:RS.value2,title:LS[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:RS.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:RS.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:RS.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:RS.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:RS.col,children:[(0,x.jsx)(`div`,{className:RS.label,title:LS[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:RS.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:RS.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:RS.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:RS.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:[RS.col,RS.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:RS.row,children:[(0,x.jsx)(`span`,{className:RS.label,title:LS[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:RS.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:RS.row,children:[(0,x.jsx)(`span`,{title:LS[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:RS.value2,children:d})]}),(0,x.jsxs)(`div`,{className:RS.row,children:[(0,x.jsx)(`span`,{title:LS[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:RS.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:RS.deptBlock,"aria-label":`Department breakdown`,title:LS[`stat.depts`],children:[(0,x.jsx)(IS,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:RS.deptLabel,children:`Depts`})]})]})}var BS={cols:12,rows:6,seedRadius:2},VS=[[1,0],[2,1],[0,2],[1,2],[2,2]],HS=[[0,1],[1,1],[2,1]],US=[[0,0],[1,0],[0,1],[1,1]],WS=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],GS=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],KS=[[1,0],[2,0],[0,1],[1,1],[1,2]];function qS(e){switch(e){case`positive`:case`hopeful`:return US;case`neutral`:return WS;case`anxious`:return HS;case`resigned`:return GS;case`defiant`:case`negative`:return VS;default:return HS}}function JS(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 YS(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 XS(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 ZS(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 QS(e){switch(e){case`birth`:return US;case`forge`:return VS;case`crisis`:return KS;case`death`:return[];default:return null}}function $S(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function eC(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=QS(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??qS(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 tC(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=US;break;case`forge_approved`:l=VS;break;case`forge_rejected`:l=HS;break;case`reuse`:l=GS;break;case`crisis`:l=KS;break;default:l=HS}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 nC(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 rC(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 iC(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 aC=[`O`,`C`,`E`,`A`,`Em`,`HH`];function oC(e,t){let n=t/2,r=t/2,i=t/2-8;return aC.map((t,a)=>{let o=Math.PI*2*a/aC.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 sC(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/aC.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function cC({profile:e,colonyMean:t,size:n=160}){let r=oC(e,n),i=t?oC(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)),aC.map((e,t)=>{let r=sC(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 lC={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`},uC={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function dC(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])=>`${uC[e]} ${t.toFixed(2)}`).join(` · `)}function fC(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=Dx(kx);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:lC.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:lC.popover,style:C,children:[(0,x.jsxs)(`div`,{className:lC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:lC.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:lC.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:lC.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:lC.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:lC.section,children:(0,x.jsxs)(`div`,{className:lC.statsGrid,children:[(0,x.jsx)(`span`,{className:lC.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:lC.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:lC.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:lC.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:lC.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:lC.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:lC.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:lC.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:lC.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:lC.statValue,children:y}),(0,x.jsx)(`span`,{className:lC.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:lC.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:lC.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:lC.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:lC.section,children:[(0,x.jsx)(`div`,{className:lC.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:lC.hexacoRow,children:[(0,x.jsx)(`div`,{className:lC.hexacoRadarWrap,children:(0,x.jsx)(cC,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:lC.hexacoTopAxes,children:dC(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:lC.section,children:[(0,x.jsx)(`div`,{className:lC.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:lC.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:lC.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:lC.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:lC.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var pC={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`},mC={animSpeed:1,deptRings:!1,deptLabels:!1,lines:!1,dust:!0,crosshair:!0,ghostTrail:!1,alerts:!0,sound:!1};function hC({open:e,settings:t,onChange:n,onClose:r}){let i=ht(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:pC.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:pC.drawer,children:[(0,x.jsxs)(`div`,{className:pC.header,children:[(0,x.jsx)(`span`,{style:By,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:pC.closeBtn,children:`×`})]}),(0,x.jsx)(gC,{label:`Animation speed`,children:[.5,1,2].map(e=>(0,x.jsx)(_C,{active:t.animSpeed===e,onClick:()=>a(`animSpeed`,e),label:`${e}x`},e))}),(0,x.jsxs)(gC,{label:`Dept rings`,children:[(0,x.jsx)(_C,{active:t.deptRings,onClick:()=>a(`deptRings`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.deptRings,onClick:()=>a(`deptRings`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Dept labels`,children:[(0,x.jsx)(_C,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Family lines`,children:[(0,x.jsx)(_C,{active:t.lines,onClick:()=>a(`lines`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.lines,onClick:()=>a(`lines`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Star dust bg`,children:[(0,x.jsx)(_C,{active:t.dust,onClick:()=>a(`dust`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.dust,onClick:()=>a(`dust`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Crosshair`,children:[(0,x.jsx)(_C,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Ghost trail`,children:[(0,x.jsx)(_C,{active:t.ghostTrail,onClick:()=>a(`ghostTrail`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.ghostTrail,onClick:()=>a(`ghostTrail`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Alert toasts`,children:[(0,x.jsx)(_C,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(gC,{label:`Sound cues`,children:[(0,x.jsx)(_C,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(_C,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(mC),style:Vy,className:pC.resetBtn,children:`Reset defaults`})]})]})}function gC({label:e,children:t}){return(0,x.jsxs)(`div`,{className:pC.row,children:[(0,x.jsx)(`span`,{style:zy,className:pC.rowLabel,children:e}),(0,x.jsx)(`div`,{className:pC.pillRow,children:t})]})}function _C({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[pC.pill,e?pC.pillActive:``].filter(Boolean).join(` `),children:n})}var vC={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`},yC={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)`},bC=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function xC({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=om(),{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:vC.drawer,children:[(0,x.jsxs)(`div`,{className:vC.header,style:v,children:[(0,x.jsxs)(`span`,{className:vC.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:vC.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:vC.sortRow,children:bC.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[vC.sortChip,t?vC.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:vC.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:vC.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:vC.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:vC.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:vC.swatch,style:{"--swatch-bg":yC[e.mood]??yC.neutral}}),(0,x.jsx)(`span`,{className:vC.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:vC.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:vC.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:[vC.row,vC.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:vC.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:vC.rowName,children:e.name})]},e.agentId)})]})]})]})}function SC({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 CC(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 wC(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=mC,focusedSide:T=null,onToggleFocus:ee,onOpenChat:E,eventFilter:D=`all`,chronicleHover:O=null,isLiveRun:te=!0}=e,k=T===c,ne=Dx(Ox),re=Dx(Ax),A=om(),j=(0,b.useRef)(null),ie=(0,b.useRef)(null),ae=(0,b.useRef)(null),[M,oe]=(0,b.useState)({w:0,h:0}),[N,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,pe]=(0,b.useState)(!1),[me,he]=(0,b.useState)(null),[ge,P]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(re){P(!0);return}let e=requestAnimationFrame(()=>P(!0));return()=>cancelAnimationFrame(e)},[re]);let F=(0,b.useRef)($S(BS.cols,BS.rows)),_e=(0,b.useRef)(-1),ve=(0,b.useRef)(``),ye=(0,b.useRef)(``),be=(0,b.useRef)(null),xe=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=ie.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(1,Math.round(t.contentRect.width)),n=Math.max(1,Math.round(t.contentRect.height));oe(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ae.current;if(!e||M.w===0||M.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(M.w*t),e.height=Math.round(M.h*t),e.style.width=`${M.w}px`,e.style.height=`${M.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[M.w,M.h]);let Se=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),I=(0,b.useMemo)(()=>!t||M.w===0?new Map:mS(t.cells,Se,M.w,M.h),[t,Se,M.w,M.h]),Ce=(0,b.useMemo)(()=>t?NS(t.cells,I):new Map,[t,I]),we=MS({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},ie,()=>I,()=>Ce),Te=f===`forge`?.7:f===`ecology`?0:1,Ee=(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=ae.current;if(!e||!t)return;let r=e.getContext(`2d`);if(!r)return;let c=we.flares.filter(e=>D===`all`?!0:D===`birth`?e.kind===`birth`:D===`death`?e.kind===`death`:D===`crisis`?e.kind===`crisis`:D!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=CC(s,j.current),d=j.current?getComputedStyle(j.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)`,ee=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,M.w,M.h);let E=F.current,O=f!==ve.current,k=t.turn!==_e.current,ne=D!==ye.current;if(k||O||ne){_e.current=t.turn,ve.current=f,ye.current=D,eC(E,t.cells,I,M.w,M.h,D);let e;e=re?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)nC(E);be.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!==be.current&&(be.current=e,tC(E,c[0],M.w,M.h),re||nC(E))}let ie=typeof document<`u`&&document.documentElement.classList.contains(`light`);if(te&&rC(r,E,M.w,M.h,u,ie?.22:.65),D===`death`?YS(r,t.cells,I,M.w,M.h,BS.cols,BS.rows,C,T):D===`birth`&&JS(r,t.cells,I,M.w,M.h,BS.cols,BS.rows),vS(r,c),f!==`ecology`&&hS(r,t.cells,I,u,Te,_,f===`divergence`,re?0:performance.now(),S,!0,g,te?m:`transparent`),f===`forge`&&h&&h.length>0&&SS(r,t.cells,I,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&CS(r,t,M.w,M.h,ee),f===`divergence`&&wS(r,t.cells,I,_,re?0:performance.now(),u),xS(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:M.w,height:M.h,lagTurns:l,cells:t.cells,positions:I,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:A.Time}),N){let e=I.get(N.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(ce&&!N&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,ce.y),r.lineTo(M.w,ce.y),r.moveTo(ce.x,0),r.lineTo(ce.x,M.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=I.get(n.agentId);if(!t)continue;let r=t.x-ce.x,i=t.y-ce.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(ce.x,ce.y),r.lineTo(ce.x+e.dx,ce.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]}`,ce.x+6,ce.y+6),r.restore())}if(v&&v!==N?.cell.agentId){let e=I.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())}},[we.tickClock,t,I,M.w,M.h,s,i,l,we.flares,f,Te,N,_,v,re,S,ce,w,a,o,h,D,te]);let De=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;le({x:r,y:i});let a=iC(t.cells,I,r,i);if(a){se(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),he(null),y?.(a.agentId);return}N&&(se(null),y?.(null));let o=BS.cols,s=BS.rows,c=D===`death`||D===`birth`?(()=>{let e=Math.floor(r/Math.max(1,M.w)*o),n=Math.floor(i/Math.max(1,M.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(D===`death`&&r.alive||D===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=I.get(r.agentId);if(!t)continue;let i=ZS(t,M.w,M.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:D===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=XS(F.current,r,i,M.w,M.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=I.get(r.agentId);if(!t)continue;let i=ZS(t,M.w,M.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?he({x:r,y:i,...c}):me&&he(null)},[t,I,N,y,D,M.w,M.h,me]),Oe=(0,b.useCallback)(()=>{se(null),he(null),le(null),y?.(null)},[y]),ke=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=iC(t.cells,I,r,i);a?(de({cell:a,x:r,y:i}),se(null),he(null),xe.current={id:a.agentId,intensity:1}):me?.nearest&&(de({cell:me.nearest,x:r,y:i}),se(null),he(null))},[t,I,me]),Ae=(0,b.useRef)(null),je=(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=iC(t.cells,I,i,a);o?Ae.current===o.agentId?(de({cell:o,x:i,y:a}),se(null),Ae.current=null,xe.current={id:o.agentId,intensity:1}):(se({cell:o,x:i,y:a}),le({x:i,y:a}),Ae.current=o.agentId,y?.(o.agentId)):(se(null),le(null),Ae.current=null,y?.(null))},[t,I,y]);(0,b.useEffect)(()=>{ue&&t&&(t.cells.find(e=>e.agentId===ue.cell.agentId)||de(null))},[ue,t]),(0,b.useEffect)(()=>{ue||(Ae.current=null)},[ue]);let Me=CC(f===`mood`?Ee:s,j.current),Ne={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)`},Pe={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)`},Fe=O&&O.side===c?Ne[O.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`,Ie=O&&O.side===c?`0 0 24px ${Pe[O.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:j,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${A.place} viz`,className:[iS.region,ne?iS.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(zS,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:ie,className:iS.canvasWrap,style:{"--tint-color":te?Me:`transparent`,"--wrap-border":Fe,"--wrap-glow":Ie},children:[(0,x.jsx)(`canvas`,{ref:ae,role:`img`,"aria-label":t?`${i} ${A.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${typeof t.foodReserve==`number`?`, food reserve ${t.foodReserve.toFixed(1)} months`:``}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${A.person} glyph for drilldown.`:`${i} ${A.place} — waiting for first turn.`,onMouseMove:De,onMouseLeave:Oe,onClick:ke,onTouchStart:je,className:iS.canvas,style:{"--canvas-cursor":N?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:iS.revealCover,style:{"--reveal-opacity":ge?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>pe(e=>!e),"aria-label":fe?`Close roster`:`Open roster`,title:fe?`Close roster`:`Open roster`,className:iS.cornerBtn,style:{"--right-offset":ee?`36px`:`8px`,"--btn-color":fe?`var(--amber)`:`var(--text-3)`,"--btn-border":fe?`var(--amber)`:`var(--border)`},children:`☰`}),ee&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>ee(c),"aria-label":k?`Restore split view`:`Focus this panel`,title:k?`Restore split view`:`Focus this panel`,className:`${iS.cornerBtn} ${iS.focusBtn}`,style:{"--btn-color":k?`var(--amber)`:`var(--text-3)`,"--btn-border":k?`var(--amber)`:`var(--border)`},children:k?`⤡`:`⤢`}),(0,x.jsx)(SC,{snapshot:t,previousSnapshot:n,sideColor:CC(s,j.current),onSelect:e=>{let t=I.get(e.agentId);t&&de({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(xC,{open:fe,cells:t?.cells??[],actorName:i,sideColor:CC(s,j.current),searchQuery:S,hoveredId:N?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?I.get(e):null;if(n&&r){se({cell:n,x:r.x,y:r.y}),y?.(e);return}}se(null),y?.(null)},onSelect:e=>{let t=I.get(e.agentId);t&&de({cell:e,x:t.x,y:t.y})},onClose:()=>pe(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:iS.divergenceEmpty,children:(0,x.jsx)(`div`,{className:iS.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),me&&!N&&!ue&&(()=>{let e=Math.min(Math.max(8,me.x+12),Math.max(8,M.w-220-8)),t=Math.max(8,me.y-84),n=me.kind===`birth`?`+ BIRTH MARKER`:me.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=me.kind===`birth`?`rgba(154, 205, 96, 0.95)`:me.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:iS.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:iS.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:iS.tileCoords,children:[`tile (`,me.col,`, `,me.row,`)`]}),me.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:iS.tileNearestName,children:me.nearest.name}),(0,x.jsxs)(`div`,{className:iS.tileNearestRole,children:[me.nearest.role,` · `,me.nearest.department.toUpperCase()]}),me.kind===`death`?(0,x.jsxs)(`div`,{className:iS.tileNearestDeath,children:[`deceased · mood at death: `,me.nearest.mood]}):me.kind===`birth`?(0,x.jsxs)(`div`,{className:iS.tileNearestBirth,children:[`native-born · generation `,me.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:iS.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,me.nearest.mood]})]}):(0,x.jsx)(`div`,{className:iS.tileAmbient,children:`ambient CA cell`}),me.kind===`life`&&(()=>{let e=F.current,t=e.cols,n=e.rows,r=e.grid[me.row*t+me.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=me.row+r,s=me.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:iS.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),N&&!ue&&(()=>{let e=Math.min(Math.max(8,N.x+12),Math.max(8,M.w-200-8)),t=Math.min(Math.max(8,N.y-80-8),Math.max(8,M.h-80-8));return(0,x.jsxs)(`div`,{className:iS.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:iS.hoverHeader,children:[N.cell.name,N.cell.featured&&(0,x.jsx)(`span`,{className:iS.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:iS.hoverRole,children:[N.cell.department.toUpperCase(),` · `,N.cell.role,typeof N.cell.age==`number`?` · age ${N.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:iS.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:iS.hoverMoodValue,children:N.cell.mood}),typeof N.cell.psychScore==`number`?` · psych ${Math.round(N.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===N.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:iS.psychBlock,children:[(0,x.jsx)(`div`,{className:iS.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:iS.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:iS.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(fC,{payload:ue,containerW:M.w,containerH:M.h,sideColor:CC(s,j.current),hexacoById:p,snapshots:r,onClose:()=>de(null),onOpenChat:E})]})]})}var TC={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 EC(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 DC(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=typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`),g=(0,b.useRef)(null),[_,v]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(_)return;let e=g.current;if(!e)return;if(typeof IntersectionObserver>`u`){v(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){v(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[_]);let y=r.actors[n]??null,S=y?.leader??null,C=i[a],w=a>0?i[a-1]:void 0,T=ve(t),ee=S?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>y?EC(y.events):{attempts:[],reuses:[]},[y]),D=S?.hexaco?{O:S.hexaco.O??S.hexaco.openness??.5,C:S.hexaco.C??S.hexaco.conscientiousness??.5,E:S.hexaco.E??S.hexaco.extraversion??.5,A:S.hexaco.A??S.hexaco.agreeableness??.5,Em:S.hexaco.Em??S.hexaco.emotionality??.5,HH:S.hexaco.HH??S.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:g,className:TC.column,style:{"--actor-color":T},"aria-label":`Living swarm grid for actor ${t+1}: ${ee}`,children:[(0,x.jsxs)(`header`,{className:TC.columnHeader,children:[(0,x.jsxs)(`span`,{className:TC.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:TC.columnHeaderText,children:[(0,x.jsx)(`span`,{className:TC.columnHeaderName,children:ee}),S?.archetype&&(0,x.jsx)(`span`,{className:TC.columnHeaderArchetype,children:S.archetype})]}),(0,x.jsxs)(`span`,{className:TC.columnHeaderPop,title:`Population alive · morale`,children:[C?.population??`—`,` · `,C?Math.round(C.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:TC.columnBody,children:_?(0,x.jsx)(wC,{snapshot:C,isLiveRun:r.isRunning&&!h,previousSnapshot:w,snapshotHistory:i,actorName:ee,actorArchetype:S?.archetype??``,leaderUnit:S?.unit??``,sideColor:T,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:TC.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:TC.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:TC.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function OC({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:TC.track,role:`region`,"aria-label":`Cohort swarm grid: ${f.length} actors`,children:(0,x.jsx)(`div`,{className:TC.trackInner,children:f.map((f,p)=>(0,x.jsx)(DC,{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 kC(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+$/,``);return`${o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`}${e.deaths>0&&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 AC={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 jC(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=0,o=null,s=0,c=``,l=``,u=0;for(let n of e.events)(n.data?.turn??-1)===t+1&&((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===`decision_made`&&(r=String(n.data?.decision??r)),n.type===`outcome`&&(i=String(n.data?.outcome??i),a=Number(n.data?.deaths??a),o=n.data?.dominantCause??o,s=Number(n.data?.moraleDelta??s)));return{actorName:n,decision:r,outcome:i,deaths:a,dominantCause:o,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}var MC=6;function NC({state:e,currentTurn:t}){let n=e.actorIds.length>2,[r,i]=(0,b.useState)(n),a=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?jC(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),o=a.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,s=a.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,c=a.find(e=>e.summary.time)?.summary.time||0;if(!o)return null;let l=a.slice(0,MC),u=a.length-l.length,d=!r,f=a.length>0;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:AC.banner,children:[(0,x.jsxs)(`div`,{className:AC.headline,children:[(0,x.jsxs)(`span`,{className:AC.turnLabel,children:[`T`,t+1,c?` \u00b7 ${c}`:``]}),(0,x.jsx)(`span`,{className:AC.title,children:o}),s&&(0,x.jsx)(`span`,{className:AC.categoryPill,children:s}),f&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":!r,"aria-label":r?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:AC.collapseBtn,children:r?`\u25be ${a.length} actors`:`▴ hide`})]}),d&&l.map((e,t)=>(0,x.jsxs)(`div`,{className:a.length<=2?t===0?AC.lineA:AC.lineB:AC.line,children:[(0,x.jsx)(`span`,{className:AC.lineLabel,children:a.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:AC.lineBody,children:[`: `,kC(e.summary)]})]},e.actorId)),d&&u>0&&(0,x.jsxs)(`div`,{className:AC.lineMore,children:[`+`,u,` more \\u00b7 see cohort grid below for the rest`]})]})}var PC=[.5,1,2,4];function FC({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:PC.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var IC=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + family lines + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths / partner arcs`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; metrics strip + crisis shockwaves lead`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function LC(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 RC(e,t){return LC(IC.find(t=>t.key===e)?.hint??``,t)}function zC({mode:e,onChange:t,counts:n,labels:r}){return Dx(`(max-width: 480px)`)?(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:LC(IC.find(t=>t.key===e)?.hint??``,r),style:{width:`100%`,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:IC.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)})}):(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:IC.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=LC(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===IC.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 BC={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 VC({open:e,onClose:t}){let n=Dx(kx),r=om();if(!e)return null;let i=[BC.dialog,n?BC.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:BC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:BC.header,children:[(0,x.jsxs)(`h2`,{className:BC.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:BC.closeBtn,children:`×`})]}),(0,x.jsxs)(HC,{title:`Modes`,children:[(0,x.jsx)(UC,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + family lines + event flares`}),(0,x.jsx)(UC,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(UC,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(UC,{k:`ECOLOGY`,v:`Hides glyphs; metrics strip + crisis flares lead`}),(0,x.jsx)(UC,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(HC,{title:`Grid elements`,children:[(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(UC,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(UC,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(UC,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(UC,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(HC,{title:`Event flares`,children:[(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(UC,{k:(0,x.jsx)(WC,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(HC,{title:`Family lines`,children:[(0,x.jsx)(UC,{k:`— side color, bowed`,v:`Partner link`}),(0,x.jsx)(UC,{k:`– teal, dashed`,v:`Parent → child link`})]}),(0,x.jsxs)(HC,{title:`Keyboard`,children:[(0,x.jsx)(UC,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(UC,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(UC,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(UC,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(UC,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(UC,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:BC.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:BC.kbd,children:`?`}),` anytime to reopen.`]})]})})}function HC({title:e,children:t}){return(0,x.jsxs)(`div`,{className:BC.section,children:[(0,x.jsx)(`div`,{className:BC.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:BC.rows,children:t})]})}function UC({k:e,v:t}){return(0,x.jsxs)(`div`,{className:BC.row,children:[(0,x.jsx)(`span`,{className:BC.rowKey,children:e}),(0,x.jsx)(`span`,{className:BC.rowVal,children:t})]})}function WC({color:e}){return(0,x.jsx)(`span`,{className:BC.swatchWrap,children:(0,x.jsx)(`span`,{className:BC.swatch,style:{"--swatch-color":e}})})}var GC={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 KC({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:GC.wrap,children:[(0,x.jsxs)(`div`,{className:GC.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:GC.legendRight,children:[(0,x.jsx)(`span`,{className:GC.legendA,children:`A`}),(0,x.jsx)(`span`,{className:GC.legendB,children:`B`}),(0,x.jsx)(`span`,{className:GC.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:GC.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:GC.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:GC.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:GC.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:GC.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:GC.tooltipRowA,children:[(0,x.jsx)(`span`,{className:GC.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:GC.tooltipRowB,children:[(0,x.jsx)(`span`,{className:GC.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 qC={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`},JC=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],YC={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)`},XC={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function ZC({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()}) — click for lineage`,toolName:i})}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:qC.bar,children:[(0,x.jsxs)(`span`,{className:qC.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:qC.filterRow,children:JC.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[qC.filterChip,t?qC.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:qC.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[qC.dot,c?qC.current:``,d?qC.hovered:``].filter(Boolean).join(` `),p={"--kind-color":YC[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):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:XC[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var QC={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 $C(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 ew({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>$C(e),[e]),i=(0,b.useMemo)(()=>$C(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:QC.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:QC.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:QC.track,children:(0,x.jsx)(`div`,{className:QC.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:QC.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:QC.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var tw={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 nw({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=om();(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:tw.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:tw.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:tw.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:tw.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:tw.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:tw.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:tw.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:tw.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:tw.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:tw.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:tw.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:tw.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:tw.clearBtn,children:`clear`})]})]})}function rw(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 iw(e,t){switch(t){case`birth`:rw(e,880,.18,.05,`triangle`),setTimeout(()=>rw(e,1320,.12,.03,`triangle`),70);break;case`death`:rw(e,160,.35,.05,`sine`);break;case`forge`:rw(e,660,.12,.04,`sine`);break;case`crisis`:rw(e,220,.22,.05,`sawtooth`),setTimeout(()=>rw(e,180,.18,.045,`sawtooth`),120)}}function aw(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=AS(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&&iw(o,`birth`),l>0&&setTimeout(()=>iw(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),iw(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var ow={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 sw(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 cw(e){let{open:t,onClose:n}=e,r=om();(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)(()=>sw(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>sw(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:ow.cell,children:[(0,x.jsx)(`span`,{className:ow.cellLabel,children:e}),(0,x.jsx)(`span`,{className:ow.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:ow.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:ow.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:ow.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:ow.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:ow.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:ow.dialog,children:[(0,x.jsxs)(`div`,{className:ow.header,children:[(0,x.jsxs)(`h2`,{className:ow.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:ow.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:ow.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:ow.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:ow.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:ow.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:ow.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 lw={backdrop:`_backdrop_lye46_1`,dialog:`_dialog_lye46_12`,headerRow:`_headerRow_lye46_28`,kicker:`_kicker_lye46_35`,title:`_title_lye46_42`,closeBtn:`_closeBtn_lye46_49`,firstForged:`_firstForged_lye46_62`,firstDept:`_firstDept_lye46_71`,section:`_section_lye46_76`,sectionLabel:`_sectionLabel_lye46_80`,empty:`_empty_lye46_89`,list:`_list_lye46_95`,attemptItem:`_attemptItem_lye46_104`,statusLabel:`_statusLabel_lye46_115`,jumpBtn:`_jumpBtn_lye46_124`,clickable:`_clickable_lye46_133`,deptLabel:`_deptLabel_lye46_138`,confLabel:`_confLabel_lye46_144`,reuseItem:`_reuseItem_lye46_150`};function uw({payload:e,forgeAttemptsA:t,forgeAttemptsB:n,reuseCallsA:r,reuseCallsB:i,onClose:a,onJumpToTurn:o}){(0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),a())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,a]);let s=(0,b.useMemo)(()=>{if(!e)return null;let a=e.side===`a`?t:n,o=e.side===`a`?r:i,s=a.filter(t=>t.name===e.toolName);s.sort((e,t)=>e.turn-t.turn||e.eventIndex-t.eventIndex);let c=o.filter(t=>t.name===e.toolName);return c.sort((e,t)=>e.turn-t.turn),{mine:s,mineReuses:c,firstApproved:s.find(e=>e.approved)}},[e,t,n,r,i]),c=ht(!!e);if(!e||!s)return null;let l={"--side-color":e.sideColor};return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Forge lineage for ${e.toolName}`,onClick:a,className:lw.backdrop,children:(0,x.jsxs)(`div`,{ref:c,tabIndex:-1,onClick:e=>e.stopPropagation(),className:lw.dialog,style:l,children:[(0,x.jsxs)(`div`,{className:lw.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:lw.kicker,children:[`Forge Lineage · `,e.side.toUpperCase()]}),(0,x.jsx)(`div`,{className:lw.title,children:e.toolName})]}),(0,x.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close lineage`,className:lw.closeBtn,children:`×`})]}),s.firstApproved&&(0,x.jsxs)(`div`,{className:lw.firstForged,children:[`First forged in`,` `,(0,x.jsx)(`span`,{className:lw.firstDept,children:s.firstApproved.department.toUpperCase()}),` `,`on T`,s.firstApproved.turn,typeof s.firstApproved.confidence==`number`?` · confidence ${s.firstApproved.confidence.toFixed(2)}`:``]}),(0,x.jsxs)(`div`,{className:lw.section,children:[(0,x.jsxs)(`div`,{className:lw.sectionLabel,children:[`Attempts (`,s.mine.length,`)`]}),s.mine.length===0?(0,x.jsx)(`div`,{className:lw.empty,children:`no forge records`}):(0,x.jsx)(`ul`,{className:lw.list,children:s.mine.map((e,t)=>{let n={"--status-color":e.approved?`var(--green)`:`var(--rust)`};return(0,x.jsxs)(`li`,{className:lw.attemptItem,style:n,children:[(0,x.jsx)(`span`,{className:lw.statusLabel,children:e.approved?`✓ Forged`:`✗ Rejected`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[lw.jumpBtn,o?lw.clickable:``].filter(Boolean).join(` `),title:o?`Jump to T${e.turn}`:void 0,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:lw.deptLabel,children:e.department}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:lw.confLabel,children:[`conf `,e.confidence.toFixed(2)]})]},`${e.turn}-${e.eventIndex}-${t}`)})})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:lw.sectionLabel,children:[`Cross-dept reuses (`,s.mineReuses.length,`)`]}),s.mineReuses.length===0?(0,x.jsx)(`div`,{className:lw.empty,children:`never reused across departments`}):(0,x.jsx)(`ul`,{className:lw.list,children:s.mineReuses.map((e,t)=>(0,x.jsxs)(`li`,{className:lw.reuseItem,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[lw.jumpBtn,o?lw.clickable:``].filter(Boolean).join(` `),children:[`T`,e.turn]}),(0,x.jsxs)(`span`,{className:lw.deptLabel,children:[e.originDept,` → `,e.callingDept]})]},`${e.turn}-${e.callingDept}-${t}`))})]})]})})}var dw={anchor:`_anchor_ze1xr_1`,trigger:`_trigger_ze1xr_5`,triggerOpen:`_triggerOpen_ze1xr_21`,recDot:`_recDot_ze1xr_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ze1xr_1`,menu:`_menu_ze1xr_36`,item:`_item_ze1xr_52`,itemRecording:`_itemRecording_ze1xr_72`,itemKey:`_itemKey_ze1xr_76`,itemKeyRecording:`_itemKeyRecording_ze1xr_82`,itemDesc:`_itemDesc_ze1xr_86`};function fw({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!i)return;let e=e=>{o.current&&!o.current.contains(e.target)&&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]),(0,x.jsxs)(`div`,{ref:o,className:dw.anchor,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[dw.trigger,i?dw.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dw.recDot}),`EXPORT ▼`]}),i&&(0,x.jsxs)(`div`,{role:`menu`,className:dw.menu,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),t()},className:dw.item,children:[(0,x.jsx)(`span`,{className:dw.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:dw.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),r()},className:[dw.item,e?dw.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[dw.itemKey,e?dw.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:dw.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),n()},className:dw.item,children:[(0,x.jsx)(`span`,{className:dw.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:dw.itemDesc,children:`Replay snapshot`})]})]})]})}var pw={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},mw=120;function hw({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>mw,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:pw.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:pw.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:pw.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var gw={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 _w({departments:e}){let[t,n]=(0,b.useState)(!1),r=ht(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:gw.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:gw.glyphRow,children:[(0,x.jsx)(vw,{type:`band`}),(0,x.jsx)(`span`,{className:gw.label,children:`Department band`}),(0,x.jsx)(vw,{type:`agent`}),(0,x.jsx)(`span`,{className:gw.label,children:`Agent`}),(0,x.jsx)(vw,{type:`featured`}),(0,x.jsx)(`span`,{className:gw.label,children:`Featured agent`}),(0,x.jsx)(vw,{type:`turn`}),(0,x.jsx)(`span`,{className:gw.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:gw.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:gw.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:gw.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:gw.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:gw.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:gw.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:gw.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function vw({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${gw.glyph} ${gw.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${gw.glyph} ${gw.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${gw.glyph} ${gw.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${gw.glyph} ${gw.turn}`,"aria-hidden":`true`,children:`T`})}}var yw={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`},bw=8;function xw({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,bw);return n.length===0?(0,x.jsxs)(`div`,{className:yw.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:yw.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:yw.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:yw.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:yw.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:yw.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:`${yw.chip} ${i?yw.chipStrong:yw.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:yw.chipDept,children:r}),(0,x.jsxs)(`span`,{className:yw.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var Sw=.2;function Cw(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths-(t?.deaths??0),birthsThisTurn:e.births-(t?.births??0),eventCategories:e.eventCategories??[],year:e.time}}function ww(e,t,n){if(!e||!t)return`Awaiting first turn snapshot.`;let r=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let i=e.deathsThisTurn>t.deathsThisTurn?`A`:`B`,a=Math.max(e.deathsThisTurn,t.deathsThisTurn),o=Math.min(e.deathsThisTurn,t.deathsThisTurn);return`Turn ${n}, year ${r}: Leader ${i} lost ${a} ${a===1?`colonist`:`colonists`}; the other lost ${o}.`}if(Math.abs(e.morale-t.morale)>=Sw){let i=e.morale<t.morale?`A`:`B`,a=e.morale<t.morale?e.morale:t.morale,o=e.morale<t.morale?t.morale:e.morale;return`Turn ${n}, year ${r}: Leader ${i}'s morale collapsed to ${Tw(a)}; the other held ${Tw(o)}.`}let i=e.eventCategories.join(`|`),a=t.eventCategories.join(`|`);return i&&a&&i!==a?`Turn ${n}, year ${r}: the leaders faced different events — A: ${e.eventCategories.join(`, `)}; B: ${t.eventCategories.join(`, `)}.`:n===1&&i&&i===a?`Turn 1, year ${r}: identical first event (${e.eventCategories.join(`, `)}). Both colonies start from the same state.`:`Turn ${n}, year ${r}: A and B tracked closely. See sub-tabs for details.`}function Tw(e){return`${Math.round(e*100)}%`}function Ew(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)??Dw(e),a=i.get(e)??Dw(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 Dw(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var Ow={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function kw(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 Aw(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 jw({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 Mw({state:e,onNavigateToChat:t}){let n=rS(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,ee]=(0,b.useState)(1),E=typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`),D=e.isRunning&&!E,[O,te]=(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=>{te(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:ne}=St(),re=(0,b.useRef)(0),A=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=A.current;A.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return re.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(re.current)},[C,T,v]);let j=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),ie=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),ae=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),M=(0,b.useCallback)(e=>{w(!1),S(e)},[]),oe=cT(),N=(0,b.useCallback)(e=>{oe(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[oe]),[se,ce]=(0,b.useState)(!1),le=iT(),de=om(),[fe,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(null),[ge,P]=(0,b.useState)(null),[F,_e]=(0,b.useState)(`all`),[ve,ye]=(0,b.useState)(null),[be,xe]=(0,b.useState)(``),[Se,I]=(0,b.useState)(null),[Ce,we]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3){let{__v:e,...n}=t;return{...mC,...n}}localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return mC}),Te=(0,b.useCallback)(e=>{we(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ce.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),I(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,Ce.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!Se)return;let e=Se.expiresAt-performance.now();if(e<=0){I(null);return}let t=setTimeout(()=>I(null),e);return()=>clearTimeout(t)},[Se]);let[Ee,De]=(0,b.useState)(null),Oe=`paracosm:seenThresholdAlerts`,ke=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Oe);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),Ae=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Oe,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ce.alerts||!e.isRunning)return;let t=ke(),n=(e,n)=>{t.has(e)||(t.add(e),De({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),Ae(t)},[d,f,Ce.alerts,ke,Ae,e.isRunning]),(0,b.useEffect)(()=>{if(!Ee)return;let e=Ee.expiresAt-performance.now();if(e<=0){De(null);return}let t=setTimeout(()=>De(null),e);return()=>clearTimeout(t)},[Ee]);let[je,Me]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),Ne=(0,b.useCallback)(e=>{Me(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Pe=(0,b.useCallback)(()=>{Ne(je===`amber`?`cool`:je===`cool`?`mono`:`amber`)},[je,Ne]),[Fe,Ie]=(0,b.useState)(!1),[Le,Re]=(0,b.useState)(!1),[ze,Be]=(0,b.useState)(!1),[Ve,He]=(0,b.useState)(null),[Ue,We]=(0,b.useState)(null),Ge=(0,b.useCallback)(e=>{We(t=>t===e?null:e)},[]),Ke=d[y]??d[d.length-1],qe=f[y]??f[f.length-1],Je=Ke?.turn??0,Ye=qe?.turn??0,Xe=le.presets.find(e=>e.id==="default"),Ze=Xe?.leaders??Xe?.actors,Qe=Ze?.[0]?{name:Ze[0].name,archetype:Ze[0].archetype,unit:ue(le,0),hexaco:Ze[0].hexaco,instructions:Ze[0].instructions,quote:``}:null,$e=Ze?.[1]?{name:Ze[1].name,archetype:Ze[1].archetype,unit:ue(le,1),hexaco:Ze[1].hexaco,instructions:Ze[1].instructions,quote:``}:null,et=p?.leader??Qe,tt=m?.leader??$e,nt=(0,b.useRef)(null),[rt,it]=(0,b.useState)(!1),at=(0,b.useRef)(null),ot=(0,b.useRef)([]),st=(0,b.useRef)(null),ct=(0,b.useRef)(0),lt=(0,b.useCallback)(()=>{let e=nt.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;st.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}ot.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&ot.current.push(e.data)},s.onstop=()=>{ct.current&&cancelAnimationFrame(ct.current),ct.current=0;let e=new Blob(ot.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)},at.current=s,it(!0),s.start();let c=()=>{let e=st.current,t=nt.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)}ct.current=requestAnimationFrame(c)};ct.current=requestAnimationFrame(c)},[]),ut=(0,b.useCallback)(()=>{let e=at.current;if(e){try{e.stop()}catch{}at.current=null,it(!1)}},[]);(0,b.useEffect)(()=>()=>{if(at.current)try{at.current.stop()}catch{}ct.current&&cancelAnimationFrame(ct.current)},[]);let dt=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:et?.name??`Leader A`,archetype:et?.archetype??``},leaderB:{name:tt?.name??`Leader B`,archetype:tt?.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,et,tt,d,f,p,m]),ft=(0,b.useCallback)(()=>{let e=nt.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]),[pt,mt]=(0,b.useState)(0),ht=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ht.current===-1||Math.abs(y-ht.current)>=2&&mt(e=>e+1),ht.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&(e.key===`ArrowLeft`?(e.preventDefault(),ie()):e.key===`ArrowRight`?(e.preventDefault(),ae()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),j()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),ce(e=>!e)):e.key===`Escape`&&se?(e.preventDefault(),ce(!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)},[ie,ae,j,se,k]);let gt=(0,b.useMemo)(()=>{let e=be.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[...(Ke?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:et?.name??`Leader A`,sideColor:`#e8b44a`})),...(qe?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:tt?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[be,Ke,qe,et,tt]),_t=(0,b.useMemo)(()=>kw(Ke,qe),[Ke,qe]),vt=(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]);aw({enabled:Ce.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:vt.a.attempts,forgeAttemptsB:vt.b.attempts});let yt=(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]),bt=(0,b.useCallback)(e=>{t?.(e)},[t]),xt=Dx(Ox),Ct=Dx(kx),wt=(0,b.useMemo)(()=>ww(d[y]?Cw(d[y],d[y-1]):null,f[y]?Cw(f[y],f[y-1]):null,y+1),[d,f,y]),Tt=(0,b.useMemo)(()=>le.departments.map(e=>({id:e.id,label:e.label,color:Ow[e.id]??`#a89878`})),[le.departments]),Et=(0,b.useMemo)(()=>Object.fromEntries(le.departments.map(e=>[e.id,e.label])),[le.departments]),[Dt,Ot]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),kt=(0,b.useCallback)(e=>{Ot(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(),kt(!Dt))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Dt,kt]);let At=(0,b.useMemo)(()=>Dt?Ew(Aw(d[y]),Aw(f[y])):null,[Dt,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 `,de.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 `,de.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 `,de.place,` visualization.`]});let jt=Ke&&qe?`A vs B: ${qe.population-Ke.population>=0?`+`:``}${qe.population-Ke.population} pop, ${qe.morale-Ke.morale>=0?`+`:``}${Math.round((qe.morale-Ke.morale)*100)}% morale${typeof Ke.foodReserve==`number`&&typeof qe.foodReserve==`number`?`, ${qe.foodReserve-Ke.foodReserve>0?`+`:``}${(qe.foodReserve-Ke.foodReserve).toFixed(1)}mo food`:``}`:``,Mt=Ct?Ue??`a`:Ue,Nt=y>0?d[y-1]??d[d.length-2]:void 0,Pt=y>0?f[y-1]??f[f.length-2]:void 0,Ft=gt;return(0,x.jsxs)(`div`,{ref:nt,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)(NC,{state:e,currentTurn:y}),(0,x.jsx)(hw,{text:wt,turn:y+1}),(0,x.jsx)(_w,{departments:Tt}),Dt&&At&&(0,x.jsx)(xw,{diff:At,departmentLabels:Et}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(`div`,{className:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(zC,{mode:O,onChange:k,counts:{forge:vt.a.attempts.filter(e=>e.approved).length+vt.b.attempts.filter(e=>e.approved).length,divergence:(_t.aliveOnlyA?.size??0)+(_t.aliveOnlyB?.size??0)},labels:de})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Be(e=>!e),"aria-label":ze?`Hide advanced tools`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":ze,title:ze?`Hide tools`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,ze?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>kt(!Dt),"aria-label":Dt?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Dt,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Dt?`on`:`off`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ce(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),ze&&(0,x.jsxs)(`div`,{role:`toolbar`,"aria-label":`Viz tools`,className:$.toolsRow,children:[(0,x.jsx)(`button`,{type:`button`,onClick:Pe,"aria-label":`Palette: ${je}. Click to cycle.`,title:`Palette: ${je.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":je===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:je===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:je}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Re(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(fw,{recording:rt,onExportPng:ft,onExportJson:dt,onToggleRecording:rt?ut:lt}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":Fe,title:`Viz settings`,className:[$.settingsBtn,Fe?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:RC(O,de)})]}),(0,x.jsx)(nw,{value:be,onChange:xe,matches:Ft,onPick:e=>{xe(e.cell.name)}}),(0,x.jsx)(ew,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:le.departments.length}),(0,x.jsx)(ZC,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:M,hoveredTurn:ge,onHoverTurnChange:P,filter:F,onFilterChange:_e,onHoverEventChange:ye,onJumpToReports:N,onForgeSelect:(e,t)=>He({toolName:e,side:t,sideColor:t===`a`?`var(--vis)`:`var(--eng)`})}),(0,x.jsx)(KC,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:M,hoveredTurn:ge,onHoverTurnChange:P}),g===`pair`&&jt&&(0,x.jsx)(`div`,{className:$.diffLine,children:jt}),g===`pair`&&Ct&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?et?.name??`Leader A`:tt?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=Mt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>We(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsx)(OC,{state:e,snapshotMap:n,currentTurn:y,gridMode:O,palette:je===`cool`?1:je===`mono`?2:0,gridSettings:Ce,hexacoById:yt,searchQuery:be,chronicleFilter:F,chronicleHover:ve,startTime:le.setup?.defaultStartTime,onOpenChat:bt}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,xt?$.leadersRowNarrow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,Mt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(wC,{snapshot:Ke,isLiveRun:D,previousSnapshot:Nt,snapshotHistory:d,actorName:et?.name??`Leader A`,actorArchetype:et?.archetype??``,leaderUnit:et?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Je<Ye?Ye-Je:0,mode:O,hexacoById:yt,leaderHexaco:et?.hexaco?{O:et.hexaco.O??et.hexaco.openness??.5,C:et.hexaco.C??et.hexaco.conscientiousness??.5,E:et.hexaco.E??et.hexaco.extraversion??.5,A:et.hexaco.A??et.hexaco.agreeableness??.5,Em:et.hexaco.Em??et.hexaco.emotionality??.5,HH:et.hexaco.HH??et.hexaco.honestyHumility??.5}:void 0,forgeAttempts:vt.a.attempts,reuseCalls:vt.a.reuses,divergedIds:_t.aliveOnlyA,siblingHoveredId:me,onHoverChange:pe,searchQuery:be,palette:je===`cool`?1:je===`mono`?2:0,settings:Ce,startTime:le.setup?.defaultStartTime,focusedSide:Mt,onToggleFocus:Ct?void 0:Ge,onOpenChat:bt,eventFilter:F,chronicleHover:ve})}),(0,x.jsx)(`div`,{className:[$.sideWrap,Mt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(wC,{snapshot:qe,isLiveRun:D,previousSnapshot:Pt,snapshotHistory:f,actorName:tt?.name??`Leader B`,actorArchetype:tt?.archetype??``,leaderUnit:tt?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:Ye<Je?Je-Ye:0,mode:O,hexacoById:yt,leaderHexaco:tt?.hexaco?{O:tt.hexaco.O??tt.hexaco.openness??.5,C:tt.hexaco.C??tt.hexaco.conscientiousness??.5,E:tt.hexaco.E??tt.hexaco.extraversion??.5,A:tt.hexaco.A??tt.hexaco.agreeableness??.5,Em:tt.hexaco.Em??tt.hexaco.emotionality??.5,HH:tt.hexaco.HH??tt.hexaco.honestyHumility??.5}:void 0,forgeAttempts:vt.b.attempts,reuseCalls:vt.b.reuses,divergedIds:_t.aliveOnlyB,siblingHoveredId:fe,onHoverChange:he,searchQuery:be,palette:je===`cool`?1:je===`mono`?2:0,settings:Ce,startTime:le.setup?.defaultStartTime,focusedSide:Mt,onToggleFocus:Ct?void 0:Ge,onOpenChat:bt,eventFilter:F,chronicleHover:ve})})]}),(0,x.jsx)(FC,{currentTurn:y,maxTurn:v,time:Ke?.time??qe?.time??0,playing:C,speed:T,onTurnChange:M,onPlayPause:j,onStepBack:ie,onStepForward:ae,onSpeedChange:ee}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(jw,{k:`?`,v:`help`}),(0,x.jsx)(jw,{k:`1-5`,v:`mode`}),(0,x.jsx)(jw,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(jw,{k:`space`,v:`play / pause`}),(0,x.jsx)(jw,{k:`click`,v:`${de.person} drilldown`}),(0,x.jsx)(jw,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ke&&qe?`Turn ${Math.max(Ke.turn,qe.turn)}. ${et?.name??`A`} ${de.place}: ${Ke.cells.filter(e=>e.alive).length} alive, ${Ke.births} born, ${Ke.deaths} died, morale ${Math.round(Ke.morale*100)}%. ${tt?.name??`B`} ${de.place}: ${qe.cells.filter(e=>e.alive).length} alive, ${qe.births} born, ${qe.deaths} died, morale ${Math.round(qe.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>M(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)(VC,{open:se,onClose:()=>ce(!1)}),(0,x.jsx)(hC,{open:Fe,settings:Ce,onChange:Te,onClose:()=>Ie(!1)}),(0,x.jsx)(uw,{payload:Ve,forgeAttemptsA:vt.a.attempts,forgeAttemptsB:vt.b.attempts,reuseCallsA:vt.a.reuses,reuseCallsB:vt.b.reuses,onClose:()=>He(null),onJumpToTurn:e=>{M(e),He(null)}}),(0,x.jsx)(cw,{open:Le,onClose:()=>Re(!1),snapsA:d,snapsB:f,actorNameA:et?.name??`Leader A`,actorNameB:tt?.name??`Leader B`,forgeApprovedA:vt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:vt.b.attempts.filter(e=>e.approved).length,reuseCountA:vt.a.reuses.length,reuseCountB:vt.b.reuses.length,divergedCount:(_t.aliveOnlyA?.size??0)+(_t.aliveOnlyB?.size??0)}),Ee&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>De(null),className:$.toast,style:{"--toast-top":Se?`68px`:`8px`,"--side-color":Ee.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":Ee.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":Ee.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:Ee.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[Ee.side.toUpperCase(),` · T`,Ee.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:Ee.message})]},Ee.key),Se&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>I(null),className:$.toast,style:{"--side-color":Se.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:[Se.side.toUpperCase(),` · T`,Se.turn,` · `,Se.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:Se.title||`${Se.category} crisis unfolding`})]},Se.key),pt>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},pt),(0,x.jsx)(`style`,{children:`
|
|
127
127
|
@keyframes paracosm-vignette {
|
|
128
128
|
0% { opacity: 0; }
|
|
129
129
|
25% { opacity: 1; }
|
|
@@ -145,26 +145,26 @@ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange
|
|
|
145
145
|
0% { opacity: 0; transform: translateY(-6px); }
|
|
146
146
|
100% { opacity: 1; transform: translateY(0); }
|
|
147
147
|
}
|
|
148
|
-
`})]})}var
|
|
149
|
-
`)}function
|
|
148
|
+
`})]})}var Nw={footer:`_footer_w3wu8_1`,phone:`_phone_w3wu8_14`,nav:`_nav_w3wu8_18`,navLink:`_navLink_w3wu8_23`,statusChip:`_statusChip_w3wu8_28`,cost:`_cost_w3wu8_39`,costAmount:`_costAmount_w3wu8_48`,costMuted:`_costMuted_w3wu8_54`,brand:`_brand_w3wu8_58`,brandAccent:`_brandAccent_w3wu8_65`,brandLink:`_brandLink_w3wu8_69`};function Pw(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 Fw({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: ${Pw(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:Nw.statusChip,style:{"--status-color":t},role:`status`,"aria-live":`polite`,"aria-label":`Simulation status: ${n}. ${i}`,title:i,children:[r,` `,n]})}function Iw(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Lw(e,t){let n=[`Total: ${Iw(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: ${Iw(e)}${t.simCalls==null?``:` (${t.simCalls} calls)`}`),r>0&&n.push(`• Chat: ${Iw(r)}${t.chatCalls==null?``:` (${t.chatCalls} calls)`}`)}return n.join(`
|
|
149
|
+
`)}function Rw({cost:e,costBreakdown:t,simStatus:n}){let r=Dx(kx),i=[`shrink-0`,Nw.footer,r?Nw.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:i,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:Nw.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:Nw.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:Nw.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:Nw.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:Nw.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:Nw.navLink,children:`blog`})]}),n&&(0,x.jsx)(Fw,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:Nw.cost,title:Lw(e,t),children:[(0,x.jsxs)(`span`,{className:Nw.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:Nw.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:Nw.costMuted,children:[e.llmCalls,` calls`]})]}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:Nw.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:Nw.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:Nw.brandLink,children:`Frame.dev`})]})]})}var zw={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`},Bw=[{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 Vw(){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:zw.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:zw.dialog,children:[(0,x.jsxs)(`div`,{className:zw.header,children:[(0,x.jsx)(`h2`,{className:zw.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:zw.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=Bw.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:zw.section,children:[(0,x.jsx)(`h3`,{className:zw.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:zw.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:zw.row,children:[(0,x.jsx)(`span`,{className:zw.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:zw.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:zw.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:zw.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:zw.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:zw.kbdInline,children:`Esc`}),` to close`]})]})}):null}var Hw={BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},Uw=Hw.VITE_GA_MEASUREMENT_ID||``,Ww=Hw.VITE_CLARITY_PROJECT_ID||``;function Gw(e,t){if(document.getElementById(e))return;let n=document.createElement(`script`);n.id=e,n.async=!0,n.src=t,document.head.appendChild(n)}function Kw(e,t){if(document.getElementById(e))return;let n=document.createElement(`script`);n.id=e,n.textContent=t,document.head.appendChild(n)}function qw(){return(0,b.useEffect)(()=>{Uw&&Uw!==`G-XXXXXXXXXX`&&(Kw(`ga-init`,`
|
|
150
150
|
window.dataLayer = window.dataLayer || [];
|
|
151
151
|
function gtag(){dataLayer.push(arguments);}
|
|
152
152
|
gtag('js', new Date());
|
|
153
|
-
gtag('config', '${
|
|
153
|
+
gtag('config', '${Uw}', {
|
|
154
154
|
page_path: window.location.pathname,
|
|
155
155
|
anonymize_ip: true,
|
|
156
156
|
allow_google_signals: false,
|
|
157
157
|
allow_ad_personalization_signals: false
|
|
158
158
|
});
|
|
159
|
-
`),
|
|
159
|
+
`),Gw(`ga-js`,`https://www.googletagmanager.com/gtag/js?id=${Uw}`)),Ww&&(document.body.setAttribute(`data-clarity-mask`,`True`),Kw(`clarity-init`,`
|
|
160
160
|
(function(c,l,a,r,i,t,y){
|
|
161
161
|
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
|
|
162
162
|
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
|
|
163
163
|
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
|
|
164
|
-
})(window, document, "clarity", "script", "${
|
|
165
|
-
`))},[]),null}var
|
|
164
|
+
})(window, document, "clarity", "script", "${Ww}");
|
|
165
|
+
`))},[]),null}var Jw={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`},Yw=[{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. Every forged tool card gets a "↗ LOG" button that jumps to the Event Log filtered to that tool.`},{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. Every forged tool has a "↗ LOG" button that scopes the Event Log sub-tab to just that tool's history.`},{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 what the "↗ LOG" buttons elsewhere link into.`},{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.`}],Xw=360,Zw=`tour-highlight`,Qw=`
|
|
166
166
|
/* The highlighted element gets a bright luminous amber glow */
|
|
167
|
-
.${
|
|
167
|
+
.${Zw} {
|
|
168
168
|
outline: 3px solid var(--amber) !important;
|
|
169
169
|
outline-offset: 8px !important;
|
|
170
170
|
box-shadow:
|
|
@@ -187,9 +187,9 @@ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange
|
|
|
187
187
|
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);
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
|
-
`;function Qw({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?Jw:Jw.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=Zw,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Xw}`)?.classList.remove(Xw)}},[]),(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(Xw),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(Xw),e.classList.add(Xw),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(Xw),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(Xw),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-Yw-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Yw-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=[qw.card,C?qw.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:qw.cardHeader,children:[(0,x.jsxs)(`span`,{className:qw.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:qw.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:qw.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[qw.title,C?qw.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[qw.description,C?qw.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:qw.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[qw.skipBtn,C?qw.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:qw.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[qw.navBtn,C?qw.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[qw.primaryBtn,C?qw.compact:``,!C&&o===a.length-1?qw.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:qw.progressBar,children:(0,x.jsx)(`div`,{className:qw.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:qw.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:qw.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:qw.kbHint,children:`Arrow keys / Esc`})]})})}function $w(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 eT=[{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:$w(`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:$w(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],tT={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`},nT=(0,b.createContext)(null);function rT(){let e=(0,b.useContext)(nT);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var iT=(0,b.createContext)(!0);function aT(){return(0,b.useContext)(iT)}var oT=(0,b.createContext)(null);function sT(){let e=(0,b.useContext)(oT);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}var cT=(0,b.createContext)(()=>{});function lT(){return(0,b.useContext)(cT)}function uT(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 dT(){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 fT(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 pT=[];function mT(){let{scenario:e,ready:t}=oe(),n=dT(),r=F({replaySessionId:n,scenarioId:t?e.id:null}),[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),[c,l]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(!c)return;let e=e=>{e.key===`Escape`&&l(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),(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 u=i&&r.events.length===0,d=u?eT:r.events,f=Ce(d,u?!0:r.isComplete,u?void 0:r.results),p=Ce(r.ownRun?.events??pT,r.ownRun?.isComplete??!1),m=r.ownRun?p:f,{toast:h}=St();Mt({events:d,replayDone:r.replayDone,tourActive:i});let g=vg(f),_=Sg(f),v=Ae(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),y=We({scenarioShortName:e.labels.shortName}),S=xm(window.location.href),[C,w]=(0,b.useState)(S.tab),[T]=(0,b.useState)(S.tab===`studio`&&S.sub===`branches`?`branches`:`author`),[ee]=(0,b.useState)(S.tab===`settings`&&S.sub===`log`?`log`:`config`),E=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(w(e),window.history.replaceState({},``,Sm(window.location.href,e)))},[]);(0,b.useEffect)(()=>{C===`about`&&(window.location.href=`/`)},[C]);let D=(0,b.useCallback)(()=>{v.save(r.events,r.results,r.verdict),h(`success`,`Saved`,`${r.events.length} events${r.verdict?` + verdict`:``} saved to file.`)},[r.events,r.results,r.verdict,v,h]),[te]=(0,b.useState)(()=>typeof window>`u`||!tt(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:ot(window.location.href,_m),autoload:at(window.location.href)}),[k,ne]=(0,b.useState)(null),[re,A]=(0,b.useState)(null),j=(0,b.useRef)(null),{leaveOwnRun:ie}=r,ae=(0,b.useCallback)(()=>{j.current=null,A(null),ne(null),ie()},[ie]),M=$e({pickFile:v.pickFile,parseFile:v.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{ae(),r.loadEvents(e,t,n),h(`info`,`Loaded`,`${e.length} events loaded.`);let i=te.destinationTab;E(i&&i!==`about`?i:`sim`)},onError:e=>{h(`error`,`Load Failed`,e)}}),N=M.openPicker;ct({openFromFile:e=>M.openFromFile(e),onInfo:(e,t)=>h(`info`,e,t),onError:(e,t)=>h(`error`,e,t)});let se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{se.current||te.autoload&&M.state.kind===`preview`&&(se.current=!0,M.confirm())},[te.autoload,M.state.kind,M]);let ce=mt({onFile:e=>M.openFromFile(e),onError:()=>{h(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{h(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),le=(0,b.useCallback)(async()=>{if(!confirm(`Clear local data? This wipes the in-browser simulation buffer + cached events for this dashboard.
|
|
190
|
+
`;function $w({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?Yw:Yw.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=Qw,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Zw}`)?.classList.remove(Zw)}},[]),(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(Zw),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(Zw),e.classList.add(Zw),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(Zw),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(Zw),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-Xw-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Xw-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=[Jw.card,C?Jw.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:Jw.cardHeader,children:[(0,x.jsxs)(`span`,{className:Jw.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:Jw.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:Jw.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[Jw.title,C?Jw.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[Jw.description,C?Jw.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:Jw.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[Jw.skipBtn,C?Jw.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:Jw.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[Jw.navBtn,C?Jw.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[Jw.primaryBtn,C?Jw.compact:``,!C&&o===a.length-1?Jw.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:Jw.progressBar,children:(0,x.jsx)(`div`,{className:Jw.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:Jw.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:Jw.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:Jw.kbHint,children:`Arrow keys / Esc`})]})})}function eT(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 tT=[{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:eT(`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:eT(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],nT={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`},rT=(0,b.createContext)(null);function iT(){let e=(0,b.useContext)(rT);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var aT=(0,b.createContext)(!0);function oT(){return(0,b.useContext)(aT)}var sT=(0,b.createContext)(null);function cT(){let e=(0,b.useContext)(sT);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}var lT=(0,b.createContext)(()=>{});function uT(){return(0,b.useContext)(lT)}function dT(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 fT(){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 pT(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 mT=[];function hT(){let{scenario:e,ready:t}=oe(),n=fT(),r=F({replaySessionId:n,scenarioId:t?e.id:null}),[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),[c,l]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(!c)return;let e=e=>{e.key===`Escape`&&l(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),(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 u=i&&r.events.length===0,d=u?tT:r.events,f=Ce(d,u?!0:r.isComplete,u?void 0:r.results),p=Ce(r.ownRun?.events??mT,r.ownRun?.isComplete??!1),m=r.ownRun?p:f,{toast:h}=St();Mt({events:d,replayDone:r.replayDone,tourActive:i});let g=vg(f),_=Sg(f),v=Ae(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),y=We({scenarioShortName:e.labels.shortName}),S=xm(window.location.href),[C,w]=(0,b.useState)(S.tab),[T]=(0,b.useState)(S.tab===`studio`&&S.sub===`branches`?`branches`:`author`),[ee]=(0,b.useState)(S.tab===`settings`&&S.sub===`log`?`log`:`config`),E=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(w(e),window.history.replaceState({},``,Sm(window.location.href,e)))},[]);(0,b.useEffect)(()=>{C===`about`&&(window.location.href=`/`)},[C]);let D=(0,b.useCallback)(()=>{v.save(r.events,r.results,r.verdict),h(`success`,`Saved`,`${r.events.length} events${r.verdict?` + verdict`:``} saved to file.`)},[r.events,r.results,r.verdict,v,h]),[te]=(0,b.useState)(()=>typeof window>`u`||!tt(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:ot(window.location.href,_m),autoload:at(window.location.href)}),[k,ne]=(0,b.useState)(null),[re,A]=(0,b.useState)(null),j=(0,b.useRef)(null),{leaveOwnRun:ie}=r,ae=(0,b.useCallback)(()=>{j.current=null,A(null),ne(null),ie()},[ie]),M=$e({pickFile:v.pickFile,parseFile:v.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{ae(),r.loadEvents(e,t,n),h(`info`,`Loaded`,`${e.length} events loaded.`);let i=te.destinationTab;E(i&&i!==`about`?i:`sim`)},onError:e=>{h(`error`,`Load Failed`,e)}}),N=M.openPicker;ct({openFromFile:e=>M.openFromFile(e),onInfo:(e,t)=>h(`info`,e,t),onError:(e,t)=>h(`error`,e,t)});let se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{se.current||te.autoload&&M.state.kind===`preview`&&(se.current=!0,M.confirm())},[te.autoload,M.state.kind,M]);let ce=mt({onFile:e=>M.openFromFile(e),onError:()=>{h(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{h(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),le=(0,b.useCallback)(async()=>{if(!confirm(`Clear local data? This wipes the in-browser simulation buffer + cached events for this dashboard.
|
|
191
191
|
|
|
192
192
|
Server-stored runs, sessions, and on-disk artifact files are kept.
|
|
193
193
|
|
|
194
|
-
Cannot be undone.`))return;v.clearCache(),ae(),r.reset(),Oe(!1);let e=``;try{e=localStorage.getItem(`paracosm:adminToken`)??``}catch{}if(!e)h(`info`,`Local data cleared`,`In-browser caches wiped. Server-stored runs are unchanged.`),E(`settings`);else{try{let t=await fetch(`/admin/data/wipe`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Admin-Token":e},body:JSON.stringify({wipeRuns:!0,wipeSessions:!0,wipeOutput:!0})});if(t.ok){let e=await t.json();h(`info`,`Wiped`,`Local + ${e.wiped.runs} runs + ${e.wiped.sessions} sessions + ${e.wiped.outputFiles} files cleared.`)}else if(t.status===401){try{localStorage.removeItem(`paracosm:adminToken`)}catch{}h(`info`,`Local data cleared`,`Server-side wipe skipped: stored admin token rejected. Re-paste it via dev-tools localStorage if needed.`)}else if(t.status===403)h(`info`,`Local data cleared`,`Server-side wipe disabled on this deployment.`);else if(t.status===503)h(`info`,`Local data cleared`,`Server-side wipe configured but no ADMIN_TOKEN set on the server.`);else{let e=await t.json().catch(()=>({}));h(`info`,`Local data cleared`,`Server-side wipe failed: ${e.error??`HTTP ${t.status}`}`)}}catch(e){h(`info`,`Local data cleared`,`Server-side wipe failed: ${e instanceof Error?e.message:String(e)}`)}E(`settings`)}},[v,r,h,ae]),[ue,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{r.providerError||fe(!1)},[r.providerError]);let pe=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(r.errors.length<=pe.current)return;let e=r.errors.slice(pe.current);pe.current=r.errors.length;let t=r.providerError;for(let n of e){if(t&&
|
|
195
|
-
`)).then(()=>{h(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{h(`error`,`Copy Failed`,`Clipboard access denied.`)})},[f,e,h]),ye=n??dt(r.events),be=(0,b.useCallback)(()=>{if(!ye)return;let e=ut(window.location.origin,ye,`viz`);navigator.clipboard.writeText(e).then(()=>{h(`success`,`Share link copied`,`Anyone with the link opens this run on the viz tab.`)}).catch(()=>{h(`error`,`Copy Failed`,`Clipboard access denied.`)})},[ye,h]),[xe,Se]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[I,we]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),Te=(0,b.useCallback)(e=>{we(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Ee=(0,b.useRef)(r.events.length);(0,b.useEffect)(()=>{let e=Ee.current,t=r.events.length;Ee.current=t,e>0&&t===0&&we({totalTokens:0,costUSD:0,calls:0})},[r.events.length]),Rt({launching:xe,setLaunching:Se,isRunning:f.isRunning,isComplete:r.isComplete,sseStatus:r.status,eventsCount:r.events.length});let[De,Oe]=(0,b.useState)(!1),ke=(0,b.useCallback)(e=>{let t=r.reset();return r.followRun(e.runKey),j.current=e.runKey,ne(null),A(e),Oe(!0),E(`sim`),t},[r,E]),je=(0,b.useCallback)((e,t)=>{t===j.current&&(j.current=null,A(null),ne(e),Oe(!0),E(`sim`))},[E]),Me=(0,b.useCallback)(()=>{j.current=null,A(null),ne(null),r.leaveOwnRun()},[r]),Ne=(0,b.useCallback)((e,t)=>t===j.current&&(j.current=null,A(null),r.leaveOwnRun(),h(`error`,`Digital twin failed`,e),!0),[r,h]);Ft({isComplete:r.isComplete,isAborted:r.isAborted,abortReason:r.abortReason,resultsCount:r.results.length,hasVerdict:!!r.verdict,replayDone:r.replayDone,tourActive:i,userTriggeredRun:De,verdict:r.verdict}),(0,b.useEffect)(()=>{if(i||!r.isComplete||r.events.length===0)return;let t=`cached:${e.labels.shortName}:${r.events.length}:${r.isAborted?`a`:`c`}`,n=`paracosm:lastCachedRunFingerprint`;try{if(sessionStorage.getItem(n)===t)return;sessionStorage.setItem(n,t)}catch{}y.push({events:r.events,results:r.results,verdict:r.verdict})},[r.isComplete,r.isAborted,r.events,r.results,r.verdict,e.labels.shortName,y,i]),Lt({events:r.events,tourActive:i,userTriggeredRun:De});let Pe=(0,b.useCallback)(async()=>{if(!t)h(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(xe||f.isRunning)h(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{Se(!0),Oe(!0),j.current===null&&k===null&&await r.reset(),E(`sim`),h(`info`,`Launching`,`Starting simulation with default settings...`);let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(me(e))}),n=await t.json();t.status===429?(Se(!1),h(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect?(O(window,n.visitorId),ae()):(Se(!1),h(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){Se(!1),h(`error`,`Launch Failed`,String(e))}},[e,t,h,E,xe,f.isRunning,r,ae,k]);return(0,x.jsx)(hn,{children:(0,x.jsx)(
|
|
194
|
+
Cannot be undone.`))return;v.clearCache(),ae(),r.reset(),Oe(!1);let e=``;try{e=localStorage.getItem(`paracosm:adminToken`)??``}catch{}if(!e)h(`info`,`Local data cleared`,`In-browser caches wiped. Server-stored runs are unchanged.`),E(`settings`);else{try{let t=await fetch(`/admin/data/wipe`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Admin-Token":e},body:JSON.stringify({wipeRuns:!0,wipeSessions:!0,wipeOutput:!0})});if(t.ok){let e=await t.json();h(`info`,`Wiped`,`Local + ${e.wiped.runs} runs + ${e.wiped.sessions} sessions + ${e.wiped.outputFiles} files cleared.`)}else if(t.status===401){try{localStorage.removeItem(`paracosm:adminToken`)}catch{}h(`info`,`Local data cleared`,`Server-side wipe skipped: stored admin token rejected. Re-paste it via dev-tools localStorage if needed.`)}else if(t.status===403)h(`info`,`Local data cleared`,`Server-side wipe disabled on this deployment.`);else if(t.status===503)h(`info`,`Local data cleared`,`Server-side wipe configured but no ADMIN_TOKEN set on the server.`);else{let e=await t.json().catch(()=>({}));h(`info`,`Local data cleared`,`Server-side wipe failed: ${e.error??`HTTP ${t.status}`}`)}}catch(e){h(`info`,`Local data cleared`,`Server-side wipe failed: ${e instanceof Error?e.message:String(e)}`)}E(`settings`)}},[v,r,h,ae]),[ue,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{r.providerError||fe(!1)},[r.providerError]);let pe=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(r.errors.length<=pe.current)return;let e=r.errors.slice(pe.current);pe.current=r.errors.length;let t=r.providerError;for(let n of e){if(t&&dT(n,t.kind))continue;let e=n.length>120?n.slice(0,120)+`...`:n;h(`error`,`Simulation Error`,e)}},[r.errors,r.providerError,h]);let he=(0,b.useRef)(null),ge=(0,b.useCallback)(()=>{he.current=C,a(!0)},[C]);(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=bm(window.location.href);e===`quickstart`&&(he.current=e,a(!0))},600);return()=>clearTimeout(e)},[]);let P=(0,b.useCallback)(e=>{window.location.hash=`chat=${encodeURIComponent(e)}`,E(`chat`)},[E]),_e=(0,b.useCallback)(()=>{a(!1),he.current&&=(E(he.current),null);try{localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{}},[E]),ve=(0,b.useCallback)(()=>{let t=(e.labels.actorNoun??`actor`).replace(/^./,e=>e.toUpperCase()),n=de(e),r=[`## ${e.labels.name} — Simulation Report`,`**Turns**: ${f.turn}/${f.maxTurns} | **Seed**: ${f.seed} | **${n.Time}**: ${f.time}`];for(let e=0;e<f.actorIds.length;e++){let n=f.actorIds[e],i=f.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(f.actorIds.length===2){let e=f.actors[f.actorIds[0]],t=f.actors[f.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)`),navigator.clipboard.writeText(r.join(`
|
|
195
|
+
`)).then(()=>{h(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{h(`error`,`Copy Failed`,`Clipboard access denied.`)})},[f,e,h]),ye=n??dt(r.events),be=(0,b.useCallback)(()=>{if(!ye)return;let e=ut(window.location.origin,ye,`viz`);navigator.clipboard.writeText(e).then(()=>{h(`success`,`Share link copied`,`Anyone with the link opens this run on the viz tab.`)}).catch(()=>{h(`error`,`Copy Failed`,`Clipboard access denied.`)})},[ye,h]),[xe,Se]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[I,we]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),Te=(0,b.useCallback)(e=>{we(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Ee=(0,b.useRef)(r.events.length);(0,b.useEffect)(()=>{let e=Ee.current,t=r.events.length;Ee.current=t,e>0&&t===0&&we({totalTokens:0,costUSD:0,calls:0})},[r.events.length]),Rt({launching:xe,setLaunching:Se,isRunning:f.isRunning,isComplete:r.isComplete,sseStatus:r.status,eventsCount:r.events.length});let[De,Oe]=(0,b.useState)(!1),ke=(0,b.useCallback)(e=>{let t=r.reset();return r.followRun(e.runKey),j.current=e.runKey,ne(null),A(e),Oe(!0),E(`sim`),t},[r,E]),je=(0,b.useCallback)((e,t)=>{t===j.current&&(j.current=null,A(null),ne(e),Oe(!0),E(`sim`))},[E]),Me=(0,b.useCallback)(()=>{j.current=null,A(null),ne(null),r.leaveOwnRun()},[r]),Ne=(0,b.useCallback)((e,t)=>t===j.current&&(j.current=null,A(null),r.leaveOwnRun(),h(`error`,`Digital twin failed`,e),!0),[r,h]);Ft({isComplete:r.isComplete,isAborted:r.isAborted,abortReason:r.abortReason,resultsCount:r.results.length,hasVerdict:!!r.verdict,replayDone:r.replayDone,tourActive:i,userTriggeredRun:De,verdict:r.verdict}),(0,b.useEffect)(()=>{if(i||!r.isComplete||r.events.length===0)return;let t=`cached:${e.labels.shortName}:${r.events.length}:${r.isAborted?`a`:`c`}`,n=`paracosm:lastCachedRunFingerprint`;try{if(sessionStorage.getItem(n)===t)return;sessionStorage.setItem(n,t)}catch{}y.push({events:r.events,results:r.results,verdict:r.verdict})},[r.isComplete,r.isAborted,r.events,r.results,r.verdict,e.labels.shortName,y,i]),Lt({events:r.events,tourActive:i,userTriggeredRun:De});let Pe=(0,b.useCallback)(async()=>{if(!t)h(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(xe||f.isRunning)h(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{Se(!0),Oe(!0),j.current===null&&k===null&&await r.reset(),E(`sim`),h(`info`,`Launching`,`Starting simulation with default settings...`);let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(me(e))}),n=await t.json();t.status===429?(Se(!1),h(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect?(O(window,n.visitorId),ae()):(Se(!1),h(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){Se(!1),h(`error`,`Launch Failed`,String(e))}},[e,t,h,E,xe,f.isRunning,r,ae,k]);return(0,x.jsx)(hn,{children:(0,x.jsx)(sT.Provider,{value:E,children:(0,x.jsx)(lT.Provider,{value:ae,children:(0,x.jsx)(rT.Provider,{value:e,children:(0,x.jsx)(aT.Provider,{value:t,children:(0,x.jsx)(yg.Provider,{value:g,children:(0,x.jsxs)(Cg.Provider,{value:_,children:[(0,x.jsx)(_n,{sse:r}),(0,x.jsx)(`a`,{className:`skip-to-content`,href:`#main-content`,children:`Skip to main content`}),(0,x.jsxs)(`div`,{className:`scanline-overlay ${nT.shell}`,children:[r.providerError&&!ue?(0,x.jsx)(Wg,{providerError:r.providerError,onDismiss:()=>fe(!0)}):null,n&&r.status===`replay_not_found`?(0,x.jsx)(dn,{replaySessionId:n}):null,n&&r.status!==`replay_not_found`?(0,x.jsx)(un,{replaySessionId:n}):null,(0,x.jsx)(Rg,{scenario:e,sse:r,gameState:f,onSave:D,onLoad:N,onClear:le,onRun:Pe,onTour:ge,onCopy:ve,onShareViz:ye?be:void 0,launching:xe,history:y.entries,onRestoreHistory:e=>{ae(),y.restore(e,r.loadEvents)},onClearHistory:()=>{y.clear(),v.clearCache(),ae(),r.reset(),Oe(!1)}}),(0,x.jsx)(Hg,{active:C,onTabChange:E,scenario:e}),De&&(0,x.jsx)(Ht,{verdict:r.verdict,currentTurn:f.turn,maxTurns:f.maxTurns,dismissedKey:o,onOpenModal:()=>l(!0),onDismiss:s,onNavigateTab:E}),(0,x.jsxs)(`main`,{id:`main-content`,tabIndex:-1,className:`flex-1 overflow-hidden ${nT.main}`,role:`main`,"aria-label":`${C} view`,children:[(0,x.jsx)(`h1`,{className:`sr-only`,children:pT(C)}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-quickstart`,"aria-labelledby":`tab-quickstart`,hidden:C!==`quickstart`,tabIndex:-1,className:C===`quickstart`?nT.tabPanel:nT.tabPanelHidden,children:(0,x.jsx)(gg,{sse:r,sessionId:n??void 0,onRunStarted:()=>{ae(),Oe(!0)},onInterventionStart:ke,onInterventionResult:je,onInterventionError:Ne})}),C===`sim`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-sim`,"aria-labelledby":`tab-sim`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(Oy,{state:f,sseStatus:r.status,onRun:Pe,onTour:ge,verdict:r.verdict,launching:xe,interventionArtifact:k,interventionRunning:re,interventionState:m,onInterventionDismiss:Me,forceLayout:i?`side-by-side`:void 0})}),C===`viz`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-viz`,"aria-labelledby":`tab-viz`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(Mw,{state:f,onNavigateToChat:P})}),C===`settings`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-settings`,"aria-labelledby":`tab-settings`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(xb,{events:d,initialSubTab:ee})}),C===`reports`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-reports`,"aria-labelledby":`tab-reports`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(Yx,{state:f,verdict:r.verdict,reportSections:e.ui.reportSections})}),C===`library`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-library`,"aria-labelledby":`tab-library`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(ki,{})}),C===`studio`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-studio`,"aria-labelledby":`tab-studio`,tabIndex:-1,className:nT.tabPanel,children:(0,x.jsx)(Em,{initialSubTab:T})}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-chat`,"aria-labelledby":`tab-chat`,tabIndex:-1,className:C===`chat`?nT.chatSurfaceVisible:nT.chatSurfaceHidden,children:(0,x.jsx)(nS,{state:f,onChatUsage:Te},`${r.runKey??``}:${r.loadedRuns}`)})]}),(0,x.jsx)(Rw,{cost:{totalTokens:(f.cost?.totalTokens??0)+I.totalTokens,totalCostUSD:Math.round(((f.cost?.totalCostUSD??0)+I.costUSD)*1e4)/1e4,llmCalls:(f.cost?.llmCalls??0)+I.calls},costBreakdown:{simUSD:f.cost?.totalCostUSD??0,simCalls:f.cost?.llmCalls??0,chatUSD:I.costUSD,chatCalls:I.calls},simStatus:{isRunning:f.isRunning,isComplete:r.isComplete,isAborted:r.isAborted,connectionStatus:r.status,abortReason:r.abortReason,providerError:r.providerError}}),c&&r.verdict&&(0,x.jsx)(on,{verdict:r.verdict,onClose:()=>l(!1)}),M.metadata&&(0,x.jsx)(vt,{metadata:M.metadata,showOverwriteWarning:r.events.length>0&&!n,currentEventCount:r.events.length,onConfirm:M.confirm,onCancel:M.cancel}),(0,x.jsx)(bt,{active:ce.isDragging}),i&&(0,x.jsx)($w,{activeTab:C,chatEnabled:e.policies.characterChat,onTabChange:E,onClose:_e,onRun:Pe}),(0,x.jsx)(Vw,{})]})]})})})})})})})}var gT=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:nT.errorBoundary,children:[(0,x.jsx)(`div`,{className:nT.errorTitle,children:`SIMULATION ERROR`}),(0,x.jsx)(`div`,{className:nT.errorMessage,children:this.state.error.message}),(0,x.jsx)(`button`,{onClick:()=>{this.setState({error:null}),window.location.reload()},className:nT.errorReload,children:`Reload Dashboard`})]}):this.props.children}};function _T(){return(0,x.jsx)(gT,{children:(0,x.jsx)(w,{children:(0,x.jsxs)(Dt,{children:[(0,x.jsx)(qw,{}),(0,x.jsx)(hT,{})]})})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(b.StrictMode,{children:(0,x.jsx)(_T,{})}));
|