paracosm 0.9.1062 → 0.9.1064
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-BYGcbkwS.js → index-B8I4CaAq.js} +16 -16
- package/dist/dashboard/dist/index.html +1 -1
- package/dist/engine/core/agent-generator.d.ts +13 -0
- package/dist/engine/core/agent-generator.d.ts.map +1 -1
- package/dist/engine/core/agent-generator.js +48 -9
- package/dist/engine/core/agent-generator.js.map +1 -1
- package/dist/engine/core/kernel.d.ts +51 -8
- package/dist/engine/core/kernel.d.ts.map +1 -1
- package/dist/engine/core/kernel.js +196 -23
- package/dist/engine/core/kernel.js.map +1 -1
- package/dist/engine/core/progression.d.ts.map +1 -1
- package/dist/engine/core/progression.js +23 -15
- package/dist/engine/core/progression.js.map +1 -1
- package/dist/engine/core/state.d.ts +2 -1
- package/dist/engine/core/state.d.ts.map +1 -1
- package/dist/engine/core/state.js.map +1 -1
- package/dist/engine/schema/stream.d.ts +1 -0
- package/dist/engine/schema/stream.d.ts.map +1 -1
- package/dist/engine/schema/stream.js +1 -0
- package/dist/engine/schema/stream.js.map +1 -1
- package/dist/runtime/orchestrator/index.d.ts +2 -0
- package/dist/runtime/orchestrator/index.d.ts.map +1 -1
- package/dist/runtime/orchestrator/index.js +12 -11
- package/dist/runtime/orchestrator/index.js.map +1 -1
- package/dist/runtime/orchestrator/outcome-effects.d.ts +21 -7
- package/dist/runtime/orchestrator/outcome-effects.d.ts.map +1 -1
- package/dist/runtime/orchestrator/outcome-effects.js +20 -10
- package/dist/runtime/orchestrator/outcome-effects.js.map +1 -1
- package/dist/runtime/util/generic-fingerprint.d.ts.map +1 -1
- package/dist/runtime/util/generic-fingerprint.js +4 -2
- package/dist/runtime/util/generic-fingerprint.js.map +1 -1
- package/dist/runtime/util/parsers.d.ts +15 -3
- package/dist/runtime/util/parsers.d.ts.map +1 -1
- package/dist/runtime/util/parsers.js +26 -20
- package/dist/runtime/util/parsers.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 Lp(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 Rp(){return(0,x.jsxs)(`section`,{className:Ei.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:Ei.guideHead,children:[(0,x.jsx)(`h3`,{className:Ei.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:Ei.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:Ei.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.`]})]}),(0,x.jsxs)(`div`,{className:Ei.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:Lp,className:Ei.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:Ei.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:Ei.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:Ei.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:Ei.guideExampleCode,children:(0,x.jsx)(`code`,{children:Ip})}),(0,x.jsxs)(`p`,{className:Ei.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 zp(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:Ei.artifactView,children:[(0,x.jsxs)(`header`,{className:Ei.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ei.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:Ei.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:Ei.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ei.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:Ei.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:Ei.artifactBody,children:s===`turn-loop`?(0,x.jsx)(Pr,{artifact:t}):(0,x.jsx)(Mr,{artifact:t,metricSpecs:u})})]})}function Bp(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:Ei.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(zp,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:Ei.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:Ei.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ei.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:Ei.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:Ei.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:Ei.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:Ei.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:Ei.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}function Vp(){let[e,t]=b.useState(!1),[n,r]=b.useState(null),[i,a]=b.useState(null);return{promoteSingle:b.useCallback(async e=>{t(!0),a(null);try{let t=await fetch(`/api/v1/library/import`,{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=await fetch(`/api/v1/library/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({artifacts:e})});if(!t.ok){let e=await t.json().catch(()=>({}));return a(e.error??`Promote failed: HTTP ${t.status}`),null}let n={kind:`bundle`,...await t.json()};return r(n),n}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),busy:e,lastResult:n,error:i}}function Hp(){let e=Nw();return(0,b.useMemo)(()=>de(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function Up(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function Wp(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=Up(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 Gp(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 Kp={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 qp(){let{state:e}=fn(),t=Hp(),n=Lw();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:Kp.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:Kp.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(Jp,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:Kp.branchList,children:e.branches.map(r=>(0,x.jsx)(Yp,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function Jp({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:Kp.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:Kp.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:Kp.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:Kp.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:Kp.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:Kp.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:Xp(t)})]},e))})]})}function Yp({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?Wp(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:Kp.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:Kp.cardHeader,children:[(0,x.jsxs)(`div`,{className:Kp.branchMeta,children:[(0,x.jsxs)(`span`,{className:Kp.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:Kp.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:Kp.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${Kp.status} ${Kp[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:Kp.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Kp.delta} ${Kp[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:Gp(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:Kp.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:Kp.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:Kp.error,role:`alert`,children:e.errorMessage})]})}function Xp(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var Zp={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function Qp({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:Zp.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${Zp.tab} ${Zp.tabActive}`:Zp.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 $p=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],em={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function tm(e){return!!e&&$p.includes(e)}function nm(e){let{tab:t}=rm(e);return t}function rm(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&em[n])return em[n];if(tm(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&em[i]?em[i]:tm(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function im(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function am(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 om(e,t){if(!t)return im(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 sm=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function cm({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),am(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=Vp(),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:Ei.tab,children:[(0,x.jsx)(Qp,{options:sm,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(qp,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rp,{}),(0,x.jsx)(Fp,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Ei.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:Ei.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:Ei.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(zp,{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)(Bp,{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)(Si,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function lm(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 um(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 dm(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 fm(e,t,n=`viz`){return st(e,t,n)}function pm(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-CjEcRF4W.mjs`,hm=`modulepreload`,gm=function(e){return`/`+e},_m={},vm=function(e){return e.pathname.endsWith(`.css`)},ym=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},bm=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=gm(t,n);let r=s(t),i=vm(r);return ym(_m,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`:hm,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)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).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 xm(){if(typeof window>`u`)return mm;try{return new URL(mm,window.location.origin).toString()}catch{return mm}}var Sm=null;async function Cm(){if(Sm)return Sm;let e=await bm(()=>import(`./pdf-BHx8b9rl.js`),[]);return e.GlobalWorkerOptions.workerSrc=xm(),Sm=e,e}async function wm(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 Cm(),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 Lp(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 Rp(){return(0,x.jsxs)(`section`,{className:Ei.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:Ei.guideHead,children:[(0,x.jsx)(`h3`,{className:Ei.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:Ei.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:Ei.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.`]})]}),(0,x.jsxs)(`div`,{className:Ei.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:Lp,className:Ei.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:Ei.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:Ei.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:Ei.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:Ei.guideExampleCode,children:(0,x.jsx)(`code`,{children:Ip})}),(0,x.jsxs)(`p`,{className:Ei.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 zp(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:Ei.artifactView,children:[(0,x.jsxs)(`header`,{className:Ei.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Ei.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:Ei.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:Ei.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ei.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:Ei.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:Ei.artifactBody,children:s===`turn-loop`?(0,x.jsx)(Pr,{artifact:t}):(0,x.jsx)(Mr,{artifact:t,metricSpecs:u})})]})}function Bp(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:Ei.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(zp,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:Ei.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:Ei.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:Ei.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:Ei.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:Ei.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:Ei.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:Ei.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:Ei.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}function Vp(){let[e,t]=b.useState(!1),[n,r]=b.useState(null),[i,a]=b.useState(null);return{promoteSingle:b.useCallback(async e=>{t(!0),a(null);try{let t=await fetch(`/api/v1/library/import`,{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=await fetch(`/api/v1/library/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({artifacts:e})});if(!t.ok){let e=await t.json().catch(()=>({}));return a(e.error??`Promote failed: HTTP ${t.status}`),null}let n={kind:`bundle`,...await t.json()};return r(n),n}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),busy:e,lastResult:n,error:i}}function Hp(){let e=Pw();return(0,b.useMemo)(()=>de(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function Up(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function Wp(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=Up(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 Gp(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 Kp={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 qp(){let{state:e}=fn(),t=Hp(),n=Rw();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:Kp.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:Kp.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(Jp,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:Kp.branchList,children:e.branches.map(r=>(0,x.jsx)(Yp,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function Jp({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:Kp.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:Kp.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:Kp.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:Kp.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:Kp.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:Kp.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:Xp(t)})]},e))})]})}function Yp({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?Wp(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:Kp.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:Kp.cardHeader,children:[(0,x.jsxs)(`div`,{className:Kp.branchMeta,children:[(0,x.jsxs)(`span`,{className:Kp.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:Kp.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:Kp.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${Kp.status} ${Kp[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:Kp.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Kp.delta} ${Kp[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:Gp(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:Kp.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:Kp.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:Kp.error,role:`alert`,children:e.errorMessage})]})}function Xp(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var Zp={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function Qp({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:Zp.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${Zp.tab} ${Zp.tabActive}`:Zp.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 $p=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],em={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function tm(e){return!!e&&$p.includes(e)}function nm(e){let{tab:t}=rm(e);return t}function rm(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&em[n])return em[n];if(tm(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&em[i]?em[i]:tm(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function im(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function am(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 om(e,t){if(!t)return im(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 sm=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function cm({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),am(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=Vp(),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:Ei.tab,children:[(0,x.jsx)(Qp,{options:sm,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(qp,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rp,{}),(0,x.jsx)(Fp,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Ei.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:Ei.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:Ei.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(zp,{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)(Bp,{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)(Si,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function lm(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 um(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 dm(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 fm(e,t,n=`viz`){return st(e,t,n)}function pm(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-CjEcRF4W.mjs`,hm=`modulepreload`,gm=function(e){return`/`+e},_m={},vm=function(e){return e.pathname.endsWith(`.css`)},ym=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},bm=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=gm(t,n);let r=s(t),i=vm(r);return ym(_m,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`:hm,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)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).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 xm(){if(typeof window>`u`)return mm;try{return new URL(mm,window.location.origin).toString()}catch{return mm}}var Sm=null;async function Cm(){if(Sm)return Sm;let e=await bm(()=>import(`./pdf-BHx8b9rl.js`),[]);return e.GlobalWorkerOptions.workerSrc=xm(),Sm=e,e}async function wm(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 Cm(),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 Tm(e){let t=Em(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('${Dm(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 Em(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Dm(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Om(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 km={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 Am(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)(()=>Tm(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Om(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:km.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:km.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:km.panel,children:[(0,x.jsxs)(`div`,{className:km.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:km.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:km.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:km.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:km.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var jm={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 Mm(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 Nm({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Nw(),i=!Fw()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,ee=()=>{s||i||(c(!0),e(a))},E=`${a} ${a===1?`actor`:`actors`}`,D=s?`Launching...`:`Run ${E} against ${y}`,O=s?`Launching...`:`${D} ->`,k=s?`Launching...`:`Run ${E}`,ne=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:jm.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:jm.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:jm.tagline,children:S}),(0,x.jsx)(`div`,{className:jm.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:jm.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:jm.scenarioPickerLabel,htmlFor:ne,children:`Scenario`}),(0,x.jsx)(`select`,{id:ne,className:jm.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=Mm(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:jm.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:jm.actorRow,children:[(0,x.jsx)(`label`,{className:jm.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:jm.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:jm.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:jm.runButton,onClick:ee,disabled:i||s,"aria-busy":s,"aria-label":D,children:[(0,x.jsx)(`span`,{className:jm.runButtonFull,"aria-hidden":`true`,children:O}),(0,x.jsx)(`span`,{className:jm.runButtonCompact,"aria-hidden":`true`,children:k})]}),(0,x.jsxs)(`div`,{className:jm.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 B={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 Pm(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 Fm(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Im(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 Lm(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 Rm(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,ie]=(0,b.useState)(null),[ae,oe]=(0,b.useState)(null);(0,b.useEffect)(()=>{oe(null),D(!1),ie(null)},[t?.id]);let se=t?.source===`compiled`,[A,ce]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)try{let e=localStorage.getItem(`paracosm:adminToken`);ce(e&&e.length>0?e:null)}catch{ce(null)}},[c]);let le=!!A&&t?.source===`compiled`,ue=(0,b.useRef)(null),de=(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?(de.current=document.activeElement,requestAnimationFrame(()=>{(ue.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):de.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=Lm(ue.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!ue.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 fe=`scenario-detail-actor-count`,pe=()=>{t&&se&&(te(ae??t.name),D(!0),ie(null))},me=()=>{D(!1),te(``),ie(null)},he=async()=>{if(!t||k)return;let e=O.trim();if(e.length===0)ie(`Name cannot be empty.`);else if(e===(ae??t.name))D(!1);else{ne(!0),ie(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(()=>({}));ie(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;oe(r),D(!1),te(``),s?.(t.id,r)}catch(e){ie(e instanceof Error?e.message:String(e))}finally{ne(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:B.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:ue,className:`${B.drawer} ${c?B.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:B.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:B.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:B.sourceBadge,"data-source":t.source??`other`,children:zm(t.source)})]}),(0,x.jsxs)(`section`,{className:B.summary,children:[E?(0,x.jsxs)(`form`,{className:B.nameEditForm,onSubmit:e=>{e.preventDefault(),he()},children:[(0,x.jsx)(`input`,{type:`text`,value:O,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),me())},disabled:k,maxLength:100,autoFocus:!0,className:B.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:B.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:B.nameEditSave,disabled:k||O.trim().length===0,children:k?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:B.nameEditCancel,onClick:me,disabled:k,children:`Cancel`})]}),re&&(0,x.jsx)(`p`,{className:B.nameEditError,role:`alert`,children:re})]}):(0,x.jsxs)(`div`,{className:B.nameRow,children:[(0,x.jsx)(`h2`,{className:B.name,children:ae??t.name}),se&&(0,x.jsx)(`button`,{type:`button`,className:B.nameEditBtn,onClick:pe,"aria-label":`Rename ${ae??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:B.description,children:t.description}),(0,x.jsxs)(`dl`,{className:B.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:B.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:B.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:B.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Pm(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:B.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:zm(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:B.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:B.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:B.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:B.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:B.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:B.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:B.presetCard,children:[(0,x.jsxs)(`div`,{className:B.presetHeader,children:[(0,x.jsx)(`span`,{className:B.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:B.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:B.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:B.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:B.hexacoRow,children:[(0,x.jsx)(`span`,{className:B.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:B.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:B.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:B.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:B.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:B.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:B.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:B.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:B.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:B.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:B.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:B.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:B.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:B.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:B.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${B.statusLine} ${B.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:B.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:B.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:B.recentRow,children:[(0,x.jsxs)(`span`,{className:B.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:B.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:B.recentMeta,children:[Pm(e.createdAt),` · `,Fm(e.costUSD),` · `,Im(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:B.footer,children:[(0,x.jsxs)(`div`,{className:B.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:fe,className:B.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:fe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:B.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:B.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:B.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`,` →`]}),le&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:B.deleteButton,onClick:async()=>{if(t&&A&&!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":A}});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.`),ce(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:B.deleteError,role:`alert`,children:T})]})]})]})]})}function zm(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var V={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 Bm(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 Vm(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Hm(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function Um(e){let{disabled:t=!1,onRunScenario:n}=e,r=Nw(),i=!Fw()||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:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:V.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${V.statusLine} ${V.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:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:V.header,children:[(0,x.jsxs)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:V.count,children:[`· `,D?`${te.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:V.actorRow,children:[(0,x.jsx)(`label`,{className:V.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:V.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:V.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:V.filterRow,children:[(0,x.jsxs)(`label`,{className:V.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:V.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:V.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:`${V.chip} ${n?V.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:V.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:V.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:V.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:V.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:V.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:V.grid,role:`list`,children:te.map(e=>{let t=Vm(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${V.card} ${V[`tone_${t}`]??``} ${r?V.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:V.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:V.cardHeader,children:[(0,x.jsx)(`span`,{className:`${V.sourceBadge} ${V[`badge_${t}`]??``}`,children:Hm(e.source)}),r&&(0,x.jsx)(`span`,{className:V.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:V.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:V.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:V.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:V.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:V.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:V.statValue,children:Bm(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:V.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)(Rm,{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 Wm=[{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 Gm(e){return .1+.6*e}var Km={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 qm(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function Jm({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(qm),[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=um(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=lm(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 wm(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:Km.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[E&&(0,x.jsx)(`p`,{className:Km.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)(Nm,{onRunStart:t,disabled:r||g||E}),n&&(0,x.jsx)(Um,{onRunScenario:n,disabled:r||g||E}),(0,x.jsxs)(`div`,{className:Km.dividerWrap,children:[(0,x.jsx)(`span`,{className:Km.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:Km.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:Km.templatePicker,children:[(0,x.jsx)(`span`,{className:Km.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:Km.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=Wm.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…`}),Wm.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:Km.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${Km.tab} ${i===e?Km.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:Km.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:Km.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:Km.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:Km.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:Km.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:Km.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:Km.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:Km.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:Km.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:Km.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:Km.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:Km.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:Km.actorCountPreview,"aria-live":`polite`,children:[`~$`,Gm(v).toFixed(2),` · `,Ym(v)]})]}),(0,x.jsx)(Am,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:Km.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,Gm(v).toFixed(2),`)`]})]})}function Ym(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 H={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`},Xm={id:``,name:``,description:``,profileJson:`{}`},Zm={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},Qm={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 $m(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function eh({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Xm),[a,o]=(0,b.useState)(Zm),[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=Qm[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Xm),o(Zm),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:H.card,children:[(0,x.jsxs)(`div`,{className:H.heading,children:[(0,x.jsx)(`h3`,{className:H.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:H.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:H.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:H.presetRow,children:[(0,x.jsx)(`span`,{className:H.presetLabel,children:`Examples`}),Object.entries(Qm).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${H.presetButton} ${p===e?H.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:H.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:H.presetBlurb,children:Qm[p].blurb}),(0,x.jsxs)(`div`,{className:H.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:H.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:H.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:`${H.textarea} ${H.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${H.textarea} ${H.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:H.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:H.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:H.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:H.input})]}),(0,x.jsxs)(`label`,{className:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:H.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:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:H.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=$m(r.profileJson,{}),o=$m(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);n?.({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,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}`)}e((await t.json()).artifact)}catch(e){t?.(e instanceof Error?e.message:String(e))}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:H.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:H.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:H.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:H.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function th(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function nh(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var rh={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 ih(){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`?nh(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=an(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:rh.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:rh.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:rh.row,children:[(0,x.jsx)(`span`,{className:rh.actor,children:a}),(0,x.jsx)(`span`,{className:rh.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:rh.meta,children:o})]})}var ah={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`},oh={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function sh({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`?ah.statusDone:n===`active`?ah.statusActive:ah.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${ah.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:ah.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:ah.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:ah.label,children:t}),i&&(0,x.jsx)(`span`,{className:ah.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:ah.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${ah.chevron} ${o?ah.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:ah.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${ah.actorChip} ${ah[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:ah.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:ah.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:oh[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:ah.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:`${ah.line} ${ah.tonePending}`,children:[(0,x.jsx)(`span`,{className:ah.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:ah.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:ah.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${ah.line} ${ah[`tone${ch(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:ah.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:ah.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:ah.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:ah.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:ah.lineBody,children:e.body})]},t))]})]})}function ch(e){return e.charAt(0).toUpperCase()+e.slice(1)}function lh(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 uh(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 dh(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 fh(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 ph(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=fh(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:dh(e.type),body:r,tone:uh(e.type),actor:typeof n==`string`?n:void 0}}function mh(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:lh(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:lh(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function hh(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=lh(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:lh(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function gh(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:lh(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:lh(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function _h(e){return e.events.map(e=>ph(e)).filter(e=>!!e)}function vh(e,t){switch(e){case`compile`:return mh(t);case`research`:return hh(t);case`actors`:return gh(t);case`running`:return _h(t);case`done`:return[]}}function yh(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 bh={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`},xh=[`compile`,`research`,`actors`,`running`,`done`];function Sh(e,t){let n=xh.indexOf(e),r=xh.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Ch({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=Lw(),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:bh.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:bh.heading,children:[(0,x.jsx)(`span`,{className:bh.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:bh.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:bh.stageList,children:m.map(n=>{let r=Sh(e,n.id);return(0,x.jsx)(`li`,{className:bh.stageItem,children:(0,x.jsx)(sh,{stageId:n.id,label:n.label,status:r,logLines:vh(n.id,p),duration:yh(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:bh.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:bh.cancel,onClick:a,children:`Cancel run`})]})}var wh=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}}}),Th={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 Eh({onSelect:e,onClose:t}){let n=ft(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Th.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Th.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Th.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:Th.list,children:Object.values(wh).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Th.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Th.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Th.description,children:t.description})]})},t.id))})]})})}var Dh={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`},Oh=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function kh({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=fn(),a=Lw(),o=Hp(),[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=fm(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:``;pm(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:Dh.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:Dh.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalCitations}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalTools}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:Dh.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:Dh.summaryNum,children:m.totalDecisions}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalTurns}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`turns simulated`})]}),m.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:[`$`,m.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:Dh.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(Ah,{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)(Eh,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function Ah({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)(()=>dm(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:Dh.card,children:[(0,x.jsxs)(`header`,{className:Dh.cardHeader,children:[(0,x.jsx)(`h4`,{className:Dh.actorName,children:e.name}),(0,x.jsx)(`span`,{className:Dh.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:Dh.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:Dh.hexaco,children:Oh.map(t=>(0,x.jsxs)(`div`,{className:Dh.trait,children:[(0,x.jsx)(`span`,{className:Dh.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:Dh.traitBarOuter,children:(0,x.jsx)(`div`,{className:Dh.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Dh.delta} ${Dh[`direction_${e.direction}`]}`,children:Gp(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.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:Dh.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var jh=`paracosm:lastLaunchConfig`,Mh=`paracosm:keyOverrides`,Nh=`paracosm:activeRunActors`,Ph=`paracosm:activeRunScenarioId`,Fh=950;function Ih(e){try{let t=e.getItem(jh);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function Lh(e,t){return e.scenarioId===t}function Rh(e,t){try{e.setItem(jh,JSON.stringify(t))}catch{}}function zh(e,t,n){try{e.setItem(Nh,JSON.stringify(t)),n?e.setItem(Ph,n):e.removeItem?.(Ph)}catch{}}function Bh(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function Vh(e){try{let t=e.getItem(Nh);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 Hh(e){try{let t=e.getItem(Mh);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function Uh(e,t){let n=(typeof e.seed==`number`?e.seed:Fh)+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 Wh=2e3,Gh=3e5;function Kh(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 qh(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 Jh(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??Wh,i=t.timeoutMs??Gh,a=t.waitImpl??Kh,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 qh(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 qh(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 Yh={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 Xh(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 Zh({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i}){let a=Nw(),o=Fw(),{toast:s}=yt(),[c,l]=(0,b.useState)({kind:`input`}),[u,d]=(0,b.useState)(null),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(!1),[g,_]=(0,b.useState)(null),v=`paracosm:catalogPendingRun`,y=(0,b.useCallback)(async t=>{d(null),n?.(),e.reset();let r=typeof window<`u`?Hh(window.localStorage):{},i=typeof window<`u`?Ih(window.localStorage):null,o={};r.openai&&(o.apiKey=r.openai),r.anthropic&&(o.anthropicKey=r.anthropic),r.serper&&(o.serperKey=r.serper),r.firecrawl&&(o.firecrawlKey=r.firecrawl),r.tavily&&(o.tavilyKey=r.tavily),r.cohere&&(o.cohereKey=r.cohere),i?.provider&&(o.provider=i.provider),i?.models&&typeof i.models==`object`&&(o.models=i.models),i?.economics&&typeof i.economics==`object`&&(o.economics=i.economics);let c=a.presets[0]?.leaders??a.presets[0]?.actors??[];if(c.length>=t){l({kind:`progress`,stage:`running`});let n=c.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));e.reset(),typeof window<`u`&&zh(window.localStorage,n,a.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...o,actors:n,turns:a.setup.defaultTurns,seed:a.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:a.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=om(window.location.href,t.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Launch failed`,t,8e3)}}else{l({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:a.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`);l({kind:`progress`,stage:`running`}),e.reset(),typeof window<`u`&&zh(window.localStorage,r,a.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...o,actors:r,turns:a.setup.defaultTurns,seed:a.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:a.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=om(window.location.href,s.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Launch failed`,t,8e3)}}},[a,e,n,s]),S=(0,b.useCallback)(async(e,t)=>{if(e===a.id)y(t);else{d(null),n?.();try{try{sessionStorage.setItem(v,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(v)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(v)}catch{}let t=Xh(e?.message??String(e));d(t),s(`error`,`Scenario switch failed`,t,8e3)}}},[a.id,y,n,s]);(0,b.useEffect)(()=>{if(!o)return;let e=null;try{let t=sessionStorage.getItem(v);if(!t)return;sessionStorage.removeItem(v),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==a.id){s(`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&&y(t)},[o]);let C=(0,b.useCallback)(async t=>{d(null),n?.(),e.reset(),l({kind:`progress`,stage:`compile`});try{let{scenario:n,scenarioId:r}=await Jh(t);l({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();_(t)}}catch{_({skipped:!0,reason:`request failed`})}l({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`);l({kind:`progress`,stage:`running`,scenario:n,actors:o}),e.reset(),typeof window<`u`&&zh(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=om(window.location.href,c.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Quickstart failed`,t,8e3)}},[e,n,s]);(0,b.useEffect)(()=>{if(c.kind!==`progress`||c.stage!==`running`||!c.scenario||!c.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=c.actors.length&&l({kind:`results`,scenario:c.scenario,actors:c.actors,artifacts:t.slice(0,c.actors.length)})},[e.results,c]),(0,b.useEffect)(()=>{if(c.kind!==`results`||f!==null)return;let e=c.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&&p(n)}).catch(()=>{}),()=>{t=!0}},[c,f]);let w=c.kind===`progress`&&c.stage===`running`&&c.actors?c.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?c.scenario?.setup.defaultTurns??r:r,maxTurns:c.scenario?.setup.defaultTurns??6,status:a}}):void 0,T=(0,b.useCallback)((e,t)=>{d(`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:Yh.view,children:[c.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:Yh.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:Yh.howItWorks,children:[(0,x.jsx)(`summary`,{className:Yh.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:Yh.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:Yh.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.`]})]})]}),u&&(0,x.jsx)(`p`,{className:Yh.errorBanner,role:`alert`,children:u}),(0,x.jsx)(ih,{}),(0,x.jsx)(Jm,{onSeedReady:C,onLoadedScenarioRunStart:y,onCatalogRunStart:S}),r&&(0,x.jsx)(eh,{onResult:r,onRunStart:i,onError:e=>d(e)})]}),c.kind===`progress`&&(0,x.jsx)(Ch,{stage:c.stage,actors:w,events:e.events,actorCount:c.actors?.length??w?.length??2,groundingSummary:g}),c.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[u&&(0,x.jsx)(`p`,{className:Yh.errorBanner,role:`alert`,children:u}),f&&c.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:Yh.compareCta,onClick:()=>h(!0),"aria-label":`Compare all ${c.artifacts.length} actors side-by-side`,children:[`Compare all `,c.artifacts.length,` actors →`]}),(0,x.jsx)(kh,{actors:c.actors,artifacts:c.artifacts,sessionId:t,onSwap:T}),f&&m&&(0,x.jsx)(Si,{bundleId:f,open:!0,onClose:()=>h(!1)})]})]})}var Qh={getNumber:()=>0,getEntry:()=>void 0,list:[]};function $h(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 eg=(0,b.createContext)(Qh);function tg(){return(0,b.useContext)(eg)}var ng={getNumber:()=>0,getEntry:()=>void 0,list:[]};function rg(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 ig=(0,b.createContext)(ng);function ag(){return(0,b.useContext)(ig)}var og=m(),sg=420,cg=260;function lg({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(sg,window.innerWidth-20),r=t.left,i=t.top-cg-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+cg>window.innerHeight-10&&(i=window.innerHeight-cg-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:`${sg}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,og.createPortal)(p,document.body):null]})}function ug(){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 dg={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`},fg=dg;function pg(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 mg(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 hg(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function gg({s:e,onPick:t}){let n=an(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()} (${pg(e.createdAt)}) · ${mg(e.durationMs)} · ${hg(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:dg.sessionCard,children:[(0,x.jsx)(`div`,{className:dg.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:dg.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:dg.sessionCardLine3,children:o})]})}function _g({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}=ug(),g=p.length>0,_=Fw();(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=nh(window.location.href,e);window.location.assign(om(t,`sim`))},C=()=>{v(),t?.()},w=th(m,p);return(0,x.jsxs)(`div`,{ref:f,className:dg.root,children:[(0,x.jsx)(lg,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:dg.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:dg.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:dg.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:dg.runNewButton,children:[(0,x.jsxs)(`span`,{className:dg.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:dg.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[dg.runSavedButton,g?``:dg.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:dg.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[dg.runSavedBadge,g?``:dg.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:dg.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(gg,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:dg.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:dg.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:dg.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:fg.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:fg.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:fg.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:fg.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=`${pg(t)} · ${e.summary.eventCount} ev · ${hg(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:fg.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:fg.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:fg.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:fg.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:fg.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:fg.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 km={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 Am(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)(()=>Tm(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Om(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:km.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:km.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:km.panel,children:[(0,x.jsxs)(`div`,{className:km.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:km.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:km.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:km.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:km.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var jm={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 Mm(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 Nm({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Pw(),i=!Iw()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,ee=()=>{s||i||(c(!0),e(a))},E=`${a} ${a===1?`actor`:`actors`}`,D=s?`Launching...`:`Run ${E} against ${y}`,O=s?`Launching...`:`${D} ->`,k=s?`Launching...`:`Run ${E}`,ne=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:jm.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:jm.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:jm.tagline,children:S}),(0,x.jsx)(`div`,{className:jm.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:jm.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:jm.scenarioPickerLabel,htmlFor:ne,children:`Scenario`}),(0,x.jsx)(`select`,{id:ne,className:jm.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=Mm(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:jm.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:jm.actorRow,children:[(0,x.jsx)(`label`,{className:jm.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:jm.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:jm.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:jm.runButton,onClick:ee,disabled:i||s,"aria-busy":s,"aria-label":D,children:[(0,x.jsx)(`span`,{className:jm.runButtonFull,"aria-hidden":`true`,children:O}),(0,x.jsx)(`span`,{className:jm.runButtonCompact,"aria-hidden":`true`,children:k})]}),(0,x.jsxs)(`div`,{className:jm.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 B={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 Pm(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 Fm(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Im(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 Lm(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 Rm(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,ie]=(0,b.useState)(null),[ae,oe]=(0,b.useState)(null);(0,b.useEffect)(()=>{oe(null),D(!1),ie(null)},[t?.id]);let se=t?.source===`compiled`,[A,ce]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)try{let e=localStorage.getItem(`paracosm:adminToken`);ce(e&&e.length>0?e:null)}catch{ce(null)}},[c]);let le=!!A&&t?.source===`compiled`,ue=(0,b.useRef)(null),de=(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?(de.current=document.activeElement,requestAnimationFrame(()=>{(ue.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):de.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=Lm(ue.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!ue.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 fe=`scenario-detail-actor-count`,pe=()=>{t&&se&&(te(ae??t.name),D(!0),ie(null))},me=()=>{D(!1),te(``),ie(null)},he=async()=>{if(!t||k)return;let e=O.trim();if(e.length===0)ie(`Name cannot be empty.`);else if(e===(ae??t.name))D(!1);else{ne(!0),ie(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(()=>({}));ie(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;oe(r),D(!1),te(``),s?.(t.id,r)}catch(e){ie(e instanceof Error?e.message:String(e))}finally{ne(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:B.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:ue,className:`${B.drawer} ${c?B.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:B.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:B.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:B.sourceBadge,"data-source":t.source??`other`,children:zm(t.source)})]}),(0,x.jsxs)(`section`,{className:B.summary,children:[E?(0,x.jsxs)(`form`,{className:B.nameEditForm,onSubmit:e=>{e.preventDefault(),he()},children:[(0,x.jsx)(`input`,{type:`text`,value:O,onChange:e=>te(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),me())},disabled:k,maxLength:100,autoFocus:!0,className:B.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:B.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:B.nameEditSave,disabled:k||O.trim().length===0,children:k?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:B.nameEditCancel,onClick:me,disabled:k,children:`Cancel`})]}),re&&(0,x.jsx)(`p`,{className:B.nameEditError,role:`alert`,children:re})]}):(0,x.jsxs)(`div`,{className:B.nameRow,children:[(0,x.jsx)(`h2`,{className:B.name,children:ae??t.name}),se&&(0,x.jsx)(`button`,{type:`button`,className:B.nameEditBtn,onClick:pe,"aria-label":`Rename ${ae??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:B.description,children:t.description}),(0,x.jsxs)(`dl`,{className:B.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:B.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:B.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:B.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Pm(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:B.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:zm(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:B.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:B.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:B.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:B.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:B.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:B.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:B.presetCard,children:[(0,x.jsxs)(`div`,{className:B.presetHeader,children:[(0,x.jsx)(`span`,{className:B.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:B.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:B.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:B.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:B.hexacoRow,children:[(0,x.jsx)(`span`,{className:B.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:B.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:B.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:B.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:B.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:B.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:B.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:B.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:B.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:B.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:B.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:B.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:B.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:B.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:B.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:B.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${B.statusLine} ${B.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:B.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:B.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:B.recentRow,children:[(0,x.jsxs)(`span`,{className:B.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:B.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:B.recentMeta,children:[Pm(e.createdAt),` · `,Fm(e.costUSD),` · `,Im(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:B.footer,children:[(0,x.jsxs)(`div`,{className:B.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:fe,className:B.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:fe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:B.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:B.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:B.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`,` →`]}),le&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`button`,{type:`button`,className:B.deleteButton,onClick:async()=>{if(t&&A&&!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":A}});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.`),ce(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:B.deleteError,role:`alert`,children:T})]})]})]})]})}function zm(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var V={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 Bm(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 Vm(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Hm(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function Um(e){let{disabled:t=!1,onRunScenario:n}=e,r=Pw(),i=!Iw()||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:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:V.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${V.statusLine} ${V.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:V.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:V.header,children:[(0,x.jsxs)(`h3`,{className:V.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:V.count,children:[`· `,D?`${te.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:V.actorRow,children:[(0,x.jsx)(`label`,{className:V.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:V.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:V.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:V.filterRow,children:[(0,x.jsxs)(`label`,{className:V.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:V.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:V.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:`${V.chip} ${n?V.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:V.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:V.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:V.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:V.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:V.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:V.grid,role:`list`,children:te.map(e=>{let t=Vm(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${V.card} ${V[`tone_${t}`]??``} ${r?V.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:V.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:V.cardHeader,children:[(0,x.jsx)(`span`,{className:`${V.sourceBadge} ${V[`badge_${t}`]??``}`,children:Hm(e.source)}),r&&(0,x.jsx)(`span`,{className:V.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:V.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:V.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:V.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:V.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:V.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:V.stat,children:[(0,x.jsx)(`dt`,{className:V.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:V.statValue,children:Bm(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:V.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)(Rm,{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 Wm=[{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 Gm(e){return .1+.6*e}var Km={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 qm(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function Jm({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(qm),[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=um(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=lm(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 wm(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:Km.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[E&&(0,x.jsx)(`p`,{className:Km.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)(Nm,{onRunStart:t,disabled:r||g||E}),n&&(0,x.jsx)(Um,{onRunScenario:n,disabled:r||g||E}),(0,x.jsxs)(`div`,{className:Km.dividerWrap,children:[(0,x.jsx)(`span`,{className:Km.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:Km.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:Km.templatePicker,children:[(0,x.jsx)(`span`,{className:Km.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:Km.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=Wm.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…`}),Wm.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:Km.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${Km.tab} ${i===e?Km.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:Km.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:Km.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:Km.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:Km.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:Km.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:Km.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:Km.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:Km.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:Km.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:Km.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:Km.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:Km.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:Km.actorCountPreview,"aria-live":`polite`,children:[`~$`,Gm(v).toFixed(2),` · `,Ym(v)]})]}),(0,x.jsx)(Am,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:Km.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,Gm(v).toFixed(2),`)`]})]})}function Ym(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 H={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`},Xm={id:``,name:``,description:``,profileJson:`{}`},Zm={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},Qm={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 $m(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function eh({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Xm),[a,o]=(0,b.useState)(Zm),[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=Qm[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Xm),o(Zm),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:H.card,children:[(0,x.jsxs)(`div`,{className:H.heading,children:[(0,x.jsx)(`h3`,{className:H.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:H.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:H.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:H.presetRow,children:[(0,x.jsx)(`span`,{className:H.presetLabel,children:`Examples`}),Object.entries(Qm).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${H.presetButton} ${p===e?H.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:H.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:H.presetBlurb,children:Qm[p].blurb}),(0,x.jsxs)(`div`,{className:H.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:H.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:H.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:`${H.textarea} ${H.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${H.textarea} ${H.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:H.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:H.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]}),(0,x.jsxs)(`label`,{className:H.field,children:[(0,x.jsx)(`span`,{className:H.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:H.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:H.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:H.input})]}),(0,x.jsxs)(`label`,{className:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:H.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:`${H.field} ${H.fieldThird}`,children:[(0,x.jsx)(`span`,{className:H.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:H.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:H.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=$m(r.profileJson,{}),o=$m(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);n?.({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,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}`)}e((await t.json()).artifact)}catch(e){t?.(e instanceof Error?e.message:String(e))}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:H.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:H.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:H.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:H.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function th(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function nh(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var rh={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 ih(){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`?nh(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=an(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:rh.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:rh.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:rh.row,children:[(0,x.jsx)(`span`,{className:rh.actor,children:a}),(0,x.jsx)(`span`,{className:rh.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:rh.meta,children:o})]})}var ah={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`},oh={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function sh({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`?ah.statusDone:n===`active`?ah.statusActive:ah.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${ah.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:ah.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:ah.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:ah.label,children:t}),i&&(0,x.jsx)(`span`,{className:ah.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:ah.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${ah.chevron} ${o?ah.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:ah.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${ah.actorChip} ${ah[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:ah.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:ah.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:oh[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:ah.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:`${ah.line} ${ah.tonePending}`,children:[(0,x.jsx)(`span`,{className:ah.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:ah.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:ah.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${ah.line} ${ah[`tone${ch(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:ah.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:ah.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:ah.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:ah.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:ah.lineBody,children:e.body})]},t))]})]})}function ch(e){return e.charAt(0).toUpperCase()+e.slice(1)}function lh(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 uh(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 dh(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 fh(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 ph(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=fh(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:dh(e.type),body:r,tone:uh(e.type),actor:typeof n==`string`?n:void 0}}function mh(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:lh(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:lh(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function hh(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=lh(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:lh(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function gh(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:lh(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:lh(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function _h(e){return e.events.map(e=>ph(e)).filter(e=>!!e)}function vh(e,t){switch(e){case`compile`:return mh(t);case`research`:return hh(t);case`actors`:return gh(t);case`running`:return _h(t);case`done`:return[]}}function yh(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 bh={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`},xh=[`compile`,`research`,`actors`,`running`,`done`];function Sh(e,t){let n=xh.indexOf(e),r=xh.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Ch({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=Rw(),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:bh.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:bh.heading,children:[(0,x.jsx)(`span`,{className:bh.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:bh.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:bh.stageList,children:m.map(n=>{let r=Sh(e,n.id);return(0,x.jsx)(`li`,{className:bh.stageItem,children:(0,x.jsx)(sh,{stageId:n.id,label:n.label,status:r,logLines:vh(n.id,p),duration:yh(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:bh.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:bh.cancel,onClick:a,children:`Cancel run`})]})}var wh=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}}}),Th={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 Eh({onSelect:e,onClose:t}){let n=ft(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Th.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Th.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Th.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:Th.list,children:Object.values(wh).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Th.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Th.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Th.description,children:t.description})]})},t.id))})]})})}var Dh={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`},Oh=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function kh({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=fn(),a=Rw(),o=Hp(),[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=fm(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:``;pm(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:Dh.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:Dh.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalCitations}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalTools}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:Dh.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:Dh.summaryNum,children:m.totalDecisions}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:m.totalTurns}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`turns simulated`})]}),m.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:Dh.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:Dh.summaryNum,children:[`$`,m.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:Dh.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:Dh.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(Ah,{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)(Eh,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function Ah({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)(()=>dm(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:Dh.card,children:[(0,x.jsxs)(`header`,{className:Dh.cardHeader,children:[(0,x.jsx)(`h4`,{className:Dh.actorName,children:e.name}),(0,x.jsx)(`span`,{className:Dh.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:Dh.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:Dh.hexaco,children:Oh.map(t=>(0,x.jsxs)(`div`,{className:Dh.trait,children:[(0,x.jsx)(`span`,{className:Dh.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:Dh.traitBarOuter,children:(0,x.jsx)(`div`,{className:Dh.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Dh.delta} ${Dh[`direction_${e.direction}`]}`,children:Gp(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:Dh.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:Dh.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:Dh.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var jh=`paracosm:lastLaunchConfig`,Mh=`paracosm:keyOverrides`,Nh=`paracosm:activeRunActors`,Ph=`paracosm:activeRunScenarioId`,Fh=950;function Ih(e){try{let t=e.getItem(jh);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function Lh(e,t){return e.scenarioId===t}function Rh(e,t){try{e.setItem(jh,JSON.stringify(t))}catch{}}function zh(e,t,n){try{e.setItem(Nh,JSON.stringify(t)),n?e.setItem(Ph,n):e.removeItem?.(Ph)}catch{}}function Bh(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function Vh(e){try{let t=e.getItem(Nh);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 Hh(e){try{let t=e.getItem(Mh);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function Uh(e,t){let n=(typeof e.seed==`number`?e.seed:Fh)+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 Wh=2e3,Gh=3e5;function Kh(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 qh(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 Jh(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??Wh,i=t.timeoutMs??Gh,a=t.waitImpl??Kh,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 qh(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 qh(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 Yh={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 Xh(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 Zh({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i}){let a=Pw(),o=Iw(),{toast:s}=yt(),[c,l]=(0,b.useState)({kind:`input`}),[u,d]=(0,b.useState)(null),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(!1),[g,_]=(0,b.useState)(null),v=`paracosm:catalogPendingRun`,y=(0,b.useCallback)(async t=>{d(null),n?.(),e.reset();let r=typeof window<`u`?Hh(window.localStorage):{},i=typeof window<`u`?Ih(window.localStorage):null,o={};r.openai&&(o.apiKey=r.openai),r.anthropic&&(o.anthropicKey=r.anthropic),r.serper&&(o.serperKey=r.serper),r.firecrawl&&(o.firecrawlKey=r.firecrawl),r.tavily&&(o.tavilyKey=r.tavily),r.cohere&&(o.cohereKey=r.cohere),i?.provider&&(o.provider=i.provider),i?.models&&typeof i.models==`object`&&(o.models=i.models),i?.economics&&typeof i.economics==`object`&&(o.economics=i.economics);let c=a.presets[0]?.leaders??a.presets[0]?.actors??[];if(c.length>=t){l({kind:`progress`,stage:`running`});let n=c.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));e.reset(),typeof window<`u`&&zh(window.localStorage,n,a.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...o,actors:n,turns:a.setup.defaultTurns,seed:a.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:a.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=om(window.location.href,t.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Launch failed`,t,8e3)}}else{l({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:a.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`);l({kind:`progress`,stage:`running`}),e.reset(),typeof window<`u`&&zh(window.localStorage,r,a.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...o,actors:r,turns:a.setup.defaultTurns,seed:a.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:a.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=om(window.location.href,s.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Launch failed`,t,8e3)}}},[a,e,n,s]),S=(0,b.useCallback)(async(e,t)=>{if(e===a.id)y(t);else{d(null),n?.();try{try{sessionStorage.setItem(v,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(v)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(v)}catch{}let t=Xh(e?.message??String(e));d(t),s(`error`,`Scenario switch failed`,t,8e3)}}},[a.id,y,n,s]);(0,b.useEffect)(()=>{if(!o)return;let e=null;try{let t=sessionStorage.getItem(v);if(!t)return;sessionStorage.removeItem(v),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==a.id){s(`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&&y(t)},[o]);let C=(0,b.useCallback)(async t=>{d(null),n?.(),e.reset(),l({kind:`progress`,stage:`compile`});try{let{scenario:n,scenarioId:r}=await Jh(t);l({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();_(t)}}catch{_({skipped:!0,reason:`request failed`})}l({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`);l({kind:`progress`,stage:`running`,scenario:n,actors:o}),e.reset(),typeof window<`u`&&zh(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=om(window.location.href,c.redirect);return}}catch(e){l({kind:`input`});let t=Xh(e?.message??String(e));d(t),s(`error`,`Quickstart failed`,t,8e3)}},[e,n,s]);(0,b.useEffect)(()=>{if(c.kind!==`progress`||c.stage!==`running`||!c.scenario||!c.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=c.actors.length&&l({kind:`results`,scenario:c.scenario,actors:c.actors,artifacts:t.slice(0,c.actors.length)})},[e.results,c]),(0,b.useEffect)(()=>{if(c.kind!==`results`||f!==null)return;let e=c.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&&p(n)}).catch(()=>{}),()=>{t=!0}},[c,f]);let w=c.kind===`progress`&&c.stage===`running`&&c.actors?c.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?c.scenario?.setup.defaultTurns??r:r,maxTurns:c.scenario?.setup.defaultTurns??6,status:a}}):void 0,T=(0,b.useCallback)((e,t)=>{d(`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:Yh.view,children:[c.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:Yh.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:Yh.howItWorks,children:[(0,x.jsx)(`summary`,{className:Yh.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:Yh.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:Yh.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.`]})]})]}),u&&(0,x.jsx)(`p`,{className:Yh.errorBanner,role:`alert`,children:u}),(0,x.jsx)(ih,{}),(0,x.jsx)(Jm,{onSeedReady:C,onLoadedScenarioRunStart:y,onCatalogRunStart:S}),r&&(0,x.jsx)(eh,{onResult:r,onRunStart:i,onError:e=>d(e)})]}),c.kind===`progress`&&(0,x.jsx)(Ch,{stage:c.stage,actors:w,events:e.events,actorCount:c.actors?.length??w?.length??2,groundingSummary:g}),c.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[u&&(0,x.jsx)(`p`,{className:Yh.errorBanner,role:`alert`,children:u}),f&&c.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:Yh.compareCta,onClick:()=>h(!0),"aria-label":`Compare all ${c.artifacts.length} actors side-by-side`,children:[`Compare all `,c.artifacts.length,` actors →`]}),(0,x.jsx)(kh,{actors:c.actors,artifacts:c.artifacts,sessionId:t,onSwap:T}),f&&m&&(0,x.jsx)(Si,{bundleId:f,open:!0,onClose:()=>h(!1)})]})]})}var Qh={getNumber:()=>0,getEntry:()=>void 0,list:[]};function $h(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 eg=(0,b.createContext)(Qh);function tg(){return(0,b.useContext)(eg)}var ng={getNumber:()=>0,getEntry:()=>void 0,list:[]};function rg(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 ig=(0,b.createContext)(ng);function ag(){return(0,b.useContext)(ig)}var og=m(),sg=420,cg=260;function lg({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(sg,window.innerWidth-20),r=t.left,i=t.top-cg-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+cg>window.innerHeight-10&&(i=window.innerHeight-cg-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:`${sg}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,og.createPortal)(p,document.body):null]})}function ug(){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 dg={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`},fg=dg;function pg(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 mg(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 hg(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function gg({s:e,onPick:t}){let n=an(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()} (${pg(e.createdAt)}) · ${mg(e.durationMs)} · ${hg(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:dg.sessionCard,children:[(0,x.jsx)(`div`,{className:dg.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:dg.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:dg.sessionCardLine3,children:o})]})}function _g({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}=ug(),g=p.length>0,_=Iw();(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=nh(window.location.href,e);window.location.assign(om(t,`sim`))},C=()=>{v(),t?.()},w=th(m,p);return(0,x.jsxs)(`div`,{ref:f,className:dg.root,children:[(0,x.jsx)(lg,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:dg.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:dg.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:dg.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:dg.runNewButton,children:[(0,x.jsxs)(`span`,{className:dg.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:dg.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[dg.runSavedButton,g?``:dg.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:dg.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[dg.runSavedBadge,g?``:dg.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:dg.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(gg,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:dg.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:dg.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:dg.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:fg.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:fg.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:fg.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:fg.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=`${pg(t)} · ${e.summary.eventCount} ev · ${hg(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:fg.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:fg.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:fg.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:fg.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:fg.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:fg.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:dg.loadFileButton,children:[(0,x.jsxs)(`span`,{className:dg.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:dg.menuButtonIcon,children:`📁`}),(0,x.jsx)(`span`,{children:`Load from file…`})]}),(0,x.jsx)(`span`,{className:dg.loadFileBadge,children:`json export`})]})]})]})}var U={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 vg({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:U.logoSpan,style:{"--logo-size":`${e}px`,"--logo-glow":n},children:[(0,x.jsx)(`img`,{src:`/favicon.svg`,width:e,height:e,alt:`Paracosm`,className:U.logoImg}),(0,x.jsx)(`span`,{className:`pc-logo-glow ${U.logoGlow}`})]})}function yg({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=ft(_);(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`another run started on the server`;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 ${U.bar}`,role:`banner`,children:[(0,x.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,x.jsxs)(`a`,{href:`/`,className:`${U.logoLink} ${U.brand}`,"aria-label":`Paracosm home`,children:[(0,x.jsx)(vg,{size:20}),(0,x.jsxs)(`span`,{children:[`PARA`,(0,x.jsx)(`span`,{className:U.brandAccent,children:`COSM`})]})]}),(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:`topbar-agentos ${U.agentosTag}`,"aria-label":`AgentOS Runtime (opens in new tab)`,title:`AgentOS Runtime`,children:`AGENTOS`}),(0,x.jsx)(`span`,{className:`topbar-agentos ${U.divider}`,"aria-hidden":`true`,children:`|`}),(0,x.jsx)(`span`,{className:`topbar-scenario ${U.scenarioName}`,children:e.labels.name})]}),(0,x.jsxs)(`div`,{className:`flex items-center gap-3 flex-1 justify-center ${U.center}`,children:[n.turn>0&&(0,x.jsxs)(`div`,{className:`topbar-meta flex items-center gap-2 shrink-0 ${U.meta}`,children:[(0,x.jsx)(lg,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:U.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:U.tokenInline,children:[(0,x.jsx)(`span`,{className:U.tokenLabel,children:`T`}),(0,x.jsx)(`strong`,{className:U.tokenValue,children:n.turn}),(0,x.jsxs)(`span`,{className:U.tokenLabel,children:[`/`,n.maxTurns]})]})}),(0,x.jsx)(lg,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:U.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:U.tokenInline,children:[(0,x.jsx)(`span`,{className:U.tokenLabel,children:`Y`}),(0,x.jsx)(`strong`,{className:U.tokenValue,children:n.time})]})}),(0,x.jsx)(lg,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:U.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:U.tokenInline,children:[(0,x.jsx)(`span`,{className:U.tokenLabel,children:`S`}),(0,x.jsx)(`strong`,{className:U.tokenValue,children:n.seed})]})}),(0,x.jsx)(`div`,{className:`topbar-progress w-20 h-1.5 rounded-full overflow-hidden ${U.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 ${U.progressFill}`,style:{"--progress-pct":D}})}),t.validationFallbacks.length>0&&(()=>{let e=t.validationFallbacks.reduce((e,t)=>e+t.count,0);return(0,x.jsx)(lg,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:U.tooltipTitle,children:[`⚠ `,e,` validation fallback`,e===1?``:`s`]}),(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.`}),(0,x.jsx)(`div`,{className:U.fallbackBlock,children:t.validationFallbacks.map(e=>(0,x.jsxs)(`div`,{className:U.fallbackRow,children:[(0,x.jsx)(`span`,{children:e.schemaName}),(0,x.jsxs)(`span`,{className:U.fallbackRowMeta,children:[e.count,`× `,e.lastSite?`(last: ${e.lastSite})`:``]})]},e.schemaName))})]}),children:(0,x.jsxs)(`span`,{"aria-label":`${e} validation fallback${e===1?``:`s`}`,className:U.fallbackPill,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),e]})})})()]}),(0,x.jsx)(`div`,{className:`topbar-center hidden md:block truncate ${U.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 ${U.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:U.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 ${U.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)(_g,{onRun:o,onLoadFromFile:i,history:d,onRestoreHistory:f,onClearHistory:p,liveStateHasEvents:t.events.length>0}),u&&!n.isRunning&&(0,x.jsx)(`span`,{className:U.launchingChip,role:`status`,"aria-live":`polite`,children:`LAUNCHING…`}),(g&&(r||c||l)||a)&&(0,x.jsxs)(`div`,{ref:y,className:U.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:`${U.toolBtn} ${U.overflowTrigger}`,children:`⋯`}),_&&(0,x.jsxs)(`div`,{ref:S,role:`menu`,tabIndex:-1,className:U.overflowMenu,children:[g&&r&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),r()},className:U.overflowItem,title:`Export simulation data as .json`,children:`Save`}),g&&l&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),l()},className:U.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:U.overflowItem,title:`Copy simulation summary to clipboard`,children:`Copy`}),a&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{v(!1),a()},className:U.overflowItemDanger,title:`Clear in-browser simulation buffer + cached events. Server-stored runs are kept.`,children:`Clear local data`})]})]}),(0,x.jsx)(`span`,{className:U.divider,"aria-hidden":`true`,children:`|`}),(0,x.jsxs)(`span`,{className:U.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 ${U.statusText}`,children:T})]}),(0,x.jsx)(`button`,{onClick:()=>h(m===`dark`?`light`:`dark`),className:`px-2 py-0.5 rounded cursor-pointer transition-colors ${U.themeBtn}`,title:`Switch to ${m===`dark`?`light`:`dark`} mode`,"aria-label":`Switch to ${m===`dark`?`light`:`dark`} mode`,children:m===`dark`?`☀`:`☽`})]})]})}var bg={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 xg({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 Sg=[{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 Cg({active:e,onTabChange:t,scenario:n}){let r=Sg.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 ${bg.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:[bg.tab,o<r.length-1?bg.withDivider:``,s?bg.active:bg.inactive].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:bg.icon,"aria-hidden":`true`,children:(0,x.jsx)(xg,{id:n.id,size:18})}),(0,x.jsx)(`span`,{className:bg.label,"aria-hidden":`true`,children:n.label})]},n.id)})})}var wg={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 Tg({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`?`${Eg(e.provider)} credits exhausted`:e.kind===`auth`?`${Eg(e.provider)} API key invalid`:e.kind===`rate_limit`?`${Eg(e.provider)} rate-limited`:e.kind===`network`?`Network error contacting ${Eg(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:wg.banner,style:i,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:wg.icon,children:`!`}),(0,x.jsxs)(`div`,{className:wg.body,children:[(0,x.jsx)(`div`,{className:wg.heading,children:r}),(0,x.jsxs)(`div`,{className:wg.message,children:[e.message,e.leader?(0,x.jsxs)(`span`,{className:wg.messageActor,children:[` (hit by `,e.leader,`)`]}):null]})]}),e.actionUrl?(0,x.jsx)(`a`,{href:e.actionUrl,target:`_blank`,rel:`noreferrer noopener`,className:wg.actionLink,children:e.kind===`quota`?`Add credits →`:`Fix key →`}):null,t?(0,x.jsx)(`button`,{onClick:t,"aria-label":`Dismiss banner`,className:wg.dismissBtn,children:`Dismiss`}):null]})}function Eg(e){return e===`openai`?`OpenAI`:e===`anthropic`?`Anthropic`:e===`openrouter`?`OpenRouter`:e===`gemini`?`Gemini`:`Provider`}var W={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`},Dg={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`},Og=[`hba1c`,`weight`,`exerciseAdherence`],kg={hba1c:`#ef6f5d`,weight:`#ffd970`,exerciseAdherence:`#34d399`,bmi:`#a78bfa`,qualityOfLife:`#7cb6ff`,mortalityRisk:`#ef6f5d`,alignmentBench:`#7cb6ff`,specGamingRate:`#ef6f5d`,releaseReadiness:`#ffd970`,morale:`#ffd970`,runwayMonths:`#5fd49a`,marketShare:`#7cb6ff`},Ag=new Set([`hba1c`,`fastingGlucose`,`weight`,`bmi`,`exerciseAdherence`,`sleepHours`,`qualityOfLife`,`mortalityRisk`,`cardioFitness`,`sideEffectBurden`]);function jg(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 Mg(e,t){let n=t-e;return Math.abs(n)<1e-6?{text:`·`,direction:`flat`}:{text:`${n>0?`+`:``}${jg(n)}`,direction:n>0?`up`:`down`}}function Ng(e){return e==null?`—`:typeof e==`number`?jg(e):typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?e:JSON.stringify(e)}var Pg={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 Fg(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 Ig({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:Og.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=>Ag.has(e))?Array.from(e).filter(e=>Ag.has(e)):Array.from(e)).slice(0,12)},[d,u]),h=c?Object.entries(c).slice(0,6):[];return(0,x.jsxs)(`div`,{className:W.root,children:[(0,x.jsxs)(`div`,{className:W.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h2`,{className:W.title,children:`Digital Twin · Intervention Result`}),(0,x.jsxs)(`span`,{className:W.subTitle,children:[l?.scenario?.name??`scenario`,` · seed `,l?.seed??`?`,` · `,o?.timepoints?.length??0,` turns`]})]}),(0,x.jsxs)(`div`,{className:W.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:W.cardsRow,children:[(0,x.jsxs)(`div`,{className:W.card,children:[(0,x.jsxs)(`div`,{className:W.cardHeader,children:[(0,x.jsx)(`span`,{className:W.cardLabel,children:`Subject`}),(0,x.jsx)(`span`,{className:W.cardId,children:r?.id})]}),(0,x.jsx)(`div`,{className:W.cardName,children:r?.name}),f.length>0&&(0,x.jsx)(`div`,{className:W.kvList,children:f.map(([e,t])=>(0,x.jsxs)(`div`,{className:W.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:Ng(t)})]},e))}),r?.signals&&r.signals.length>0&&(0,x.jsx)(`div`,{className:W.signalList,children:r.signals.slice(0,4).map((e,t)=>(0,x.jsxs)(`div`,{className:W.signal,children:[(0,x.jsx)(`span`,{className:W.signalLabel,children:e.label}),(0,x.jsxs)(`span`,{className:W.signalValue,children:[typeof e.value==`number`?jg(e.value):String(e.value),e.unit?` ${e.unit}`:``]})]},t))})]}),(0,x.jsxs)(`div`,{className:W.card,children:[(0,x.jsxs)(`div`,{className:W.cardHeader,children:[(0,x.jsx)(`span`,{className:W.cardLabel,children:`Intervention`}),(0,x.jsx)(`span`,{className:W.cardId,children:i?.id})]}),(0,x.jsx)(`div`,{className:W.cardName,children:i?.name}),i?.description&&(0,x.jsx)(`p`,{className:W.description,children:i.description}),(0,x.jsxs)(`div`,{className:W.kvList,children:[i?.duration&&(0,x.jsxs)(`div`,{className:W.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:W.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:W.section,children:[(0,x.jsx)(`h3`,{className:W.sectionTitle,children:`Final state · delta vs initial`}),(0,x.jsx)(`div`,{className:W.metricsGrid,children:m.map(e=>{let t=u[e],n=d[e];if(typeof n!=`number`)return null;let r=typeof t==`number`?Mg(t,n):null;return(0,x.jsxs)(`div`,{className:W.metric,children:[(0,x.jsx)(`span`,{className:W.metricLabel,children:Dg[e]??e}),(0,x.jsx)(`span`,{className:W.metricValue,children:jg(n)}),r&&(0,x.jsx)(`span`,{className:`${W.metricDelta} ${r.direction===`up`?W.metricDeltaUp:r.direction===`down`?W.metricDeltaDown:``}`,children:r.text})]},e)})})]}),p&&p.series.length>0&&(0,x.jsxs)(`div`,{className:W.section,children:[(0,x.jsx)(`h3`,{className:W.sectionTitle,children:`Trajectory`}),(0,x.jsxs)(`div`,{className:W.chartWrap,children:[(0,x.jsxs)(`svg`,{className:W.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:kg[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:kg[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:W.chartLegend,children:p.series.map(e=>(0,x.jsxs)(`span`,{className:W.legendItem,children:[(0,x.jsx)(`span`,{className:`${W.legendSwatch} ${W.legendSwatchInline}`,style:{"--swatch-color":kg[e.metric]}}),Dg[e.metric]??e.metric]},e.metric))})]})]}),h.length>0&&(0,x.jsxs)(`div`,{className:W.section,children:[(0,x.jsx)(`h3`,{className:W.sectionTitle,children:`Fingerprint`}),(0,x.jsx)(`div`,{className:W.fingerprintList,children:h.map(([e,t])=>(0,x.jsxs)(`span`,{className:W.fingerprintChip,children:[e,(0,x.jsx)(`b`,{children:String(t)})]},e))})]}),(0,x.jsx)(Lg,{state:t}),n&&(0,x.jsx)(`div`,{className:W.dismissBar,children:(0,x.jsx)(`button`,{onClick:n,className:W.dismissButton,children:`Clear · run another`})})]})}function Lg({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:W.section,children:[(0,x.jsxs)(`h3`,{className:W.sectionTitle,children:[`Playback · `,r,` / `,n,` events`]}),(0,x.jsxs)(`div`,{className:W.playbackControls,children:[(0,x.jsx)(`button`,{onClick:()=>o(!a),className:W.playbackPlayBtn,children:a?`Pause`:r>=n?`Replay`:`Play`}),(0,x.jsx)(`button`,{onClick:()=>{i(0),o(!1)},className:W.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:W.playbackSlider})]}),(0,x.jsx)(`div`,{className:W.playbackList,children:c.length===0?(0,x.jsx)(`div`,{className:W.playbackHint,children:`Drag the slider or press Play to step through the run.`}):c.map(e=>(0,x.jsxs)(`div`,{className:W.playbackEvent,children:[(0,x.jsx)(`span`,{className:W.playbackTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:W.playbackType,children:Pg[e.type]??e.type}),(0,x.jsx)(`span`,{className:W.playbackBody,children:Fg(e)})]},e.id))})]})}var G={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`},Rg={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 zg(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 Bg(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 Vg({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:G.root,children:[(0,x.jsxs)(`div`,{className:G.headerRow,children:[(0,x.jsxs)(`h2`,{className:G.title,children:[(0,x.jsx)(`span`,{className:G.spinner,"aria-hidden":`true`}),`Digital Twin · Running`]}),(0,x.jsxs)(`span`,{className:G.timer,children:[r,`s elapsed · streaming live · 1 turn × LLM decisions`]})]}),(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:t.id})]}),(0,x.jsx)(`div`,{className:G.cardName,children:t.name}),y.length>0&&(0,x.jsx)(`div`,{className:G.kvList,children:y.map(([e,t])=>(0,x.jsxs)(`div`,{className:G.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:typeof t==`number`?zg(t):String(t)})]},e))})]}),(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:n.id})]}),(0,x.jsx)(`div`,{className:G.cardName,children:n.name}),(0,x.jsx)(`p`,{className:G.description,children:n.description}),n.duration&&(0,x.jsx)(`div`,{className:G.kvList,children:(0,x.jsxs)(`div`,{className:G.kv,children:[(0,x.jsx)(`span`,{children:`Duration`}),(0,x.jsxs)(`span`,{children:[n.duration.value,` `,n.duration.unit]})]})})]})]}),(0,x.jsxs)(`div`,{className:G.statsBar,children:[(0,x.jsxs)(`div`,{className:G.stat,children:[(0,x.jsx)(`span`,{className:G.statLabel,children:`Turn`}),(0,x.jsxs)(`span`,{className:G.statValue,children:[d,` / `,f]}),(0,x.jsx)(`div`,{className:G.progressBar,children:(0,x.jsx)(`div`,{className:G.progressFill,style:{width:`${p}%`}})})]}),(0,x.jsxs)(`div`,{className:G.stat,children:[(0,x.jsx)(`span`,{className:G.statLabel,children:`LLM Calls`}),(0,x.jsx)(`span`,{className:G.statValue,children:h})]}),(0,x.jsxs)(`div`,{className:G.stat,children:[(0,x.jsx)(`span`,{className:G.statLabel,children:`Cost`}),(0,x.jsxs)(`span`,{className:G.statValue,children:[`$`,m.toFixed(4)]})]}),(0,x.jsxs)(`div`,{className:G.stat,children:[(0,x.jsx)(`span`,{className:G.statLabel,children:`Tools forged`}),(0,x.jsx)(`span`,{className:G.statValue,children:g})]}),(0,x.jsxs)(`div`,{className:G.stat,children:[(0,x.jsx)(`span`,{className:G.statLabel,children:`Citations`}),(0,x.jsx)(`span`,{className:G.statValue,children:_})]})]}),(0,x.jsxs)(`div`,{className:G.eventLog,children:[(0,x.jsxs)(`div`,{className:G.eventLogHeader,children:[(0,x.jsx)(`span`,{className:G.eventLogTitle,children:`Live event log · streaming from /events`}),(0,x.jsxs)(`span`,{className:G.timer,children:[u.length,` events`]})]}),(0,x.jsx)(`div`,{ref:o,onScroll:v,className:G.eventLogScroll,children:u.length===0?(0,x.jsx)(`div`,{className:G.eventEmpty,children:`Waiting for the first server event…`}):u.map(e=>(0,x.jsxs)(`div`,{className:G.eventRow,children:[(0,x.jsx)(`span`,{className:G.eventTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:G.eventType,children:Rg[e.type]??e.type}),(0,x.jsx)(`span`,{className:G.eventBody,children:Bg(e)})]},e.id))})]})]})}var Hg=`▁▂▃▄▅▆▇█`;function Ug({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=>Hg[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 Wg(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 Gg(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:Kg(r),value:e}),n.length>=t)break}return n}function Kg(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 qg(e,t){let n=Math.round(t*4);return`${e} ${`█`.repeat(n)+`░`.repeat(4-n)} ${t.toFixed(2)}`}function Jg({actorIndex:e,leader:t,popHistory:n,moraleHistory:r,verdictPlacement:i,compact:a=!1,event:o,statuses:s,pendingDecision:c,nameFallback:l}){let u=ye(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:Wg(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)=>qg(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)(lg,{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)(Ug,{data:n,label:`POP`,color:u}),` `,(0,x.jsx)(Ug,{data:r,label:`MORALE`,suffix:`%`,color:`var(--amber)`})]})]}),(0,x.jsx)(Yg,{moraleHistory:r,event:o,statuses:s,pendingDecision:c})]})}function Yg({moraleHistory:e,event:t,statuses:n,pendingDecision:r}){let i=e.length>0?e[e.length-1]:null,a=i===null?null:Wg(i),o=Gg(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:Kg(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 Xg(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 Zg(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function Qg(e,t){if(t.format===`percent`)return`${Math.round(Zg(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 $g={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 e_(e){return e===`foodMonthsReserve`?`mo`:``}var t_={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},n_={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function r_(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function i_(e,t){return e?t===`neutral`?$g.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?$g.deltaPositive:$g.deltaNegative:e.startsWith(`+`)?$g.deltaPositive:$g.deltaNegative:``}function a_(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 o_({actors:e,crisisText:t,toolRegistry:n}){let r=Nw(),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=r_(g,k.toolsA),re=r_(_,k.toolsB),ie=r_(D,k.reuseA),ae=r_(O,k.reuseB),oe=r_(v,k.citationsA),se=r_(y,k.citationsB),A=r_(f,k.deathsA),ce=r_(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 le=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),ue=ye(0),de=ye(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${$g.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":ue,"--actor-color-b":de},children:[t&&(0,x.jsx)(`span`,{className:$g.crisis,children:t}),le.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:Zg(t,e),i=r_(Zg(t,e),r(u?.[e.id])),a=r_(Zg(n,e),r(d?.[e.id])),o=Qg(t,e),s=Qg(n,e),f=e_(e.id),p=t_[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=n_[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:i_(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:$g.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:$g.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:i_(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.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}),A&&(0,x.jsx)(`span`,{className:i_(A,`lossIsRed`),children:A}),(0,x.jsx)(`span`,{className:$g.sep,children:`vs`}),(0,x.jsx)(`span`,{className:$g.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}),ce&&(0,x.jsx)(`span`,{className:i_(ce,`lossIsRed`),children:ce}),(()=>{let e=a_(m),t=a_(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:$g.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:g}),ne&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ne}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:_}),re&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:re})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:D}),ie&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ie}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:O}),ae&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ae})]}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:v}),oe&&(0,x.jsx)(`span`,{className:i_(oe,`neutral`),children:oe}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:y}),se&&(0,x.jsx)(`span`,{className:i_(se,`neutral`),children:se})]}),(w||T)&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${Xg(w)||`(none)`}\n\nLeader B:\n${Xg(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:T?Object.keys(T).length:0})]}),(ee||E)&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${Xg(ee)||`(none)`}\n\nLeader B:\n${Xg(E)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:ee?Object.keys(ee).length:0}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:E?Object.keys(E).length:0})]})]})}var s_={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 c_(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 l_(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 u_(e){if(!e)return null;let{color:t}=l_(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:s_.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function d_({t:e,sideColor:t}){let{label:n,color:r}=l_(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:s_.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:s_.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:s_.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:s_.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:s_.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:s_.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:s_.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:s_.tooltipDecision,children:[(0,x.jsx)(`span`,{className:s_.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:s_.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function f_({turns:e,actorIndex:t}){let n=ye(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:s_.side,children:e.map(e=>(0,x.jsx)(lg,{dot:!0,content:(0,x.jsx)(d_,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[s_.entry,e.current?s_.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:s_.entryHead,children:[(0,x.jsxs)(`span`,{className:s_.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:s_.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:s_.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:s_.entryEmergent,children:`EMERGENT`}),u_(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:s_.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:s_.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:s_.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:s_.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:s_.entryDecision,children:e.decision})]})},e.turn))})}function p_({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?c_(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 ${s_.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=ye(e.idx);return(0,x.jsxs)(`div`,{className:s_.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:s_.sideHeader,children:[(0,x.jsxs)(`span`,{className:s_.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:s_.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:s_.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(f_,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var m_={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 h_({outcome:e}){let t=m_[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 g_={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 __({citations:e,label:t=`sources`,inline:n=!1}){let r=tg();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:[g_.row,n?g_.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:g_.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(v_,{n:e,entry:t},e))]})}function v_({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:g_.popoverWrap,children:[(0,x.jsxs)(`div`,{className:g_.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:g_.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:g_.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:g_.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:g_.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:g_.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:g_.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(lg,{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:g_.pill,children:[`[`,e,`]`]})})}var q={eventStartRow:`_eventStartRow_14tji_1`,notFirst:`_notFirst_14tji_9`,eventNumber:`_eventNumber_14tji_14`,eventStartTitle:`_eventStartTitle_14tji_21`,eventCategoryPill:`_eventCategoryPill_14tji_26`,promotionTooltipTitle:`_promotionTooltipTitle_14tji_35`,promotionTooltipRow:`_promotionTooltipRow_14tji_42`,promotionTooltipKey:`_promotionTooltipKey_14tji_46`,promotionTooltipValue:`_promotionTooltipValue_14tji_50`,promotionTooltipReason:`_promotionTooltipReason_14tji_55`,promotionRow:`_promotionRow_14tji_60`,promotionArrow:`_promotionArrow_14tji_70`,promotionRole:`_promotionRole_14tji_75`,promotionReason:`_promotionReason_14tji_81`,forgeBtn:`_forgeBtn_14tji_90`,forgeSlide:`_forgeSlide_14tji_1`,forgeRow:`_forgeRow_14tji_110`,forgeBadge:`_forgeBadge_14tji_117`,forgeDept:`_forgeDept_14tji_130`,forgeDescription:`_forgeDescription_14tji_136`,forgeName:`_forgeName_14tji_141`,forgeVerdictPass:`_forgeVerdictPass_14tji_147`,forgeVerdictFail:`_forgeVerdictFail_14tji_159`,forgeFieldsRow:`_forgeFieldsRow_14tji_171`,fieldsLabelIn:`_fieldsLabelIn_14tji_181`,fieldsLabelOut:`_fieldsLabelOut_14tji_185`,forgeError:`_forgeError_14tji_189`,specWrap:`_specWrap_14tji_196`,specCard:`_specCard_14tji_200`,specHeader:`_specHeader_14tji_209`,specHeaderDept:`_specHeaderDept_14tji_217`,specToolCount:`_specToolCount_14tji_225`,severityBadge:`_severityBadge_14tji_231`,specSummary:`_specSummary_14tji_241`,specSummaryEmpty:`_specSummaryEmpty_14tji_248`,specRisks:`_specRisks_14tji_256`,specRisksLabel:`_specRisksLabel_14tji_260`,specRiskRow:`_specRiskRow_14tji_269`,specRiskSeverity:`_specRiskSeverity_14tji_278`,specRecs:`_specRecs_14tji_287`,specRecsLabel:`_specRecsLabel_14tji_291`,specRecRow:`_specRecRow_14tji_300`,toolDetail:`_toolDetail_14tji_309`,newTool:`_newTool_14tji_320`,forgeGlow:`_forgeGlow_14tji_1`,reused:`_reused_14tji_324`,toolSummary:`_toolSummary_14tji_328`,toolSummaryMain:`_toolSummaryMain_14tji_336`,toolSummaryHead:`_toolSummaryHead_14tji_341`,toolNewBadge:`_toolNewBadge_14tji_348`,toolReusedBadge:`_toolReusedBadge_14tji_361`,toolFirstForged:`_toolFirstForged_14tji_374`,toolSchemaBadge:`_toolSchemaBadge_14tji_380`,toolDescription:`_toolDescription_14tji_390`,toolNameLine:`_toolNameLine_14tji_397`,toolPassPill:`_toolPassPill_14tji_405`,toolFailPill:`_toolFailPill_14tji_418`,toolInspectBtn:`_toolInspectBtn_14tji_431`,toolBody:`_toolBody_14tji_449`,toolMetaRow:`_toolMetaRow_14tji_454`,toolMetaLabel:`_toolMetaLabel_14tji_459`,toolRawSummary:`_toolRawSummary_14tji_466`,toolRawPre:`_toolRawPre_14tji_474`,toolEmpty:`_toolEmpty_14tji_489`,outcomeCard:`_outcomeCard_14tji_494`,decisionPulse:`_decisionPulse_14tji_1`,outcomeHead:`_outcomeHead_14tji_505`,outcomeLabel:`_outcomeLabel_14tji_512`,outcomeMeta:`_outcomeMeta_14tji_520`,outcomeText:`_outcomeText_14tji_527`,outcomeDeltas:`_outcomeDeltas_14tji_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_14tji_540`,outcomeReasoningSummary:`_outcomeReasoningSummary_14tji_544`,outcomeReasoningBody:`_outcomeReasoningBody_14tji_551`,outcomeReasoningPre:`_outcomeReasoningPre_14tji_558`,outcomeRationale:`_outcomeRationale_14tji_570`,outcomePolicyLine:`_outcomePolicyLine_14tji_575`,driftRow:`_driftRow_14tji_579`,driftLabel:`_driftLabel_14tji_587`,driftName:`_driftName_14tji_595`,reactionsCard:`_reactionsCard_14tji_599`,reactionsHead:`_reactionsHead_14tji_608`,reactionsLabel:`_reactionsLabel_14tji_615`,reactionsBar:`_reactionsBar_14tji_624`,reactionsBarSegment:`_reactionsBarSegment_14tji_633`,reactionsLegend:`_reactionsLegend_14tji_638`,reactionsLegendItem:`_reactionsLegendItem_14tji_645`,reactionsLegendSwatch:`_reactionsLegendSwatch_14tji_651`,reactionsQuotesSummary:`_reactionsQuotesSummary_14tji_659`,reactionsQuotesList:`_reactionsQuotesList_14tji_667`,reactionTooltipName:`_reactionTooltipName_14tji_674`,reactionTooltipMeta:`_reactionTooltipMeta_14tji_680`,reactionTooltipHexaco:`_reactionTooltipHexaco_14tji_685`,reactionTooltipHealth:`_reactionTooltipHealth_14tji_692`,reactionTooltipQuote:`_reactionTooltipQuote_14tji_697`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_14tji_705`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_14tji_712`,reactionRow:`_reactionRow_14tji_718`,notLast:`_notLast_14tji_727`,reactionRowName:`_reactionRowName_14tji_731`,reactionRowQuote:`_reactionRowQuote_14tji_738`,reactionRowMoodPill:`_reactionRowMoodPill_14tji_749`,bulletinWrap:`_bulletinWrap_14tji_761`,bulletinTooltipName:`_bulletinTooltipName_14tji_765`,bulletinTooltipRole:`_bulletinTooltipRole_14tji_769`,bulletinTooltipBody:`_bulletinTooltipBody_14tji_774`,bulletinTooltipMood:`_bulletinTooltipMood_14tji_780`,bulletinRow:`_bulletinRow_14tji_786`,bulletinName:`_bulletinName_14tji_795`,bulletinPost:`_bulletinPost_14tji_801`,bulletinLikes:`_bulletinLikes_14tji_810`,turnDone:`_turnDone_14tji_816`,fallbackBox:`_fallbackBox_14tji_829`,fallbackTitle:`_fallbackTitle_14tji_841`,fallbackSite:`_fallbackSite_14tji_847`,fallbackPreviewWrap:`_fallbackPreviewWrap_14tji_852`,fallbackPreviewSummary:`_fallbackPreviewSummary_14tji_856`,fallbackPreviewPre:`_fallbackPreviewPre_14tji_862`,modalBackdrop:`_modalBackdrop_14tji_873`,modalDialog:`_modalDialog_14tji_884`,modalHeader:`_modalHeader_14tji_900`,modalHeaderLeft:`_modalHeaderLeft_14tji_907`,modalKicker:`_modalKicker_14tji_912`,modalTitle:`_modalTitle_14tji_922`,modalDescription:`_modalDescription_14tji_930`,modalCloseBtn:`_modalCloseBtn_14tji_936`,modalScroll:`_modalScroll_14tji_947`,modalPills:`_modalPills_14tji_953`,modalEmpty:`_modalEmpty_14tji_962`,usageList:`_usageList_14tji_968`,usageItem:`_usageItem_14tji_977`,usageHeader:`_usageHeader_14tji_988`,usageTurn:`_usageTurn_14tji_995`,usageTime:`_usageTime_14tji_1000`,usageDept:`_usageDept_14tji_1004`,usageEvent:`_usageEvent_14tji_1009`,usageStatus:`_usageStatus_14tji_1013`,usageStatusBadge:`_usageStatusBadge_14tji_1019`,usageConf:`_usageConf_14tji_1028`,usageOutput:`_usageOutput_14tji_1033`,codePre:`_codePre_14tji_1041`,fieldsBlock:`_fieldsBlock_14tji_1057`,pill:`_pill_14tji_1065`,modalSection:`_modalSection_14tji_1076`,modalSectionTitle:`_modalSectionTitle_14tji_1080`,schemaBlock:`_schemaBlock_14tji_1090`,schemaFieldsLabel:`_schemaFieldsLabel_14tji_1094`,schemaFieldsList:`_schemaFieldsList_14tji_1102`,schemaTitle:`_schemaTitle_14tji_1107`,schemaTable:`_schemaTable_14tji_1116`,schemaRow:`_schemaRow_14tji_1124`,schemaKeyCell:`_schemaKeyCell_14tji_1128`,schemaRequired:`_schemaRequired_14tji_1136`,schemaTypeCell:`_schemaTypeCell_14tji_1141`,schemaDescCell:`_schemaDescCell_14tji_1148`,forgeDetails:`_forgeDetails_14tji_1156`,forgeSummary:`_forgeSummary_14tji_1168`,forgeInspectAbs:`_forgeInspectAbs_14tji_1185`,forgeBody:`_forgeBody_14tji_1203`,specDetails:`_specDetails_14tji_1208`,specSummaryRow:`_specSummaryRow_14tji_1217`,specBody:`_specBody_14tji_1234`,reactionsDetails:`_reactionsDetails_14tji_1240`,reactionsSummary:`_reactionsSummary_14tji_1248`,reactionsTopMood:`_reactionsTopMood_14tji_1265`,reactionsBody:`_reactionsBody_14tji_1273`,bulletinDetails:`_bulletinDetails_14tji_1278`,bulletinSummary:`_bulletinSummary_14tji_1282`,bulletinSummaryLabel:`_bulletinSummaryLabel_14tji_1300`,bulletinSummaryNames:`_bulletinSummaryNames_14tji_1310`,bulletinBody:`_bulletinBody_14tji_1320`,fallbackDetails:`_fallbackDetails_14tji_1324`,fallbackSummary:`_fallbackSummary_14tji_1335`},y_={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 x_({event:e,actorIndex:t}){let n=Nw(),r=ag(),[i,a]=(0,b.useState)(null),o=ye(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)(lg,{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)(S_,{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)(__,{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)(T_,{label:`INPUT`,color:`var(--teal)`,schema:u,fields:e.inputFields}),(d||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(T_,{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)(S_,{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.systemDeltas,l=String(c.turn||``),u=Number(c._toolCount??0),d=Number(c._citeCount??0),f={"--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:f,children:[(0,x.jsxs)(`div`,{className:q.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:q.outcomeLabel,children:[`DECISION #`,l]}),(0,x.jsxs)(`span`,{className:q.outcomeMeta,children:[u,` tools · `,d,` citations`]})]}),(0,x.jsx)(h_,{outcome:e})]}),(0,x.jsx)(`div`,{className:q.outcomeText,children:n}),s&&Object.keys(s).length>0&&(0,x.jsx)(`div`,{className:q.outcomeDeltas,children:Object.entries(s).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)(lg,{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":y_[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":y_[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)(lg,{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":y_[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||``);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:[`⚠ SCHEMA FALLBACK — `,e]}),(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`site: `,t||`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 S_({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)(C_,{label:`${e.mode}`,color:`var(--text-3)`}),(0,x.jsx)(C_,{label:e.approved?`PASS ${e.confidence.toFixed(2)}`:`RETRY`,color:e.approved?`var(--green)`:`var(--amber)`}),(0,x.jsx)(C_,{label:`first forged T${e.firstForgedTurn} · ${e.firstForgedDepartment}`,color:`var(--amber)`}),e.reuseCount>0&&(0,x.jsx)(C_,{label:`reused ${e.reuseCount}×`,color:`var(--green)`}),e.departments.size>0&&(0,x.jsx)(C_,{label:`used by ${[...e.departments].join(`, `)}`,color:`var(--teal)`})]}),e.inputSchema&&(0,x.jsx)(w_,{title:`INPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.inputSchema,null,2)})}),e.outputSchema&&(0,x.jsx)(w_,{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)(w_,{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)(w_,{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)(w_,{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 C_({label:e,color:t}){return(0,x.jsx)(`span`,{className:q.pill,style:{"--pill-color":t},children:e})}function w_({title:e,children:t}){return(0,x.jsxs)(`div`,{className:q.modalSection,children:[(0,x.jsx)(`div`,{className:q.modalSectionTitle,children:e}),t]})}function T_({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 E_={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},D_={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},O_={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`},k_={same:E_.same,"different-outcome":E_.differentOutcome,"different-event":E_.differentEvent,pending:E_.pending,"one-sided":E_.oneSided};function A_({classification:e}){return(0,x.jsx)(`span`,{className:`${E_.badge} ${k_[e]}`,"aria-label":O_[e],children:D_[e]})}var j_={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`},M_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function N_(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 P_({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${j_.row} ${e.classification===`different-outcome`?j_.differentOutcome:e.classification===`different-event`?j_.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:j_.header,children:[(0,x.jsxs)(`span`,{className:j_.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(A_,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:j_.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:j_.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:j_.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:j_.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:j_.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!M_.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:j_.cell,style:{"--cell-color":ye(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:j_.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:j_.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 ${j_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:j_.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:j_.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:j_.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:j_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${j_.cellPendingSpinner}`}),N_(t)]}):a.map(e=>(0,x.jsx)(x_,{event:e,actorIndex:n},e.id))]},n)})})]})}function F_(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 I_(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=F_(e,t,n);r&&i.set(n,r)}return i}var L_={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function R_({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)(()=>I_(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>z_(a),[a]),u=(0,b.useMemo)(()=>z_(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 ${L_.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:L_.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:L_.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(P_,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function z_(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 B_={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`},V_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function H_(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 U_(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 W_({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(U_),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:B_.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:B_.header,children:[(0,x.jsxs)(`span`,{className:B_.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:B_.headerTitle,children:s}):(0,x.jsx)(`span`,{className:B_.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:B_.headerTitlePerActor,style:{"--cell-color":ye(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:B_.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!V_.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:B_.cell,style:{"--cell-color":ye(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:B_.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:B_.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:B_.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 ${B_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:B_.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:B_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${B_.cellPendingSpinner}`}),H_(o)]}):s.map(e=>(0,x.jsx)(x_,{event:e,actorIndex:a%2},e.id))]},t)})})]})}var G_={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},K_=360;function q_({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>J_(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":`${K_}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:G_.grid,style:c,children:(0,x.jsxs)(`div`,{className:G_.scrollX,children:[(0,x.jsx)(`header`,{className:G_.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:G_.headerCell,children:(0,x.jsx)(Jg,{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:G_.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:G_.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(W_,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function J_(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 Y_={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 X_(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:Y_.item,children:[(0,x.jsxs)(`span`,{className:Y_.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y_.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:Y_.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:Y_.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 Z_(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function Q_(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 $_({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:Y_.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:Y_.filterField,children:[(0,x.jsx)(`label`,{className:Y_.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:Y_.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:Y_.filterField,children:[(0,x.jsx)(`label`,{className:Y_.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:Y_.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:Y_.filterStats,children:[`Showing `,s,` of `,o]})]})}function ev({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)(()=>Q_(e.list),[e.list]),d=(0,b.useMemo)(()=>Z_(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)($_,{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:Y_.list,children:d.map(X_)}):(0,x.jsx)(`div`,{className:Y_.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:Y_.wrap,children:[(0,x.jsxs)(`summary`,{className:Y_.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:Y_.wrap,children:[(0,x.jsxs)(`h3`,{className:Y_.title,children:[t,` · `,e.list.length]}),f,p]})}function tv({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:Y_.list,children:e.list.map(X_)})}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 nv({registry:e,title:t=`Forged Toolbox`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let a=Lw();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=rv(e.inputSchema,e.inputFields),i=rv(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)(lg,{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)(iv,{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 rv(e,t){return e&&typeof e==`object`&&e.properties?Object.keys(e.properties).length:t.length}function iv({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 av={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 ov({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:av.bar,children:[(0,x.jsx)(`span`,{className:av.label,children:`Evidence`}),o>0&&(0,x.jsx)(cv,{label:`References`,count:o,onClick:()=>i(`refs`),ariaLabel:`Open References list (${o} sources)`}),s>0&&(0,x.jsx)(cv,{label:`Forged Toolbox`,count:s,onClick:()=>i(`tools`),ariaLabel:`Open Forged Toolbox (${s} tools)`}),n,(0,x.jsx)(`span`,{className:av.spacer}),(0,x.jsx)(`span`,{className:av.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(lv,{title:`References · ${o}`,onClose:a,extraActions:(0,x.jsx)(sv,{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)(tv,{registry:e})}),r===`tools`&&(0,x.jsx)(lv,{title:`Forged Toolbox · ${s}`,onClose:a,extraActions:(0,x.jsx)(sv,{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)(nv,{registry:t,title:``,collapsible:!1})})]})}function sv({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:av.exportBtn,children:e})}function cv({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:av.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:av.ctaCount,children:t})]})}function lv({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:av.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:av.modalDialog,children:[(0,x.jsxs)(`div`,{className:av.modalHeader,children:[(0,x.jsx)(`h2`,{className:av.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:av.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:av.modalBody,children:n})]})})}var uv={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function dv({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=Nw(),i=Fw(),a=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=Ih(window.localStorage);if(!e||!Lh(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=Uh(e,Hh(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){Rh(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&zh(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=om(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]);return e?(0,x.jsxs)(`div`,{className:uv.panel,children:[(0,x.jsx)(`span`,{className:uv.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:uv.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:uv.button,onClick:a,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var fv={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}=ug(),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=[fv.card,c?fv.empty:``].filter(Boolean).join(` `),u=[fv.kicker,c?fv.empty:``].filter(Boolean).join(` `),d=[fv.lead,c?fv.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:fv.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:fv.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:fv.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:fv.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:fv.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:fv.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:fv.tile,children:[(0,x.jsx)(`span`,{className:fv.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:fv.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,an(e)?`${an(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:fv.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:fv.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:fv.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 mv={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`},hv={...mv,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function gv({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`?hv:mv,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`?hv:mv,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var _v={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`},vv=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function yv(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 vv){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 bv(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 xv=`Unknown`;function Sv(e){return e?e.trim():``}function Cv(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=Sv(i?.leader?.archetype),o=a||`__unknown__`,s=a||xv,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 wv={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 Tv({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:wv.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:wv.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:wv.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${wv.pill} ${r?wv.pillFocused:``} ${a?wv.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:wv.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:wv.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var Ev=18,Dv=80,Ov=9;function kv(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+Dv,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 Av(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+Dv)*2}function jv({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>kv(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(()=>yv(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=Nw(),l=b.useMemo(()=>n.map(t=>bv(e,t)),[n,e]),u=(0,b.useMemo)(()=>Cv(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:_v.empty,children:`Constellation will appear when actors are launched.`});let h=Av(n.length);return(0,x.jsxs)(`div`,{className:_v.wrap,children:[(0,x.jsx)(Tv,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:_v.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<Ov&&(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:_v.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:_v.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=ye(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:_v.node,cx:a.cx,cy:a.cy,r:Ev,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:_v.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`?_v.outcomeSuccess:e.latestOutcome===`failure`?_v.outcomeFailure:_v.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:_v.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:_v.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${_v.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:_v.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:_v.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:_v.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:_v.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function Mv(e){return e.length>0?e[e.length-1]:0}function Nv(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:Mv(t.popHistory),morale:Mv(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function Pv(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?Nv(t,n):null}).filter(e=>e!==null)}function Fv(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function Iv(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 Lv(e,t,n){return[...e].sort((e,r)=>Iv(e,r,t,n))}var Rv={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`},zv=[{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 Bv(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function Vv({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(Fv(e)),e))},[]),s=(0,b.useMemo)(()=>Pv(e),[e]),c=(0,b.useMemo)(()=>Lv(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:Rv.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:Rv.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:Rv.scroll,children:(0,x.jsxs)(`table`,{className:Rv.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:Rv.colorCell}),zv.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":Bv(t,i),className:`${Rv.th} ${e.numeric?Rv.numeric:``} ${t?Rv.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:Rv.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:Rv.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?ye(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${Rv.row} ${t?Rv.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:Rv.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:Rv.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:Rv.nameCell,children:[(0,x.jsx)(`span`,{className:Rv.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:Rv.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:Rv.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:Rv.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.population}),(0,x.jsx)(`td`,{className:Rv.numCell,children:(0,x.jsxs)(`span`,{className:Rv.moraleWrap,children:[(0,x.jsx)(`span`,{className:Rv.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:Rv.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:Rv.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.tools})]},n.id)})})]})})})}function Hv(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 Uv(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:Hv(r,.25),median:Hv(r,.5),q3:Hv(r,.75),max:r[r.length-1]})}return i}var Wv=e=>e.popHistory,Gv=e=>e.moraleHistory;function Kv(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 qv(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 Jv={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`},Yv=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:Gv,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:Wv}],Xv=360,Zv=90,Qv=8,$v=6;function ey({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:Jv.empty,role:`status`,children:`No turns recorded yet.`});let r=t??qv(e),i=e.map(e=>Kv(e,r.lo,r.hi)),a=t=>e.length===1?180:Qv+t/(e.length-1)*344,o=e=>$v+(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:Jv.chart,viewBox:`0 0 ${Xv} ${Zv}`,width:Xv,height:Zv,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:Jv.envelope,d:s}),(0,x.jsx)(`path`,{className:Jv.iqr,d:c}),(0,x.jsx)(`path`,{className:Jv.median,d:l})]})}function ty({state:e}){let t=(0,b.useMemo)(()=>Yv.map(t=>({def:t,bands:Uv(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:Jv.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:Jv.heading,children:[(0,x.jsx)(`span`,{className:Jv.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:Jv.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:Jv.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:Jv.chartWrap,children:[(0,x.jsxs)(`div`,{className:Jv.chartHeader,children:[(0,x.jsx)(`span`,{className:Jv.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:Jv.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)(ey,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var ny={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 ry(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function iy({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=ft(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?ny.dockOverlay:ny.overlay,p=d?ny.dock:ny.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:ny.head,children:[(0,x.jsx)(`div`,{className:ny.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:ny.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:ny.body,children:[(0,x.jsx)(Jg,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:ny.section,children:[(0,x.jsxs)(`h3`,{className:ny.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:ny.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:ny.decisionItem,children:[(0,x.jsxs)(`div`,{className:ny.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:ny.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:ny.section,children:[(0,x.jsxs)(`h3`,{className:ny.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:ny.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:ny.turnArticle,children:[(0,x.jsxs)(`header`,{className:ny.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:ny.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:ny.turnEvent,children:[(0,x.jsx)(`span`,{className:ny.turnEventType,children:e.type}),` `,ry(e)]},e.id))})]},e))]})]})]})})}var ay={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 oy({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:ay.introBar,children:[(0,x.jsxs)(`div`,{className:ay.introBody,children:[(0,x.jsx)(`b`,{className:ay.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:ay.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:ay.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function sy({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,launching:a,interventionArtifact:o,interventionRunning:s,onInterventionDismiss:c,forceLayout:l}){let u=Nw(),d=Fw();if(o)return(0,x.jsx)(`div`,{className:ay.root,children:(0,x.jsx)(`div`,{className:ay.scrollableBody,children:(0,x.jsx)(Ig,{artifact:o,state:e,onDismiss:c})})});if(s)return(0,x.jsx)(`div`,{className:ay.root,children:(0,x.jsx)(`div`,{className:ay.scrollableBody,children:(0,x.jsx)(Vg,{state:e,subject:s.subject,intervention:s.intervention})})});let f=tg(),p=ag(),[m,h]=(0,b.useState)(!1),g=a??m,[_,v]=(0,b.useState)(`side-by-side`),y=(0,b.useRef)(!1),S=(0,b.useCallback)(e=>{y.current=!0,v(e)},[]);(0,b.useEffect)(()=>{y.current||e.actorIds.length>50&&_!==`constellation`&&v(`constellation`)},[e.actorIds.length,_]);let C=l??_,[w,T]=(0,b.useState)(null),ee=w?e.actorIds.indexOf(w):0,E=e.actorIds[0],D=e.actorIds[1],O=E?e.actors[E]:null,te=D?e.actors[D]:null,k=Object.values(e.actors).some(e=>e.events.length>0),ne=e.isRunning&&!k;(0,b.useEffect)(()=>{(k||e.isRunning)&&a===void 0&&h(!1)},[k,e.isRunning,a]);let re=(0,b.useCallback)(()=>{a===void 0&&h(!0),n?.()},[n,a]),ie=u.presets.find(e=>e.id==="default"),ae=ie?.leaders??ie?.actors,oe=(0,b.useMemo)(()=>typeof window>`u`?null:Vh(window.localStorage),[]),se=ae?.[0]??oe?.[0],A=ae?.[1]??oe?.[1],ce=se?.name?{name:se.name,archetype:se.archetype??``,unit:se.unit??ue(u,0),hexaco:se.hexaco??{},instructions:se.instructions??``,quote:``}:null,le=A?.name?{name:A.name,archetype:A.archetype??``,unit:A.unit??ue(u,1),hexaco:A.hexaco??{},instructions:A.instructions??``,quote:``}:null,[de,fe]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),pe=()=>{fe(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},me=O?.event,he=me?`T${me.turn} \u2014 ${me.time}: ${me.title}`:``,ge=(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]),_e=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,ve=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(ay.flashOn),window.setTimeout(()=>e.classList.remove(ay.flashOn),1200))},[]),ye=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),j=e.isRunning||e.isComplete||k||t===`connected`;return(0,x.jsxs)(`div`,{className:ay.root,children:[(0,x.jsxs)(`div`,{className:ay.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(Zt,{verdict:i}):null,C===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(jv,{state:e,onActorClick:e=>T(e)}),(0,x.jsx)(ty,{state:e}),(0,x.jsx)(Vv,{state:e,onActorClick:e=>T(e)})]}):e.actorIds.length>=3?(0,x.jsx)(o_,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:he,toolRegistry:p}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${ay.leadersRow}`,children:[(0,x.jsx)(Jg,{actorIndex:0,leader:O?.leader||ce,popHistory:O?.popHistory||[],moraleHistory:O?.moraleHistory||[],verdictPlacement:ge(`A`),event:O?.event,statuses:O?.statuses,pendingDecision:O?.pendingDecision}),(0,x.jsx)(Jg,{actorIndex:1,leader:te?.leader||le,popHistory:te?.popHistory||[],moraleHistory:te?.moraleHistory||[],verdictPlacement:ge(`B`),event:te?.event,statuses:te?.statuses,pendingDecision:te?.pendingDecision})]}),(0,x.jsx)(o_,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:he,toolRegistry:p})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:ay.progressBar,children:[(0,x.jsxs)(`span`,{className:ay.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:ay.progressTrack,children:(0,x.jsx)(`div`,{className:ay.progressFill,style:{width:`${_e}%`}})}),(0,x.jsxs)(`span`,{className:ay.progressPercent,children:[Math.round(_e),`%`]})]}),de&&(O?.events.length??0)>0&&(0,x.jsx)(oy,{onDismiss:pe}),ne&&!k&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),g&&!k&&!e.isRunning&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!k&&!e.isComplete&&!g&&t===`connecting`&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!k&&t===`connected`&&!g&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!k&&t===`connected`&&!g&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:ay.centerState,children:[(0,x.jsx)(`div`,{className:ay.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:ay.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:ay.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:re,disabled:g||!d,className:ay.buttonRun,children:g?`Launching…`:d?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:ve,className:ay.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:ye,className:ay.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:ay.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:ay.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:ay.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${ay.replayCtaWrap} ${ay.flashCard}`,children:(0,x.jsx)(pv,{})})]}),j&&C===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)(R_,{state:e}),j&&C===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(q_,{state:e}),(0,x.jsx)(p_,{state:e})]}),(0,x.jsx)(ov,{citationRegistry:f,toolRegistry:p,layoutToggle:(0,x.jsx)(gv,{layout:C,actorCount:e.actorIds.length,onChange:S})}),(0,x.jsx)(dv,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(iy,{actorName:w,actorIndex:ee>=0?ee:0,state:e,onClose:()=>T(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function cy(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 ly({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=cy(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 uy={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 dy(){return(0,x.jsxs)(`div`,{className:uy.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:uy.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:uy.body,children:[(0,x.jsx)(`div`,{className:uy.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:uy.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:uy.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:uy.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:uy.link,children:`Trait-model cookbook`})]})]})]})}var fy={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`}],my=[{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 hy({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:fy.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:fy.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${fy.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:fy.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:fy.input})]}),(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:fy.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:fy.input})]}),(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:fy.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:fy.input})]})]}),(0,x.jsxs)(`div`,{className:fy.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:fy.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:fy.textarea})]}),(0,x.jsx)(dy,{}),(0,x.jsxs)(`div`,{className:fy.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:fy.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${fy.presetSelect}`,onChange:e=>{let t=my.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...`}),my.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${fy.hexacoGrid}`,children:py.map(e=>(0,x.jsx)(ly,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function gy(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 _y={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},vy={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},yy={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`},by={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`},xy={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:[]},Sy=`paracosm:editorCompileResult`;function Cy(){try{let e=window.sessionStorage.getItem(Sy);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 wy(){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)(()=>Cy()),k=(0,b.useRef)(null),ne=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t).catch(()=>{});try{window.sessionStorage.removeItem(Sy)}catch{}},[]);let re=(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)(()=>(re(),E(window,re)),[re]),(0,b.useEffect)(()=>{if(!n.trim())a(``);else try{JSON.parse(n),a(``)}catch(e){a(String(e).replace(`SyntaxError: `,``))}},[n]);let ie=()=>r(JSON.stringify(xy,null,2)),ae=(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}`})}},[]),oe=()=>k.current?.click(),se=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=``},A=()=>{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`})}},ce=(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]),le=(0,b.useCallback)(async()=>{if(n.trim()&&!i&&e.adminWrite)try{let e=JSON.parse(n),t=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!0})})).json();t.savedToDisk?(ee(window),O({success:!0,message:t.switchable?`Saved "${t.id}" to disk at scenarios/${t.id}.json and loaded it into the live scenario catalog.`:`Saved "${t.id}" draft JSON to disk at scenarios/${t.id}.json. Compile it to make it runnable after restart.`})):O({success:!1,message:t.error||`Disk write not enabled (ADMIN_WRITE=false)`})}catch(e){O({success:!1,message:String(e)})}},[n,i,e.adminWrite]),ue=(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=gy({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(`
|
|
122
|
+
`)}function Zg(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function Qg(e,t){if(t.format===`percent`)return`${Math.round(Zg(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 $g={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 e_(e){return e===`foodMonthsReserve`?`mo`:``}var t_={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},n_={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function r_(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function i_(e,t){return e?t===`neutral`?$g.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?$g.deltaPositive:$g.deltaNegative:e.startsWith(`+`)?$g.deltaPositive:$g.deltaNegative:``}function a_(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 o_({actors:e,crisisText:t,toolRegistry:n}){let r=Pw(),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=r_(g,k.toolsA),re=r_(_,k.toolsB),ie=r_(D,k.reuseA),ae=r_(O,k.reuseB),oe=r_(v,k.citationsA),se=r_(y,k.citationsB),A=r_(f,k.deathsA),ce=r_(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 le=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),ue=ye(0),de=ye(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${$g.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":ue,"--actor-color-b":de},children:[t&&(0,x.jsx)(`span`,{className:$g.crisis,children:t}),le.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:Zg(t,e),i=r_(Zg(t,e),r(u?.[e.id])),a=r_(Zg(n,e),r(d?.[e.id])),o=Qg(t,e),s=Qg(n,e),f=e_(e.id),p=t_[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=n_[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:i_(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:$g.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:$g.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:i_(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.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}),A&&(0,x.jsx)(`span`,{className:i_(A,`lossIsRed`),children:A}),(0,x.jsx)(`span`,{className:$g.sep,children:`vs`}),(0,x.jsx)(`span`,{className:$g.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}),ce&&(0,x.jsx)(`span`,{className:i_(ce,`lossIsRed`),children:ce}),(()=>{let e=a_(m),t=a_(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:$g.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:g}),ne&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ne}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:_}),re&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:re})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:D}),ie&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ie}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:O}),ae&&(0,x.jsx)(`span`,{className:$g.deltaPositive,children:ae})]}),(0,x.jsxs)(`span`,{className:$g.pill,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:v}),oe&&(0,x.jsx)(`span`,{className:i_(oe,`neutral`),children:oe}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:y}),se&&(0,x.jsx)(`span`,{className:i_(se,`neutral`),children:se})]}),(w||T)&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${Xg(w)||`(none)`}\n\nLeader B:\n${Xg(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:T?Object.keys(T).length:0})]}),(ee||E)&&(0,x.jsxs)(`span`,{className:$g.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${Xg(ee)||`(none)`}\n\nLeader B:\n${Xg(E)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:$g.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:$g.valueA,children:ee?Object.keys(ee).length:0}),(0,x.jsx)(`span`,{className:$g.sep,children:`/`}),(0,x.jsx)(`span`,{className:$g.valueB,children:E?Object.keys(E).length:0})]})]})}var s_={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 c_(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 l_(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 u_(e){if(!e)return null;let{color:t}=l_(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:s_.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function d_({t:e,sideColor:t}){let{label:n,color:r}=l_(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:s_.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:s_.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:s_.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:s_.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:s_.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:s_.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:s_.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:s_.tooltipDecision,children:[(0,x.jsx)(`span`,{className:s_.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:s_.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function f_({turns:e,actorIndex:t}){let n=ye(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:s_.side,children:e.map(e=>(0,x.jsx)(lg,{dot:!0,content:(0,x.jsx)(d_,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[s_.entry,e.current?s_.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:s_.entryHead,children:[(0,x.jsxs)(`span`,{className:s_.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:s_.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:s_.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:s_.entryEmergent,children:`EMERGENT`}),u_(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:s_.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:s_.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:s_.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:s_.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:s_.entryDecision,children:e.decision})]})},e.turn))})}function p_({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?c_(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 ${s_.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=ye(e.idx);return(0,x.jsxs)(`div`,{className:s_.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:s_.sideHeader,children:[(0,x.jsxs)(`span`,{className:s_.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:s_.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:s_.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(f_,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var m_={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 h_({outcome:e}){let t=m_[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 g_={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 __({citations:e,label:t=`sources`,inline:n=!1}){let r=tg();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:[g_.row,n?g_.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:g_.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(v_,{n:e,entry:t},e))]})}function v_({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:g_.popoverWrap,children:[(0,x.jsxs)(`div`,{className:g_.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:g_.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:g_.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:g_.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:g_.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:g_.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:g_.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(lg,{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:g_.pill,children:[`[`,e,`]`]})})}var q={eventStartRow:`_eventStartRow_14tji_1`,notFirst:`_notFirst_14tji_9`,eventNumber:`_eventNumber_14tji_14`,eventStartTitle:`_eventStartTitle_14tji_21`,eventCategoryPill:`_eventCategoryPill_14tji_26`,promotionTooltipTitle:`_promotionTooltipTitle_14tji_35`,promotionTooltipRow:`_promotionTooltipRow_14tji_42`,promotionTooltipKey:`_promotionTooltipKey_14tji_46`,promotionTooltipValue:`_promotionTooltipValue_14tji_50`,promotionTooltipReason:`_promotionTooltipReason_14tji_55`,promotionRow:`_promotionRow_14tji_60`,promotionArrow:`_promotionArrow_14tji_70`,promotionRole:`_promotionRole_14tji_75`,promotionReason:`_promotionReason_14tji_81`,forgeBtn:`_forgeBtn_14tji_90`,forgeSlide:`_forgeSlide_14tji_1`,forgeRow:`_forgeRow_14tji_110`,forgeBadge:`_forgeBadge_14tji_117`,forgeDept:`_forgeDept_14tji_130`,forgeDescription:`_forgeDescription_14tji_136`,forgeName:`_forgeName_14tji_141`,forgeVerdictPass:`_forgeVerdictPass_14tji_147`,forgeVerdictFail:`_forgeVerdictFail_14tji_159`,forgeFieldsRow:`_forgeFieldsRow_14tji_171`,fieldsLabelIn:`_fieldsLabelIn_14tji_181`,fieldsLabelOut:`_fieldsLabelOut_14tji_185`,forgeError:`_forgeError_14tji_189`,specWrap:`_specWrap_14tji_196`,specCard:`_specCard_14tji_200`,specHeader:`_specHeader_14tji_209`,specHeaderDept:`_specHeaderDept_14tji_217`,specToolCount:`_specToolCount_14tji_225`,severityBadge:`_severityBadge_14tji_231`,specSummary:`_specSummary_14tji_241`,specSummaryEmpty:`_specSummaryEmpty_14tji_248`,specRisks:`_specRisks_14tji_256`,specRisksLabel:`_specRisksLabel_14tji_260`,specRiskRow:`_specRiskRow_14tji_269`,specRiskSeverity:`_specRiskSeverity_14tji_278`,specRecs:`_specRecs_14tji_287`,specRecsLabel:`_specRecsLabel_14tji_291`,specRecRow:`_specRecRow_14tji_300`,toolDetail:`_toolDetail_14tji_309`,newTool:`_newTool_14tji_320`,forgeGlow:`_forgeGlow_14tji_1`,reused:`_reused_14tji_324`,toolSummary:`_toolSummary_14tji_328`,toolSummaryMain:`_toolSummaryMain_14tji_336`,toolSummaryHead:`_toolSummaryHead_14tji_341`,toolNewBadge:`_toolNewBadge_14tji_348`,toolReusedBadge:`_toolReusedBadge_14tji_361`,toolFirstForged:`_toolFirstForged_14tji_374`,toolSchemaBadge:`_toolSchemaBadge_14tji_380`,toolDescription:`_toolDescription_14tji_390`,toolNameLine:`_toolNameLine_14tji_397`,toolPassPill:`_toolPassPill_14tji_405`,toolFailPill:`_toolFailPill_14tji_418`,toolInspectBtn:`_toolInspectBtn_14tji_431`,toolBody:`_toolBody_14tji_449`,toolMetaRow:`_toolMetaRow_14tji_454`,toolMetaLabel:`_toolMetaLabel_14tji_459`,toolRawSummary:`_toolRawSummary_14tji_466`,toolRawPre:`_toolRawPre_14tji_474`,toolEmpty:`_toolEmpty_14tji_489`,outcomeCard:`_outcomeCard_14tji_494`,decisionPulse:`_decisionPulse_14tji_1`,outcomeHead:`_outcomeHead_14tji_505`,outcomeLabel:`_outcomeLabel_14tji_512`,outcomeMeta:`_outcomeMeta_14tji_520`,outcomeText:`_outcomeText_14tji_527`,outcomeDeltas:`_outcomeDeltas_14tji_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_14tji_540`,outcomeReasoningSummary:`_outcomeReasoningSummary_14tji_544`,outcomeReasoningBody:`_outcomeReasoningBody_14tji_551`,outcomeReasoningPre:`_outcomeReasoningPre_14tji_558`,outcomeRationale:`_outcomeRationale_14tji_570`,outcomePolicyLine:`_outcomePolicyLine_14tji_575`,driftRow:`_driftRow_14tji_579`,driftLabel:`_driftLabel_14tji_587`,driftName:`_driftName_14tji_595`,reactionsCard:`_reactionsCard_14tji_599`,reactionsHead:`_reactionsHead_14tji_608`,reactionsLabel:`_reactionsLabel_14tji_615`,reactionsBar:`_reactionsBar_14tji_624`,reactionsBarSegment:`_reactionsBarSegment_14tji_633`,reactionsLegend:`_reactionsLegend_14tji_638`,reactionsLegendItem:`_reactionsLegendItem_14tji_645`,reactionsLegendSwatch:`_reactionsLegendSwatch_14tji_651`,reactionsQuotesSummary:`_reactionsQuotesSummary_14tji_659`,reactionsQuotesList:`_reactionsQuotesList_14tji_667`,reactionTooltipName:`_reactionTooltipName_14tji_674`,reactionTooltipMeta:`_reactionTooltipMeta_14tji_680`,reactionTooltipHexaco:`_reactionTooltipHexaco_14tji_685`,reactionTooltipHealth:`_reactionTooltipHealth_14tji_692`,reactionTooltipQuote:`_reactionTooltipQuote_14tji_697`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_14tji_705`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_14tji_712`,reactionRow:`_reactionRow_14tji_718`,notLast:`_notLast_14tji_727`,reactionRowName:`_reactionRowName_14tji_731`,reactionRowQuote:`_reactionRowQuote_14tji_738`,reactionRowMoodPill:`_reactionRowMoodPill_14tji_749`,bulletinWrap:`_bulletinWrap_14tji_761`,bulletinTooltipName:`_bulletinTooltipName_14tji_765`,bulletinTooltipRole:`_bulletinTooltipRole_14tji_769`,bulletinTooltipBody:`_bulletinTooltipBody_14tji_774`,bulletinTooltipMood:`_bulletinTooltipMood_14tji_780`,bulletinRow:`_bulletinRow_14tji_786`,bulletinName:`_bulletinName_14tji_795`,bulletinPost:`_bulletinPost_14tji_801`,bulletinLikes:`_bulletinLikes_14tji_810`,turnDone:`_turnDone_14tji_816`,fallbackBox:`_fallbackBox_14tji_829`,fallbackTitle:`_fallbackTitle_14tji_841`,fallbackSite:`_fallbackSite_14tji_847`,fallbackPreviewWrap:`_fallbackPreviewWrap_14tji_852`,fallbackPreviewSummary:`_fallbackPreviewSummary_14tji_856`,fallbackPreviewPre:`_fallbackPreviewPre_14tji_862`,modalBackdrop:`_modalBackdrop_14tji_873`,modalDialog:`_modalDialog_14tji_884`,modalHeader:`_modalHeader_14tji_900`,modalHeaderLeft:`_modalHeaderLeft_14tji_907`,modalKicker:`_modalKicker_14tji_912`,modalTitle:`_modalTitle_14tji_922`,modalDescription:`_modalDescription_14tji_930`,modalCloseBtn:`_modalCloseBtn_14tji_936`,modalScroll:`_modalScroll_14tji_947`,modalPills:`_modalPills_14tji_953`,modalEmpty:`_modalEmpty_14tji_962`,usageList:`_usageList_14tji_968`,usageItem:`_usageItem_14tji_977`,usageHeader:`_usageHeader_14tji_988`,usageTurn:`_usageTurn_14tji_995`,usageTime:`_usageTime_14tji_1000`,usageDept:`_usageDept_14tji_1004`,usageEvent:`_usageEvent_14tji_1009`,usageStatus:`_usageStatus_14tji_1013`,usageStatusBadge:`_usageStatusBadge_14tji_1019`,usageConf:`_usageConf_14tji_1028`,usageOutput:`_usageOutput_14tji_1033`,codePre:`_codePre_14tji_1041`,fieldsBlock:`_fieldsBlock_14tji_1057`,pill:`_pill_14tji_1065`,modalSection:`_modalSection_14tji_1076`,modalSectionTitle:`_modalSectionTitle_14tji_1080`,schemaBlock:`_schemaBlock_14tji_1090`,schemaFieldsLabel:`_schemaFieldsLabel_14tji_1094`,schemaFieldsList:`_schemaFieldsList_14tji_1102`,schemaTitle:`_schemaTitle_14tji_1107`,schemaTable:`_schemaTable_14tji_1116`,schemaRow:`_schemaRow_14tji_1124`,schemaKeyCell:`_schemaKeyCell_14tji_1128`,schemaRequired:`_schemaRequired_14tji_1136`,schemaTypeCell:`_schemaTypeCell_14tji_1141`,schemaDescCell:`_schemaDescCell_14tji_1148`,forgeDetails:`_forgeDetails_14tji_1156`,forgeSummary:`_forgeSummary_14tji_1168`,forgeInspectAbs:`_forgeInspectAbs_14tji_1185`,forgeBody:`_forgeBody_14tji_1203`,specDetails:`_specDetails_14tji_1208`,specSummaryRow:`_specSummaryRow_14tji_1217`,specBody:`_specBody_14tji_1234`,reactionsDetails:`_reactionsDetails_14tji_1240`,reactionsSummary:`_reactionsSummary_14tji_1248`,reactionsTopMood:`_reactionsTopMood_14tji_1265`,reactionsBody:`_reactionsBody_14tji_1273`,bulletinDetails:`_bulletinDetails_14tji_1278`,bulletinSummary:`_bulletinSummary_14tji_1282`,bulletinSummaryLabel:`_bulletinSummaryLabel_14tji_1300`,bulletinSummaryNames:`_bulletinSummaryNames_14tji_1310`,bulletinBody:`_bulletinBody_14tji_1320`,fallbackDetails:`_fallbackDetails_14tji_1324`,fallbackSummary:`_fallbackSummary_14tji_1335`},y_={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 x_({event:e,actorIndex:t}){let n=Pw(),r=ag(),[i,a]=(0,b.useState)(null),o=ye(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)(lg,{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)(S_,{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)(__,{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)(T_,{label:`INPUT`,color:`var(--teal)`,schema:u,fields:e.inputFields}),(d||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(T_,{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)(S_,{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.systemDeltas,...c.politicsDeltas},l=String(c.turn||``),u=Number(c._toolCount??0),d=Number(c._citeCount??0),f={"--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:f,children:[(0,x.jsxs)(`div`,{className:q.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:q.outcomeLabel,children:[`DECISION #`,l]}),(0,x.jsxs)(`span`,{className:q.outcomeMeta,children:[u,` tools · `,d,` citations`]})]}),(0,x.jsx)(h_,{outcome:e})]}),(0,x.jsx)(`div`,{className:q.outcomeText,children:n}),Object.keys(s).length>0&&(0,x.jsx)(`div`,{className:q.outcomeDeltas,children:Object.entries(s).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)(lg,{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":y_[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":y_[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)(lg,{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":y_[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||``);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:[`⚠ SCHEMA FALLBACK — `,e]}),(0,x.jsxs)(`span`,{className:q.fallbackSite,children:[`site: `,t||`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 S_({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)(C_,{label:`${e.mode}`,color:`var(--text-3)`}),(0,x.jsx)(C_,{label:e.approved?`PASS ${e.confidence.toFixed(2)}`:`RETRY`,color:e.approved?`var(--green)`:`var(--amber)`}),(0,x.jsx)(C_,{label:`first forged T${e.firstForgedTurn} · ${e.firstForgedDepartment}`,color:`var(--amber)`}),e.reuseCount>0&&(0,x.jsx)(C_,{label:`reused ${e.reuseCount}×`,color:`var(--green)`}),e.departments.size>0&&(0,x.jsx)(C_,{label:`used by ${[...e.departments].join(`, `)}`,color:`var(--teal)`})]}),e.inputSchema&&(0,x.jsx)(w_,{title:`INPUT SCHEMA`,children:(0,x.jsx)(`pre`,{className:q.codePre,children:JSON.stringify(e.inputSchema,null,2)})}),e.outputSchema&&(0,x.jsx)(w_,{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)(w_,{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)(w_,{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)(w_,{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 C_({label:e,color:t}){return(0,x.jsx)(`span`,{className:q.pill,style:{"--pill-color":t},children:e})}function w_({title:e,children:t}){return(0,x.jsxs)(`div`,{className:q.modalSection,children:[(0,x.jsx)(`div`,{className:q.modalSectionTitle,children:e}),t]})}function T_({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 E_={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},D_={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},O_={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`},k_={same:E_.same,"different-outcome":E_.differentOutcome,"different-event":E_.differentEvent,pending:E_.pending,"one-sided":E_.oneSided};function A_({classification:e}){return(0,x.jsx)(`span`,{className:`${E_.badge} ${k_[e]}`,"aria-label":O_[e],children:D_[e]})}var j_={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`},M_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function N_(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 P_({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${j_.row} ${e.classification===`different-outcome`?j_.differentOutcome:e.classification===`different-event`?j_.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:j_.header,children:[(0,x.jsxs)(`span`,{className:j_.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(A_,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:j_.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:j_.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:j_.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:j_.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:j_.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!M_.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:j_.cell,style:{"--cell-color":ye(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:j_.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:j_.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 ${j_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:j_.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:j_.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:j_.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:j_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${j_.cellPendingSpinner}`}),N_(t)]}):a.map(e=>(0,x.jsx)(x_,{event:e,actorIndex:n},e.id))]},n)})})]})}function F_(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 I_(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=F_(e,t,n);r&&i.set(n,r)}return i}var L_={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function R_({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)(()=>I_(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>z_(a),[a]),u=(0,b.useMemo)(()=>z_(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 ${L_.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:L_.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:L_.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(P_,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function z_(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 B_={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`},V_=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function H_(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 U_(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 W_({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(U_),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:B_.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:B_.header,children:[(0,x.jsxs)(`span`,{className:B_.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:B_.headerTitle,children:s}):(0,x.jsx)(`span`,{className:B_.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:B_.headerTitlePerActor,style:{"--cell-color":ye(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:B_.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!V_.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:B_.cell,style:{"--cell-color":ye(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:B_.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:B_.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:B_.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 ${B_.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:B_.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:B_.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${B_.cellPendingSpinner}`}),H_(o)]}):s.map(e=>(0,x.jsx)(x_,{event:e,actorIndex:a%2},e.id))]},t)})})]})}var G_={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},K_=360;function q_({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>J_(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":`${K_}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:G_.grid,style:c,children:(0,x.jsxs)(`div`,{className:G_.scrollX,children:[(0,x.jsx)(`header`,{className:G_.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:G_.headerCell,children:(0,x.jsx)(Jg,{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:G_.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:G_.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(W_,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function J_(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 Y_={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 X_(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:Y_.item,children:[(0,x.jsxs)(`span`,{className:Y_.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y_.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:Y_.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:Y_.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 Z_(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function Q_(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 $_({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:Y_.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:Y_.filterField,children:[(0,x.jsx)(`label`,{className:Y_.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:Y_.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:Y_.filterField,children:[(0,x.jsx)(`label`,{className:Y_.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:Y_.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:Y_.filterStats,children:[`Showing `,s,` of `,o]})]})}function ev({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)(()=>Q_(e.list),[e.list]),d=(0,b.useMemo)(()=>Z_(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)($_,{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:Y_.list,children:d.map(X_)}):(0,x.jsx)(`div`,{className:Y_.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:Y_.wrap,children:[(0,x.jsxs)(`summary`,{className:Y_.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:Y_.wrap,children:[(0,x.jsxs)(`h3`,{className:Y_.title,children:[t,` · `,e.list.length]}),f,p]})}function tv({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:Y_.list,children:e.list.map(X_)})}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 nv({registry:e,title:t=`Forged Toolbox`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let a=Rw();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=rv(e.inputSchema,e.inputFields),i=rv(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)(lg,{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)(iv,{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 rv(e,t){return e&&typeof e==`object`&&e.properties?Object.keys(e.properties).length:t.length}function iv({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 av={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 ov({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:av.bar,children:[(0,x.jsx)(`span`,{className:av.label,children:`Evidence`}),o>0&&(0,x.jsx)(cv,{label:`References`,count:o,onClick:()=>i(`refs`),ariaLabel:`Open References list (${o} sources)`}),s>0&&(0,x.jsx)(cv,{label:`Forged Toolbox`,count:s,onClick:()=>i(`tools`),ariaLabel:`Open Forged Toolbox (${s} tools)`}),n,(0,x.jsx)(`span`,{className:av.spacer}),(0,x.jsx)(`span`,{className:av.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(lv,{title:`References · ${o}`,onClose:a,extraActions:(0,x.jsx)(sv,{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)(tv,{registry:e})}),r===`tools`&&(0,x.jsx)(lv,{title:`Forged Toolbox · ${s}`,onClose:a,extraActions:(0,x.jsx)(sv,{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)(nv,{registry:t,title:``,collapsible:!1})})]})}function sv({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:av.exportBtn,children:e})}function cv({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:av.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:av.ctaCount,children:t})]})}function lv({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:av.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:av.modalDialog,children:[(0,x.jsxs)(`div`,{className:av.modalHeader,children:[(0,x.jsx)(`h2`,{className:av.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:av.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:av.modalBody,children:n})]})})}var uv={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function dv({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=Pw(),i=Iw(),a=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=Ih(window.localStorage);if(!e||!Lh(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=Uh(e,Hh(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){Rh(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&zh(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=om(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]);return e?(0,x.jsxs)(`div`,{className:uv.panel,children:[(0,x.jsx)(`span`,{className:uv.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:uv.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:uv.button,onClick:a,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var fv={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}=ug(),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=[fv.card,c?fv.empty:``].filter(Boolean).join(` `),u=[fv.kicker,c?fv.empty:``].filter(Boolean).join(` `),d=[fv.lead,c?fv.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:fv.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:fv.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:fv.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:fv.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:fv.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:fv.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:fv.tile,children:[(0,x.jsx)(`span`,{className:fv.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:fv.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,an(e)?`${an(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:fv.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:fv.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:fv.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 mv={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`},hv={...mv,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function gv({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`?hv:mv,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`?hv:mv,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var _v={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`},vv=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function yv(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 vv){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 bv(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 xv=`Unknown`;function Sv(e){return e?e.trim():``}function Cv(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=Sv(i?.leader?.archetype),o=a||`__unknown__`,s=a||xv,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 wv={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 Tv({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:wv.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:wv.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:wv.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${wv.pill} ${r?wv.pillFocused:``} ${a?wv.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:wv.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:wv.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var Ev=18,Dv=80,Ov=9;function kv(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+Dv,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 Av(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+Dv)*2}function jv({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>kv(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(()=>yv(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=Pw(),l=b.useMemo(()=>n.map(t=>bv(e,t)),[n,e]),u=(0,b.useMemo)(()=>Cv(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:_v.empty,children:`Constellation will appear when actors are launched.`});let h=Av(n.length);return(0,x.jsxs)(`div`,{className:_v.wrap,children:[(0,x.jsx)(Tv,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:_v.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<Ov&&(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:_v.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:_v.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=ye(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:_v.node,cx:a.cx,cy:a.cy,r:Ev,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:_v.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`?_v.outcomeSuccess:e.latestOutcome===`failure`?_v.outcomeFailure:_v.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:_v.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:_v.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${_v.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:_v.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:_v.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:_v.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:_v.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function Mv(e){return e.length>0?e[e.length-1]:0}function Nv(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:Mv(t.popHistory),morale:Mv(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function Pv(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?Nv(t,n):null}).filter(e=>e!==null)}function Fv(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function Iv(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 Lv(e,t,n){return[...e].sort((e,r)=>Iv(e,r,t,n))}var Rv={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`},zv=[{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 Bv(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function Vv({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(Fv(e)),e))},[]),s=(0,b.useMemo)(()=>Pv(e),[e]),c=(0,b.useMemo)(()=>Lv(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:Rv.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:Rv.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:Rv.scroll,children:(0,x.jsxs)(`table`,{className:Rv.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:Rv.colorCell}),zv.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":Bv(t,i),className:`${Rv.th} ${e.numeric?Rv.numeric:``} ${t?Rv.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:Rv.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:Rv.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?ye(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${Rv.row} ${t?Rv.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:Rv.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:Rv.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:Rv.nameCell,children:[(0,x.jsx)(`span`,{className:Rv.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:Rv.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:Rv.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:Rv.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.population}),(0,x.jsx)(`td`,{className:Rv.numCell,children:(0,x.jsxs)(`span`,{className:Rv.moraleWrap,children:[(0,x.jsx)(`span`,{className:Rv.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:Rv.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:Rv.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:Rv.numCell,children:n.tools})]},n.id)})})]})})})}function Hv(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 Uv(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:Hv(r,.25),median:Hv(r,.5),q3:Hv(r,.75),max:r[r.length-1]})}return i}var Wv=e=>e.popHistory,Gv=e=>e.moraleHistory;function Kv(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 qv(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 Jv={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`},Yv=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:Gv,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:Wv}],Xv=360,Zv=90,Qv=8,$v=6;function ey({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:Jv.empty,role:`status`,children:`No turns recorded yet.`});let r=t??qv(e),i=e.map(e=>Kv(e,r.lo,r.hi)),a=t=>e.length===1?180:Qv+t/(e.length-1)*344,o=e=>$v+(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:Jv.chart,viewBox:`0 0 ${Xv} ${Zv}`,width:Xv,height:Zv,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:Jv.envelope,d:s}),(0,x.jsx)(`path`,{className:Jv.iqr,d:c}),(0,x.jsx)(`path`,{className:Jv.median,d:l})]})}function ty({state:e}){let t=(0,b.useMemo)(()=>Yv.map(t=>({def:t,bands:Uv(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:Jv.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:Jv.heading,children:[(0,x.jsx)(`span`,{className:Jv.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:Jv.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:Jv.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:Jv.chartWrap,children:[(0,x.jsxs)(`div`,{className:Jv.chartHeader,children:[(0,x.jsx)(`span`,{className:Jv.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:Jv.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)(ey,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var ny={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 ry(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function iy({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=ft(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?ny.dockOverlay:ny.overlay,p=d?ny.dock:ny.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:ny.head,children:[(0,x.jsx)(`div`,{className:ny.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:ny.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:ny.body,children:[(0,x.jsx)(Jg,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:ny.section,children:[(0,x.jsxs)(`h3`,{className:ny.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:ny.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:ny.decisionItem,children:[(0,x.jsxs)(`div`,{className:ny.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:ny.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:ny.section,children:[(0,x.jsxs)(`h3`,{className:ny.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:ny.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:ny.turnArticle,children:[(0,x.jsxs)(`header`,{className:ny.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:ny.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:ny.turnEvent,children:[(0,x.jsx)(`span`,{className:ny.turnEventType,children:e.type}),` `,ry(e)]},e.id))})]},e))]})]})]})})}var ay={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 oy({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:ay.introBar,children:[(0,x.jsxs)(`div`,{className:ay.introBody,children:[(0,x.jsx)(`b`,{className:ay.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:ay.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:ay.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function sy({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,launching:a,interventionArtifact:o,interventionRunning:s,onInterventionDismiss:c,forceLayout:l}){let u=Pw(),d=Iw();if(o)return(0,x.jsx)(`div`,{className:ay.root,children:(0,x.jsx)(`div`,{className:ay.scrollableBody,children:(0,x.jsx)(Ig,{artifact:o,state:e,onDismiss:c})})});if(s)return(0,x.jsx)(`div`,{className:ay.root,children:(0,x.jsx)(`div`,{className:ay.scrollableBody,children:(0,x.jsx)(Vg,{state:e,subject:s.subject,intervention:s.intervention})})});let f=tg(),p=ag(),[m,h]=(0,b.useState)(!1),g=a??m,[_,v]=(0,b.useState)(`side-by-side`),y=(0,b.useRef)(!1),S=(0,b.useCallback)(e=>{y.current=!0,v(e)},[]);(0,b.useEffect)(()=>{y.current||e.actorIds.length>50&&_!==`constellation`&&v(`constellation`)},[e.actorIds.length,_]);let C=l??_,[w,T]=(0,b.useState)(null),ee=w?e.actorIds.indexOf(w):0,E=e.actorIds[0],D=e.actorIds[1],O=E?e.actors[E]:null,te=D?e.actors[D]:null,k=Object.values(e.actors).some(e=>e.events.length>0),ne=e.isRunning&&!k;(0,b.useEffect)(()=>{(k||e.isRunning)&&a===void 0&&h(!1)},[k,e.isRunning,a]);let re=(0,b.useCallback)(()=>{a===void 0&&h(!0),n?.()},[n,a]),ie=u.presets.find(e=>e.id==="default"),ae=ie?.leaders??ie?.actors,oe=(0,b.useMemo)(()=>typeof window>`u`?null:Vh(window.localStorage),[]),se=ae?.[0]??oe?.[0],A=ae?.[1]??oe?.[1],ce=se?.name?{name:se.name,archetype:se.archetype??``,unit:se.unit??ue(u,0),hexaco:se.hexaco??{},instructions:se.instructions??``,quote:``}:null,le=A?.name?{name:A.name,archetype:A.archetype??``,unit:A.unit??ue(u,1),hexaco:A.hexaco??{},instructions:A.instructions??``,quote:``}:null,[de,fe]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),pe=()=>{fe(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},me=O?.event,he=me?`T${me.turn} \u2014 ${me.time}: ${me.title}`:``,ge=(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]),_e=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,ve=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(ay.flashOn),window.setTimeout(()=>e.classList.remove(ay.flashOn),1200))},[]),ye=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),j=e.isRunning||e.isComplete||k||t===`connected`;return(0,x.jsxs)(`div`,{className:ay.root,children:[(0,x.jsxs)(`div`,{className:ay.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(Zt,{verdict:i}):null,C===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(jv,{state:e,onActorClick:e=>T(e)}),(0,x.jsx)(ty,{state:e}),(0,x.jsx)(Vv,{state:e,onActorClick:e=>T(e)})]}):e.actorIds.length>=3?(0,x.jsx)(o_,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:he,toolRegistry:p}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${ay.leadersRow}`,children:[(0,x.jsx)(Jg,{actorIndex:0,leader:O?.leader||ce,popHistory:O?.popHistory||[],moraleHistory:O?.moraleHistory||[],verdictPlacement:ge(`A`),event:O?.event,statuses:O?.statuses,pendingDecision:O?.pendingDecision}),(0,x.jsx)(Jg,{actorIndex:1,leader:te?.leader||le,popHistory:te?.popHistory||[],moraleHistory:te?.moraleHistory||[],verdictPlacement:ge(`B`),event:te?.event,statuses:te?.statuses,pendingDecision:te?.pendingDecision})]}),(0,x.jsx)(o_,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:he,toolRegistry:p})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:ay.progressBar,children:[(0,x.jsxs)(`span`,{className:ay.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:ay.progressTrack,children:(0,x.jsx)(`div`,{className:ay.progressFill,style:{width:`${_e}%`}})}),(0,x.jsxs)(`span`,{className:ay.progressPercent,children:[Math.round(_e),`%`]})]}),de&&(O?.events.length??0)>0&&(0,x.jsx)(oy,{onDismiss:pe}),ne&&!k&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),g&&!k&&!e.isRunning&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!k&&!e.isComplete&&!g&&t===`connecting`&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!k&&t===`connected`&&!g&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:ay.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${ay.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:ay.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:ay.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!k&&t===`connected`&&!g&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:ay.centerState,children:[(0,x.jsx)(`div`,{className:ay.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:ay.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:ay.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:re,disabled:g||!d,className:ay.buttonRun,children:g?`Launching…`:d?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:ve,className:ay.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:ye,className:ay.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:ay.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:ay.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:ay.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${ay.replayCtaWrap} ${ay.flashCard}`,children:(0,x.jsx)(pv,{})})]}),j&&C===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)(R_,{state:e}),j&&C===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(q_,{state:e}),(0,x.jsx)(p_,{state:e})]}),(0,x.jsx)(ov,{citationRegistry:f,toolRegistry:p,layoutToggle:(0,x.jsx)(gv,{layout:C,actorCount:e.actorIds.length,onChange:S})}),(0,x.jsx)(dv,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(iy,{actorName:w,actorIndex:ee>=0?ee:0,state:e,onClose:()=>T(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function cy(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 ly({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=cy(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 uy={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 dy(){return(0,x.jsxs)(`div`,{className:uy.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:uy.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:uy.body,children:[(0,x.jsx)(`div`,{className:uy.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:uy.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:uy.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:uy.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:uy.link,children:`Trait-model cookbook`})]})]})]})}var fy={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`}],my=[{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 hy({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:fy.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:fy.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${fy.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:fy.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:fy.input})]}),(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:fy.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:fy.input})]}),(0,x.jsxs)(`div`,{className:fy.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:fy.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:fy.input})]})]}),(0,x.jsxs)(`div`,{className:fy.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:fy.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:fy.textarea})]}),(0,x.jsx)(dy,{}),(0,x.jsxs)(`div`,{className:fy.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:fy.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${fy.presetSelect}`,onChange:e=>{let t=my.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...`}),my.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${fy.hexacoGrid}`,children:py.map(e=>(0,x.jsx)(ly,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function gy(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 _y={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},vy={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},yy={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`},by={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`},xy={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:[]},Sy=`paracosm:editorCompileResult`;function Cy(){try{let e=window.sessionStorage.getItem(Sy);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 wy(){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)(()=>Cy()),k=(0,b.useRef)(null),ne=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t).catch(()=>{});try{window.sessionStorage.removeItem(Sy)}catch{}},[]);let re=(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)(()=>(re(),E(window,re)),[re]),(0,b.useEffect)(()=>{if(!n.trim())a(``);else try{JSON.parse(n),a(``)}catch(e){a(String(e).replace(`SyntaxError: `,``))}},[n]);let ie=()=>r(JSON.stringify(xy,null,2)),ae=(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}`})}},[]),oe=()=>k.current?.click(),se=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=``},A=()=>{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`})}},ce=(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]),le=(0,b.useCallback)(async()=>{if(n.trim()&&!i&&e.adminWrite)try{let e=JSON.parse(n),t=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!0})})).json();t.savedToDisk?(ee(window),O({success:!0,message:t.switchable?`Saved "${t.id}" to disk at scenarios/${t.id}.json and loaded it into the live scenario catalog.`:`Saved "${t.id}" draft JSON to disk at scenarios/${t.id}.json. Compile it to make it runnable after restart.`})):O({success:!1,message:t.error||`Disk write not enabled (ADMIN_WRITE=false)`})}catch(e){O({success:!1,message:String(e)})}},[n,i,e.adminWrite]),ue=(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=gy({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
123
|
`);i=a.pop()||``;for(let e of a)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(Sy,JSON.stringify({success:!0,message:`Compiled: ${t.id} (${t.departments} departments, ${t.hooks} hooks). Configure actors below and launch.`}))}catch{}te(),window.location.reload();return}t.error&&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]),de=n.split(`
|
|
124
|
-
`).length,fe=new Blob([n]).size;return(0,x.jsxs)(`div`,{className:by.card,children:[(0,x.jsxs)(`div`,{className:by.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:by.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:by.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:by.btnRow,children:[(0,x.jsx)(`button`,{onClick:ae,className:[by.btn,by.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:ie,className:by.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:oe,className:by.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:A,className:by.btn,disabled:!n.trim()||!!i,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:k,type:`file`,accept:`.json,application/json`,onChange:se,className:by.fileInput})]})]}),(0,x.jsxs)(`div`,{className:by.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:ne,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:by.editor}),(0,x.jsxs)(`div`,{className:by.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:[de,` lines, `,(fe/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:by.seedDetails,children:[(0,x.jsx)(`summary`,{className:by.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:by.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,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:by.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:`https://example.com/article`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),inputMode:`numeric`,placeholder:`5`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),placeholder:`anthropic or openai (optional)`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,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:by.input})]}),(0,x.jsxs)(`label`,{className:by.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:by.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:by.progressWrap,children:w.map(e=>(0,x.jsxs)(`div`,{className:by.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:by.progressStatus,children:e.status})]},e.hook))}),D&&(0,x.jsx)(`div`,{className:by.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:by.actions,children:[(0,x.jsx)(`button`,{onClick:ce,disabled:!n.trim()||!!i||S,className:by.actionBtn,"aria-label":`Store scenario in memory`,children:S?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:ue,disabled:!n.trim()||!!i||v,className:[by.actionBtn,by.primary].join(` `),"aria-label":`Compile scenario`,children:v?`Compiling...`:`Compile Scenario`}),e.adminWrite&&(0,x.jsx)(`button`,{onClick:le,disabled:!n.trim()||!!i,className:[by.actionBtn,by.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:by.spacer}),e.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:by.memCount,children:[e.memoryScenarios.length,` in memory`]})]})]})}function Ty(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``}}function Ey(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=Dy(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!ky(e,o)||n&&!Oy(e,n))})}function Dy(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Oy(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 ky(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 Ay(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=Dy(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function jy(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 My(e,t){let n=Ty(),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 Ny={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 Py(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function Fy({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>Ay(e),[e]),i=Py(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:Ny.bar,children:[(0,x.jsxs)(`div`,{className:Ny.topRow,children:[(0,x.jsxs)(`div`,{className:Ny.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ny.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:Ny.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:Ny.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:Ny.chipClear,onClick:()=>a({toolHash:``}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:Ny.resetButton,disabled:!i,onClick:()=>n(Ty()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:Ny.facetsRow,children:[(0,x.jsx)(`span`,{className:Ny.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:Ny.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[Ny.checkbox,t?Ny.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:Ny.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ny.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:Ny.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:Ny.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:Ny.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:Ny.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:Ny.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:Ny.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:Ny.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var Iy={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`},Ly={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 Ry(){return typeof window>`u`?My(``,``):My(window.location.search,window.location.hash)}function zy({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(Ry);(0,b.useEffect)(()=>{let e=()=>i(Ry());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=jy(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=Ey(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 ${Iy.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:Iy.header,children:(0,x.jsxs)(`h2`,{className:Iy.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(Fy,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:Iy.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=Ly[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:Iy.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:Iy.eventSummary,children:[(0,x.jsx)(`span`,{className:Iy.index,children:t}),(0,x.jsx)(`span`,{className:Iy.type,children:e.type}),(0,x.jsx)(`span`,{className:Iy.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:Iy.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:Iy.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:Iy.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:Iy.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:Iy.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var By=[{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 Vy(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`},Hy=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],Uy={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},Wy={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)`}]},Gy={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`}},Ky={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.`}},qy=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function Jy(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:qy[e]??`The Strategist`,unit:ue(t,e),instructions:``,hexaco:{...Uy}}}function Yy(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function Xy(e,t,n,r,i){let a=Yy(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 Zy=2,Qy=8;function $y({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),am(e===`config`?null:e)},[]),a=Nw(),o=Fw(),s=Hp(),c=Lw(),l=typeof window<`u`?Vh(window.localStorage):null,[u]=(0,b.useState)(()=>typeof window<`u`?Bh(window.localStorage):null),[d,f]=(0,b.useState)(()=>{let e=Math.max(Zy,Math.min(Qy,Math.max(Yy(a)?.length??0,l?.length??0)));return Xy(Array.from({length:e},(e,t)=>{let n=l?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??ue(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??Uy}}:Jy(t,a)}),a,a,u,[])}),p=(0,b.useRef)([]),m=(0,b.useRef)(a);(0,b.useEffect)(()=>{let e=m.current;m.current=a,f(t=>Xy(t,e,a,u,p.current))},[a.id,a.presets.length]);let h=(0,b.useCallback)((e,t)=>{f(n=>n.map((n,r)=>{if(r!==e)return n;let i=Object.keys(t).filter(e=>t[e]!==n[e]);return p.current[e]={...p.current[e],...Object.fromEntries(i.map(e=>[e,t[e]]))},t}))},[]),g=(0,b.useCallback)(()=>{f(e=>e.length<Qy?[...e,Jy(e.length,a)]:e)},[a]),_=(0,b.useCallback)(e=>{p.current.splice(e,1),f(t=>t.length>Zy?t.filter((t,n)=>n!==e):t)},[]),[v,y]=(0,b.useState)(a.setup.defaultTurns),[S,C]=(0,b.useState)(a.setup.defaultSeed),[w,T]=(0,b.useState)(a.setup.defaultStartTime),[ee,D]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[O,k]=(0,b.useState)(a.setup.defaultPopulation),ne=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=ne.current;e.has(`turns`)||y(a.setup.defaultTurns),e.has(`seed`)||C(a.setup.defaultSeed),e.has(`startTime`)||T(a.setup.defaultStartTime),e.has(`timePerTurn`)||D(a.setup.defaultTimePerTurn||0),e.has(`population`)||k(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[re,ie]=(0,b.useState)(`openai`),[ae,oe]=(0,b.useState)(!1),[se,A]=(0,b.useState)(`balanced`),[ce,le]=(0,b.useState)(!1),[de,fe]=(0,b.useState)(``),[pe,me]=(0,b.useState)([]),[he,ge]=(0,b.useState)(a.id),[_e,ve]=(0,b.useState)({}),[j,be]=(0,b.useState)(!1),[xe,Se]=(0,b.useState)(`local_demo`),[Ce,we]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[Te,M]=(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(Te))}catch{}},[Te]);let[N,Ee]=(0,b.useState)(Gy[re]??Gy.openai);(0,b.useEffect)(()=>{let e=re;Gy[e]&&Ee(Gy[e])},[re]);let De=!!Te.openai||!!Te.anthropic,Oe=!!_e.openai||!!_e.anthropic,ke=De||!j&&Oe,Ae=De||!j&&Oe,je=j&&!De?`economy`:se,Me=Vy(xe),Ne=j&&!De,Pe=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{me(e.scenarios||[]),ge(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(Pe(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&ve(e.keys),typeof e.hostedDemo==`boolean`&&be(e.hostedDemo),typeof e.serverMode==`string`&&Se(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&we({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),E(window,Pe)),[Pe]);let Fe=async e=>{if(e!==he)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(te(),window.location.reload())}catch{}},Ie=(0,b.useCallback)(async()=>{if(o){le(!0),fe(`Starting...`);try{let e={actors:d.map(e=>({...e,hexaco:e.hexaco})),provider:re,turns:v,seed:S,startTime:w,timePerTurn:ee||void 0,population:O,liveSearch:ae,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:je},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}zh(window.localStorage,d,a.id),Te.openai&&(e.apiKey=Te.openai),Te.anthropic&&(e.anthropicKey=Te.anthropic),Te.serper&&(e.serperKey=Te.serper),Te.firecrawl&&(e.firecrawlKey=Te.firecrawl),Te.tavily&&(e.tavilyKey=Te.tavily),Te.cohere&&(e.cohereKey=Te.cohere),Ae&&(e.models={...N});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){fe(`Rate limited: ${n.error||`too many simulations`}`),le(!1);return}if(n.redirect){fe(`Running...`);let e=nm(om(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else fe(`Error: ${n.error||`unknown`}`),le(!1)}catch(e){fe(`Failed: ${e}`),le(!1)}}},[d,v,S,w,ee,O,re,ae,c,a,o,Te,N,Ae,je]),Le=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(Qp,{options:Hy,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(zy,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(pv,{}),pe.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:_y,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:he,onChange:e=>Fe(e.target.value),children:pe.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===he?`● `:``,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:he})]})]}),(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:Me.label}),`. `,Me.description]}),(0,x.jsx)(`div`,{className:`${d.length>2?`responsive-grid-cohort`:`responsive-grid-2`} ${Y.leadersGrid}`,children:d.map((e,t)=>(0,x.jsxs)(`div`,{className:Y.leaderCardWrap,style:{position:`relative`},children:[(0,x.jsx)(hy,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:ye(t),data:e,onChange:e=>h(t,e)}),d.length>Zy&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>_(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:d.length<Qy?(0,x.jsxs)(`button`,{type:`button`,onClick:g,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,d.length,`/`,Qy,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,Qy,` 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:vy,className:Y.legend,children:`Simulation`}),Ne&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,Ce.maxTurns,`, population to `,Ce.maxPopulation,`, active departments to `,Ce.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:_y,children:[`Turns`,Ne&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${Ce.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,Ce.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:Ne?Ce.maxTurns:v,onChange:e=>{ne.current.add(`turns`),y(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:Ne,className:Le(Ne),title:Ne?`Locked at ${Ce.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:_y,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:ee,onChange:e=>{ne.current.add(`timePerTurn`),D(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:_y,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:S,onChange:e=>{ne.current.add(`seed`),C(parseInt(e.target.value)||a.setup.defaultSeed)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`time-input`,style:_y,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:w,onChange:e=>{ne.current.add(`startTime`),T(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:_y,children:[`Population`,Ne&&(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:Ne?30:O,onChange:e=>{ne.current.add(`population`),k(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:Ne,className:Le(Ne),title:Ne?`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:_y,children:`Provider`}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Y.input}`,value:re,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:_y,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(ae),onChange:e=>oe(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:_y,children:[`Economics`,Ne&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Le(Ne)}`,value:je,onChange:e=>A(e.target.value),disabled:Ne,title:By.find(e=>e.value===je)?.description,children:By.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:By.find(e=>e.value===je)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:vy,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:_y,children:[t,_e[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:Te[e],onChange:t=>M(n=>({...n,[e]:t.target.value})),placeholder:_e[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),ke&&(re===`openai`||re===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:vy,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(Ky).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:_y,children:Ky[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:N[e],onChange:t=>Ee(n=>({...n,[e]:t.target.value})),children:Wy[re].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:Ky[e].help})]},e))})]}),!ke&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,j?`Runs against the host API keys are capped to ${Ce.maxTurns} turns, ${Ce.maxPopulation} colonists, ${Ce.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)(wy,{}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Ie,disabled:ce||!o,"aria-label":ce?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:ce?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),de&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:de})]})]})]})}function eb(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 tb(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:eb(e.hexaco),instructions:e.instructions})),...t]}var nb={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function rb(e,t,n,r){let i=Math.max(0,t-e)*nb[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function ib(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}function ab(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function ob(e){let t=e.trajectory?.timepoints?.length??0,n=ab(e),r=Math.max(t,...n);return r>0?r:6}function sb(e,t){return ab(e).includes(t)&&t<ob(e)}var cb={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 lb(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=
|
|
126
|
-
Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:cb.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:cb.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:cb.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:cb.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()?ib(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:cb.confirmButton,children:`Fork`})]})]})})}var ub=`/retry-stats`;function db(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(ub,{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 pb(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function mb(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function hb(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function gb(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function _b({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=ft(!0),c=db(!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:pb(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,mb(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 ${pb(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${pb(-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 (`,mb(t),` reused / `,mb(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,mb(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,mb(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:mb(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:pb(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=hb(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=hb(t.avgAttempts),r=gb(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:mb(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:mb(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:pb(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:pb(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,mb(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:pb(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,mb(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:pb(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,mb(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`},yb=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],bb={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},xb={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function Sb(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function Cb(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 wb({events:e,actorName:t,baselineHexaco:n}){let r=Sb(n),i=Cb(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`}),yb.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:bb[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:vb.legend,children:yb.map(e=>(0,x.jsxs)(`span`,{className:vb.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:vb.legendSwatch,style:{"--trait-color":bb[e]}}),(0,x.jsx)(`span`,{className:vb.legendLabel,children:xb[e]}),(0,x.jsx)(`span`,{className:vb.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var Tb={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},Eb={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},Db=[`crisis`,`departments`,`decision`,`outcome`],Ob=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function kb(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function Ab(e){return e!==`quotes`}function jb(e){let t=[];for(let n of e??[])kb(n)&&!t.includes(n)&&t.push(n);return t}function Mb(e){let t=jb(e.configuredSections),n=t.length>0?t:Db,r=n.filter(Ab);for(let t of Ob)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 Nb={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`},Pb=[{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 Fb(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function Ib({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:Nb.bar,children:[(0,x.jsx)(`div`,{className:Nb.barLeftWrap,children:(0,x.jsx)(`div`,{className:Nb.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:Nb.barRightWrap,children:(0,x.jsx)(`div`,{className:Nb.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function Lb(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=Bt(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:Vt(e),a:e.a,b:e.b,text:t=>Ht(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=>Fb(e??0,`int`)}]:Pb.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>Fb(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:Nb.section,children:[(0,x.jsxs)(`div`,{className:Nb.header,children:[(0,x.jsx)(`div`,{className:Nb.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:Nb.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:Nb.headline,children:r}),i&&(0,x.jsx)(`div`,{className:Nb.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:Nb.body,children:[(0,x.jsxs)(`div`,{className:Nb.bodyHeader,children:[(0,x.jsx)(`span`,{className:Nb.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:Nb.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Wt(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:Nb.statRow,children:[(0,x.jsxs)(`div`,{className:Nb.statRowHead,children:[(0,x.jsx)(`span`,{className:Nb.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:Nb.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:Nb.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(Ib,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:Nb.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:Nb.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:Nb.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var Rb={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function zb(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 Bb(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 Vb(e,t,n){let r=n??Rb[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>Bb(e,t))].sort((e,t)=>e-t),a=zb(i,.25),o=zb(i,.75),s=zb(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=Bb(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 Hb(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=Bb(e,n),i=Bb(t,n);return Rb[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=Bb(e,n),i=Bb(t,n);return Rb[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 Ub(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=zb([...e.map(e=>Bb(e,t))].sort((e,t)=>e-t),.5),r={},i=Rb[t]===`higher`?1:-1;for(let a of e){let e=(Bb(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function Wb(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var Gb={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`},Kb=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],qb=[`morale`,`population`,`deaths`,`tools`],Jb=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function Yb({state:e}){let t=(0,b.useMemo)(()=>Pv(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>Kb.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:Vb(t,e)})),[t]),r=(0,b.useMemo)(()=>Hb(t,qb),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>Jb.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:Ub(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:Gb.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:Gb.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:Gb.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:Gb.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:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:Gb.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:Gb.quartileBlock,children:[(0,x.jsxs)(`div`,{className:Gb.metricHead,children:[(0,x.jsx)(`span`,{className:Gb.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:Gb.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:Gb.quartileRow,children:[(0,x.jsx)(`span`,{className:Gb.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:Gb.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${Gb.actorPill} ${Gb.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:Gb.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:Gb.quartileRow,children:[(0,x.jsx)(`span`,{className:Gb.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:Gb.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${Gb.actorPill} ${Gb.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:Gb.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:Gb.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:Gb.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:Gb.paretoItem,children:[(0,x.jsx)(`span`,{className:Gb.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:Gb.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:Gb.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:Gb.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:Gb.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:Gb.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:Gb.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:Gb.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:Gb.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:Gb.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:Gb.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:Gb.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?Gb.deltaPositive:n<0?Gb.deltaNegative:Gb.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${Gb.medianMetricCol} ${r}`,role:`cell`,children:[Wb(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function Xb(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 Zb(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var Qb=[{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 $b(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 ex(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 Qb.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?$b(a,e.id):[],b:o?$b(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 Qb.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?$b(t.events,e.id):[]}))}))}function nx(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:Zb(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 rx(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 ix=`(max-width: 768px)`,ax=`(max-width: 480px)`,ox=`(prefers-reduced-motion: reduce)`,sx={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`},cx={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},lx={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function ux(e,t=!1){return e?t?lx[e]??`·`:cx[e]??e.replace(/_/g,` `).toUpperCase():`·`}function dx({outcome:e,sideColor:t,compact:n}){let r=Xb(e);return(0,x.jsx)(`div`,{className:sx.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:ux(e,n)})}function fx(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=rx(ax);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:sx.section,children:[(0,x.jsx)(`div`,{className:sx.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:sx.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:[sx.cell,e.diverged?sx.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:sx.cellHead,children:[(0,x.jsxs)(`span`,{className:sx.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(dx,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(dx,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:sx.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var px={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 mx(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 hx(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 gx({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:px.card,children:[(0,x.jsxs)(`div`,{className:px.cardHeader,children:[(0,x.jsx)(`span`,{className:px.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:px.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:px.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=hx(n);return(0,x.jsxs)(`span`,{className:px.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:px.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:mx(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:px.card,children:[(0,x.jsxs)(`div`,{className:px.cardHeader,children:[(0,x.jsx)(`span`,{className:px.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:px.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:px.cardFooter,children:[(0,x.jsx)(`span`,{className:px.lastA,children:h==null?`·`:mx(h,e.unit)}),(0,x.jsx)(`span`,{className:px.lastB,children:g==null?`·`:mx(g,e.unit)})]})]})}function _x(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:px.section,style:c,children:[(0,x.jsxs)(`div`,{className:px.sectionHeader,children:[(0,x.jsx)(`span`,{className:px.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:px.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:px.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:px.legendCohortSlot,"aria-hidden":`true`,children:hx(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:px.legend,children:[(0,x.jsx)(`span`,{className:px.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:px.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${px.grid}`,children:s.map(e=>(0,x.jsx)(gx,{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 yx(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 bx(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 xx(){return{events:new Map,reactions:[],totalReactions:0}}function Sx(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 Cx(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=xx(),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=Sx(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=Sx(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=Sx(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=Sx(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 wx(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function Tx({state:e,verdict:t,reportSections:n}){let r=tg(),i=ag(),[a,o]=bx(`paracosm-reports-refs-open`,!1),[s,c]=bx(`paracosm-reports-tools-open`,!1),[l,u]=(0,b.useState)(!1),{state:d,dispatch:f}=fn(),p=Lw(),m=Hp(),[h,g]=(0,b.useState)(null),_=d.parent,v=Nw(),y=Fw(),S=_?.metadata?.scenario,C=typeof S?.id==`string`&&S.id!==v.id,w=(0,b.useCallback)(t=>!_||e.isRunning||!y||C?!1:sb(_,t),[_,e.isRunning,y,C]),T=(0,b.useCallback)(async e=>{g(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=ob(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: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}p(`studio`)}catch(e){f({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[f,p]),ee=e.actorIds[0]??null,E=e.actorIds[1]??null,[D,O]=(0,b.useState)(ee),[te,k]=(0,b.useState)(E);(0,b.useEffect)(()=>{D&&!e.actorIds.includes(D)&&O(ee),te&&!e.actorIds.includes(te)&&k(E)},[e.actorIds,D,te,ee,E]);let ne=D??ee,re=te??E,ie=e.actorIds.length>2,[ae,oe]=(0,b.useState)(!ie);(0,b.useEffect)(()=>{oe(!ie)},[ie]);let se=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,Cx(e.actors[n]?.events));return t},[e]),A=(0,b.useMemo)(()=>{let e=ne&&se.get(ne)||new Map,t=re&&se.get(re)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??xx(),b:t.get(n)??xx()}])},[se,ne,re]),ce=(0,b.useMemo)(()=>{if(!ie)return[];let t=new Set;for(let e of se.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,se.get(r)?.get(t)??xx());return[t,n]})},[ie,se,e.actorIds]),le=ne,ue=re,de=le?e.actors[le]:null,fe=ue?e.actors[ue]:null,pe=de?.leader?.name||`Leader A`,me=fe?.leader?.name||`Leader B`,he=(de?.events.some(e=>e.type===`personality_drift`)??!1)||(fe?.events.some(e=>e.type===`personality_drift`)??!1),ge=A.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),_e=A.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),ve=(0,b.useMemo)(()=>Mb({configuredSections:n,hasQuotes:ge,hasCausality:_e,hasVerdict:!!t,hasTrajectories:he,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:i.list.length>0,hasReferences:r.list.length>0}),[n,ge,_e,t,he,e.cost,i.list.length,r.list.length]),j=(0,b.useMemo)(()=>nx(A),[A]),be=(0,b.useMemo)(()=>ex(e,ne,re),[e,ne,re]),xe=(0,b.useMemo)(()=>ie?tx(e,ye):null,[ie,e]),Se=(0,b.useMemo)(()=>{let e=[];j.length>0&&e.push({id:`strip`,label:`Strip`}),be.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),he&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of A)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,j.length,be,he,A,i.list.length,r.list.length]),Ce=(0,b.useRef)(null),we=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{we.current&&Ce.current&&A.length>0&&Ce.current.scrollTo({top:Ce.current.scrollHeight,behavior:`smooth`})},[A.length]),!(de?.events.length??0)&&!(fe?.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:Ce,onScroll:()=>{let e=Ce.current;e&&(we.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[y&&C&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,S?.name??S?.id,`, and a fork runs in its parent's scenario. Switch to `,S?.name??S?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&A.length===0)return null;let i=A.length,a=A[A.length-1],o=A[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=de?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=fe?.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":wx(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=>oe(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:ne??``,onChange:e=>O(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===re,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:re??``,onChange:e=>k(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.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:j,leaderAName:pe,leaderBName:me})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!ie||ae?(0,x.jsx)(_x,{metrics:be,leaderAName:pe,leaderBName:me}):xe&&(0,x.jsx)(_x,{metrics:xe,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[he&&ae&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(wb,{events:de?.events??[],actorName:pe,baselineHexaco:de?.leader?.hexaco}),(0,x.jsx)(wb,{events:fe?.events??[],actorName:me,baselineHexaco:fe?.leader?.hexaco})]}),he&&!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)(wb,{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)(_b,{combined:e.cost,leaderA:(le?e.costByActor[le]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(ue?e.costByActor[ue]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:de?.leader?.name,leaderBName:fe?.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&&A.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`}),w(e)&&(0,x.jsxs)(`button`,{type:`button`,className:cb.forkButton,onClick:()=>g(e),"aria-label":`Fork at ${m.time} ${e}`,children:[`↳ Fork at `,m.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)(Dx,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:pe,sideColor:`var(--vis)`,sections:ve.eventSections}),(0,x.jsx)(Dx,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:me,sideColor:`var(--eng)`,sections:ve.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(Ox,{data:n,name:pe,sideColor:`var(--vis)`,showQuotes:ve.footerSections.includes(`quotes`)}),(0,x.jsx)(Ox,{data:r,name:me,sideColor:`var(--eng)`,showQuotes:ve.footerSections.includes(`quotes`)})]})]},e)}),ie&&ce.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`}),w(t)&&(0,x.jsxs)(`button`,{type:`button`,className:cb.forkButton,onClick:()=>g(t),"aria-label":`Fork at ${m.time} ${t}`,children:[`↳ Fork at `,m.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)(Dx,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:ve.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)(Ox,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:ve.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:i.list.length>0&&(0,x.jsx)(nv,{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)(Lb,{verdict:t,leaderAName:pe,leaderBName:me}),(0,x.jsx)(Yb,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(Zt,{verdict:t})})]}),(0,x.jsx)(`section`,{id:`references`,children:r.list.length>0&&(0,x.jsx)(ev,{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:ve.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:Tb[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:ve.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:Eb[e]},e))})]})]})]})]}),(0,x.jsx)(yx,{items:Se,scrollRoot:Ce.current}),h!==null&&_&&(0,x.jsx)(lb,{parentArtifact:_,atTurn:h,maxTurns:ob(_),costPreset:`economy`,provider:`openai`,onConfirm:T,onClose:()=>g(null)})]})}var Ex={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Dx({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)(h_,{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)(__,{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 Ox({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":Ex[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`},kx={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Ax(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function jx({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":Ax(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 Mx({state:e,onChatUsage:t}){let n=Nw(),[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=r?a.get(r)??[]:[];r&&s.get(r);let _=(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]),v=e.actorIds.length>=2,[y,S]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!v)y!==null&&S(null);else if(y!==`all`&&!(y&&_.has(y))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(_.get(e)?.length??0)>0);S(t??`all`)}else S(`all`)}},[v,_,e.actorIds,y]);let[C,w]=(0,b.useState)(null),T=(0,b.useMemo)(()=>{if(y&&y!==`all`)return _.get(y)??[];let e=[],t=new Set;for(let n of _.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[_,y]),ee=(0,b.useMemo)(()=>{let e=new Set;for(let t of T){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[T]);(0,b.useEffect)(()=>{C&&!ee.includes(C)&&w(null)},[ee,C]);let E=(0,b.useMemo)(()=>C?T.filter(e=>(e.department||``).trim()===C):T,[T,C]),D=E.find(e=>e.name===r);(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[g,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let O=e=>{i(e),o(t=>{if(t.has(e))return t;let n=E.find(t=>t.name===e),r=n?{role:`agent`,name:n.name,text:`${n.role} in ${n.department}, age ${n.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.`},i=new Map(t);return i.set(e,[r]),i})},te=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},k=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},ne=async()=>{if(!l.trim()||!r||d)return;let e=r,n=l.trim();u(``),f(!0),te(e,e=>[...e,{role:`user`,text:n}]);let i=[...s.get(e)??[],{role:`user`,content:n}];k(e,()=>i);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),a=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,message:n,history:i,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(a.reply){te(e,t=>[...t,{role:`agent`,name:a.colonist||e,text:a.reply}]),k(e,e=>[...e,{role:`assistant`,content:a.reply}]);let n=a.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else te(e,e=>[...e,{role:`agent`,text:a.error||`No response`}])}catch(t){te(e,e=>[...e,{role:`agent`,text:`Chat failed: ${t}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),v&&_.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:y??``,onChange:e=>S(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 _.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=_.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)})]})]}),ee.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:C??``,onChange:e=>w(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,T.length,`)`]}),ee.map(e=>{let t=T.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>O(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":kx[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(jx,{memory:D.memory,events:e,scenario:n}),g.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&ne(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:ne,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 Nx(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 Px={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 Fx(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 Ix(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 Lx(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 Rx(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function zx(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 Bx(e,t,n){let r=zx(t,n,Rx(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=Fx(Ix(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,Lx(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function Vx(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=Fx(Ix(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,Lx(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=Fx(Ix(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,Lx(o,c,t,n))}),r}function Hx(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=Fx(Ix(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,Lx(s,c,t,n))}return i}function Ux(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=Fx(Ix(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,Lx(o,s,t,n))}return r}function Wx(e,t,n,r){return t===`families`?Vx(e,n,r):t===`mood`?Hx(e,n,r):t===`age`?Ux(e,n,r):Bx(e,n,r)}function Gx(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 Kx={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)`},qx=6;function Jx(e,t){e.save();for(let n of t){let t=Kx[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<qx;t++){let r=t/qx*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 Yx={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 Xx(e){return Yx[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function Zx(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=Xx(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=Xx(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 Qx(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 $x(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 eS(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 nS(){return{items:[]}}function rS(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function iS(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 aS(e){return e.items}var oS=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function sS(e,t,n,r){let i=(0,b.useRef)(nS()),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=rx(ox);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(),s=new Set(r.cells.map(e=>e.agentId)),l=new Set(t.cells.map(e=>e.agentId));for(let e of t.cells)if(!s.has(e.agentId)&&e.alive){let t=o.get(e.agentId);t&&rS(i.current,{kind:`birth`,x:t.x,y:t.y,totalFrames:30,sourceId:e.agentId})}for(let e of r.cells){let n=t.cells.find(t=>t.agentId===e.agentId);if(n&&e.alive&&!n.alive||e.alive&&!l.has(e.agentId)){let t=o.get(e.agentId);t&&rS(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(!oS.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),rS(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&&rS(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&&rS(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,iS(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:aS(i.current),tickClock:o}}function cS(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 lS={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function uS(e){return lS[(e||``).toLowerCase()]??`#a89878`}function dS({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:uS(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 fS={"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.`},pS={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 mS({snapshot:e,sideColor:t}){let n=rx(ix),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:[pS.strip,n?pS.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[pS.col,pS.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:pS.rowBaseline,children:[(0,x.jsx)(`span`,{className:pS.label,title:fS[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:pS.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:pS.bar,children:(0,x.jsx)(`div`,{className:pS.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:pS.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:pS.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:pS.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:pS.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:pS.col,children:[(0,x.jsxs)(`div`,{className:pS.moodHeader,children:[(0,x.jsx)(`span`,{className:pS.label,title:fS[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:pS.value2,title:fS[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:pS.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:pS.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:pS.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:pS.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:pS.col,children:[(0,x.jsx)(`div`,{className:pS.label,title:fS[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:pS.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:pS.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:pS.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:pS.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:[pS.col,pS.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:pS.row,children:[(0,x.jsx)(`span`,{className:pS.label,title:fS[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:pS.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:pS.row,children:[(0,x.jsx)(`span`,{title:fS[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:pS.value2,children:d})]}),(0,x.jsxs)(`div`,{className:pS.row,children:[(0,x.jsx)(`span`,{title:fS[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:pS.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:pS.deptBlock,"aria-label":`Department breakdown`,title:fS[`stat.depts`],children:[(0,x.jsx)(dS,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:pS.deptLabel,children:`Depts`})]})]})}var hS={cols:12,rows:6,seedRadius:2},gS=[[1,0],[2,1],[0,2],[1,2],[2,2]],_S=[[0,1],[1,1],[2,1]],vS=[[0,0],[1,0],[0,1],[1,1]],yS=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],bS=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],xS=[[1,0],[2,0],[0,1],[1,1],[1,2]];function SS(e){switch(e){case`positive`:case`hopeful`:return vS;case`neutral`:return yS;case`anxious`:return _S;case`resigned`:return bS;case`defiant`:case`negative`:return gS;default:return _S}}function CS(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 wS(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 TS(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 ES(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 DS(e){switch(e){case`birth`:return vS;case`forge`:return gS;case`crisis`:return xS;case`death`:return[];default:return null}}function OS(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function kS(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=DS(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??SS(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 AS(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=vS;break;case`forge_approved`:l=gS;break;case`forge_rejected`:l=_S;break;case`reuse`:l=bS;break;case`crisis`:l=xS;break;default:l=_S}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 jS(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 MS(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 NS(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 PS=[`O`,`C`,`E`,`A`,`Em`,`HH`];function FS(e,t){let n=t/2,r=t/2,i=t/2-8;return PS.map((t,a)=>{let o=Math.PI*2*a/PS.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 IS(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/PS.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function LS({profile:e,colonyMean:t,size:n=160}){let r=FS(e,n),i=t?FS(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)),PS.map((e,t)=>{let r=IS(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 RS={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`},zS={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function BS(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])=>`${zS[e]} ${t.toFixed(2)}`).join(` · `)}function VS(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=rx(ax);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:RS.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:RS.popover,style:C,children:[(0,x.jsxs)(`div`,{className:RS.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:RS.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:RS.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:RS.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:RS.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:RS.section,children:(0,x.jsxs)(`div`,{className:RS.statsGrid,children:[(0,x.jsx)(`span`,{className:RS.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:RS.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:RS.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:RS.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:RS.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:RS.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:RS.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:RS.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:RS.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:RS.statValue,children:y}),(0,x.jsx)(`span`,{className:RS.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:RS.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:RS.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:RS.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:RS.section,children:[(0,x.jsx)(`div`,{className:RS.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:RS.hexacoRow,children:[(0,x.jsx)(`div`,{className:RS.hexacoRadarWrap,children:(0,x.jsx)(LS,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:RS.hexacoTopAxes,children:BS(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:RS.section,children:[(0,x.jsx)(`div`,{className:RS.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:RS.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:RS.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:RS.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:RS.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var HS={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`},US={animSpeed:1,deptRings:!1,deptLabels:!1,lines:!1,dust:!0,crosshair:!0,ghostTrail:!1,alerts:!0,sound:!1};function WS({open:e,settings:t,onChange:n,onClose:r}){let i=ft(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:HS.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:HS.drawer,children:[(0,x.jsxs)(`div`,{className:HS.header,children:[(0,x.jsx)(`span`,{style:vy,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:HS.closeBtn,children:`×`})]}),(0,x.jsx)(GS,{label:`Animation speed`,children:[.5,1,2].map(e=>(0,x.jsx)(KS,{active:t.animSpeed===e,onClick:()=>a(`animSpeed`,e),label:`${e}x`},e))}),(0,x.jsxs)(GS,{label:`Dept rings`,children:[(0,x.jsx)(KS,{active:t.deptRings,onClick:()=>a(`deptRings`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.deptRings,onClick:()=>a(`deptRings`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Dept labels`,children:[(0,x.jsx)(KS,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Family lines`,children:[(0,x.jsx)(KS,{active:t.lines,onClick:()=>a(`lines`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.lines,onClick:()=>a(`lines`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Star dust bg`,children:[(0,x.jsx)(KS,{active:t.dust,onClick:()=>a(`dust`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.dust,onClick:()=>a(`dust`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Crosshair`,children:[(0,x.jsx)(KS,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Ghost trail`,children:[(0,x.jsx)(KS,{active:t.ghostTrail,onClick:()=>a(`ghostTrail`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.ghostTrail,onClick:()=>a(`ghostTrail`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Alert toasts`,children:[(0,x.jsx)(KS,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(GS,{label:`Sound cues`,children:[(0,x.jsx)(KS,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(KS,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(US),style:yy,className:HS.resetBtn,children:`Reset defaults`})]})]})}function GS({label:e,children:t}){return(0,x.jsxs)(`div`,{className:HS.row,children:[(0,x.jsx)(`span`,{style:_y,className:HS.rowLabel,children:e}),(0,x.jsx)(`div`,{className:HS.pillRow,children:t})]})}function KS({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[HS.pill,e?HS.pillActive:``].filter(Boolean).join(` `),children:n})}var qS={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`},JS={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)`},YS=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function XS({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=Hp(),{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:qS.drawer,children:[(0,x.jsxs)(`div`,{className:qS.header,style:v,children:[(0,x.jsxs)(`span`,{className:qS.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:qS.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:qS.sortRow,children:YS.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[qS.sortChip,t?qS.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:qS.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:qS.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:qS.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:qS.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:qS.swatch,style:{"--swatch-bg":JS[e.mood]??JS.neutral}}),(0,x.jsx)(`span`,{className:qS.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:qS.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:qS.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:[qS.row,qS.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:qS.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:qS.rowName,children:e.name})]},e.agentId)})]})]})]})}function ZS({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 QS(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 $S(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=US,focusedSide:T=null,onToggleFocus:ee,onOpenChat:E,eventFilter:D=`all`,chronicleHover:O=null,isLiveRun:te=!0}=e,k=T===c,ne=rx(ix),re=rx(ox),ie=Hp(),ae=(0,b.useRef)(null),oe=(0,b.useRef)(null),se=(0,b.useRef)(null),[A,ce]=(0,b.useState)({w:0,h:0}),[le,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(null),[pe,me]=(0,b.useState)(null),[he,ge]=(0,b.useState)(!1),[_e,ve]=(0,b.useState)(null),[ye,j]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(re){j(!0);return}let e=requestAnimationFrame(()=>j(!0));return()=>cancelAnimationFrame(e)},[re]);let be=(0,b.useRef)(OS(hS.cols,hS.rows)),xe=(0,b.useRef)(-1),Se=(0,b.useRef)(``),Ce=(0,b.useRef)(``),we=(0,b.useRef)(null),Te=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=oe.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));ce(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=se.current;if(!e||A.w===0||A.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(A.w*t),e.height=Math.round(A.h*t),e.style.width=`${A.w}px`,e.style.height=`${A.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[A.w,A.h]);let M=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),N=(0,b.useMemo)(()=>!t||A.w===0?new Map:Wx(t.cells,M,A.w,A.h),[t,M,A.w,A.h]),Ee=(0,b.useMemo)(()=>t?cS(t.cells,N):new Map,[t,N]),De=sS({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},oe,()=>N,()=>Ee),Oe=f===`forge`?.7:f===`ecology`?0:1,ke=(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=se.current;if(!e||!t)return;let r=e.getContext(`2d`);if(!r)return;let c=De.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=QS(s,ae.current),d=ae.current?getComputedStyle(ae.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,A.w,A.h);let E=be.current,O=f!==Se.current,k=t.turn!==xe.current,ne=D!==Ce.current;if(k||O||ne){xe.current=t.turn,Se.current=f,Ce.current=D,kS(E,t.cells,N,A.w,A.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)jS(E);we.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!==we.current&&(we.current=e,AS(E,c[0],A.w,A.h),re||jS(E))}let oe=typeof document<`u`&&document.documentElement.classList.contains(`light`);if(te&&MS(r,E,A.w,A.h,u,oe?.22:.65),D===`death`?wS(r,t.cells,N,A.w,A.h,hS.cols,hS.rows,C,T):D===`birth`&&CS(r,t.cells,N,A.w,A.h,hS.cols,hS.rows),Jx(r,c),f!==`ecology`&&Gx(r,t.cells,N,u,Oe,_,f===`divergence`,re?0:performance.now(),S,!0,g,te?m:`transparent`),f===`forge`&&h&&h.length>0&&Qx(r,t.cells,N,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&$x(r,t,A.w,A.h,ee),f===`divergence`&&eS(r,t.cells,N,_,re?0:performance.now(),u),Zx(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:A.w,height:A.h,lagTurns:l,cells:t.cells,positions:N,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:ie.Time}),le){let e=N.get(le.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(de&&!le&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,de.y),r.lineTo(A.w,de.y),r.moveTo(de.x,0),r.lineTo(de.x,A.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=N.get(n.agentId);if(!t)continue;let r=t.x-de.x,i=t.y-de.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(de.x,de.y),r.lineTo(de.x+e.dx,de.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]}`,de.x+6,de.y+6),r.restore())}if(v&&v!==le?.cell.agentId){let e=N.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())}},[De.tickClock,t,N,A.w,A.h,s,i,l,De.flares,f,Oe,le,_,v,re,S,de,w,a,o,h,D,te]);let Ae=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;fe({x:r,y:i});let a=NS(t.cells,N,r,i);if(a){ue(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ve(null),y?.(a.agentId);return}le&&(ue(null),y?.(null));let o=hS.cols,s=hS.rows,c=D===`death`||D===`birth`?(()=>{let e=Math.floor(r/Math.max(1,A.w)*o),n=Math.floor(i/Math.max(1,A.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=N.get(r.agentId);if(!t)continue;let i=ES(t,A.w,A.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=TS(be.current,r,i,A.w,A.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=N.get(r.agentId);if(!t)continue;let i=ES(t,A.w,A.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?ve({x:r,y:i,...c}):_e&&ve(null)},[t,N,le,y,D,A.w,A.h,_e]),je=(0,b.useCallback)(()=>{ue(null),ve(null),fe(null),y?.(null)},[y]),Me=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=NS(t.cells,N,r,i);a?(me({cell:a,x:r,y:i}),ue(null),ve(null),Te.current={id:a.agentId,intensity:1}):_e?.nearest&&(me({cell:_e.nearest,x:r,y:i}),ue(null),ve(null))},[t,N,_e]),Ne=(0,b.useRef)(null),Pe=(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=NS(t.cells,N,i,a);o?Ne.current===o.agentId?(me({cell:o,x:i,y:a}),ue(null),Ne.current=null,Te.current={id:o.agentId,intensity:1}):(ue({cell:o,x:i,y:a}),fe({x:i,y:a}),Ne.current=o.agentId,y?.(o.agentId)):(ue(null),fe(null),Ne.current=null,y?.(null))},[t,N,y]);(0,b.useEffect)(()=>{pe&&t&&(t.cells.find(e=>e.agentId===pe.cell.agentId)||me(null))},[pe,t]),(0,b.useEffect)(()=>{pe||(Ne.current=null)},[pe]);let Fe=QS(f===`mood`?ke:s,ae.current),Ie={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)`},Le={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)`},Re=O&&O.side===c?Ie[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`,ze=O&&O.side===c?`0 0 24px ${Le[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:ae,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${ie.place} viz`,className:[Px.region,ne?Px.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(mS,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:oe,className:Px.canvasWrap,style:{"--tint-color":te?Fe:`transparent`,"--wrap-border":Re,"--wrap-glow":ze},children:[(0,x.jsx)(`canvas`,{ref:se,role:`img`,"aria-label":t?`${i} ${ie.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 ${ie.person} glyph for drilldown.`:`${i} ${ie.place} — waiting for first turn.`,onMouseMove:Ae,onMouseLeave:je,onClick:Me,onTouchStart:Pe,className:Px.canvas,style:{"--canvas-cursor":le?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:Px.revealCover,style:{"--reveal-opacity":ye?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ge(e=>!e),"aria-label":he?`Close roster`:`Open roster`,title:he?`Close roster`:`Open roster`,className:Px.cornerBtn,style:{"--right-offset":ee?`36px`:`8px`,"--btn-color":he?`var(--amber)`:`var(--text-3)`,"--btn-border":he?`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:`${Px.cornerBtn} ${Px.focusBtn}`,style:{"--btn-color":k?`var(--amber)`:`var(--text-3)`,"--btn-border":k?`var(--amber)`:`var(--border)`},children:k?`⤡`:`⤢`}),(0,x.jsx)(ZS,{snapshot:t,previousSnapshot:n,sideColor:QS(s,ae.current),onSelect:e=>{let t=N.get(e.agentId);t&&me({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(XS,{open:he,cells:t?.cells??[],actorName:i,sideColor:QS(s,ae.current),searchQuery:S,hoveredId:le?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?N.get(e):null;if(n&&r){ue({cell:n,x:r.x,y:r.y}),y?.(e);return}}ue(null),y?.(null)},onSelect:e=>{let t=N.get(e.agentId);t&&me({cell:e,x:t.x,y:t.y})},onClose:()=>ge(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:Px.divergenceEmpty,children:(0,x.jsx)(`div`,{className:Px.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),_e&&!le&&!pe&&(()=>{let e=Math.min(Math.max(8,_e.x+12),Math.max(8,A.w-220-8)),t=Math.max(8,_e.y-84),n=_e.kind===`birth`?`+ BIRTH MARKER`:_e.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=_e.kind===`birth`?`rgba(154, 205, 96, 0.95)`:_e.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:Px.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:Px.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:Px.tileCoords,children:[`tile (`,_e.col,`, `,_e.row,`)`]}),_e.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:Px.tileNearestName,children:_e.nearest.name}),(0,x.jsxs)(`div`,{className:Px.tileNearestRole,children:[_e.nearest.role,` · `,_e.nearest.department.toUpperCase()]}),_e.kind===`death`?(0,x.jsxs)(`div`,{className:Px.tileNearestDeath,children:[`deceased · mood at death: `,_e.nearest.mood]}):_e.kind===`birth`?(0,x.jsxs)(`div`,{className:Px.tileNearestBirth,children:[`native-born · generation `,_e.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:Px.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,_e.nearest.mood]})]}):(0,x.jsx)(`div`,{className:Px.tileAmbient,children:`ambient CA cell`}),_e.kind===`life`&&(()=>{let e=be.current,t=e.cols,n=e.rows,r=e.grid[_e.row*t+_e.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=_e.row+r,s=_e.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:Px.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),le&&!pe&&(()=>{let e=Math.min(Math.max(8,le.x+12),Math.max(8,A.w-200-8)),t=Math.min(Math.max(8,le.y-80-8),Math.max(8,A.h-80-8));return(0,x.jsxs)(`div`,{className:Px.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:Px.hoverHeader,children:[le.cell.name,le.cell.featured&&(0,x.jsx)(`span`,{className:Px.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:Px.hoverRole,children:[le.cell.department.toUpperCase(),` · `,le.cell.role,typeof le.cell.age==`number`?` · age ${le.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:Px.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:Px.hoverMoodValue,children:le.cell.mood}),typeof le.cell.psychScore==`number`?` · psych ${Math.round(le.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===le.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:Px.psychBlock,children:[(0,x.jsx)(`div`,{className:Px.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:Px.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:Px.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(VS,{payload:pe,containerW:A.w,containerH:A.h,sideColor:QS(s,ae.current),hexacoById:p,snapshots:r,onClose:()=>me(null),onOpenChat:E})]})]})}var eC={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 nC(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=ye(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:eC.column,style:{"--actor-color":T},"aria-label":`Living swarm grid for actor ${t+1}: ${ee}`,children:[(0,x.jsxs)(`header`,{className:eC.columnHeader,children:[(0,x.jsxs)(`span`,{className:eC.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:eC.columnHeaderText,children:[(0,x.jsx)(`span`,{className:eC.columnHeaderName,children:ee}),S?.archetype&&(0,x.jsx)(`span`,{className:eC.columnHeaderArchetype,children:S.archetype})]}),(0,x.jsxs)(`span`,{className:eC.columnHeaderPop,title:`Population alive · morale`,children:[C?.population??`—`,` · `,C?Math.round(C.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:eC.columnBody,children:_?(0,x.jsx)($S,{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:eC.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:eC.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:eC.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function rC({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:eC.track,role:`region`,"aria-label":`Cohort swarm grid: ${f.length} actors`,children:(0,x.jsx)(`div`,{className:eC.trackInner,children:f.map((f,p)=>(0,x.jsx)(nC,{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 iC(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 oC(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 sC=6;function cC({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?oC(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,sC),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:[`: `,iC(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 lC=[.5,1,2,4];function uC({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:lC.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var dC=[{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 fC(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 pC(e,t){return fC(dC.find(t=>t.key===e)?.hint??``,t)}function mC({mode:e,onChange:t,counts:n,labels:r}){return rx(`(max-width: 480px)`)?(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:fC(dC.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:dC.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:dC.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=fC(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===dC.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 hC={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 gC({open:e,onClose:t}){let n=rx(ax),r=Hp();if(!e)return null;let i=[hC.dialog,n?hC.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:hC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:hC.header,children:[(0,x.jsxs)(`h2`,{className:hC.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:hC.closeBtn,children:`×`})]}),(0,x.jsxs)(_C,{title:`Modes`,children:[(0,x.jsx)(vC,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + family lines + event flares`}),(0,x.jsx)(vC,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(vC,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(vC,{k:`ECOLOGY`,v:`Hides glyphs; metrics strip + crisis flares lead`}),(0,x.jsx)(vC,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(_C,{title:`Grid elements`,children:[(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(vC,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(vC,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(vC,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(vC,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(_C,{title:`Event flares`,children:[(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(vC,{k:(0,x.jsx)(yC,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(_C,{title:`Family lines`,children:[(0,x.jsx)(vC,{k:`— side color, bowed`,v:`Partner link`}),(0,x.jsx)(vC,{k:`– teal, dashed`,v:`Parent → child link`})]}),(0,x.jsxs)(_C,{title:`Keyboard`,children:[(0,x.jsx)(vC,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(vC,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(vC,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(vC,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(vC,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(vC,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:hC.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:hC.kbd,children:`?`}),` anytime to reopen.`]})]})})}function _C({title:e,children:t}){return(0,x.jsxs)(`div`,{className:hC.section,children:[(0,x.jsx)(`div`,{className:hC.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:hC.rows,children:t})]})}function vC({k:e,v:t}){return(0,x.jsxs)(`div`,{className:hC.row,children:[(0,x.jsx)(`span`,{className:hC.rowKey,children:e}),(0,x.jsx)(`span`,{className:hC.rowVal,children:t})]})}function yC({color:e}){return(0,x.jsx)(`span`,{className:hC.swatchWrap,children:(0,x.jsx)(`span`,{className:hC.swatch,style:{"--swatch-color":e}})})}var bC={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 xC({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:bC.wrap,children:[(0,x.jsxs)(`div`,{className:bC.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:bC.legendRight,children:[(0,x.jsx)(`span`,{className:bC.legendA,children:`A`}),(0,x.jsx)(`span`,{className:bC.legendB,children:`B`}),(0,x.jsx)(`span`,{className:bC.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:bC.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:bC.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:bC.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:bC.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:bC.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:bC.tooltipRowA,children:[(0,x.jsx)(`span`,{className:bC.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:bC.tooltipRowB,children:[(0,x.jsx)(`span`,{className:bC.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 SC={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`},CC=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],wC={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)`},TC={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function EC({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:SC.bar,children:[(0,x.jsxs)(`span`,{className:SC.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:SC.filterRow,children:CC.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[SC.filterChip,t?SC.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:SC.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[SC.dot,c?SC.current:``,d?SC.hovered:``].filter(Boolean).join(` `),p={"--kind-color":wC[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:TC[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var DC={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 OC(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 kC({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>OC(e),[e]),i=(0,b.useMemo)(()=>OC(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:DC.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:DC.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:DC.track,children:(0,x.jsx)(`div`,{className:DC.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:DC.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:DC.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var AC={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 jC({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Hp();(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:AC.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:AC.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:AC.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:AC.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:AC.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:AC.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:AC.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:AC.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:AC.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:AC.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:AC.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:AC.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:AC.clearBtn,children:`clear`})]})]})}function MC(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 NC(e,t){switch(t){case`birth`:MC(e,880,.18,.05,`triangle`),setTimeout(()=>MC(e,1320,.12,.03,`triangle`),70);break;case`death`:MC(e,160,.35,.05,`sine`);break;case`forge`:MC(e,660,.12,.04,`sine`);break;case`crisis`:MC(e,220,.22,.05,`sawtooth`),setTimeout(()=>MC(e,180,.18,.045,`sawtooth`),120)}}function PC(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=new Set(t.cells.map(e=>e.agentId)),c=new Set(e.cells.map(e=>e.agentId)),l=0,u=0;for(let t of e.cells)if(!s.has(t.agentId)&&t.alive){let i=`${r}|t${e.turn}|birth|${t.agentId}`;n.current.has(i)||(n.current.add(i),l+=1)}for(let i of t.cells){let t=e.cells.find(e=>e.agentId===i.agentId);if(t&&i.alive&&!t.alive||i.alive&&!c.has(i.agentId)){let t=`${r}|t${e.turn}|death|${i.agentId}`;n.current.has(t)||(n.current.add(t),u+=1)}}l>0&&NC(o,`birth`),u>0&&setTimeout(()=>NC(o,`death`),l>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),NC(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var FC={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 IC(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 LC(e){let{open:t,onClose:n}=e,r=Hp();(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)(()=>IC(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>IC(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:FC.cell,children:[(0,x.jsx)(`span`,{className:FC.cellLabel,children:e}),(0,x.jsx)(`span`,{className:FC.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:FC.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:FC.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:FC.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:FC.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:FC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:FC.dialog,children:[(0,x.jsxs)(`div`,{className:FC.header,children:[(0,x.jsxs)(`h2`,{className:FC.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:FC.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:FC.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:FC.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:FC.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:FC.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:FC.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 RC={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 zC({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=ft(!!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:RC.backdrop,children:(0,x.jsxs)(`div`,{ref:c,tabIndex:-1,onClick:e=>e.stopPropagation(),className:RC.dialog,style:l,children:[(0,x.jsxs)(`div`,{className:RC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:RC.kicker,children:[`Forge Lineage · `,e.side.toUpperCase()]}),(0,x.jsx)(`div`,{className:RC.title,children:e.toolName})]}),(0,x.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close lineage`,className:RC.closeBtn,children:`×`})]}),s.firstApproved&&(0,x.jsxs)(`div`,{className:RC.firstForged,children:[`First forged in`,` `,(0,x.jsx)(`span`,{className:RC.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:RC.section,children:[(0,x.jsxs)(`div`,{className:RC.sectionLabel,children:[`Attempts (`,s.mine.length,`)`]}),s.mine.length===0?(0,x.jsx)(`div`,{className:RC.empty,children:`no forge records`}):(0,x.jsx)(`ul`,{className:RC.list,children:s.mine.map((e,t)=>{let n={"--status-color":e.approved?`var(--green)`:`var(--rust)`};return(0,x.jsxs)(`li`,{className:RC.attemptItem,style:n,children:[(0,x.jsx)(`span`,{className:RC.statusLabel,children:e.approved?`✓ Forged`:`✗ Rejected`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[RC.jumpBtn,o?RC.clickable:``].filter(Boolean).join(` `),title:o?`Jump to T${e.turn}`:void 0,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:RC.deptLabel,children:e.department}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:RC.confLabel,children:[`conf `,e.confidence.toFixed(2)]})]},`${e.turn}-${e.eventIndex}-${t}`)})})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:RC.sectionLabel,children:[`Cross-dept reuses (`,s.mineReuses.length,`)`]}),s.mineReuses.length===0?(0,x.jsx)(`div`,{className:RC.empty,children:`never reused across departments`}):(0,x.jsx)(`ul`,{className:RC.list,children:s.mineReuses.map((e,t)=>(0,x.jsxs)(`li`,{className:RC.reuseItem,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[RC.jumpBtn,o?RC.clickable:``].filter(Boolean).join(` `),children:[`T`,e.turn]}),(0,x.jsxs)(`span`,{className:RC.deptLabel,children:[e.originDept,` → `,e.callingDept]})]},`${e.turn}-${e.callingDept}-${t}`))})]})]})})}var BC={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 VC({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:BC.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:[BC.trigger,i?BC.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:BC.recDot}),`EXPORT ▼`]}),i&&(0,x.jsxs)(`div`,{role:`menu`,className:BC.menu,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),t()},className:BC.item,children:[(0,x.jsx)(`span`,{className:BC.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:BC.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),r()},className:[BC.item,e?BC.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[BC.itemKey,e?BC.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:BC.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),n()},className:BC.item,children:[(0,x.jsx)(`span`,{className:BC.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:BC.itemDesc,children:`Replay snapshot`})]})]})]})}var HC={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},UC=120;function WC({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>UC,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:HC.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:HC.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:HC.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var GC={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 KC({departments:e}){let[t,n]=(0,b.useState)(!1),r=ft(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:GC.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:GC.glyphRow,children:[(0,x.jsx)(qC,{type:`band`}),(0,x.jsx)(`span`,{className:GC.label,children:`Department band`}),(0,x.jsx)(qC,{type:`agent`}),(0,x.jsx)(`span`,{className:GC.label,children:`Agent`}),(0,x.jsx)(qC,{type:`featured`}),(0,x.jsx)(`span`,{className:GC.label,children:`Featured agent`}),(0,x.jsx)(qC,{type:`turn`}),(0,x.jsx)(`span`,{className:GC.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:GC.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:GC.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:GC.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:GC.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:GC.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:GC.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:GC.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function qC({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${GC.glyph} ${GC.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${GC.glyph} ${GC.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${GC.glyph} ${GC.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${GC.glyph} ${GC.turn}`,"aria-hidden":`true`,children:`T`})}}var JC={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`},YC=8;function XC({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,YC);return n.length===0?(0,x.jsxs)(`div`,{className:JC.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:JC.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:JC.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:JC.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:JC.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:JC.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:`${JC.chip} ${i?JC.chipStrong:JC.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:JC.chipDept,children:r}),(0,x.jsxs)(`span`,{className:JC.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var ZC=.2;function QC(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 $C(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)>=ZC){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 ${ew(a)}; the other held ${ew(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 ew(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)??nw(e),a=i.get(e)??nw(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 nw(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var rw={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function iw(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 ow({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 sw({state:e,onNavigateToChat:t}){let n=Nx(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}=yt(),re=(0,b.useRef)(0),ie=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ie.current;ie.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 ae=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),oe=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),se=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),A=(0,b.useCallback)(e=>{w(!1),S(e)},[]),ce=Lw(),le=(0,b.useCallback)(e=>{ce(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[ce]),[de,fe]=(0,b.useState)(!1),pe=Nw(),me=Hp(),[he,ge]=(0,b.useState)(null),[_e,ve]=(0,b.useState)(null),[ye,j]=(0,b.useState)(null),[be,xe]=(0,b.useState)(`all`),[Se,Ce]=(0,b.useState)(null),[we,Te]=(0,b.useState)(``),[M,N]=(0,b.useState)(null),[Ee,De]=(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{...US,...n}}localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return US}),Oe=(0,b.useCallback)(e=>{De(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ee.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),N(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,Ee.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!M)return;let e=M.expiresAt-performance.now();if(e<=0){N(null);return}let t=setTimeout(()=>N(null),e);return()=>clearTimeout(t)},[M]);let[ke,Ae]=(0,b.useState)(null),je=`paracosm:seenThresholdAlerts`,Me=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(je);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),Ne=(0,b.useCallback)(e=>{try{sessionStorage.setItem(je,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ee.alerts||!e.isRunning)return;let t=Me(),n=(e,n)=>{t.has(e)||(t.add(e),Ae({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),Ne(t)},[d,f,Ee.alerts,Me,Ne,e.isRunning]),(0,b.useEffect)(()=>{if(!ke)return;let e=ke.expiresAt-performance.now();if(e<=0){Ae(null);return}let t=setTimeout(()=>Ae(null),e);return()=>clearTimeout(t)},[ke]);let[Pe,Fe]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),Ie=(0,b.useCallback)(e=>{Fe(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Le=(0,b.useCallback)(()=>{Ie(Pe===`amber`?`cool`:Pe===`cool`?`mono`:`amber`)},[Pe,Ie]),[Re,ze]=(0,b.useState)(!1),[Be,Ve]=(0,b.useState)(!1),[He,Ue]=(0,b.useState)(!1),[We,Ge]=(0,b.useState)(null),[Ke,qe]=(0,b.useState)(null),Je=(0,b.useCallback)(e=>{qe(t=>t===e?null:e)},[]),Ye=d[y]??d[d.length-1],Xe=f[y]??f[f.length-1],Ze=Ye?.turn??0,Qe=Xe?.turn??0,$e=pe.presets.find(e=>e.id==="default"),et=$e?.leaders??$e?.actors,tt=et?.[0]?{name:et[0].name,archetype:et[0].archetype,unit:ue(pe,0),hexaco:et[0].hexaco,instructions:et[0].instructions,quote:``}:null,nt=et?.[1]?{name:et[1].name,archetype:et[1].archetype,unit:ue(pe,1),hexaco:et[1].hexaco,instructions:et[1].instructions,quote:``}:null,rt=p?.leader??tt,it=m?.leader??nt,at=(0,b.useRef)(null),[ot,st]=(0,b.useState)(!1),ct=(0,b.useRef)(null),lt=(0,b.useRef)([]),ut=(0,b.useRef)(null),dt=(0,b.useRef)(0),ft=(0,b.useCallback)(()=>{let e=at.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;ut.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}lt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&<.current.push(e.data)},s.onstop=()=>{dt.current&&cancelAnimationFrame(dt.current),dt.current=0;let e=new Blob(lt.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)},ct.current=s,st(!0),s.start();let c=()=>{let e=ut.current,t=at.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)}dt.current=requestAnimationFrame(c)};dt.current=requestAnimationFrame(c)},[]),pt=(0,b.useCallback)(()=>{let e=ct.current;if(e){try{e.stop()}catch{}ct.current=null,st(!1)}},[]);(0,b.useEffect)(()=>()=>{if(ct.current)try{ct.current.stop()}catch{}dt.current&&cancelAnimationFrame(dt.current)},[]);let mt=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:rt?.name??`Leader A`,archetype:rt?.archetype??``},leaderB:{name:it?.name??`Leader B`,archetype:it?.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,rt,it,d,f,p,m]),ht=(0,b.useCallback)(()=>{let e=at.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]),[gt,_t]=(0,b.useState)(0),vt=(0,b.useRef)(-1);(0,b.useEffect)(()=>{vt.current===-1||Math.abs(y-vt.current)>=2&&_t(e=>e+1),vt.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(),oe()):e.key===`ArrowRight`?(e.preventDefault(),se()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),ae()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),fe(e=>!e)):e.key===`Escape`&&de?(e.preventDefault(),fe(!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)},[oe,se,ae,de,k]);let bt=(0,b.useMemo)(()=>{let e=we.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[...(Ye?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:rt?.name??`Leader A`,sideColor:`#e8b44a`})),...(Xe?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:it?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[we,Ye,Xe,rt,it]),xt=(0,b.useMemo)(()=>iw(Ye,Xe),[Ye,Xe]),St=(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]);PC({enabled:Ee.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:St.a.attempts,forgeAttemptsB:St.b.attempts});let Ct=(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]),wt=(0,b.useCallback)(e=>{t?.(e)},[t]),Tt=rx(ix),Et=rx(ax),Dt=(0,b.useMemo)(()=>$C(d[y]?QC(d[y],d[y-1]):null,f[y]?QC(f[y],f[y-1]):null,y+1),[d,f,y]),Ot=(0,b.useMemo)(()=>pe.departments.map(e=>({id:e.id,label:e.label,color:rw[e.id]??`#a89878`})),[pe.departments]),kt=(0,b.useMemo)(()=>Object.fromEntries(pe.departments.map(e=>[e.id,e.label])),[pe.departments]),[At,jt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Mt=(0,b.useCallback)(e=>{jt(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(),Mt(!At))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[At,Mt]);let Nt=(0,b.useMemo)(()=>At?tw(aw(d[y]),aw(f[y])):null,[At,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 `,me.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 `,me.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 `,me.place,` visualization.`]});let Pt=Ye&&Xe?`A vs B: ${Xe.population-Ye.population>=0?`+`:``}${Xe.population-Ye.population} pop, ${Xe.morale-Ye.morale>=0?`+`:``}${Math.round((Xe.morale-Ye.morale)*100)}% morale${typeof Ye.foodReserve==`number`&&typeof Xe.foodReserve==`number`?`, ${Xe.foodReserve-Ye.foodReserve>0?`+`:``}${(Xe.foodReserve-Ye.foodReserve).toFixed(1)}mo food`:``}`:``,Ft=Et?Ke??`a`:Ke,It=y>0?d[y-1]??d[d.length-2]:void 0,Lt=y>0?f[y-1]??f[f.length-2]:void 0,Rt=bt;return(0,x.jsxs)(`div`,{ref:at,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)(cC,{state:e,currentTurn:y}),(0,x.jsx)(WC,{text:Dt,turn:y+1}),(0,x.jsx)(KC,{departments:Ot}),At&&Nt&&(0,x.jsx)(XC,{diff:Nt,departmentLabels:kt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(`div`,{className:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(mC,{mode:O,onChange:k,counts:{forge:St.a.attempts.filter(e=>e.approved).length+St.b.attempts.filter(e=>e.approved).length,divergence:(xt.aliveOnlyA?.size??0)+(xt.aliveOnlyB?.size??0)},labels:me})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ue(e=>!e),"aria-label":He?`Hide advanced tools`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":He,title:He?`Hide tools`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,He?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Mt(!At),"aria-label":At?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":At,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,At?`on`:`off`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>fe(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),He&&(0,x.jsxs)(`div`,{role:`toolbar`,"aria-label":`Viz tools`,className:$.toolsRow,children:[(0,x.jsx)(`button`,{type:`button`,onClick:Le,"aria-label":`Palette: ${Pe}. Click to cycle.`,title:`Palette: ${Pe.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Pe===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Pe===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Pe}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ve(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(VC,{recording:ot,onExportPng:ht,onExportJson:mt,onToggleRecording:ot?pt:ft}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ze(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":Re,title:`Viz settings`,className:[$.settingsBtn,Re?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:pC(O,me)})]}),(0,x.jsx)(jC,{value:we,onChange:Te,matches:Rt,onPick:e=>{Te(e.cell.name)}}),(0,x.jsx)(kC,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:pe.departments.length}),(0,x.jsx)(EC,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:A,hoveredTurn:ye,onHoverTurnChange:j,filter:be,onFilterChange:xe,onHoverEventChange:Ce,onJumpToReports:le,onForgeSelect:(e,t)=>Ge({toolName:e,side:t,sideColor:t===`a`?`var(--vis)`:`var(--eng)`})}),(0,x.jsx)(xC,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:A,hoveredTurn:ye,onHoverTurnChange:j}),g===`pair`&&Pt&&(0,x.jsx)(`div`,{className:$.diffLine,children:Pt}),g===`pair`&&Et&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?rt?.name??`Leader A`:it?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=Ft===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>qe(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsx)(rC,{state:e,snapshotMap:n,currentTurn:y,gridMode:O,palette:Pe===`cool`?1:Pe===`mono`?2:0,gridSettings:Ee,hexacoById:Ct,searchQuery:we,chronicleFilter:be,chronicleHover:Se,startTime:pe.setup?.defaultStartTime,onOpenChat:wt}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,Tt?$.leadersRowNarrow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,Ft===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)($S,{snapshot:Ye,isLiveRun:D,previousSnapshot:It,snapshotHistory:d,actorName:rt?.name??`Leader A`,actorArchetype:rt?.archetype??``,leaderUnit:rt?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ze<Qe?Qe-Ze:0,mode:O,hexacoById:Ct,leaderHexaco:rt?.hexaco?{O:rt.hexaco.O??rt.hexaco.openness??.5,C:rt.hexaco.C??rt.hexaco.conscientiousness??.5,E:rt.hexaco.E??rt.hexaco.extraversion??.5,A:rt.hexaco.A??rt.hexaco.agreeableness??.5,Em:rt.hexaco.Em??rt.hexaco.emotionality??.5,HH:rt.hexaco.HH??rt.hexaco.honestyHumility??.5}:void 0,forgeAttempts:St.a.attempts,reuseCalls:St.a.reuses,divergedIds:xt.aliveOnlyA,siblingHoveredId:_e,onHoverChange:ge,searchQuery:we,palette:Pe===`cool`?1:Pe===`mono`?2:0,settings:Ee,startTime:pe.setup?.defaultStartTime,focusedSide:Ft,onToggleFocus:Et?void 0:Je,onOpenChat:wt,eventFilter:be,chronicleHover:Se})}),(0,x.jsx)(`div`,{className:[$.sideWrap,Ft===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)($S,{snapshot:Xe,isLiveRun:D,previousSnapshot:Lt,snapshotHistory:f,actorName:it?.name??`Leader B`,actorArchetype:it?.archetype??``,leaderUnit:it?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:Qe<Ze?Ze-Qe:0,mode:O,hexacoById:Ct,leaderHexaco:it?.hexaco?{O:it.hexaco.O??it.hexaco.openness??.5,C:it.hexaco.C??it.hexaco.conscientiousness??.5,E:it.hexaco.E??it.hexaco.extraversion??.5,A:it.hexaco.A??it.hexaco.agreeableness??.5,Em:it.hexaco.Em??it.hexaco.emotionality??.5,HH:it.hexaco.HH??it.hexaco.honestyHumility??.5}:void 0,forgeAttempts:St.b.attempts,reuseCalls:St.b.reuses,divergedIds:xt.aliveOnlyB,siblingHoveredId:he,onHoverChange:ve,searchQuery:we,palette:Pe===`cool`?1:Pe===`mono`?2:0,settings:Ee,startTime:pe.setup?.defaultStartTime,focusedSide:Ft,onToggleFocus:Et?void 0:Je,onOpenChat:wt,eventFilter:be,chronicleHover:Se})})]}),(0,x.jsx)(uC,{currentTurn:y,maxTurn:v,time:Ye?.time??Xe?.time??0,playing:C,speed:T,onTurnChange:A,onPlayPause:ae,onStepBack:oe,onStepForward:se,onSpeedChange:ee}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(ow,{k:`?`,v:`help`}),(0,x.jsx)(ow,{k:`1-5`,v:`mode`}),(0,x.jsx)(ow,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(ow,{k:`space`,v:`play / pause`}),(0,x.jsx)(ow,{k:`click`,v:`${me.person} drilldown`}),(0,x.jsx)(ow,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ye&&Xe?`Turn ${Math.max(Ye.turn,Xe.turn)}. ${rt?.name??`A`} ${me.place}: ${Ye.cells.filter(e=>e.alive).length} alive, ${Ye.births} born, ${Ye.deaths} died, morale ${Math.round(Ye.morale*100)}%. ${it?.name??`B`} ${me.place}: ${Xe.cells.filter(e=>e.alive).length} alive, ${Xe.births} born, ${Xe.deaths} died, morale ${Math.round(Xe.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>A(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)(gC,{open:de,onClose:()=>fe(!1)}),(0,x.jsx)(WS,{open:Re,settings:Ee,onChange:Oe,onClose:()=>ze(!1)}),(0,x.jsx)(zC,{payload:We,forgeAttemptsA:St.a.attempts,forgeAttemptsB:St.b.attempts,reuseCallsA:St.a.reuses,reuseCallsB:St.b.reuses,onClose:()=>Ge(null),onJumpToTurn:e=>{A(e),Ge(null)}}),(0,x.jsx)(LC,{open:Be,onClose:()=>Ve(!1),snapsA:d,snapsB:f,actorNameA:rt?.name??`Leader A`,actorNameB:it?.name??`Leader B`,forgeApprovedA:St.a.attempts.filter(e=>e.approved).length,forgeApprovedB:St.b.attempts.filter(e=>e.approved).length,reuseCountA:St.a.reuses.length,reuseCountB:St.b.reuses.length,divergedCount:(xt.aliveOnlyA?.size??0)+(xt.aliveOnlyB?.size??0)}),ke&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>Ae(null),className:$.toast,style:{"--toast-top":M?`68px`:`8px`,"--side-color":ke.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":ke.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":ke.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:ke.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ke.side.toUpperCase(),` · T`,ke.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:ke.message})]},ke.key),M&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>N(null),className:$.toast,style:{"--side-color":M.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:[M.side.toUpperCase(),` · T`,M.turn,` · `,M.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:M.title||`${M.category} crisis unfolding`})]},M.key),gt>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},gt),(0,x.jsx)(`style`,{children:`
|
|
124
|
+
`).length,fe=new Blob([n]).size;return(0,x.jsxs)(`div`,{className:by.card,children:[(0,x.jsxs)(`div`,{className:by.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:by.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:by.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:by.btnRow,children:[(0,x.jsx)(`button`,{onClick:ae,className:[by.btn,by.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:ie,className:by.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:oe,className:by.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:A,className:by.btn,disabled:!n.trim()||!!i,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:k,type:`file`,accept:`.json,application/json`,onChange:se,className:by.fileInput})]})]}),(0,x.jsxs)(`div`,{className:by.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:ne,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:by.editor}),(0,x.jsxs)(`div`,{className:by.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:[de,` lines, `,(fe/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:by.seedDetails,children:[(0,x.jsx)(`summary`,{className:by.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:by.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,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:by.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:`https://example.com/article`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),inputMode:`numeric`,placeholder:`5`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),placeholder:`anthropic or openai (optional)`,className:by.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:_y,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:by.input})]}),(0,x.jsxs)(`label`,{className:by.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:by.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:by.progressWrap,children:w.map(e=>(0,x.jsxs)(`div`,{className:by.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:by.progressStatus,children:e.status})]},e.hook))}),D&&(0,x.jsx)(`div`,{className:by.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:by.actions,children:[(0,x.jsx)(`button`,{onClick:ce,disabled:!n.trim()||!!i||S,className:by.actionBtn,"aria-label":`Store scenario in memory`,children:S?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:ue,disabled:!n.trim()||!!i||v,className:[by.actionBtn,by.primary].join(` `),"aria-label":`Compile scenario`,children:v?`Compiling...`:`Compile Scenario`}),e.adminWrite&&(0,x.jsx)(`button`,{onClick:le,disabled:!n.trim()||!!i,className:[by.actionBtn,by.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:by.spacer}),e.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:by.memCount,children:[e.memoryScenarios.length,` in memory`]})]})]})}function Ty(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``}}function Ey(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=Dy(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!ky(e,o)||n&&!Oy(e,n))})}function Dy(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Oy(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 ky(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 Ay(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=Dy(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function jy(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 My(e,t){let n=Ty(),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 Ny={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 Py(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function Fy({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>Ay(e),[e]),i=Py(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:Ny.bar,children:[(0,x.jsxs)(`div`,{className:Ny.topRow,children:[(0,x.jsxs)(`div`,{className:Ny.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ny.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:Ny.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:Ny.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:Ny.chipClear,onClick:()=>a({toolHash:``}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:Ny.resetButton,disabled:!i,onClick:()=>n(Ty()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:Ny.facetsRow,children:[(0,x.jsx)(`span`,{className:Ny.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:Ny.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[Ny.checkbox,t?Ny.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:Ny.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ny.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:Ny.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:Ny.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:Ny.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:Ny.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:Ny.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:Ny.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:Ny.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var Iy={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`},Ly={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 Ry(){return typeof window>`u`?My(``,``):My(window.location.search,window.location.hash)}function zy({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(Ry);(0,b.useEffect)(()=>{let e=()=>i(Ry());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=jy(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=Ey(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 ${Iy.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:Iy.header,children:(0,x.jsxs)(`h2`,{className:Iy.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(Fy,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:Iy.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=Ly[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:Iy.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:Iy.eventSummary,children:[(0,x.jsx)(`span`,{className:Iy.index,children:t}),(0,x.jsx)(`span`,{className:Iy.type,children:e.type}),(0,x.jsx)(`span`,{className:Iy.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:Iy.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:Iy.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:Iy.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:Iy.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:Iy.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var By=[{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 Vy(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`},Hy=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],Uy={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},Wy={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)`}]},Gy={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`}},Ky={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.`}},qy=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function Jy(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:qy[e]??`The Strategist`,unit:ue(t,e),instructions:``,hexaco:{...Uy}}}function Yy(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function Xy(e,t,n,r,i){let a=Yy(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 Zy=2,Qy=8;function $y({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),am(e===`config`?null:e)},[]),a=Pw(),o=Iw(),s=Hp(),c=Rw(),l=typeof window<`u`?Vh(window.localStorage):null,[u]=(0,b.useState)(()=>typeof window<`u`?Bh(window.localStorage):null),[d,f]=(0,b.useState)(()=>{let e=Math.max(Zy,Math.min(Qy,Math.max(Yy(a)?.length??0,l?.length??0)));return Xy(Array.from({length:e},(e,t)=>{let n=l?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??ue(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??Uy}}:Jy(t,a)}),a,a,u,[])}),p=(0,b.useRef)([]),m=(0,b.useRef)(a);(0,b.useEffect)(()=>{let e=m.current;m.current=a,f(t=>Xy(t,e,a,u,p.current))},[a.id,a.presets.length]);let h=(0,b.useCallback)((e,t)=>{f(n=>n.map((n,r)=>{if(r!==e)return n;let i=Object.keys(t).filter(e=>t[e]!==n[e]);return p.current[e]={...p.current[e],...Object.fromEntries(i.map(e=>[e,t[e]]))},t}))},[]),g=(0,b.useCallback)(()=>{f(e=>e.length<Qy?[...e,Jy(e.length,a)]:e)},[a]),_=(0,b.useCallback)(e=>{p.current.splice(e,1),f(t=>t.length>Zy?t.filter((t,n)=>n!==e):t)},[]),[v,y]=(0,b.useState)(a.setup.defaultTurns),[S,C]=(0,b.useState)(a.setup.defaultSeed),[w,T]=(0,b.useState)(a.setup.defaultStartTime),[ee,D]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[O,k]=(0,b.useState)(a.setup.defaultPopulation),ne=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=ne.current;e.has(`turns`)||y(a.setup.defaultTurns),e.has(`seed`)||C(a.setup.defaultSeed),e.has(`startTime`)||T(a.setup.defaultStartTime),e.has(`timePerTurn`)||D(a.setup.defaultTimePerTurn||0),e.has(`population`)||k(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[re,ie]=(0,b.useState)(`openai`),[ae,oe]=(0,b.useState)(!1),[se,A]=(0,b.useState)(`balanced`),[ce,le]=(0,b.useState)(!1),[de,fe]=(0,b.useState)(``),[pe,me]=(0,b.useState)([]),[he,ge]=(0,b.useState)(a.id),[_e,ve]=(0,b.useState)({}),[j,be]=(0,b.useState)(!1),[xe,Se]=(0,b.useState)(`local_demo`),[Ce,we]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[Te,M]=(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(Te))}catch{}},[Te]);let[N,Ee]=(0,b.useState)(Gy[re]??Gy.openai);(0,b.useEffect)(()=>{let e=re;Gy[e]&&Ee(Gy[e])},[re]);let De=!!Te.openai||!!Te.anthropic,Oe=!!_e.openai||!!_e.anthropic,ke=De||!j&&Oe,Ae=De||!j&&Oe,je=j&&!De?`economy`:se,Me=Vy(xe),Ne=j&&!De,Pe=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{me(e.scenarios||[]),ge(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(Pe(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&ve(e.keys),typeof e.hostedDemo==`boolean`&&be(e.hostedDemo),typeof e.serverMode==`string`&&Se(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&we({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),E(window,Pe)),[Pe]);let Fe=async e=>{if(e!==he)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(te(),window.location.reload())}catch{}},Ie=(0,b.useCallback)(async()=>{if(o){le(!0),fe(`Starting...`);try{let e={actors:d.map(e=>({...e,hexaco:e.hexaco})),provider:re,turns:v,seed:S,startTime:w,timePerTurn:ee||void 0,population:O,liveSearch:ae,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:je},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}zh(window.localStorage,d,a.id),Te.openai&&(e.apiKey=Te.openai),Te.anthropic&&(e.anthropicKey=Te.anthropic),Te.serper&&(e.serperKey=Te.serper),Te.firecrawl&&(e.firecrawlKey=Te.firecrawl),Te.tavily&&(e.tavilyKey=Te.tavily),Te.cohere&&(e.cohereKey=Te.cohere),Ae&&(e.models={...N});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){fe(`Rate limited: ${n.error||`too many simulations`}`),le(!1);return}if(n.redirect){fe(`Running...`);let e=nm(om(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else fe(`Error: ${n.error||`unknown`}`),le(!1)}catch(e){fe(`Failed: ${e}`),le(!1)}}},[d,v,S,w,ee,O,re,ae,c,a,o,Te,N,Ae,je]),Le=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(Qp,{options:Hy,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(zy,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(pv,{}),pe.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:_y,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:he,onChange:e=>Fe(e.target.value),children:pe.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===he?`● `:``,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:he})]})]}),(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:Me.label}),`. `,Me.description]}),(0,x.jsx)(`div`,{className:`${d.length>2?`responsive-grid-cohort`:`responsive-grid-2`} ${Y.leadersGrid}`,children:d.map((e,t)=>(0,x.jsxs)(`div`,{className:Y.leaderCardWrap,style:{position:`relative`},children:[(0,x.jsx)(hy,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:ye(t),data:e,onChange:e=>h(t,e)}),d.length>Zy&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>_(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:d.length<Qy?(0,x.jsxs)(`button`,{type:`button`,onClick:g,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,d.length,`/`,Qy,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,Qy,` 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:vy,className:Y.legend,children:`Simulation`}),Ne&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,Ce.maxTurns,`, population to `,Ce.maxPopulation,`, active departments to `,Ce.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:_y,children:[`Turns`,Ne&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${Ce.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,Ce.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:Ne?Ce.maxTurns:v,onChange:e=>{ne.current.add(`turns`),y(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:Ne,className:Le(Ne),title:Ne?`Locked at ${Ce.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:_y,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:ee,onChange:e=>{ne.current.add(`timePerTurn`),D(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:_y,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:S,onChange:e=>{ne.current.add(`seed`),C(parseInt(e.target.value)||a.setup.defaultSeed)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`time-input`,style:_y,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:w,onChange:e=>{ne.current.add(`startTime`),T(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:_y,children:[`Population`,Ne&&(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:Ne?30:O,onChange:e=>{ne.current.add(`population`),k(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:Ne,className:Le(Ne),title:Ne?`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:_y,children:`Provider`}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Y.input}`,value:re,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:_y,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(ae),onChange:e=>oe(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:_y,children:[`Economics`,Ne&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Le(Ne)}`,value:je,onChange:e=>A(e.target.value),disabled:Ne,title:By.find(e=>e.value===je)?.description,children:By.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:By.find(e=>e.value===je)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:vy,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:_y,children:[t,_e[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:Te[e],onChange:t=>M(n=>({...n,[e]:t.target.value})),placeholder:_e[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),ke&&(re===`openai`||re===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:vy,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(Ky).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:_y,children:Ky[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:N[e],onChange:t=>Ee(n=>({...n,[e]:t.target.value})),children:Wy[re].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:Ky[e].help})]},e))})]}),!ke&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,j?`Runs against the host API keys are capped to ${Ce.maxTurns} turns, ${Ce.maxPopulation} colonists, ${Ce.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)(wy,{}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Ie,disabled:ce||!o,"aria-label":ce?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:ce?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),de&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:de})]})]})]})}function eb(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 tb(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:eb(e.hexaco),instructions:e.instructions})),...t]}var nb={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function rb(e,t,n,r){let i=Math.max(0,t-e)*nb[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function ib(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}function ab(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function ob(e){let t=e.trajectory?.timepoints?.length??0,n=ab(e),r=Math.max(t,...n);return r>0?r:6}function sb(e,t){return ab(e).includes(t)&&t<ob(e)}var cb={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 lb(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=Pw(),u=Hp(),d=ft(!0),f=tb(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=rb(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:cb.backdrop,onClick:c,children:(0,x.jsxs)(`div`,{ref:d,tabIndex:-1,className:cb.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:cb.header,children:[(0,x.jsxs)(`h3`,{id:`fork-modal-title`,children:[`Fork at `,u.Time,` `,n]}),(0,x.jsx)(`button`,{type:`button`,className:cb.closeButton,onClick:c,"aria-label":`Close fork modal`,children:`×`})]}),(0,x.jsxs)(`div`,{className:cb.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-leader-select`,children:`Override leader`}),f.length===0?(0,x.jsx)(`p`,{className:cb.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:cb.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:cb.hint,children:`Leave blank to resume from the parent's RNG state.`})]}),(0,x.jsxs)(`details`,{className:cb.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:cb.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:cb.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:cb.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:cb.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()?ib(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:cb.confirmButton,children:`Fork`})]})]})})}var ub=`/retry-stats`;function db(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(ub,{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 pb(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function mb(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function hb(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function gb(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function _b({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=ft(!0),c=db(!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:pb(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,mb(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 ${pb(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${pb(-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 (`,mb(t),` reused / `,mb(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,mb(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,mb(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:mb(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:pb(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=hb(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=hb(t.avgAttempts),r=gb(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:mb(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:mb(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:pb(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:pb(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,mb(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:pb(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,mb(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:pb(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,mb(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`},yb=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],bb={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},xb={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function Sb(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function Cb(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 wb({events:e,actorName:t,baselineHexaco:n}){let r=Sb(n),i=Cb(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`}),yb.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:bb[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:vb.legend,children:yb.map(e=>(0,x.jsxs)(`span`,{className:vb.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:vb.legendSwatch,style:{"--trait-color":bb[e]}}),(0,x.jsx)(`span`,{className:vb.legendLabel,children:xb[e]}),(0,x.jsx)(`span`,{className:vb.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var Tb={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},Eb={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},Db=[`crisis`,`departments`,`decision`,`outcome`],Ob=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function kb(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function Ab(e){return e!==`quotes`}function jb(e){let t=[];for(let n of e??[])kb(n)&&!t.includes(n)&&t.push(n);return t}function Mb(e){let t=jb(e.configuredSections),n=t.length>0?t:Db,r=n.filter(Ab);for(let t of Ob)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 Nb={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`},Pb=[{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 Fb(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function Ib({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:Nb.bar,children:[(0,x.jsx)(`div`,{className:Nb.barLeftWrap,children:(0,x.jsx)(`div`,{className:Nb.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:Nb.barRightWrap,children:(0,x.jsx)(`div`,{className:Nb.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function Lb(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=Bt(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:Vt(e),a:e.a,b:e.b,text:t=>Ht(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=>Fb(e??0,`int`)}]:Pb.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>Fb(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:Nb.section,children:[(0,x.jsxs)(`div`,{className:Nb.header,children:[(0,x.jsx)(`div`,{className:Nb.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:Nb.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:Nb.headline,children:r}),i&&(0,x.jsx)(`div`,{className:Nb.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:Nb.body,children:[(0,x.jsxs)(`div`,{className:Nb.bodyHeader,children:[(0,x.jsx)(`span`,{className:Nb.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:Nb.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Wt(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:Nb.statRow,children:[(0,x.jsxs)(`div`,{className:Nb.statRowHead,children:[(0,x.jsx)(`span`,{className:Nb.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:Nb.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:Nb.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(Ib,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:Nb.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:Nb.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:Nb.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var Rb={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function zb(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 Bb(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 Vb(e,t,n){let r=n??Rb[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>Bb(e,t))].sort((e,t)=>e-t),a=zb(i,.25),o=zb(i,.75),s=zb(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=Bb(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 Hb(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=Bb(e,n),i=Bb(t,n);return Rb[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=Bb(e,n),i=Bb(t,n);return Rb[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 Ub(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=zb([...e.map(e=>Bb(e,t))].sort((e,t)=>e-t),.5),r={},i=Rb[t]===`higher`?1:-1;for(let a of e){let e=(Bb(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function Wb(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var Gb={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`},Kb=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],qb=[`morale`,`population`,`deaths`,`tools`],Jb=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function Yb({state:e}){let t=(0,b.useMemo)(()=>Pv(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>Kb.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:Vb(t,e)})),[t]),r=(0,b.useMemo)(()=>Hb(t,qb),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>Jb.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:Ub(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:Gb.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:Gb.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:Gb.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:Gb.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:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:Gb.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:Gb.quartileBlock,children:[(0,x.jsxs)(`div`,{className:Gb.metricHead,children:[(0,x.jsx)(`span`,{className:Gb.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:Gb.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:Gb.quartileRow,children:[(0,x.jsx)(`span`,{className:Gb.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:Gb.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${Gb.actorPill} ${Gb.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:Gb.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:Gb.quartileRow,children:[(0,x.jsx)(`span`,{className:Gb.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:Gb.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${Gb.actorPill} ${Gb.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:Gb.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:Gb.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:Gb.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:Gb.paretoItem,children:[(0,x.jsx)(`span`,{className:Gb.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:Gb.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:Gb.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:Gb.section,children:[(0,x.jsx)(`h4`,{className:Gb.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:Gb.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:Gb.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:Gb.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:Gb.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:Gb.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:Gb.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:Gb.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:Gb.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:Gb.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?Gb.deltaPositive:n<0?Gb.deltaNegative:Gb.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${Gb.medianMetricCol} ${r}`,role:`cell`,children:[Wb(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function Xb(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 Zb(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var Qb=[{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 $b(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 ex(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 Qb.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?$b(a,e.id):[],b:o?$b(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 Qb.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?$b(t.events,e.id):[]}))}))}function nx(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:Zb(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 rx(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 ix=`(max-width: 768px)`,ax=`(max-width: 480px)`,ox=`(prefers-reduced-motion: reduce)`,sx={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`},cx={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},lx={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function ux(e,t=!1){return e?t?lx[e]??`·`:cx[e]??e.replace(/_/g,` `).toUpperCase():`·`}function dx({outcome:e,sideColor:t,compact:n}){let r=Xb(e);return(0,x.jsx)(`div`,{className:sx.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:ux(e,n)})}function fx(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=rx(ax);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:sx.section,children:[(0,x.jsx)(`div`,{className:sx.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:sx.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:[sx.cell,e.diverged?sx.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:sx.cellHead,children:[(0,x.jsxs)(`span`,{className:sx.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(dx,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(dx,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:sx.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var px={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 mx(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 hx(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 gx({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:px.card,children:[(0,x.jsxs)(`div`,{className:px.cardHeader,children:[(0,x.jsx)(`span`,{className:px.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:px.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:px.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=hx(n);return(0,x.jsxs)(`span`,{className:px.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:px.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:mx(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:px.card,children:[(0,x.jsxs)(`div`,{className:px.cardHeader,children:[(0,x.jsx)(`span`,{className:px.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:px.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:px.cardFooter,children:[(0,x.jsx)(`span`,{className:px.lastA,children:h==null?`·`:mx(h,e.unit)}),(0,x.jsx)(`span`,{className:px.lastB,children:g==null?`·`:mx(g,e.unit)})]})]})}function _x(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:px.section,style:c,children:[(0,x.jsxs)(`div`,{className:px.sectionHeader,children:[(0,x.jsx)(`span`,{className:px.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:px.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:px.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:px.legendCohortSlot,"aria-hidden":`true`,children:hx(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:px.legend,children:[(0,x.jsx)(`span`,{className:px.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:px.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${px.grid}`,children:s.map(e=>(0,x.jsx)(gx,{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 yx(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 bx(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 xx(){return{events:new Map,reactions:[],totalReactions:0}}function Sx(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 Cx(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=xx(),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=Sx(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=Sx(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=Sx(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=Sx(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 wx(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function Tx({state:e,verdict:t,reportSections:n}){let r=tg(),i=ag(),[a,o]=bx(`paracosm-reports-refs-open`,!1),[s,c]=bx(`paracosm-reports-tools-open`,!1),[l,u]=(0,b.useState)(!1),{state:d,dispatch:f}=fn(),p=Rw(),m=Hp(),[h,g]=(0,b.useState)(null),_=d.parent,v=Pw(),y=Iw(),S=_?.metadata?.scenario,C=typeof S?.id==`string`&&S.id!==v.id,w=(0,b.useCallback)(t=>!_||e.isRunning||!y||C?!1:sb(_,t),[_,e.isRunning,y,C]),T=(0,b.useCallback)(async e=>{g(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=ob(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: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}p(`studio`)}catch(e){f({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[f,p]),ee=e.actorIds[0]??null,E=e.actorIds[1]??null,[D,O]=(0,b.useState)(ee),[te,k]=(0,b.useState)(E);(0,b.useEffect)(()=>{D&&!e.actorIds.includes(D)&&O(ee),te&&!e.actorIds.includes(te)&&k(E)},[e.actorIds,D,te,ee,E]);let ne=D??ee,re=te??E,ie=e.actorIds.length>2,[ae,oe]=(0,b.useState)(!ie);(0,b.useEffect)(()=>{oe(!ie)},[ie]);let se=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,Cx(e.actors[n]?.events));return t},[e]),A=(0,b.useMemo)(()=>{let e=ne&&se.get(ne)||new Map,t=re&&se.get(re)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??xx(),b:t.get(n)??xx()}])},[se,ne,re]),ce=(0,b.useMemo)(()=>{if(!ie)return[];let t=new Set;for(let e of se.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,se.get(r)?.get(t)??xx());return[t,n]})},[ie,se,e.actorIds]),le=ne,ue=re,de=le?e.actors[le]:null,fe=ue?e.actors[ue]:null,pe=de?.leader?.name||`Leader A`,me=fe?.leader?.name||`Leader B`,he=(de?.events.some(e=>e.type===`personality_drift`)??!1)||(fe?.events.some(e=>e.type===`personality_drift`)??!1),ge=A.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),_e=A.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),ve=(0,b.useMemo)(()=>Mb({configuredSections:n,hasQuotes:ge,hasCausality:_e,hasVerdict:!!t,hasTrajectories:he,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:i.list.length>0,hasReferences:r.list.length>0}),[n,ge,_e,t,he,e.cost,i.list.length,r.list.length]),j=(0,b.useMemo)(()=>nx(A),[A]),be=(0,b.useMemo)(()=>ex(e,ne,re),[e,ne,re]),xe=(0,b.useMemo)(()=>ie?tx(e,ye):null,[ie,e]),Se=(0,b.useMemo)(()=>{let e=[];j.length>0&&e.push({id:`strip`,label:`Strip`}),be.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),he&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of A)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,j.length,be,he,A,i.list.length,r.list.length]),Ce=(0,b.useRef)(null),we=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{we.current&&Ce.current&&A.length>0&&Ce.current.scrollTo({top:Ce.current.scrollHeight,behavior:`smooth`})},[A.length]),!(de?.events.length??0)&&!(fe?.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:Ce,onScroll:()=>{let e=Ce.current;e&&(we.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[y&&C&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,S?.name??S?.id,`, and a fork runs in its parent's scenario. Switch to `,S?.name??S?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&A.length===0)return null;let i=A.length,a=A[A.length-1],o=A[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=de?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=fe?.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":wx(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=>oe(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:ne??``,onChange:e=>O(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===re,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:re??``,onChange:e=>k(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.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:j,leaderAName:pe,leaderBName:me})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!ie||ae?(0,x.jsx)(_x,{metrics:be,leaderAName:pe,leaderBName:me}):xe&&(0,x.jsx)(_x,{metrics:xe,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[he&&ae&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(wb,{events:de?.events??[],actorName:pe,baselineHexaco:de?.leader?.hexaco}),(0,x.jsx)(wb,{events:fe?.events??[],actorName:me,baselineHexaco:fe?.leader?.hexaco})]}),he&&!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)(wb,{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)(_b,{combined:e.cost,leaderA:(le?e.costByActor[le]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(ue?e.costByActor[ue]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:de?.leader?.name,leaderBName:fe?.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&&A.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`}),w(e)&&(0,x.jsxs)(`button`,{type:`button`,className:cb.forkButton,onClick:()=>g(e),"aria-label":`Fork at ${m.time} ${e}`,children:[`↳ Fork at `,m.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)(Dx,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:pe,sideColor:`var(--vis)`,sections:ve.eventSections}),(0,x.jsx)(Dx,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:me,sideColor:`var(--eng)`,sections:ve.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(Ox,{data:n,name:pe,sideColor:`var(--vis)`,showQuotes:ve.footerSections.includes(`quotes`)}),(0,x.jsx)(Ox,{data:r,name:me,sideColor:`var(--eng)`,showQuotes:ve.footerSections.includes(`quotes`)})]})]},e)}),ie&&ce.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`}),w(t)&&(0,x.jsxs)(`button`,{type:`button`,className:cb.forkButton,onClick:()=>g(t),"aria-label":`Fork at ${m.time} ${t}`,children:[`↳ Fork at `,m.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)(Dx,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:ve.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)(Ox,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:ve.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:i.list.length>0&&(0,x.jsx)(nv,{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)(Lb,{verdict:t,leaderAName:pe,leaderBName:me}),(0,x.jsx)(Yb,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(Zt,{verdict:t})})]}),(0,x.jsx)(`section`,{id:`references`,children:r.list.length>0&&(0,x.jsx)(ev,{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:ve.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:Tb[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:ve.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:Eb[e]},e))})]})]})]})]}),(0,x.jsx)(yx,{items:Se,scrollRoot:Ce.current}),h!==null&&_&&(0,x.jsx)(lb,{parentArtifact:_,atTurn:h,maxTurns:ob(_),costPreset:`economy`,provider:`openai`,onConfirm:T,onClose:()=>g(null)})]})}var Ex={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Dx({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)(h_,{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)(__,{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 Ox({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":Ex[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`},kx={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function Ax(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function jx({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":Ax(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 Mx({state:e,onChatUsage:t}){let n=Pw(),[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=r?a.get(r)??[]:[];r&&s.get(r);let _=(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]),v=e.actorIds.length>=2,[y,S]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!v)y!==null&&S(null);else if(y!==`all`&&!(y&&_.has(y))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(_.get(e)?.length??0)>0);S(t??`all`)}else S(`all`)}},[v,_,e.actorIds,y]);let[C,w]=(0,b.useState)(null),T=(0,b.useMemo)(()=>{if(y&&y!==`all`)return _.get(y)??[];let e=[],t=new Set;for(let n of _.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[_,y]),ee=(0,b.useMemo)(()=>{let e=new Set;for(let t of T){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[T]);(0,b.useEffect)(()=>{C&&!ee.includes(C)&&w(null)},[ee,C]);let E=(0,b.useMemo)(()=>C?T.filter(e=>(e.department||``).trim()===C):T,[T,C]),D=E.find(e=>e.name===r);(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[g,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let O=e=>{i(e),o(t=>{if(t.has(e))return t;let n=E.find(t=>t.name===e),r=n?{role:`agent`,name:n.name,text:`${n.role} in ${n.department}, age ${n.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.`},i=new Map(t);return i.set(e,[r]),i})},te=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},k=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},ne=async()=>{if(!l.trim()||!r||d)return;let e=r,n=l.trim();u(``),f(!0),te(e,e=>[...e,{role:`user`,text:n}]);let i=[...s.get(e)??[],{role:`user`,content:n}];k(e,()=>i);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),a=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,message:n,history:i,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(a.reply){te(e,t=>[...t,{role:`agent`,name:a.colonist||e,text:a.reply}]),k(e,e=>[...e,{role:`assistant`,content:a.reply}]);let n=a.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else te(e,e=>[...e,{role:`agent`,text:a.error||`No response`}])}catch(t){te(e,e=>[...e,{role:`agent`,text:`Chat failed: ${t}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),v&&_.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:y??``,onChange:e=>S(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 _.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=_.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)})]})]}),ee.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:C??``,onChange:e=>w(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,T.length,`)`]}),ee.map(e=>{let t=T.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>O(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":kx[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(jx,{memory:D.memory,events:e,scenario:n}),g.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&ne(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:ne,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 Nx(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 Px={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 Fx(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 Ix(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 Lx(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 Rx(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function zx(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 Bx(e,t,n){let r=zx(t,n,Rx(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=Fx(Ix(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,Lx(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function Vx(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=Fx(Ix(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,Lx(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=Fx(Ix(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,Lx(o,c,t,n))}),r}function Hx(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=Fx(Ix(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,Lx(s,c,t,n))}return i}function Ux(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=Fx(Ix(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,Lx(o,s,t,n))}return r}function Wx(e,t,n,r){return t===`families`?Vx(e,n,r):t===`mood`?Hx(e,n,r):t===`age`?Ux(e,n,r):Bx(e,n,r)}function Gx(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 Kx={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)`},qx=6;function Jx(e,t){e.save();for(let n of t){let t=Kx[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<qx;t++){let r=t/qx*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 Yx={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 Xx(e){return Yx[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function Zx(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=Xx(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=Xx(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 Qx(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 $x(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 eS(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 nS(){return{items:[]}}function rS(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function iS(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 aS(e){return e.items}function oS(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 sS=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function cS(e,t,n,r){let i=(0,b.useRef)(nS()),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=rx(ox);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}=oS(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&rS(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&&rS(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(!sS.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),rS(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&&rS(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&&rS(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,iS(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:aS(i.current),tickClock:o}}function lS(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 uS={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function dS(e){return uS[(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:dS(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 pS={"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.`},mS={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 hS({snapshot:e,sideColor:t}){let n=rx(ix),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:[mS.strip,n?mS.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[mS.col,mS.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:mS.rowBaseline,children:[(0,x.jsx)(`span`,{className:mS.label,title:pS[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:mS.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:mS.bar,children:(0,x.jsx)(`div`,{className:mS.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:mS.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:mS.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:mS.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:mS.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:mS.col,children:[(0,x.jsxs)(`div`,{className:mS.moodHeader,children:[(0,x.jsx)(`span`,{className:mS.label,title:pS[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:mS.value2,title:pS[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:mS.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:mS.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:mS.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:mS.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:mS.col,children:[(0,x.jsx)(`div`,{className:mS.label,title:pS[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:mS.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:mS.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:mS.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:mS.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:[mS.col,mS.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:mS.row,children:[(0,x.jsx)(`span`,{className:mS.label,title:pS[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:mS.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:mS.row,children:[(0,x.jsx)(`span`,{title:pS[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:mS.value2,children:d})]}),(0,x.jsxs)(`div`,{className:mS.row,children:[(0,x.jsx)(`span`,{title:pS[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:mS.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:mS.deptBlock,"aria-label":`Department breakdown`,title:pS[`stat.depts`],children:[(0,x.jsx)(fS,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:mS.deptLabel,children:`Depts`})]})]})}var gS={cols:12,rows:6,seedRadius:2},_S=[[1,0],[2,1],[0,2],[1,2],[2,2]],vS=[[0,1],[1,1],[2,1]],yS=[[0,0],[1,0],[0,1],[1,1]],bS=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],xS=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],SS=[[1,0],[2,0],[0,1],[1,1],[1,2]];function CS(e){switch(e){case`positive`:case`hopeful`:return yS;case`neutral`:return bS;case`anxious`:return vS;case`resigned`:return xS;case`defiant`:case`negative`:return _S;default:return vS}}function wS(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 TS(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 ES(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 DS(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 OS(e){switch(e){case`birth`:return yS;case`forge`:return _S;case`crisis`:return SS;case`death`:return[];default:return null}}function kS(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function AS(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=OS(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??CS(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 jS(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=yS;break;case`forge_approved`:l=_S;break;case`forge_rejected`:l=vS;break;case`reuse`:l=xS;break;case`crisis`:l=SS;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 MS(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 NS(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 PS(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 FS=[`O`,`C`,`E`,`A`,`Em`,`HH`];function IS(e,t){let n=t/2,r=t/2,i=t/2-8;return FS.map((t,a)=>{let o=Math.PI*2*a/FS.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 LS(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/FS.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function RS({profile:e,colonyMean:t,size:n=160}){let r=IS(e,n),i=t?IS(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)),FS.map((e,t)=>{let r=LS(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 zS={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`},BS={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function VS(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])=>`${BS[e]} ${t.toFixed(2)}`).join(` · `)}function HS(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=rx(ax);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:zS.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:zS.popover,style:C,children:[(0,x.jsxs)(`div`,{className:zS.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:zS.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:zS.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:zS.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:zS.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:zS.section,children:(0,x.jsxs)(`div`,{className:zS.statsGrid,children:[(0,x.jsx)(`span`,{className:zS.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:zS.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:zS.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:zS.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:zS.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:zS.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:zS.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:zS.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:zS.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:zS.statValue,children:y}),(0,x.jsx)(`span`,{className:zS.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:zS.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:zS.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:zS.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:zS.section,children:[(0,x.jsx)(`div`,{className:zS.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:zS.hexacoRow,children:[(0,x.jsx)(`div`,{className:zS.hexacoRadarWrap,children:(0,x.jsx)(RS,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:zS.hexacoTopAxes,children:VS(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:zS.section,children:[(0,x.jsx)(`div`,{className:zS.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:zS.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:zS.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:zS.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:zS.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var US={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`},WS={animSpeed:1,deptRings:!1,deptLabels:!1,lines:!1,dust:!0,crosshair:!0,ghostTrail:!1,alerts:!0,sound:!1};function GS({open:e,settings:t,onChange:n,onClose:r}){let i=ft(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:US.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:US.drawer,children:[(0,x.jsxs)(`div`,{className:US.header,children:[(0,x.jsx)(`span`,{style:vy,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:US.closeBtn,children:`×`})]}),(0,x.jsx)(KS,{label:`Animation speed`,children:[.5,1,2].map(e=>(0,x.jsx)(qS,{active:t.animSpeed===e,onClick:()=>a(`animSpeed`,e),label:`${e}x`},e))}),(0,x.jsxs)(KS,{label:`Dept rings`,children:[(0,x.jsx)(qS,{active:t.deptRings,onClick:()=>a(`deptRings`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.deptRings,onClick:()=>a(`deptRings`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Dept labels`,children:[(0,x.jsx)(qS,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Family lines`,children:[(0,x.jsx)(qS,{active:t.lines,onClick:()=>a(`lines`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.lines,onClick:()=>a(`lines`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Star dust bg`,children:[(0,x.jsx)(qS,{active:t.dust,onClick:()=>a(`dust`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.dust,onClick:()=>a(`dust`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Crosshair`,children:[(0,x.jsx)(qS,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Ghost trail`,children:[(0,x.jsx)(qS,{active:t.ghostTrail,onClick:()=>a(`ghostTrail`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.ghostTrail,onClick:()=>a(`ghostTrail`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Alert toasts`,children:[(0,x.jsx)(qS,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(KS,{label:`Sound cues`,children:[(0,x.jsx)(qS,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(qS,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(WS),style:yy,className:US.resetBtn,children:`Reset defaults`})]})]})}function KS({label:e,children:t}){return(0,x.jsxs)(`div`,{className:US.row,children:[(0,x.jsx)(`span`,{style:_y,className:US.rowLabel,children:e}),(0,x.jsx)(`div`,{className:US.pillRow,children:t})]})}function qS({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[US.pill,e?US.pillActive:``].filter(Boolean).join(` `),children:n})}var JS={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`},YS={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)`},XS=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function ZS({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=Hp(),{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:JS.drawer,children:[(0,x.jsxs)(`div`,{className:JS.header,style:v,children:[(0,x.jsxs)(`span`,{className:JS.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:JS.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:JS.sortRow,children:XS.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[JS.sortChip,t?JS.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:JS.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:JS.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:JS.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:JS.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:JS.swatch,style:{"--swatch-bg":YS[e.mood]??YS.neutral}}),(0,x.jsx)(`span`,{className:JS.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:JS.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:JS.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:[JS.row,JS.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:JS.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:JS.rowName,children:e.name})]},e.agentId)})]})]})]})}function QS({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 $S(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 eC(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=WS,focusedSide:T=null,onToggleFocus:ee,onOpenChat:E,eventFilter:D=`all`,chronicleHover:O=null,isLiveRun:te=!0}=e,k=T===c,ne=rx(ix),re=rx(ox),ie=Hp(),ae=(0,b.useRef)(null),oe=(0,b.useRef)(null),se=(0,b.useRef)(null),[A,ce]=(0,b.useState)({w:0,h:0}),[le,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(null),[pe,me]=(0,b.useState)(null),[he,ge]=(0,b.useState)(!1),[_e,ve]=(0,b.useState)(null),[ye,j]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(re){j(!0);return}let e=requestAnimationFrame(()=>j(!0));return()=>cancelAnimationFrame(e)},[re]);let be=(0,b.useRef)(kS(gS.cols,gS.rows)),xe=(0,b.useRef)(-1),Se=(0,b.useRef)(``),Ce=(0,b.useRef)(``),we=(0,b.useRef)(null),Te=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=oe.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));ce(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=se.current;if(!e||A.w===0||A.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(A.w*t),e.height=Math.round(A.h*t),e.style.width=`${A.w}px`,e.style.height=`${A.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[A.w,A.h]);let M=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),N=(0,b.useMemo)(()=>!t||A.w===0?new Map:Wx(t.cells,M,A.w,A.h),[t,M,A.w,A.h]),Ee=(0,b.useMemo)(()=>t?lS(t.cells,N):new Map,[t,N]),De=cS({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},oe,()=>N,()=>Ee),Oe=f===`forge`?.7:f===`ecology`?0:1,ke=(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=se.current;if(!e||!t)return;let r=e.getContext(`2d`);if(!r)return;let c=De.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=$S(s,ae.current),d=ae.current?getComputedStyle(ae.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,A.w,A.h);let E=be.current,O=f!==Se.current,k=t.turn!==xe.current,ne=D!==Ce.current;if(k||O||ne){xe.current=t.turn,Se.current=f,Ce.current=D,AS(E,t.cells,N,A.w,A.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)MS(E);we.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!==we.current&&(we.current=e,jS(E,c[0],A.w,A.h),re||MS(E))}let oe=typeof document<`u`&&document.documentElement.classList.contains(`light`);if(te&&NS(r,E,A.w,A.h,u,oe?.22:.65),D===`death`?TS(r,t.cells,N,A.w,A.h,gS.cols,gS.rows,C,T):D===`birth`&&wS(r,t.cells,N,A.w,A.h,gS.cols,gS.rows),Jx(r,c),f!==`ecology`&&Gx(r,t.cells,N,u,Oe,_,f===`divergence`,re?0:performance.now(),S,!0,g,te?m:`transparent`),f===`forge`&&h&&h.length>0&&Qx(r,t.cells,N,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&$x(r,t,A.w,A.h,ee),f===`divergence`&&eS(r,t.cells,N,_,re?0:performance.now(),u),Zx(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:A.w,height:A.h,lagTurns:l,cells:t.cells,positions:N,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:ie.Time}),le){let e=N.get(le.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(de&&!le&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,de.y),r.lineTo(A.w,de.y),r.moveTo(de.x,0),r.lineTo(de.x,A.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=N.get(n.agentId);if(!t)continue;let r=t.x-de.x,i=t.y-de.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(de.x,de.y),r.lineTo(de.x+e.dx,de.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]}`,de.x+6,de.y+6),r.restore())}if(v&&v!==le?.cell.agentId){let e=N.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())}},[De.tickClock,t,N,A.w,A.h,s,i,l,De.flares,f,Oe,le,_,v,re,S,de,w,a,o,h,D,te]);let Ae=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;fe({x:r,y:i});let a=PS(t.cells,N,r,i);if(a){ue(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ve(null),y?.(a.agentId);return}le&&(ue(null),y?.(null));let o=gS.cols,s=gS.rows,c=D===`death`||D===`birth`?(()=>{let e=Math.floor(r/Math.max(1,A.w)*o),n=Math.floor(i/Math.max(1,A.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=N.get(r.agentId);if(!t)continue;let i=DS(t,A.w,A.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=ES(be.current,r,i,A.w,A.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=N.get(r.agentId);if(!t)continue;let i=DS(t,A.w,A.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?ve({x:r,y:i,...c}):_e&&ve(null)},[t,N,le,y,D,A.w,A.h,_e]),je=(0,b.useCallback)(()=>{ue(null),ve(null),fe(null),y?.(null)},[y]),Me=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=PS(t.cells,N,r,i);a?(me({cell:a,x:r,y:i}),ue(null),ve(null),Te.current={id:a.agentId,intensity:1}):_e?.nearest&&(me({cell:_e.nearest,x:r,y:i}),ue(null),ve(null))},[t,N,_e]),Ne=(0,b.useRef)(null),Pe=(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=PS(t.cells,N,i,a);o?Ne.current===o.agentId?(me({cell:o,x:i,y:a}),ue(null),Ne.current=null,Te.current={id:o.agentId,intensity:1}):(ue({cell:o,x:i,y:a}),fe({x:i,y:a}),Ne.current=o.agentId,y?.(o.agentId)):(ue(null),fe(null),Ne.current=null,y?.(null))},[t,N,y]);(0,b.useEffect)(()=>{pe&&t&&(t.cells.find(e=>e.agentId===pe.cell.agentId)||me(null))},[pe,t]),(0,b.useEffect)(()=>{pe||(Ne.current=null)},[pe]);let Fe=$S(f===`mood`?ke:s,ae.current),Ie={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)`},Le={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)`},Re=O&&O.side===c?Ie[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`,ze=O&&O.side===c?`0 0 24px ${Le[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:ae,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${ie.place} viz`,className:[Px.region,ne?Px.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(hS,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:oe,className:Px.canvasWrap,style:{"--tint-color":te?Fe:`transparent`,"--wrap-border":Re,"--wrap-glow":ze},children:[(0,x.jsx)(`canvas`,{ref:se,role:`img`,"aria-label":t?`${i} ${ie.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 ${ie.person} glyph for drilldown.`:`${i} ${ie.place} — waiting for first turn.`,onMouseMove:Ae,onMouseLeave:je,onClick:Me,onTouchStart:Pe,className:Px.canvas,style:{"--canvas-cursor":le?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:Px.revealCover,style:{"--reveal-opacity":ye?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ge(e=>!e),"aria-label":he?`Close roster`:`Open roster`,title:he?`Close roster`:`Open roster`,className:Px.cornerBtn,style:{"--right-offset":ee?`36px`:`8px`,"--btn-color":he?`var(--amber)`:`var(--text-3)`,"--btn-border":he?`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:`${Px.cornerBtn} ${Px.focusBtn}`,style:{"--btn-color":k?`var(--amber)`:`var(--text-3)`,"--btn-border":k?`var(--amber)`:`var(--border)`},children:k?`⤡`:`⤢`}),(0,x.jsx)(QS,{snapshot:t,previousSnapshot:n,sideColor:$S(s,ae.current),onSelect:e=>{let t=N.get(e.agentId);t&&me({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(ZS,{open:he,cells:t?.cells??[],actorName:i,sideColor:$S(s,ae.current),searchQuery:S,hoveredId:le?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?N.get(e):null;if(n&&r){ue({cell:n,x:r.x,y:r.y}),y?.(e);return}}ue(null),y?.(null)},onSelect:e=>{let t=N.get(e.agentId);t&&me({cell:e,x:t.x,y:t.y})},onClose:()=>ge(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:Px.divergenceEmpty,children:(0,x.jsx)(`div`,{className:Px.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),_e&&!le&&!pe&&(()=>{let e=Math.min(Math.max(8,_e.x+12),Math.max(8,A.w-220-8)),t=Math.max(8,_e.y-84),n=_e.kind===`birth`?`+ BIRTH MARKER`:_e.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=_e.kind===`birth`?`rgba(154, 205, 96, 0.95)`:_e.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:Px.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:Px.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:Px.tileCoords,children:[`tile (`,_e.col,`, `,_e.row,`)`]}),_e.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:Px.tileNearestName,children:_e.nearest.name}),(0,x.jsxs)(`div`,{className:Px.tileNearestRole,children:[_e.nearest.role,` · `,_e.nearest.department.toUpperCase()]}),_e.kind===`death`?(0,x.jsxs)(`div`,{className:Px.tileNearestDeath,children:[`deceased · mood at death: `,_e.nearest.mood]}):_e.kind===`birth`?(0,x.jsxs)(`div`,{className:Px.tileNearestBirth,children:[`native-born · generation `,_e.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:Px.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,_e.nearest.mood]})]}):(0,x.jsx)(`div`,{className:Px.tileAmbient,children:`ambient CA cell`}),_e.kind===`life`&&(()=>{let e=be.current,t=e.cols,n=e.rows,r=e.grid[_e.row*t+_e.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=_e.row+r,s=_e.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:Px.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),le&&!pe&&(()=>{let e=Math.min(Math.max(8,le.x+12),Math.max(8,A.w-200-8)),t=Math.min(Math.max(8,le.y-80-8),Math.max(8,A.h-80-8));return(0,x.jsxs)(`div`,{className:Px.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:Px.hoverHeader,children:[le.cell.name,le.cell.featured&&(0,x.jsx)(`span`,{className:Px.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:Px.hoverRole,children:[le.cell.department.toUpperCase(),` · `,le.cell.role,typeof le.cell.age==`number`?` · age ${le.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:Px.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:Px.hoverMoodValue,children:le.cell.mood}),typeof le.cell.psychScore==`number`?` · psych ${Math.round(le.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===le.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:Px.psychBlock,children:[(0,x.jsx)(`div`,{className:Px.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:Px.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:Px.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(HS,{payload:pe,containerW:A.w,containerH:A.h,sideColor:$S(s,ae.current),hexacoById:p,snapshots:r,onClose:()=>me(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 nC(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 rC(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=ye(t),ee=S?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>y?nC(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)(eC,{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 iC({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)(rC,{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 aC(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 oC={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 sC(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 cC=6;function lC({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?sC(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,cC),u=a.length-l.length,d=!r,f=a.length>0;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:oC.banner,children:[(0,x.jsxs)(`div`,{className:oC.headline,children:[(0,x.jsxs)(`span`,{className:oC.turnLabel,children:[`T`,t+1,c?` \u00b7 ${c}`:``]}),(0,x.jsx)(`span`,{className:oC.title,children:o}),s&&(0,x.jsx)(`span`,{className:oC.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:oC.collapseBtn,children:r?`\u25be ${a.length} actors`:`▴ hide`})]}),d&&l.map((e,t)=>(0,x.jsxs)(`div`,{className:a.length<=2?t===0?oC.lineA:oC.lineB:oC.line,children:[(0,x.jsx)(`span`,{className:oC.lineLabel,children:a.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:oC.lineBody,children:[`: `,aC(e.summary)]})]},e.actorId)),d&&u>0&&(0,x.jsxs)(`div`,{className:oC.lineMore,children:[`+`,u,` more \\u00b7 see cohort grid below for the rest`]})]})}var uC=[.5,1,2,4];function dC({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:uC.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 pC(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 mC(e,t){return pC(fC.find(t=>t.key===e)?.hint??``,t)}function hC({mode:e,onChange:t,counts:n,labels:r}){return rx(`(max-width: 480px)`)?(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:pC(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=pC(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 gC={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 _C({open:e,onClose:t}){let n=rx(ax),r=Hp();if(!e)return null;let i=[gC.dialog,n?gC.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:gC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:gC.header,children:[(0,x.jsxs)(`h2`,{className:gC.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:gC.closeBtn,children:`×`})]}),(0,x.jsxs)(vC,{title:`Modes`,children:[(0,x.jsx)(yC,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + family lines + event flares`}),(0,x.jsx)(yC,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(yC,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(yC,{k:`ECOLOGY`,v:`Hides glyphs; metrics strip + crisis flares lead`}),(0,x.jsx)(yC,{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)(yC,{k:(0,x.jsx)(bC,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(yC,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(yC,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(yC,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(yC,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(vC,{title:`Event flares`,children:[(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(yC,{k:(0,x.jsx)(bC,{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)(yC,{k:`— side color, bowed`,v:`Partner link`}),(0,x.jsx)(yC,{k:`– teal, dashed`,v:`Parent → child link`})]}),(0,x.jsxs)(vC,{title:`Keyboard`,children:[(0,x.jsx)(yC,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(yC,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(yC,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(yC,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(yC,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(yC,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:gC.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:gC.kbd,children:`?`}),` anytime to reopen.`]})]})})}function vC({title:e,children:t}){return(0,x.jsxs)(`div`,{className:gC.section,children:[(0,x.jsx)(`div`,{className:gC.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:gC.rows,children:t})]})}function yC({k:e,v:t}){return(0,x.jsxs)(`div`,{className:gC.row,children:[(0,x.jsx)(`span`,{className:gC.rowKey,children:e}),(0,x.jsx)(`span`,{className:gC.rowVal,children:t})]})}function bC({color:e}){return(0,x.jsx)(`span`,{className:gC.swatchWrap,children:(0,x.jsx)(`span`,{className:gC.swatch,style:{"--swatch-color":e}})})}var xC={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 SC({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:xC.wrap,children:[(0,x.jsxs)(`div`,{className:xC.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:xC.legendRight,children:[(0,x.jsx)(`span`,{className:xC.legendA,children:`A`}),(0,x.jsx)(`span`,{className:xC.legendB,children:`B`}),(0,x.jsx)(`span`,{className:xC.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:xC.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:xC.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:xC.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:xC.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:xC.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:xC.tooltipRowA,children:[(0,x.jsx)(`span`,{className:xC.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:xC.tooltipRowB,children:[(0,x.jsx)(`span`,{className:xC.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 CC={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`},wC=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],TC={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)`},EC={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function DC({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:CC.bar,children:[(0,x.jsxs)(`span`,{className:CC.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:CC.filterRow,children:wC.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[CC.filterChip,t?CC.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:CC.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[CC.dot,c?CC.current:``,d?CC.hovered:``].filter(Boolean).join(` `),p={"--kind-color":TC[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:EC[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var OC={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 kC(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 AC({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>kC(e),[e]),i=(0,b.useMemo)(()=>kC(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:OC.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:OC.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:OC.track,children:(0,x.jsx)(`div`,{className:OC.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:OC.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:OC.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var jC={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 MC({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Hp();(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:jC.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:jC.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:jC.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:jC.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:jC.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:jC.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:jC.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:jC.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:jC.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:jC.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:jC.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:jC.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:jC.clearBtn,children:`clear`})]})]})}function NC(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 PC(e,t){switch(t){case`birth`:NC(e,880,.18,.05,`triangle`),setTimeout(()=>NC(e,1320,.12,.03,`triangle`),70);break;case`death`:NC(e,160,.35,.05,`sine`);break;case`forge`:NC(e,660,.12,.04,`sine`);break;case`crisis`:NC(e,220,.22,.05,`sawtooth`),setTimeout(()=>NC(e,180,.18,.045,`sawtooth`),120)}}function FC(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=oS(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&&PC(o,`birth`),l>0&&setTimeout(()=>PC(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),PC(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var IC={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 LC(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 RC(e){let{open:t,onClose:n}=e,r=Hp();(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)(()=>LC(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>LC(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:IC.cell,children:[(0,x.jsx)(`span`,{className:IC.cellLabel,children:e}),(0,x.jsx)(`span`,{className:IC.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:IC.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:IC.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:IC.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:IC.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:IC.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:IC.dialog,children:[(0,x.jsxs)(`div`,{className:IC.header,children:[(0,x.jsxs)(`h2`,{className:IC.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:IC.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:IC.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:IC.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:IC.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:IC.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:IC.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 zC={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 BC({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=ft(!!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:zC.backdrop,children:(0,x.jsxs)(`div`,{ref:c,tabIndex:-1,onClick:e=>e.stopPropagation(),className:zC.dialog,style:l,children:[(0,x.jsxs)(`div`,{className:zC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:zC.kicker,children:[`Forge Lineage · `,e.side.toUpperCase()]}),(0,x.jsx)(`div`,{className:zC.title,children:e.toolName})]}),(0,x.jsx)(`button`,{type:`button`,onClick:a,"aria-label":`Close lineage`,className:zC.closeBtn,children:`×`})]}),s.firstApproved&&(0,x.jsxs)(`div`,{className:zC.firstForged,children:[`First forged in`,` `,(0,x.jsx)(`span`,{className:zC.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:zC.section,children:[(0,x.jsxs)(`div`,{className:zC.sectionLabel,children:[`Attempts (`,s.mine.length,`)`]}),s.mine.length===0?(0,x.jsx)(`div`,{className:zC.empty,children:`no forge records`}):(0,x.jsx)(`ul`,{className:zC.list,children:s.mine.map((e,t)=>{let n={"--status-color":e.approved?`var(--green)`:`var(--rust)`};return(0,x.jsxs)(`li`,{className:zC.attemptItem,style:n,children:[(0,x.jsx)(`span`,{className:zC.statusLabel,children:e.approved?`✓ Forged`:`✗ Rejected`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[zC.jumpBtn,o?zC.clickable:``].filter(Boolean).join(` `),title:o?`Jump to T${e.turn}`:void 0,children:[`T`,e.turn]}),(0,x.jsx)(`span`,{className:zC.deptLabel,children:e.department}),typeof e.confidence==`number`&&(0,x.jsxs)(`span`,{className:zC.confLabel,children:[`conf `,e.confidence.toFixed(2)]})]},`${e.turn}-${e.eventIndex}-${t}`)})})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:zC.sectionLabel,children:[`Cross-dept reuses (`,s.mineReuses.length,`)`]}),s.mineReuses.length===0?(0,x.jsx)(`div`,{className:zC.empty,children:`never reused across departments`}):(0,x.jsx)(`ul`,{className:zC.list,children:s.mineReuses.map((e,t)=>(0,x.jsxs)(`li`,{className:zC.reuseItem,children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o?.(Math.max(0,e.turn-1)),className:[zC.jumpBtn,o?zC.clickable:``].filter(Boolean).join(` `),children:[`T`,e.turn]}),(0,x.jsxs)(`span`,{className:zC.deptLabel,children:[e.originDept,` → `,e.callingDept]})]},`${e.turn}-${e.callingDept}-${t}`))})]})]})})}var VC={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 HC({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:VC.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:[VC.trigger,i?VC.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:VC.recDot}),`EXPORT ▼`]}),i&&(0,x.jsxs)(`div`,{role:`menu`,className:VC.menu,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),t()},className:VC.item,children:[(0,x.jsx)(`span`,{className:VC.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:VC.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),r()},className:[VC.item,e?VC.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[VC.itemKey,e?VC.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:VC.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{a(!1),n()},className:VC.item,children:[(0,x.jsx)(`span`,{className:VC.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:VC.itemDesc,children:`Replay snapshot`})]})]})]})}var UC={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},WC=120;function GC({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>WC,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:UC.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:UC.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:UC.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var KC={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 qC({departments:e}){let[t,n]=(0,b.useState)(!1),r=ft(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:KC.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:KC.glyphRow,children:[(0,x.jsx)(JC,{type:`band`}),(0,x.jsx)(`span`,{className:KC.label,children:`Department band`}),(0,x.jsx)(JC,{type:`agent`}),(0,x.jsx)(`span`,{className:KC.label,children:`Agent`}),(0,x.jsx)(JC,{type:`featured`}),(0,x.jsx)(`span`,{className:KC.label,children:`Featured agent`}),(0,x.jsx)(JC,{type:`turn`}),(0,x.jsx)(`span`,{className:KC.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:KC.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:KC.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:KC.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:KC.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:KC.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:KC.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:KC.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function JC({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${KC.glyph} ${KC.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${KC.glyph} ${KC.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${KC.glyph} ${KC.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${KC.glyph} ${KC.turn}`,"aria-hidden":`true`,children:`T`})}}var YC={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`},XC=8;function ZC({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,XC);return n.length===0?(0,x.jsxs)(`div`,{className:YC.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:YC.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:YC.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:YC.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:YC.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:YC.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:`${YC.chip} ${i?YC.chipStrong:YC.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:YC.chipDept,children:r}),(0,x.jsxs)(`span`,{className:YC.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var QC=.2;function $C(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 ew(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)>=QC){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 nw(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)??rw(e),a=i.get(e)??rw(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 rw(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var iw={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function aw(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 ow(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 sw({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 cw({state:e,onNavigateToChat:t}){let n=Nx(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}=yt(),re=(0,b.useRef)(0),ie=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ie.current;ie.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 ae=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),oe=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),se=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),A=(0,b.useCallback)(e=>{w(!1),S(e)},[]),ce=Rw(),le=(0,b.useCallback)(e=>{ce(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[ce]),[de,fe]=(0,b.useState)(!1),pe=Pw(),me=Hp(),[he,ge]=(0,b.useState)(null),[_e,ve]=(0,b.useState)(null),[ye,j]=(0,b.useState)(null),[be,xe]=(0,b.useState)(`all`),[Se,Ce]=(0,b.useState)(null),[we,Te]=(0,b.useState)(``),[M,N]=(0,b.useState)(null),[Ee,De]=(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{...WS,...n}}localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return WS}),Oe=(0,b.useCallback)(e=>{De(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ee.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),N(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,Ee.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!M)return;let e=M.expiresAt-performance.now();if(e<=0){N(null);return}let t=setTimeout(()=>N(null),e);return()=>clearTimeout(t)},[M]);let[ke,Ae]=(0,b.useState)(null),je=`paracosm:seenThresholdAlerts`,Me=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(je);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),Ne=(0,b.useCallback)(e=>{try{sessionStorage.setItem(je,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!Ee.alerts||!e.isRunning)return;let t=Me(),n=(e,n)=>{t.has(e)||(t.add(e),Ae({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),Ne(t)},[d,f,Ee.alerts,Me,Ne,e.isRunning]),(0,b.useEffect)(()=>{if(!ke)return;let e=ke.expiresAt-performance.now();if(e<=0){Ae(null);return}let t=setTimeout(()=>Ae(null),e);return()=>clearTimeout(t)},[ke]);let[Pe,Fe]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),Ie=(0,b.useCallback)(e=>{Fe(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Le=(0,b.useCallback)(()=>{Ie(Pe===`amber`?`cool`:Pe===`cool`?`mono`:`amber`)},[Pe,Ie]),[Re,ze]=(0,b.useState)(!1),[Be,Ve]=(0,b.useState)(!1),[He,Ue]=(0,b.useState)(!1),[We,Ge]=(0,b.useState)(null),[Ke,qe]=(0,b.useState)(null),Je=(0,b.useCallback)(e=>{qe(t=>t===e?null:e)},[]),Ye=d[y]??d[d.length-1],Xe=f[y]??f[f.length-1],Ze=Ye?.turn??0,Qe=Xe?.turn??0,$e=pe.presets.find(e=>e.id==="default"),et=$e?.leaders??$e?.actors,tt=et?.[0]?{name:et[0].name,archetype:et[0].archetype,unit:ue(pe,0),hexaco:et[0].hexaco,instructions:et[0].instructions,quote:``}:null,nt=et?.[1]?{name:et[1].name,archetype:et[1].archetype,unit:ue(pe,1),hexaco:et[1].hexaco,instructions:et[1].instructions,quote:``}:null,rt=p?.leader??tt,it=m?.leader??nt,at=(0,b.useRef)(null),[ot,st]=(0,b.useState)(!1),ct=(0,b.useRef)(null),lt=(0,b.useRef)([]),ut=(0,b.useRef)(null),dt=(0,b.useRef)(0),ft=(0,b.useCallback)(()=>{let e=at.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;ut.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}lt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&<.current.push(e.data)},s.onstop=()=>{dt.current&&cancelAnimationFrame(dt.current),dt.current=0;let e=new Blob(lt.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)},ct.current=s,st(!0),s.start();let c=()=>{let e=ut.current,t=at.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)}dt.current=requestAnimationFrame(c)};dt.current=requestAnimationFrame(c)},[]),pt=(0,b.useCallback)(()=>{let e=ct.current;if(e){try{e.stop()}catch{}ct.current=null,st(!1)}},[]);(0,b.useEffect)(()=>()=>{if(ct.current)try{ct.current.stop()}catch{}dt.current&&cancelAnimationFrame(dt.current)},[]);let mt=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:rt?.name??`Leader A`,archetype:rt?.archetype??``},leaderB:{name:it?.name??`Leader B`,archetype:it?.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,rt,it,d,f,p,m]),ht=(0,b.useCallback)(()=>{let e=at.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]),[gt,_t]=(0,b.useState)(0),vt=(0,b.useRef)(-1);(0,b.useEffect)(()=>{vt.current===-1||Math.abs(y-vt.current)>=2&&_t(e=>e+1),vt.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(),oe()):e.key===`ArrowRight`?(e.preventDefault(),se()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),ae()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),fe(e=>!e)):e.key===`Escape`&&de?(e.preventDefault(),fe(!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)},[oe,se,ae,de,k]);let bt=(0,b.useMemo)(()=>{let e=we.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[...(Ye?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:rt?.name??`Leader A`,sideColor:`#e8b44a`})),...(Xe?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:it?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[we,Ye,Xe,rt,it]),xt=(0,b.useMemo)(()=>aw(Ye,Xe),[Ye,Xe]),St=(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]);FC({enabled:Ee.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:St.a.attempts,forgeAttemptsB:St.b.attempts});let Ct=(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]),wt=(0,b.useCallback)(e=>{t?.(e)},[t]),Tt=rx(ix),Et=rx(ax),Dt=(0,b.useMemo)(()=>ew(d[y]?$C(d[y],d[y-1]):null,f[y]?$C(f[y],f[y-1]):null,y+1),[d,f,y]),Ot=(0,b.useMemo)(()=>pe.departments.map(e=>({id:e.id,label:e.label,color:iw[e.id]??`#a89878`})),[pe.departments]),kt=(0,b.useMemo)(()=>Object.fromEntries(pe.departments.map(e=>[e.id,e.label])),[pe.departments]),[At,jt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Mt=(0,b.useCallback)(e=>{jt(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(),Mt(!At))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[At,Mt]);let Nt=(0,b.useMemo)(()=>At?nw(ow(d[y]),ow(f[y])):null,[At,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 `,me.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 `,me.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 `,me.place,` visualization.`]});let Pt=Ye&&Xe?`A vs B: ${Xe.population-Ye.population>=0?`+`:``}${Xe.population-Ye.population} pop, ${Xe.morale-Ye.morale>=0?`+`:``}${Math.round((Xe.morale-Ye.morale)*100)}% morale${typeof Ye.foodReserve==`number`&&typeof Xe.foodReserve==`number`?`, ${Xe.foodReserve-Ye.foodReserve>0?`+`:``}${(Xe.foodReserve-Ye.foodReserve).toFixed(1)}mo food`:``}`:``,Ft=Et?Ke??`a`:Ke,It=y>0?d[y-1]??d[d.length-2]:void 0,Lt=y>0?f[y-1]??f[f.length-2]:void 0,Rt=bt;return(0,x.jsxs)(`div`,{ref:at,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)(lC,{state:e,currentTurn:y}),(0,x.jsx)(GC,{text:Dt,turn:y+1}),(0,x.jsx)(qC,{departments:Ot}),At&&Nt&&(0,x.jsx)(ZC,{diff:Nt,departmentLabels:kt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(`div`,{className:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(hC,{mode:O,onChange:k,counts:{forge:St.a.attempts.filter(e=>e.approved).length+St.b.attempts.filter(e=>e.approved).length,divergence:(xt.aliveOnlyA?.size??0)+(xt.aliveOnlyB?.size??0)},labels:me})}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ue(e=>!e),"aria-label":He?`Hide advanced tools`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":He,title:He?`Hide tools`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,He?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Mt(!At),"aria-label":At?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":At,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,At?`on`:`off`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>fe(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),He&&(0,x.jsxs)(`div`,{role:`toolbar`,"aria-label":`Viz tools`,className:$.toolsRow,children:[(0,x.jsx)(`button`,{type:`button`,onClick:Le,"aria-label":`Palette: ${Pe}. Click to cycle.`,title:`Palette: ${Pe.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Pe===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Pe===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Pe}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ve(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(HC,{recording:ot,onExportPng:ht,onExportJson:mt,onToggleRecording:ot?pt:ft}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>ze(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":Re,title:`Viz settings`,className:[$.settingsBtn,Re?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:mC(O,me)})]}),(0,x.jsx)(MC,{value:we,onChange:Te,matches:Rt,onPick:e=>{Te(e.cell.name)}}),(0,x.jsx)(AC,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:pe.departments.length}),(0,x.jsx)(DC,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:A,hoveredTurn:ye,onHoverTurnChange:j,filter:be,onFilterChange:xe,onHoverEventChange:Ce,onJumpToReports:le,onForgeSelect:(e,t)=>Ge({toolName:e,side:t,sideColor:t===`a`?`var(--vis)`:`var(--eng)`})}),(0,x.jsx)(SC,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:A,hoveredTurn:ye,onHoverTurnChange:j}),g===`pair`&&Pt&&(0,x.jsx)(`div`,{className:$.diffLine,children:Pt}),g===`pair`&&Et&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?rt?.name??`Leader A`:it?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=Ft===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>qe(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsx)(iC,{state:e,snapshotMap:n,currentTurn:y,gridMode:O,palette:Pe===`cool`?1:Pe===`mono`?2:0,gridSettings:Ee,hexacoById:Ct,searchQuery:we,chronicleFilter:be,chronicleHover:Se,startTime:pe.setup?.defaultStartTime,onOpenChat:wt}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,Tt?$.leadersRowNarrow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,Ft===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(eC,{snapshot:Ye,isLiveRun:D,previousSnapshot:It,snapshotHistory:d,actorName:rt?.name??`Leader A`,actorArchetype:rt?.archetype??``,leaderUnit:rt?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ze<Qe?Qe-Ze:0,mode:O,hexacoById:Ct,leaderHexaco:rt?.hexaco?{O:rt.hexaco.O??rt.hexaco.openness??.5,C:rt.hexaco.C??rt.hexaco.conscientiousness??.5,E:rt.hexaco.E??rt.hexaco.extraversion??.5,A:rt.hexaco.A??rt.hexaco.agreeableness??.5,Em:rt.hexaco.Em??rt.hexaco.emotionality??.5,HH:rt.hexaco.HH??rt.hexaco.honestyHumility??.5}:void 0,forgeAttempts:St.a.attempts,reuseCalls:St.a.reuses,divergedIds:xt.aliveOnlyA,siblingHoveredId:_e,onHoverChange:ge,searchQuery:we,palette:Pe===`cool`?1:Pe===`mono`?2:0,settings:Ee,startTime:pe.setup?.defaultStartTime,focusedSide:Ft,onToggleFocus:Et?void 0:Je,onOpenChat:wt,eventFilter:be,chronicleHover:Se})}),(0,x.jsx)(`div`,{className:[$.sideWrap,Ft===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(eC,{snapshot:Xe,isLiveRun:D,previousSnapshot:Lt,snapshotHistory:f,actorName:it?.name??`Leader B`,actorArchetype:it?.archetype??``,leaderUnit:it?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:Qe<Ze?Ze-Qe:0,mode:O,hexacoById:Ct,leaderHexaco:it?.hexaco?{O:it.hexaco.O??it.hexaco.openness??.5,C:it.hexaco.C??it.hexaco.conscientiousness??.5,E:it.hexaco.E??it.hexaco.extraversion??.5,A:it.hexaco.A??it.hexaco.agreeableness??.5,Em:it.hexaco.Em??it.hexaco.emotionality??.5,HH:it.hexaco.HH??it.hexaco.honestyHumility??.5}:void 0,forgeAttempts:St.b.attempts,reuseCalls:St.b.reuses,divergedIds:xt.aliveOnlyB,siblingHoveredId:he,onHoverChange:ve,searchQuery:we,palette:Pe===`cool`?1:Pe===`mono`?2:0,settings:Ee,startTime:pe.setup?.defaultStartTime,focusedSide:Ft,onToggleFocus:Et?void 0:Je,onOpenChat:wt,eventFilter:be,chronicleHover:Se})})]}),(0,x.jsx)(dC,{currentTurn:y,maxTurn:v,time:Ye?.time??Xe?.time??0,playing:C,speed:T,onTurnChange:A,onPlayPause:ae,onStepBack:oe,onStepForward:se,onSpeedChange:ee}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(sw,{k:`?`,v:`help`}),(0,x.jsx)(sw,{k:`1-5`,v:`mode`}),(0,x.jsx)(sw,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(sw,{k:`space`,v:`play / pause`}),(0,x.jsx)(sw,{k:`click`,v:`${me.person} drilldown`}),(0,x.jsx)(sw,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ye&&Xe?`Turn ${Math.max(Ye.turn,Xe.turn)}. ${rt?.name??`A`} ${me.place}: ${Ye.cells.filter(e=>e.alive).length} alive, ${Ye.births} born, ${Ye.deaths} died, morale ${Math.round(Ye.morale*100)}%. ${it?.name??`B`} ${me.place}: ${Xe.cells.filter(e=>e.alive).length} alive, ${Xe.births} born, ${Xe.deaths} died, morale ${Math.round(Xe.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>A(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)(_C,{open:de,onClose:()=>fe(!1)}),(0,x.jsx)(GS,{open:Re,settings:Ee,onChange:Oe,onClose:()=>ze(!1)}),(0,x.jsx)(BC,{payload:We,forgeAttemptsA:St.a.attempts,forgeAttemptsB:St.b.attempts,reuseCallsA:St.a.reuses,reuseCallsB:St.b.reuses,onClose:()=>Ge(null),onJumpToTurn:e=>{A(e),Ge(null)}}),(0,x.jsx)(RC,{open:Be,onClose:()=>Ve(!1),snapsA:d,snapsB:f,actorNameA:rt?.name??`Leader A`,actorNameB:it?.name??`Leader B`,forgeApprovedA:St.a.attempts.filter(e=>e.approved).length,forgeApprovedB:St.b.attempts.filter(e=>e.approved).length,reuseCountA:St.a.reuses.length,reuseCountB:St.b.reuses.length,divergedCount:(xt.aliveOnlyA?.size??0)+(xt.aliveOnlyB?.size??0)}),ke&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>Ae(null),className:$.toast,style:{"--toast-top":M?`68px`:`8px`,"--side-color":ke.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":ke.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":ke.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:ke.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ke.side.toUpperCase(),` · T`,ke.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:ke.message})]},ke.key),M&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>N(null),className:$.toast,style:{"--side-color":M.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:[M.side.toUpperCase(),` · T`,M.turn,` · `,M.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:M.title||`${M.category} crisis unfolding`})]},M.key),gt>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},gt),(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 lw={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 uw(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`another run started on the server`;case`unknown`:return`reason not recorded by the server`;default:return e}}function dw({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: ${uw(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:lw.statusChip,style:{"--status-color":t},role:`status`,"aria-live":`polite`,"aria-label":`Simulation status: ${n}. ${i}`,title:i,children:[r,` `,n]})}function fw(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function pw(e,t){let n=[`Total: ${fw(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: ${fw(e)}${t.simCalls==null?``:` (${t.simCalls} calls)`}`),r>0&&n.push(`• Chat: ${fw(r)}${t.chatCalls==null?``:` (${t.chatCalls} calls)`}`)}return n.join(`
|
|
149
|
+
`)}function mw({cost:e,costBreakdown:t,simStatus:n}){let r=rx(ax),i=[`shrink-0`,lw.footer,r?lw.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:i,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:lw.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:lw.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:lw.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:lw.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:lw.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:lw.navLink,children:`blog`})]}),n&&(0,x.jsx)(dw,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:lw.cost,title:pw(e,t),children:[(0,x.jsxs)(`span`,{className:lw.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:lw.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:lw.costMuted,children:[e.llmCalls,` calls`]})]}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:lw.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:lw.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:lw.brandLink,children:`Frame.dev`})]})]})}var hw={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`},gw=[{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 _w(){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:hw.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:hw.dialog,children:[(0,x.jsxs)(`div`,{className:hw.header,children:[(0,x.jsx)(`h2`,{className:hw.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:hw.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=gw.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:hw.section,children:[(0,x.jsx)(`h3`,{className:hw.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:hw.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:hw.row,children:[(0,x.jsx)(`span`,{className:hw.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:hw.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:hw.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:hw.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:hw.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:hw.kbdInline,children:`Esc`}),` to close`]})]})}):null}var vw={BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},yw=vw.VITE_GA_MEASUREMENT_ID||``,bw=vw.VITE_CLARITY_PROJECT_ID||``;function xw(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 Sw(e,t){if(document.getElementById(e))return;let n=document.createElement(`script`);n.id=e,n.textContent=t,document.head.appendChild(n)}function Cw(){return(0,b.useEffect)(()=>{yw&&yw!==`G-XXXXXXXXXX`&&(Sw(`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', '${yw}', {
|
|
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
|
+
`),xw(`ga-js`,`https://www.googletagmanager.com/gtag/js?id=${yw}`)),bw&&(document.body.setAttribute(`data-clarity-mask`,`True`),Sw(`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", "${bw}");
|
|
165
|
+
`))},[]),null}var ww={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`},Tw=[{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.`}],Ew=360,Dw=`tour-highlight`,Ow=`
|
|
166
166
|
/* The highlighted element gets a bright luminous amber glow */
|
|
167
|
-
.${
|
|
167
|
+
.${Dw} {
|
|
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 Ow({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?ww:ww.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=Dw,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Ew}`)?.classList.remove(Ew)}},[]),(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(Ew),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(Ew),e.classList.add(Ew),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(Ew),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(Ew),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-Tw-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Tw-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=[Cw.card,C?Cw.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:Cw.cardHeader,children:[(0,x.jsxs)(`span`,{className:Cw.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:Cw.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:Cw.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[Cw.title,C?Cw.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[Cw.description,C?Cw.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:Cw.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[Cw.skipBtn,C?Cw.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:Cw.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[Cw.navBtn,C?Cw.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[Cw.primaryBtn,C?Cw.compact:``,!C&&o===a.length-1?Cw.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:Cw.progressBar,children:(0,x.jsx)(`div`,{className:Cw.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:Cw.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:Cw.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:Cw.kbHint,children:`Arrow keys / Esc`})]})})}function kw(e,t){let n=[`medical`,`engineering`,`agriculture`,`governance`,`science`,`logistics`],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 Aw=[{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:`Chief Scientist`,department:`science`,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:`Chief Scientist`,department:`science`,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:kw(`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:kw(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],jw={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`},Mw=(0,b.createContext)(null);function Nw(){let e=(0,b.useContext)(Mw);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var Pw=(0,b.createContext)(!0);function Fw(){return(0,b.useContext)(Pw)}var Iw=(0,b.createContext)(null);function Lw(){let e=(0,b.useContext)(Iw);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}function Rw(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 zw(){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 Bw(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`}}function Vw(){let{scenario:e,ready:t}=oe(),n=zw(),r=_e({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?Aw:r.events,f=Se(d,u?!0:r.isComplete),{toast:p}=yt();kt({events:d,replayDone:r.replayDone,tourActive:i});let m=$h(f),h=rg(f),g=De(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),_=Ve({scenarioShortName:e.labels.shortName}),v=rm(window.location.href),[y,S]=(0,b.useState)(v.tab),[C]=(0,b.useState)(v.tab===`studio`&&v.sub===`branches`?`branches`:`author`),[w]=(0,b.useState)(v.tab===`settings`&&v.sub===`log`?`log`:`config`),T=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(S(e),window.history.replaceState({},``,im(window.location.href,e)))},[]);(0,b.useEffect)(()=>{y===`about`&&(window.location.href=`/`)},[y]);let ee=(0,b.useCallback)(()=>{g.save(r.events,r.results,r.verdict),p(`success`,`Saved`,`${r.events.length} events${r.verdict?` + verdict`:``} saved to file.`)},[r.events,r.results,r.verdict,g,p]),[E]=(0,b.useState)(()=>typeof window>`u`||!Qe(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:rt(window.location.href,$p),autoload:nt(window.location.href)}),D=Xe({pickFile:g.pickFile,parseFile:g.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{r.loadEvents(e,t,n),p(`info`,`Loaded`,`${e.length} events loaded.`);let i=E.destinationTab;T(i&&i!==`about`?i:`sim`)},onError:e=>{p(`error`,`Load Failed`,e)}}),O=D.openPicker;at({openFromFile:e=>D.openFromFile(e),onInfo:(e,t)=>p(`info`,e,t),onError:(e,t)=>p(`error`,e,t)});let te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{te.current||E.autoload&&D.state.kind===`preview`&&(te.current=!0,D.confirm())},[E.autoload,D.state.kind,D]);let k=dt({onFile:e=>D.openFromFile(e),onError:()=>{p(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{p(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),ne=(0,b.useCallback)(async()=>{if(!confirm(`Clear local data? This wipes the in-browser simulation buffer + cached events for this dashboard.
|
|
190
|
+
`;function kw({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?Tw:Tw.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=Ow,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Dw}`)?.classList.remove(Dw)}},[]),(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(Dw),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(Dw),e.classList.add(Dw),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(Dw),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(Dw),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-Ew-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Ew-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=[ww.card,C?ww.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:ww.cardHeader,children:[(0,x.jsxs)(`span`,{className:ww.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:ww.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:ww.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[ww.title,C?ww.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[ww.description,C?ww.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:ww.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[ww.skipBtn,C?ww.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:ww.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[ww.navBtn,C?ww.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[ww.primaryBtn,C?ww.compact:``,!C&&o===a.length-1?ww.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:ww.progressBar,children:(0,x.jsx)(`div`,{className:ww.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:ww.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:ww.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:ww.kbHint,children:`Arrow keys / Esc`})]})})}function Aw(e,t){let n=[`medical`,`engineering`,`agriculture`,`governance`,`science`,`logistics`],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 jw=[{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:`Chief Scientist`,department:`science`,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:`Chief Scientist`,department:`science`,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:Aw(`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:Aw(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],Mw={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`},Nw=(0,b.createContext)(null);function Pw(){let e=(0,b.useContext)(Nw);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var Fw=(0,b.createContext)(!0);function Iw(){return(0,b.useContext)(Fw)}var Lw=(0,b.createContext)(null);function Rw(){let e=(0,b.useContext)(Lw);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}function zw(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 Bw(){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 Vw(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`}}function Hw(){let{scenario:e,ready:t}=oe(),n=Bw(),r=_e({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?jw:r.events,f=Se(d,u?!0:r.isComplete),{toast:p}=yt();kt({events:d,replayDone:r.replayDone,tourActive:i});let m=$h(f),h=rg(f),g=De(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),_=Ve({scenarioShortName:e.labels.shortName}),v=rm(window.location.href),[y,S]=(0,b.useState)(v.tab),[C]=(0,b.useState)(v.tab===`studio`&&v.sub===`branches`?`branches`:`author`),[w]=(0,b.useState)(v.tab===`settings`&&v.sub===`log`?`log`:`config`),T=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(S(e),window.history.replaceState({},``,im(window.location.href,e)))},[]);(0,b.useEffect)(()=>{y===`about`&&(window.location.href=`/`)},[y]);let ee=(0,b.useCallback)(()=>{g.save(r.events,r.results,r.verdict),p(`success`,`Saved`,`${r.events.length} events${r.verdict?` + verdict`:``} saved to file.`)},[r.events,r.results,r.verdict,g,p]),[E]=(0,b.useState)(()=>typeof window>`u`||!Qe(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:rt(window.location.href,$p),autoload:nt(window.location.href)}),D=Xe({pickFile:g.pickFile,parseFile:g.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{r.loadEvents(e,t,n),p(`info`,`Loaded`,`${e.length} events loaded.`);let i=E.destinationTab;T(i&&i!==`about`?i:`sim`)},onError:e=>{p(`error`,`Load Failed`,e)}}),O=D.openPicker;at({openFromFile:e=>D.openFromFile(e),onInfo:(e,t)=>p(`info`,e,t),onError:(e,t)=>p(`error`,e,t)});let te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{te.current||E.autoload&&D.state.kind===`preview`&&(te.current=!0,D.confirm())},[E.autoload,D.state.kind,D]);let k=dt({onFile:e=>D.openFromFile(e),onError:()=>{p(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{p(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),ne=(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;g.clearCache(),r.reset(),N(!1);let e=``;try{e=localStorage.getItem(`paracosm:adminToken`)??``}catch{}if(!e)p(`info`,`Local data cleared`,`In-browser caches wiped. Server-stored runs are unchanged.`),T(`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();p(`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{}p(`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)p(`info`,`Local data cleared`,`Server-side wipe disabled on this deployment.`);else if(t.status===503)p(`info`,`Local data cleared`,`Server-side wipe configured but no ADMIN_TOKEN set on the server.`);else{let e=await t.json().catch(()=>({}));p(`info`,`Local data cleared`,`Server-side wipe failed: ${e.error??`HTTP ${t.status}`}`)}}catch(e){p(`info`,`Local data cleared`,`Server-side wipe failed: ${e instanceof Error?e.message:String(e)}`)}T(`settings`)}},[g,r,p]),[re,ie]=(0,b.useState)(!1);(0,b.useEffect)(()=>{r.providerError||ie(!1)},[r.providerError]);let ae=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(r.errors.length<=ae.current)return;let e=r.errors.slice(ae.current);ae.current=r.errors.length;let t=r.providerError;for(let n of e){if(t&&
|
|
195
|
-
`)).then(()=>{p(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{p(`error`,`Copy Failed`,`Clipboard access denied.`)})},[f,e,p]),fe=n??ct(r.events),pe=(0,b.useCallback)(()=>{if(!fe)return;let e=st(window.location.origin,fe,`viz`);navigator.clipboard.writeText(e).then(()=>{p(`success`,`Share link copied`,`Anyone with the link opens this run on the viz tab.`)}).catch(()=>{p(`error`,`Copy Failed`,`Clipboard access denied.`)})},[fe,p]),[he,ge]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[ve,ye]=(0,b.useState)(null),[j,be]=(0,b.useState)(null),[xe,Ce]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),we=(0,b.useCallback)(e=>{Ce(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Te=(0,b.useRef)(r.events.length);(0,b.useEffect)(()=>{let e=Te.current,t=r.events.length;Te.current=t,e>0&&t===0&&Ce({totalTokens:0,costUSD:0,calls:0})},[r.events.length]),Ft({launching:he,setLaunching:ge,isRunning:f.isRunning,isComplete:r.isComplete,sseStatus:r.status,eventsCount:r.events.length});let[M,N]=(0,b.useState)(!1),Ee=(0,b.useCallback)(e=>{r.reset(),ye(null),be(e),N(!0),T(`sim`)},[r,T]),Oe=(0,b.useCallback)(e=>{be(null),ye(e),N(!0),T(`sim`)},[T]),ke=(0,b.useCallback)(()=>{be(null),ye(null)},[]);Mt({isComplete:r.isComplete,isAborted:r.isAborted,abortReason:r.abortReason,resultsCount:r.results.length,hasVerdict:!!r.verdict,replayDone:r.replayDone,tourActive:i,userTriggeredRun:M,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{}_.push({events:r.events,results:r.results,verdict:r.verdict})},[r.isComplete,r.isAborted,r.events,r.results,r.verdict,e.labels.shortName,_,i]),Pt({events:r.events,tourActive:i,userTriggeredRun:M});let Ae=(0,b.useCallback)(async()=>{if(!t)p(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(he||f.isRunning)p(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{ge(!0),N(!0),r.reset(),T(`sim`),p(`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?(ge(!1),p(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect||(ge(!1),p(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){ge(!1),p(`error`,`Launch Failed`,String(e))}},[e,t,p,T,he,f.isRunning,r]);return(0,x.jsx)(dn,{children:(0,x.jsx)(
|
|
194
|
+
Cannot be undone.`))return;g.clearCache(),r.reset(),N(!1);let e=``;try{e=localStorage.getItem(`paracosm:adminToken`)??``}catch{}if(!e)p(`info`,`Local data cleared`,`In-browser caches wiped. Server-stored runs are unchanged.`),T(`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();p(`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{}p(`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)p(`info`,`Local data cleared`,`Server-side wipe disabled on this deployment.`);else if(t.status===503)p(`info`,`Local data cleared`,`Server-side wipe configured but no ADMIN_TOKEN set on the server.`);else{let e=await t.json().catch(()=>({}));p(`info`,`Local data cleared`,`Server-side wipe failed: ${e.error??`HTTP ${t.status}`}`)}}catch(e){p(`info`,`Local data cleared`,`Server-side wipe failed: ${e instanceof Error?e.message:String(e)}`)}T(`settings`)}},[g,r,p]),[re,ie]=(0,b.useState)(!1);(0,b.useEffect)(()=>{r.providerError||ie(!1)},[r.providerError]);let ae=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(r.errors.length<=ae.current)return;let e=r.errors.slice(ae.current);ae.current=r.errors.length;let t=r.providerError;for(let n of e){if(t&&zw(n,t.kind))continue;let e=n.length>120?n.slice(0,120)+`...`:n;p(`error`,`Simulation Error`,e)}},[r.errors,r.providerError,p]);let se=(0,b.useRef)(null),A=(0,b.useCallback)(()=>{se.current=y,a(!0)},[y]);(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=nm(window.location.href);e===`quickstart`&&(se.current=e,a(!0))},600);return()=>clearTimeout(e)},[]);let ce=(0,b.useCallback)(e=>{window.location.hash=`chat=${encodeURIComponent(e)}`,T(`chat`)},[T]),le=(0,b.useCallback)(()=>{a(!1),se.current&&=(T(se.current),null);try{localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{}},[T]),ue=(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(()=>{p(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{p(`error`,`Copy Failed`,`Clipboard access denied.`)})},[f,e,p]),fe=n??ct(r.events),pe=(0,b.useCallback)(()=>{if(!fe)return;let e=st(window.location.origin,fe,`viz`);navigator.clipboard.writeText(e).then(()=>{p(`success`,`Share link copied`,`Anyone with the link opens this run on the viz tab.`)}).catch(()=>{p(`error`,`Copy Failed`,`Clipboard access denied.`)})},[fe,p]),[he,ge]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[ve,ye]=(0,b.useState)(null),[j,be]=(0,b.useState)(null),[xe,Ce]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),we=(0,b.useCallback)(e=>{Ce(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Te=(0,b.useRef)(r.events.length);(0,b.useEffect)(()=>{let e=Te.current,t=r.events.length;Te.current=t,e>0&&t===0&&Ce({totalTokens:0,costUSD:0,calls:0})},[r.events.length]),Ft({launching:he,setLaunching:ge,isRunning:f.isRunning,isComplete:r.isComplete,sseStatus:r.status,eventsCount:r.events.length});let[M,N]=(0,b.useState)(!1),Ee=(0,b.useCallback)(e=>{r.reset(),ye(null),be(e),N(!0),T(`sim`)},[r,T]),Oe=(0,b.useCallback)(e=>{be(null),ye(e),N(!0),T(`sim`)},[T]),ke=(0,b.useCallback)(()=>{be(null),ye(null)},[]);Mt({isComplete:r.isComplete,isAborted:r.isAborted,abortReason:r.abortReason,resultsCount:r.results.length,hasVerdict:!!r.verdict,replayDone:r.replayDone,tourActive:i,userTriggeredRun:M,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{}_.push({events:r.events,results:r.results,verdict:r.verdict})},[r.isComplete,r.isAborted,r.events,r.results,r.verdict,e.labels.shortName,_,i]),Pt({events:r.events,tourActive:i,userTriggeredRun:M});let Ae=(0,b.useCallback)(async()=>{if(!t)p(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(he||f.isRunning)p(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{ge(!0),N(!0),r.reset(),T(`sim`),p(`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?(ge(!1),p(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect||(ge(!1),p(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){ge(!1),p(`error`,`Launch Failed`,String(e))}},[e,t,p,T,he,f.isRunning,r]);return(0,x.jsx)(dn,{children:(0,x.jsx)(Lw.Provider,{value:T,children:(0,x.jsx)(Nw.Provider,{value:e,children:(0,x.jsx)(Fw.Provider,{value:t,children:(0,x.jsx)(eg.Provider,{value:m,children:(0,x.jsxs)(ig.Provider,{value:h,children:[(0,x.jsx)(pn,{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 ${Mw.shell}`,children:[r.providerError&&!re?(0,x.jsx)(Tg,{providerError:r.providerError,onDismiss:()=>ie(!0)}):null,n&&r.status===`replay_not_found`?(0,x.jsx)(sn,{replaySessionId:n}):null,n&&r.status!==`replay_not_found`?(0,x.jsx)(on,{replaySessionId:n}):null,(0,x.jsx)(yg,{scenario:e,sse:r,gameState:f,onSave:ee,onLoad:O,onClear:ne,onRun:Ae,onTour:A,onCopy:ue,onShareViz:fe?pe:void 0,launching:he,history:_.entries,onRestoreHistory:e=>_.restore(e,r.loadEvents),onClearHistory:()=>{_.clear(),g.clearCache(),r.reset(),N(!1)}}),(0,x.jsx)(Cg,{active:y,onTabChange:T,scenario:e}),M&&(0,x.jsx)(zt,{verdict:r.verdict,currentTurn:f.turn,maxTurns:f.maxTurns,dismissedKey:o,onOpenModal:()=>l(!0),onDismiss:s,onNavigateTab:T}),(0,x.jsxs)(`main`,{id:`main-content`,tabIndex:-1,className:`flex-1 overflow-hidden ${Mw.main}`,role:`main`,"aria-label":`${y} view`,children:[(0,x.jsx)(`h1`,{className:`sr-only`,children:Vw(y)}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-quickstart`,"aria-labelledby":`tab-quickstart`,hidden:y!==`quickstart`,tabIndex:-1,className:y===`quickstart`?Mw.tabPanel:Mw.tabPanelHidden,children:(0,x.jsx)(Zh,{sse:r,sessionId:n??void 0,onRunStarted:()=>N(!0),onInterventionStart:Ee,onInterventionResult:Oe})}),y===`sim`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-sim`,"aria-labelledby":`tab-sim`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)(sy,{state:f,sseStatus:r.status,onRun:Ae,onTour:A,verdict:r.verdict,launching:he,interventionArtifact:ve,interventionRunning:j,onInterventionDismiss:ke,forceLayout:i?`side-by-side`:void 0})}),y===`viz`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-viz`,"aria-labelledby":`tab-viz`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)(cw,{state:f,onNavigateToChat:ce})}),y===`settings`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-settings`,"aria-labelledby":`tab-settings`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)($y,{events:d,initialSubTab:w})}),y===`reports`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-reports`,"aria-labelledby":`tab-reports`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)(Tx,{state:f,verdict:r.verdict,reportSections:e.ui.reportSections})}),y===`library`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-library`,"aria-labelledby":`tab-library`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)(Ti,{})}),y===`studio`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-studio`,"aria-labelledby":`tab-studio`,tabIndex:-1,className:Mw.tabPanel,children:(0,x.jsx)(cm,{initialSubTab:C})}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-chat`,"aria-labelledby":`tab-chat`,tabIndex:-1,className:y===`chat`?Mw.chatSurfaceVisible:Mw.chatSurfaceHidden,children:(0,x.jsx)(Mx,{state:f,onChatUsage:we})})]}),(0,x.jsx)(mw,{cost:{totalTokens:(f.cost?.totalTokens??0)+xe.totalTokens,totalCostUSD:Math.round(((f.cost?.totalCostUSD??0)+xe.costUSD)*1e4)/1e4,llmCalls:(f.cost?.llmCalls??0)+xe.calls},costBreakdown:{simUSD:f.cost?.totalCostUSD??0,simCalls:f.cost?.llmCalls??0,chatUSD:xe.costUSD,chatCalls:xe.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)(tn,{verdict:r.verdict,onClose:()=>l(!1)}),D.metadata&&(0,x.jsx)(ht,{metadata:D.metadata,showOverwriteWarning:r.events.length>0&&!n,currentEventCount:r.events.length,onConfirm:D.confirm,onCancel:D.cancel}),(0,x.jsx)(_t,{active:k.isDragging}),i&&(0,x.jsx)(kw,{activeTab:y,chatEnabled:e.policies.characterChat,onTabChange:T,onClose:le,onRun:Ae}),(0,x.jsx)(_w,{})]})]})})})})})})}var Uw=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:Mw.errorBoundary,children:[(0,x.jsx)(`div`,{className:Mw.errorTitle,children:`SIMULATION ERROR`}),(0,x.jsx)(`div`,{className:Mw.errorMessage,children:this.state.error.message}),(0,x.jsx)(`button`,{onClick:()=>{this.setState({error:null}),window.location.reload()},className:Mw.errorReload,children:`Reload Dashboard`})]}):this.props.children}};function Ww(){return(0,x.jsx)(Uw,{children:(0,x.jsx)(w,{children:(0,x.jsxs)(wt,{children:[(0,x.jsx)(Cw,{}),(0,x.jsx)(Hw,{})]})})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(b.StrictMode,{children:(0,x.jsx)(Ww,{})}));
|