paracosm 0.9.1151 → 0.9.1152
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.
|
@@ -110,7 +110,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
110
110
|
|
|
111
111
|
`);if(i.trim().length===0){let e=Error(`PDF contains no extractable text. It may be a scanned image without OCR.`);throw e.code=`PDF_NO_TEXT`,e}return{text:i,pages:e.numPages,truncated:l}}finally{try{await o.destroy()}catch{}}}function jh(e){let t=Mh(e.seedText.length>0?e.seedText:`<paste your scenario above>`),n=[];return n.push(`// Recreate this Quickstart run from your code.`),n.push(`import { runMany } from 'paracosm';`),n.push(``),e.sourceUrl&&e.sourceUrl.length>0?(n.push(`const { runs } = await runMany(`),n.push(` new URL('${Nh(e.sourceUrl)}'),`),n.push(` { count: ${e.actorCount} },`),n.push(`);`)):(n.push(`const { runs } = await runMany(`),n.push(` \`${t}\`,`),n.push(` { count: ${e.actorCount} },`),n.push(`);`)),n.push(``),n.push(`runs.forEach(({ actor, artifact }) => console.log(actor.name, artifact.fingerprint));`),n.join(`
|
|
112
112
|
`)}function Mh(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Nh(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Ph(e){let t={seedText:e.seedText.length>0?e.seedText:`<paste your scenario above>`};e.domainHint&&e.domainHint.trim().length>0&&(t.domainHint=e.domainHint),e.actorCount!==2&&(t.actorCount=e.actorCount);let n=`'${JSON.stringify(t).replace(/'/g,`'\\''`)}'`,r=[];return r.push(`# This compiles a typed ScenarioPackage from your prompt.`),r.push(`# For the full flow (auto-generate HEXACO leaders + simulate),`),r.push(`# install paracosm and use the TypeScript tab.`),r.push(`curl -X POST https://paracosm.agentos.sh/api/quickstart/compile-from-seed \\`),r.push(` -H 'Content-Type: application/json' \\`),r.push(` -d ${n}`),r.join(`
|
|
113
|
-
`)}var Fh={wrap:`_wrap_5ldo7_1`,toggle:`_toggle_5ldo7_6`,panel:`_panel_5ldo7_34`,tabRow:`_tabRow_5ldo7_42`,tabPill:`_tabPill_5ldo7_51`,copyBtn:`_copyBtn_5ldo7_74`,code:`_code_5ldo7_97`};function Ih(e){let{disabled:t,initiallyExpanded:n=!1,initialTab:r=`ts`,...i}=e,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(r),[l,u]=(0,b.useState)(`idle`),d=(0,b.useMemo)(()=>jh(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Ph(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),p=s===`ts`?d:f,m=(0,b.useCallback)(async()=>{try{await navigator.clipboard.writeText(p),u(`ok`)}catch{u(`fail`)}window.setTimeout(()=>u(`idle`),1500)},[p]),h=`quickstart-view-as-code-panel`,g=`quickstart-view-as-code-tab-ts`,_=`quickstart-view-as-code-tab-curl`,v=s===`ts`?g:_;return(0,x.jsxs)(`div`,{className:Fh.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:Fh.toggle,"aria-expanded":a,"aria-controls":h,disabled:t,onClick:()=>o(e=>!e),children:a?`▾ Hide code`:`▸ View as code`}),a&&(0,x.jsxs)(`div`,{id:h,role:`tabpanel`,"aria-labelledby":v,className:Fh.panel,children:[(0,x.jsxs)(`div`,{className:Fh.tabRow,role:`tablist`,"aria-label":`Recipe language`,children:[(0,x.jsx)(`button`,{type:`button`,id:g,role:`tab`,"aria-pressed":s===`ts`,"aria-selected":s===`ts`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`ts`),children:`TypeScript`}),(0,x.jsx)(`button`,{type:`button`,id:_,role:`tab`,"aria-pressed":s===`curl`,"aria-selected":s===`curl`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:Fh.copyBtn,onClick:m,"aria-label":`Copy ${s===`ts`?`TypeScript`:`curl`} recipe`,children:l===`ok`?`Copied ✓`:l===`fail`?`Press ⌘C`:`Copy`})]}),(0,x.jsx)(`pre`,{className:Fh.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Lh={card:`_card_srwu8_2`,heading:`_heading_srwu8_15`,subline:`_subline_srwu8_25`,scenarioPickerRow:`_scenarioPickerRow_srwu8_34`,scenarioPickerLabel:`_scenarioPickerLabel_srwu8_45`,scenarioPickerSelect:`_scenarioPickerSelect_srwu8_54`,scenarioPickerHint:`_scenarioPickerHint_srwu8_66`,actorRow:`_actorRow_srwu8_73`,actorLabel:`_actorLabel_srwu8_82`,actorSlider:`_actorSlider_srwu8_91`,actorValue:`_actorValue_srwu8_96`,runButton:`_runButton_srwu8_102`,runButtonFull:`_runButtonFull_srwu8_134`,runButtonCompact:`_runButtonCompact_srwu8_138`,tagline:`_tagline_srwu8_144`,tradeoff:`_tradeoff_srwu8_154`};function Rh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function zh({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Qk(),i=!eA()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,E=()=>{s||i||(c(!0),e(a))},D=`${a} ${a===1?`actor`:`actors`}`,O=s?`Launching...`:`Run ${D} against ${y}`,k=s?`Launching...`:`${O} ->`,A=s?`Launching...`:`Run ${D}`,j=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Lh.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Lh.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Lh.tagline,children:S}),(0,x.jsx)(`div`,{className:Lh.subline,children:C}),l.length>=2&&(()=>{let e=l.some(e=>e.id===r.id)?l:[...l,{id:r.id,name:r.labels.name||r.id,source:`active`}];return(0,x.jsxs)(`div`,{className:Lh.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Lh.scenarioPickerLabel,htmlFor:j,children:`Scenario`}),(0,x.jsx)(`select`,{id:j,className:Lh.scenarioPickerSelect,value:r.id,onChange:e=>m(e.target.value),disabled:i||s||d,"aria-label":`Switch active scenario`,children:e.map(e=>{let t=e.source===`builtin`?`[builtin]`:e.source===`disk`?`[disk]`:e.source===`compiled`?`[compiled]`:e.source===`active`?`[active]`:``,n=[];if(t&&n.push(t),typeof e.runCount==`number`&&e.runCount>0&&n.push(`${e.runCount} run${e.runCount===1?``:`s`}`),e.compiledAt){let t=Rh(e.compiledAt);t&&n.push(t)}let r=n.length>0?` · ${n.join(` · `)}`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.name,r]},e.id)})}),d&&(0,x.jsx)(`span`,{className:Lh.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Lh.actorRow,children:[(0,x.jsx)(`label`,{className:Lh.actorLabel,htmlFor:T,children:`Actors`}),(0,x.jsx)(`input`,{id:T,type:`range`,min:1,max:300,value:a,onChange:e=>o(parseInt(e.target.value,10)),disabled:i||s,className:Lh.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Lh.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Lh.runButton,onClick:E,disabled:i||s,"aria-busy":s,"aria-label":O,children:[(0,x.jsx)(`span`,{className:Lh.runButtonFull,"aria-hidden":`true`,children:k}),(0,x.jsx)(`span`,{className:Lh.runButtonCompact,"aria-hidden":`true`,children:A})]}),(0,x.jsxs)(`div`,{className:Lh.tradeoff,children:[_&&!v&&`Same scenario, fresh seed: skips the compile step.`,_&&v&&`Same scenario; ${a} LLM-generated actors replace the preset leaders for this run (~30s for generation).`,!_&&`Same scenario; ~30s for actor generation since no preset is defined.`]})]})}var W={backdrop:`_backdrop_nucmo_1`,backdropFadeIn:`_backdropFadeIn_nucmo_1`,drawer:`_drawer_nucmo_17`,open:`_open_nucmo_34`,header:`_header_nucmo_38`,closeBtn:`_closeBtn_nucmo_50`,sourceBadge:`_sourceBadge_nucmo_63`,summary:`_summary_nucmo_86`,nameRow:`_nameRow_nucmo_94`,name:`_name_nucmo_94`,nameEditBtn:`_nameEditBtn_nucmo_110`,nameEditForm:`_nameEditForm_nucmo_129`,nameEditInput:`_nameEditInput_nucmo_135`,nameEditActions:`_nameEditActions_nucmo_150`,nameEditSave:`_nameEditSave_nucmo_155`,nameEditCancel:`_nameEditCancel_nucmo_173`,nameEditError:`_nameEditError_nucmo_195`,description:`_description_nucmo_202`,metaGrid:`_metaGrid_nucmo_209`,meta:`_meta_nucmo_209`,sectionHeading:`_sectionHeading_nucmo_235`,seedSection:`_seedSection_nucmo_245`,seedHint:`_seedHint_nucmo_250`,seedBody:`_seedBody_nucmo_257`,presetsSection:`_presetsSection_nucmo_273`,departmentsSection:`_departmentsSection_nucmo_274`,sectionHint:`_sectionHint_nucmo_279`,sectionCount:`_sectionCount_nucmo_287`,presetList:`_presetList_nucmo_294`,presetCard:`_presetCard_nucmo_303`,presetHeader:`_presetHeader_nucmo_313`,presetName:`_presetName_nucmo_320`,presetArchetype:`_presetArchetype_nucmo_327`,presetUnit:`_presetUnit_nucmo_340`,hexacoList:`_hexacoList_nucmo_347`,hexacoRow:`_hexacoRow_nucmo_356`,hexacoAxis:`_hexacoAxis_nucmo_364`,hexacoBar:`_hexacoBar_nucmo_372`,hexacoFill:`_hexacoFill_nucmo_380`,hexacoValue:`_hexacoValue_nucmo_386`,presetInstructions:`_presetInstructions_nucmo_393`,deptChips:`_deptChips_nucmo_401`,deptChip:`_deptChip_nucmo_401`,deptIcon:`_deptIcon_nucmo_423`,deptRole:`_deptRole_nucmo_427`,recentSection:`_recentSection_nucmo_431`,statusLine:`_statusLine_nucmo_438`,error:`_error_nucmo_445`,recentList:`_recentList_nucmo_449`,recentRow:`_recentRow_nucmo_458`,recentTitle:`_recentTitle_nucmo_468`,recentArchetype:`_recentArchetype_nucmo_475`,recentMeta:`_recentMeta_nucmo_480`,footer:`_footer_nucmo_486`,actorRow:`_actorRow_nucmo_497`,actorLabel:`_actorLabel_nucmo_505`,actorSlider:`_actorSlider_nucmo_514`,actorValue:`_actorValue_nucmo_519`,runButton:`_runButton_nucmo_527`,deleteButton:`_deleteButton_nucmo_549`,deleteError:`_deleteError_nucmo_572`},Bh=`Admin token refused and cleared. ${R}`,Vh=(e,t)=>`The server refused the admin token this ${e} was sent with. A newer token is saved in this browser; press ${t} to try again with it.`,Hh=`scenario-rename-error`;function Uh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Wh(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Gh(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return`—`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Kh(e){return e?Array.from(e.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`):[]}function qh(e){let{scenario:t,disabled:n=!1,initialActorCount:r=2,onRunScenario:i,onClose:a,onDeleted:o,onRenamed:s}=e,c=t!==null,[l,u]=(0,b.useState)(r),[d,f]=(0,b.useState)([]),[p,m]=(0,b.useState)(!1),[h,g]=(0,b.useState)(null),[_,v]=(0,b.useState)(null),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(null),[D,O]=(0,b.useState)(!1),[k,A]=(0,b.useState)(``),[j,ee]=(0,b.useState)(!1),[te,M]=(0,b.useState)(null),[N,ne]=(0,b.useState)(null);(0,b.useEffect)(()=>{ne(null),O(!1),M(null)},[t?.id]);let[P,re]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)return E(null),re(B()||null),Se(()=>re(B()||null))},[c]);let ie=!!P&&t?.source===`compiled`,F=!!P&&t?.source===`compiled`,I=(0,b.useRef)(null),ae=(0,b.useRef)(null);if((0,b.useEffect)(()=>{if(!t){f([]),g(null),v(null);return}let e=!1;return m(!0),g(null),S(!0),v(null),fetch(`/api/v1/runs?scenario=${encodeURIComponent(t.id)}&limit=5`).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||f(n.runs??[])}).catch(t=>{e||(g(t instanceof Error?t.message:String(t)),f([]))}).finally(()=>{e||m(!1)}),fetch(`/scenarios/${encodeURIComponent(t.id)}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}).then(t=>{e||v(t)}).catch(()=>{e||v(null)}).finally(()=>{e||S(!1)}),()=>{e=!0}},[t?.id]),(0,b.useEffect)(()=>{c?(ae.current=document.activeElement,requestAnimationFrame(()=>{(I.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ae.current?.focus()},[c]),(0,b.useEffect)(()=>{if(!c)return;function e(e){if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`Tab`){let t=Kh(I.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!I.current?.contains(i)?(e.preventDefault(),n.focus()):e.shiftKey&&i===n?(e.preventDefault(),r.focus()):!e.shiftKey&&i===r&&(e.preventDefault(),n.focus())}}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c,a]),!t)return null;let oe=`scenario-detail-actor-count`,se=()=>{t&&F&&(A(N??t.name),O(!0),M(null))},ce=()=>{O(!1),A(``),M(null)},le=async()=>{if(!t||!P||j)return;let e=k.trim();if(e.length===0){M(`Name cannot be empty.`);return}if(e===(N??t.name)){O(!1);return}let n=xe(P);if(n)M(n),re(B()||null);else{ee(!0),M(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:P},body:JSON.stringify({name:e})});if(n.status===401){be(P);let e=B()||null;re(e),M(e?Vh(`rename`,`Save`):Bh);return}if(!n.ok){let e=await n.json().catch(()=>({}));M(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ne(r),O(!1),A(``),s?.(t.id,r)}catch(e){M(e instanceof Error?e.message:String(e))}finally{ee(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:W.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:I,className:`${W.drawer} ${c?W.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:W.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:W.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:W.sourceBadge,"data-source":t.source??`other`,children:Jh(t.source)})]}),(0,x.jsxs)(`section`,{className:W.summary,children:[D?(0,x.jsxs)(`form`,{className:W.nameEditForm,onSubmit:e=>{e.preventDefault(),le()},children:[(0,x.jsx)(`input`,{type:`text`,value:k,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),ce())},disabled:j,maxLength:100,autoFocus:!0,className:W.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:W.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:W.nameEditSave,disabled:j||!P||k.trim().length===0,"aria-describedby":te?Hh:void 0,children:j?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:W.nameEditCancel,onClick:ce,disabled:j,children:`Cancel`})]}),te&&(0,x.jsx)(`p`,{id:Hh,className:W.nameEditError,role:`alert`,children:te})]}):(0,x.jsxs)(`div`,{className:W.nameRow,children:[(0,x.jsx)(`h2`,{className:W.name,children:N??t.name}),F&&(0,x.jsx)(`button`,{type:`button`,className:W.nameEditBtn,onClick:se,"aria-label":`Rename ${N??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:W.description,children:t.description}),(0,x.jsxs)(`dl`,{className:W.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Total runs`}),(0,x.jsx)(`dd`,{children:t.runCount.toLocaleString()})]}),typeof t.departments==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Uh(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:Jh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:W.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:W.seedHint,children:`Original brief that compile-from-seed turned into this scenario. Truncated to 1KB at persist time so very long sources read as their leading section.`}),(0,x.jsx)(`pre`,{className:W.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:W.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:W.sectionHint,children:`Default leader pair the scenario ships with. Picking Run with the slot count below fills these in first; extra slots beyond the preset get LLM-generated.`}),(0,x.jsx)(`ul`,{className:W.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:W.presetCard,children:[(0,x.jsxs)(`div`,{className:W.presetHeader,children:[(0,x.jsx)(`span`,{className:W.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:W.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:W.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:W.hexacoList,"aria-label":`HEXACO profile for ${e.name}`,children:Object.entries(e.hexaco).slice(0,6).map(([e,t])=>{let n=Math.round((Number(t)||0)*100);return(0,x.jsxs)(`li`,{className:W.hexacoRow,children:[(0,x.jsx)(`span`,{className:W.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:W.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:W.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:W.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:W.presetInstructions,title:e.instructions,children:e.instructions.length>220?`${e.instructions.slice(0,220)}…`:e.instructions})]},`${e.name}-${t}`))})]}),_&&_.departments.length>0&&(0,x.jsxs)(`section`,{className:W.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:W.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:W.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:W.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:W.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:W.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:W.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:W.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:W.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:W.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${W.statusLine} ${W.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:W.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:W.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:W.recentRow,children:[(0,x.jsxs)(`span`,{className:W.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:W.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:W.recentMeta,children:[Uh(e.createdAt),` · `,Wh(e.costUSD),` · `,Gh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:W.footer,children:[(0,x.jsxs)(`div`,{className:W.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:oe,className:W.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:oe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:W.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:W.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:W.runButton,onClick:()=>i(t.id,l),disabled:n||C,"aria-label":`Run ${l} actor${l===1?``:`s`} against ${t.name}`,children:[`Run `,l,` `,l===1?`actor`:`actors`,` →`]}),ie&&(0,x.jsx)(`button`,{type:`button`,className:W.deleteButton,onClick:async()=>{if(!t||!P||C||!(typeof window<`u`&&window.confirm(`Delete this scenario?\n\n"${t.name}"\n\nRemoves the scenario from disk + the live catalog. Past runs are kept (they live in run-history). Cannot be undone.`)))return;let e=xe(P);if(e)E(e),re(B()||null);else{w(!0),E(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{[fe]:P}});if(e.status===401){be(P);let e=B()||null;re(e),E(e?Vh(`delete`,`Delete`):Bh);return}if(!e.ok){let t=await e.json().catch(()=>({}));E(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){E(e instanceof Error?e.message:String(e))}finally{w(!1)}}},disabled:C||n,"aria-label":`Delete scenario ${t.name}`,children:C?`Deleting…`:`Delete (admin)`}),T&&(0,x.jsx)(`p`,{className:W.deleteError,role:`alert`,children:T})]})]})]})}function Jh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var Yh={section:`_section_1l91i_1`,header:`_header_1l91i_5`,heading:`_heading_1l91i_14`,count:`_count_1l91i_24`,statusLine:`_statusLine_1l91i_32`,error:`_error_1l91i_39`,actorRow:`_actorRow_1l91i_43`,actorLabel:`_actorLabel_1l91i_54`,actorSlider:`_actorSlider_1l91i_63`,actorValue:`_actorValue_1l91i_68`,filterRow:`_filterRow_1l91i_76`,searchLabel:`_searchLabel_1l91i_84`,searchInput:`_searchInput_1l91i_90`,chipGroup:`_chipGroup_1l91i_108`,chip:`_chip_1l91i_108`,chipActive:`_chipActive_1l91i_133`,chipCount:`_chipCount_1l91i_139`,sortLabel:`_sortLabel_1l91i_145`,sortSelect:`_sortSelect_1l91i_150`,emptyMatches:`_emptyMatches_1l91i_165`,clearFiltersBtn:`_clearFiltersBtn_1l91i_176`,grid:`_grid_1l91i_187`,card:`_card_1l91i_196`,cardBody:`_cardBody_1l91i_211`,cardActive:`_cardActive_1l91i_231`,cardHeader:`_cardHeader_1l91i_236`,sourceBadge:`_sourceBadge_1l91i_243`,badge_builtin:`_badge_builtin_1l91i_254`,badge_disk:`_badge_disk_1l91i_258`,badge_compiled:`_badge_compiled_1l91i_262`,badge_memory:`_badge_memory_1l91i_262`,badge_other:`_badge_other_1l91i_266`,activeBadge:`_activeBadge_1l91i_270`,cardName:`_cardName_1l91i_282`,cardSeed:`_cardSeed_1l91i_292`,cardStats:`_cardStats_1l91i_303`,stat:`_stat_1l91i_32`,statKey:`_statKey_1l91i_317`,statValue:`_statValue_1l91i_324`,runButton:`_runButton_1l91i_331`};function Xh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Zh(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Qh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function $h(e){let{disabled:t=!1,onRunScenario:n}=e,r=Qk(),i=!eA()||t,a=r.id,[o,s]=(0,b.useState)([]),[c,l]=(0,b.useState)(2),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=setTimeout(()=>_(m),120);return()=>clearTimeout(e)},[m]);let[v,y]=(0,b.useState)(`all`),[S,C]=(0,b.useState)(`curated`),[w,T]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1,t=null,n=async()=>{try{let t=await fetch(`/scenarios`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;s(n.scenarios??[]),p(null)}catch(t){if(e)return;p(t instanceof Error?t.message:String(t))}finally{e||d(!1)}};return n(),t=setInterval(n,3e4),()=>{e=!0,t&&clearInterval(t)}},[]),u&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:Yh.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${Yh.statusLine} ${Yh.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let E=`scenario-catalog-actor-count`,D=`scenario-catalog-search`,O=g.trim().length>0||v!==`all`,k=g.trim().toLowerCase(),A=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:k.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(k))].sort((e,t)=>{if(e.id===a)return-1;if(t.id===a)return 1;if(S===`most-runs`){let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n}else if(S===`newest`){let n=e.compiledAt?Date.parse(e.compiledAt):0,r=t.compiledAt?Date.parse(t.compiledAt):0;if(n!==r)return r-n}else if(S===`alphabetical`)return e.name.localeCompare(t.name);else{let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n;if(e.compiledAt&&t.compiledAt){let n=Date.parse(e.compiledAt),r=Date.parse(t.compiledAt);if(Number.isFinite(n)&&Number.isFinite(r)&&n!==r)return r-n}}return e.name.localeCompare(t.name)}),j=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:Yh.header,children:[(0,x.jsxs)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:Yh.count,children:[`· `,O?`${A.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:Yh.actorRow,children:[(0,x.jsx)(`label`,{className:Yh.actorLabel,htmlFor:E,children:`Actors`}),(0,x.jsx)(`input`,{id:E,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:Yh.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:Yh.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:Yh.filterRow,children:[(0,x.jsxs)(`label`,{className:Yh.searchLabel,htmlFor:D,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:D,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:Yh.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:Yh.chipGroup,role:`group`,"aria-label":`Filter by scenario source`,children:[{key:`all`,label:`All`},{key:`builtin`,label:`Built-in`},{key:`disk`,label:`Saved`},{key:`compiled`,label:`Custom`}].map(e=>{let t=e.key===`all`?o.length:j[e.key]??0,n=v===e.key;return e.key!==`all`&&t===0?null:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>y(e.key),className:`${Yh.chip} ${n?Yh.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:Yh.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:Yh.sortLabel,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Sort scenarios`}),(0,x.jsxs)(`select`,{value:S,onChange:e=>C(e.target.value),className:Yh.sortSelect,"aria-label":`Sort catalog`,children:[(0,x.jsx)(`option`,{value:`curated`,children:`Sort: Curated`}),(0,x.jsx)(`option`,{value:`most-runs`,children:`Sort: Most runs`}),(0,x.jsx)(`option`,{value:`newest`,children:`Sort: Newest first`}),(0,x.jsx)(`option`,{value:`alphabetical`,children:`Sort: A → Z`})]})]})]}),A.length===0?(0,x.jsxs)(`div`,{className:Yh.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:Yh.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:Yh.grid,role:`list`,children:A.map(e=>{let t=Zh(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${Yh.card} ${Yh[`tone_${t}`]??``} ${r?Yh.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:Yh.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:Yh.cardHeader,children:[(0,x.jsx)(`span`,{className:`${Yh.sourceBadge} ${Yh[`badge_${t}`]??``}`,children:Qh(e.source)}),r&&(0,x.jsx)(`span`,{className:Yh.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:Yh.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:Yh.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:Yh.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:Xh(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:Yh.runButton,onClick:t=>{t.stopPropagation(),n(e.id,c)},disabled:i,"aria-label":`Run ${c} actor${c===1?``:`s`} against ${e.name}`,children:[`Run `,c,` `,c===1?`actor`:`actors`,` →`]})]},e.id)})}),(0,x.jsx)(qh,{scenario:w,disabled:i,initialActorCount:c,onRunScenario:(e,t)=>{T(null),n(e,t)},onClose:()=>T(null),onDeleted:e=>{s(t=>t.filter(t=>t.id!==e))},onRenamed:(e,t)=>{s(n=>n.map(n=>n.id===e?{...n,name:t}:n)),T(n=>n&&n.id===e?{...n,name:t}:n)}})]})}var eg=[{id:`hurricane-evacuation`,label:`What if a coastal mayor has 36 hours to evacuate before a hurricane?`,seedText:`A coastal metro of 800,000 has 36 hours before a Category 4 hurricane landfall. The mayor must decide a phased evacuation across three districts served by a single causeway bridge, with a regional hospital, a fuel depot, and an aging levee system in play. Departments involved: emergency management, public health, transportation, utilities, communications.`},{id:`saas-mid-tier`,label:`What if a developer-tools SaaS adds a $14 mid-tier?`,seedText:`StackPulse, a developer-focused observability SaaS (logs + metrics + tracing aimed at series-B-to-D startup engineering teams of 5-50 people), introduces a new $14/month "Builder" tier between the free Sandbox plan and the existing $29 Pro plan. The 180,000-user paid base is mostly engineering managers and SREs at venture-backed startups; their #1 jobs-to-be-done are debugging production incidents under 15 minutes and proving reliability SLAs to enterprise customers. Builder caps log retention at 7 days (Pro keeps 30) and limits trace sampling to 10% (Pro is full). Existing Pro subs get 90-day grandfathering. Competitors: Datadog (incumbent, 10x the price), Honeycomb (premium tier), self-hosted Grafana stacks. Test the impact on Free-to-Paid conversion, Pro downgrade rate, net ARPU, and churn over six months. Departments: pricing, growth, success, finance, engineering.`},{id:`ai-lab-early-release`,label:`What if an AI lab releases a frontier model six weeks early?`,seedText:`An AI lab decides whether to release a frontier multimodal model six weeks early. Two evaluators flag a 4.2% specification-gaming rate on long-horizon agentic tasks and early mesa-objective signals under DPO. A rival lab's weaker model ships on schedule, capturing $240M ARR in enterprise deals. Council: alignment, capability, policy, infra, comms.`},{id:`generation-ship-fuel-leak`,label:`What if a generation ship discovers a fuel leak at year 18?`,seedText:`A generation ship with 2,400 passengers at year 18 of a 40-year interstellar transit discovers a slow fuel leak on the main reactor. Reactor crew wants to EVA-repair (non-zero fatality risk); bridge wants to coast at reduced thrust and accept a 14-year transit extension. Departments: engineering, life support, medical, psych, command.`},{id:`city-congestion-pricing`,label:`What if a city pilots congestion pricing for 12 months?`,seedText:`A mid-size city of 650,000 pilots downtown congestion pricing for 12 months. $9 peak / $3 off-peak on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two BRT lines and a 30% transit fare cut for low-income riders. Test VMT, transit ridership, small-business revenue, equity outcomes.`}];function tg(e){return .1+.6*e}var ng={pendingSeedNotice:`_pendingSeedNotice_1rh83_1`,dividerWrap:`_dividerWrap_1rh83_15`,dividerLine:`_dividerLine_1rh83_27`,seedInput:`_seedInput_1rh83_33`,templatePicker:`_templatePicker_1rh83_48`,templatePickerLabel:`_templatePickerLabel_1rh83_55`,templatePickerSelect:`_templatePickerSelect_1rh83_65`,tabs:`_tabs_1rh83_90`,tab:`_tab_1rh83_90`,tabActive:`_tabActive_1rh83_119`,textarea:`_textarea_1rh83_124`,input:`_input_1rh83_125`,urlRow:`_urlRow_1rh83_142`,fetchButton:`_fetchButton_1rh83_150`,runButton:`_runButton_1rh83_151`,dropZone:`_dropZone_1rh83_185`,hint:`_hint_1rh83_205`,charCount:`_charCount_1rh83_218`,error:`_error_1rh83_225`,actorCountRow:`_actorCountRow_1rh83_235`,actorCountLabel:`_actorCountLabel_1rh83_246`,actorCountSlider:`_actorCountSlider_1rh83_257`,actorCountPreview:`_actorCountPreview_1rh83_313`};function rg(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function ig({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(rg),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(void 0),[f,p]=(0,b.useState)(``),[m,h]=(0,b.useState)(null),[g,_]=(0,b.useState)(!1),[v,y]=(0,b.useState)(2),S=(0,b.useRef)(null),C=(0,b.useCallback)(()=>{let t=o.trim(),n=gh(t);n.ok?(h(null),e({seedText:t,sourceUrl:u,domainHint:f.trim()||void 0,actorCount:v})):h(n.reason===`too-short`?`Paste at least 200 characters of source material.`:n.reason===`too-long`?`Source material exceeds 50 000 characters.`:`Source material is empty.`)},[o,u,f,v,e]),w=(0,b.useCallback)(async()=>{let e=hh(c);if(!e.ok)h(e.error);else{_(!0),h(null);try{let t=await fetch(`/api/quickstart/fetch-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e.url.toString()})});if(!t.ok){let e=await t.json().catch(()=>({}));h(e.error??`Fetch failed: HTTP ${t.status}`);return}let n=await t.json();s(n.text),d(n.sourceUrl??e.url.toString()),a(`paste`)}catch(e){let t=e?.message??String(e),n=/Failed to fetch|NetworkError|ERR_/i.test(t)?`Couldn't reach the server. Check your connection and try again.`:`URL fetch failed: ${t}`;h(n)}finally{_(!1)}}},[c]),T=(0,b.useCallback)(async e=>{if(e.size>10485760)h(`PDF exceeds 10 MB limit.`);else if(e.type!==`application/pdf`&&!e.name.toLowerCase().endsWith(`.pdf`))h(`File is not a PDF: ${e.name}`);else{_(!0),h(null);try{let{text:t,truncated:n}=await Ah(e);s(n?`${t}\n\n[Truncated to first 50 KB.]`:t),d(void 0),a(`paste`)}catch(e){let t=e?.code,n=String(e?.message??e),r;r=t===`PDF_NO_TEXT`?`No text found in this PDF. It looks like a scanned image — try a text-based PDF, or paste the content into WRITE.`:/InvalidPDFException|invalid pdf|corrupt/i.test(n)?`This PDF appears to be corrupted or password-protected. Try a different file or paste the text directly.`:/worker|GlobalWorkerOptions/i.test(n)?`Couldn't load the PDF parser (${n}). Try a different file, or paste the text into WRITE.`:`Couldn't read this PDF (${n}). Try paste-text or a different file.`,h(r)}finally{_(!1)}}},[]),E={paste:`WRITE`,url:`URL`,pdf:`PDF`},D=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:ng.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[D&&(0,x.jsx)(`p`,{className:ng.pendingSeedNotice,role:`status`,"aria-live":`polite`,children:`You have draft seed text below. Submit it to compile a new scenario, or clear it to run the loaded one.`}),(0,x.jsx)(zh,{onRunStart:t,disabled:r||g||D}),n&&(0,x.jsx)($h,{onRunScenario:n,disabled:r||g||D}),(0,x.jsxs)(`div`,{className:ng.dividerWrap,children:[(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:ng.templatePicker,children:[(0,x.jsx)(`span`,{className:ng.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:ng.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=eg.find(e=>e.id===t);n&&(a(`paste`),s(n.seedText),h(null),e.target.value=``)},children:[(0,x.jsx)(`option`,{value:``,children:`Pick a sample scenario…`}),eg.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:ng.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${ng.tab} ${i===e?ng.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:E[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:ng.textarea,placeholder:`Type or paste a brief, article, meeting notes, or any domain-specific source material (at least 200 characters).`,value:o,onChange:e=>s(e.target.value),rows:6,disabled:r}),i===`url`&&(0,x.jsxs)(`div`,{className:ng.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:ng.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:ng.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:ng.dropZone,"data-paracosm-local-dropzone":`pdf`,onClick:()=>{r||S.current?.click()},onDragOver:e=>e.preventDefault(),onDrop:e=>{if(e.preventDefault(),r)return;let t=e.dataTransfer.files[0];t&&T(t)},role:`button`,tabIndex:r?-1:0,"aria-disabled":r,onKeyDown:e=>{r||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S.current?.click())},children:[(0,x.jsx)(`input`,{ref:S,type:`file`,accept:`application/pdf,.pdf`,onChange:e=>{let t=e.target.files?.[0];t&&T(t)},hidden:!0}),g?`Extracting text...`:`Drop a PDF or click to upload (max 10 MB, first 50 KB of text used)`]}),(0,x.jsxs)(`div`,{className:ng.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:ng.input,type:`text`,placeholder:`e.g., "clinical trial decision" or "startup growth"`,value:f,onChange:e=>p(e.target.value),maxLength:80,disabled:r})]}),m&&(0,x.jsx)(`p`,{className:ng.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:ng.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:ng.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:ng.actorCountLabel,children:[`Actors: `,(0,x.jsx)(`strong`,{children:v})]}),(0,x.jsx)(`input`,{id:`quickstart-actor-count`,type:`range`,min:1,max:300,value:v,onChange:e=>y(parseInt(e.target.value,10)),disabled:r,className:ng.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:ng.actorCountPreview,"aria-live":`polite`,children:[`~$`,tg(v).toFixed(2),` · `,ag(v)]})]}),(0,x.jsx)(Ih,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:ng.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,tg(v).toFixed(2),`)`]})]})}function ag(e){if(e<=0)return`—`;let t=2+5*Math.max(1,Math.ceil(e/8));return`${t}–${Math.ceil(t*1.5)} min`}var G={card:`_card_182vb_1`,heading:`_heading_182vb_15`,title:`_title_182vb_23`,eyebrow:`_eyebrow_182vb_35`,copy:`_copy_182vb_43`,presetRow:`_presetRow_182vb_50`,presetLabel:`_presetLabel_182vb_61`,presetButton:`_presetButton_182vb_71`,presetButtonActive:`_presetButtonActive_182vb_91`,presetClear:`_presetClear_182vb_97`,presetBlurb:`_presetBlurb_182vb_118`,formGrid:`_formGrid_182vb_126`,formCell:`_formCell_182vb_137`,formLegend:`_formLegend_182vb_152`,field:`_field_182vb_165`,fieldRow:`_fieldRow_182vb_171`,fieldThird:`_fieldThird_182vb_177`,fieldLabel:`_fieldLabel_182vb_182`,input:`_input_182vb_191`,textarea:`_textarea_182vb_212`,mono:`_mono_182vb_235`,actions:`_actions_182vb_240`,button:`_button_182vb_248`,helper:`_helper_182vb_270`,spinner:`_spinner_182vb_276`,"idc-spin":`_idc-spin_182vb_1`,timer:`_timer_182vb_288`},og=`paracosm:lastLaunchConfig`,sg=`paracosm:keyOverrides`,cg=`paracosm:activeRunActors`,lg=`paracosm:activeRunScenarioId`,ug=950;function dg(e){try{let t=e.getItem(og);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function fg(e,t){return e.scenarioId===t}function pg(e,t){try{e.setItem(og,JSON.stringify(t))}catch{}}function mg(e,t,n){try{e.setItem(cg,JSON.stringify(t)),n?e.setItem(lg,n):e.removeItem?.(lg)}catch{}}function hg(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function gg(e){try{let t=e.getItem(cg);if(!t)return null;let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):null}catch{return null}}function _g(e){try{let t=e.getItem(sg);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function vg(e,t){let n=(typeof e.seed==`number`?e.seed:ug)+1,r={...e,seed:n};return t.openai&&(r.apiKey=t.openai),t.anthropic&&(r.anthropicKey=t.anthropic),t.serper&&(r.serperKey=t.serper),t.firecrawl&&(r.firecrawlKey=t.firecrawl),t.tavily&&(r.tavilyKey=t.tavily),t.cohere&&(r.cohereKey=t.cohere),r}function yg(e){if(typeof e!=`string`)return;let t=e.trim();if(t&&!t.includes(`...`))return t}function bg(e){let t=yg(e.openai),n=yg(e.anthropic);return{...t?{apiKey:t}:{},...n?{anthropicKey:n}:{}}}function xg(e){let t=bg(e);return t.apiKey!==void 0||t.anthropicKey!==void 0}var Sg={id:``,name:``,description:``,profileJson:`{}`},Cg={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},wg={medical:{label:`Patient · treatment`,blurb:`Type 2 diabetes patient on a 12-week semaglutide + lifestyle protocol.`,subject:{id:`patient-maria-2026`,name:`Maria Chen`,description:`58 y/o T2D for 4 yrs, sedentary, family hx CVD, on metformin.`,profileJson:JSON.stringify({age:58,yearsWithT2D:4,bmi:31,a1cBaseline:7.8,weightLb:178,fastingGlucose:156,sleepHoursBaseline:6.2,exerciseMinPerWeek:0,comorbidities:`hypertension, dyslipidemia`},null,2)},intervention:{id:`glp1-12wk-protocol`,name:`12-week semaglutide + lifestyle protocol`,description:`Initiate semaglutide 0.25mg weekly, titrate to 1.0mg by week 4. Pair with dietitian-led nutrition plan and 150min/wk graded exercise. Behavioral health checkpoints biweekly. Monitor for GI side effects, gallbladder, pancreatitis.`,durationValue:`84`,durationUnit:`days`,adherence:`0.85`},signalsJson:JSON.stringify([{label:`HbA1c`,value:7.8,unit:`%`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Fasting glucose`,value:156,unit:`mg/dL`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Weight`,value:178,unit:`lb`,recordedAt:`2026-09-15T00:00:00Z`},{label:`BMI`,value:31,unit:`kg/m²`,recordedAt:`2026-09-15T00:00:00Z`}],null,2)},policy:{label:`Jurisdiction · ordinance`,blurb:`A mid-size city pilots downtown congestion pricing for 12 months.`,subject:{id:`city-portland-2026`,name:`Portland Metro`,description:`Pacific Northwest mid-size city with dense urban core, mature transit, organized downtown business association.`,profileJson:JSON.stringify({population:65e4,downtownEmployment:11e4,modeShareTransit:.18,modeShareCar:.62,modeShareActive:.14,avgPeakSpeedMph:14.2,annualCO2Tons:182e4,unemploymentRate:.044},null,2)},intervention:{id:`congestion-pricing-12mo`,name:`Downtown congestion pricing pilot`,description:`Charge $9/peak-hour ($3 off-peak) on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two new BRT lines and a 30% transit fare cut for low-income riders. Pilot runs 12 months with quarterly review.`,durationValue:`12`,durationUnit:`months`,adherence:`0.78`},signalsJson:JSON.stringify([{label:`Downtown VMT`,value:1.42,unit:`million-mi/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Transit ridership`,value:118e3,unit:`boardings/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Peak speed`,value:14.2,unit:`mph`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)},product:{label:`Market · launch`,blurb:`A SaaS launches a new mid-tier price point against a price-sensitive prosumer segment.`,subject:{id:`segment-prosumer-creators`,name:`Prosumer creators`,description:`Independent creators earning $40k-$120k/yr who self-fund their tooling. Cross-tool stackers; price-sensitive within 20% bands.`,profileJson:JSON.stringify({addressableUsers:18e5,currentPaidConversion:.034,avgARPU_USD:22,churnMonthly:.038,npsCurrent:41,topCompetitorPriceUSD:18,topCompetitorMarketShare:.31},null,2)},intervention:{id:`mid-tier-pricing-launch`,name:`New $14/mo mid-tier launch`,description:`Introduce a third pricing tier at $14/mo (between Free and the existing $29/mo Pro), unlocking 60% of Pro features. Bundle with 90-day grandfathering for current Pro subs and a quarterly migration check-in. 6-month pilot before deciding to globalize.`,durationValue:`6`,durationUnit:`months`,adherence:`0.72`},signalsJson:JSON.stringify([{label:`Free → Paid conversion`,value:.034,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Monthly churn`,value:.038,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`NPS`,value:41,unit:`score`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)}};function Tg(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function Eg(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dg({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Sg),[a,o]=(0,b.useState)(Cg),[s,c]=(0,b.useState)(`[]`),[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(0),[p,m]=(0,b.useState)(null),h=e=>{let t=wg[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Sg),o(Cg),c(`[]`),m(null)},_=r.id.trim().length>0&&r.name.trim().length>0&&a.id.trim().length>0&&a.name.trim().length>0&&a.description.trim().length>0;return(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.heading,children:[(0,x.jsx)(`h3`,{className:G.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:G.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:G.copy,children:`Define a subject (patient, market segment, jurisdiction, vehicle, anything) and an intervention to apply to it. Paracosm runs a real LLM-driven simulation across a five-department analysis team and returns a typed RunArtifact with the trajectory.`}),(0,x.jsxs)(`div`,{className:G.presetRow,children:[(0,x.jsx)(`span`,{className:G.presetLabel,children:`Examples`}),Object.entries(wg).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${G.presetButton} ${p===e?G.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:G.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:G.presetBlurb,children:wg[p].blurb}),(0,x.jsxs)(`div`,{className:G.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:r.id,onChange:e=>i(t=>({...t,id:e.target.value})),placeholder:`patient-001`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:r.name,onChange:e=>i(t=>({...t,name:e.target.value})),placeholder:`Maria Chen`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:r.description,onChange:e=>i(t=>({...t,description:e.target.value})),placeholder:`Age, key attributes, baseline state.`,className:G.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Profile (JSON)`}),(0,x.jsx)(`textarea`,{value:r.profileJson,onChange:e=>i(t=>({...t,profileJson:e.target.value})),placeholder:`{"age": 58, "bmi": 31}`,className:`${G.textarea} ${G.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${G.textarea} ${G.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:a.id,onChange:e=>o(t=>({...t,id:e.target.value})),placeholder:`semaglutide-12wk`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:a.name,onChange:e=>o(t=>({...t,name:e.target.value})),placeholder:`12-week semaglutide protocol`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:a.description,onChange:e=>o(t=>({...t,description:e.target.value})),placeholder:`What is being applied, by whom, with what monitoring.`,className:G.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:G.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:G.input})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:G.input,children:[(0,x.jsx)(`option`,{value:`days`,children:`days`}),(0,x.jsx)(`option`,{value:`weeks`,children:`weeks`}),(0,x.jsx)(`option`,{value:`months`,children:`months`}),(0,x.jsx)(`option`,{value:`quarters`,children:`quarters`}),(0,x.jsx)(`option`,{value:`years`,children:`years`})]})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Adherence`}),(0,x.jsx)(`input`,{type:`number`,min:`0`,max:`1`,step:`0.05`,value:a.adherence,onChange:e=>o(t=>({...t,adherence:e.target.value})),className:G.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:G.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=Tg(r.profileJson,{}),o=Tg(s,[]),c={id:r.id.trim(),name:r.name.trim(),profile:r.description.trim()?{...i,description:r.description.trim()}:i,signals:o,markers:[]},d=Number(a.durationValue),p=Number(a.adherence),m={id:a.id.trim(),name:a.name.trim(),description:a.description.trim(),duration:Number.isFinite(d)&&d>0?{value:d,unit:a.durationUnit.trim()||`weeks`}:void 0,adherenceProfile:Number.isFinite(p)?{expected:Math.max(0,Math.min(1,p))}:void 0};u(!0),f(0);let h=Date.now(),g=window.setInterval(()=>{f(Math.round((Date.now()-h)/1e3))},500),v=Eg();await n?.({runKey:v,subject:{id:c.id,name:c.name,profile:c.profile},intervention:{id:m.id,name:m.name,description:m.description,duration:m.duration}});try{let t=await fetch(`/api/quickstart/simulate-intervention`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subject:c,intervention:m,runKey:v,options:{maxTurns:2,seed:11,costPreset:`economy`},...bg(_g(window.localStorage))})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Digital twin run failed: HTTP ${t.status}`)}let n=await t.json();k(window,n.visitorId),e(n.artifact,v)}catch(e){t?.(e instanceof Error?e.message:String(e),v)}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:G.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:G.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:G.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:G.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function Og(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function kg(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Ag={card:`_card_1qdw6_1`,eyebrow:`_eyebrow_1qdw6_27`,row:`_row_1qdw6_36`,actor:`_actor_1qdw6_45`,arrow:`_arrow_1qdw6_56`,meta:`_meta_1qdw6_62`};function jg(){let{sessions:e}=Oe(),t=e[0]?.id?e[0]:null;if(!t)return null;let n=typeof window<`u`?kg(window.location.href,t.id):`?replay=${encodeURIComponent(t.id)}`,r=t.seedText?t.seedText.length>70?`${t.seedText.slice(0,70).trim()}…`:t.seedText.trim():null,i=Rn(t,3),a=t.title||t.scenarioName||i||r||t.id,o=[t.scenarioName&&t.scenarioName!==a?t.scenarioName:null,typeof t.eventCount==`number`?`${t.eventCount} events`:null,typeof t.durationMs==`number`?`${Math.round(t.durationMs/1e3)}s`:null,typeof t.createdAt==`number`?new Date(t.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Ag.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Ag.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Ag.row,children:[(0,x.jsx)(`span`,{className:Ag.actor,children:a}),(0,x.jsx)(`span`,{className:Ag.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Ag.meta,children:o})]})}var Mg={card:`_card_14dqa_7`,statusPending:`_statusPending_14dqa_18`,statusActive:`_statusActive_14dqa_22`,statusDone:`_statusDone_14dqa_27`,header:`_header_14dqa_31`,marker:`_marker_14dqa_60`,pulseDot:`_pulseDot_14dqa_1`,label:`_label_14dqa_93`,duration:`_duration_14dqa_100`,count:`_count_14dqa_121`,chevron:`_chevron_14dqa_137`,chevronOpen:`_chevronOpen_14dqa_148`,actorChips:`_actorChips_14dqa_164`,actorChip:`_actorChip_14dqa_164`,actorChipName:`_actorChipName_14dqa_190`,actorChipState:`_actorChipState_14dqa_194`,actor_running:`_actor_running_14dqa_203`,actor_complete:`_actor_complete_14dqa_212`,actor_error:`_actor_error_14dqa_221`,actor_aborted:`_actor_aborted_14dqa_230`,body:`_body_14dqa_241`,line:`_line_14dqa_266`,lineTs:`_lineTs_14dqa_283`,lineGlyph:`_lineGlyph_14dqa_290`,lineTag:`_lineTag_14dqa_296`,lineActor:`_lineActor_14dqa_309`,lineBody:`_lineBody_14dqa_324`,tonePending:`_tonePending_14dqa_332`,toneInfo:`_toneInfo_14dqa_336`,toneActive:`_toneActive_14dqa_345`,toneDone:`_toneDone_14dqa_358`,toneWarn:`_toneWarn_14dqa_367`,toneError:`_toneError_14dqa_380`},Ng={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Pg({stageId:e,label:t,status:n,logLines:r,duration:i,actors:a}){let[o,s]=(0,b.useState)(n!==`pending`),c=(0,b.useRef)(null),l=(0,b.useRef)(!0);(0,b.useEffect)(()=>{(n===`active`||n===`done`)&&s(e=>e||!0)},[n]);let u=()=>{let e=c.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)};(0,b.useEffect)(()=>{if(!l.current)return;let e=c.current;e&&(e.scrollTop=e.scrollHeight)},[r.length]);let d=n===`done`?`✓`:n===`active`?`●`:`○`,f=n===`done`?Mg.statusDone:n===`active`?Mg.statusActive:Mg.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${Mg.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:Mg.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:Mg.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:Mg.label,children:t}),i&&(0,x.jsx)(`span`,{className:Mg.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:Mg.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${Mg.chevron} ${o?Mg.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:Mg.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${Mg.actorChip} ${Mg[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:Mg.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:Mg.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Ng[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:Mg.body,ref:c,onScroll:u,role:`log`,"aria-live":n===`active`?`polite`:`off`,"aria-label":`${t} log`,children:[r.length===0&&(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg.tonePending}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg[`tone${Fg(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:Mg.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:Mg.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:e.body})]},t))]})]})}function Fg(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ig(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=e/1e3,n=Math.floor(t/60),r=Math.floor(t%60),i=Math.floor(t*10%10);return`${n}:${String(r).padStart(2,`0`)}.${i}`}function Lg(e){return e===`turn_start`||e===`turn_done`?`active`:e===`specialist_done`||e===`sim_complete`||e===`agent_reactions`?`done`:e===`decision_pending`||e===`decision_made`||e===`outcome`?`info`:e===`sim_aborted`||e===`provider_error`||e===`validation_fallback`?`warn`:`info`}function Rg(e){switch(e){case`turn_start`:return`TURN`;case`turn_done`:return`TURN`;case`specialist_start`:return`SPEC`;case`specialist_done`:return`SPEC`;case`decision_pending`:return`DEC`;case`decision_made`:return`DEC`;case`outcome`:return`OUT`;case`agent_reactions`:return`REACT`;case`bulletin`:return`NEWS`;case`promotion`:return`PROMO`;case`systems_snapshot`:return`SNAP`;case`drift`:return`DRIFT`;case`personality_drift`:return`DRIFT`;case`sim_aborted`:return`ABORT`;case`provider_error`:return`ERR`;case`validation_fallback`:return`FALLBACK`;case`sim_complete`:return`DONE`;default:return e.toUpperCase().slice(0,8)}}function zg(e){let t=e.data??{};return(typeof t.summary==`string`?t.summary:``)||(typeof t.department==`string`?t.department:typeof t.title==`string`?t.title:typeof t.decision==`string`?t.decision:typeof t.outcome==`string`?t.outcome:typeof t.eventType==`string`?t.eventType:typeof t.tool==`string`?t.tool:``)}function Bg(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=zg(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:e.type===`validation_fallback`&&e.data?.salvaged===!0?`SALVAGE`:Rg(e.type),body:r,tone:Lg(e.type),actor:typeof n==`string`?n:void 0}}function Vg(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Ig(a-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/compile-from-seed`,tone:t===`compile`?`active`:`info`});let o=r?.research;return o&&i.push({ts:Ig(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Hg(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Ig(o-n);if(i?.skipped)return a.push({ts:s,glyph:`⚠`,tag:`SKIP`,body:`Deep research skipped: ${i.reason??`unknown`}`,tone:`warn`}),a;if(i?.citations&&i.citations.length>0){let e=i.providersUsed?.length?` · providers: ${i.providersUsed.join(` + `)}`:``;a.push({ts:s,glyph:`→`,tag:`POST`,body:`/api/quickstart/ground-scenario · ${i.citations.length} queries${e}`,tone:t===`research`?`active`:`info`});for(let e of i.providersFailed??[])a.push({ts:s,glyph:`⚠`,tag:e.provider.toUpperCase().slice(0,8),body:`provider unavailable: ${e.reason.slice(0,120)}`,tone:`warn`});for(let e of i.citations){a.push({ts:s,glyph:`·`,tag:`QUERY`,body:`"${e.query}" → ${e.sources.length} source${e.sources.length===1?``:`s`}`,tone:`info`});for(let t of e.sources.slice(0,3)){let e=(t.provider??``).toUpperCase()||t.domain.toUpperCase().slice(0,16)||`SRC`;a.push({ts:s,glyph:`·`,tag:e,body:t.title,tone:`done`})}}if(typeof i.totalSources==`number`){let e=typeof i.durationMs==`number`?` · ${(i.durationMs/1e3).toFixed(1)}s`:``;a.push({ts:s,glyph:`✓`,tag:`OK`,body:`${i.totalSources} unique sources attached to ScenarioPackage${e}`,tone:`done`})}return a}a.push({ts:s,glyph:`·`,tag:`NOTE`,body:`Grounding scenario with web research…`,tone:t===`research`?`active`:`info`});let c=r?.actors;return c&&a.push({ts:Ig(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Ug(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Ig(o-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/generate-actors · count=${i}`,tone:t===`actors`?`active`:`info`});let s=r?.running;return s&&a.push({ts:Ig(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Wg(e){return e.events.map(e=>Bg(e)).filter(e=>!!e)}function Gg(e,t){switch(e){case`compile`:return Vg(t);case`research`:return Hg(t);case`actors`:return Ug(t);case`running`:return Wg(t);case`done`:return[]}}function Kg(e,t){let n=[`compile`,`research`,`actors`,`running`,`done`],r=n.indexOf(e),i=t.phaseTransitionMs?.[e],a=n[r+1],o=a?t.phaseTransitionMs?.[a]:void 0;if(!i)return``;let s=((o??Date.now())-i)/1e3;return s<1?`${Math.max(1,Math.round(s*1e3))}ms`:s<10?`${s.toFixed(1)}s`:`${Math.round(s)}s`}var qg={progress:`_progress_5dmny_6`,heading:`_heading_5dmny_19`,title:`_title_5dmny_26`,subtitle:`_subtitle_5dmny_35`,stageList:`_stageList_5dmny_43`,stageItem:`_stageItem_5dmny_55`,cancel:`_cancel_5dmny_59`,jumpToSim:`_jumpToSim_5dmny_84`},Jg=[`compile`,`research`,`actors`,`running`,`done`];function Yg(e,t){let n=Jg.indexOf(e),r=Jg.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Xg({stage:e,actors:t,events:n,actorCount:r,groundingSummary:i,onCancel:a}){let o=(0,b.useRef)(Date.now()),[s,c]=(0,b.useState)(()=>({compile:Date.now()})),l=(0,b.useRef)(e);(0,b.useEffect)(()=>{l.current!==e&&(l.current=e,c(t=>t[e]?t:{...t,[e]:Date.now()}))},[e]);let[,u]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(e===`done`)return;let t=setInterval(()=>u(e=>(e+1)%1e6),1e3);return()=>clearInterval(t)},[e]);let d=r??t?.length??3,f=nA(),p=(0,b.useMemo)(()=>({stage:e,startMs:o.current,phaseTransitionMs:s,actorCount:d,events:n??[],groundingSummary:i??null}),[e,s,d,n,i]),m=[{id:`compile`,label:`Compile scenario`},{id:`research`,label:`Ground with citations`},{id:`actors`,label:`Generate ${d} actor${d===1?``:`s`}`},{id:`running`,label:`Run ${d} simulation${d===1?``:`s`}`}];return(0,x.jsxs)(`section`,{className:qg.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:qg.heading,children:[(0,x.jsx)(`span`,{className:qg.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:qg.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:qg.stageList,children:m.map(n=>{let r=Yg(e,n.id);return(0,x.jsx)(`li`,{className:qg.stageItem,children:(0,x.jsx)(Pg,{stageId:n.id,label:n.label,status:r,logLines:Gg(n.id,p),duration:Kg(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:qg.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:qg.cancel,onClick:a,children:`Cancel run`})]})}var Zg=Object.freeze({visionary:{id:`visionary`,name:`Aria Okafor`,archetype:`The Visionary`,description:`Bets on bold experiments. Tolerates ambiguity. Casts a wide pattern net.`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},pragmatist:{id:`pragmatist`,name:`Marcus Reyes`,archetype:`The Pragmatist`,description:`Leads by protocol and evidence. Safety margins first.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.35,agreeableness:.6,emotionality:.5,honestyHumility:.85}},innovator:{id:`innovator`,name:`Yuki Tanaka`,archetype:`The Innovator`,description:`Pushes novel tool forging. Accepts higher variance.`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.7,agreeableness:.45,emotionality:.35,honestyHumility:.55}},stabilizer:{id:`stabilizer`,name:`Elena Voss`,archetype:`The Stabilizer`,description:`Holds the line. Protects existing capacity. Change-averse.`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.75,emotionality:.55,honestyHumility:.7}},"crisis-manager":{id:`crisis-manager`,name:`Nadia Chen`,archetype:`The Crisis Manager`,description:`Thrives under pressure. Decisive. Low emotional reactivity.`,hexaco:{openness:.55,conscientiousness:.8,extraversion:.75,agreeableness:.45,emotionality:.25,honestyHumility:.6}},"growth-optimist":{id:`growth-optimist`,name:`Diego Santoro`,archetype:`The Growth Optimist`,description:`Chases expansion. High risk tolerance. Charismatic rally-er.`,hexaco:{openness:.8,conscientiousness:.5,extraversion:.9,agreeableness:.55,emotionality:.35,honestyHumility:.4}},"protocol-builder":{id:`protocol-builder`,name:`Priya Rao`,archetype:`The Protocol Builder`,description:`Codifies everything. Demands evidence. Slow to decide, hard to dislodge.`,hexaco:{openness:.5,conscientiousness:.95,extraversion:.35,agreeableness:.6,emotionality:.45,honestyHumility:.9}},"social-architect":{id:`social-architect`,name:`Kai Rivers`,archetype:`The Social Architect`,description:`Builds coalitions. Manages morale. Relationship-first.`,hexaco:{openness:.6,conscientiousness:.65,extraversion:.8,agreeableness:.9,emotionality:.55,honestyHumility:.7}},"cost-cutter":{id:`cost-cutter`,name:`Hannah Novak`,archetype:`The Cost Cutter`,description:`Optimizes ruthlessly. Will trade morale for capacity.`,hexaco:{openness:.35,conscientiousness:.9,extraversion:.45,agreeableness:.3,emotionality:.25,honestyHumility:.55}},"compliance-hawk":{id:`compliance-hawk`,name:`Owen Ibarra`,archetype:`The Compliance Hawk`,description:`Audits every decision. Never cuts corners. Reports failures transparently.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.45,agreeableness:.65,emotionality:.5,honestyHumility:.95}}}),Qg={backdrop:`_backdrop_fgbmo_1`,dialog:`_dialog_fgbmo_12`,header:`_header_fgbmo_23`,list:`_list_fgbmo_47`,preset:`_preset_fgbmo_56`,archetype:`_archetype_fgbmo_82`,description:`_description_fgbmo_87`};function $g({onSelect:e,onClose:t}){let n=Pt(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Qg.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Qg.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Qg.header,children:[(0,x.jsx)(`h3`,{children:`Swap leader`}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,children:`×`})]}),(0,x.jsx)(`ul`,{className:Qg.list,children:Object.values(Zg).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Qg.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Qg.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Qg.description,children:t.description})]})},t.id))})]})})}var e_={results:`_results_8jenm_2`,runSummary:`_runSummary_8jenm_15`,summaryStat:`_summaryStat_8jenm_26`,summaryNum:`_summaryNum_8jenm_40`,summaryLabel:`_summaryLabel_8jenm_50`,grid:`_grid_8jenm_61`,card:`_card_8jenm_81`,cardHeader:`_cardHeader_8jenm_92`,actorName:`_actorName_8jenm_106`,archetype:`_archetype_8jenm_110`,swap:`_swap_8jenm_119`,hexaco:`_hexaco_8jenm_142`,trait:`_trait_8jenm_151`,traitLabel:`_traitLabel_8jenm_160`,traitBarOuter:`_traitBarOuter_8jenm_168`,traitBarInner:`_traitBarInner_8jenm_175`,fingerprint:`_fingerprint_8jenm_180`,deltas:`_deltas_8jenm_192`,delta:`_delta_8jenm_192`,direction_up:`_direction_up_8jenm_209`,direction_down:`_direction_down_8jenm_213`,direction_changed:`_direction_changed_8jenm_217`,actions:`_actions_8jenm_222`,forkButton:`_forkButton_8jenm_249`,forkHint:`_forkHint_8jenm_259`},t_=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function n_({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=Gn(),a=nA(),o=Lm(),[s,c]=(0,b.useState)(null),l=on(),u=l.clear,[d,f]=(0,b.useState)(null);(0,b.useEffect)(()=>{u()},[n,u]);let p=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},m=e=>{n&&(f(e),l.share(vh(window.location.origin,n)))},h=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;yh(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},g=(0,b.useMemo)(()=>({totalTools:t.reduce((e,t)=>e+(t?.forgedTools?.length??0),0),totalCitations:t.reduce((e,t)=>e+(t?.citations?.length??0),0),totalDecisions:t.reduce((e,t)=>e+(t?.decisions?.length??0),0),totalTurns:t.reduce((e,t)=>e+(t?.trajectory?.timepoints?.length??0),0),totalCostUSD:t.reduce((e,t)=>e+(t?.cost?.totalUSD??0),0)}),[t]);return(0,x.jsxs)(`div`,{className:e_.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:e_.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Web sources Paracosm pulled via Serper + Tavily and attached to the scenario before generating actors. Grounds the sim in real-world knowledge instead of pure LLM imagination.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalCitations}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one at runtime, run in a QuickJS WebAssembly sandbox. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTools}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalDecisions}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total simulation turns across all 3 parallel actors. Each turn = one decision cycle: department analysis, commander decision, kernel advance, agent reactions.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTurns}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`turns simulated`})]}),g.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total LLM spend across all 3 actors. Provider: gpt-5.4-mini for sims, gpt-4o for verdict.`,children:[(0,x.jsxs)(`span`,{className:e_.summaryNum,children:[`$`,g.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:e_.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(r_,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,shareEnabled:!!n,onDownload:()=>h(r),onShare:()=>m(r),shareNote:d===r&&l.shared?(0,x.jsx)(dn,{shared:l.shared,onClose:l.clear}):null,onFork:()=>p(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)($g,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function r_({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,shareEnabled:a,shareNote:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>_h(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:e_.card,children:[(0,x.jsxs)(`header`,{className:e_.cardHeader,children:[(0,x.jsx)(`h4`,{className:e_.actorName,children:e.name}),(0,x.jsx)(`span`,{className:e_.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:e_.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:e_.hexaco,children:t_.map(t=>(0,x.jsxs)(`div`,{className:e_.trait,children:[(0,x.jsx)(`span`,{className:e_.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:e_.traitBarOuter,children:(0,x.jsx)(`div`,{className:e_.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:e_.fingerprint,children:[(0,x.jsx)(`span`,{children:`FP`}),(0,x.jsx)(`code`,{children:t.fingerprint?Object.values(t.fingerprint).slice(0,3).join(` / `):`n/a`})]}),d.length>0&&(0,x.jsx)(`ul`,{className:e_.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${e_.delta} ${e_[`direction_${e.direction}`]}`,children:Bm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:e_.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!a,title:`Copy a deep link that opens this run on the visualization tab`,children:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:e_.forkButton,title:f===0?`No turns completed yet`:`Promote to fork root and open Branches tab. ${f} ${f===1?r:`${r}s`} available.`,children:`Fork in Branches →`})]}),o,(0,x.jsx)(`div`,{className:e_.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var i_=2e3,a_=3e5;function o_(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}async function s_(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{throw Error(`Compile returned non-JSON HTTP ${e.status} response`)}if(!e.ok&&(!n||typeof n!=`object`))throw Error(`Compile failed: HTTP ${e.status}`);if(!n||typeof n!=`object`)throw Error(`Compile returned empty body`);return n}async function c_(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??i_,i=t.timeoutMs??a_,a=t.waitImpl??o_,o=Date.now(),s=await n(`/api/quickstart/compile-from-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t.signal});if(!s.ok&&s.status!==202){let e=await s.json().catch(()=>({}));throw Error(e.error??`Compile failed: HTTP ${s.status}`)}let c=await s_(s);if(c.status===`done`&&c.scenario)return{scenario:c.scenario,scenarioId:c.scenario.id,jobId:c.jobId};if(c.status===`error`)throw Error(c.error??`Compile failed`);for(;Date.now()-o<i;){await a(r,t.signal);let e=await n(`/api/quickstart/compile-from-seed/status`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jobId:c.jobId}),signal:t.signal});if(!e.ok){if(e.status===404)throw Error(`Compile job expired or not found. Please retry.`);let t=await e.json().catch(()=>({}));throw Error(t.error??`Compile status check failed: HTTP ${e.status}`)}let i=await s_(e);if(i.status===`done`&&i.scenario)return{scenario:i.scenario,scenarioId:i.scenario.id,jobId:i.jobId};if(i.status===`error`)throw Error(i.error??`Compile failed`)}throw Error(`Compile is taking longer than ${Math.round(i/1e3)}s. The server may still be working — please retry in a minute.`)}var l_={view:`_view_1gdit_2`,header:`_header_1gdit_12`,howItWorks:`_howItWorks_1gdit_36`,glossary:`_glossary_1gdit_43`,timingHint:`_timingHint_1gdit_44`,howItWorksSummary:`_howItWorksSummary_1gdit_60`,errorBanner:`_errorBanner_1gdit_137`,compareCta:`_compareCta_1gdit_149`};function u_(e){return/Failed to fetch|NetworkError|ERR_CONNECTION|ERR_NETWORK/i.test(e)?`Couldn't reach the server. Check your connection and try again.`:/HTTP 502|HTTP 503|HTTP 504/.test(e)?`Server is temporarily unavailable (502/503/504). Try again in a moment.`:/HTTP 429|rate.?limit/i.test(e)?`Hosted demo is rate-limited (3 runs/day). Drop your own API key in Settings to bypass — your saved keys flow into the run automatically.`:/HTTP 401|HTTP 403|unauthor/i.test(e)?`Auth error talking to the LLM provider. Check your API key in Settings.`:/Two actors required|at least 2 actors/i.test(e)?`This scenario needs at least 2 actors. Bump the slider before launching.`:/TypeError|ReferenceError|Cannot read propert|is not a function|is not iterable/i.test(e)?(typeof console<`u`&&console.error(`[quickstart] launch error:`,e),`Something went wrong starting the run. Refresh the page and try again — if it keeps happening, drop a note in the GitHub issues with what you clicked just before.`):e}function d_({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=Qk(),s=eA(),{toast:c}=Ht(),[l,u]=(0,b.useState)({kind:`input`}),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(!1),[_,v]=(0,b.useState)(null),y=`paracosm:catalogPendingRun`,S=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset();let r=typeof window<`u`?_g(window.localStorage):{},i=typeof window<`u`?dg(window.localStorage):null,a=bg(r),s={...a};r.serper&&(s.serperKey=r.serper),r.firecrawl&&(s.firecrawlKey=r.firecrawl),r.tavily&&(s.tavilyKey=r.tavily),r.cohere&&(s.cohereKey=r.cohere),i?.provider&&(s.provider=i.provider),i?.models&&typeof i.models==`object`&&(s.models=i.models),i?.economics&&typeof i.economics==`object`&&(s.economics=i.economics);let l=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(l.length>=t){u({kind:`progress`,stage:`running`});let n=l.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&mg(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:n,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Setup failed: HTTP ${e.status}`)}let t=await e.json().catch(()=>({}));if(t.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}else{u({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:o.id,count:t,...a})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${n.status}`)}let r=(await n.json().catch(()=>null))?.actors;if(!r||r.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`}),await e.reset(),typeof window<`u`&&mg(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:r,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${i.status}`)}let c=await i.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}},[o,e,n,c]),C=(0,b.useCallback)(async(e,t)=>{if(e===o.id)S(t);else{f(null),n?.();try{try{sessionStorage.setItem(y,JSON.stringify({scenarioId:e,actorCount:t,ts:Date.now()}))}catch{}let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})});if(!n.ok){try{sessionStorage.removeItem(y)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=u_(e?.message??String(e));f(t),c(`error`,`Scenario switch failed`,t,8e3)}}},[o.id,S,n,c]);(0,b.useEffect)(()=>{if(!s)return;let e=null;try{let t=sessionStorage.getItem(y);if(!t)return;sessionStorage.removeItem(y),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==o.id){c(`error`,`Scenario changed`,`Another tab of this browser picked a different scenario before the run you picked could start, so nothing ran. Pick it in the catalog again.`,8e3);return}let t=typeof e?.actorCount==`number`&&e.actorCount>0?Math.min(300,Math.max(1,e.actorCount)):null;t!==null&&S(t)},[s]);let w=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset(),u({kind:`progress`,stage:`compile`});try{let n=typeof window<`u`?bg(_g(window.localStorage)):{},{scenario:r,scenarioId:i}=await c_({...t,...n});u({kind:`progress`,stage:`research`,scenario:r});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:r});let a=Math.max(1,Math.min(300,t.actorCount??2)),o=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i,count:a,...n})});if(!o.ok){let e=await o.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${o.status}`)}let s=(await o.json().catch(()=>null))?.actors;if(!s||s.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:r,actors:s}),await e.reset(),typeof window<`u`&&mg(window.localStorage,s,i);let c=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,actors:s,turns:r.setup.defaultTurns,seed:r.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:i}})});if(!c.ok){let e=await c.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${c.status}`)}let l=await c.json().catch(()=>({}));if(l.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,l.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Quickstart failed`,t,8e3)}},[e,n,c]);(0,b.useEffect)(()=>{if(l.kind!==`progress`||l.stage!==`running`||!l.scenario||!l.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=l.actors.length&&u({kind:`results`,scenario:l.scenario,actors:l.actors,artifacts:t.slice(0,l.actors.length)})},[e.results,l]),(0,b.useEffect)(()=>{if(l.kind!==`results`||p!==null)return;let e=l.artifacts[0]?.metadata?.runId;if(!e)return;let t=!1;return fetch(`/api/v1/runs/${encodeURIComponent(e)}`).then(async e=>e.ok?e.json():null).then(e=>{if(t)return;let n=e?.record?.bundleId;n&&m(n)}).catch(()=>{}),()=>{t=!0}},[l,p]);let T=l.kind===`progress`&&l.stage===`running`&&l.actors?l.actors.map((t,n)=>{let r=e.events.filter(e=>e.type===`turn_done`||e.type===`turn_start`).reduce((e,t)=>{let n=t.data?.turn??0;return n>e?n:e},0),i=e.results.find(e=>e.actorIndex===n),a=e.errors.length>0&&!i?`error`:e.isAborted?`aborted`:i?`complete`:`running`;return{name:t.name,archetype:t.archetype,currentTurn:i?l.scenario?.setup.defaultTurns??r:r,maxTurns:l.scenario?.setup.defaultTurns??6,status:a}}):void 0,E=(0,b.useCallback)((e,t)=>{f(`Actor swap rerun is a v1.1 follow-up. Use "Fork in Branches" on the Branches tab to try a preset actor against this run.`)},[]);return(0,x.jsxs)(`div`,{className:l_.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:l_.header,children:[(0,x.jsx)(`h2`,{children:`Quickstart`}),(0,x.jsx)(`p`,{children:`Paste a what-if scenario. Paracosm compiles it into a typed world and runs LLM-driven decision-makers with measurable personalities against it, returning a replayable trajectory you can fork and compare.`}),(0,x.jsxs)(`details`,{className:l_.howItWorks,children:[(0,x.jsx)(`summary`,{className:l_.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:l_.glossary,"aria-label":`Key terms`,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Scenario`}),` — the world Paracosm compiles from your prompt: departments, agents, events, starting state.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Actor`}),` — an LLM decision-maker driving the scenario, weighted by a HEXACO personality vector.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run`}),` — one actor playing the scenario turn by turn. Paracosm runs N actors in parallel against the same world so you can compare divergent outcomes.`]})]}),(0,x.jsxs)(`p`,{className:l_.timingHint,children:[(0,x.jsx)(`strong`,{children:`Heads-up:`}),` a fresh run takes `,(0,x.jsx)(`strong`,{children:`2-5 minutes`}),` (compile, ground with citations, generate actors, simulate). For instant results, replay a cached run below.`]})]})]}),d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),(0,x.jsx)(jg,{}),(0,x.jsx)(ig,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(Dg,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Xg,{stage:l.stage,actors:T,events:e.events,actorCount:l.actors?.length??T?.length??2,groundingSummary:_}),l.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:l_.compareCta,onClick:()=>g(!0),"aria-label":`Compare all ${l.artifacts.length} actors side-by-side`,children:[`Compare all `,l.artifacts.length,` actors →`]}),(0,x.jsx)(n_,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:E}),p&&h&&(0,x.jsx)(ra,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var f_={getNumber:()=>0,getEntry:()=>void 0,list:[]};function p_(e){return(0,b.useMemo)(()=>{let t=new Map,n=[],r=1;for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`specialist_done`)continue;let a=String(e.data?.department||``),o=e.data?.citationList||[];for(let e of o){let o=(e.url||``).trim(),s=(e.text||``).trim();if(!o&&!s||!o&&s===`Seed document`)continue;let c=o||`text:${s}`,l=t.get(c);l||(l={n:r++,text:s||o,url:o,doi:e.doi,departments:new Set,actorNames:new Set},t.set(c,l),n.push(l)),a&&l.departments.add(a),l.actorNames.add(i),!l.doi&&e.doi&&(l.doi=e.doi)}}}return{getNumber:e=>e?(t.get(e)||t.get(`text:${e}`))?.n??0:0,getEntry:e=>t.get(e)||t.get(`text:${e}`),list:n}},[e])}var m_=(0,b.createContext)(f_);function h_(){return(0,b.useContext)(m_)}var g_=()=>({tools:0,forges:0,reforges:0,passed:0,didNotPass:0});function __(e){let t=String(e??``).trim();return t===`unnamed`?``:t}var v_=e=>Array.isArray(e)?e:[];function y_(e){if(e.type!==`specialist_done`)return!1;let t=e.data?.forgedTools;return t!=null&&!Array.isArray(t)}function b_(e,t,n,r){return{n:0,name:e,description:String(r.description||e),mode:String(r.mode||`sandbox`),firstForgedTurn:r.turn,firstForgedDepartment:r.department,departments:new Set,actorNames:new Set([n]),reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:r.confidence,approved:r.approved,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:r.errorReason,inputFields:v_(r.inputFields),outputFields:v_(r.outputFields),history:[],actorIndex:t,actorName:n,attempts:[],outcome:r.approved?`passed`:`did_not_pass`,sameNameActors:[]}}function x_(e,t,n){let r=new Map;for(let t of e){if(t.type!==`event_start`)continue;let e=`${Number(t.data?.turn??t.turn??0)}:${Number(t.data?.eventIndex??0)}`;r.has(e)||r.set(e,String(t.data?.title??``))}let i=new Map,a=[],o=new Map,s=[];for(let c of e){let e=c.data??{};if(c.type===`forge_attempt`){let o=__(e.name);if(!o)continue;let l=Number(e.turn??c.turn??0),u=Number(e.eventIndex??0),d=String(e.department??``),f=e.approved===!0,p=typeof e.confidence==`number`?e.confidence:null,m=typeof e.errorReason==`string`&&e.errorReason?e.errorReason:null,h=i.get(o);h||(h=b_(o,t,n,{description:e.description,mode:e.mode,turn:l,department:d,confidence:p??0,approved:f,errorReason:m??void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(o,h),a.push(h));let g={attempt:h.attempts.length+1,turn:l,time:Number(e.time??0),eventIndex:u,department:d,eventTitle:r.get(`${l}:${u}`)??``,approved:f,confidence:p,errorReason:m,description:String(e.description??``),inputFields:v_(e.inputFields),outputFields:v_(e.outputFields),eventId:c.id};h.attempts.push(g),d&&h.departments.add(d),p!==null&&p>h.confidence&&(h.confidence=p),f?(h.approved=!0,h.errorReason=void 0):!h.approved&&m&&(h.errorReason=m),s.push(f?`passed`:`did_not_pass`);continue}if(c.type!==`specialist_done`)continue;let l=Array.isArray(e._filteredTools)?e._filteredTools:[],u=String(e.department||``);for(let e of l){let r=__(e.name);if(!r)continue;let s=e.approved!==!1,l=i.get(r);if(l?(o.has(l)||(typeof e.description==`string`&&e.description&&(l.description=e.description),typeof e.mode==`string`&&e.mode&&(l.mode=e.mode),typeof e.firstForgedTurn==`number`&&(l.firstForgedTurn=e.firstForgedTurn),typeof e.firstForgedDepartment==`string`&&e.firstForgedDepartment&&(l.firstForgedDepartment=e.firstForgedDepartment),Array.isArray(e.inputFields)&&(l.inputFields=e.inputFields),Array.isArray(e.outputFields)&&(l.outputFields=e.outputFields)),typeof e.confidence==`number`&&e.confidence>l.confidence&&(l.confidence=e.confidence),s&&(l.approved=!0),l.approved?l.errorReason=void 0:typeof e.errorReason==`string`&&e.errorReason&&(l.errorReason=e.errorReason)):(l=b_(r,t,n,{description:e.description,mode:e.mode,turn:typeof e.firstForgedTurn==`number`?e.firstForgedTurn:c.turn??0,department:String(e.firstForgedDepartment||u),confidence:typeof e.confidence==`number`?e.confidence:s?.85:0,approved:s,errorReason:typeof e.errorReason==`string`?e.errorReason:void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(r,l),a.push(l)),typeof e.output==`string`&&(e.output||l.sampleOutput===null)&&(l.sampleOutput=e.output),!l.inputSchema&&e.inputSchema&&(l.inputSchema=e.inputSchema),!l.outputSchema&&e.outputSchema&&(l.outputSchema=e.outputSchema),u&&l.departments.add(u),o.set(l,s),Array.isArray(e.history)){let t=e.history;l.history=t.map(e=>({...e,actorName:n})),l.reuseCount=Math.max(0,t.length-1),l.reforgeCount=t.filter(e=>e.isReforge).length,l.rejectedReforges=t.filter(e=>e.isReforge&&e.rejected).length}}}for(let e of a){o.has(e)||(e.history=e.attempts.map((e,t)=>({turn:e.turn,time:e.time,eventIndex:e.eventIndex,eventTitle:e.eventTitle,department:e.department,output:null,isReforge:t>0,rejected:!e.approved,confidence:e.confidence??void 0,actorName:n})),e.reforgeCount=Math.max(0,e.attempts.length-1),e.rejectedReforges=e.attempts.filter(e=>!e.approved).length);let t=e.attempts[e.attempts.length-1];e.outcome=(t?t.approved:o.get(e)!==!1)?`passed`:`did_not_pass`}return{entries:a,strip:s}}function S_(e,t){e.tools+=t.tools,e.forges+=t.forges,e.reforges+=t.reforges,e.passed+=t.passed,e.didNotPass+=t.didNotPass}function C_(e){let t=[],n=[],r=g_(),i=new Map,a=new Map,o=(e,t)=>`${e}\u0000${t}`;e.actorIds.forEach((s,c)=>{let l=e.actors[s],u=l?.events??[],d=u.some(y_),{entries:f,strip:p}=d?{entries:[],strip:[]}:x_(u,c,s),m=g_();for(let e of f){e.n=t.length+1,t.push(e),i.set(o(c,e.name),e);let n=a.get(e.name);n?n.push(e):a.set(e.name,[e]);let r=e.attempts.filter(e=>e.approved).length;S_(m,{tools:1,forges:e.attempts.length,reforges:Math.max(0,e.attempts.length-1),passed:r,didNotPass:e.attempts.length-r})}S_(r,m),n.push({index:c,label:`A${c+1}`,name:s,archetype:l?.leader?.archetype??``,counts:m,strip:p,status:e.isComplete?`done`:u.length===0?`waiting`:`running`,unreadable:d})});for(let e of a.values())for(let t of e)t.sameNameActors=e.filter(e=>e!==t).map(e=>e.actorIndex);return{getNumber:e=>a.get(e.trim())?.[0]?.n??0,getEntry:e=>a.get(e.trim())?.[0],getEntryFor:(e,t)=>i.get(o(e,t.trim())),getEntryByNumber:e=>Number.isInteger(e)&&e>=1?t[e-1]:void 0,list:t,actors:n,counts:r}}var w_={getNumber:()=>0,getEntry:()=>void 0,getEntryFor:()=>void 0,getEntryByNumber:()=>void 0,list:[],actors:[],counts:{tools:0,forges:0,reforges:0,passed:0,didNotPass:0}};function T_(e){return(0,b.useMemo)(()=>C_(e),[e])}var E_=(0,b.createContext)(w_);function D_(){return(0,b.useContext)(E_)}var O_=[`request`,`code`,`tests`,`judge`,`added`];function k_(e){return e===`passed`?`passed`:`didNotPass`}var A_=`request`;function j_(e){return e===`passed`?{stations:{request:`reached`,code:`reached`,tests:`reached`,judge:`reached`,added:`reached`},stop:null,deciding:`judge`}:{stations:{request:`reached`,code:`unknown`,tests:`unknown`,judge:`unknown`,added:`notReached`},stop:null,deciding:`request`}}function M_(e,t){let n=e.attempts.length;return n===0?0:Number.isFinite(t)?Math.min(Math.max(Math.trunc(t),1),n):n}function N_(e,t){let n=e.attempts;if(n.length===0)return{...j_(e.outcome),spurs:[],branch:null};let r=M_(e,t),i=e=>e?`passed`:`did_not_pass`,a=n[r-1],o=n[r];return{...j_(i(a.approved)),spurs:n.slice(0,r-1).map(e=>({attempt:e.attempt,station:A_,outcome:i(e.approved)})),branch:o?{attempt:o.attempt,station:A_,outcome:i(o.approved)}:null}}function P_(e,t){return t<=2?Pe(e):`var(--forge-quiet)`}function F_(e){return e.history.slice(1).filter(e=>!e.isReforge).length}var I_={forge_toolbox_open:{from:[`sim`,`reports`,`viz`]},forge_trace_open:{from:[`toolbox`,`inspect`,`viz`,`link`]},forge_station_open:{station:O_,via:[`press`,`open_all`,`kept`]},forge_toolbox_filter:{show:[`all`,`passed`,`did_not_pass`]},forge_record_export:{what:[`toolbox`,`record_copy`,`record_download`]},forge_log_jump:{},forge_link_copy:{},forge_toolbox_group:{group:[`actor`,`department`,`none`]},forge_group_toggle:{scope:[`one`,`all`]},forge_actor_filter:{actors:[`1`,`2-4`,`5-24`,`25+`]},forge_actor_picker_open:{where:[`toolbox`,`compare`,`event_log`]}};function L_(e){return!Number.isFinite(e)||e<1?null:e===1?`1`:e<=4?`2-4`:e<=24?`5-24`:`25+`}function R_(e,t){try{let n=e.paracosmConsent;return typeof n?.allows==`function`&&n.allows(t)===!0}catch{return!1}}function z_(e){try{let{origin:t,pathname:n}=e.location;return typeof t==`string`&&typeof n==`string`?t+n:null}catch{return null}}function B_(e,t){let n=t??(typeof window>`u`?void 0:window);if(!n)return;let r=n,i=I_[e.name];if(!i)return;let a=R_(r,`measure`),o=R_(r,`record`);if(!a&&!o)return;let s={},c=e;for(let[e,t]of Object.entries(i)){let n=c[e];typeof n==`string`&&t.includes(n)&&(s[e]=n)}if(a&&typeof r.gtag==`function`){let t=z_(n);try{r.gtag(`event`,e.name,t===null?s:{...s,page_location:t})}catch{}}if(o&&typeof r.clarity==`function`)try{r.clarity(`event`,e.name)}catch{}}var V_={tool:`tool`,attempt:`attempt`,open:`open`,toolbox:`toolbox`,show:`show`,find:`find`,group:`group`,actors:`actors`},H_=Object.values(V_),U_=[V_.tool,V_.attempt,V_.open];function W_(e){if(e===null||!/^\d+$/.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t>=1?t:null}function G_(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase());return O_.filter(e=>t.includes(e))}function K_(e){let t=[];for(let n of e.split(`,`)){let e=W_(n);e!==null&&!t.includes(e)&&t.push(e)}return t}function q_(e,t,n){let r={trace:null,toolbox:{open:!1}},i=[],a;try{a=new URL(e).searchParams}catch{return{state:r,dangling:i}}r.toolbox.open=a.get(V_.toolbox)===`1`;for(let e of[V_.show,V_.find,V_.group]){let t=a.get(e);t!==null&&t!==``&&(r.toolbox[e]=t)}let o=a.get(V_.actors);if(o!==null){let e=K_(o),a=n?e.filter(e=>e<=t.actors.length):e;a.length>0?r.toolbox.actors=a:n&&i.push(V_.actors)}if(!n)return{state:r,dangling:i};let s=U_.filter(e=>a.has(e));if(s.length===0)return{state:r,dangling:i};let c=W_(a.get(V_.tool)),l=c===null?void 0:t.getEntryByNumber(c);if(!l)return i.push(...s),{state:r,dangling:i};let u;if(a.has(V_.attempt)){let e=W_(a.get(V_.attempt));if(e===null||e>l.attempts.length)return i.push(...s),{state:r,dangling:i};u=e}let d;if(a.has(V_.open)){let e=G_(a.get(V_.open)??``);e.length>0?d=e:i.push(V_.open)}return r.trace={actorIndex:l.actorIndex,toolName:l.name,...u===void 0?{}:{attempt:u},...d?{open:d}:{}},{state:r,dangling:i}}function J_(e,t,n){let r=new URL(e);for(let e of H_)r.searchParams.delete(e);let i=t.trace,a=i?n.getEntryFor(i.actorIndex,i.toolName):void 0;if(i&&a){r.searchParams.set(V_.tool,String(a.n)),i.attempt!==void 0&&i.attempt>=1&&i.attempt<a.attempts.length&&r.searchParams.set(V_.attempt,String(Math.trunc(i.attempt)));let e=O_.filter(e=>i.open?.includes(e));e.length>0&&r.searchParams.set(V_.open,e.join(`,`))}let o=t.toolbox;return o.open&&r.searchParams.set(V_.toolbox,`1`),o.show&&r.searchParams.set(V_.show,o.show),o.find&&r.searchParams.set(V_.find,o.find),o.group&&r.searchParams.set(V_.group,o.group),o.actors&&o.actors.length>0&&r.searchParams.set(V_.actors,o.actors.join(`,`)),r.toString()}function Y_(e,t){let n;try{n=new URL(e)}catch{return e}let r=[[V_.show,t.show&&t.show!==`all`?t.show:null],[V_.find,t.find?t.find:null]];if(t.open!==void 0&&r.push([V_.toolbox,t.open?`1`:null]),t.group!==void 0&&r.push([V_.group,t.group?t.group:null]),t.actors!==void 0){let e=[...new Set(t.actors)].filter(e=>Number.isInteger(e)&&e>=0).sort((e,t)=>e-t).map(e=>e+1);r.push([V_.actors,e.length>0?e.join(`,`):null])}let i=!1;for(let[e,t]of r)n.searchParams.get(e)===t&&n.searchParams.getAll(e).length<=1||(i=!0,t===null?n.searchParams.delete(e):n.searchParams.set(e,t));return i?n.toString():e}function X_(e,t){let n;try{n=new URL(e)}catch{return e}let r=(t??H_).filter(e=>n.searchParams.has(e));if(r.length===0)return e;for(let e of r)n.searchParams.delete(e);return n.toString()}function Z_(e,t,n,r,i){return J_(Ot(e,t,n),{trace:r,toolbox:{open:!1}},i)}function Q_(e){let t;try{t=sh(e)}catch{return`sim`}return t===`about`||t===`quickstart`?`sim`:t}var $_=(0,b.createContext)({openTrace:()=>{},openToolbox:()=>{},close:()=>{},showActorLog:()=>{},current:{trace:null,toolbox:!1}});function ev(){return(0,b.useContext)($_)}var tv=[`all`,`passed`,`did_not_pass`],nv=[`actor`,`department`,`none`],rv=e=>e>2?`actor`:`none`,iv={show:`all`,find:``,group:null,actors:[]},av={...iv,set:()=>{}},ov=(0,b.createContext)(av);function sv(){return(0,b.useContext)(ov)}var cv=[`run`,`tools`,`didNotPass`],lv=/^a(\d+)$/i;function uv(e,t){let n=t.trim();if(n===``)return e;let r=lv.exec(n);if(r){let t=`A${Number.parseInt(r[1],10)}`;return e.filter(e=>e.label===t)}let i=n.toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(i)||e.archetype.toLowerCase().includes(i))}function dv(e,t){let n=(e,t)=>e.index-t.index,r=[...e];return t===`tools`?r.sort((e,t)=>t.counts.tools-e.counts.tools||n(e,t)):t===`didNotPass`?r.sort((e,t)=>t.counts.didNotPass-e.counts.didNotPass||n(e,t)):r.sort(n)}function fv(e,t){return t>0&&e.length===0?`error`:`ready`}function pv(e,t,n){let r=new Set(e);for(let e of t){if(n!==void 0&&r.size>=n)break;r.add(e.index)}return r}function mv(e,t){let n=[...new Set(e)].filter(e=>Number.isInteger(e)&&e>=0&&e<t).sort((e,t)=>e-t);return n.length===0||n.length>=t?null:n}var hv={request:`Request`,code:`Code`,tests:`Tests`,judge:`Judge`,added:`Added`},gv={unknown:`Unknown`,notReached:`Not reached`},_v={reached:`reached`,stopped:`stopped here`,unknown:gv.unknown,notReached:gv.notReached},vv=(e,t)=>`${hv[e]}: ${_v[t]}`,yv=`The forge's stations`,bv={passed:`Passed`,rejected:`Rejected by the judge`,notJudged:`Not judged`,refused:`Refused`,failed:`Failed`,didNotPass:`Did not pass`},xv=e=>`A${e+1}`,Sv=e=>`+${e}`,Cv=(e,t)=>`${e}, forged tool ${t}`,wv=e=>`Forged tool ${e}`,Tv=`Close the trace`,Ev={key:`Copy link to this tool`,copied:`Link copied. Anyone with it can open this tool's trace and replay the run.`,failed:`Could not copy. Select the link and copy it.`,offline:`You are offline`},Dv={toLight:`Switch to light mode`,toDark:`Switch to dark mode`},Ov=`Written by an AI model during this paracosm run`,kv={passed:`Passed. The judge approved it.`,did_not_pass:`Did not pass. The run's record does not say where the forge stopped.`},Av={heading:`The reason the run recorded`,limit:`The run's record keeps at most 240 characters of this reason.`,none:`The record gave no reason.`},jv={code:`The code was not recorded for this run.`,tests:`The tests were not recorded for this run.`},Mv=e=>`Approved · confidence ${e.toFixed(2)} out of 1`,Nv=e=>e===1?`Used 1 time`:`Used ${e} times`,Pv={open:`Open all`,close:`Close all`,openName:`Open all stations`,closeName:`Close all stations`};function Fv(e){return[e.archetype?`${e.label} ${e.name}, ${e.archetype}`:`${e.label} ${e.name}`,e.department,`turn ${e.turn}`,e.eventTitle?`for “${e.eventTitle}”`:``].filter(Boolean).join(` · `)}var Iv=e=>`Go to the event: ${e}`,Lv={whatItDoes:`What it does`,inputFields:`Input fields`,outputFields:`Output fields`,columns:[`Field`,`Type`,`Required`,`Description`],rawJson:`Raw JSON`,noInputFields:`This tool declares no input fields.`,noOutputFields:`This tool declares no output fields.`,notRecorded:`Not recorded`,yes:`Yes`,no:`No`},Rv={heading:`What the judge said`,notice:`A model's review of this code, not a security audit. Check before reuse.`,meterName:`The judge's confidence`,wordsNotRecorded:`The judge's words were not recorded for this run.`},zv=e=>`The judge's confidence: ${e.toFixed(2)} out of 1`,Bv={output:`Output the run recorded`,testNotRecorded:`This forge's test was not recorded.`,notUsed:`Not used after it was forged.`};function Vv(e,t,n){return[`Turn ${e}`,t,n?`“${n}”`:``].filter(Boolean).join(` · `)}var Hv={key:`Record`,rawRecord:`The raw record`,copy:`Copy record`,copied:`Copied`,copyFailed:`Could not copy. Select the record and copy it.`,download:`Download JSON`,downloadFailed:`Could not download. Try again, or use Copy record.`,showInEventLog:`Show in Event Log`,unreadable:`This record could not be shown.`},Uv=e=>`${e}-trace.json`,Wv={previous:`Previous attempt`,next:`Next attempt`},Gv=(e,t)=>`${e} of ${t}`,Kv=(e,t)=>`Attempt ${e} of ${t}`,qv=(e,t)=>`Attempt ${e} · ${t}`,Jv=e=>e.toLocaleString(`en-US`),Yv=(e,t,n)=>`${Jv(e)} ${e===1?t:n}`,Xv=`FORGED TOOLBOX`,Zv=e=>`Forged toolbox, ${Yv(e,`tool`,`tools`)}`,Qv=e=>`Forged toolbox · ${Jv(e)}`,$v=`Close the toolbox`;function ey(e,t){let n=e.reforges>0?` (${Yv(e.reforges,`re-forge`,`re-forges`)})`:``;return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}${n}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``,t>2?`${Jv(t)} actors`:``].filter(Boolean).join(` · `)}var ty={name:`Show`,menuLead:`Show:`,all:`All`,passed:bv.passed,did_not_pass:bv.didNotPass},ny={label:`Find a tool`,placeholder:`Tool name…`,clear:`Clear`,clearName:`Clear the search`},ry={noTools:`No department forged a tool in this run.`,everyToolPassed:`Every tool in this run passed.`},iy=e=>`No tool matches “${e}”.`,ay=`Export JSON`,oy=`paracosm-toolbox.json`;function sy(e){return[e.department,`turn ${e.turn}`,e.uses===null?``:`used ${Yv(e.uses,`time`,`times`)}`,e.reforges>0?Yv(e.reforges,`re-forge`,`re-forges`):``].filter(Boolean).join(` · `)}function cy(e){return e.length>3?`Same name in ${Jv(e.length)} other actors`:`Same name: ${e.join(`, `)}`}function ly(e){let t=`${e.name}, ${e.outcome}, made by ${e.actorLabel} ${e.actorName}`;return e.forges>1?`${t}, forged ${Jv(e.forges)} times`:t}var uy={name:`Group`,actor:`Actor`,department:`Department`,none:`None`},dy=e=>`Group: ${uy[e]}`,fy={open:`Open all groups`,close:`Close all groups`};function py(e){return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var my=`No tools`,hy=e=>`${e}'s tools could not be read.`,gy=e=>`${Jv(e)} tools: the most one actor's registry holds`;function _y(e){let t=[`${e.label} ${e.name}`,e.archetype].filter(Boolean);return e.unreadable?[...t,hy(e.label)].join(`, `):e.tools===0?[...t,my].join(`, `):[...t,Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}function vy(e,t){return[e,Yv(t.tools,`tool`,`tools`),t.didNotPass>0?`${Jv(t.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}var yy=e=>`Exporting ${Jv(e)} tools…`,by=`Could not export. Try again.`,xy={dialogName:`Choose actors`,listName:`Actors`,findLabel:`Find an actor`,findPlaceholder:`Name, archetype or A-number…`,clearSearchName:`Clear the actor search`,sortName:`Sort`,sortLead:`Sort:`,selectShown:`Select shown`,clear:`Clear`,done:`Done`,showAll:`Show all`,waiting:`Waiting to start`,unreadable:`The actors could not be read.`},Sy={run:`Run order`,tools:`Most tools`,didNotPass:`Most forges that did not pass`},Cy=(e,t)=>e===null?`Actors: All ${Jv(t)}`:`Actors: ${Jv(e)} of ${Jv(t)}`,wy=(e,t)=>`Showing ${Jv(e)} of ${Jv(t)} actors`;function Ty(e,t,n){return`${wy(e,t)} · ${ey(n,0)}`}function Ey(e){return e.tools===0?my:[Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var Dy=e=>`No actor matches “${e}”.`,Oy={backdrop:`_backdrop_1mlna_1`,dialog:`_dialog_1mlna_15`,"sheet-up":`_sheet-up_1mlna_1`,header:`_header_1mlna_50`,headerEnd:`_headerEnd_1mlna_62`,key:`_key_1mlna_69`,iconKey:`_iconKey_1mlna_106`,lookGlyph:`_lookGlyph_1mlna_111`,number:`_number_1mlna_116`,linkNote:`_linkNote_1mlna_135`,linkSaid:`_linkSaid_1mlna_144`,linkText:`_linkText_1mlna_151`,name:`_name_1mlna_165`,nameInRow:`_nameInRow_1mlna_184`,head:`_head_1mlna_50`,label:`_label_1mlna_195`,outcome:`_outcome_1mlna_202`,attempts:`_attempts_1mlna_219`,attemptLine:`_attemptLine_1mlna_226`,reason:`_reason_1mlna_234`,reasonHeading:`_reasonHeading_1mlna_242`,reasonText:`_reasonText_1mlna_250`,reasonNote:`_reasonNote_1mlna_263`,line:`_line_1mlna_270`,recordFoot:`_recordFoot_1mlna_274`,recordKey:`_recordKey_1mlna_283`,recordBody:`_recordBody_1mlna_288`,nameInHead:`_nameInHead_1mlna_355`,lineHead:`_lineHead_1mlna_389`};function ky(){let{resolved:e,setTheme:t}=C(),n=e===`dark`?`light`:`dark`,r=n===`light`?Dv.toLight:Dv.toDark;return(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(n),"aria-label":r,title:r,children:(0,x.jsx)(`span`,{className:Oy.lookGlyph,"aria-hidden":`true`,children:e===`dark`?`☀`:`☽`})})}var Ay=m();function jy(e,t=!1){let[n,r]=(0,b.useState)(()=>typeof window>`u`||!window.matchMedia?t:window.matchMedia(e).matches);return(0,b.useEffect)(()=>{if(typeof window>`u`||!window.matchMedia)return;let t=window.matchMedia(e),n=e=>r(e.matches);return t.addEventListener(`change`,n),r(t.matches),()=>t.removeEventListener(`change`,n)},[e]),n}var My=`(max-width: 768px)`,Ny=`(max-width: 480px)`,Py=`(max-width: 899.98px)`,Fy=`(prefers-reduced-motion: reduce)`,Iy={tile:`_tile_1dw5u_1`,band:`_band_1dw5u_17`,label:`_label_1dw5u_26`},Ly={2:28,3:32,4:40};function Ry({index:e,colour:t}){let n=xv(e),r={"--tile-size":`${Ly[n.length]??Ly[4]}px`,"--tile-band":t};return(0,x.jsxs)(`span`,{className:Iy.tile,style:r,"data-actor-tile":n,translate:`no`,children:[(0,x.jsx)(`span`,{className:Iy.band,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:Iy.label,children:n})]})}var zy={strip:`_strip_1uso4_1`,cell:`_cell_1uso4_10`,more:`_more_1uso4_27`},By=20;function Vy({cells:e,max:t=By}){let n=e.slice(0,Math.max(0,t)),r=e.length-n.length;return(0,x.jsxs)(`span`,{className:zy.strip,"aria-hidden":`true`,"data-forge-strip":e.length,children:[n.map((e,t)=>(0,x.jsx)(`span`,{className:zy.cell,"data-cell":e},t)),r>0&&(0,x.jsx)(`span`,{className:zy.more,children:Sv(r)})]})}function Hy({count:e,lineHeights:t,scrollTop:n,viewport:r,overscan:i,keep:a}){if(e<=0)return{first:0,last:-1,padTop:0,padBottom:0};let o=e=>{let n=typeof t==`number`?t:t[e]??0;return Number.isFinite(n)&&n>0?n:0},s=Math.max(0,n),c=s+Math.max(0,r),l=0,u=-1,d=-1;for(let t=0;t<e;t+=1){let e=o(t);if(l>=c&&u>=0)break;u<0&&l+e>s&&(u=t),u>=0&&(d=t),l+=e}u<0&&(u=e-1,d=e-1);let f=Math.max(0,Math.floor(i)),p=Math.max(0,u-f),m=Math.min(e-1,d+f),h=(e,t)=>{let n=0;for(let r=e;r<t;r+=1)n+=o(r);return n};if(a!==void 0&&Number.isInteger(a)&&a>=0&&a<e){if(a>=p-1&&a<=m+1)p=Math.min(p,a),m=Math.max(m,a);else if(a<p)return{first:p,last:m,kept:a,gap:h(a+1,p),padTop:h(0,a),padBottom:h(m+1,e)};else return{first:p,last:m,kept:a,gap:h(m+1,a),padTop:h(0,p),padBottom:h(a+1,e)}}return{first:p,last:m,padTop:h(0,p),padBottom:h(m+1,e)}}var Uy=`button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Wy(e){for(let t=e.parentElement;t&&t!==document.body&&t!==document.documentElement;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight+1)return t}return null}function Gy(e){if(!e)return{top:0,bottom:window.innerHeight,padTop:0};let t=e.getBoundingClientRect().top+e.clientTop,n=Number.parseFloat(getComputedStyle(e).scrollPaddingTop);return{top:t,bottom:t+e.clientHeight,padTop:Number.isFinite(n)?n:0}}function Ky(e){let t=e.getBoundingClientRect(),{top:n,bottom:r}=Gy(Wy(e));return{scrollTop:Math.max(0,n-t.top),viewport:Math.max(0,r-Math.max(n,t.top))}}function qy(e,t,n){let r=e.length>50,i=(0,b.useRef)(new Map),a=(0,b.useRef)(new Map),o=(0,b.useRef)(-1),[s,c]=(0,b.useState)(0),[l,u]=(0,b.useState)(()=>({scrollTop:0,viewport:typeof window>`u`?0:window.innerHeight})),d=(0,b.useMemo)(()=>e.map(e=>{let t=i.current.get(e.key);if(t!==void 0)return t;let n=a.current.get(e.kind);return n&&n.n>0?n.sum/n.n:e.estimate}),[e,s]),f=n!==null&&n>=0&&n<e.length?n:void 0,p=r?Hy({count:e.length,lineHeights:d,scrollTop:l.scrollTop,viewport:l.viewport,overscan:8,keep:f}):{first:0,last:e.length-1,padTop:0,padBottom:0},m=(0,b.useRef)({heights:d,range:p,keep:f,windowed:r});m.current={heights:d,range:p,keep:f,windowed:r};let h=(0,b.useCallback)(()=>{let e=m.current;if(!t||!e.windowed)return;let n=Ky(t),r=Hy({count:e.heights.length,lineHeights:e.heights,scrollTop:n.scrollTop,viewport:n.viewport,overscan:8,keep:e.keep});(r.first!==e.range.first||r.last!==e.range.last||r.kept!==e.range.kept)&&u(n)},[t]);(0,b.useEffect)(()=>{if(!t)return;let e=0,n=()=>{e===0&&(e=window.requestAnimationFrame(()=>{e=0,h()}))};document.addEventListener(`scroll`,n,{capture:!0,passive:!0}),window.addEventListener(`resize`,n);let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(t),n(),()=>{document.removeEventListener(`scroll`,n,{capture:!0}),window.removeEventListener(`resize`,n),r?.disconnect(),e!==0&&window.cancelAnimationFrame(e)}},[t,h]),(0,b.useLayoutEffect)(()=>{if(!t)return;let n=t.clientWidth;n>0&&Math.abs(n-o.current)>1&&(i.current.clear(),a.current.clear(),o.current=n);let r=!1;for(let n of t.querySelectorAll(`[data-line]`)){let t=e[Number(n.dataset.line)];if(!t)continue;let o=n.getBoundingClientRect().height;if(!(o>0))continue;let s=i.current.get(t.key);if(s!==void 0&&Math.abs(s-o)<.5)continue;i.current.set(t.key,o);let c=a.current.get(t.kind)??{sum:0,n:0};s===void 0?(c.sum+=o,c.n+=1):c.sum+=o-s,a.current.set(t.kind,c),r=!0}r?c(e=>e+1):h()});let g=(0,b.useCallback)(e=>{let n=m.current;if(!t||e<0||e>=n.heights.length)return;let r=0;for(let t=0;t<e;t+=1)r+=n.heights[t];let i=Wy(t),{top:a,bottom:o,padTop:s}=Gy(i),c=t.getBoundingClientRect().top+r,l=c+n.heights[e],u=c<a+s?c-(a+s):l>o?l-o:0;u!==0&&(i?i.scrollTop+=u:window.scrollBy(0,u)),h()},[t,h]);return{...p,windowed:r,scrollToLine:g}}function Jy(e,t,n){for(let r=t+n;r>=0&&r<e.length;r+=n)if(e[r].focusable)return r;return-1}function Yy(e,t){return Jy(e,t===1?-1:e.length,t)}function Xy(e,t){let[n,r]=(0,b.useState)(null),[i,a]=(0,b.useState)(null),o=(0,b.useRef)(null),s=(0,b.useRef)(e);s.current=e;let c=(0,b.useRef)(0),l=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(c.current=e.shiftKey?-1:1,window.setTimeout(()=>{c.current=0},0))};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,b.useEffect)(()=>{if(!t)return;let e=e=>{let n=e instanceof Element?e.closest(`[data-line]`):null;return n&&t.contains(n)?Number(n.dataset.line):-1},n=e=>{l.current=0,a(e)},i=i=>{let a=s.current,o=e(i.target),l=a[o];if(!l)return;let u=i.relatedTarget,d=c.current;if(d!==0&&!(u instanceof Node&&t.contains(u))){let e=Yy(a,d);e>=0&&e!==o&&n(a[e].key)}r(e=>e?.key===l.key?e:{key:l.key,headKey:l.headKey})},o=e=>{let n=e.relatedTarget;n instanceof Node&&!t.contains(n)&&(t.closest(`[role="dialog"]`)??t.closest(`[data-toolbox-list]`))?.contains(n)&&r(null)},u=r=>{if(r.key!==`Tab`||r.altKey||r.ctrlKey||r.metaKey)return;let i=s.current,a=e(r.target);if(a<0)return;let o=Jy(i,a,r.shiftKey?-1:1);o<0||t.querySelector(`[data-line="${o}"]`)||(r.preventDefault(),r.stopPropagation(),n(i[o].key))};return t.addEventListener(`focusin`,i),t.addEventListener(`focusout`,o),t.addEventListener(`keydown`,u,!0),()=>{t.removeEventListener(`focusin`,i),t.removeEventListener(`focusout`,o),t.removeEventListener(`keydown`,u,!0)}},[t]),(0,b.useLayoutEffect)(()=>{if(t){if(i!==null){let n=e.findIndex(e=>e.key===i),r=n>=0?t.querySelector(`[data-line="${n}"]`):null;if(r){a(null),(r.matches(Uy)?r:r.querySelector(Uy))?.focus();return}l.current+=1,n<0||l.current>3?a(null):o.current?.(n)}else if(n&&!e.some(e=>e.key===n.key)){let t=document.activeElement;(t===null||t===document.body||!t.isConnected)&&n.headKey&&e.some(e=>e.key===n.headKey)?(l.current=0,a(n.headKey)):r(null)}}});let u=n?.key??null,d=u===null?-1:e.findIndex(e=>e.key===u);return{keep:d>=0?d:null,scrollTo:o}}var K={list:`_list_yqq00_1`,count:`_count_yqq00_15`,keyRows:`_keyRows_yqq00_23`,lead:`_lead_yqq00_30`,key:`_key_yqq00_23`,actorsMenu:`_actorsMenu_yqq00_42`,keys:`_keys_yqq00_48`,segments:`_segments_yqq00_55`,segment:`_segment_yqq00_55`,menu:`_menu_yqq00_106`,menuSelect:`_menuSelect_yqq00_135`,menuMark:`_menuMark_yqq00_158`,find:`_find_yqq00_167`,findLabel:`_findLabel_yqq00_175`,field:`_field_yqq00_183`,input:`_input_yqq00_189`,clear:`_clear_yqq00_218`,groupMenu:`_groupMenu_yqq00_276`,menuKey:`_menuKey_yqq00_282`,menuKeyMark:`_menuKeyMark_yqq00_288`,groupList:`_groupList_yqq00_293`,groupItem:`_groupItem_yqq00_306`,groupCheck:`_groupCheck_yqq00_332`,empty:`_empty_yqq00_342`,emptyWords:`_emptyWords_yqq00_350`,rows:`_rows_yqq00_357`,head:`_head_yqq00_361`,row:`_row_yqq00_357`,openAll:`_openAll_yqq00_376`,stations:`_stations_yqq00_388`,items:`_items_yqq00_411`,item:`_item_yqq00_411`,sideMark:`_sideMark_yqq00_422`,top:`_top_yqq00_456`,name:`_name_yqq00_465`,outcome:`_outcome_yqq00_476`,lineCell:`_lineCell_yqq00_488`,does:`_does_yqq00_495`,metaCell:`_metaCell_yqq00_504`,meta:`_meta_yqq00_504`,same:`_same_yqq00_512`,actor:`_actor_yqq00_42`,groups:`_groups_yqq00_525`,fold:`_fold_yqq00_529`,foldTop:`_foldTop_yqq00_533`,foldHeading:`_foldHeading_yqq00_537`,foldHead:`_foldHead_yqq00_537`,chevron:`_chevron_yqq00_577`,chevronRoom:`_chevronRoom_yqq00_578`,foldTile:`_foldTile_yqq00_590`,foldName:`_foldName_yqq00_596`,foldActor:`_foldActor_yqq00_607`,foldCount:`_foldCount_yqq00_611`,foldNote:`_foldNote_yqq00_612`,foldStrip:`_foldStrip_yqq00_621`,foldHeadDept:`_foldHeadDept_yqq00_630`,foldStill:`_foldStill_yqq00_643`,foldWay:`_foldWay_yqq00_647`,department:`_department_yqq00_651`,deptLine:`_deptLine_yqq00_655`,pageFold:`_pageFold_yqq00_664`,pageFoldSummary:`_pageFoldSummary_yqq00_670`},Zy={picker:`_picker_wqyxx_1`,"picker-up":`_picker-up_wqyxx_1`,top:`_top_wqyxx_32`,find:`_find_wqyxx_39`,sort:`_sort_wqyxx_47`,list:`_list_wqyxx_76`,rows:`_rows_wqyxx_85`,option:`_option_wqyxx_89`,box:`_box_wqyxx_118`,tile:`_tile_wqyxx_135`,who:`_who_wqyxx_141`,name:`_name_wqyxx_150`,dot:`_dot_wqyxx_155`,archetype:`_archetype_wqyxx_156`,second:`_second_wqyxx_161`,counts:`_counts_wqyxx_171`,strip:`_strip_wqyxx_178`,empty:`_empty_wqyxx_183`,emptyWords:`_emptyWords_wqyxx_192`,said:`_said_wqyxx_200`,foot:`_foot_wqyxx_212`,done:`_done_wqyxx_261`},Qy=56,$y=`button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function eb(){return(0,x.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.25`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function tb({actors:e,chosen:t,max:n,tools:r=0,onChange:i,onClose:a,opener:o,where:s=`toolbox`}){let c=(0,b.useId)(),l=(0,b.useRef)(null),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(``),[p,m]=(0,b.useState)(`run`),[h,g]=(0,b.useState)(``),_=jy(`(min-width: 900px)`),v=jy(`(min-width: 1440px)`),y=fv(e,r),S=(0,b.useMemo)(()=>dv(uv(e,d),p),[e,d,p]),C=S.length>0&&S.every(e=>t.has(e.index)),w=n!==void 0&&t.size>=n,T=(0,b.useRef)(!1);(0,b.useEffect)(()=>{T.current||(T.current=!0,B_({name:`forge_actor_picker_open`,where:s}))},[s]),(0,b.useEffect)(()=>{u.current?.focus({preventScroll:!0})},[]);let E=(0,b.useCallback)(()=>{a(),o?.isConnected&&o.focus()},[a,o]);(0,b.useEffect)(()=>{let e=l.current;if(!e)return;let t=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),E();return}if(t.key!==`Tab`||t.altKey||t.ctrlKey||t.metaKey)return;t.stopPropagation();let n=Array.from(e.querySelectorAll($y)).filter(e=>e.tabIndex>=0&&e.offsetParent!==null);if(n.length===0){t.preventDefault();return}let r=n.indexOf(document.activeElement);(t.shiftKey?r<=0:r===-1||r===n.length-1)&&(t.preventDefault(),n[t.shiftKey?n.length-1:0].focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)},[E]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target;l.current?.contains(t)||o?.contains(t)||a()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[a,o]);let[D,O]=(0,b.useState)(null);(0,b.useLayoutEffect)(()=>{if(!_||!o){O(null);return}let e=v?560:480,t=()=>{let t=o.getBoundingClientRect(),n=Math.round(t.bottom+4),r=Math.round(Math.max(8,Math.min(t.left,window.innerWidth-e-8))),i=Math.round(Math.max(240,Math.min(560,window.innerHeight-n-16)));O(e=>e&&e.top===n&&e.left===r&&e.maxHeight===i?e:{top:n,left:r,maxHeight:i})};return t(),document.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t),()=>{document.removeEventListener(`scroll`,t,{capture:!0}),window.removeEventListener(`resize`,t)}},[_,v,o]);let k=(0,b.useCallback)(t=>{i(t);let n=L_(t.size);n&&B_({name:`forge_actor_filter`,actors:n});let r=e.length;g(wy(t.size===0?r:Math.min(t.size,r),r))},[i,e.length]),A=e=>{let n=new Set(t);if(n.has(e))n.delete(e);else if(w)return;else n.add(e);k(n)},j=(0,b.useMemo)(()=>S.map(e=>({key:e.label,kind:`option`,estimate:Qy,focusable:!0})),[S]),[ee,te]=(0,b.useState)(0),[M,N]=(0,b.useState)(!1),[ne,P]=(0,b.useState)(null),re=(0,b.useRef)(null),ie=(0,b.useRef)(!1),F=Math.min(ee,Math.max(0,S.length-1)),I=qy(j,ne,M?F:null),ae=F>=I.first&&F<=I.last||F===I.kept?F:I.first;(0,b.useEffect)(()=>{te(0),re.current&&(re.current.scrollTop=0)},[d,p]),(0,b.useLayoutEffect)(()=>{if(!ie.current||!ne)return;let e=ne.querySelector(`[data-line="${F}"]`);e?(ie.current=!1,e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`})):I.scrollToLine(F)});let oe=e=>{S.length!==0&&(ie.current=!0,te(Math.max(0,Math.min(S.length-1,e))))},se=e=>{switch(e.key){case`ArrowDown`:e.preventDefault(),oe(F+1);break;case`ArrowUp`:e.preventDefault(),oe(F-1);break;case`Home`:e.preventDefault(),oe(0);break;case`End`:e.preventDefault(),oe(S.length-1);break;case` `:case`Enter`:e.preventDefault(),S[F]&&A(S[F].index)}},ce=()=>{f(``),u.current?.focus()},le=()=>{k(new Set),E()},L=[],ue=I.kept!==void 0&&I.kept<I.first;I.kept!==void 0&&ue&&L.push(I.kept);for(let e=I.first;e<=I.last;e+=1)L.push(e);I.kept!==void 0&&!ue&&L.push(I.kept);let de=I.kept===void 0||!I.gap?-1:ue?I.first:I.kept,fe=I.windowed?{paddingTop:I.padTop,paddingBottom:I.padBottom}:void 0,R=_&&D?{top:D.top,left:D.left,maxHeight:D.maxHeight}:void 0,z=e=>{let n=S[e];if(!n)return null;let r=t.has(n.index),i=!r&&w,a=n.unreadable?hy(n.label):n.status===`waiting`?xy.waiting:Ey(n.counts);return(0,x.jsxs)(`div`,{role:`option`,"aria-selected":r,"aria-disabled":i?!0:void 0,"aria-setsize":S.length,"aria-posinset":e+1,"aria-label":_y({label:n.label,name:n.name,archetype:n.archetype,tools:n.counts.tools,didNotPass:n.counts.didNotPass,unreadable:n.unreadable}),tabIndex:e===ae?0:-1,className:Zy.option,"data-actor":n.label,"data-line":e,onClick:()=>{te(e),A(n.index)},onFocus:()=>te(e),children:[(0,x.jsx)(`span`,{className:Zy.box,"data-checked":r,"aria-hidden":`true`,children:r&&(0,x.jsx)(eb,{})}),(0,x.jsx)(`span`,{className:Zy.tile,children:(0,x.jsx)(Ry,{index:n.index,colour:Pe(n.index)})}),(0,x.jsxs)(`span`,{className:Zy.who,translate:`no`,children:[(0,x.jsx)(`span`,{className:Zy.name,"data-picker-name":!0,children:n.name}),n.archetype&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Zy.dot,"aria-hidden":`true`,children:` · `}),(0,x.jsx)(`span`,{className:Zy.archetype,"data-picker-archetype":!0,children:n.archetype})]})]}),(0,x.jsxs)(`span`,{className:Zy.second,children:[(0,x.jsx)(`span`,{className:Zy.counts,"data-picker-counts":!0,children:a}),!n.unreadable&&(0,x.jsx)(`span`,{className:Zy.strip,children:(0,x.jsx)(Vy,{cells:n.strip,max:v?20:10})})]})]},n.label)},pe=(0,x.jsx)(`div`,{ref:l,role:`dialog`,"aria-label":xy.dialogName,className:Zy.picker,style:R,"data-actor-picker":!0,children:y===`error`?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-error":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:xy.unreadable}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:le,children:xy.showAll})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Zy.top,children:[(0,x.jsxs)(`div`,{className:Zy.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:c,children:xy.findLabel}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:c,ref:u,className:K.input,type:`search`,placeholder:xy.findPlaceholder,value:d,onChange:e=>f(e.target.value),spellCheck:!1,autoComplete:`off`}),d!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":xy.clearSearchName,title:xy.clearSearchName,onClick:ce,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]}),(0,x.jsxs)(`label`,{className:Zy.sort,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:xy.sortLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":xy.sortName,value:p,onChange:e=>m(e.target.value),children:cv.map(e=>(0,x.jsx)(`option`,{value:e,children:Sy[e]},e))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})]}),S.length===0?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-empty":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:Dy(d.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:ce,children:xy.clear})]}):(0,x.jsx)(`div`,{ref:re,role:`listbox`,"aria-multiselectable":`true`,"aria-label":xy.listName,className:Zy.list,onKeyDown:se,onFocus:()=>N(!0),onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||N(!1)},children:(0,x.jsx)(`div`,{ref:P,className:Zy.rows,style:fe,"data-windowed":I.windowed,children:L.flatMap(e=>[e===de?(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:{height:I.gap}},`gap`):null,z(e)])})}),(0,x.jsx)(`p`,{className:Zy.said,role:`status`,children:h}),(0,x.jsxs)(`div`,{className:Zy.foot,"data-picker-foot":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:K.key,"aria-disabled":C||w||S.length===0?!0:void 0,onClick:()=>{C||w||S.length===0||k(pv(t,S,n))},children:xy.selectShown}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:()=>k(new Set),children:xy.clear}),(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${Zy.done}`,onClick:E,children:xy.done})]})]})}),me=o?.closest(`[role="dialog"]`)??(typeof document>`u`?null:document.body);return me?(0,Ay.createPortal)(pe,me):pe}var nb=e=>e.kind===`actor`?`actor:${e.actor.label}`:`department:${e.name}`,rb=e=>e.kind===`department`||!e.actor.unreadable&&e.actor.counts.tools>0;function ib(){let e=jy(`(min-width: 1440px)`),t=jy(`(min-width: 900px)`);return e?50:t?30:1/0}function ab(){return(0,x.jsx)(`svg`,{className:K.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function ob({head:e,open:t,onToggle:n,onShowInEventLog:r}){let i=(0,b.useId)(),a=ib();if(e.kind===`department`)return(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":e.name,children:(0,x.jsxs)(`button`,{type:`button`,className:`${K.foldHead} ${K.foldHeadDept}`,"aria-expanded":t,"aria-label":vy(e.name,e.counts),onClick:n,children:[(0,x.jsx)(ab,{}),(0,x.jsx)(`span`,{className:K.foldName,"data-fold-name":!0,"data-text":`heading`,children:e.name}),(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:py(e.counts)})]})});let{actor:o}=e,s=!o.unreadable&&o.counts.tools>=50,c=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.foldTile,children:(0,x.jsx)(Ry,{index:o.index,colour:Pe(o.index)})}),(0,x.jsxs)(`span`,{className:K.foldName,"data-fold-name":!0,translate:`no`,"data-text":`heading`,children:[(0,x.jsx)(`span`,{className:K.foldActor,children:o.name}),o.archetype?` · ${o.archetype}`:``]}),o.unreadable?(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-error":!0,children:hy(o.label)}):(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:o.counts.tools===0?my:py(o.counts)}),s&&(0,x.jsx)(`span`,{id:i,className:K.foldNote,"data-fold-note":!0,children:gy(50)}),!o.unreadable&&(0,x.jsx)(`span`,{className:K.foldStrip,children:(0,x.jsx)(Vy,{cells:o.strip,max:a})})]}),l=_y({label:o.label,name:o.name,archetype:o.archetype,tools:o.counts.tools,didNotPass:o.counts.didNotPass,unreadable:o.unreadable});return rb(e)?(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`button`,{type:`button`,className:K.foldHead,"aria-expanded":t,"aria-label":l,"aria-describedby":s?i:void 0,onClick:n,children:[(0,x.jsx)(ab,{}),c]})}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`span`,{className:`${K.foldHead} ${K.foldStill}`,children:[(0,x.jsx)(`span`,{className:K.chevronRoom,"aria-hidden":`true`}),c]})}),o.unreadable&&r&&(0,x.jsx)(`div`,{className:K.foldWay,children:(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:r,children:Hv.showInEventLog})})]})}var sb={glyph:`_glyph_bhdp0_1`,passed:`_passed_bhdp0_8`,rejected:`_rejected_bhdp0_12`,refused:`_refused_bhdp0_13`,failed:`_failed_bhdp0_14`,notJudged:`_notJudged_bhdp0_18`,didNotPass:`_didNotPass_bhdp0_22`};function cb(e,t,n){let r={fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`},i=(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r});switch(e){case`passed`:return(0,x.jsx)(`path`,{fill:`currentColor`,fillRule:`evenodd`,d:`M1 10a9 9 0 1 0 18 0a9 9 0 1 0 -18 0Z M4.75 11.05L8.63 14.93L15.28 7.82L13.52 6.18L8.57 11.47L6.45 9.35Z`});case`rejected`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M6.9 6.9L13.1 13.1M13.1 6.9L6.9 13.1`,...r})]});case`refused`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M4.2 15.8L15.8 4.2`,...r})]});case`failed`:return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 2.2L18.2 16.8H1.8Z`,...r}),(0,x.jsx)(`path`,{d:`M10 7.4V12.2`,...r})]});case`notJudged`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M7.7 7.9a2.4 2.4 0 1 1 3.5 2.1c-.8.4-1.2.9-1.2 1.7v.4`,...r}),(0,x.jsx)(`circle`,{cx:`10`,cy:`14.5`,r:`1.1`,fill:`currentColor`})]});case`didNotPass`:return(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r,strokeLinecap:`butt`,strokeDasharray:n})}}function lb({kind:e,size:t}){let n=t===10?3:1.75,r=t===10?`5 4`:`2.6 2.1`;return(0,x.jsx)(`svg`,{className:`${sb.glyph} ${sb[e]}`,"data-glyph":e,width:t,height:t,viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:cb(e,n,r)})}var ub={cell:`_cell_1xygk_1`,trace:`_trace_1xygk_22`,station:`_station_1xygk_35`,stationKey:`_stationKey_1xygk_58`,mark:`_mark_1xygk_83`,name:`_name_1xygk_91`,result:`_result_1xygk_119`,evidence:`_evidence_1xygk_120`,fork:`_fork_1xygk_144`,forkLink:`_forkLink_1xygk_167`,forkWords:`_forkWords_1xygk_200`,chevron:`_chevron_1xygk_205`,row:`_row_1xygk_267`,spur:`_spur_1xygk_275`,rowStation:`_rowStation_1xygk_279`,segment:`_segment_1xygk_290`},db=e=>e===`reached`||e===`stopped`,fb=e=>e===void 0?void 0:db(e)?`solid`:`dashed`;function pb({model:e,station:t,size:n}){let r=e.stations[t];if(r===`stopped`){let r=e.stop;return(0,x.jsx)(lb,{kind:r&&r.station===t?r.glyph:`didNotPass`,size:n})}return(0,x.jsx)(`span`,{className:ub.cell,"data-cell":r})}function mb({mark:e,onAttempt:t,href:n}){let r=k_(e.outcome);return(0,x.jsx)(`div`,{className:ub.fork,"data-fork":e.attempt,children:(0,x.jsxs)(`a`,{className:ub.forkLink,href:n,"data-fork-attempt":e.attempt,onClick:n=>{n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||(n.preventDefault(),t?.(e.attempt))},children:[(0,x.jsx)(lb,{kind:r,size:20}),(0,x.jsx)(`span`,{className:ub.forkWords,children:qv(e.attempt,bv[r])}),(0,x.jsx)(`svg`,{className:ub.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})})}function hb(e){return e===`notReached`?gv.notReached:e===`unknown`?gv.unknown:null}function gb({model:e,size:t,colour:n,open:r,onToggle:i,stationResult:a,renderEvidence:o,onAttempt:s,attemptHref:c}){let l=(0,b.useId)(),u={"--line":n};return t===`row`?(0,x.jsx)(`span`,{className:ub.row,style:u,"aria-hidden":`true`,"data-forge-line":`row`,children:O_.map((t,n)=>{let r=e.spurs.filter(e=>e.station===t);return(0,x.jsxs)(b.Fragment,{children:[n>0&&(0,x.jsx)(`span`,{className:ub.segment,"data-rail":fb(e.stations[t])}),(0,x.jsxs)(`span`,{className:ub.rowStation,"data-station":t,"data-state":e.stations[t],children:[(0,x.jsx)(pb,{model:e,station:t,size:10}),r.length>0&&(0,x.jsx)(`span`,{className:ub.spur,"data-spurs":r.length,children:r.map(e=>(0,x.jsx)(lb,{kind:k_(e.outcome),size:10},e.attempt))})]})]},t)})}):(0,x.jsx)(`ol`,{className:ub.trace,style:u,role:`list`,"aria-label":yv,"data-forge-line":`trace`,children:O_.map((t,n)=>{let u=e.stations[t],d=o?.(t),f=d!=null&&d!==!1,p=db(u)&&f,m=p&&!!r?.has(t),h=a?.(t)??hb(u),g=`${l}-${t}-result`,_=`${l}-${t}-evidence`,v=`${l}-${t}-name`,y=u===`notReached`||u===`unknown`,b=[...e.spurs.filter(e=>e.station===t),...e.branch&&e.branch.station===t?[e.branch]:[]];return(0,x.jsxs)(`li`,{className:ub.station,"data-station":t,"data-state":u,"data-open":m||void 0,"data-rail":fb(e.stations[O_[n+1]]),children:[(0,x.jsxs)(`button`,{type:`button`,className:ub.stationKey,"aria-label":vv(t,u),"aria-expanded":p?m:void 0,"aria-controls":p?_:void 0,"aria-disabled":!p||void 0,"aria-describedby":!p&&h!=null?g:void 0,tabIndex:p?void 0:-1,onClick:p?()=>i?.(t):void 0,children:[(0,x.jsx)(`span`,{className:ub.mark,"aria-hidden":`true`,children:(0,x.jsx)(pb,{model:e,station:t,size:20})}),(0,x.jsx)(`span`,{id:v,className:ub.name,"data-text":`heading`,children:hv[t]})]}),!m&&h!=null&&(0,x.jsx)(`div`,{id:g,className:ub.result,"data-quiet":y||void 0,"data-text":y?void 0:`body`,children:h}),p&&(0,x.jsx)(`div`,{id:_,className:ub.evidence,role:`region`,"aria-labelledby":v,hidden:!m,children:m?d:null}),b.map(e=>(0,x.jsx)(mb,{mark:e,onAttempt:s,href:c?c(e.attempt):`#`},e.attempt))]},t)})})}function _b(e){let t=e.split(`_`);return t.map((e,n)=>(0,x.jsxs)(b.Fragment,{children:[n<t.length-1?`${e}_`:e,n<t.length-1&&(0,x.jsx)(`wbr`,{})]},n))}function vb({entry:e,actorCount:t,onOpen:n,line:r,setSize:i,posInSet:a}){let o=(0,b.useId)(),s=xv(e.actorIndex),c=k_(e.outcome),l=bv[c],u=e.attempts.length,d=e.description!==``&&e.description!==e.name,f=e.sameNameActors.map(xv),p={"--actor":Pe(e.actorIndex)};return(0,x.jsxs)(`li`,{className:K.item,style:p,"data-tool-row":e.n,"data-tool-name":e.name,"data-actor":s,"data-outcome":e.outcome,"data-line":r,"aria-setsize":i,"aria-posinset":a,children:[(0,x.jsx)(`span`,{className:K.sideMark,"data-side-mark":!0,"aria-hidden":`true`}),(0,x.jsxs)(`button`,{type:`button`,className:K.row,"aria-label":ly({name:e.name,outcome:l,actorLabel:s,actorName:e.actorName,forges:u}),"aria-describedby":d?`${o}-does ${o}-meta`:`${o}-meta`,onClick:e=>n(e.currentTarget),children:[(0,x.jsxs)(`span`,{className:K.top,children:[(0,x.jsxs)(`span`,{className:K.name,"data-row-name":!0,"data-text":`heading`,children:[(0,x.jsxs)(`span`,{children:[`[`,e.n,`]`]}),` `,(0,x.jsx)(`span`,{translate:`no`,children:_b(e.name)})]}),(0,x.jsxs)(`span`,{className:K.outcome,"data-row-outcome":!0,children:[(0,x.jsx)(lb,{kind:c,size:20}),(0,x.jsx)(`span`,{children:l})]})]}),(0,x.jsx)(`span`,{className:K.lineCell,children:(0,x.jsx)(gb,{model:N_(e,NaN),size:`row`,colour:P_(e.actorIndex,t)})}),d&&(0,x.jsx)(`span`,{id:`${o}-does`,className:K.does,"data-row-does":!0,"data-text":`body`,children:e.description}),(0,x.jsxs)(`span`,{id:`${o}-meta`,className:K.metaCell,children:[(0,x.jsxs)(`span`,{className:K.meta,"data-row-meta":!0,children:[(0,x.jsx)(`span`,{className:K.actor,"data-row-actor":!0,children:`${s} ${e.actorName}`}),` · ${sy({department:e.firstForgedDepartment,turn:e.firstForgedTurn,uses:e.outcome===`passed`?F_(e):null,reforges:Math.max(0,u-1)})}`]}),f.length>0&&(0,x.jsx)(`span`,{className:K.same,"data-row-same":!0,children:cy(f)})]})]})]})}function yb(e,t,n,r=null){let i=n.trim().toLowerCase(),a=r===null?null:new Set(r);return t===`all`&&i===``&&a===null?e:e.filter(e=>(a===null||a.has(e.actorIndex))&&(t===`all`||e.outcome===t)&&(i===``||e.name.toLowerCase().includes(i)))}function bb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e)t.tools+=n.counts.tools,t.forges+=n.counts.forges,t.reforges+=n.counts.reforges,t.passed+=n.counts.passed,t.didNotPass+=n.counts.didNotPass;return t}var xb=e=>e.firstForgedDepartment||gv.unknown;function Sb(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return[...n]}function Cb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e){let e=n.attempts.filter(e=>e.approved).length;t.tools+=1,t.forges+=n.attempts.length,t.reforges+=Math.max(0,n.attempts.length-1),t.passed+=e,t.didNotPass+=n.attempts.length-e}return t}function wb(e,t,n){return t===`none`?[{head:null,rows:e}]:t===`department`?Sb(e,xb).map(([e,t])=>({head:{kind:`department`,name:e,counts:Cb(t)},rows:t})):n.map(t=>{let n=e.filter(e=>e.actorIndex===t.index);return{head:{kind:`actor`,actor:t},rows:Sb(n,xb).flatMap(([,e])=>e)}})}var Tb={head:64,dept:40,row:112},Eb=e=>`${e.actorIndex}:${e.name}`,Db=e=>e.kind===`head`?null:e.dept;function Ob(e,t,n,r){let i=[];if(e===`none`)return t.forEach((e,t)=>{i.push({kind:`row`,key:Eb(e),estimate:Tb.row,focusable:!0,fold:-1,dept:null,entry:e,pos:t+1})}),{lines:i,rowCount:t.length};let a=0;return n.forEach((e,t)=>{let n=e.head;if(n===null)return;let o=nb(n),s=rb(n)&&e.rows.length>0&&r(o),c=rb(n)||n.kind===`actor`&&n.actor.unreadable;i.push({kind:`head`,key:o,estimate:Tb.head,focusable:c,fold:t});let l=n.kind===`actor`?Sb(e.rows,xb):[[null,e.rows]];for(let[e,n]of l){s&&e!==null&&i.push({kind:`dept`,key:`${o}|dept:${e}`,estimate:Tb.dept,focusable:!1,headKey:o,fold:t,dept:e});for(let r of n)a+=1,s&&i.push({kind:`row`,key:`${o}|${Eb(r)}`,estimate:Tb.row,focusable:!0,headKey:o,fold:t,dept:e,entry:r,pos:a})}}),{lines:i,rowCount:a}}var kb=8,Ab=new Set,jb=[];function Mb({value:e,onChoose:t}){let[n,r]=(0,b.useState)(!1),i=(0,b.useId)(),a=(0,b.useRef)(null),o=(0,b.useRef)(null),s=(0,b.useRef)([]);(0,b.useEffect)(()=>{n&&s.current[nv.indexOf(e)]?.focus()},[n,e]),(0,b.useEffect)(()=>{if(!n)return;let e=e=>{a.current?.contains(e.target)||r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]);let c=()=>{r(!1),o.current?.focus()},l=e=>{t(e),c()},u=e=>s.current[(e+nv.length)%nv.length]?.focus();return(0,x.jsxs)(`div`,{ref:a,className:K.groupMenu,children:[(0,x.jsxs)(`button`,{ref:o,type:`button`,className:`${K.key} ${K.menuKey}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>r(e=>!e),onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),r(!0))},children:[(0,x.jsx)(`span`,{children:dy(e)}),(0,x.jsx)(`svg`,{className:K.menuKeyMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),n&&(0,x.jsx)(`div`,{id:i,role:`menu`,"aria-label":uy.name,className:K.groupList,onKeyDown:e=>{let t=s.current.findIndex(e=>e===document.activeElement);switch(e.key){case`ArrowDown`:e.preventDefault(),u(t+1);break;case`ArrowUp`:e.preventDefault(),u(t-1);break;case`Home`:e.preventDefault(),u(0);break;case`End`:e.preventDefault(),u(nv.length-1);break;case`Enter`:case` `:e.preventDefault(),t>=0&&l(nv[t]);break;case`Escape`:e.preventDefault(),c();break;case`Tab`:c()}},children:nv.map((t,n)=>(0,x.jsxs)(`div`,{ref:e=>{s.current[n]=e},role:`menuitemradio`,"aria-checked":t===e,tabIndex:-1,className:K.groupItem,onClick:()=>l(t),children:[(0,x.jsx)(`svg`,{className:K.groupCheck,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,x.jsx)(`span`,{children:uy[t]})]},t))})]})}function Nb({inPage:e=!1}){let t=D_(),{show:n,find:r,group:i,actors:a,set:o}=sv(),{openTrace:s,showActorLog:c}=ev(),l=(0,b.useId)(),u=(0,b.useId)(),d=(0,b.useRef)(null),f=(0,b.useRef)(null),p=(0,b.useRef)(null),[m,h]=(0,b.useState)(!1),g=t.actors.length,_=(0,b.useMemo)(()=>mv(a,g),[a,g]),v=(0,b.useMemo)(()=>_===null?t.actors:_.map(e=>t.actors[e]),[_,t.actors]),y=(0,b.useMemo)(()=>new Set(a.filter(e=>e<g)),[a,g]),S=(0,b.useMemo)(()=>yb(t.list,`all`,``,_),[t.list,_]),C=(0,b.useMemo)(()=>yb(S,n,r),[S,n,r]),w=i??rv(g),T=n!==`all`||r.trim()!==``,E=(0,b.useMemo)(()=>{let e=S.filter(e=>e.outcome===`passed`).length;return[{id:`all`,count:S.length},{id:`passed`,count:e},{id:`did_not_pass`,count:S.length-e}].filter(e=>e.id===`all`||e.count>0||e.id===n)},[S,n]),D=(0,b.useMemo)(()=>{let e=wb(C,w,v);return T?e.filter(e=>e.head===null||e.rows.length>0||e.head.kind===`actor`&&e.head.actor.unreadable):e},[C,w,v,T]),O=_===null?ey(t.counts,g):Ty(_.length,g,bb(v)),k=(0,b.useCallback)(e=>{o({actors:[...e].sort((e,t)=>e-t)})},[o]),A=(0,b.useCallback)(()=>h(!1),[]),[j,ee]=(0,b.useState)({group:w,all:null,toggled:Ab}),te=(0,b.useMemo)(()=>j.group===w?j:{group:w,all:null,toggled:Ab},[j,w]),M=g<=kb,N=(0,b.useCallback)(e=>(te.all??M)!==te.toggled.has(e),[te,M]),ne=D.filter(e=>e.head!==null&&rb(e.head)&&e.rows.length>0),P=ne.length>0&&ne.every(e=>N(nb(e.head))),re=w===`none`||ne.length===0,ie=e=>{B_({name:`forge_group_toggle`,scope:`one`}),ee(t=>{let n=t.group===w?t:{group:w,all:null,toggled:Ab},r=new Set(n.toggled);return r.has(e)?r.delete(e):r.add(e),{...n,toggled:r}})},F=()=>{B_({name:`forge_group_toggle`,scope:`all`}),ee({group:w,all:!P,toggled:Ab})},I=e=>{e!==w&&B_({name:`forge_toolbox_group`,group:e}),o({group:e===rv(g)?null:e})},ae=e=>{e!==n&&B_({name:`forge_toolbox_filter`,show:e}),o({show:e})},oe=(0,b.useCallback)((e,t)=>{s({actorIndex:e.actorIndex,toolName:e.name},t,`toolbox`)},[s]),{lines:se,rowCount:ce}=(0,b.useMemo)(()=>Ob(w,C,D,N),[w,C,D,N]),[le,L]=(0,b.useState)(null),ue=Xy(se,le),de=qy(se,le,ue.keep);ue.scrollTo.current=de.scrollToLine;let fe=()=>{o({find:``}),f.current?.focus()},R=()=>{ae(`all`);let e=d.current?.querySelectorAll(`input[type="radio"][value="all"], select`);Array.from(e??[]).find(e=>e.offsetParent!==null)?.focus()},z=e=>`${ty[e.id]} ${Jv(e.count)}`,pe=e=>{let t=se[e];return t.kind===`row`?(0,x.jsx)(vb,{entry:t.entry,actorCount:g,onOpen:e=>oe(t.entry,e),line:e,setSize:ce,posInSet:t.pos},Eb(t.entry)):null},me=[],he=de.kept!==void 0&&de.kept<de.first;de.kept!==void 0&&he&&me.push(de.kept);for(let e=de.first;e<=de.last;e+=1)me.push(e);de.kept!==void 0&&!he&&me.push(de.kept);let ge=de.kept===void 0||!de.gap?-1:he?de.first:de.kept,_e=(e,t)=>{if(e!==ge)return null;let n={height:de.gap};return t?(0,x.jsx)(`li`,{role:`presentation`,"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`):(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`)},B=e=>e.flatMap(e=>[_e(e,!0),pe(e)]),ve=de.windowed?{paddingTop:de.padTop,paddingBottom:de.padBottom}:void 0,ye=[];for(let e of me){let t=ye[ye.length-1];t&&t.fold===se[e].fold?t.at.push(e):ye.push({fold:se[e].fold,at:[e]})}let be=e=>{let t=[];for(let n of e){let e=Db(se[n])??``,r=t[t.length-1];r&&r.dept===e?r.at.push(n):t.push({dept:e,at:[n]})}return t};return(0,x.jsxs)(`div`,{className:K.list,"data-toolbox-list":e?`page`:`dialog`,children:[(0,x.jsx)(`p`,{className:K.count,"data-toolbox-count":!0,children:O}),t.list.length===0?(0,x.jsxs)(`div`,{className:K.empty,"data-toolbox-empty":`no-tools`,children:[(0,x.jsx)(Vy,{cells:jb}),(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.noTools})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:K.keyRows,children:[(0,x.jsxs)(`div`,{className:K.lead,"data-toolbox-lead":!0,children:[(0,x.jsx)(Mb,{value:w,onChoose:I}),(0,x.jsxs)(`div`,{className:K.actorsMenu,children:[(0,x.jsx)(`button`,{ref:p,type:`button`,className:K.key,"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>h(e=>!e),children:Cy(_===null?null:_.length,g)}),m&&(0,x.jsx)(tb,{actors:t.actors,tools:t.list.length,chosen:y,onChange:k,onClose:A,opener:p.current})]})]}),(0,x.jsxs)(`div`,{ref:d,className:K.keys,"data-toolbox-keys":!0,children:[(0,x.jsx)(`div`,{className:K.segments,role:`radiogroup`,"aria-label":ty.name,children:E.map(e=>(0,x.jsxs)(`label`,{className:K.segment,"data-show":e.id,children:[(0,x.jsx)(`input`,{type:`radio`,name:u,value:e.id,checked:n===e.id,onChange:()=>ae(e.id)}),(0,x.jsx)(`span`,{children:z(e)})]},e.id))}),(0,x.jsxs)(`label`,{className:K.menu,"data-toolbox-menu":!0,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:ty.menuLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":ty.name,value:n,onChange:e=>ae(e.target.value),children:E.map(e=>(0,x.jsx)(`option`,{value:e.id,children:z(e)},e.id))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,x.jsxs)(`div`,{className:K.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:l,children:ny.label}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:l,ref:f,className:K.input,type:`search`,placeholder:ny.placeholder,value:r,onChange:e=>o({find:e.target.value}),spellCheck:!1,autoComplete:`off`}),r!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":ny.clearName,title:ny.clearName,onClick:fe,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]})]})]}),C.length===0&&T?(0,x.jsx)(`div`,{className:K.empty,"data-toolbox-empty":r.trim()===``?`no-rows`:`no-match`,children:r.trim()===``?(0,x.jsxs)(x.Fragment,{children:[n===`did_not_pass`&&_===null&&(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.everyToolPassed}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:R,children:ty.all})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:iy(r.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:fe,children:ny.clear})]})}):(0,x.jsxs)(`div`,{className:K.rows,children:[(0,x.jsxs)(`div`,{className:K.head,children:[(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${K.openAll}`,"aria-disabled":re?!0:void 0,tabIndex:re?-1:void 0,onClick:re?void 0:F,children:P?fy.close:fy.open}),(0,x.jsx)(`span`,{className:K.stations,"data-toolbox-stations":!0,"aria-hidden":`true`,children:O_.map(e=>(0,x.jsx)(`span`,{children:hv[e]},e))})]}),w===`none`?(0,x.jsx)(`ol`,{ref:L,className:K.items,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:B(me)}):(0,x.jsx)(`div`,{ref:L,role:`list`,className:K.groups,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:ye.map(({fold:e,at:t})=>{let n=D[e],r=n?.head??null;if(r===null)return null;let i=nb(r),a=rb(r)&&n.rows.length>0&&N(i),o=t.find(e=>se[e].kind===`head`),s=t.filter(e=>se[e].kind!==`head`);return(0,x.jsxs)(`div`,{role:`listitem`,"aria-setsize":D.length,"aria-posinset":e+1,className:K.fold,"data-fold":r.kind===`actor`?r.actor.label:r.name,children:[o!==void 0&&_e(o,!1),o!==void 0&&(0,x.jsx)(`div`,{className:K.foldTop,"data-line":o,children:(0,x.jsx)(ob,{head:r,open:a,onToggle:()=>ie(i),onShowInEventLog:r.kind===`actor`&&r.actor.unreadable?()=>c(r.actor.index):void 0})}),r.kind===`actor`?be(s).map(({dept:e,at:t})=>{let n=t.find(e=>se[e].kind===`dept`),r=t.filter(e=>se[e].kind===`row`);return(0,x.jsxs)(`div`,{className:K.department,children:[n!==void 0&&_e(n,!1),n!==void 0&&(0,x.jsx)(`h4`,{className:K.deptLine,"data-dept-line":!0,"data-line":n,children:e}),r.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(r)})]},e)}):s.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(s)})]},i)})})]})]})]})}var Pb={dialog:`_dialog_x8cpw_1`,"sheet-up":`_sheet-up_x8cpw_1`,header:`_header_x8cpw_36`,headerEnd:`_headerEnd_x8cpw_48`,title:`_title_x8cpw_55`,exportInHeader:`_exportInHeader_x8cpw_73`,exportStatus:`_exportStatus_x8cpw_77`,footStatus:`_footStatus_x8cpw_95`,body:`_body_x8cpw_106`,foot:`_foot_x8cpw_95`,exportAtFoot:`_exportAtFoot_x8cpw_114`};function Fb(e){return e.map(e=>({n:e.n,name:e.name,description:e.description,mode:e.mode,firstForgedTurn:e.firstForgedTurn,firstForgedDepartment:e.firstForgedDepartment,departments:[...e.departments],reuseCount:e.reuseCount,approved:e.approved,confidence:e.confidence,inputSchema:e.inputSchema,outputSchema:e.outputSchema,sampleOutput:e.sampleOutput,inputFields:e.inputFields,outputFields:e.outputFields,actor:xv(e.actorIndex),actorName:e.actorName}))}function Ib(e){let t=new Blob([JSON.stringify(Fb(e),null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=oy,r.click(),URL.revokeObjectURL(n)}var Lb=500;function Rb({covered:e,onClose:t}){let n=D_(),{show:r,find:i,actors:a}=sv(),o=Pt(!0),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{s.current?.focus()},[]);let c=(0,b.useRef)(e);c.current=e,(0,b.useEffect)(()=>{let e=e=>{e.key!==`Escape`||e.defaultPrevented||c.current||(e.preventDefault(),t())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t]);let[l,u]=(0,b.useState)({state:`idle`}),d=()=>{B_({name:`forge_record_export`,what:`toolbox`});let e=yb(n.list,r,i,mv(a,n.actors.length)),t=()=>{try{Ib(e),u({state:`idle`})}catch{u({state:`failed`})}};e.length<=Lb?t():(u({state:`exporting`,tools:e.length}),requestAnimationFrame(()=>{window.setTimeout(t,0)}))},f=l.state===`exporting`?yy(l.tools):l.state===`failed`?by:``;return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,x.jsxs)(`div`,{ref:o,role:`dialog`,"aria-modal":`true`,"aria-label":Zv(n.list.length),tabIndex:-1,className:Pb.dialog,inert:e,children:[(0,x.jsxs)(`div`,{className:Pb.header,"data-toolbox-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(),"aria-label":$v,title:$v,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(`h2`,{ref:s,className:Pb.title,tabIndex:-1,"data-toolbox-title":!0,"data-text":`heading`,children:Xv}),(0,x.jsxs)(`span`,{className:Pb.headerEnd,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportInHeader}`,onClick:d,children:ay}),(0,x.jsx)(ky,{})]}),(0,x.jsx)(`span`,{className:Pb.exportStatus,role:`status`,"data-export-status":!0,children:f})]}),(0,x.jsx)(`div`,{className:Pb.body,children:(0,x.jsx)(Nb,{})}),(0,x.jsxs)(`div`,{className:Pb.foot,children:[(0,x.jsx)(`p`,{className:Pb.footStatus,role:`status`,"data-export-status":!0,children:f}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportAtFoot}`,onClick:d,children:ay})]})]})})}var zb=`paracosm:forgeOpenStations`,Bb=20,Vb=e=>typeof e==`string`&&O_.includes(e);function Hb(e){let t=new Map,n;try{n=e.getItem(zb)}catch{return t}if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}if(!r||typeof r!=`object`||Array.isArray(r))return t;for(let[e,n]of Object.entries(r))Array.isArray(n)&&t.set(e,O_.filter(e=>n.some(t=>Vb(t)&&t===e)));return t}function Ub(e,t){return Hb(e).get(t)??[]}function Wb(e,t,n){let r=Hb(e);r.delete(t),r.set(t,O_.filter(e=>n.includes(e)));let i=[...r.keys()];for(let e of i.slice(0,Math.max(0,i.length-Bb)))r.delete(e);try{e.setItem(zb,JSON.stringify(Object.fromEntries(r)))}catch{}}function Gb(e,t,n){let r=new Set([e.deciding]);for(let e of t)n(e)&&r.add(e);return r}function Kb(e){return t=>t===`request`||e&&(t===`judge`||t===`added`)}function qb(e,t){let n=null;try{n=new URL(e).searchParams.get(`replay`)}catch{}return n||t||`live`}var Jb={open:`_open_o8eqn_1`,part:`_part_o8eqn_11`,heading:`_heading_o8eqn_18`,body:`_body_o8eqn_26`,meta:`_meta_o8eqn_34`,quiet:`_quiet_o8eqn_42`,code:`_code_o8eqn_49`,actor:`_actor_o8eqn_62`,rule:`_rule_o8eqn_68`,actorText:`_actorText_o8eqn_74`,link:`_link_o8eqn_81`,fieldsBar:`_fieldsBar_o8eqn_105`,switch:`_switch_o8eqn_110`,switchTrack:`_switchTrack_o8eqn_139`,caption:`_caption_o8eqn_167`,fields:`_fields_o8eqn_105`,confidence:`_confidence_o8eqn_247`,meter:`_meter_o8eqn_258`,meterFill:`_meterFill_o8eqn_267`,uses:`_uses_o8eqn_275`,use:`_use_o8eqn_275`,recordKeys:`_recordKeys_o8eqn_295`,recordSaid:`_recordSaid_o8eqn_307`,record:`_record_o8eqn_295`};function Yb(e,t){let n=t.trim(),r=e=>String(e??``).trim()===n,i=[];for(let t of e){let e=t.data??{},n=t.type===`forge_attempt`&&r(e.name),a=t.type===`specialist_done`&&Array.isArray(e.forgedTools)&&e.forgedTools.some(e=>!!e&&typeof e==`object`&&r(e.name));if(!n&&!a)continue;let o={...e};delete o._filteredTools,i.push(o)}return i}function Xb(e){try{return JSON.stringify(e,null,2)}catch{return null}}var Zb=5e3;function Qb({entry:e,frames:t,onShowInEventLog:n}){let r=(0,b.useId)(),i=(0,b.useMemo)(()=>Xb(t),[t]),[a,o]=(0,b.useState)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(0);(0,b.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]);let l=e=>{s.current!==null&&window.clearTimeout(s.current),s.current=null,o(e),e===`copied`&&(s.current=window.setTimeout(()=>o(null),Zb))},u=()=>{if(i===null)return;B_({name:`forge_record_export`,what:`record_copy`});let e=++c.current;Dt(i).then(()=>{e===c.current&&l(`copied`)},()=>{e===c.current&&l(`copyFailed`)})},d=()=>{if(i!==null){B_({name:`forge_record_export`,what:`record_download`});try{let t=URL.createObjectURL(new Blob([i],{type:`application/json`})),n=document.createElement(`a`);n.href=t,n.download=Uv(e.name),document.body.append(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3),l(null)}catch{l(`downloadFailed`)}}},f={copied:Hv.copied,copyFailed:Hv.copyFailed,downloadFailed:Hv.downloadFailed};return(0,x.jsxs)(`section`,{className:Jb.open,"data-record-panel":!0,"aria-labelledby":r,children:[(0,x.jsx)(`h3`,{id:r,className:Jb.heading,"data-text":`heading`,children:Hv.rawRecord}),i===null?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Hv.unreadable}),(0,x.jsx)(`div`,{className:Jb.recordKeys,children:(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Jb.recordKeys,children:[(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:u,children:Hv.copy}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:d,children:Hv.download}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog}),(0,x.jsx)(`p`,{className:Jb.recordSaid,role:`status`,children:a?f[a]:null})]}),(0,x.jsx)(`pre`,{className:Jb.record,"data-raw-record":!0,translate:`no`,tabIndex:0,"aria-label":Hv.rawRecord,children:i})]})]})}function $b({entry:e}){let t=F_(e);return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Nv(t)}),e.history.length>0&&(0,x.jsx)(`ol`,{className:Jb.uses,children:e.history.map((e,t)=>{let n=t===0||e.isReforge;return(0,x.jsxs)(`li`,{className:Jb.use,"data-history-row":n?`forge`:`use`,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Vv(e.turn,e.department,e.eventTitle)}),e.output?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Bv.output}),(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,children:e.output})]}):null,n&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.testNotRecorded})]},`${e.turn}-${e.eventIndex}-${e.department}-${t}`)})}),t===0&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.notUsed})]})}function ex({confidence:e}){let t=Math.min(1,Math.max(0,Number(e.toFixed(2))));return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`h3`,{className:Jb.heading,"data-text":`heading`,children:Rv.heading}),(0,x.jsx)(`p`,{className:Jb.meta,children:Rv.notice}),(0,x.jsxs)(`div`,{className:Jb.confidence,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:zv(e)}),(0,x.jsx)(`div`,{role:`meter`,className:Jb.meter,"aria-label":Rv.meterName,"aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":t,children:(0,x.jsx)(`span`,{className:Jb.meterFill,style:{width:`${t*100}%`},"data-meter-fill":!0})})]}),(0,x.jsx)(`p`,{className:Jb.quiet,children:Rv.wordsNotRecorded})]})}function tx({station:e}){return(0,x.jsx)(x.Fragment,{children:jv[e]})}function nx({reason:e}){let t=(0,b.useId)();return(0,x.jsxs)(`section`,{className:Oy.reason,"aria-labelledby":t,children:[(0,x.jsx)(`h3`,{id:t,className:Oy.reasonHeading,"data-text":`heading`,children:Av.heading}),e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`pre`,{className:Oy.reasonText,translate:`no`,children:e}),(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.limit})]}):(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.none})]})}var rx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ix(e){if(!rx(e))return``;let{type:t}=e;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`string`).join(` | `):``}function ax(e,t){if(rx(e)&&rx(e.properties)){let t=Array.isArray(e.required)?e.required:[];return Object.entries(e.properties).map(([e,n])=>({name:e,type:ix(n),required:t.includes(e),description:rx(n)&&typeof n.description==`string`?n.description:``}))}return t.map(e=>({name:e,type:null,required:null,description:``}))}function ox(e,t){if(t.length===0||!rx(e)||!rx(e.properties))return e;let n=Object.keys(e.properties);return n.length===t.length&&t.every(e=>n.includes(e))?e:void 0}function sx(e,t,n){return[`sim-event-${e}-${t}-${n}`,`turn-row-${t}-h`].find(e=>document.getElementById(e)!==null)??null}function cx({caption:e,rows:t,none:n}){let r=(0,b.useId)(),[i,a,o,s]=Lv.columns;return t.length===0?(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`p`,{className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`p`,{className:Jb.quiet,children:n})]}):(0,x.jsxs)(`table`,{className:Jb.fields,role:`table`,"aria-labelledby":r,children:[(0,x.jsx)(`caption`,{id:r,className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`thead`,{role:`rowgroup`,children:(0,x.jsx)(`tr`,{role:`row`,children:Lv.columns.map(e=>(0,x.jsx)(`th`,{role:`columnheader`,scope:`col`,children:e},e))})}),(0,x.jsx)(`tbody`,{role:`rowgroup`,children:t.map(e=>(0,x.jsxs)(`tr`,{role:`row`,children:[(0,x.jsx)(`td`,{role:`cell`,"data-label":i,"data-code":``,translate:`no`,children:e.name}),e.type===null?(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-quiet":``,children:Lv.notRecorded}):(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-code":``,translate:`no`,children:e.type}),(0,x.jsx)(`td`,{role:`cell`,"data-label":o,children:e.required===null?``:e.required?Lv.yes:Lv.no}),(0,x.jsx)(`td`,{role:`cell`,"data-label":s,children:e.description})]},e.name))})]})}function lx({entry:e,attempt:t,actor:n,onGoToEvent:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useId)(),s=t??e.history[0]??null,c=s?.turn??e.firstForgedTurn,l=s?.eventIndex??0,u=s?.department||e.firstForgedDepartment,d=s?.eventTitle??``,f=t?.description||e.description,[p,m]=(0,b.useState)(null);(0,b.useEffect)(()=>{m(sx(e.actorIndex,c,l))},[e.actorIndex,c,l]);let h=e=>{let t=p?document.getElementById(p):null;t&&(e.preventDefault(),r(t))},g=t&&t.inputFields.length>0?t.inputFields:e.inputFields,_=t&&t.outputFields.length>0?t.outputFields:e.outputFields,v=ox(e.inputSchema,t?t.inputFields:[]),y=ox(e.outputSchema,t?t.outputFields:[]),S=v!=null||y!=null;return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsxs)(`div`,{className:Jb.actor,style:{"--actor":n.colour},"data-actor-line":!0,children:[(0,x.jsx)(`span`,{className:Jb.rule,"aria-hidden":`true`,"data-actor-rule":!0}),(0,x.jsxs)(`div`,{className:Jb.actorText,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Fv({label:n.label,name:n.name,archetype:n.archetype,department:u,turn:c,eventTitle:d})}),p&&d&&(0,x.jsx)(`a`,{className:Jb.link,href:`#${p}`,onClick:h,children:Iv(d)})]})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`h3`,{id:o,className:Jb.heading,"data-text":`heading`,children:Lv.whatItDoes}),(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:f})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[S&&(0,x.jsx)(`div`,{className:Jb.fieldsBar,children:(0,x.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":i,className:Jb.switch,onClick:()=>a(e=>!e),children:[(0,x.jsx)(`span`,{className:Jb.switchTrack,"aria-hidden":`true`}),Lv.rawJson]})}),i&&S?(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,"data-raw-json":!0,children:JSON.stringify({input:v??null,output:y??null},null,2)}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(cx,{caption:Lv.inputFields,rows:ax(v,g),none:Lv.noInputFields}),(0,x.jsx)(cx,{caption:Lv.outputFields,rows:ax(y,_),none:Lv.noOutputFields})]})]})]})}var ux=5e3;function dx(){let[e,t]=(0,b.useState)(()=>typeof navigator>`u`||navigator.onLine!==!1);return(0,b.useEffect)(()=>{let e=()=>t(navigator.onLine!==!1);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]),e}function fx(){try{return window.localStorage}catch{return null}}function px({entry:e,attempt:t,open:n,actorCount:r,runKey:i,sessionId:a=null,events:o,onClose:s,onGoToEvent:c,onShowInEventLog:l,onShown:u}){let d=D_(),f=Pt(!0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useId)();(0,b.useEffect)(()=>{[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null)?.focus()},[]),(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let[g,_]=(0,b.useState)(t),v=e.attempts.length,y=M_(e,g??NaN),S=y>0?e.attempts[y-1]:null,C=S?S.approved?`passed`:`did_not_pass`:e.outcome,w=C===`passed`,T=S?S.errorReason:e.errorReason??null,E=S?.confidence??e.confidence,D=N_(e,y),O=(0,b.useMemo)(()=>Kb(w),[w]),k=O_.filter(e=>(D.stations[e]===`reached`||D.stations[e]===`stopped`)&&O(e)),A=(0,b.useMemo)(()=>qb(window.location.href,i),[i]),[j,ee]=(0,b.useState)(()=>{let e=fx(),t=e?Ub(e,A):[];return Gb(D,[...t,...n??[]],O)}),te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(!te.current){te.current=!0;for(let e of O_)e!==D.deciding&&j.has(e)&&B_({name:`forge_station_open`,station:e,via:`kept`})}},[D.deciding,j]);let M=e=>{ee(e);let t=fx();t&&Wb(t,A,[...e])},N=e=>{let t=new Set(j);t.has(e)?t.delete(e):(t.add(e),B_({name:`forge_station_open`,station:e,via:`press`})),M(t)},ne=k.every(e=>j.has(e)),P=()=>{if(!ne)for(let e of k)j.has(e)||B_({name:`forge_station_open`,station:e,via:`open_all`});M(new Set(ne?k.filter(e=>e===D.deciding):k))},re=(0,b.useRef)(null),ie=(t,n)=>{let r=M_(e,t);if(r===0||r===y)return;let i=e.attempts[r-1].approved;ee(Gb(N_(e,r),[...j],Kb(i))),re.current=n?y:null,_(r)},F=(0,b.useRef)(y);(0,b.useEffect)(()=>{F.current!==y&&(F.current=y,g===void 0&&ee(e=>Gb(D,[...e],O)))},[y,g,D,O]),(0,b.useEffect)(()=>{let e=re.current;re.current=null,e!==null&&(f.current?.querySelector(`[data-fork-attempt="${e}"]`)??[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null))?.focus()},[y,f]),(0,b.useEffect)(()=>{u?.({attempt:y,open:O_.filter(e=>j.has(e))})},[u,y,j]);let{shared:I,share:ae,clear:oe}=on(),se=dx(),ce=(0,b.useId)();(0,b.useEffect)(()=>{if(I?.state!==`copied`)return;let e=window.setTimeout(oe,ux);return()=>window.clearTimeout(e)},[I,oe]);let le=()=>{a&&(B_({name:`forge_link_copy`}),ae(Z_(window.location.origin,a,Q_(window.location.href),{actorIndex:e.actorIndex,toolName:e.name,...y>0?{attempt:y}:{},open:O_.filter(e=>j.has(e))},d)))},L=I?.state===`refused`||I?.state===`unanswered`,[ue,de]=(0,b.useState)(!1),fe=(0,b.useMemo)(()=>ue?Yb(o,e.name):[],[ue,o,e.name]),R=()=>{B_({name:`forge_log_jump`}),l()},z=t=>{switch(t){case`request`:return S?.description||e.description;case`code`:return w?(0,x.jsx)(tx,{station:`code`}):null;case`tests`:return w?(0,x.jsx)(tx,{station:`tests`}):null;case`judge`:return w?Mv(E):null;case`added`:return w?Nv(F_(e)):null}},pe=d.actors[e.actorIndex];return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&s()},children:(0,x.jsxs)(`div`,{ref:f,role:`dialog`,"aria-modal":`true`,"aria-label":Cv(e.name,e.n),tabIndex:-1,className:Oy.dialog,children:[(0,x.jsxs)(`div`,{className:Oy.header,"data-forge-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>s(),"aria-label":Tv,title:Tv,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(Ry,{index:e.actorIndex,colour:Pe(e.actorIndex)}),(0,x.jsx)(`span`,{className:Oy.number,children:wv(e.n)}),(0,x.jsx)(`h2`,{ref:p,className:`${Oy.name} ${Oy.nameInRow}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`span`,{className:Oy.headerEnd,children:[a&&(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:le,"aria-label":Ev.key,"aria-describedby":ce,title:Ev.key,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6.5 9.5L9.5 6.5M7 4.5L8.5 3a2.5 2.5 0 0 1 3.5 3.5L10.5 8M9 11.5L7.5 13A2.5 2.5 0 0 1 4 9.5L5.5 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(ky,{})]})]}),a&&(0,x.jsxs)(`div`,{id:ce,className:Oy.linkNote,role:`status`,"aria-live":`polite`,"data-link-note":!0,children:[!se&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.offline}),I?.state===`copied`&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.copied}),L&&I&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.failed}),(0,x.jsx)(`p`,{className:Oy.linkText,"data-tool-link":!0,translate:`no`,children:I.url})]})]}),(0,x.jsxs)(`div`,{className:Oy.head,"data-forge-head":!0,children:[v>1&&(0,x.jsxs)(`div`,{className:Oy.attempts,role:`group`,"aria-label":Kv(y,v),children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.previous,title:Wv.previous,"aria-disabled":y<=1||void 0,onClick:()=>{y>1&&ie(y-1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M10 3.5L5.5 8L10 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(`span`,{className:Oy.attemptLine,"data-attempt-line":!0,"aria-hidden":`true`,children:y===v?Gv(y,v):Kv(y,v)}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.next,title:Wv.next,"aria-disabled":y>=v||void 0,onClick:()=>{y<v&&ie(y+1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})})]}),(0,x.jsx)(`p`,{className:Oy.label,children:Ov}),(0,x.jsx)(`h2`,{ref:m,className:`${Oy.name} ${Oy.nameInHead}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`p`,{className:Oy.outcome,"data-forge-outcome":!0,"data-text":`heading`,children:[(0,x.jsx)(lb,{kind:k_(C),size:20}),(0,x.jsx)(`span`,{children:kv[C]})]}),!w&&(0,x.jsx)(nx,{reason:T})]}),(0,x.jsxs)(`div`,{className:Oy.line,children:[k.length>1&&(0,x.jsx)(`div`,{className:Oy.lineHead,children:(0,x.jsx)(`button`,{type:`button`,className:Oy.key,"aria-label":ne?Pv.closeName:Pv.openName,onClick:P,children:ne?Pv.close:Pv.open})}),(0,x.jsx)(gb,{model:D,size:`trace`,colour:P_(e.actorIndex,r),open:j,onToggle:N,stationResult:z,renderEvidence:t=>{if(!O(t))return null;switch(t){case`request`:return(0,x.jsx)(lx,{entry:e,attempt:S,actor:{label:pe?.label??xv(e.actorIndex),name:e.actorName,archetype:pe?.archetype??``,colour:Pe(e.actorIndex)},onGoToEvent:c});case`judge`:return(0,x.jsx)(ex,{confidence:E});case`added`:return(0,x.jsx)($b,{entry:e});default:return null}},onAttempt:e=>ie(e,!0)})]}),(0,x.jsxs)(`div`,{className:Oy.recordFoot,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.recordKey}`,"aria-expanded":ue,"aria-controls":h,onClick:()=>de(e=>!e),children:Hv.key}),(0,x.jsx)(`div`,{id:h,className:Oy.recordBody,hidden:!ue,children:ue&&(0,x.jsx)(Qb,{entry:e,frames:fe,onShowInEventLog:R})})]})]})})}var mx={trace:null,toolbox:!1},hx=[];function gx(e){let{show:t,find:n,group:r,actors:i}=q_(e,{getEntryByNumber:()=>void 0,actors:[]},!1).state.toolbox;return{show:tv.includes(t)?t:`all`,find:n??``,group:nv.includes(r)?r:null,actors:[...new Set((i??[]).map(e=>e-1))].sort((e,t)=>e-t)}}var _x=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),vx=(e,t)=>e.show===t.show&&e.find===t.find&&e.group===t.group&&_x(e.actors,t.actors);function yx({state:e,runKey:t,sessionId:n,showToolLog:r,children:i}){let a=D_(),[o,s]=(0,b.useState)(mx),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(!1),d=(0,b.useRef)(!1),f=(0,b.useRef)(0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useRef)(a);h.current=a;let g=(0,b.useRef)(e.isComplete);g.current=e.isComplete;let _=(0,b.useRef)(o);_.current=o;let v=(0,b.useRef)(null),[y,S]=(0,b.useState)(null),[C,w]=(0,b.useState)(()=>typeof window>`u`?iv:gx(window.location.href)),T=(0,b.useRef)(C),E=(0,b.useCallback)(()=>{let e=window.location.href,t=Y_(e,{...u.current&&d.current?{open:!0}:{},...T.current});if(t!==e)try{window.history.replaceState(window.history.state,``,t)}catch{}},[]),D=(0,b.useCallback)(e=>{let t=T.current,n={...t,...e};vx(n,t)||(T.current=n,w(n),E())},[E]),O=(0,b.useCallback)(()=>{d.current||=(v.current=window.location.href,window.history.pushState({forgeView:!0},``),!0)},[]),k=(0,b.useCallback)((e,t,n)=>{h.current.getEntryFor(e.actorIndex,e.toolName)&&(n&&B_({name:`forge_trace_open`,from:n}),u.current?l.current=t??null:c.current=t??null,O(),S(null),s(t=>({trace:e,toolbox:t.toolbox})))},[O]),A=(0,b.useCallback)((e,t)=>{u.current||(t&&B_({name:`forge_toolbox_open`,from:t}),c.current=e??null,u.current=!0,O(),E(),s(e=>({trace:e.trace,toolbox:!0})))},[O,E]),j=(0,b.useCallback)((e,t)=>{if(e instanceof HTMLElement&&(c.current=e,p.current=e),l.current=null,u.current=!1,s(mx),d.current){d.current=!1;let e=v.current;v.current=null,e!==null&&e!==window.location.href&&window.history.replaceState(window.history.state,``,e),f.current+=1,m.current=t??null,window.history.back()}else t?.()},[]),ee=(0,b.useCallback)(()=>{if(!u.current){j();return}S(null),s({trace:null,toolbox:!0});let e=window.location.href,t=X_(e,U_);t!==e&&window.history.replaceState(window.history.state,``,t)},[j]),te=(0,b.useCallback)(()=>j(),[j]);(0,b.useEffect)(()=>{let e=()=>{if(f.current>0){--f.current,E();let e=m.current;m.current=null,e?.();let t=p.current;p.current=null,t?.isConnected&&requestAnimationFrame(()=>{t.scrollIntoView({block:`nearest`}),document.activeElement!==t&&t.focus({preventScroll:!0})})}else if(d.current)_.current.trace&&u.current?(S(null),s({trace:null,toolbox:!0}),d.current=!1,O(),E()):(d.current=!1,v.current=null,l.current=null,u.current=!1,s(mx),E());else{if(window.history.state?.forgeView!==!0)return;let{state:e}=q_(window.location.href,h.current,g.current);if(!e.trace&&!e.toolbox.open)return;d.current=!0,v.current=Y_(X_(window.location.href,U_),{open:!1,...T.current}),u.current=e.toolbox.open,S(null),s({trace:e.trace??null,toolbox:e.toolbox.open})}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[O,E]);let M=o.trace,N=M?a.getEntryFor(M.actorIndex,M.toolName):void 0,ne=N?e.actors[e.actorIds[N.actorIndex]]?.events??hx:hx,P=(0,b.useCallback)(()=>{if(!N)return;let{name:e,actorName:t}=N;j(null,()=>r?.(e,t))},[N,j,r]),re=(0,b.useCallback)(t=>{let n=e.actorIds[t];n&&j(null,()=>r?.(``,n))},[e.actorIds,j,r]);(0,b.useEffect)(()=>{M&&!N&&ee()},[M,N,ee]),(0,b.useEffect)(()=>{if(!M||!N||!d.current)return;let e=window.location.href,t=J_(e,{trace:{actorIndex:N.actorIndex,toolName:N.name,...y&&y.attempt>0?{attempt:y.attempt}:{},...y?{open:y.open}:{}},toolbox:q_(e,a,!1).state.toolbox},a);t!==e&&window.history.replaceState(window.history.state,``,t)},[M,N,y,a]);let ie=e.isComplete,F=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!ie)return;let e=`${t??``}|${n??``}`;if(F.current===e)return;F.current=e;let r=window.location.href,{state:i,dangling:o}=q_(r,a,!0);o.length>0&&window.history.replaceState(window.history.state,``,X_(r,o));let s=gx(window.location.href),c={...s,actors:s.actors.filter(e=>e<a.actors.length)};if(vx(c,T.current)||(T.current=c,w(c)),_.current.trace||_.current.toolbox)return;let l=Y_(X_(window.location.href,U_),{open:!1,...c});l!==window.location.href&&window.history.replaceState(window.history.state,``,l),i.toolbox.open&&A(null),i.trace&&k(i.trace,null,`link`)},[ie,t,n,a,k,A]);let I=M!==null,ae=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(I){ae.current=!0;return}if(!ae.current||(ae.current=!1,!o.toolbox))return;let e=l.current;l.current=null,e?.isConnected?e.focus():document.querySelector(`[data-toolbox-title]`)?.focus()},[I,o.toolbox]);let oe=M!==null||o.toolbox,se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(oe){se.current=!0;return}if(!se.current)return;se.current=!1;let e=c.current;c.current=null,e?.isConnected&&e.focus()},[oe]);let ce=(0,b.useMemo)(()=>({openTrace:k,openToolbox:A,close:j,showActorLog:re,current:o}),[k,A,j,re,o]),le=(0,b.useMemo)(()=>({...C,set:D}),[C,D]);return(0,x.jsx)($_.Provider,{value:ce,children:(0,x.jsxs)(ov.Provider,{value:le,children:[i,o.toolbox&&(0,x.jsx)(Rb,{covered:M!==null,onClose:te}),M&&N&&(0,x.jsx)(px,{entry:N,attempt:M.attempt,open:M.open,actorCount:e.actorIds.length,runKey:t,sessionId:ie?n:null,events:ne,onShown:S,onClose:ee,onGoToEvent:j,onShowInEventLog:P},`${N.actorIndex}:${N.name}`)]})})}var bx=420,xx=260;function Sx({content:e,children:t,dot:n,block:r,disabled:i=!1}){let[a,o]=(0,b.useState)(!1),[s,c]=(0,b.useState)({x:0,y:0}),l=(0,b.useRef)(null),u=(0,b.useRef)(void 0);b.useEffect(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),o(!1))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=(0,b.useCallback)(e=>{clearTimeout(u.current);let t=e.currentTarget.getBoundingClientRect(),n=Math.min(bx,window.innerWidth-20),r=t.left,i=t.top-xx-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+xx>window.innerHeight-10&&(i=window.innerHeight-xx-10),i<10&&(i=10),c({x:r,y:i}),o(!0)},[]),f=(0,b.useCallback)(()=>{u.current=setTimeout(()=>o(!1),100)},[]),p=a&&!i?(0,x.jsx)(`div`,{id:`paracosm-tooltip`,role:`tooltip`,onMouseEnter:()=>{clearTimeout(u.current),o(!0)},onMouseLeave:f,style:{position:`fixed`,left:s.x,top:s.y,zIndex:99999,background:`var(--bg-card)`,border:`2px solid var(--amber)`,borderRadius:`8px`,padding:`14px 18px`,fontSize:`var(--font-sm)`,color:`var(--text-1)`,lineHeight:1.6,width:`${bx}px`,maxWidth:`90vw`,maxHeight:`80vh`,overflowY:`auto`,boxShadow:`0 8px 40px rgba(0,0,0,.4)`,pointerEvents:`auto`,whiteSpace:`normal`,wordBreak:`break-word`,animation:`fadeUp 0.15s ease both`},children:e}):null;return(0,x.jsxs)(`span`,{ref:l,onMouseEnter:d,onMouseLeave:f,style:{position:`relative`,display:r?`block`:`inline-flex`,alignItems:r?void 0:`center`,width:r?`100%`:void 0,minWidth:r?0:void 0,cursor:`pointer`},tabIndex:0,"aria-describedby":a?`paracosm-tooltip`:void 0,onFocus:d,onBlur:f,children:[t,n&&(0,x.jsx)(`span`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`var(--amber)`,opacity:a?.8:0,marginLeft:`3px`,transition:`opacity 0.15s`,flexShrink:0,display:`inline-block`,verticalAlign:`middle`},"aria-hidden":`true`}),p&&typeof document<`u`?(0,Ay.createPortal)(p,document.body):null]})}var Cx={root:`_root_a1e21_1`,triggerButton:`_triggerButton_a1e21_6`,triggerCaret:`_triggerCaret_a1e21_29`,menuPopover:`_menuPopover_a1e21_34`,menuButton:`_menuButton_a1e21_49`,loadFileButton:`_loadFileButton_a1e21_49`,runSavedButton:`_runSavedButton_a1e21_49`,runNewButton:`_runNewButton_a1e21_49`,menuButtonInnerLeft:`_menuButtonInnerLeft_a1e21_68`,menuButtonIcon:`_menuButtonIcon_a1e21_74`,runNewBadge:`_runNewBadge_a1e21_94`,disabled:`_disabled_a1e21_116`,runSavedBadge:`_runSavedBadge_a1e21_128`,savedCardsWrap:`_savedCardsWrap_a1e21_145`,savedStatus:`_savedStatus_a1e21_149`,savedError:`_savedError_a1e21_149`,loadFileBadge:`_loadFileBadge_a1e21_170`,sessionCard:`_sessionCard_a1e21_181`,sessionCardTitle:`_sessionCardTitle_a1e21_203`,sessionCardLine2:`_sessionCardLine2_a1e21_212`,sessionCardLine3:`_sessionCardLine3_a1e21_218`,tooltipHeading:`_tooltipHeading_a1e21_224`,historyRow:`_historyRow_a1e21_234`,historyRowLabel:`_historyRowLabel_a1e21_259`,historyRowBadge:`_historyRowBadge_a1e21_265`,historyList:`_historyList_a1e21_276`,historyCardWrap:`_historyCardWrap_a1e21_285`,historyCard:`_historyCard_a1e21_285`,historyCardTitle:`_historyCardTitle_a1e21_310`,historyCardLine2:`_historyCardLine2_a1e21_318`,historyCardLine3:`_historyCardLine3_a1e21_324`,historyDelete:`_historyDelete_a1e21_329`,historyClearAll:`_historyClearAll_a1e21_353`},wx=Cx;function Tx(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ex(e){if(!e||e<=0)return`·`;let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Dx(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Ox({s:e,onPick:t}){let n=Rn(e),r=n?`${n}${e.scenarioName?` · ${e.scenarioName}`:``}`:e.scenarioName||`Simulation Run`,i=e.title||e.scenarioName||r,a=[n,e.title&&e.scenarioName?e.scenarioName:``,e.turnCount==null?``:`${e.turnCount} turn${e.turnCount===1?``:`s`}`].filter(Boolean).join(` · `),o=`${new Date(e.createdAt).toLocaleString()} (${Tx(e.createdAt)}) · ${Ex(e.durationMs)} · ${Dx(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Cx.sessionCard,children:[(0,x.jsx)(`div`,{className:Cx.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Cx.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Cx.sessionCardLine3,children:o})]})}function kx({onRun:e,onLoadFromFile:t,history:n=[],onRestoreHistory:r,onClearHistory:i,liveStateHasEvents:a=!1}){let[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(!1),[u,d]=(0,b.useState)(!0),f=(0,b.useRef)(null),{sessions:p,status:m,refresh:h}=Oe(),g=p.length>0,_=eA();(0,b.useEffect)(()=>{o&&h()},[o,h]);let v=(0,b.useCallback)(()=>{s(!1),l(!1)},[]);(0,b.useEffect)(()=>{if(!o)return;let e=e=>{f.current&&!f.current.contains(e.target)&&v()},t=e=>{e.key===`Escape`&&v()};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[o,v]);let y=()=>{_&&(v(),e?.())},S=e=>{window.location.assign(kg(window.location.href,e))},C=()=>{v(),t?.()},w=Og(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Cx.root,children:[(0,x.jsx)(Sx,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Cx.tooltipHeading,children:`Run`}),(0,x.jsx)(`div`,{children:`Launches a fresh simulation, replays a cached one, or loads a saved JSON from disk. Click to open the menu.`})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>s(e=>!e),"aria-haspopup":`menu`,"aria-expanded":o,className:Cx.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Cx.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Cx.runNewButton,children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Cx.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Cx.runSavedButton,g?``:Cx.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Cx.runSavedBadge,g?``:Cx.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Cx.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Ox,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Cx.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Session cache is disabled on this server.`})]}),n.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,className:wx.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:wx.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:wx.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:wx.historyList,children:[n.map(e=>{let t=Date.parse(e.createdAt)||e.id,n=(e.summary.actorNames??[]).join(` vs `)||e.scenarioShortName,i=e.summary.turnCount?`${e.summary.turnCount} turn${e.summary.turnCount===1?``:`s`}`:``,o=[n,n===e.scenarioShortName?``:e.scenarioShortName,i].filter(Boolean).join(` · `),s=`${Tx(t)} · ${e.summary.eventCount} ev · ${Dx(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:wx.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:wx.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:wx.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:wx.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:wx.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:wx.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. It also lets go of this browser's run on the server, stopping it if it is running. Run history, saved sessions and output files are kept: Delete server data in the ⋯ menu deletes those, where admin writes are on and an admin token is saved.`,onClick:()=>{window.confirm(`Clear all local browser state?
|
|
113
|
+
`)}var Fh={wrap:`_wrap_5ldo7_1`,toggle:`_toggle_5ldo7_6`,panel:`_panel_5ldo7_34`,tabRow:`_tabRow_5ldo7_42`,tabPill:`_tabPill_5ldo7_51`,copyBtn:`_copyBtn_5ldo7_74`,code:`_code_5ldo7_97`};function Ih(e){let{disabled:t,initiallyExpanded:n=!1,initialTab:r=`ts`,...i}=e,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(r),[l,u]=(0,b.useState)(`idle`),d=(0,b.useMemo)(()=>jh(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Ph(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),p=s===`ts`?d:f,m=(0,b.useCallback)(async()=>{try{await navigator.clipboard.writeText(p),u(`ok`)}catch{u(`fail`)}window.setTimeout(()=>u(`idle`),1500)},[p]),h=`quickstart-view-as-code-panel`,g=`quickstart-view-as-code-tab-ts`,_=`quickstart-view-as-code-tab-curl`,v=s===`ts`?g:_;return(0,x.jsxs)(`div`,{className:Fh.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:Fh.toggle,"aria-expanded":a,"aria-controls":h,disabled:t,onClick:()=>o(e=>!e),children:a?`▾ Hide code`:`▸ View as code`}),a&&(0,x.jsxs)(`div`,{id:h,role:`tabpanel`,"aria-labelledby":v,className:Fh.panel,children:[(0,x.jsxs)(`div`,{className:Fh.tabRow,role:`tablist`,"aria-label":`Recipe language`,children:[(0,x.jsx)(`button`,{type:`button`,id:g,role:`tab`,"aria-pressed":s===`ts`,"aria-selected":s===`ts`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`ts`),children:`TypeScript`}),(0,x.jsx)(`button`,{type:`button`,id:_,role:`tab`,"aria-pressed":s===`curl`,"aria-selected":s===`curl`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:Fh.copyBtn,onClick:m,"aria-label":`Copy ${s===`ts`?`TypeScript`:`curl`} recipe`,children:l===`ok`?`Copied ✓`:l===`fail`?`Press ⌘C`:`Copy`})]}),(0,x.jsx)(`pre`,{className:Fh.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Lh={card:`_card_srwu8_2`,heading:`_heading_srwu8_15`,subline:`_subline_srwu8_25`,scenarioPickerRow:`_scenarioPickerRow_srwu8_34`,scenarioPickerLabel:`_scenarioPickerLabel_srwu8_45`,scenarioPickerSelect:`_scenarioPickerSelect_srwu8_54`,scenarioPickerHint:`_scenarioPickerHint_srwu8_66`,actorRow:`_actorRow_srwu8_73`,actorLabel:`_actorLabel_srwu8_82`,actorSlider:`_actorSlider_srwu8_91`,actorValue:`_actorValue_srwu8_96`,runButton:`_runButton_srwu8_102`,runButtonFull:`_runButtonFull_srwu8_134`,runButtonCompact:`_runButtonCompact_srwu8_138`,tagline:`_tagline_srwu8_144`,tradeoff:`_tradeoff_srwu8_154`};function Rh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function zh({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Qk(),i=!eA()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,E=()=>{s||i||(c(!0),e(a))},D=`${a} ${a===1?`actor`:`actors`}`,O=s?`Launching...`:`Run ${D} against ${y}`,k=s?`Launching...`:`${O} ->`,A=s?`Launching...`:`Run ${D}`,j=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Lh.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Lh.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Lh.tagline,children:S}),(0,x.jsx)(`div`,{className:Lh.subline,children:C}),l.length>=2&&(()=>{let e=l.some(e=>e.id===r.id)?l:[...l,{id:r.id,name:r.labels.name||r.id,source:`active`}];return(0,x.jsxs)(`div`,{className:Lh.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Lh.scenarioPickerLabel,htmlFor:j,children:`Scenario`}),(0,x.jsx)(`select`,{id:j,className:Lh.scenarioPickerSelect,value:r.id,onChange:e=>m(e.target.value),disabled:i||s||d,"aria-label":`Switch active scenario`,children:e.map(e=>{let t=e.source===`builtin`?`[builtin]`:e.source===`disk`?`[disk]`:e.source===`compiled`?`[compiled]`:e.source===`active`?`[active]`:``,n=[];if(t&&n.push(t),typeof e.runCount==`number`&&e.runCount>0&&n.push(`${e.runCount} run${e.runCount===1?``:`s`}`),e.compiledAt){let t=Rh(e.compiledAt);t&&n.push(t)}let r=n.length>0?` · ${n.join(` · `)}`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.name,r]},e.id)})}),d&&(0,x.jsx)(`span`,{className:Lh.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Lh.actorRow,children:[(0,x.jsx)(`label`,{className:Lh.actorLabel,htmlFor:T,children:`Actors`}),(0,x.jsx)(`input`,{id:T,type:`range`,min:1,max:300,value:a,onChange:e=>o(parseInt(e.target.value,10)),disabled:i||s,className:Lh.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Lh.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Lh.runButton,onClick:E,disabled:i||s,"aria-busy":s,"aria-label":O,children:[(0,x.jsx)(`span`,{className:Lh.runButtonFull,"aria-hidden":`true`,children:k}),(0,x.jsx)(`span`,{className:Lh.runButtonCompact,"aria-hidden":`true`,children:A})]}),(0,x.jsxs)(`div`,{className:Lh.tradeoff,children:[_&&!v&&`Same scenario, fresh seed: skips the compile step.`,_&&v&&`Same scenario; ${a} LLM-generated actors replace the preset leaders for this run (~30s for generation).`,!_&&`Same scenario; ~30s for actor generation since no preset is defined.`]})]})}var W={backdrop:`_backdrop_nucmo_1`,backdropFadeIn:`_backdropFadeIn_nucmo_1`,drawer:`_drawer_nucmo_17`,open:`_open_nucmo_34`,header:`_header_nucmo_38`,closeBtn:`_closeBtn_nucmo_50`,sourceBadge:`_sourceBadge_nucmo_63`,summary:`_summary_nucmo_86`,nameRow:`_nameRow_nucmo_94`,name:`_name_nucmo_94`,nameEditBtn:`_nameEditBtn_nucmo_110`,nameEditForm:`_nameEditForm_nucmo_129`,nameEditInput:`_nameEditInput_nucmo_135`,nameEditActions:`_nameEditActions_nucmo_150`,nameEditSave:`_nameEditSave_nucmo_155`,nameEditCancel:`_nameEditCancel_nucmo_173`,nameEditError:`_nameEditError_nucmo_195`,description:`_description_nucmo_202`,metaGrid:`_metaGrid_nucmo_209`,meta:`_meta_nucmo_209`,sectionHeading:`_sectionHeading_nucmo_235`,seedSection:`_seedSection_nucmo_245`,seedHint:`_seedHint_nucmo_250`,seedBody:`_seedBody_nucmo_257`,presetsSection:`_presetsSection_nucmo_273`,departmentsSection:`_departmentsSection_nucmo_274`,sectionHint:`_sectionHint_nucmo_279`,sectionCount:`_sectionCount_nucmo_287`,presetList:`_presetList_nucmo_294`,presetCard:`_presetCard_nucmo_303`,presetHeader:`_presetHeader_nucmo_313`,presetName:`_presetName_nucmo_320`,presetArchetype:`_presetArchetype_nucmo_327`,presetUnit:`_presetUnit_nucmo_340`,hexacoList:`_hexacoList_nucmo_347`,hexacoRow:`_hexacoRow_nucmo_356`,hexacoAxis:`_hexacoAxis_nucmo_364`,hexacoBar:`_hexacoBar_nucmo_372`,hexacoFill:`_hexacoFill_nucmo_380`,hexacoValue:`_hexacoValue_nucmo_386`,presetInstructions:`_presetInstructions_nucmo_393`,deptChips:`_deptChips_nucmo_401`,deptChip:`_deptChip_nucmo_401`,deptIcon:`_deptIcon_nucmo_423`,deptRole:`_deptRole_nucmo_427`,recentSection:`_recentSection_nucmo_431`,statusLine:`_statusLine_nucmo_438`,error:`_error_nucmo_445`,recentList:`_recentList_nucmo_449`,recentRow:`_recentRow_nucmo_458`,recentTitle:`_recentTitle_nucmo_468`,recentArchetype:`_recentArchetype_nucmo_475`,recentMeta:`_recentMeta_nucmo_480`,footer:`_footer_nucmo_486`,actorRow:`_actorRow_nucmo_497`,actorLabel:`_actorLabel_nucmo_505`,actorSlider:`_actorSlider_nucmo_514`,actorValue:`_actorValue_nucmo_519`,runButton:`_runButton_nucmo_527`,deleteButton:`_deleteButton_nucmo_549`,deleteError:`_deleteError_nucmo_572`},Bh=`Admin token refused and cleared. ${R}`,Vh=(e,t)=>`The server refused the admin token this ${e} was sent with. A newer token is saved in this browser; press ${t} to try again with it.`,Hh=`scenario-rename-error`;function Uh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Wh(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Gh(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return`—`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Kh(e){return e?Array.from(e.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`):[]}function qh(e){let{scenario:t,disabled:n=!1,initialActorCount:r=2,onRunScenario:i,onClose:a,onDeleted:o,onRenamed:s}=e,c=t!==null,[l,u]=(0,b.useState)(r),[d,f]=(0,b.useState)([]),[p,m]=(0,b.useState)(!1),[h,g]=(0,b.useState)(null),[_,v]=(0,b.useState)(null),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(null),[D,O]=(0,b.useState)(!1),[k,A]=(0,b.useState)(``),[j,ee]=(0,b.useState)(!1),[te,M]=(0,b.useState)(null),[N,ne]=(0,b.useState)(null);(0,b.useEffect)(()=>{ne(null),O(!1),M(null)},[t?.id]);let[P,re]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)return E(null),re(B()||null),Se(()=>re(B()||null))},[c]);let ie=!!P&&t?.source===`compiled`,F=!!P&&t?.source===`compiled`,I=(0,b.useRef)(null),ae=(0,b.useRef)(null);if((0,b.useEffect)(()=>{if(!t){f([]),g(null),v(null);return}let e=!1;return m(!0),g(null),S(!0),v(null),fetch(`/api/v1/runs?scenario=${encodeURIComponent(t.id)}&limit=5`).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||f(n.runs??[])}).catch(t=>{e||(g(t instanceof Error?t.message:String(t)),f([]))}).finally(()=>{e||m(!1)}),fetch(`/scenarios/${encodeURIComponent(t.id)}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}).then(t=>{e||v(t)}).catch(()=>{e||v(null)}).finally(()=>{e||S(!1)}),()=>{e=!0}},[t?.id]),(0,b.useEffect)(()=>{c?(ae.current=document.activeElement,requestAnimationFrame(()=>{(I.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ae.current?.focus()},[c]),(0,b.useEffect)(()=>{if(!c)return;function e(e){if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`Tab`){let t=Kh(I.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!I.current?.contains(i)?(e.preventDefault(),n.focus()):e.shiftKey&&i===n?(e.preventDefault(),r.focus()):!e.shiftKey&&i===r&&(e.preventDefault(),n.focus())}}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c,a]),!t)return null;let oe=`scenario-detail-actor-count`,se=()=>{t&&F&&(A(N??t.name),O(!0),M(null))},ce=()=>{O(!1),A(``),M(null)},le=async()=>{if(!t||!P||j)return;let e=k.trim();if(e.length===0){M(`Name cannot be empty.`);return}if(e===(N??t.name)){O(!1);return}let n=xe(P);if(n)M(n),re(B()||null);else{ee(!0),M(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:P},body:JSON.stringify({name:e})});if(n.status===401){be(P);let e=B()||null;re(e),M(e?Vh(`rename`,`Save`):Bh);return}if(!n.ok){let e=await n.json().catch(()=>({}));M(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ne(r),O(!1),A(``),s?.(t.id,r)}catch(e){M(e instanceof Error?e.message:String(e))}finally{ee(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:W.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:I,className:`${W.drawer} ${c?W.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:W.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:W.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:W.sourceBadge,"data-source":t.source??`other`,children:Jh(t.source)})]}),(0,x.jsxs)(`section`,{className:W.summary,children:[D?(0,x.jsxs)(`form`,{className:W.nameEditForm,onSubmit:e=>{e.preventDefault(),le()},children:[(0,x.jsx)(`input`,{type:`text`,value:k,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),ce())},disabled:j,maxLength:100,autoFocus:!0,className:W.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:W.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:W.nameEditSave,disabled:j||!P||k.trim().length===0,"aria-describedby":te?Hh:void 0,children:j?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:W.nameEditCancel,onClick:ce,disabled:j,children:`Cancel`})]}),te&&(0,x.jsx)(`p`,{id:Hh,className:W.nameEditError,role:`alert`,children:te})]}):(0,x.jsxs)(`div`,{className:W.nameRow,children:[(0,x.jsx)(`h2`,{className:W.name,children:N??t.name}),F&&(0,x.jsx)(`button`,{type:`button`,className:W.nameEditBtn,onClick:se,"aria-label":`Rename ${N??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:W.description,children:t.description}),(0,x.jsxs)(`dl`,{className:W.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Total runs`}),(0,x.jsx)(`dd`,{children:t.runCount.toLocaleString()})]}),typeof t.departments==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Uh(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:Jh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:W.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:W.seedHint,children:`Original brief that compile-from-seed turned into this scenario. Truncated to 1KB at persist time so very long sources read as their leading section.`}),(0,x.jsx)(`pre`,{className:W.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:W.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:W.sectionHint,children:`Default leader pair the scenario ships with. Picking Run with the slot count below fills these in first; extra slots beyond the preset get LLM-generated.`}),(0,x.jsx)(`ul`,{className:W.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:W.presetCard,children:[(0,x.jsxs)(`div`,{className:W.presetHeader,children:[(0,x.jsx)(`span`,{className:W.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:W.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:W.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:W.hexacoList,"aria-label":`HEXACO profile for ${e.name}`,children:Object.entries(e.hexaco).slice(0,6).map(([e,t])=>{let n=Math.round((Number(t)||0)*100);return(0,x.jsxs)(`li`,{className:W.hexacoRow,children:[(0,x.jsx)(`span`,{className:W.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:W.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:W.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:W.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:W.presetInstructions,title:e.instructions,children:e.instructions.length>220?`${e.instructions.slice(0,220)}…`:e.instructions})]},`${e.name}-${t}`))})]}),_&&_.departments.length>0&&(0,x.jsxs)(`section`,{className:W.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:W.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:W.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:W.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:W.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:W.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:W.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:W.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:W.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:W.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${W.statusLine} ${W.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:W.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:W.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:W.recentRow,children:[(0,x.jsxs)(`span`,{className:W.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:W.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:W.recentMeta,children:[Uh(e.createdAt),` · `,Wh(e.costUSD),` · `,Gh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:W.footer,children:[(0,x.jsxs)(`div`,{className:W.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:oe,className:W.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:oe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:W.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:W.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:W.runButton,onClick:()=>i(t.id,l),disabled:n||C,"aria-label":`Run ${l} actor${l===1?``:`s`} against ${t.name}`,children:[`Run `,l,` `,l===1?`actor`:`actors`,` →`]}),ie&&(0,x.jsx)(`button`,{type:`button`,className:W.deleteButton,onClick:async()=>{if(!t||!P||C||!(typeof window<`u`&&window.confirm(`Delete this scenario?\n\n"${t.name}"\n\nRemoves the scenario from disk + the live catalog. Past runs are kept (they live in run-history). Cannot be undone.`)))return;let e=xe(P);if(e)E(e),re(B()||null);else{w(!0),E(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{[fe]:P}});if(e.status===401){be(P);let e=B()||null;re(e),E(e?Vh(`delete`,`Delete`):Bh);return}if(!e.ok){let t=await e.json().catch(()=>({}));E(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){E(e instanceof Error?e.message:String(e))}finally{w(!1)}}},disabled:C||n,"aria-label":`Delete scenario ${t.name}`,children:C?`Deleting…`:`Delete (admin)`}),T&&(0,x.jsx)(`p`,{className:W.deleteError,role:`alert`,children:T})]})]})]})}function Jh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var Yh={section:`_section_1l91i_1`,header:`_header_1l91i_5`,heading:`_heading_1l91i_14`,count:`_count_1l91i_24`,statusLine:`_statusLine_1l91i_32`,error:`_error_1l91i_39`,actorRow:`_actorRow_1l91i_43`,actorLabel:`_actorLabel_1l91i_54`,actorSlider:`_actorSlider_1l91i_63`,actorValue:`_actorValue_1l91i_68`,filterRow:`_filterRow_1l91i_76`,searchLabel:`_searchLabel_1l91i_84`,searchInput:`_searchInput_1l91i_90`,chipGroup:`_chipGroup_1l91i_108`,chip:`_chip_1l91i_108`,chipActive:`_chipActive_1l91i_133`,chipCount:`_chipCount_1l91i_139`,sortLabel:`_sortLabel_1l91i_145`,sortSelect:`_sortSelect_1l91i_150`,emptyMatches:`_emptyMatches_1l91i_165`,clearFiltersBtn:`_clearFiltersBtn_1l91i_176`,grid:`_grid_1l91i_187`,card:`_card_1l91i_196`,cardBody:`_cardBody_1l91i_211`,cardActive:`_cardActive_1l91i_231`,cardHeader:`_cardHeader_1l91i_236`,sourceBadge:`_sourceBadge_1l91i_243`,badge_builtin:`_badge_builtin_1l91i_254`,badge_disk:`_badge_disk_1l91i_258`,badge_compiled:`_badge_compiled_1l91i_262`,badge_memory:`_badge_memory_1l91i_262`,badge_other:`_badge_other_1l91i_266`,activeBadge:`_activeBadge_1l91i_270`,cardName:`_cardName_1l91i_282`,cardSeed:`_cardSeed_1l91i_292`,cardStats:`_cardStats_1l91i_303`,stat:`_stat_1l91i_32`,statKey:`_statKey_1l91i_317`,statValue:`_statValue_1l91i_324`,runButton:`_runButton_1l91i_331`};function Xh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Zh(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Qh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function $h(e){let{disabled:t=!1,onRunScenario:n}=e,r=Qk(),i=!eA()||t,a=r.id,[o,s]=(0,b.useState)([]),[c,l]=(0,b.useState)(2),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=setTimeout(()=>_(m),120);return()=>clearTimeout(e)},[m]);let[v,y]=(0,b.useState)(`all`),[S,C]=(0,b.useState)(`curated`),[w,T]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1,t=null,n=async()=>{try{let t=await fetch(`/scenarios`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;s(n.scenarios??[]),p(null)}catch(t){if(e)return;p(t instanceof Error?t.message:String(t))}finally{e||d(!1)}};return n(),t=setInterval(n,3e4),()=>{e=!0,t&&clearInterval(t)}},[]),u&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:Yh.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${Yh.statusLine} ${Yh.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let E=`scenario-catalog-actor-count`,D=`scenario-catalog-search`,O=g.trim().length>0||v!==`all`,k=g.trim().toLowerCase(),A=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:k.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(k))].sort((e,t)=>{if(e.id===a)return-1;if(t.id===a)return 1;if(S===`most-runs`){let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n}else if(S===`newest`){let n=e.compiledAt?Date.parse(e.compiledAt):0,r=t.compiledAt?Date.parse(t.compiledAt):0;if(n!==r)return r-n}else if(S===`alphabetical`)return e.name.localeCompare(t.name);else{let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n;if(e.compiledAt&&t.compiledAt){let n=Date.parse(e.compiledAt),r=Date.parse(t.compiledAt);if(Number.isFinite(n)&&Number.isFinite(r)&&n!==r)return r-n}}return e.name.localeCompare(t.name)}),j=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:Yh.header,children:[(0,x.jsxs)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:Yh.count,children:[`· `,O?`${A.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:Yh.actorRow,children:[(0,x.jsx)(`label`,{className:Yh.actorLabel,htmlFor:E,children:`Actors`}),(0,x.jsx)(`input`,{id:E,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:Yh.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:Yh.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:Yh.filterRow,children:[(0,x.jsxs)(`label`,{className:Yh.searchLabel,htmlFor:D,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:D,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:Yh.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:Yh.chipGroup,role:`group`,"aria-label":`Filter by scenario source`,children:[{key:`all`,label:`All`},{key:`builtin`,label:`Built-in`},{key:`disk`,label:`Saved`},{key:`compiled`,label:`Custom`}].map(e=>{let t=e.key===`all`?o.length:j[e.key]??0,n=v===e.key;return e.key!==`all`&&t===0?null:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>y(e.key),className:`${Yh.chip} ${n?Yh.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:Yh.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:Yh.sortLabel,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Sort scenarios`}),(0,x.jsxs)(`select`,{value:S,onChange:e=>C(e.target.value),className:Yh.sortSelect,"aria-label":`Sort catalog`,children:[(0,x.jsx)(`option`,{value:`curated`,children:`Sort: Curated`}),(0,x.jsx)(`option`,{value:`most-runs`,children:`Sort: Most runs`}),(0,x.jsx)(`option`,{value:`newest`,children:`Sort: Newest first`}),(0,x.jsx)(`option`,{value:`alphabetical`,children:`Sort: A → Z`})]})]})]}),A.length===0?(0,x.jsxs)(`div`,{className:Yh.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:Yh.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:Yh.grid,role:`list`,children:A.map(e=>{let t=Zh(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${Yh.card} ${Yh[`tone_${t}`]??``} ${r?Yh.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:Yh.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:Yh.cardHeader,children:[(0,x.jsx)(`span`,{className:`${Yh.sourceBadge} ${Yh[`badge_${t}`]??``}`,children:Qh(e.source)}),r&&(0,x.jsx)(`span`,{className:Yh.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:Yh.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:Yh.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:Yh.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:Xh(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:Yh.runButton,onClick:t=>{t.stopPropagation(),n(e.id,c)},disabled:i,"aria-label":`Run ${c} actor${c===1?``:`s`} against ${e.name}`,children:[`Run `,c,` `,c===1?`actor`:`actors`,` →`]})]},e.id)})}),(0,x.jsx)(qh,{scenario:w,disabled:i,initialActorCount:c,onRunScenario:(e,t)=>{T(null),n(e,t)},onClose:()=>T(null),onDeleted:e=>{s(t=>t.filter(t=>t.id!==e))},onRenamed:(e,t)=>{s(n=>n.map(n=>n.id===e?{...n,name:t}:n)),T(n=>n&&n.id===e?{...n,name:t}:n)}})]})}var eg=[{id:`hurricane-evacuation`,label:`What if a coastal mayor has 36 hours to evacuate before a hurricane?`,seedText:`A coastal metro of 800,000 has 36 hours before a Category 4 hurricane landfall. The mayor must decide a phased evacuation across three districts served by a single causeway bridge, with a regional hospital, a fuel depot, and an aging levee system in play. Departments involved: emergency management, public health, transportation, utilities, communications.`},{id:`saas-mid-tier`,label:`What if a developer-tools SaaS adds a $14 mid-tier?`,seedText:`StackPulse, a developer-focused observability SaaS (logs + metrics + tracing aimed at series-B-to-D startup engineering teams of 5-50 people), introduces a new $14/month "Builder" tier between the free Sandbox plan and the existing $29 Pro plan. The 180,000-user paid base is mostly engineering managers and SREs at venture-backed startups; their #1 jobs-to-be-done are debugging production incidents under 15 minutes and proving reliability SLAs to enterprise customers. Builder caps log retention at 7 days (Pro keeps 30) and limits trace sampling to 10% (Pro is full). Existing Pro subs get 90-day grandfathering. Competitors: Datadog (incumbent, 10x the price), Honeycomb (premium tier), self-hosted Grafana stacks. Test the impact on Free-to-Paid conversion, Pro downgrade rate, net ARPU, and churn over six months. Departments: pricing, growth, success, finance, engineering.`},{id:`ai-lab-early-release`,label:`What if an AI lab releases a frontier model six weeks early?`,seedText:`An AI lab decides whether to release a frontier multimodal model six weeks early. Two evaluators flag a 4.2% specification-gaming rate on long-horizon agentic tasks and early mesa-objective signals under DPO. A rival lab's weaker model ships on schedule, capturing $240M ARR in enterprise deals. Council: alignment, capability, policy, infra, comms.`},{id:`generation-ship-fuel-leak`,label:`What if a generation ship discovers a fuel leak at year 18?`,seedText:`A generation ship with 2,400 passengers at year 18 of a 40-year interstellar transit discovers a slow fuel leak on the main reactor. Reactor crew wants to EVA-repair (non-zero fatality risk); bridge wants to coast at reduced thrust and accept a 14-year transit extension. Departments: engineering, life support, medical, psych, command.`},{id:`city-congestion-pricing`,label:`What if a city pilots congestion pricing for 12 months?`,seedText:`A mid-size city of 650,000 pilots downtown congestion pricing for 12 months. $9 peak / $3 off-peak on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two BRT lines and a 30% transit fare cut for low-income riders. Test VMT, transit ridership, small-business revenue, equity outcomes.`}];function tg(e){return .1+.6*e}var ng={pendingSeedNotice:`_pendingSeedNotice_1rh83_1`,dividerWrap:`_dividerWrap_1rh83_15`,dividerLine:`_dividerLine_1rh83_27`,seedInput:`_seedInput_1rh83_33`,templatePicker:`_templatePicker_1rh83_48`,templatePickerLabel:`_templatePickerLabel_1rh83_55`,templatePickerSelect:`_templatePickerSelect_1rh83_65`,tabs:`_tabs_1rh83_90`,tab:`_tab_1rh83_90`,tabActive:`_tabActive_1rh83_119`,textarea:`_textarea_1rh83_124`,input:`_input_1rh83_125`,urlRow:`_urlRow_1rh83_142`,fetchButton:`_fetchButton_1rh83_150`,runButton:`_runButton_1rh83_151`,dropZone:`_dropZone_1rh83_185`,hint:`_hint_1rh83_205`,charCount:`_charCount_1rh83_218`,error:`_error_1rh83_225`,actorCountRow:`_actorCountRow_1rh83_235`,actorCountLabel:`_actorCountLabel_1rh83_246`,actorCountSlider:`_actorCountSlider_1rh83_257`,actorCountPreview:`_actorCountPreview_1rh83_313`};function rg(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function ig({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(rg),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(void 0),[f,p]=(0,b.useState)(``),[m,h]=(0,b.useState)(null),[g,_]=(0,b.useState)(!1),[v,y]=(0,b.useState)(2),S=(0,b.useRef)(null),C=(0,b.useCallback)(()=>{let t=o.trim(),n=gh(t);n.ok?(h(null),e({seedText:t,sourceUrl:u,domainHint:f.trim()||void 0,actorCount:v})):h(n.reason===`too-short`?`Paste at least 200 characters of source material.`:n.reason===`too-long`?`Source material exceeds 50 000 characters.`:`Source material is empty.`)},[o,u,f,v,e]),w=(0,b.useCallback)(async()=>{let e=hh(c);if(!e.ok)h(e.error);else{_(!0),h(null);try{let t=await fetch(`/api/quickstart/fetch-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e.url.toString()})});if(!t.ok){let e=await t.json().catch(()=>({}));h(e.error??`Fetch failed: HTTP ${t.status}`);return}let n=await t.json();s(n.text),d(n.sourceUrl??e.url.toString()),a(`paste`)}catch(e){let t=e?.message??String(e),n=/Failed to fetch|NetworkError|ERR_/i.test(t)?`Couldn't reach the server. Check your connection and try again.`:`URL fetch failed: ${t}`;h(n)}finally{_(!1)}}},[c]),T=(0,b.useCallback)(async e=>{if(e.size>10485760)h(`PDF exceeds 10 MB limit.`);else if(e.type!==`application/pdf`&&!e.name.toLowerCase().endsWith(`.pdf`))h(`File is not a PDF: ${e.name}`);else{_(!0),h(null);try{let{text:t,truncated:n}=await Ah(e);s(n?`${t}\n\n[Truncated to first 50 KB.]`:t),d(void 0),a(`paste`)}catch(e){let t=e?.code,n=String(e?.message??e),r;r=t===`PDF_NO_TEXT`?`No text found in this PDF. It looks like a scanned image — try a text-based PDF, or paste the content into WRITE.`:/InvalidPDFException|invalid pdf|corrupt/i.test(n)?`This PDF appears to be corrupted or password-protected. Try a different file or paste the text directly.`:/worker|GlobalWorkerOptions/i.test(n)?`Couldn't load the PDF parser (${n}). Try a different file, or paste the text into WRITE.`:`Couldn't read this PDF (${n}). Try paste-text or a different file.`,h(r)}finally{_(!1)}}},[]),E={paste:`WRITE`,url:`URL`,pdf:`PDF`},D=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:ng.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[D&&(0,x.jsx)(`p`,{className:ng.pendingSeedNotice,role:`status`,"aria-live":`polite`,children:`You have draft seed text below. Submit it to compile a new scenario, or clear it to run the loaded one.`}),(0,x.jsx)(zh,{onRunStart:t,disabled:r||g||D}),n&&(0,x.jsx)($h,{onRunScenario:n,disabled:r||g||D}),(0,x.jsxs)(`div`,{className:ng.dividerWrap,children:[(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:ng.templatePicker,children:[(0,x.jsx)(`span`,{className:ng.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:ng.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=eg.find(e=>e.id===t);n&&(a(`paste`),s(n.seedText),h(null),e.target.value=``)},children:[(0,x.jsx)(`option`,{value:``,children:`Pick a sample scenario…`}),eg.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:ng.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${ng.tab} ${i===e?ng.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:E[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:ng.textarea,placeholder:`Type or paste a brief, article, meeting notes, or any domain-specific source material (at least 200 characters).`,value:o,onChange:e=>s(e.target.value),rows:6,disabled:r}),i===`url`&&(0,x.jsxs)(`div`,{className:ng.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:ng.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:ng.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:ng.dropZone,"data-paracosm-local-dropzone":`pdf`,onClick:()=>{r||S.current?.click()},onDragOver:e=>e.preventDefault(),onDrop:e=>{if(e.preventDefault(),r)return;let t=e.dataTransfer.files[0];t&&T(t)},role:`button`,tabIndex:r?-1:0,"aria-disabled":r,onKeyDown:e=>{r||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S.current?.click())},children:[(0,x.jsx)(`input`,{ref:S,type:`file`,accept:`application/pdf,.pdf`,onChange:e=>{let t=e.target.files?.[0];t&&T(t)},hidden:!0}),g?`Extracting text...`:`Drop a PDF or click to upload (max 10 MB, first 50 KB of text used)`]}),(0,x.jsxs)(`div`,{className:ng.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:ng.input,type:`text`,placeholder:`e.g., "clinical trial decision" or "startup growth"`,value:f,onChange:e=>p(e.target.value),maxLength:80,disabled:r})]}),m&&(0,x.jsx)(`p`,{className:ng.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:ng.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:ng.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:ng.actorCountLabel,children:[`Actors: `,(0,x.jsx)(`strong`,{children:v})]}),(0,x.jsx)(`input`,{id:`quickstart-actor-count`,type:`range`,min:1,max:300,value:v,onChange:e=>y(parseInt(e.target.value,10)),disabled:r,className:ng.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:ng.actorCountPreview,"aria-live":`polite`,children:[`~$`,tg(v).toFixed(2),` · `,ag(v)]})]}),(0,x.jsx)(Ih,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:ng.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,tg(v).toFixed(2),`)`]})]})}function ag(e){if(e<=0)return`—`;let t=2+5*Math.max(1,Math.ceil(e/8));return`${t}–${Math.ceil(t*1.5)} min`}var G={card:`_card_182vb_1`,heading:`_heading_182vb_15`,title:`_title_182vb_23`,eyebrow:`_eyebrow_182vb_35`,copy:`_copy_182vb_43`,presetRow:`_presetRow_182vb_50`,presetLabel:`_presetLabel_182vb_61`,presetButton:`_presetButton_182vb_71`,presetButtonActive:`_presetButtonActive_182vb_91`,presetClear:`_presetClear_182vb_97`,presetBlurb:`_presetBlurb_182vb_118`,formGrid:`_formGrid_182vb_126`,formCell:`_formCell_182vb_137`,formLegend:`_formLegend_182vb_152`,field:`_field_182vb_165`,fieldRow:`_fieldRow_182vb_171`,fieldThird:`_fieldThird_182vb_177`,fieldLabel:`_fieldLabel_182vb_182`,input:`_input_182vb_191`,textarea:`_textarea_182vb_212`,mono:`_mono_182vb_235`,actions:`_actions_182vb_240`,button:`_button_182vb_248`,helper:`_helper_182vb_270`,spinner:`_spinner_182vb_276`,"idc-spin":`_idc-spin_182vb_1`,timer:`_timer_182vb_288`},og=`paracosm:lastLaunchConfig`,sg=`paracosm:keyOverrides`,cg=`paracosm:activeRunActors`,lg=`paracosm:activeRunScenarioId`,ug=950;function dg(e){try{let t=e.getItem(og);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function fg(e,t){return e.scenarioId===t}function pg(e,t){try{e.setItem(og,JSON.stringify(t))}catch{}}function mg(e,t,n){try{e.setItem(cg,JSON.stringify(t)),n?e.setItem(lg,n):e.removeItem?.(lg)}catch{}}function hg(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function gg(e){try{let t=e.getItem(cg);if(!t)return null;let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):null}catch{return null}}function _g(e){try{let t=e.getItem(sg);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function vg(e,t){let n=(typeof e.seed==`number`?e.seed:ug)+1,r={...e,seed:n};return t.openai&&(r.apiKey=t.openai),t.anthropic&&(r.anthropicKey=t.anthropic),t.serper&&(r.serperKey=t.serper),t.firecrawl&&(r.firecrawlKey=t.firecrawl),t.tavily&&(r.tavilyKey=t.tavily),t.cohere&&(r.cohereKey=t.cohere),r}function yg(e){if(typeof e!=`string`)return;let t=e.trim();if(t&&!t.includes(`...`))return t}function bg(e){let t=yg(e.openai),n=yg(e.anthropic);return{...t?{apiKey:t}:{},...n?{anthropicKey:n}:{}}}function xg(e){let t=bg(e);return t.apiKey!==void 0||t.anthropicKey!==void 0}var Sg={id:``,name:``,description:``,profileJson:`{}`},Cg={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},wg={medical:{label:`Patient · treatment`,blurb:`Type 2 diabetes patient on a 12-week semaglutide + lifestyle protocol.`,subject:{id:`patient-maria-2026`,name:`Maria Chen`,description:`58 y/o T2D for 4 yrs, sedentary, family hx CVD, on metformin.`,profileJson:JSON.stringify({age:58,yearsWithT2D:4,bmi:31,a1cBaseline:7.8,weightLb:178,fastingGlucose:156,sleepHoursBaseline:6.2,exerciseMinPerWeek:0,comorbidities:`hypertension, dyslipidemia`},null,2)},intervention:{id:`glp1-12wk-protocol`,name:`12-week semaglutide + lifestyle protocol`,description:`Initiate semaglutide 0.25mg weekly, titrate to 1.0mg by week 4. Pair with dietitian-led nutrition plan and 150min/wk graded exercise. Behavioral health checkpoints biweekly. Monitor for GI side effects, gallbladder, pancreatitis.`,durationValue:`84`,durationUnit:`days`,adherence:`0.85`},signalsJson:JSON.stringify([{label:`HbA1c`,value:7.8,unit:`%`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Fasting glucose`,value:156,unit:`mg/dL`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Weight`,value:178,unit:`lb`,recordedAt:`2026-09-15T00:00:00Z`},{label:`BMI`,value:31,unit:`kg/m²`,recordedAt:`2026-09-15T00:00:00Z`}],null,2)},policy:{label:`Jurisdiction · ordinance`,blurb:`A mid-size city pilots downtown congestion pricing for 12 months.`,subject:{id:`city-portland-2026`,name:`Portland Metro`,description:`Pacific Northwest mid-size city with dense urban core, mature transit, organized downtown business association.`,profileJson:JSON.stringify({population:65e4,downtownEmployment:11e4,modeShareTransit:.18,modeShareCar:.62,modeShareActive:.14,avgPeakSpeedMph:14.2,annualCO2Tons:182e4,unemploymentRate:.044},null,2)},intervention:{id:`congestion-pricing-12mo`,name:`Downtown congestion pricing pilot`,description:`Charge $9/peak-hour ($3 off-peak) on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two new BRT lines and a 30% transit fare cut for low-income riders. Pilot runs 12 months with quarterly review.`,durationValue:`12`,durationUnit:`months`,adherence:`0.78`},signalsJson:JSON.stringify([{label:`Downtown VMT`,value:1.42,unit:`million-mi/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Transit ridership`,value:118e3,unit:`boardings/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Peak speed`,value:14.2,unit:`mph`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)},product:{label:`Market · launch`,blurb:`A SaaS launches a new mid-tier price point against a price-sensitive prosumer segment.`,subject:{id:`segment-prosumer-creators`,name:`Prosumer creators`,description:`Independent creators earning $40k-$120k/yr who self-fund their tooling. Cross-tool stackers; price-sensitive within 20% bands.`,profileJson:JSON.stringify({addressableUsers:18e5,currentPaidConversion:.034,avgARPU_USD:22,churnMonthly:.038,npsCurrent:41,topCompetitorPriceUSD:18,topCompetitorMarketShare:.31},null,2)},intervention:{id:`mid-tier-pricing-launch`,name:`New $14/mo mid-tier launch`,description:`Introduce a third pricing tier at $14/mo (between Free and the existing $29/mo Pro), unlocking 60% of Pro features. Bundle with 90-day grandfathering for current Pro subs and a quarterly migration check-in. 6-month pilot before deciding to globalize.`,durationValue:`6`,durationUnit:`months`,adherence:`0.72`},signalsJson:JSON.stringify([{label:`Free → Paid conversion`,value:.034,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Monthly churn`,value:.038,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`NPS`,value:41,unit:`score`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)}};function Tg(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function Eg(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dg({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Sg),[a,o]=(0,b.useState)(Cg),[s,c]=(0,b.useState)(`[]`),[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(0),[p,m]=(0,b.useState)(null),h=e=>{let t=wg[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Sg),o(Cg),c(`[]`),m(null)},_=r.id.trim().length>0&&r.name.trim().length>0&&a.id.trim().length>0&&a.name.trim().length>0&&a.description.trim().length>0;return(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.heading,children:[(0,x.jsx)(`h3`,{className:G.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:G.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:G.copy,children:`Define a subject (patient, market segment, jurisdiction, vehicle, anything) and an intervention to apply to it. Paracosm runs a real LLM-driven simulation across a five-department analysis team and returns a typed RunArtifact with the trajectory.`}),(0,x.jsxs)(`div`,{className:G.presetRow,children:[(0,x.jsx)(`span`,{className:G.presetLabel,children:`Examples`}),Object.entries(wg).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${G.presetButton} ${p===e?G.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:G.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:G.presetBlurb,children:wg[p].blurb}),(0,x.jsxs)(`div`,{className:G.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:r.id,onChange:e=>i(t=>({...t,id:e.target.value})),placeholder:`patient-001`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:r.name,onChange:e=>i(t=>({...t,name:e.target.value})),placeholder:`Maria Chen`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:r.description,onChange:e=>i(t=>({...t,description:e.target.value})),placeholder:`Age, key attributes, baseline state.`,className:G.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Profile (JSON)`}),(0,x.jsx)(`textarea`,{value:r.profileJson,onChange:e=>i(t=>({...t,profileJson:e.target.value})),placeholder:`{"age": 58, "bmi": 31}`,className:`${G.textarea} ${G.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${G.textarea} ${G.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:a.id,onChange:e=>o(t=>({...t,id:e.target.value})),placeholder:`semaglutide-12wk`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:a.name,onChange:e=>o(t=>({...t,name:e.target.value})),placeholder:`12-week semaglutide protocol`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:a.description,onChange:e=>o(t=>({...t,description:e.target.value})),placeholder:`What is being applied, by whom, with what monitoring.`,className:G.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:G.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:G.input})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:G.input,children:[(0,x.jsx)(`option`,{value:`days`,children:`days`}),(0,x.jsx)(`option`,{value:`weeks`,children:`weeks`}),(0,x.jsx)(`option`,{value:`months`,children:`months`}),(0,x.jsx)(`option`,{value:`quarters`,children:`quarters`}),(0,x.jsx)(`option`,{value:`years`,children:`years`})]})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Adherence`}),(0,x.jsx)(`input`,{type:`number`,min:`0`,max:`1`,step:`0.05`,value:a.adherence,onChange:e=>o(t=>({...t,adherence:e.target.value})),className:G.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:G.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=Tg(r.profileJson,{}),o=Tg(s,[]),c={id:r.id.trim(),name:r.name.trim(),profile:r.description.trim()?{...i,description:r.description.trim()}:i,signals:o,markers:[]},d=Number(a.durationValue),p=Number(a.adherence),m={id:a.id.trim(),name:a.name.trim(),description:a.description.trim(),duration:Number.isFinite(d)&&d>0?{value:d,unit:a.durationUnit.trim()||`weeks`}:void 0,adherenceProfile:Number.isFinite(p)?{expected:Math.max(0,Math.min(1,p))}:void 0};u(!0),f(0);let h=Date.now(),g=window.setInterval(()=>{f(Math.round((Date.now()-h)/1e3))},500),v=Eg();await n?.({runKey:v,subject:{id:c.id,name:c.name,profile:c.profile},intervention:{id:m.id,name:m.name,description:m.description,duration:m.duration}});try{let t=await fetch(`/api/quickstart/simulate-intervention`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subject:c,intervention:m,runKey:v,options:{maxTurns:2,seed:11,costPreset:`economy`},...bg(_g(window.localStorage))})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Digital twin run failed: HTTP ${t.status}`)}let n=await t.json();k(window,n.visitorId),e(n.artifact,v)}catch(e){t?.(e instanceof Error?e.message:String(e),v)}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:G.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:G.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:G.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:G.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function Og(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function kg(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Ag={card:`_card_1qdw6_1`,eyebrow:`_eyebrow_1qdw6_27`,row:`_row_1qdw6_36`,actor:`_actor_1qdw6_45`,arrow:`_arrow_1qdw6_56`,meta:`_meta_1qdw6_62`};function jg(){let{sessions:e}=Oe(),t=e[0]?.id?e[0]:null;if(!t)return null;let n=typeof window<`u`?kg(window.location.href,t.id):`?replay=${encodeURIComponent(t.id)}`,r=t.seedText?t.seedText.length>70?`${t.seedText.slice(0,70).trim()}…`:t.seedText.trim():null,i=Rn(t,3),a=t.title||t.scenarioName||i||r||t.id,o=[t.scenarioName&&t.scenarioName!==a?t.scenarioName:null,typeof t.eventCount==`number`?`${t.eventCount} events`:null,typeof t.durationMs==`number`?`${Math.round(t.durationMs/1e3)}s`:null,typeof t.createdAt==`number`?new Date(t.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Ag.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Ag.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Ag.row,children:[(0,x.jsx)(`span`,{className:Ag.actor,children:a}),(0,x.jsx)(`span`,{className:Ag.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Ag.meta,children:o})]})}var Mg={card:`_card_14dqa_7`,statusPending:`_statusPending_14dqa_18`,statusActive:`_statusActive_14dqa_22`,statusDone:`_statusDone_14dqa_27`,header:`_header_14dqa_31`,marker:`_marker_14dqa_60`,pulseDot:`_pulseDot_14dqa_1`,label:`_label_14dqa_93`,duration:`_duration_14dqa_100`,count:`_count_14dqa_121`,chevron:`_chevron_14dqa_137`,chevronOpen:`_chevronOpen_14dqa_148`,actorChips:`_actorChips_14dqa_164`,actorChip:`_actorChip_14dqa_164`,actorChipName:`_actorChipName_14dqa_190`,actorChipState:`_actorChipState_14dqa_194`,actor_running:`_actor_running_14dqa_203`,actor_complete:`_actor_complete_14dqa_212`,actor_error:`_actor_error_14dqa_221`,actor_aborted:`_actor_aborted_14dqa_230`,body:`_body_14dqa_241`,line:`_line_14dqa_266`,lineTs:`_lineTs_14dqa_283`,lineGlyph:`_lineGlyph_14dqa_290`,lineTag:`_lineTag_14dqa_296`,lineActor:`_lineActor_14dqa_309`,lineBody:`_lineBody_14dqa_324`,tonePending:`_tonePending_14dqa_332`,toneInfo:`_toneInfo_14dqa_336`,toneActive:`_toneActive_14dqa_345`,toneDone:`_toneDone_14dqa_358`,toneWarn:`_toneWarn_14dqa_367`,toneError:`_toneError_14dqa_380`},Ng={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Pg({stageId:e,label:t,status:n,logLines:r,duration:i,actors:a}){let[o,s]=(0,b.useState)(n!==`pending`),c=(0,b.useRef)(null),l=(0,b.useRef)(!0);(0,b.useEffect)(()=>{(n===`active`||n===`done`)&&s(e=>e||!0)},[n]);let u=()=>{let e=c.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)};(0,b.useEffect)(()=>{if(!l.current)return;let e=c.current;e&&(e.scrollTop=e.scrollHeight)},[r.length]);let d=n===`done`?`✓`:n===`active`?`●`:`○`,f=n===`done`?Mg.statusDone:n===`active`?Mg.statusActive:Mg.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${Mg.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:Mg.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:Mg.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:Mg.label,children:t}),i&&(0,x.jsx)(`span`,{className:Mg.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:Mg.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${Mg.chevron} ${o?Mg.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:Mg.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${Mg.actorChip} ${Mg[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:Mg.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:Mg.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Ng[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:Mg.body,ref:c,onScroll:u,role:`log`,"aria-live":n===`active`?`polite`:`off`,"aria-label":`${t} log`,children:[r.length===0&&(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg.tonePending}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg[`tone${Fg(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:Mg.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:Mg.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:e.body})]},t))]})]})}function Fg(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ig(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=e/1e3,n=Math.floor(t/60),r=Math.floor(t%60),i=Math.floor(t*10%10);return`${n}:${String(r).padStart(2,`0`)}.${i}`}function Lg(e){return e===`turn_start`||e===`turn_done`?`active`:e===`specialist_done`||e===`sim_complete`||e===`agent_reactions`?`done`:e===`decision_pending`||e===`decision_made`||e===`outcome`?`info`:e===`sim_aborted`||e===`provider_error`||e===`validation_fallback`?`warn`:`info`}function Rg(e){switch(e){case`turn_start`:return`TURN`;case`turn_done`:return`TURN`;case`specialist_start`:return`SPEC`;case`specialist_done`:return`SPEC`;case`decision_pending`:return`DEC`;case`decision_made`:return`DEC`;case`outcome`:return`OUT`;case`agent_reactions`:return`REACT`;case`bulletin`:return`NEWS`;case`promotion`:return`PROMO`;case`systems_snapshot`:return`SNAP`;case`drift`:return`DRIFT`;case`personality_drift`:return`DRIFT`;case`sim_aborted`:return`ABORT`;case`provider_error`:return`ERR`;case`validation_fallback`:return`FALLBACK`;case`sim_complete`:return`DONE`;default:return e.toUpperCase().slice(0,8)}}function zg(e){let t=e.data??{};return(typeof t.summary==`string`?t.summary:``)||(typeof t.department==`string`?t.department:typeof t.title==`string`?t.title:typeof t.decision==`string`?t.decision:typeof t.outcome==`string`?t.outcome:typeof t.eventType==`string`?t.eventType:typeof t.tool==`string`?t.tool:``)}function Bg(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=zg(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:e.type===`validation_fallback`&&e.data?.salvaged===!0?`SALVAGE`:Rg(e.type),body:r,tone:Lg(e.type),actor:typeof n==`string`?n:void 0}}function Vg(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Ig(a-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/compile-from-seed`,tone:t===`compile`?`active`:`info`});let o=r?.research;return o&&i.push({ts:Ig(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Hg(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Ig(o-n);if(i?.skipped)return a.push({ts:s,glyph:`⚠`,tag:`SKIP`,body:`Deep research skipped: ${i.reason??`unknown`}`,tone:`warn`}),a;if(i?.citations&&i.citations.length>0){let e=i.providersUsed?.length?` · providers: ${i.providersUsed.join(` + `)}`:``;a.push({ts:s,glyph:`→`,tag:`POST`,body:`/api/quickstart/ground-scenario · ${i.citations.length} queries${e}`,tone:t===`research`?`active`:`info`});for(let e of i.providersFailed??[])a.push({ts:s,glyph:`⚠`,tag:e.provider.toUpperCase().slice(0,8),body:`provider unavailable: ${e.reason.slice(0,120)}`,tone:`warn`});for(let e of i.citations){a.push({ts:s,glyph:`·`,tag:`QUERY`,body:`"${e.query}" → ${e.sources.length} source${e.sources.length===1?``:`s`}`,tone:`info`});for(let t of e.sources.slice(0,3)){let e=(t.provider??``).toUpperCase()||t.domain.toUpperCase().slice(0,16)||`SRC`;a.push({ts:s,glyph:`·`,tag:e,body:t.title,tone:`done`})}}if(typeof i.totalSources==`number`){let e=typeof i.durationMs==`number`?` · ${(i.durationMs/1e3).toFixed(1)}s`:``;a.push({ts:s,glyph:`✓`,tag:`OK`,body:`${i.totalSources} unique sources attached to ScenarioPackage${e}`,tone:`done`})}return a}a.push({ts:s,glyph:`·`,tag:`NOTE`,body:`Grounding scenario with web research…`,tone:t===`research`?`active`:`info`});let c=r?.actors;return c&&a.push({ts:Ig(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Ug(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Ig(o-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/generate-actors · count=${i}`,tone:t===`actors`?`active`:`info`});let s=r?.running;return s&&a.push({ts:Ig(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Wg(e){return e.events.map(e=>Bg(e)).filter(e=>!!e)}function Gg(e,t){switch(e){case`compile`:return Vg(t);case`research`:return Hg(t);case`actors`:return Ug(t);case`running`:return Wg(t);case`done`:return[]}}function Kg(e,t){let n=[`compile`,`research`,`actors`,`running`,`done`],r=n.indexOf(e),i=t.phaseTransitionMs?.[e],a=n[r+1],o=a?t.phaseTransitionMs?.[a]:void 0;if(!i)return``;let s=((o??Date.now())-i)/1e3;return s<1?`${Math.max(1,Math.round(s*1e3))}ms`:s<10?`${s.toFixed(1)}s`:`${Math.round(s)}s`}var qg={progress:`_progress_5dmny_6`,heading:`_heading_5dmny_19`,title:`_title_5dmny_26`,subtitle:`_subtitle_5dmny_35`,stageList:`_stageList_5dmny_43`,stageItem:`_stageItem_5dmny_55`,cancel:`_cancel_5dmny_59`,jumpToSim:`_jumpToSim_5dmny_84`},Jg=[`compile`,`research`,`actors`,`running`,`done`];function Yg(e,t){let n=Jg.indexOf(e),r=Jg.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Xg({stage:e,actors:t,events:n,actorCount:r,groundingSummary:i,onCancel:a}){let o=(0,b.useRef)(Date.now()),[s,c]=(0,b.useState)(()=>({compile:Date.now()})),l=(0,b.useRef)(e);(0,b.useEffect)(()=>{l.current!==e&&(l.current=e,c(t=>t[e]?t:{...t,[e]:Date.now()}))},[e]);let[,u]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(e===`done`)return;let t=setInterval(()=>u(e=>(e+1)%1e6),1e3);return()=>clearInterval(t)},[e]);let d=r??t?.length??3,f=nA(),p=(0,b.useMemo)(()=>({stage:e,startMs:o.current,phaseTransitionMs:s,actorCount:d,events:n??[],groundingSummary:i??null}),[e,s,d,n,i]),m=[{id:`compile`,label:`Compile scenario`},{id:`research`,label:`Ground with citations`},{id:`actors`,label:`Generate ${d} actor${d===1?``:`s`}`},{id:`running`,label:`Run ${d} simulation${d===1?``:`s`}`}];return(0,x.jsxs)(`section`,{className:qg.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:qg.heading,children:[(0,x.jsx)(`span`,{className:qg.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:qg.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:qg.stageList,children:m.map(n=>{let r=Yg(e,n.id);return(0,x.jsx)(`li`,{className:qg.stageItem,children:(0,x.jsx)(Pg,{stageId:n.id,label:n.label,status:r,logLines:Gg(n.id,p),duration:Kg(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:qg.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:qg.cancel,onClick:a,children:`Cancel run`})]})}var Zg=Object.freeze({visionary:{id:`visionary`,name:`Aria Okafor`,archetype:`The Visionary`,description:`Bets on bold experiments. Tolerates ambiguity. Casts a wide pattern net.`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},pragmatist:{id:`pragmatist`,name:`Marcus Reyes`,archetype:`The Pragmatist`,description:`Leads by protocol and evidence. Safety margins first.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.35,agreeableness:.6,emotionality:.5,honestyHumility:.85}},innovator:{id:`innovator`,name:`Yuki Tanaka`,archetype:`The Innovator`,description:`Pushes novel tool forging. Accepts higher variance.`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.7,agreeableness:.45,emotionality:.35,honestyHumility:.55}},stabilizer:{id:`stabilizer`,name:`Elena Voss`,archetype:`The Stabilizer`,description:`Holds the line. Protects existing capacity. Change-averse.`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.75,emotionality:.55,honestyHumility:.7}},"crisis-manager":{id:`crisis-manager`,name:`Nadia Chen`,archetype:`The Crisis Manager`,description:`Thrives under pressure. Decisive. Low emotional reactivity.`,hexaco:{openness:.55,conscientiousness:.8,extraversion:.75,agreeableness:.45,emotionality:.25,honestyHumility:.6}},"growth-optimist":{id:`growth-optimist`,name:`Diego Santoro`,archetype:`The Growth Optimist`,description:`Chases expansion. High risk tolerance. Charismatic rally-er.`,hexaco:{openness:.8,conscientiousness:.5,extraversion:.9,agreeableness:.55,emotionality:.35,honestyHumility:.4}},"protocol-builder":{id:`protocol-builder`,name:`Priya Rao`,archetype:`The Protocol Builder`,description:`Codifies everything. Demands evidence. Slow to decide, hard to dislodge.`,hexaco:{openness:.5,conscientiousness:.95,extraversion:.35,agreeableness:.6,emotionality:.45,honestyHumility:.9}},"social-architect":{id:`social-architect`,name:`Kai Rivers`,archetype:`The Social Architect`,description:`Builds coalitions. Manages morale. Relationship-first.`,hexaco:{openness:.6,conscientiousness:.65,extraversion:.8,agreeableness:.9,emotionality:.55,honestyHumility:.7}},"cost-cutter":{id:`cost-cutter`,name:`Hannah Novak`,archetype:`The Cost Cutter`,description:`Optimizes ruthlessly. Will trade morale for capacity.`,hexaco:{openness:.35,conscientiousness:.9,extraversion:.45,agreeableness:.3,emotionality:.25,honestyHumility:.55}},"compliance-hawk":{id:`compliance-hawk`,name:`Owen Ibarra`,archetype:`The Compliance Hawk`,description:`Audits every decision. Never cuts corners. Reports failures transparently.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.45,agreeableness:.65,emotionality:.5,honestyHumility:.95}}}),Qg={backdrop:`_backdrop_fgbmo_1`,dialog:`_dialog_fgbmo_12`,header:`_header_fgbmo_23`,list:`_list_fgbmo_47`,preset:`_preset_fgbmo_56`,archetype:`_archetype_fgbmo_82`,description:`_description_fgbmo_87`};function $g({onSelect:e,onClose:t}){let n=Pt(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Qg.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Qg.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Qg.header,children:[(0,x.jsx)(`h3`,{children:`Swap leader`}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,children:`×`})]}),(0,x.jsx)(`ul`,{className:Qg.list,children:Object.values(Zg).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Qg.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Qg.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Qg.description,children:t.description})]})},t.id))})]})})}var e_={results:`_results_8jenm_2`,runSummary:`_runSummary_8jenm_15`,summaryStat:`_summaryStat_8jenm_26`,summaryNum:`_summaryNum_8jenm_40`,summaryLabel:`_summaryLabel_8jenm_50`,grid:`_grid_8jenm_61`,card:`_card_8jenm_81`,cardHeader:`_cardHeader_8jenm_92`,actorName:`_actorName_8jenm_106`,archetype:`_archetype_8jenm_110`,swap:`_swap_8jenm_119`,hexaco:`_hexaco_8jenm_142`,trait:`_trait_8jenm_151`,traitLabel:`_traitLabel_8jenm_160`,traitBarOuter:`_traitBarOuter_8jenm_168`,traitBarInner:`_traitBarInner_8jenm_175`,fingerprint:`_fingerprint_8jenm_180`,deltas:`_deltas_8jenm_192`,delta:`_delta_8jenm_192`,direction_up:`_direction_up_8jenm_209`,direction_down:`_direction_down_8jenm_213`,direction_changed:`_direction_changed_8jenm_217`,actions:`_actions_8jenm_222`,forkButton:`_forkButton_8jenm_249`,forkHint:`_forkHint_8jenm_259`},t_=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function n_({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=Gn(),a=nA(),o=Lm(),[s,c]=(0,b.useState)(null),l=on(),u=l.clear,[d,f]=(0,b.useState)(null);(0,b.useEffect)(()=>{u()},[n,u]);let p=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},m=e=>{n&&(f(e),l.share(vh(window.location.origin,n)))},h=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;yh(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},g=(0,b.useMemo)(()=>({totalTools:t.reduce((e,t)=>e+(t?.forgedTools?.length??0),0),totalCitations:t.reduce((e,t)=>e+(t?.citations?.length??0),0),totalDecisions:t.reduce((e,t)=>e+(t?.decisions?.length??0),0),totalTurns:t.reduce((e,t)=>e+(t?.trajectory?.timepoints?.length??0),0),totalCostUSD:t.reduce((e,t)=>e+(t?.cost?.totalUSD??0),0)}),[t]);return(0,x.jsxs)(`div`,{className:e_.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:e_.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Web sources Paracosm pulled via Serper + Tavily and attached to the scenario before generating actors. Grounds the sim in real-world knowledge instead of pure LLM imagination.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalCitations}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one at runtime, run in a QuickJS WebAssembly sandbox. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTools}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalDecisions}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total simulation turns across all 3 parallel actors. Each turn = one decision cycle: department analysis, commander decision, kernel advance, agent reactions.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTurns}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`turns simulated`})]}),g.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total LLM spend across all 3 actors. Provider: gpt-5.4-mini for sims, gpt-4o for verdict.`,children:[(0,x.jsxs)(`span`,{className:e_.summaryNum,children:[`$`,g.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:e_.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(r_,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,shareEnabled:!!n,onDownload:()=>h(r),onShare:()=>m(r),shareNote:d===r&&l.shared?(0,x.jsx)(dn,{shared:l.shared,onClose:l.clear}):null,onFork:()=>p(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)($g,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function r_({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,shareEnabled:a,shareNote:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>_h(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:e_.card,children:[(0,x.jsxs)(`header`,{className:e_.cardHeader,children:[(0,x.jsx)(`h4`,{className:e_.actorName,children:e.name}),(0,x.jsx)(`span`,{className:e_.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:e_.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:e_.hexaco,children:t_.map(t=>(0,x.jsxs)(`div`,{className:e_.trait,children:[(0,x.jsx)(`span`,{className:e_.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:e_.traitBarOuter,children:(0,x.jsx)(`div`,{className:e_.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:e_.fingerprint,children:[(0,x.jsx)(`span`,{children:`FP`}),(0,x.jsx)(`code`,{children:t.fingerprint?Object.values(t.fingerprint).slice(0,3).join(` / `):`n/a`})]}),d.length>0&&(0,x.jsx)(`ul`,{className:e_.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${e_.delta} ${e_[`direction_${e.direction}`]}`,children:Bm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:e_.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!a,title:`Copy a deep link that opens this run on the visualization tab`,children:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:e_.forkButton,title:f===0?`No turns completed yet`:`Promote to fork root and open Branches tab. ${f} ${f===1?r:`${r}s`} available.`,children:`Fork in Branches →`})]}),o,(0,x.jsx)(`div`,{className:e_.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var i_=2e3,a_=3e5;function o_(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}async function s_(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{throw Error(`Compile returned non-JSON HTTP ${e.status} response`)}if(!e.ok&&(!n||typeof n!=`object`))throw Error(`Compile failed: HTTP ${e.status}`);if(!n||typeof n!=`object`)throw Error(`Compile returned empty body`);return n}async function c_(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??i_,i=t.timeoutMs??a_,a=t.waitImpl??o_,o=Date.now(),s=await n(`/api/quickstart/compile-from-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t.signal});if(!s.ok&&s.status!==202){let e=await s.json().catch(()=>({}));throw Error(e.error??`Compile failed: HTTP ${s.status}`)}let c=await s_(s);if(c.status===`done`&&c.scenario)return{scenario:c.scenario,scenarioId:c.scenario.id,jobId:c.jobId};if(c.status===`error`)throw Error(c.error??`Compile failed`);for(;Date.now()-o<i;){await a(r,t.signal);let e=await n(`/api/quickstart/compile-from-seed/status`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jobId:c.jobId}),signal:t.signal});if(!e.ok){if(e.status===404)throw Error(`Compile job expired or not found. Please retry.`);let t=await e.json().catch(()=>({}));throw Error(t.error??`Compile status check failed: HTTP ${e.status}`)}let i=await s_(e);if(i.status===`done`&&i.scenario)return{scenario:i.scenario,scenarioId:i.scenario.id,jobId:i.jobId};if(i.status===`error`)throw Error(i.error??`Compile failed`)}throw Error(`Compile is taking longer than ${Math.round(i/1e3)}s. The server may still be working — please retry in a minute.`)}var l_={view:`_view_1gdit_2`,header:`_header_1gdit_12`,howItWorks:`_howItWorks_1gdit_36`,glossary:`_glossary_1gdit_43`,timingHint:`_timingHint_1gdit_44`,howItWorksSummary:`_howItWorksSummary_1gdit_60`,errorBanner:`_errorBanner_1gdit_137`,compareCta:`_compareCta_1gdit_149`};function u_(e){return/Failed to fetch|NetworkError|ERR_CONNECTION|ERR_NETWORK/i.test(e)?`Couldn't reach the server. Check your connection and try again.`:/HTTP 502|HTTP 503|HTTP 504/.test(e)?`Server is temporarily unavailable (502/503/504). Try again in a moment.`:/HTTP 429|rate.?limit/i.test(e)?`Hosted demo is rate-limited (3 runs/day). Drop your own API key in Settings to bypass — your saved keys flow into the run automatically.`:/HTTP 401|HTTP 403|unauthor/i.test(e)?`Auth error talking to the LLM provider. Check your API key in Settings.`:/Two actors required|at least 2 actors/i.test(e)?`This scenario needs at least 2 actors. Bump the slider before launching.`:/TypeError|ReferenceError|Cannot read propert|is not a function|is not iterable/i.test(e)?(typeof console<`u`&&console.error(`[quickstart] launch error:`,e),`Something went wrong starting the run. Refresh the page and try again — if it keeps happening, drop a note in the GitHub issues with what you clicked just before.`):e}function d_({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=Qk(),s=eA(),{toast:c}=Ht(),[l,u]=(0,b.useState)({kind:`input`}),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(!1),[_,v]=(0,b.useState)(null),y=`paracosm:catalogPendingRun`,S=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset();let r=typeof window<`u`?_g(window.localStorage):{},i=typeof window<`u`?dg(window.localStorage):null,a=bg(r),s={...a};r.serper&&(s.serperKey=r.serper),r.firecrawl&&(s.firecrawlKey=r.firecrawl),r.tavily&&(s.tavilyKey=r.tavily),r.cohere&&(s.cohereKey=r.cohere),i?.provider&&(s.provider=i.provider),i?.models&&typeof i.models==`object`&&(s.models=i.models),i?.economics&&typeof i.economics==`object`&&(s.economics=i.economics);let l=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(l.length>=t){u({kind:`progress`,stage:`running`});let n=l.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&mg(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:n,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Setup failed: HTTP ${e.status}`)}let t=await e.json().catch(()=>({}));if(t.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}else{u({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:o.id,count:t,...a})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${n.status}`)}let r=(await n.json().catch(()=>null))?.actors;if(!r||r.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`}),await e.reset(),typeof window<`u`&&mg(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:r,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${i.status}`)}let c=await i.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}},[o,e,n,c]),C=(0,b.useCallback)(async(e,t)=>{if(e===o.id)S(t);else{f(null),n?.();try{try{sessionStorage.setItem(y,JSON.stringify({scenarioId:e,actorCount:t,ts:Date.now()}))}catch{}let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})});if(!n.ok){try{sessionStorage.removeItem(y)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=u_(e?.message??String(e));f(t),c(`error`,`Scenario switch failed`,t,8e3)}}},[o.id,S,n,c]);(0,b.useEffect)(()=>{if(!s)return;let e=null;try{let t=sessionStorage.getItem(y);if(!t)return;sessionStorage.removeItem(y),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==o.id){c(`error`,`Scenario changed`,`Another tab of this browser picked a different scenario before the run you picked could start, so nothing ran. Pick it in the catalog again.`,8e3);return}let t=typeof e?.actorCount==`number`&&e.actorCount>0?Math.min(300,Math.max(1,e.actorCount)):null;t!==null&&S(t)},[s]);let w=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset(),u({kind:`progress`,stage:`compile`});try{let n=typeof window<`u`?bg(_g(window.localStorage)):{},{scenario:r,scenarioId:i}=await c_({...t,...n});u({kind:`progress`,stage:`research`,scenario:r});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:r});let a=Math.max(1,Math.min(300,t.actorCount??2)),o=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i,count:a,...n})});if(!o.ok){let e=await o.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${o.status}`)}let s=(await o.json().catch(()=>null))?.actors;if(!s||s.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:r,actors:s}),await e.reset(),typeof window<`u`&&mg(window.localStorage,s,i);let c=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,actors:s,turns:r.setup.defaultTurns,seed:r.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:i}})});if(!c.ok){let e=await c.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${c.status}`)}let l=await c.json().catch(()=>({}));if(l.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,l.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Quickstart failed`,t,8e3)}},[e,n,c]);(0,b.useEffect)(()=>{if(l.kind!==`progress`||l.stage!==`running`||!l.scenario||!l.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=l.actors.length&&u({kind:`results`,scenario:l.scenario,actors:l.actors,artifacts:t.slice(0,l.actors.length)})},[e.results,l]),(0,b.useEffect)(()=>{if(l.kind!==`results`||p!==null)return;let e=l.artifacts[0]?.metadata?.runId;if(!e)return;let t=!1;return fetch(`/api/v1/runs/${encodeURIComponent(e)}`).then(async e=>e.ok?e.json():null).then(e=>{if(t)return;let n=e?.record?.bundleId;n&&m(n)}).catch(()=>{}),()=>{t=!0}},[l,p]);let T=l.kind===`progress`&&l.stage===`running`&&l.actors?l.actors.map((t,n)=>{let r=e.events.filter(e=>e.type===`turn_done`||e.type===`turn_start`).reduce((e,t)=>{let n=t.data?.turn??0;return n>e?n:e},0),i=e.results.find(e=>e.actorIndex===n),a=e.errors.length>0&&!i?`error`:e.isAborted?`aborted`:i?`complete`:`running`;return{name:t.name,archetype:t.archetype,currentTurn:i?l.scenario?.setup.defaultTurns??r:r,maxTurns:l.scenario?.setup.defaultTurns??6,status:a}}):void 0,E=(0,b.useCallback)((e,t)=>{f(`Actor swap rerun is a v1.1 follow-up. Use "Fork in Branches" on the Branches tab to try a preset actor against this run.`)},[]);return(0,x.jsxs)(`div`,{className:l_.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:l_.header,children:[(0,x.jsx)(`h2`,{children:`Quickstart`}),(0,x.jsx)(`p`,{children:`Paste a what-if scenario. Paracosm compiles it into a typed world and runs LLM-driven decision-makers with measurable personalities against it, returning a replayable trajectory you can fork and compare.`}),(0,x.jsxs)(`details`,{className:l_.howItWorks,children:[(0,x.jsx)(`summary`,{className:l_.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:l_.glossary,"aria-label":`Key terms`,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Scenario`}),` — the world Paracosm compiles from your prompt: departments, agents, events, starting state.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Actor`}),` — an LLM decision-maker driving the scenario, weighted by a HEXACO personality vector.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run`}),` — one actor playing the scenario turn by turn. Paracosm runs N actors in parallel against the same world so you can compare divergent outcomes.`]})]}),(0,x.jsxs)(`p`,{className:l_.timingHint,children:[(0,x.jsx)(`strong`,{children:`Heads-up:`}),` a fresh run takes `,(0,x.jsx)(`strong`,{children:`2-5 minutes`}),` (compile, ground with citations, generate actors, simulate). For instant results, replay a cached run below.`]})]})]}),d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),(0,x.jsx)(jg,{}),(0,x.jsx)(ig,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(Dg,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Xg,{stage:l.stage,actors:T,events:e.events,actorCount:l.actors?.length??T?.length??2,groundingSummary:_}),l.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:l_.compareCta,onClick:()=>g(!0),"aria-label":`Compare all ${l.artifacts.length} actors side-by-side`,children:[`Compare all `,l.artifacts.length,` actors →`]}),(0,x.jsx)(n_,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:E}),p&&h&&(0,x.jsx)(ra,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var f_={getNumber:()=>0,getEntry:()=>void 0,list:[]};function p_(e){return(0,b.useMemo)(()=>{let t=new Map,n=[],r=1;for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`specialist_done`)continue;let a=String(e.data?.department||``),o=e.data?.citationList||[];for(let e of o){let o=(e.url||``).trim(),s=(e.text||``).trim();if(!o&&!s||!o&&s===`Seed document`)continue;let c=o||`text:${s}`,l=t.get(c);l||(l={n:r++,text:s||o,url:o,doi:e.doi,departments:new Set,actorNames:new Set},t.set(c,l),n.push(l)),a&&l.departments.add(a),l.actorNames.add(i),!l.doi&&e.doi&&(l.doi=e.doi)}}}return{getNumber:e=>e?(t.get(e)||t.get(`text:${e}`))?.n??0:0,getEntry:e=>t.get(e)||t.get(`text:${e}`),list:n}},[e])}var m_=(0,b.createContext)(f_);function h_(){return(0,b.useContext)(m_)}var g_=()=>({tools:0,forges:0,reforges:0,passed:0,didNotPass:0});function __(e){let t=String(e??``).trim();return t===`unnamed`?``:t}var v_=e=>Array.isArray(e)?e:[];function y_(e){if(e.type!==`specialist_done`)return!1;let t=e.data?.forgedTools;return t!=null&&!Array.isArray(t)}function b_(e,t,n,r){return{n:0,name:e,description:String(r.description||e),mode:String(r.mode||`sandbox`),firstForgedTurn:r.turn,firstForgedDepartment:r.department,departments:new Set,actorNames:new Set([n]),reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:r.confidence,approved:r.approved,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:r.errorReason,inputFields:v_(r.inputFields),outputFields:v_(r.outputFields),history:[],actorIndex:t,actorName:n,attempts:[],outcome:r.approved?`passed`:`did_not_pass`,sameNameActors:[]}}function x_(e,t,n){let r=new Map;for(let t of e){if(t.type!==`event_start`)continue;let e=`${Number(t.data?.turn??t.turn??0)}:${Number(t.data?.eventIndex??0)}`;r.has(e)||r.set(e,String(t.data?.title??``))}let i=new Map,a=[],o=new Map,s=[];for(let c of e){let e=c.data??{};if(c.type===`forge_attempt`){let o=__(e.name);if(!o)continue;let l=Number(e.turn??c.turn??0),u=Number(e.eventIndex??0),d=String(e.department??``),f=e.approved===!0,p=typeof e.confidence==`number`?e.confidence:null,m=typeof e.errorReason==`string`&&e.errorReason?e.errorReason:null,h=i.get(o);h||(h=b_(o,t,n,{description:e.description,mode:e.mode,turn:l,department:d,confidence:p??0,approved:f,errorReason:m??void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(o,h),a.push(h));let g={attempt:h.attempts.length+1,turn:l,time:Number(e.time??0),eventIndex:u,department:d,eventTitle:r.get(`${l}:${u}`)??``,approved:f,confidence:p,errorReason:m,description:String(e.description??``),inputFields:v_(e.inputFields),outputFields:v_(e.outputFields),eventId:c.id};h.attempts.push(g),d&&h.departments.add(d),p!==null&&p>h.confidence&&(h.confidence=p),f?(h.approved=!0,h.errorReason=void 0):!h.approved&&m&&(h.errorReason=m),s.push(f?`passed`:`did_not_pass`);continue}if(c.type!==`specialist_done`)continue;let l=Array.isArray(e._filteredTools)?e._filteredTools:[],u=String(e.department||``);for(let e of l){let r=__(e.name);if(!r)continue;let s=e.approved!==!1,l=i.get(r);if(l?(o.has(l)||(typeof e.description==`string`&&e.description&&(l.description=e.description),typeof e.mode==`string`&&e.mode&&(l.mode=e.mode),typeof e.firstForgedTurn==`number`&&(l.firstForgedTurn=e.firstForgedTurn),typeof e.firstForgedDepartment==`string`&&e.firstForgedDepartment&&(l.firstForgedDepartment=e.firstForgedDepartment),Array.isArray(e.inputFields)&&(l.inputFields=e.inputFields),Array.isArray(e.outputFields)&&(l.outputFields=e.outputFields)),typeof e.confidence==`number`&&e.confidence>l.confidence&&(l.confidence=e.confidence),s&&(l.approved=!0),l.approved?l.errorReason=void 0:typeof e.errorReason==`string`&&e.errorReason&&(l.errorReason=e.errorReason)):(l=b_(r,t,n,{description:e.description,mode:e.mode,turn:typeof e.firstForgedTurn==`number`?e.firstForgedTurn:c.turn??0,department:String(e.firstForgedDepartment||u),confidence:typeof e.confidence==`number`?e.confidence:s?.85:0,approved:s,errorReason:typeof e.errorReason==`string`?e.errorReason:void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(r,l),a.push(l)),typeof e.output==`string`&&(e.output||l.sampleOutput===null)&&(l.sampleOutput=e.output),!l.inputSchema&&e.inputSchema&&(l.inputSchema=e.inputSchema),!l.outputSchema&&e.outputSchema&&(l.outputSchema=e.outputSchema),u&&l.departments.add(u),o.set(l,s),Array.isArray(e.history)){let t=e.history;l.history=t.map(e=>({...e,actorName:n})),l.reuseCount=Math.max(0,t.length-1),l.reforgeCount=t.filter(e=>e.isReforge).length,l.rejectedReforges=t.filter(e=>e.isReforge&&e.rejected).length}}}for(let e of a){o.has(e)||(e.history=e.attempts.map((e,t)=>({turn:e.turn,time:e.time,eventIndex:e.eventIndex,eventTitle:e.eventTitle,department:e.department,output:null,isReforge:t>0,rejected:!e.approved,confidence:e.confidence??void 0,actorName:n})),e.reforgeCount=Math.max(0,e.attempts.length-1),e.rejectedReforges=e.attempts.filter(e=>!e.approved).length);let t=e.attempts[e.attempts.length-1];e.outcome=(t?t.approved:o.get(e)!==!1)?`passed`:`did_not_pass`}return{entries:a,strip:s}}function S_(e,t){e.tools+=t.tools,e.forges+=t.forges,e.reforges+=t.reforges,e.passed+=t.passed,e.didNotPass+=t.didNotPass}function C_(e){let t=[],n=[],r=g_(),i=new Map,a=new Map,o=(e,t)=>`${e}\u0000${t}`;e.actorIds.forEach((s,c)=>{let l=e.actors[s],u=l?.events??[],d=u.some(y_),{entries:f,strip:p}=d?{entries:[],strip:[]}:x_(u,c,s),m=g_();for(let e of f){e.n=t.length+1,t.push(e),i.set(o(c,e.name),e);let n=a.get(e.name);n?n.push(e):a.set(e.name,[e]);let r=e.attempts.filter(e=>e.approved).length;S_(m,{tools:1,forges:e.attempts.length,reforges:Math.max(0,e.attempts.length-1),passed:r,didNotPass:e.attempts.length-r})}S_(r,m),n.push({index:c,label:`A${c+1}`,name:s,archetype:l?.leader?.archetype??``,counts:m,strip:p,status:e.isComplete?`done`:u.length===0?`waiting`:`running`,unreadable:d})});for(let e of a.values())for(let t of e)t.sameNameActors=e.filter(e=>e!==t).map(e=>e.actorIndex);return{getNumber:e=>a.get(e.trim())?.[0]?.n??0,getEntry:e=>a.get(e.trim())?.[0],getEntryFor:(e,t)=>i.get(o(e,t.trim())),getEntryByNumber:e=>Number.isInteger(e)&&e>=1?t[e-1]:void 0,list:t,actors:n,counts:r}}var w_={getNumber:()=>0,getEntry:()=>void 0,getEntryFor:()=>void 0,getEntryByNumber:()=>void 0,list:[],actors:[],counts:{tools:0,forges:0,reforges:0,passed:0,didNotPass:0}};function T_(e){return(0,b.useMemo)(()=>C_(e),[e])}var E_=(0,b.createContext)(w_);function D_(){return(0,b.useContext)(E_)}var O_=[`request`,`code`,`tests`,`judge`,`added`];function k_(e){return e===`passed`?`passed`:`didNotPass`}var A_=`request`;function j_(e){return e===`passed`?{stations:{request:`reached`,code:`reached`,tests:`reached`,judge:`reached`,added:`reached`},stop:null,deciding:`judge`}:{stations:{request:`reached`,code:`unknown`,tests:`unknown`,judge:`unknown`,added:`notReached`},stop:null,deciding:`request`}}function M_(e,t){let n=e.attempts.length;return n===0?0:Number.isFinite(t)?Math.min(Math.max(Math.trunc(t),1),n):n}function N_(e,t){let n=e.attempts;if(n.length===0)return{...j_(e.outcome),spurs:[],branch:null};let r=M_(e,t),i=e=>e?`passed`:`did_not_pass`,a=n[r-1],o=n[r];return{...j_(i(a.approved)),spurs:n.slice(0,r-1).map(e=>({attempt:e.attempt,station:A_,outcome:i(e.approved)})),branch:o?{attempt:o.attempt,station:A_,outcome:i(o.approved)}:null}}function P_(e,t){return t<=2?Pe(e):`var(--forge-quiet)`}function F_(e){return e.history.slice(1).filter(e=>!e.isReforge).length}var I_={forge_toolbox_open:{from:[`sim`,`reports`,`viz`]},forge_trace_open:{from:[`toolbox`,`inspect`,`viz`,`link`]},forge_station_open:{station:O_,via:[`press`,`open_all`,`kept`]},forge_toolbox_filter:{show:[`all`,`passed`,`did_not_pass`]},forge_record_export:{what:[`toolbox`,`record_copy`,`record_download`]},forge_log_jump:{},forge_link_copy:{},forge_toolbox_group:{group:[`actor`,`department`,`none`]},forge_group_toggle:{scope:[`one`,`all`]},forge_actor_filter:{actors:[`1`,`2-4`,`5-24`,`25+`]},forge_actor_picker_open:{where:[`toolbox`,`compare`,`event_log`]}};function L_(e){return!Number.isFinite(e)||e<1?null:e===1?`1`:e<=4?`2-4`:e<=24?`5-24`:`25+`}function R_(e,t){try{let n=e.paracosmConsent;return typeof n?.allows==`function`&&n.allows(t)===!0}catch{return!1}}function z_(e){try{let{origin:t,pathname:n}=e.location;return typeof t==`string`&&typeof n==`string`?t+n:null}catch{return null}}function B_(e,t){let n=t??(typeof window>`u`?void 0:window);if(!n)return;let r=n,i=I_[e.name];if(!i)return;let a=R_(r,`measure`),o=R_(r,`record`);if(!a&&!o)return;let s={},c=e;for(let[e,t]of Object.entries(i)){let n=c[e];typeof n==`string`&&t.includes(n)&&(s[e]=n)}if(a&&typeof r.gtag==`function`){let t=z_(n);try{r.gtag(`event`,e.name,t===null?s:{...s,page_location:t})}catch{}}if(o&&typeof r.clarity==`function`)try{r.clarity(`event`,e.name)}catch{}}var V_={tool:`tool`,attempt:`attempt`,open:`open`,toolbox:`toolbox`,show:`show`,find:`find`,group:`group`,actors:`actors`},H_=Object.values(V_),U_=[V_.tool,V_.attempt,V_.open];function W_(e){if(e===null||!/^\d+$/.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t>=1?t:null}function G_(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase());return O_.filter(e=>t.includes(e))}function K_(e){let t=[];for(let n of e.split(`,`)){let e=W_(n);e!==null&&!t.includes(e)&&t.push(e)}return t}function q_(e,t,n){let r={trace:null,toolbox:{open:!1}},i=[],a;try{a=new URL(e).searchParams}catch{return{state:r,dangling:i}}r.toolbox.open=a.get(V_.toolbox)===`1`;for(let e of[V_.show,V_.find,V_.group]){let t=a.get(e);t!==null&&t!==``&&(r.toolbox[e]=t)}let o=a.get(V_.actors);if(o!==null){let e=K_(o),a=n?e.filter(e=>e<=t.actors.length):e;a.length>0?r.toolbox.actors=a:n&&i.push(V_.actors)}if(!n)return{state:r,dangling:i};let s=U_.filter(e=>a.has(e));if(s.length===0)return{state:r,dangling:i};let c=W_(a.get(V_.tool)),l=c===null?void 0:t.getEntryByNumber(c);if(!l)return i.push(...s),{state:r,dangling:i};let u;if(a.has(V_.attempt)){let e=W_(a.get(V_.attempt));if(e===null||e>l.attempts.length)return i.push(...s),{state:r,dangling:i};u=e}let d;if(a.has(V_.open)){let e=G_(a.get(V_.open)??``);e.length>0?d=e:i.push(V_.open)}return r.trace={actorIndex:l.actorIndex,toolName:l.name,...u===void 0?{}:{attempt:u},...d?{open:d}:{}},{state:r,dangling:i}}function J_(e,t,n){let r=new URL(e);for(let e of H_)r.searchParams.delete(e);let i=t.trace,a=i?n.getEntryFor(i.actorIndex,i.toolName):void 0;if(i&&a){r.searchParams.set(V_.tool,String(a.n)),i.attempt!==void 0&&i.attempt>=1&&i.attempt<a.attempts.length&&r.searchParams.set(V_.attempt,String(Math.trunc(i.attempt)));let e=O_.filter(e=>i.open?.includes(e));e.length>0&&r.searchParams.set(V_.open,e.join(`,`))}let o=t.toolbox;return o.open&&r.searchParams.set(V_.toolbox,`1`),o.show&&r.searchParams.set(V_.show,o.show),o.find&&r.searchParams.set(V_.find,o.find),o.group&&r.searchParams.set(V_.group,o.group),o.actors&&o.actors.length>0&&r.searchParams.set(V_.actors,o.actors.join(`,`)),r.toString()}function Y_(e,t){let n;try{n=new URL(e)}catch{return e}let r=[[V_.show,t.show&&t.show!==`all`?t.show:null],[V_.find,t.find?t.find:null]];if(t.open!==void 0&&r.push([V_.toolbox,t.open?`1`:null]),t.group!==void 0&&r.push([V_.group,t.group?t.group:null]),t.actors!==void 0){let e=[...new Set(t.actors)].filter(e=>Number.isInteger(e)&&e>=0).sort((e,t)=>e-t).map(e=>e+1);r.push([V_.actors,e.length>0?e.join(`,`):null])}let i=!1;for(let[e,t]of r)n.searchParams.get(e)===t&&n.searchParams.getAll(e).length<=1||(i=!0,t===null?n.searchParams.delete(e):n.searchParams.set(e,t));return i?n.toString():e}function X_(e,t){let n;try{n=new URL(e)}catch{return e}let r=(t??H_).filter(e=>n.searchParams.has(e));if(r.length===0)return e;for(let e of r)n.searchParams.delete(e);return n.toString()}function Z_(e,t,n,r,i){return J_(Ot(e,t,n),{trace:r,toolbox:{open:!1}},i)}function Q_(e){let t;try{t=sh(e)}catch{return`sim`}return t===`about`||t===`quickstart`?`sim`:t}var $_=(0,b.createContext)({openTrace:()=>{},openToolbox:()=>{},close:()=>{},showActorLog:()=>{},current:{trace:null,toolbox:!1}});function ev(){return(0,b.useContext)($_)}var tv=[`all`,`passed`,`did_not_pass`],nv=[`actor`,`department`,`none`],rv=e=>e>2?`actor`:`none`,iv={show:`all`,find:``,group:null,actors:[]},av={...iv,set:()=>{}},ov=(0,b.createContext)(av);function sv(){return(0,b.useContext)(ov)}var cv=[`run`,`tools`,`didNotPass`],lv=/^a(\d+)$/i;function uv(e,t){let n=t.trim();if(n===``)return e;let r=lv.exec(n);if(r){let t=`A${Number.parseInt(r[1],10)}`;return e.filter(e=>e.label===t)}let i=n.toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(i)||e.archetype.toLowerCase().includes(i))}function dv(e,t){let n=(e,t)=>e.index-t.index,r=[...e];return t===`tools`?r.sort((e,t)=>t.counts.tools-e.counts.tools||n(e,t)):t===`didNotPass`?r.sort((e,t)=>t.counts.didNotPass-e.counts.didNotPass||n(e,t)):r.sort(n)}function fv(e,t){return t>0&&e.length===0?`error`:`ready`}function pv(e,t,n){let r=new Set(e);for(let e of t){if(n!==void 0&&r.size>=n)break;r.add(e.index)}return r}function mv(e,t){let n=[...new Set(e)].filter(e=>Number.isInteger(e)&&e>=0&&e<t).sort((e,t)=>e-t);return n.length===0||n.length>=t?null:n}function hv(e,t){let n=document.createElement(`a`),r=URL.createObjectURL(new Blob([e],{type:`application/json`}));try{n.href=r,n.download=t,document.body.append(n),n.click()}finally{n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}}var gv={request:`Request`,code:`Code`,tests:`Tests`,judge:`Judge`,added:`Added`},_v={unknown:`Unknown`,notReached:`Not reached`},vv={reached:`reached`,stopped:`stopped here`,unknown:_v.unknown,notReached:_v.notReached},yv=(e,t)=>`${gv[e]}: ${vv[t]}`,bv=`The forge's stations`,xv={passed:`Passed`,rejected:`Rejected by the judge`,notJudged:`Not judged`,refused:`Refused`,failed:`Failed`,didNotPass:`Did not pass`},Sv=e=>`A${e+1}`,Cv=e=>`+${e}`,wv=(e,t)=>`${e}, forged tool ${t}`,Tv=e=>`Forged tool ${e}`,Ev=`Close the trace`,Dv={key:`Copy link to this tool`,copied:`Link copied. Anyone with it can open this tool's trace and replay the run.`,failed:`Could not copy. Select the link and copy it.`,offline:`You are offline`},Ov={toLight:`Switch to light mode`,toDark:`Switch to dark mode`},kv=`Written by an AI model during this paracosm run`,Av={passed:`Passed. The judge approved it.`,did_not_pass:`Did not pass. The run's record does not say where the forge stopped.`},jv={heading:`The reason the run recorded`,limit:`The run's record keeps at most 240 characters of this reason.`,none:`The record gave no reason.`},Mv={code:`The code was not recorded for this run.`,tests:`The tests were not recorded for this run.`},Nv=e=>`Approved · confidence ${e.toFixed(2)} out of 1`,Pv=e=>e===1?`Used 1 time`:`Used ${e} times`,Fv={open:`Open all`,close:`Close all`,openName:`Open all stations`,closeName:`Close all stations`};function Iv(e){return[e.archetype?`${e.label} ${e.name}, ${e.archetype}`:`${e.label} ${e.name}`,e.department,`turn ${e.turn}`,e.eventTitle?`for “${e.eventTitle}”`:``].filter(Boolean).join(` · `)}var Lv=e=>`Go to the event: ${e}`,Rv={whatItDoes:`What it does`,inputFields:`Input fields`,outputFields:`Output fields`,columns:[`Field`,`Type`,`Required`,`Description`],rawJson:`Raw JSON`,noInputFields:`This tool declares no input fields.`,noOutputFields:`This tool declares no output fields.`,notRecorded:`Not recorded`,yes:`Yes`,no:`No`},zv={heading:`What the judge said`,notice:`A model's review of this code, not a security audit. Check before reuse.`,meterName:`The judge's confidence`,wordsNotRecorded:`The judge's words were not recorded for this run.`},Bv=e=>`The judge's confidence: ${e.toFixed(2)} out of 1`,Vv={output:`Output the run recorded`,testNotRecorded:`This forge's test was not recorded.`,notUsed:`Not used after it was forged.`};function Hv(e,t,n){return[`Turn ${e}`,t,n?`“${n}”`:``].filter(Boolean).join(` · `)}var Uv={key:`Record`,rawRecord:`The raw record`,copy:`Copy record`,copied:`Copied`,copyFailed:`Could not copy. Select the record and copy it.`,download:`Download JSON`,downloadFailed:`Could not download. Try again, or use Copy record.`,showInEventLog:`Show in Event Log`,unreadable:`This record could not be shown.`},Wv=e=>`${e}-trace.json`,Gv={previous:`Previous attempt`,next:`Next attempt`},Kv=(e,t)=>`${e} of ${t}`,qv=(e,t)=>`Attempt ${e} of ${t}`,Jv=(e,t)=>`Attempt ${e} · ${t}`,Yv=e=>e.toLocaleString(`en-US`),Xv=(e,t,n)=>`${Yv(e)} ${e===1?t:n}`,Zv=`FORGED TOOLBOX`,Qv=e=>`Forged toolbox, ${Xv(e,`tool`,`tools`)}`,$v=e=>`Forged toolbox · ${Yv(e)}`,ey=`Close the toolbox`;function ty(e,t){let n=e.reforges>0?` (${Xv(e.reforges,`re-forge`,`re-forges`)})`:``;return[`${Xv(e.tools,`tool`,`tools`)} from ${Xv(e.forges,`forge`,`forges`)}${n}`,e.passed>0?`${Yv(e.passed)} passed`:``,e.didNotPass>0?`${Yv(e.didNotPass)} did not pass`:``,t>2?`${Yv(t)} actors`:``].filter(Boolean).join(` · `)}var ny={name:`Show`,menuLead:`Show:`,all:`All`,passed:xv.passed,did_not_pass:xv.didNotPass},ry={label:`Find a tool`,placeholder:`Tool name…`,clear:`Clear`,clearName:`Clear the search`},iy={noTools:`No department forged a tool in this run.`,everyToolPassed:`Every tool in this run passed.`},ay=e=>`No tool matches “${e}”.`,oy=`Export JSON`,sy=`paracosm-toolbox.json`;function cy(e){return[e.department,`turn ${e.turn}`,e.uses===null?``:`used ${Xv(e.uses,`time`,`times`)}`,e.reforges>0?Xv(e.reforges,`re-forge`,`re-forges`):``].filter(Boolean).join(` · `)}function ly(e){return e.length>3?`Same name in ${Yv(e.length)} other actors`:`Same name: ${e.join(`, `)}`}function uy(e){let t=`${e.name}, ${e.outcome}, made by ${e.actorLabel} ${e.actorName}`;return e.forges>1?`${t}, forged ${Yv(e.forges)} times`:t}var dy={name:`Group`,actor:`Actor`,department:`Department`,none:`None`},fy=e=>`Group: ${dy[e]}`,py={open:`Open all groups`,close:`Close all groups`};function my(e){return[`${Xv(e.tools,`tool`,`tools`)} from ${Xv(e.forges,`forge`,`forges`)}`,e.passed>0?`${Yv(e.passed)} passed`:``,e.didNotPass>0?`${Yv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var hy=`No tools`,gy=e=>`${e}'s tools could not be read.`,_y=e=>`${Yv(e)} tools: the most one actor's registry holds`;function vy(e){let t=[`${e.label} ${e.name}`,e.archetype].filter(Boolean);return e.unreadable?[...t,gy(e.label)].join(`, `):e.tools===0?[...t,hy].join(`, `):[...t,Xv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Yv(e.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}function yy(e,t){return[e,Xv(t.tools,`tool`,`tools`),t.didNotPass>0?`${Yv(t.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}var by=e=>`Exporting ${Yv(e)} tools…`,xy=`Could not export. Try again.`,Sy={dialogName:`Choose actors`,listName:`Actors`,findLabel:`Find an actor`,findPlaceholder:`Name, archetype or A-number…`,clearSearchName:`Clear the actor search`,sortName:`Sort`,sortLead:`Sort:`,selectShown:`Select shown`,clear:`Clear`,done:`Done`,showAll:`Show all`,waiting:`Waiting to start`,unreadable:`The actors could not be read.`},Cy={run:`Run order`,tools:`Most tools`,didNotPass:`Most forges that did not pass`},wy=(e,t)=>e===null?`Actors: All ${Yv(t)}`:`Actors: ${Yv(e)} of ${Yv(t)}`,Ty=(e,t)=>`Showing ${Yv(e)} of ${Yv(t)} actors`;function Ey(e,t,n){return`${Ty(e,t)} · ${ty(n,0)}`}function Dy(e){return e.tools===0?hy:[Xv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Yv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var Oy=e=>`No actor matches “${e}”.`,ky={backdrop:`_backdrop_1mlna_1`,dialog:`_dialog_1mlna_15`,"sheet-up":`_sheet-up_1mlna_1`,header:`_header_1mlna_50`,headerEnd:`_headerEnd_1mlna_62`,key:`_key_1mlna_69`,iconKey:`_iconKey_1mlna_106`,lookGlyph:`_lookGlyph_1mlna_111`,number:`_number_1mlna_116`,linkNote:`_linkNote_1mlna_135`,linkSaid:`_linkSaid_1mlna_144`,linkText:`_linkText_1mlna_151`,name:`_name_1mlna_165`,nameInRow:`_nameInRow_1mlna_184`,head:`_head_1mlna_50`,label:`_label_1mlna_195`,outcome:`_outcome_1mlna_202`,attempts:`_attempts_1mlna_219`,attemptLine:`_attemptLine_1mlna_226`,reason:`_reason_1mlna_234`,reasonHeading:`_reasonHeading_1mlna_242`,reasonText:`_reasonText_1mlna_250`,reasonNote:`_reasonNote_1mlna_263`,line:`_line_1mlna_270`,recordFoot:`_recordFoot_1mlna_274`,recordKey:`_recordKey_1mlna_283`,recordBody:`_recordBody_1mlna_288`,nameInHead:`_nameInHead_1mlna_355`,lineHead:`_lineHead_1mlna_389`};function Ay(){let{resolved:e,setTheme:t}=C(),n=e===`dark`?`light`:`dark`,r=n===`light`?Ov.toLight:Ov.toDark;return(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,onClick:()=>t(n),"aria-label":r,title:r,children:(0,x.jsx)(`span`,{className:ky.lookGlyph,"aria-hidden":`true`,children:e===`dark`?`☀`:`☽`})})}var jy=m();function My(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 Ny=`(max-width: 768px)`,Py=`(max-width: 480px)`,Fy=`(max-width: 899.98px)`,Iy=`(prefers-reduced-motion: reduce)`,Ly={tile:`_tile_1dw5u_1`,band:`_band_1dw5u_17`,label:`_label_1dw5u_26`},Ry={2:28,3:32,4:40};function zy({index:e,colour:t}){let n=Sv(e),r={"--tile-size":`${Ry[n.length]??Ry[4]}px`,"--tile-band":t};return(0,x.jsxs)(`span`,{className:Ly.tile,style:r,"data-actor-tile":n,translate:`no`,children:[(0,x.jsx)(`span`,{className:Ly.band,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:Ly.label,children:n})]})}var By={strip:`_strip_1uso4_1`,cell:`_cell_1uso4_10`,more:`_more_1uso4_27`},Vy=20;function Hy({cells:e,max:t=Vy}){let n=e.slice(0,Math.max(0,t)),r=e.length-n.length;return(0,x.jsxs)(`span`,{className:By.strip,"aria-hidden":`true`,"data-forge-strip":e.length,children:[n.map((e,t)=>(0,x.jsx)(`span`,{className:By.cell,"data-cell":e},t)),r>0&&(0,x.jsx)(`span`,{className:By.more,children:Cv(r)})]})}function Uy({count:e,lineHeights:t,scrollTop:n,viewport:r,overscan:i,keep:a}){if(e<=0)return{first:0,last:-1,padTop:0,padBottom:0};let o=e=>{let n=typeof t==`number`?t:t[e]??0;return Number.isFinite(n)&&n>0?n:0},s=Math.max(0,n),c=s+Math.max(0,r),l=0,u=-1,d=-1;for(let t=0;t<e;t+=1){let e=o(t);if(l>=c&&u>=0)break;u<0&&l+e>s&&(u=t),u>=0&&(d=t),l+=e}u<0&&(u=e-1,d=e-1);let f=Math.max(0,Math.floor(i)),p=Math.max(0,u-f),m=Math.min(e-1,d+f),h=(e,t)=>{let n=0;for(let r=e;r<t;r+=1)n+=o(r);return n};if(a!==void 0&&Number.isInteger(a)&&a>=0&&a<e){if(a>=p-1&&a<=m+1)p=Math.min(p,a),m=Math.max(m,a);else if(a<p)return{first:p,last:m,kept:a,gap:h(a+1,p),padTop:h(0,a),padBottom:h(m+1,e)};else return{first:p,last:m,kept:a,gap:h(m+1,a),padTop:h(0,p),padBottom:h(a+1,e)}}return{first:p,last:m,padTop:h(0,p),padBottom:h(m+1,e)}}var Wy=`button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Gy(e){for(let t=e.parentElement;t&&t!==document.body&&t!==document.documentElement;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight+1)return t}return null}function Ky(e){if(!e)return{top:0,bottom:window.innerHeight,padTop:0};let t=e.getBoundingClientRect().top+e.clientTop,n=Number.parseFloat(getComputedStyle(e).scrollPaddingTop);return{top:t,bottom:t+e.clientHeight,padTop:Number.isFinite(n)?n:0}}function qy(e){let t=e.getBoundingClientRect(),{top:n,bottom:r}=Ky(Gy(e));return{scrollTop:Math.max(0,n-t.top),viewport:Math.max(0,r-Math.max(n,t.top))}}function Jy(e,t,n){let r=e.length>50,i=(0,b.useRef)(new Map),a=(0,b.useRef)(new Map),o=(0,b.useRef)(-1),[s,c]=(0,b.useState)(0),[l,u]=(0,b.useState)(()=>({scrollTop:0,viewport:typeof window>`u`?0:window.innerHeight})),d=(0,b.useMemo)(()=>e.map(e=>{let t=i.current.get(e.key);if(t!==void 0)return t;let n=a.current.get(e.kind);return n&&n.n>0?n.sum/n.n:e.estimate}),[e,s]),f=n!==null&&n>=0&&n<e.length?n:void 0,p=r?Uy({count:e.length,lineHeights:d,scrollTop:l.scrollTop,viewport:l.viewport,overscan:8,keep:f}):{first:0,last:e.length-1,padTop:0,padBottom:0},m=(0,b.useRef)({heights:d,range:p,keep:f,windowed:r});m.current={heights:d,range:p,keep:f,windowed:r};let h=(0,b.useCallback)(()=>{let e=m.current;if(!t||!e.windowed)return;let n=qy(t),r=Uy({count:e.heights.length,lineHeights:e.heights,scrollTop:n.scrollTop,viewport:n.viewport,overscan:8,keep:e.keep});(r.first!==e.range.first||r.last!==e.range.last||r.kept!==e.range.kept)&&u(n)},[t]);(0,b.useEffect)(()=>{if(!t)return;let e=0,n=()=>{e===0&&(e=window.requestAnimationFrame(()=>{e=0,h()}))};document.addEventListener(`scroll`,n,{capture:!0,passive:!0}),window.addEventListener(`resize`,n);let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(t),n(),()=>{document.removeEventListener(`scroll`,n,{capture:!0}),window.removeEventListener(`resize`,n),r?.disconnect(),e!==0&&window.cancelAnimationFrame(e)}},[t,h]),(0,b.useLayoutEffect)(()=>{if(!t)return;let n=t.clientWidth;n>0&&Math.abs(n-o.current)>1&&(i.current.clear(),a.current.clear(),o.current=n);let r=!1;for(let n of t.querySelectorAll(`[data-line]`)){let t=e[Number(n.dataset.line)];if(!t)continue;let o=n.getBoundingClientRect().height;if(!(o>0))continue;let s=i.current.get(t.key);if(s!==void 0&&Math.abs(s-o)<.5)continue;i.current.set(t.key,o);let c=a.current.get(t.kind)??{sum:0,n:0};s===void 0?(c.sum+=o,c.n+=1):c.sum+=o-s,a.current.set(t.kind,c),r=!0}r?c(e=>e+1):h()});let g=(0,b.useCallback)(e=>{let n=m.current;if(!t||e<0||e>=n.heights.length)return;let r=0;for(let t=0;t<e;t+=1)r+=n.heights[t];let i=Gy(t),{top:a,bottom:o,padTop:s}=Ky(i),c=t.getBoundingClientRect().top+r,l=c+n.heights[e],u=c<a+s?c-(a+s):l>o?l-o:0;u!==0&&(i?i.scrollTop+=u:window.scrollBy(0,u)),h()},[t,h]);return{...p,windowed:r,scrollToLine:g}}function Yy(e,t,n){for(let r=t+n;r>=0&&r<e.length;r+=n)if(e[r].focusable)return r;return-1}function Xy(e,t){return Yy(e,t===1?-1:e.length,t)}function Zy(e,t){let[n,r]=(0,b.useState)(null),[i,a]=(0,b.useState)(null),o=(0,b.useRef)(null),s=(0,b.useRef)(e);s.current=e;let c=(0,b.useRef)(0),l=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(c.current=e.shiftKey?-1:1,window.setTimeout(()=>{c.current=0},0))};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,b.useEffect)(()=>{if(!t)return;let e=e=>{let n=e instanceof Element?e.closest(`[data-line]`):null;return n&&t.contains(n)?Number(n.dataset.line):-1},n=e=>{l.current=0,a(e)},i=i=>{let a=s.current,o=e(i.target),l=a[o];if(!l)return;let u=i.relatedTarget,d=c.current;if(d!==0&&!(u instanceof Node&&t.contains(u))){let e=Xy(a,d);e>=0&&e!==o&&n(a[e].key)}r(e=>e?.key===l.key?e:{key:l.key,headKey:l.headKey})},o=e=>{let n=e.relatedTarget;n instanceof Node&&!t.contains(n)&&(t.closest(`[role="dialog"]`)??t.closest(`[data-toolbox-list]`))?.contains(n)&&r(null)},u=r=>{if(r.key!==`Tab`||r.altKey||r.ctrlKey||r.metaKey)return;let i=s.current,a=e(r.target);if(a<0)return;let o=Yy(i,a,r.shiftKey?-1:1);o<0||t.querySelector(`[data-line="${o}"]`)||(r.preventDefault(),r.stopPropagation(),n(i[o].key))};return t.addEventListener(`focusin`,i),t.addEventListener(`focusout`,o),t.addEventListener(`keydown`,u,!0),()=>{t.removeEventListener(`focusin`,i),t.removeEventListener(`focusout`,o),t.removeEventListener(`keydown`,u,!0)}},[t]),(0,b.useLayoutEffect)(()=>{if(t){if(i!==null){let n=e.findIndex(e=>e.key===i),r=n>=0?t.querySelector(`[data-line="${n}"]`):null;if(r){a(null),(r.matches(Wy)?r:r.querySelector(Wy))?.focus();return}l.current+=1,n<0||l.current>3?a(null):o.current?.(n)}else if(n&&!e.some(e=>e.key===n.key)){let t=document.activeElement;(t===null||t===document.body||!t.isConnected)&&n.headKey&&e.some(e=>e.key===n.headKey)?(l.current=0,a(n.headKey)):r(null)}}});let u=n?.key??null,d=u===null?-1:e.findIndex(e=>e.key===u);return{keep:d>=0?d:null,scrollTo:o}}var K={list:`_list_yqq00_1`,count:`_count_yqq00_15`,keyRows:`_keyRows_yqq00_23`,lead:`_lead_yqq00_30`,key:`_key_yqq00_23`,actorsMenu:`_actorsMenu_yqq00_42`,keys:`_keys_yqq00_48`,segments:`_segments_yqq00_55`,segment:`_segment_yqq00_55`,menu:`_menu_yqq00_106`,menuSelect:`_menuSelect_yqq00_135`,menuMark:`_menuMark_yqq00_158`,find:`_find_yqq00_167`,findLabel:`_findLabel_yqq00_175`,field:`_field_yqq00_183`,input:`_input_yqq00_189`,clear:`_clear_yqq00_218`,groupMenu:`_groupMenu_yqq00_276`,menuKey:`_menuKey_yqq00_282`,menuKeyMark:`_menuKeyMark_yqq00_288`,groupList:`_groupList_yqq00_293`,groupItem:`_groupItem_yqq00_306`,groupCheck:`_groupCheck_yqq00_332`,empty:`_empty_yqq00_342`,emptyWords:`_emptyWords_yqq00_350`,rows:`_rows_yqq00_357`,head:`_head_yqq00_361`,row:`_row_yqq00_357`,openAll:`_openAll_yqq00_376`,stations:`_stations_yqq00_388`,items:`_items_yqq00_411`,item:`_item_yqq00_411`,sideMark:`_sideMark_yqq00_422`,top:`_top_yqq00_456`,name:`_name_yqq00_465`,outcome:`_outcome_yqq00_476`,lineCell:`_lineCell_yqq00_488`,does:`_does_yqq00_495`,metaCell:`_metaCell_yqq00_504`,meta:`_meta_yqq00_504`,same:`_same_yqq00_512`,actor:`_actor_yqq00_42`,groups:`_groups_yqq00_525`,fold:`_fold_yqq00_529`,foldTop:`_foldTop_yqq00_533`,foldHeading:`_foldHeading_yqq00_537`,foldHead:`_foldHead_yqq00_537`,chevron:`_chevron_yqq00_577`,chevronRoom:`_chevronRoom_yqq00_578`,foldTile:`_foldTile_yqq00_590`,foldName:`_foldName_yqq00_596`,foldActor:`_foldActor_yqq00_607`,foldCount:`_foldCount_yqq00_611`,foldNote:`_foldNote_yqq00_612`,foldStrip:`_foldStrip_yqq00_621`,foldHeadDept:`_foldHeadDept_yqq00_630`,foldStill:`_foldStill_yqq00_643`,foldWay:`_foldWay_yqq00_647`,department:`_department_yqq00_651`,deptLine:`_deptLine_yqq00_655`,pageFold:`_pageFold_yqq00_664`,pageFoldSummary:`_pageFoldSummary_yqq00_670`},Qy={picker:`_picker_wqyxx_1`,"picker-up":`_picker-up_wqyxx_1`,top:`_top_wqyxx_32`,find:`_find_wqyxx_39`,sort:`_sort_wqyxx_47`,list:`_list_wqyxx_76`,rows:`_rows_wqyxx_85`,option:`_option_wqyxx_89`,box:`_box_wqyxx_118`,tile:`_tile_wqyxx_135`,who:`_who_wqyxx_141`,name:`_name_wqyxx_150`,dot:`_dot_wqyxx_155`,archetype:`_archetype_wqyxx_156`,second:`_second_wqyxx_161`,counts:`_counts_wqyxx_171`,strip:`_strip_wqyxx_178`,empty:`_empty_wqyxx_183`,emptyWords:`_emptyWords_wqyxx_192`,said:`_said_wqyxx_200`,foot:`_foot_wqyxx_212`,done:`_done_wqyxx_261`},$y=56,eb=`button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function tb(){return(0,x.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.25`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function nb({actors:e,chosen:t,max:n,tools:r=0,onChange:i,onClose:a,opener:o,where:s=`toolbox`}){let c=(0,b.useId)(),l=(0,b.useRef)(null),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(``),[p,m]=(0,b.useState)(`run`),[h,g]=(0,b.useState)(``),_=My(`(min-width: 900px)`),v=My(`(min-width: 1440px)`),y=fv(e,r),S=(0,b.useMemo)(()=>dv(uv(e,d),p),[e,d,p]),C=S.length>0&&S.every(e=>t.has(e.index)),w=n!==void 0&&t.size>=n,T=(0,b.useRef)(!1);(0,b.useEffect)(()=>{T.current||(T.current=!0,B_({name:`forge_actor_picker_open`,where:s}))},[s]),(0,b.useEffect)(()=>{u.current?.focus({preventScroll:!0})},[]);let E=(0,b.useCallback)(()=>{a(),o?.isConnected&&o.focus()},[a,o]);(0,b.useEffect)(()=>{let e=l.current;if(!e)return;let t=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),E();return}if(t.key!==`Tab`||t.altKey||t.ctrlKey||t.metaKey)return;t.stopPropagation();let n=Array.from(e.querySelectorAll(eb)).filter(e=>e.tabIndex>=0&&e.offsetParent!==null);if(n.length===0){t.preventDefault();return}let r=n.indexOf(document.activeElement);(t.shiftKey?r<=0:r===-1||r===n.length-1)&&(t.preventDefault(),n[t.shiftKey?n.length-1:0].focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)},[E]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target;l.current?.contains(t)||o?.contains(t)||a()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[a,o]);let[D,O]=(0,b.useState)(null);(0,b.useLayoutEffect)(()=>{if(!_||!o){O(null);return}let e=v?560:480,t=()=>{let t=o.getBoundingClientRect(),n=Math.round(t.bottom+4),r=Math.round(Math.max(8,Math.min(t.left,window.innerWidth-e-8))),i=Math.round(Math.max(240,Math.min(560,window.innerHeight-n-16)));O(e=>e&&e.top===n&&e.left===r&&e.maxHeight===i?e:{top:n,left:r,maxHeight:i})};return t(),document.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t),()=>{document.removeEventListener(`scroll`,t,{capture:!0}),window.removeEventListener(`resize`,t)}},[_,v,o]);let k=(0,b.useCallback)(t=>{i(t);let n=L_(t.size);n&&B_({name:`forge_actor_filter`,actors:n});let r=e.length;g(Ty(t.size===0?r:Math.min(t.size,r),r))},[i,e.length]),A=e=>{let n=new Set(t);if(n.has(e))n.delete(e);else if(w)return;else n.add(e);k(n)},j=(0,b.useMemo)(()=>S.map(e=>({key:e.label,kind:`option`,estimate:$y,focusable:!0})),[S]),[ee,te]=(0,b.useState)(0),[M,N]=(0,b.useState)(!1),[ne,P]=(0,b.useState)(null),re=(0,b.useRef)(null),ie=(0,b.useRef)(!1),F=Math.min(ee,Math.max(0,S.length-1)),I=Jy(j,ne,M?F:null),ae=F>=I.first&&F<=I.last||F===I.kept?F:I.first;(0,b.useEffect)(()=>{te(0),re.current&&(re.current.scrollTop=0)},[d,p]),(0,b.useLayoutEffect)(()=>{if(!ie.current||!ne)return;let e=ne.querySelector(`[data-line="${F}"]`);e?(ie.current=!1,e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`})):I.scrollToLine(F)});let oe=e=>{S.length!==0&&(ie.current=!0,te(Math.max(0,Math.min(S.length-1,e))))},se=e=>{switch(e.key){case`ArrowDown`:e.preventDefault(),oe(F+1);break;case`ArrowUp`:e.preventDefault(),oe(F-1);break;case`Home`:e.preventDefault(),oe(0);break;case`End`:e.preventDefault(),oe(S.length-1);break;case` `:case`Enter`:e.preventDefault(),S[F]&&A(S[F].index)}},ce=()=>{f(``),u.current?.focus()},le=()=>{k(new Set),E()},L=[],ue=I.kept!==void 0&&I.kept<I.first;I.kept!==void 0&&ue&&L.push(I.kept);for(let e=I.first;e<=I.last;e+=1)L.push(e);I.kept!==void 0&&!ue&&L.push(I.kept);let de=I.kept===void 0||!I.gap?-1:ue?I.first:I.kept,fe=I.windowed?{paddingTop:I.padTop,paddingBottom:I.padBottom}:void 0,R=_&&D?{top:D.top,left:D.left,maxHeight:D.maxHeight}:void 0,z=e=>{let n=S[e];if(!n)return null;let r=t.has(n.index),i=!r&&w,a=n.unreadable?gy(n.label):n.status===`waiting`?Sy.waiting:Dy(n.counts);return(0,x.jsxs)(`div`,{role:`option`,"aria-selected":r,"aria-disabled":i?!0:void 0,"aria-setsize":S.length,"aria-posinset":e+1,"aria-label":vy({label:n.label,name:n.name,archetype:n.archetype,tools:n.counts.tools,didNotPass:n.counts.didNotPass,unreadable:n.unreadable}),tabIndex:e===ae?0:-1,className:Qy.option,"data-actor":n.label,"data-line":e,onClick:()=>{te(e),A(n.index)},onFocus:()=>te(e),children:[(0,x.jsx)(`span`,{className:Qy.box,"data-checked":r,"aria-hidden":`true`,children:r&&(0,x.jsx)(tb,{})}),(0,x.jsx)(`span`,{className:Qy.tile,children:(0,x.jsx)(zy,{index:n.index,colour:Pe(n.index)})}),(0,x.jsxs)(`span`,{className:Qy.who,translate:`no`,children:[(0,x.jsx)(`span`,{className:Qy.name,"data-picker-name":!0,children:n.name}),n.archetype&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Qy.dot,"aria-hidden":`true`,children:` · `}),(0,x.jsx)(`span`,{className:Qy.archetype,"data-picker-archetype":!0,children:n.archetype})]})]}),(0,x.jsxs)(`span`,{className:Qy.second,children:[(0,x.jsx)(`span`,{className:Qy.counts,"data-picker-counts":!0,children:a}),!n.unreadable&&(0,x.jsx)(`span`,{className:Qy.strip,children:(0,x.jsx)(Hy,{cells:n.strip,max:v?20:10})})]})]},n.label)},pe=(0,x.jsx)(`div`,{ref:l,role:`dialog`,"aria-label":Sy.dialogName,className:Qy.picker,style:R,"data-actor-picker":!0,children:y===`error`?(0,x.jsxs)(`div`,{className:Qy.empty,"data-picker-error":!0,children:[(0,x.jsx)(`p`,{className:Qy.emptyWords,"data-text":`body`,children:Sy.unreadable}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:le,children:Sy.showAll})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Qy.top,children:[(0,x.jsxs)(`div`,{className:Qy.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:c,children:Sy.findLabel}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:c,ref:u,className:K.input,type:`search`,placeholder:Sy.findPlaceholder,value:d,onChange:e=>f(e.target.value),spellCheck:!1,autoComplete:`off`}),d!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":Sy.clearSearchName,title:Sy.clearSearchName,onClick:ce,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]}),(0,x.jsxs)(`label`,{className:Qy.sort,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:Sy.sortLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":Sy.sortName,value:p,onChange:e=>m(e.target.value),children:cv.map(e=>(0,x.jsx)(`option`,{value:e,children:Cy[e]},e))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})]}),S.length===0?(0,x.jsxs)(`div`,{className:Qy.empty,"data-picker-empty":!0,children:[(0,x.jsx)(`p`,{className:Qy.emptyWords,"data-text":`body`,children:Oy(d.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:ce,children:Sy.clear})]}):(0,x.jsx)(`div`,{ref:re,role:`listbox`,"aria-multiselectable":`true`,"aria-label":Sy.listName,className:Qy.list,onKeyDown:se,onFocus:()=>N(!0),onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||N(!1)},children:(0,x.jsx)(`div`,{ref:P,className:Qy.rows,style:fe,"data-windowed":I.windowed,children:L.flatMap(e=>[e===de?(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:{height:I.gap}},`gap`):null,z(e)])})}),(0,x.jsx)(`p`,{className:Qy.said,role:`status`,children:h}),(0,x.jsxs)(`div`,{className:Qy.foot,"data-picker-foot":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:K.key,"aria-disabled":C||w||S.length===0?!0:void 0,onClick:()=>{C||w||S.length===0||k(pv(t,S,n))},children:Sy.selectShown}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:()=>k(new Set),children:Sy.clear}),(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${Qy.done}`,onClick:E,children:Sy.done})]})]})}),me=o?.closest(`[role="dialog"]`)??(typeof document>`u`?null:document.body);return me?(0,jy.createPortal)(pe,me):pe}var rb=e=>e.kind===`actor`?`actor:${e.actor.label}`:`department:${e.name}`,ib=e=>e.kind===`department`||!e.actor.unreadable&&e.actor.counts.tools>0;function ab(){let e=My(`(min-width: 1440px)`),t=My(`(min-width: 900px)`);return e?50:t?30:1/0}function ob(){return(0,x.jsx)(`svg`,{className:K.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function sb({head:e,open:t,onToggle:n,onShowInEventLog:r}){let i=(0,b.useId)(),a=ab();if(e.kind===`department`)return(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":e.name,children:(0,x.jsxs)(`button`,{type:`button`,className:`${K.foldHead} ${K.foldHeadDept}`,"aria-expanded":t,"aria-label":yy(e.name,e.counts),onClick:n,children:[(0,x.jsx)(ob,{}),(0,x.jsx)(`span`,{className:K.foldName,"data-fold-name":!0,"data-text":`heading`,children:e.name}),(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:my(e.counts)})]})});let{actor:o}=e,s=!o.unreadable&&o.counts.tools>=50,c=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.foldTile,children:(0,x.jsx)(zy,{index:o.index,colour:Pe(o.index)})}),(0,x.jsxs)(`span`,{className:K.foldName,"data-fold-name":!0,translate:`no`,"data-text":`heading`,children:[(0,x.jsx)(`span`,{className:K.foldActor,children:o.name}),o.archetype?` · ${o.archetype}`:``]}),o.unreadable?(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-error":!0,children:gy(o.label)}):(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:o.counts.tools===0?hy:my(o.counts)}),s&&(0,x.jsx)(`span`,{id:i,className:K.foldNote,"data-fold-note":!0,children:_y(50)}),!o.unreadable&&(0,x.jsx)(`span`,{className:K.foldStrip,children:(0,x.jsx)(Hy,{cells:o.strip,max:a})})]}),l=vy({label:o.label,name:o.name,archetype:o.archetype,tools:o.counts.tools,didNotPass:o.counts.didNotPass,unreadable:o.unreadable});return ib(e)?(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`button`,{type:`button`,className:K.foldHead,"aria-expanded":t,"aria-label":l,"aria-describedby":s?i:void 0,onClick:n,children:[(0,x.jsx)(ob,{}),c]})}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`span`,{className:`${K.foldHead} ${K.foldStill}`,children:[(0,x.jsx)(`span`,{className:K.chevronRoom,"aria-hidden":`true`}),c]})}),o.unreadable&&r&&(0,x.jsx)(`div`,{className:K.foldWay,children:(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:r,children:Uv.showInEventLog})})]})}var cb={glyph:`_glyph_bhdp0_1`,passed:`_passed_bhdp0_8`,rejected:`_rejected_bhdp0_12`,refused:`_refused_bhdp0_13`,failed:`_failed_bhdp0_14`,notJudged:`_notJudged_bhdp0_18`,didNotPass:`_didNotPass_bhdp0_22`};function lb(e,t,n){let r={fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`},i=(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r});switch(e){case`passed`:return(0,x.jsx)(`path`,{fill:`currentColor`,fillRule:`evenodd`,d:`M1 10a9 9 0 1 0 18 0a9 9 0 1 0 -18 0Z M4.75 11.05L8.63 14.93L15.28 7.82L13.52 6.18L8.57 11.47L6.45 9.35Z`});case`rejected`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M6.9 6.9L13.1 13.1M13.1 6.9L6.9 13.1`,...r})]});case`refused`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M4.2 15.8L15.8 4.2`,...r})]});case`failed`:return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 2.2L18.2 16.8H1.8Z`,...r}),(0,x.jsx)(`path`,{d:`M10 7.4V12.2`,...r})]});case`notJudged`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M7.7 7.9a2.4 2.4 0 1 1 3.5 2.1c-.8.4-1.2.9-1.2 1.7v.4`,...r}),(0,x.jsx)(`circle`,{cx:`10`,cy:`14.5`,r:`1.1`,fill:`currentColor`})]});case`didNotPass`:return(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r,strokeLinecap:`butt`,strokeDasharray:n})}}function ub({kind:e,size:t}){let n=t===10?3:1.75,r=t===10?`5 4`:`2.6 2.1`;return(0,x.jsx)(`svg`,{className:`${cb.glyph} ${cb[e]}`,"data-glyph":e,width:t,height:t,viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:lb(e,n,r)})}var db={cell:`_cell_1xygk_1`,trace:`_trace_1xygk_22`,station:`_station_1xygk_35`,stationKey:`_stationKey_1xygk_58`,mark:`_mark_1xygk_83`,name:`_name_1xygk_91`,result:`_result_1xygk_119`,evidence:`_evidence_1xygk_120`,fork:`_fork_1xygk_144`,forkLink:`_forkLink_1xygk_167`,forkWords:`_forkWords_1xygk_200`,chevron:`_chevron_1xygk_205`,row:`_row_1xygk_267`,spur:`_spur_1xygk_275`,rowStation:`_rowStation_1xygk_279`,segment:`_segment_1xygk_290`},fb=e=>e===`reached`||e===`stopped`,pb=e=>e===void 0?void 0:fb(e)?`solid`:`dashed`;function mb({model:e,station:t,size:n}){let r=e.stations[t];if(r===`stopped`){let r=e.stop;return(0,x.jsx)(ub,{kind:r&&r.station===t?r.glyph:`didNotPass`,size:n})}return(0,x.jsx)(`span`,{className:db.cell,"data-cell":r})}function hb({mark:e,onAttempt:t,href:n}){let r=k_(e.outcome);return(0,x.jsx)(`div`,{className:db.fork,"data-fork":e.attempt,children:(0,x.jsxs)(`a`,{className:db.forkLink,href:n,"data-fork-attempt":e.attempt,onClick:n=>{n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||(n.preventDefault(),t?.(e.attempt))},children:[(0,x.jsx)(ub,{kind:r,size:20}),(0,x.jsx)(`span`,{className:db.forkWords,children:Jv(e.attempt,xv[r])}),(0,x.jsx)(`svg`,{className:db.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})})}function gb(e){return e===`notReached`?_v.notReached:e===`unknown`?_v.unknown:null}function _b({model:e,size:t,colour:n,open:r,onToggle:i,stationResult:a,renderEvidence:o,onAttempt:s,attemptHref:c}){let l=(0,b.useId)(),u={"--line":n};return t===`row`?(0,x.jsx)(`span`,{className:db.row,style:u,"aria-hidden":`true`,"data-forge-line":`row`,children:O_.map((t,n)=>{let r=e.spurs.filter(e=>e.station===t);return(0,x.jsxs)(b.Fragment,{children:[n>0&&(0,x.jsx)(`span`,{className:db.segment,"data-rail":pb(e.stations[t])}),(0,x.jsxs)(`span`,{className:db.rowStation,"data-station":t,"data-state":e.stations[t],children:[(0,x.jsx)(mb,{model:e,station:t,size:10}),r.length>0&&(0,x.jsx)(`span`,{className:db.spur,"data-spurs":r.length,children:r.map(e=>(0,x.jsx)(ub,{kind:k_(e.outcome),size:10},e.attempt))})]})]},t)})}):(0,x.jsx)(`ol`,{className:db.trace,style:u,role:`list`,"aria-label":bv,"data-forge-line":`trace`,children:O_.map((t,n)=>{let u=e.stations[t],d=o?.(t),f=d!=null&&d!==!1,p=fb(u)&&f,m=p&&!!r?.has(t),h=a?.(t)??gb(u),g=`${l}-${t}-result`,_=`${l}-${t}-evidence`,v=`${l}-${t}-name`,y=u===`notReached`||u===`unknown`,b=[...e.spurs.filter(e=>e.station===t),...e.branch&&e.branch.station===t?[e.branch]:[]];return(0,x.jsxs)(`li`,{className:db.station,"data-station":t,"data-state":u,"data-open":m||void 0,"data-rail":pb(e.stations[O_[n+1]]),children:[(0,x.jsxs)(`button`,{type:`button`,className:db.stationKey,"aria-label":yv(t,u),"aria-expanded":p?m:void 0,"aria-controls":p?_:void 0,"aria-disabled":!p||void 0,"aria-describedby":!p&&h!=null?g:void 0,tabIndex:p?void 0:-1,onClick:p?()=>i?.(t):void 0,children:[(0,x.jsx)(`span`,{className:db.mark,"aria-hidden":`true`,children:(0,x.jsx)(mb,{model:e,station:t,size:20})}),(0,x.jsx)(`span`,{id:v,className:db.name,"data-text":`heading`,children:gv[t]})]}),!m&&h!=null&&(0,x.jsx)(`div`,{id:g,className:db.result,"data-quiet":y||void 0,"data-text":y?void 0:`body`,children:h}),p&&(0,x.jsx)(`div`,{id:_,className:db.evidence,role:`region`,"aria-labelledby":v,hidden:!m,children:m?d:null}),b.map(e=>(0,x.jsx)(hb,{mark:e,onAttempt:s,href:c?c(e.attempt):`#`},e.attempt))]},t)})})}function vb(e){let t=e.split(`_`);return t.map((e,n)=>(0,x.jsxs)(b.Fragment,{children:[n<t.length-1?`${e}_`:e,n<t.length-1&&(0,x.jsx)(`wbr`,{})]},n))}function yb({entry:e,actorCount:t,onOpen:n,line:r,setSize:i,posInSet:a}){let o=(0,b.useId)(),s=Sv(e.actorIndex),c=k_(e.outcome),l=xv[c],u=e.attempts.length,d=e.description!==``&&e.description!==e.name,f=e.sameNameActors.map(Sv),p={"--actor":Pe(e.actorIndex)};return(0,x.jsxs)(`li`,{className:K.item,style:p,"data-tool-row":e.n,"data-tool-name":e.name,"data-actor":s,"data-outcome":e.outcome,"data-line":r,"aria-setsize":i,"aria-posinset":a,children:[(0,x.jsx)(`span`,{className:K.sideMark,"data-side-mark":!0,"aria-hidden":`true`}),(0,x.jsxs)(`button`,{type:`button`,className:K.row,"aria-label":uy({name:e.name,outcome:l,actorLabel:s,actorName:e.actorName,forges:u}),"aria-describedby":d?`${o}-does ${o}-meta`:`${o}-meta`,onClick:e=>n(e.currentTarget),children:[(0,x.jsxs)(`span`,{className:K.top,children:[(0,x.jsxs)(`span`,{className:K.name,"data-row-name":!0,"data-text":`heading`,children:[(0,x.jsxs)(`span`,{children:[`[`,e.n,`]`]}),` `,(0,x.jsx)(`span`,{translate:`no`,children:vb(e.name)})]}),(0,x.jsxs)(`span`,{className:K.outcome,"data-row-outcome":!0,children:[(0,x.jsx)(ub,{kind:c,size:20}),(0,x.jsx)(`span`,{children:l})]})]}),(0,x.jsx)(`span`,{className:K.lineCell,children:(0,x.jsx)(_b,{model:N_(e,NaN),size:`row`,colour:P_(e.actorIndex,t)})}),d&&(0,x.jsx)(`span`,{id:`${o}-does`,className:K.does,"data-row-does":!0,"data-text":`body`,children:e.description}),(0,x.jsxs)(`span`,{id:`${o}-meta`,className:K.metaCell,children:[(0,x.jsxs)(`span`,{className:K.meta,"data-row-meta":!0,children:[(0,x.jsx)(`span`,{className:K.actor,"data-row-actor":!0,children:`${s} ${e.actorName}`}),` · ${cy({department:e.firstForgedDepartment,turn:e.firstForgedTurn,uses:e.outcome===`passed`?F_(e):null,reforges:Math.max(0,u-1)})}`]}),f.length>0&&(0,x.jsx)(`span`,{className:K.same,"data-row-same":!0,children:ly(f)})]})]})]})}function bb(e,t,n,r=null){let i=n.trim().toLowerCase(),a=r===null?null:new Set(r);return t===`all`&&i===``&&a===null?e:e.filter(e=>(a===null||a.has(e.actorIndex))&&(t===`all`||e.outcome===t)&&(i===``||e.name.toLowerCase().includes(i)))}function xb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e)t.tools+=n.counts.tools,t.forges+=n.counts.forges,t.reforges+=n.counts.reforges,t.passed+=n.counts.passed,t.didNotPass+=n.counts.didNotPass;return t}var Sb=e=>e.firstForgedDepartment||_v.unknown;function Cb(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return[...n]}function wb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e){let e=n.attempts.filter(e=>e.approved).length;t.tools+=1,t.forges+=n.attempts.length,t.reforges+=Math.max(0,n.attempts.length-1),t.passed+=e,t.didNotPass+=n.attempts.length-e}return t}function Tb(e,t,n){return t===`none`?[{head:null,rows:e}]:t===`department`?Cb(e,Sb).map(([e,t])=>({head:{kind:`department`,name:e,counts:wb(t)},rows:t})):n.map(t=>{let n=e.filter(e=>e.actorIndex===t.index);return{head:{kind:`actor`,actor:t},rows:Cb(n,Sb).flatMap(([,e])=>e)}})}var Eb={head:64,dept:40,row:112},Db=e=>`${e.actorIndex}:${e.name}`,Ob=e=>e.kind===`head`?null:e.dept;function kb(e,t,n,r){let i=[];if(e===`none`)return t.forEach((e,t)=>{i.push({kind:`row`,key:Db(e),estimate:Eb.row,focusable:!0,fold:-1,dept:null,entry:e,pos:t+1})}),{lines:i,rowCount:t.length};let a=0;return n.forEach((e,t)=>{let n=e.head;if(n===null)return;let o=rb(n),s=ib(n)&&e.rows.length>0&&r(o),c=ib(n)||n.kind===`actor`&&n.actor.unreadable;i.push({kind:`head`,key:o,estimate:Eb.head,focusable:c,fold:t});let l=n.kind===`actor`?Cb(e.rows,Sb):[[null,e.rows]];for(let[e,n]of l){s&&e!==null&&i.push({kind:`dept`,key:`${o}|dept:${e}`,estimate:Eb.dept,focusable:!1,headKey:o,fold:t,dept:e});for(let r of n)a+=1,s&&i.push({kind:`row`,key:`${o}|${Db(r)}`,estimate:Eb.row,focusable:!0,headKey:o,fold:t,dept:e,entry:r,pos:a})}}),{lines:i,rowCount:a}}var Ab=8,jb=new Set,Mb=[];function Nb({value:e,onChoose:t}){let[n,r]=(0,b.useState)(!1),i=(0,b.useId)(),a=(0,b.useRef)(null),o=(0,b.useRef)(null),s=(0,b.useRef)([]);(0,b.useEffect)(()=>{n&&s.current[nv.indexOf(e)]?.focus()},[n,e]),(0,b.useEffect)(()=>{if(!n)return;let e=e=>{a.current?.contains(e.target)||r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]);let c=()=>{r(!1),o.current?.focus()},l=e=>{t(e),c()},u=e=>s.current[(e+nv.length)%nv.length]?.focus();return(0,x.jsxs)(`div`,{ref:a,className:K.groupMenu,children:[(0,x.jsxs)(`button`,{ref:o,type:`button`,className:`${K.key} ${K.menuKey}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>r(e=>!e),onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),r(!0))},children:[(0,x.jsx)(`span`,{children:fy(e)}),(0,x.jsx)(`svg`,{className:K.menuKeyMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),n&&(0,x.jsx)(`div`,{id:i,role:`menu`,"aria-label":dy.name,className:K.groupList,onKeyDown:e=>{let t=s.current.findIndex(e=>e===document.activeElement);switch(e.key){case`ArrowDown`:e.preventDefault(),u(t+1);break;case`ArrowUp`:e.preventDefault(),u(t-1);break;case`Home`:e.preventDefault(),u(0);break;case`End`:e.preventDefault(),u(nv.length-1);break;case`Enter`:case` `:e.preventDefault(),t>=0&&l(nv[t]);break;case`Escape`:e.preventDefault(),c();break;case`Tab`:c()}},children:nv.map((t,n)=>(0,x.jsxs)(`div`,{ref:e=>{s.current[n]=e},role:`menuitemradio`,"aria-checked":t===e,tabIndex:-1,className:K.groupItem,onClick:()=>l(t),children:[(0,x.jsx)(`svg`,{className:K.groupCheck,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,x.jsx)(`span`,{children:dy[t]})]},t))})]})}function Pb({inPage:e=!1}){let t=D_(),{show:n,find:r,group:i,actors:a,set:o}=sv(),{openTrace:s,showActorLog:c}=ev(),l=(0,b.useId)(),u=(0,b.useId)(),d=(0,b.useRef)(null),f=(0,b.useRef)(null),p=(0,b.useRef)(null),[m,h]=(0,b.useState)(!1),g=t.actors.length,_=(0,b.useMemo)(()=>mv(a,g),[a,g]),v=(0,b.useMemo)(()=>_===null?t.actors:_.map(e=>t.actors[e]),[_,t.actors]),y=(0,b.useMemo)(()=>new Set(a.filter(e=>e<g)),[a,g]),S=(0,b.useMemo)(()=>bb(t.list,`all`,``,_),[t.list,_]),C=(0,b.useMemo)(()=>bb(S,n,r),[S,n,r]),w=i??rv(g),T=n!==`all`||r.trim()!==``,E=(0,b.useMemo)(()=>{let e=S.filter(e=>e.outcome===`passed`).length;return[{id:`all`,count:S.length},{id:`passed`,count:e},{id:`did_not_pass`,count:S.length-e}].filter(e=>e.id===`all`||e.count>0||e.id===n)},[S,n]),D=(0,b.useMemo)(()=>{let e=Tb(C,w,v);return T?e.filter(e=>e.head===null||e.rows.length>0||e.head.kind===`actor`&&e.head.actor.unreadable):e},[C,w,v,T]),O=_===null?ty(t.counts,g):Ey(_.length,g,xb(v)),k=(0,b.useCallback)(e=>{o({actors:[...e].sort((e,t)=>e-t)})},[o]),A=(0,b.useCallback)(()=>h(!1),[]),[j,ee]=(0,b.useState)({group:w,all:null,toggled:jb}),te=(0,b.useMemo)(()=>j.group===w?j:{group:w,all:null,toggled:jb},[j,w]),M=g<=Ab,N=(0,b.useCallback)(e=>(te.all??M)!==te.toggled.has(e),[te,M]),ne=D.filter(e=>e.head!==null&&ib(e.head)&&e.rows.length>0),P=ne.length>0&&ne.every(e=>N(rb(e.head))),re=w===`none`||ne.length===0,ie=e=>{B_({name:`forge_group_toggle`,scope:`one`}),ee(t=>{let n=t.group===w?t:{group:w,all:null,toggled:jb},r=new Set(n.toggled);return r.has(e)?r.delete(e):r.add(e),{...n,toggled:r}})},F=()=>{B_({name:`forge_group_toggle`,scope:`all`}),ee({group:w,all:!P,toggled:jb})},I=e=>{e!==w&&B_({name:`forge_toolbox_group`,group:e}),o({group:e===rv(g)?null:e})},ae=e=>{e!==n&&B_({name:`forge_toolbox_filter`,show:e}),o({show:e})},oe=(0,b.useCallback)((e,t)=>{s({actorIndex:e.actorIndex,toolName:e.name},t,`toolbox`)},[s]),{lines:se,rowCount:ce}=(0,b.useMemo)(()=>kb(w,C,D,N),[w,C,D,N]),[le,L]=(0,b.useState)(null),ue=Zy(se,le),de=Jy(se,le,ue.keep);ue.scrollTo.current=de.scrollToLine;let fe=()=>{o({find:``}),f.current?.focus()},R=()=>{ae(`all`);let e=d.current?.querySelectorAll(`input[type="radio"][value="all"], select`);Array.from(e??[]).find(e=>e.offsetParent!==null)?.focus()},z=e=>`${ny[e.id]} ${Yv(e.count)}`,pe=e=>{let t=se[e];return t.kind===`row`?(0,x.jsx)(yb,{entry:t.entry,actorCount:g,onOpen:e=>oe(t.entry,e),line:e,setSize:ce,posInSet:t.pos},Db(t.entry)):null},me=[],he=de.kept!==void 0&&de.kept<de.first;de.kept!==void 0&&he&&me.push(de.kept);for(let e=de.first;e<=de.last;e+=1)me.push(e);de.kept!==void 0&&!he&&me.push(de.kept);let ge=de.kept===void 0||!de.gap?-1:he?de.first:de.kept,_e=(e,t)=>{if(e!==ge)return null;let n={height:de.gap};return t?(0,x.jsx)(`li`,{role:`presentation`,"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`):(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`)},B=e=>e.flatMap(e=>[_e(e,!0),pe(e)]),ve=de.windowed?{paddingTop:de.padTop,paddingBottom:de.padBottom}:void 0,ye=[];for(let e of me){let t=ye[ye.length-1];t&&t.fold===se[e].fold?t.at.push(e):ye.push({fold:se[e].fold,at:[e]})}let be=e=>{let t=[];for(let n of e){let e=Ob(se[n])??``,r=t[t.length-1];r&&r.dept===e?r.at.push(n):t.push({dept:e,at:[n]})}return t};return(0,x.jsxs)(`div`,{className:K.list,"data-toolbox-list":e?`page`:`dialog`,children:[(0,x.jsx)(`p`,{className:K.count,"data-toolbox-count":!0,children:O}),t.list.length===0?(0,x.jsxs)(`div`,{className:K.empty,"data-toolbox-empty":`no-tools`,children:[(0,x.jsx)(Hy,{cells:Mb}),(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:iy.noTools})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:K.keyRows,children:[(0,x.jsxs)(`div`,{className:K.lead,"data-toolbox-lead":!0,children:[(0,x.jsx)(Nb,{value:w,onChoose:I}),(0,x.jsxs)(`div`,{className:K.actorsMenu,children:[(0,x.jsx)(`button`,{ref:p,type:`button`,className:K.key,"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>h(e=>!e),children:wy(_===null?null:_.length,g)}),m&&(0,x.jsx)(nb,{actors:t.actors,tools:t.list.length,chosen:y,onChange:k,onClose:A,opener:p.current})]})]}),(0,x.jsxs)(`div`,{ref:d,className:K.keys,"data-toolbox-keys":!0,children:[(0,x.jsx)(`div`,{className:K.segments,role:`radiogroup`,"aria-label":ny.name,children:E.map(e=>(0,x.jsxs)(`label`,{className:K.segment,"data-show":e.id,children:[(0,x.jsx)(`input`,{type:`radio`,name:u,value:e.id,checked:n===e.id,onChange:()=>ae(e.id)}),(0,x.jsx)(`span`,{children:z(e)})]},e.id))}),(0,x.jsxs)(`label`,{className:K.menu,"data-toolbox-menu":!0,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:ny.menuLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":ny.name,value:n,onChange:e=>ae(e.target.value),children:E.map(e=>(0,x.jsx)(`option`,{value:e.id,children:z(e)},e.id))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,x.jsxs)(`div`,{className:K.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:l,children:ry.label}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:l,ref:f,className:K.input,type:`search`,placeholder:ry.placeholder,value:r,onChange:e=>o({find:e.target.value}),spellCheck:!1,autoComplete:`off`}),r!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":ry.clearName,title:ry.clearName,onClick:fe,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]})]})]}),C.length===0&&T?(0,x.jsx)(`div`,{className:K.empty,"data-toolbox-empty":r.trim()===``?`no-rows`:`no-match`,children:r.trim()===``?(0,x.jsxs)(x.Fragment,{children:[n===`did_not_pass`&&_===null&&(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:iy.everyToolPassed}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:R,children:ny.all})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ay(r.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:fe,children:ry.clear})]})}):(0,x.jsxs)(`div`,{className:K.rows,children:[(0,x.jsxs)(`div`,{className:K.head,children:[(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${K.openAll}`,"aria-disabled":re?!0:void 0,tabIndex:re?-1:void 0,onClick:re?void 0:F,children:P?py.close:py.open}),(0,x.jsx)(`span`,{className:K.stations,"data-toolbox-stations":!0,"aria-hidden":`true`,children:O_.map(e=>(0,x.jsx)(`span`,{children:gv[e]},e))})]}),w===`none`?(0,x.jsx)(`ol`,{ref:L,className:K.items,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:B(me)}):(0,x.jsx)(`div`,{ref:L,role:`list`,className:K.groups,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:ye.map(({fold:e,at:t})=>{let n=D[e],r=n?.head??null;if(r===null)return null;let i=rb(r),a=ib(r)&&n.rows.length>0&&N(i),o=t.find(e=>se[e].kind===`head`),s=t.filter(e=>se[e].kind!==`head`);return(0,x.jsxs)(`div`,{role:`listitem`,"aria-setsize":D.length,"aria-posinset":e+1,className:K.fold,"data-fold":r.kind===`actor`?r.actor.label:r.name,children:[o!==void 0&&_e(o,!1),o!==void 0&&(0,x.jsx)(`div`,{className:K.foldTop,"data-line":o,children:(0,x.jsx)(sb,{head:r,open:a,onToggle:()=>ie(i),onShowInEventLog:r.kind===`actor`&&r.actor.unreadable?()=>c(r.actor.index):void 0})}),r.kind===`actor`?be(s).map(({dept:e,at:t})=>{let n=t.find(e=>se[e].kind===`dept`),r=t.filter(e=>se[e].kind===`row`);return(0,x.jsxs)(`div`,{className:K.department,children:[n!==void 0&&_e(n,!1),n!==void 0&&(0,x.jsx)(`h4`,{className:K.deptLine,"data-dept-line":!0,"data-line":n,children:e}),r.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(r)})]},e)}):s.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(s)})]},i)})})]})]})]})}var Fb={dialog:`_dialog_x8cpw_1`,"sheet-up":`_sheet-up_x8cpw_1`,header:`_header_x8cpw_36`,headerEnd:`_headerEnd_x8cpw_48`,title:`_title_x8cpw_55`,exportInHeader:`_exportInHeader_x8cpw_73`,exportStatus:`_exportStatus_x8cpw_77`,footStatus:`_footStatus_x8cpw_95`,body:`_body_x8cpw_106`,foot:`_foot_x8cpw_95`,exportAtFoot:`_exportAtFoot_x8cpw_114`};function Ib(e){return e.map(e=>({n:e.n,name:e.name,description:e.description,mode:e.mode,firstForgedTurn:e.firstForgedTurn,firstForgedDepartment:e.firstForgedDepartment,departments:[...e.departments],reuseCount:e.reuseCount,approved:e.approved,confidence:e.confidence,inputSchema:e.inputSchema,outputSchema:e.outputSchema,sampleOutput:e.sampleOutput,inputFields:e.inputFields,outputFields:e.outputFields,actor:Sv(e.actorIndex),actorName:e.actorName}))}var Lb=500;function Rb({covered:e,onClose:t}){let n=D_(),{show:r,find:i,actors:a}=sv(),o=Pt(!0),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{s.current?.focus()},[]);let c=(0,b.useRef)(e);c.current=e,(0,b.useEffect)(()=>{let e=e=>{e.key!==`Escape`||e.defaultPrevented||c.current||(e.preventDefault(),t())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t]);let[l,u]=(0,b.useState)({state:`idle`}),d=()=>{B_({name:`forge_record_export`,what:`toolbox`});let e=bb(n.list,r,i,mv(a,n.actors.length)),t=()=>{try{hv(JSON.stringify(Ib(e),null,2),sy),u({state:`idle`})}catch{u({state:`failed`})}};e.length<=Lb?t():(u({state:`exporting`,tools:e.length}),requestAnimationFrame(()=>{window.setTimeout(t,0)}))},f=l.state===`exporting`?by(l.tools):l.state===`failed`?xy:``;return(0,x.jsx)(`div`,{className:ky.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,x.jsxs)(`div`,{ref:o,role:`dialog`,"aria-modal":`true`,"aria-label":Qv(n.list.length),tabIndex:-1,className:Fb.dialog,inert:e,children:[(0,x.jsxs)(`div`,{className:Fb.header,"data-toolbox-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,onClick:()=>t(),"aria-label":ey,title:ey,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(`h2`,{ref:s,className:Fb.title,tabIndex:-1,"data-toolbox-title":!0,"data-text":`heading`,children:Zv}),(0,x.jsxs)(`span`,{className:Fb.headerEnd,children:[(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${Fb.exportInHeader}`,onClick:d,children:oy}),(0,x.jsx)(Ay,{})]}),(0,x.jsx)(`span`,{className:Fb.exportStatus,role:`status`,"data-export-status":!0,children:f})]}),(0,x.jsx)(`div`,{className:Fb.body,children:(0,x.jsx)(Pb,{})}),(0,x.jsxs)(`div`,{className:Fb.foot,children:[(0,x.jsx)(`p`,{className:Fb.footStatus,role:`status`,"data-export-status":!0,children:f}),(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${Fb.exportAtFoot}`,onClick:d,children:oy})]})]})})}var zb=`paracosm:forgeOpenStations`,Bb=20,Vb=e=>typeof e==`string`&&O_.includes(e);function Hb(e){let t=new Map,n;try{n=e.getItem(zb)}catch{return t}if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}if(!r||typeof r!=`object`||Array.isArray(r))return t;for(let[e,n]of Object.entries(r))Array.isArray(n)&&t.set(e,O_.filter(e=>n.some(t=>Vb(t)&&t===e)));return t}function Ub(e,t){return Hb(e).get(t)??[]}function Wb(e,t,n){let r=Hb(e);r.delete(t),r.set(t,O_.filter(e=>n.includes(e)));let i=[...r.keys()];for(let e of i.slice(0,Math.max(0,i.length-Bb)))r.delete(e);try{e.setItem(zb,JSON.stringify(Object.fromEntries(r)))}catch{}}function Gb(e,t,n){let r=new Set([e.deciding]);for(let e of t)n(e)&&r.add(e);return r}function Kb(e){return t=>t===`request`||e&&(t===`judge`||t===`added`)}function qb(e,t){let n=null;try{n=new URL(e).searchParams.get(`replay`)}catch{}return n||t||`live`}var Jb={open:`_open_o8eqn_1`,part:`_part_o8eqn_11`,heading:`_heading_o8eqn_18`,body:`_body_o8eqn_26`,meta:`_meta_o8eqn_34`,quiet:`_quiet_o8eqn_42`,code:`_code_o8eqn_49`,actor:`_actor_o8eqn_62`,rule:`_rule_o8eqn_68`,actorText:`_actorText_o8eqn_74`,link:`_link_o8eqn_81`,fieldsBar:`_fieldsBar_o8eqn_105`,switch:`_switch_o8eqn_110`,switchTrack:`_switchTrack_o8eqn_139`,caption:`_caption_o8eqn_167`,fields:`_fields_o8eqn_105`,confidence:`_confidence_o8eqn_247`,meter:`_meter_o8eqn_258`,meterFill:`_meterFill_o8eqn_267`,uses:`_uses_o8eqn_275`,use:`_use_o8eqn_275`,recordKeys:`_recordKeys_o8eqn_295`,recordSaid:`_recordSaid_o8eqn_307`,record:`_record_o8eqn_295`};function Yb(e,t){let n=t.trim(),r=e=>String(e??``).trim()===n,i=[];for(let t of e){let e=t.data??{},n=t.type===`forge_attempt`&&r(e.name),a=t.type===`specialist_done`&&Array.isArray(e.forgedTools)&&e.forgedTools.some(e=>!!e&&typeof e==`object`&&r(e.name));if(!n&&!a)continue;let o={...e};delete o._filteredTools,i.push(o)}return i}function Xb(e){try{return JSON.stringify(e,null,2)}catch{return null}}var Zb=5e3;function Qb({entry:e,frames:t,onShowInEventLog:n}){let r=(0,b.useId)(),i=(0,b.useMemo)(()=>Xb(t),[t]),[a,o]=(0,b.useState)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(0);(0,b.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]);let l=e=>{s.current!==null&&window.clearTimeout(s.current),s.current=null,o(e),e===`copied`&&(s.current=window.setTimeout(()=>o(null),Zb))},u=()=>{if(i===null)return;B_({name:`forge_record_export`,what:`record_copy`});let e=++c.current;Dt(i).then(()=>{e===c.current&&l(`copied`)},()=>{e===c.current&&l(`copyFailed`)})},d=()=>{if(i!==null){B_({name:`forge_record_export`,what:`record_download`});try{hv(i,Wv(e.name)),l(null)}catch{l(`downloadFailed`)}}},f={copied:Uv.copied,copyFailed:Uv.copyFailed,downloadFailed:Uv.downloadFailed};return(0,x.jsxs)(`section`,{className:Jb.open,"data-record-panel":!0,"aria-labelledby":r,children:[(0,x.jsx)(`h3`,{id:r,className:Jb.heading,"data-text":`heading`,children:Uv.rawRecord}),i===null?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Uv.unreadable}),(0,x.jsx)(`div`,{className:Jb.recordKeys,children:(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Uv.showInEventLog})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Jb.recordKeys,children:[(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:u,children:Uv.copy}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:d,children:Uv.download}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Uv.showInEventLog}),(0,x.jsx)(`p`,{className:Jb.recordSaid,role:`status`,children:a?f[a]:null})]}),(0,x.jsx)(`pre`,{className:Jb.record,"data-raw-record":!0,translate:`no`,tabIndex:0,"aria-label":Uv.rawRecord,children:i})]})]})}function $b({entry:e}){let t=F_(e);return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Pv(t)}),e.history.length>0&&(0,x.jsx)(`ol`,{className:Jb.uses,children:e.history.map((e,t)=>{let n=t===0||e.isReforge;return(0,x.jsxs)(`li`,{className:Jb.use,"data-history-row":n?`forge`:`use`,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Hv(e.turn,e.department,e.eventTitle)}),e.output?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Vv.output}),(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,children:e.output})]}):null,n&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Vv.testNotRecorded})]},`${e.turn}-${e.eventIndex}-${e.department}-${t}`)})}),t===0&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Vv.notUsed})]})}function ex({confidence:e}){let t=Math.min(1,Math.max(0,Number(e.toFixed(2))));return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`h3`,{className:Jb.heading,"data-text":`heading`,children:zv.heading}),(0,x.jsx)(`p`,{className:Jb.meta,children:zv.notice}),(0,x.jsxs)(`div`,{className:Jb.confidence,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Bv(e)}),(0,x.jsx)(`div`,{role:`meter`,className:Jb.meter,"aria-label":zv.meterName,"aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":t,children:(0,x.jsx)(`span`,{className:Jb.meterFill,style:{width:`${t*100}%`},"data-meter-fill":!0})})]}),(0,x.jsx)(`p`,{className:Jb.quiet,children:zv.wordsNotRecorded})]})}function tx({station:e}){return(0,x.jsx)(x.Fragment,{children:Mv[e]})}function nx({reason:e}){let t=(0,b.useId)();return(0,x.jsxs)(`section`,{className:ky.reason,"aria-labelledby":t,children:[(0,x.jsx)(`h3`,{id:t,className:ky.reasonHeading,"data-text":`heading`,children:jv.heading}),e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`pre`,{className:ky.reasonText,translate:`no`,children:e}),(0,x.jsx)(`p`,{className:ky.reasonNote,children:jv.limit})]}):(0,x.jsx)(`p`,{className:ky.reasonNote,children:jv.none})]})}var rx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ix(e){if(!rx(e))return``;let{type:t}=e;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`string`).join(` | `):``}function ax(e,t){if(rx(e)&&rx(e.properties)){let t=Array.isArray(e.required)?e.required:[];return Object.entries(e.properties).map(([e,n])=>({name:e,type:ix(n),required:t.includes(e),description:rx(n)&&typeof n.description==`string`?n.description:``}))}return t.map(e=>({name:e,type:null,required:null,description:``}))}function ox(e,t){if(t.length===0||!rx(e)||!rx(e.properties))return e;let n=Object.keys(e.properties);return n.length===t.length&&t.every(e=>n.includes(e))?e:void 0}function sx(e,t,n){return[`sim-event-${e}-${t}-${n}`,`turn-row-${t}-h`].find(e=>document.getElementById(e)!==null)??null}function cx({caption:e,rows:t,none:n}){let r=(0,b.useId)(),[i,a,o,s]=Rv.columns;return t.length===0?(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`p`,{className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`p`,{className:Jb.quiet,children:n})]}):(0,x.jsxs)(`table`,{className:Jb.fields,role:`table`,"aria-labelledby":r,children:[(0,x.jsx)(`caption`,{id:r,className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`thead`,{role:`rowgroup`,children:(0,x.jsx)(`tr`,{role:`row`,children:Rv.columns.map(e=>(0,x.jsx)(`th`,{role:`columnheader`,scope:`col`,children:e},e))})}),(0,x.jsx)(`tbody`,{role:`rowgroup`,children:t.map(e=>(0,x.jsxs)(`tr`,{role:`row`,children:[(0,x.jsx)(`td`,{role:`cell`,"data-label":i,"data-code":``,translate:`no`,children:e.name}),e.type===null?(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-quiet":``,children:Rv.notRecorded}):(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-code":``,translate:`no`,children:e.type}),(0,x.jsx)(`td`,{role:`cell`,"data-label":o,children:e.required===null?``:e.required?Rv.yes:Rv.no}),(0,x.jsx)(`td`,{role:`cell`,"data-label":s,children:e.description})]},e.name))})]})}function lx({entry:e,attempt:t,actor:n,onGoToEvent:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useId)(),s=t??e.history[0]??null,c=s?.turn??e.firstForgedTurn,l=s?.eventIndex??0,u=s?.department||e.firstForgedDepartment,d=s?.eventTitle??``,f=t?.description||e.description,[p,m]=(0,b.useState)(null);(0,b.useEffect)(()=>{m(sx(e.actorIndex,c,l))},[e.actorIndex,c,l]);let h=e=>{let t=p?document.getElementById(p):null;t&&(e.preventDefault(),r(t))},g=t&&t.inputFields.length>0?t.inputFields:e.inputFields,_=t&&t.outputFields.length>0?t.outputFields:e.outputFields,v=ox(e.inputSchema,t?t.inputFields:[]),y=ox(e.outputSchema,t?t.outputFields:[]),S=v!=null||y!=null;return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsxs)(`div`,{className:Jb.actor,style:{"--actor":n.colour},"data-actor-line":!0,children:[(0,x.jsx)(`span`,{className:Jb.rule,"aria-hidden":`true`,"data-actor-rule":!0}),(0,x.jsxs)(`div`,{className:Jb.actorText,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Iv({label:n.label,name:n.name,archetype:n.archetype,department:u,turn:c,eventTitle:d})}),p&&d&&(0,x.jsx)(`a`,{className:Jb.link,href:`#${p}`,onClick:h,children:Lv(d)})]})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`h3`,{id:o,className:Jb.heading,"data-text":`heading`,children:Rv.whatItDoes}),(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:f})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[S&&(0,x.jsx)(`div`,{className:Jb.fieldsBar,children:(0,x.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":i,className:Jb.switch,onClick:()=>a(e=>!e),children:[(0,x.jsx)(`span`,{className:Jb.switchTrack,"aria-hidden":`true`}),Rv.rawJson]})}),i&&S?(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,"data-raw-json":!0,children:JSON.stringify({input:v??null,output:y??null},null,2)}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(cx,{caption:Rv.inputFields,rows:ax(v,g),none:Rv.noInputFields}),(0,x.jsx)(cx,{caption:Rv.outputFields,rows:ax(y,_),none:Rv.noOutputFields})]})]})]})}var ux=5e3;function dx(){let[e,t]=(0,b.useState)(()=>typeof navigator>`u`||navigator.onLine!==!1);return(0,b.useEffect)(()=>{let e=()=>t(navigator.onLine!==!1);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]),e}function fx(){try{return window.localStorage}catch{return null}}function px({entry:e,attempt:t,open:n,actorCount:r,runKey:i,sessionId:a=null,events:o,onClose:s,onGoToEvent:c,onShowInEventLog:l,onShown:u}){let d=D_(),f=Pt(!0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useId)();(0,b.useEffect)(()=>{[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null)?.focus()},[]),(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let[g,_]=(0,b.useState)(t),v=e.attempts.length,y=M_(e,g??NaN),S=y>0?e.attempts[y-1]:null,C=S?S.approved?`passed`:`did_not_pass`:e.outcome,w=C===`passed`,T=S?S.errorReason:e.errorReason??null,E=S?.confidence??e.confidence,D=N_(e,y),O=(0,b.useMemo)(()=>Kb(w),[w]),k=O_.filter(e=>(D.stations[e]===`reached`||D.stations[e]===`stopped`)&&O(e)),A=(0,b.useMemo)(()=>qb(window.location.href,i),[i]),[j,ee]=(0,b.useState)(()=>{let e=fx(),t=e?Ub(e,A):[];return Gb(D,[...t,...n??[]],O)}),te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(!te.current){te.current=!0;for(let e of O_)e!==D.deciding&&j.has(e)&&B_({name:`forge_station_open`,station:e,via:`kept`})}},[D.deciding,j]);let M=e=>{ee(e);let t=fx();t&&Wb(t,A,[...e])},N=e=>{let t=new Set(j);t.has(e)?t.delete(e):(t.add(e),B_({name:`forge_station_open`,station:e,via:`press`})),M(t)},ne=k.every(e=>j.has(e)),P=()=>{if(!ne)for(let e of k)j.has(e)||B_({name:`forge_station_open`,station:e,via:`open_all`});M(new Set(ne?k.filter(e=>e===D.deciding):k))},re=(0,b.useRef)(null),ie=(t,n)=>{let r=M_(e,t);if(r===0||r===y)return;let i=e.attempts[r-1].approved;ee(Gb(N_(e,r),[...j],Kb(i))),re.current=n?y:null,_(r)},F=(0,b.useRef)(y);(0,b.useEffect)(()=>{F.current!==y&&(F.current=y,g===void 0&&ee(e=>Gb(D,[...e],O)))},[y,g,D,O]),(0,b.useEffect)(()=>{let e=re.current;re.current=null,e!==null&&(f.current?.querySelector(`[data-fork-attempt="${e}"]`)??[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null))?.focus()},[y,f]),(0,b.useEffect)(()=>{u?.({attempt:y,open:O_.filter(e=>j.has(e))})},[u,y,j]);let{shared:I,share:ae,clear:oe}=on(),se=dx(),ce=(0,b.useId)();(0,b.useEffect)(()=>{if(I?.state!==`copied`)return;let e=window.setTimeout(oe,ux);return()=>window.clearTimeout(e)},[I,oe]);let le=()=>{a&&(B_({name:`forge_link_copy`}),ae(Z_(window.location.origin,a,Q_(window.location.href),{actorIndex:e.actorIndex,toolName:e.name,...y>0?{attempt:y}:{},open:O_.filter(e=>j.has(e))},d)))},L=I?.state===`refused`||I?.state===`unanswered`,[ue,de]=(0,b.useState)(!1),fe=(0,b.useMemo)(()=>ue?Yb(o,e.name):[],[ue,o,e.name]),R=()=>{B_({name:`forge_log_jump`}),l()},z=t=>{switch(t){case`request`:return S?.description||e.description;case`code`:return w?(0,x.jsx)(tx,{station:`code`}):null;case`tests`:return w?(0,x.jsx)(tx,{station:`tests`}):null;case`judge`:return w?Nv(E):null;case`added`:return w?Pv(F_(e)):null}},pe=d.actors[e.actorIndex];return(0,x.jsx)(`div`,{className:ky.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&s()},children:(0,x.jsxs)(`div`,{ref:f,role:`dialog`,"aria-modal":`true`,"aria-label":wv(e.name,e.n),tabIndex:-1,className:ky.dialog,children:[(0,x.jsxs)(`div`,{className:ky.header,"data-forge-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,onClick:()=>s(),"aria-label":Ev,title:Ev,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(zy,{index:e.actorIndex,colour:Pe(e.actorIndex)}),(0,x.jsx)(`span`,{className:ky.number,children:Tv(e.n)}),(0,x.jsx)(`h2`,{ref:p,className:`${ky.name} ${ky.nameInRow}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`span`,{className:ky.headerEnd,children:[a&&(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,onClick:le,"aria-label":Dv.key,"aria-describedby":ce,title:Dv.key,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6.5 9.5L9.5 6.5M7 4.5L8.5 3a2.5 2.5 0 0 1 3.5 3.5L10.5 8M9 11.5L7.5 13A2.5 2.5 0 0 1 4 9.5L5.5 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(Ay,{})]})]}),a&&(0,x.jsxs)(`div`,{id:ce,className:ky.linkNote,role:`status`,"aria-live":`polite`,"data-link-note":!0,children:[!se&&(0,x.jsx)(`p`,{className:ky.linkSaid,children:Dv.offline}),I?.state===`copied`&&(0,x.jsx)(`p`,{className:ky.linkSaid,children:Dv.copied}),L&&I&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:ky.linkSaid,children:Dv.failed}),(0,x.jsx)(`p`,{className:ky.linkText,"data-tool-link":!0,translate:`no`,children:I.url})]})]}),(0,x.jsxs)(`div`,{className:ky.head,"data-forge-head":!0,children:[v>1&&(0,x.jsxs)(`div`,{className:ky.attempts,role:`group`,"aria-label":qv(y,v),children:[(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,"aria-label":Gv.previous,title:Gv.previous,"aria-disabled":y<=1||void 0,onClick:()=>{y>1&&ie(y-1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M10 3.5L5.5 8L10 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(`span`,{className:ky.attemptLine,"data-attempt-line":!0,"aria-hidden":`true`,children:y===v?Kv(y,v):qv(y,v)}),(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.iconKey}`,"aria-label":Gv.next,title:Gv.next,"aria-disabled":y>=v||void 0,onClick:()=>{y<v&&ie(y+1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})})]}),(0,x.jsx)(`p`,{className:ky.label,children:kv}),(0,x.jsx)(`h2`,{ref:m,className:`${ky.name} ${ky.nameInHead}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`p`,{className:ky.outcome,"data-forge-outcome":!0,"data-text":`heading`,children:[(0,x.jsx)(ub,{kind:k_(C),size:20}),(0,x.jsx)(`span`,{children:Av[C]})]}),!w&&(0,x.jsx)(nx,{reason:T})]}),(0,x.jsxs)(`div`,{className:ky.line,children:[k.length>1&&(0,x.jsx)(`div`,{className:ky.lineHead,children:(0,x.jsx)(`button`,{type:`button`,className:ky.key,"aria-label":ne?Fv.closeName:Fv.openName,onClick:P,children:ne?Fv.close:Fv.open})}),(0,x.jsx)(_b,{model:D,size:`trace`,colour:P_(e.actorIndex,r),open:j,onToggle:N,stationResult:z,renderEvidence:t=>{if(!O(t))return null;switch(t){case`request`:return(0,x.jsx)(lx,{entry:e,attempt:S,actor:{label:pe?.label??Sv(e.actorIndex),name:e.actorName,archetype:pe?.archetype??``,colour:Pe(e.actorIndex)},onGoToEvent:c});case`judge`:return(0,x.jsx)(ex,{confidence:E});case`added`:return(0,x.jsx)($b,{entry:e});default:return null}},onAttempt:e=>ie(e,!0)})]}),(0,x.jsxs)(`div`,{className:ky.recordFoot,children:[(0,x.jsx)(`button`,{type:`button`,className:`${ky.key} ${ky.recordKey}`,"aria-expanded":ue,"aria-controls":h,onClick:()=>de(e=>!e),children:Uv.key}),(0,x.jsx)(`div`,{id:h,className:ky.recordBody,hidden:!ue,children:ue&&(0,x.jsx)(Qb,{entry:e,frames:fe,onShowInEventLog:R})})]})]})})}var mx={trace:null,toolbox:!1},hx=[];function gx(e){let{show:t,find:n,group:r,actors:i}=q_(e,{getEntryByNumber:()=>void 0,actors:[]},!1).state.toolbox;return{show:tv.includes(t)?t:`all`,find:n??``,group:nv.includes(r)?r:null,actors:[...new Set((i??[]).map(e=>e-1))].sort((e,t)=>e-t)}}var _x=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),vx=(e,t)=>e.show===t.show&&e.find===t.find&&e.group===t.group&&_x(e.actors,t.actors);function yx({state:e,runKey:t,sessionId:n,showToolLog:r,children:i}){let a=D_(),[o,s]=(0,b.useState)(mx),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(!1),d=(0,b.useRef)(!1),f=(0,b.useRef)(0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useRef)(a);h.current=a;let g=(0,b.useRef)(e.isComplete);g.current=e.isComplete;let _=(0,b.useRef)(o);_.current=o;let v=(0,b.useRef)(null),[y,S]=(0,b.useState)(null),[C,w]=(0,b.useState)(()=>typeof window>`u`?iv:gx(window.location.href)),T=(0,b.useRef)(C),E=(0,b.useCallback)(()=>{let e=window.location.href,t=Y_(e,{...u.current&&d.current?{open:!0}:{},...T.current});if(t!==e)try{window.history.replaceState(window.history.state,``,t)}catch{}},[]),D=(0,b.useCallback)(e=>{let t=T.current,n={...t,...e};vx(n,t)||(T.current=n,w(n),E())},[E]),O=(0,b.useCallback)(()=>{d.current||=(v.current=window.location.href,window.history.pushState({forgeView:!0},``),!0)},[]),k=(0,b.useCallback)((e,t,n)=>{h.current.getEntryFor(e.actorIndex,e.toolName)&&(n&&B_({name:`forge_trace_open`,from:n}),u.current?l.current=t??null:c.current=t??null,O(),S(null),s(t=>({trace:e,toolbox:t.toolbox})))},[O]),A=(0,b.useCallback)((e,t)=>{u.current||(t&&B_({name:`forge_toolbox_open`,from:t}),c.current=e??null,u.current=!0,O(),E(),s(e=>({trace:e.trace,toolbox:!0})))},[O,E]),j=(0,b.useCallback)((e,t)=>{if(e instanceof HTMLElement&&(c.current=e,p.current=e),l.current=null,u.current=!1,s(mx),d.current){d.current=!1;let e=v.current;v.current=null,e!==null&&e!==window.location.href&&window.history.replaceState(window.history.state,``,e),f.current+=1,m.current=t??null,window.history.back()}else t?.()},[]),ee=(0,b.useCallback)(()=>{if(!u.current){j();return}S(null),s({trace:null,toolbox:!0});let e=window.location.href,t=X_(e,U_);t!==e&&window.history.replaceState(window.history.state,``,t)},[j]),te=(0,b.useCallback)(()=>j(),[j]);(0,b.useEffect)(()=>{let e=()=>{if(f.current>0){--f.current,E();let e=m.current;m.current=null,e?.();let t=p.current;p.current=null,t?.isConnected&&requestAnimationFrame(()=>{t.scrollIntoView({block:`nearest`}),document.activeElement!==t&&t.focus({preventScroll:!0})})}else if(d.current)_.current.trace&&u.current?(S(null),s({trace:null,toolbox:!0}),d.current=!1,O(),E()):(d.current=!1,v.current=null,l.current=null,u.current=!1,s(mx),E());else{if(window.history.state?.forgeView!==!0)return;let{state:e}=q_(window.location.href,h.current,g.current);if(!e.trace&&!e.toolbox.open)return;d.current=!0,v.current=Y_(X_(window.location.href,U_),{open:!1,...T.current}),u.current=e.toolbox.open,S(null),s({trace:e.trace??null,toolbox:e.toolbox.open})}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[O,E]);let M=o.trace,N=M?a.getEntryFor(M.actorIndex,M.toolName):void 0,ne=N?e.actors[e.actorIds[N.actorIndex]]?.events??hx:hx,P=(0,b.useCallback)(()=>{if(!N)return;let{name:e,actorName:t}=N;j(null,()=>r?.(e,t))},[N,j,r]),re=(0,b.useCallback)(t=>{let n=e.actorIds[t];n&&j(null,()=>r?.(``,n))},[e.actorIds,j,r]);(0,b.useEffect)(()=>{M&&!N&&ee()},[M,N,ee]),(0,b.useEffect)(()=>{if(!M||!N||!d.current)return;let e=window.location.href,t=J_(e,{trace:{actorIndex:N.actorIndex,toolName:N.name,...y&&y.attempt>0?{attempt:y.attempt}:{},...y?{open:y.open}:{}},toolbox:q_(e,a,!1).state.toolbox},a);t!==e&&window.history.replaceState(window.history.state,``,t)},[M,N,y,a]);let ie=e.isComplete,F=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!ie)return;let e=`${t??``}|${n??``}`;if(F.current===e)return;F.current=e;let r=window.location.href,{state:i,dangling:o}=q_(r,a,!0);o.length>0&&window.history.replaceState(window.history.state,``,X_(r,o));let s=gx(window.location.href),c={...s,actors:s.actors.filter(e=>e<a.actors.length)};if(vx(c,T.current)||(T.current=c,w(c)),_.current.trace||_.current.toolbox)return;let l=Y_(X_(window.location.href,U_),{open:!1,...c});l!==window.location.href&&window.history.replaceState(window.history.state,``,l),i.toolbox.open&&A(null),i.trace&&k(i.trace,null,`link`)},[ie,t,n,a,k,A]);let I=M!==null,ae=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(I){ae.current=!0;return}if(!ae.current||(ae.current=!1,!o.toolbox))return;let e=l.current;l.current=null,e?.isConnected?e.focus():document.querySelector(`[data-toolbox-title]`)?.focus()},[I,o.toolbox]);let oe=M!==null||o.toolbox,se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(oe){se.current=!0;return}if(!se.current)return;se.current=!1;let e=c.current;c.current=null,e?.isConnected&&e.focus()},[oe]);let ce=(0,b.useMemo)(()=>({openTrace:k,openToolbox:A,close:j,showActorLog:re,current:o}),[k,A,j,re,o]),le=(0,b.useMemo)(()=>({...C,set:D}),[C,D]);return(0,x.jsx)($_.Provider,{value:ce,children:(0,x.jsxs)(ov.Provider,{value:le,children:[i,o.toolbox&&(0,x.jsx)(Rb,{covered:M!==null,onClose:te}),M&&N&&(0,x.jsx)(px,{entry:N,attempt:M.attempt,open:M.open,actorCount:e.actorIds.length,runKey:t,sessionId:ie?n:null,events:ne,onShown:S,onClose:ee,onGoToEvent:j,onShowInEventLog:P},`${N.actorIndex}:${N.name}`)]})})}var bx=420,xx=260;function Sx({content:e,children:t,dot:n,block:r,disabled:i=!1}){let[a,o]=(0,b.useState)(!1),[s,c]=(0,b.useState)({x:0,y:0}),l=(0,b.useRef)(null),u=(0,b.useRef)(void 0);b.useEffect(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),o(!1))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=(0,b.useCallback)(e=>{clearTimeout(u.current);let t=e.currentTarget.getBoundingClientRect(),n=Math.min(bx,window.innerWidth-20),r=t.left,i=t.top-xx-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+xx>window.innerHeight-10&&(i=window.innerHeight-xx-10),i<10&&(i=10),c({x:r,y:i}),o(!0)},[]),f=(0,b.useCallback)(()=>{u.current=setTimeout(()=>o(!1),100)},[]),p=a&&!i?(0,x.jsx)(`div`,{id:`paracosm-tooltip`,role:`tooltip`,onMouseEnter:()=>{clearTimeout(u.current),o(!0)},onMouseLeave:f,style:{position:`fixed`,left:s.x,top:s.y,zIndex:99999,background:`var(--bg-card)`,border:`2px solid var(--amber)`,borderRadius:`8px`,padding:`14px 18px`,fontSize:`var(--font-sm)`,color:`var(--text-1)`,lineHeight:1.6,width:`${bx}px`,maxWidth:`90vw`,maxHeight:`80vh`,overflowY:`auto`,boxShadow:`0 8px 40px rgba(0,0,0,.4)`,pointerEvents:`auto`,whiteSpace:`normal`,wordBreak:`break-word`,animation:`fadeUp 0.15s ease both`},children:e}):null;return(0,x.jsxs)(`span`,{ref:l,onMouseEnter:d,onMouseLeave:f,style:{position:`relative`,display:r?`block`:`inline-flex`,alignItems:r?void 0:`center`,width:r?`100%`:void 0,minWidth:r?0:void 0,cursor:`pointer`},tabIndex:0,"aria-describedby":a?`paracosm-tooltip`:void 0,onFocus:d,onBlur:f,children:[t,n&&(0,x.jsx)(`span`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`var(--amber)`,opacity:a?.8:0,marginLeft:`3px`,transition:`opacity 0.15s`,flexShrink:0,display:`inline-block`,verticalAlign:`middle`},"aria-hidden":`true`}),p&&typeof document<`u`?(0,jy.createPortal)(p,document.body):null]})}var Cx={root:`_root_a1e21_1`,triggerButton:`_triggerButton_a1e21_6`,triggerCaret:`_triggerCaret_a1e21_29`,menuPopover:`_menuPopover_a1e21_34`,menuButton:`_menuButton_a1e21_49`,loadFileButton:`_loadFileButton_a1e21_49`,runSavedButton:`_runSavedButton_a1e21_49`,runNewButton:`_runNewButton_a1e21_49`,menuButtonInnerLeft:`_menuButtonInnerLeft_a1e21_68`,menuButtonIcon:`_menuButtonIcon_a1e21_74`,runNewBadge:`_runNewBadge_a1e21_94`,disabled:`_disabled_a1e21_116`,runSavedBadge:`_runSavedBadge_a1e21_128`,savedCardsWrap:`_savedCardsWrap_a1e21_145`,savedStatus:`_savedStatus_a1e21_149`,savedError:`_savedError_a1e21_149`,loadFileBadge:`_loadFileBadge_a1e21_170`,sessionCard:`_sessionCard_a1e21_181`,sessionCardTitle:`_sessionCardTitle_a1e21_203`,sessionCardLine2:`_sessionCardLine2_a1e21_212`,sessionCardLine3:`_sessionCardLine3_a1e21_218`,tooltipHeading:`_tooltipHeading_a1e21_224`,historyRow:`_historyRow_a1e21_234`,historyRowLabel:`_historyRowLabel_a1e21_259`,historyRowBadge:`_historyRowBadge_a1e21_265`,historyList:`_historyList_a1e21_276`,historyCardWrap:`_historyCardWrap_a1e21_285`,historyCard:`_historyCard_a1e21_285`,historyCardTitle:`_historyCardTitle_a1e21_310`,historyCardLine2:`_historyCardLine2_a1e21_318`,historyCardLine3:`_historyCardLine3_a1e21_324`,historyDelete:`_historyDelete_a1e21_329`,historyClearAll:`_historyClearAll_a1e21_353`},wx=Cx;function Tx(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ex(e){if(!e||e<=0)return`·`;let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Dx(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Ox({s:e,onPick:t}){let n=Rn(e),r=n?`${n}${e.scenarioName?` · ${e.scenarioName}`:``}`:e.scenarioName||`Simulation Run`,i=e.title||e.scenarioName||r,a=[n,e.title&&e.scenarioName?e.scenarioName:``,e.turnCount==null?``:`${e.turnCount} turn${e.turnCount===1?``:`s`}`].filter(Boolean).join(` · `),o=`${new Date(e.createdAt).toLocaleString()} (${Tx(e.createdAt)}) · ${Ex(e.durationMs)} · ${Dx(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Cx.sessionCard,children:[(0,x.jsx)(`div`,{className:Cx.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Cx.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Cx.sessionCardLine3,children:o})]})}function kx({onRun:e,onLoadFromFile:t,history:n=[],onRestoreHistory:r,onClearHistory:i,liveStateHasEvents:a=!1}){let[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(!1),[u,d]=(0,b.useState)(!0),f=(0,b.useRef)(null),{sessions:p,status:m,refresh:h}=Oe(),g=p.length>0,_=eA();(0,b.useEffect)(()=>{o&&h()},[o,h]);let v=(0,b.useCallback)(()=>{s(!1),l(!1)},[]);(0,b.useEffect)(()=>{if(!o)return;let e=e=>{f.current&&!f.current.contains(e.target)&&v()},t=e=>{e.key===`Escape`&&v()};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[o,v]);let y=()=>{_&&(v(),e?.())},S=e=>{window.location.assign(kg(window.location.href,e))},C=()=>{v(),t?.()},w=Og(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Cx.root,children:[(0,x.jsx)(Sx,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Cx.tooltipHeading,children:`Run`}),(0,x.jsx)(`div`,{children:`Launches a fresh simulation, replays a cached one, or loads a saved JSON from disk. Click to open the menu.`})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>s(e=>!e),"aria-haspopup":`menu`,"aria-expanded":o,className:Cx.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Cx.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Cx.runNewButton,children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Cx.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Cx.runSavedButton,g?``:Cx.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Cx.runSavedBadge,g?``:Cx.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Cx.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Ox,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Cx.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Session cache is disabled on this server.`})]}),n.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,className:wx.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:wx.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:wx.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:wx.historyList,children:[n.map(e=>{let t=Date.parse(e.createdAt)||e.id,n=(e.summary.actorNames??[]).join(` vs `)||e.scenarioShortName,i=e.summary.turnCount?`${e.summary.turnCount} turn${e.summary.turnCount===1?``:`s`}`:``,o=[n,n===e.scenarioShortName?``:e.scenarioShortName,i].filter(Boolean).join(` · `),s=`${Tx(t)} · ${e.summary.eventCount} ev · ${Dx(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:wx.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:wx.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:wx.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:wx.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:wx.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:wx.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. It also lets go of this browser's run on the server, stopping it if it is running. Run history, saved sessions and output files are kept: Delete server data in the ⋯ menu deletes those, where admin writes are on and an admin token is saved.`,onClick:()=>{window.confirm(`Clear all local browser state?
|
|
114
114
|
|
|
115
115
|
• Saved-runs ring (this dropdown)
|
|
116
116
|
• Event cache (Sim / Constellation / Log)
|
|
@@ -125,7 +125,7 @@ Cannot be undone.`)&&i()},children:`Clear local data`})]})]}),t&&(0,x.jsxs)(`but
|
|
|
125
125
|
`);o=n.pop()||``;for(let e of n)if(e.startsWith(`data: `))try{let t=JSON.parse(e.slice(6));if(t.hook&&O(e=>{let n=e.findIndex(e=>e.hook===t.hook);if(n>=0){let r=[...e];return r[n]=t,r}return[...e,t]}),t.id){let e=null;try{let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t.id})});n.ok||(e=(await n.json().catch(()=>({}))).error??`HTTP ${n.status}`)}catch(t){e=String(t)}if(e){A({success:!1,message:`Compiled ${t.id}, but switching to it failed: ${e}`});continue}try{window.sessionStorage.setItem(Rw,JSON.stringify({success:!0,message:`Compiled: ${t.id} (${t.departments} departments, ${t.hooks} hooks). Configure actors below and launch.`}))}catch{}te(),window.location.reload();return}t.error&&A({success:!1,message:t.error})}catch{}}}catch(e){A({success:!1,message:String(e)})}S(!1)},[r,a,s,l,d,p,h,_]),oe=r.split(`
|
|
126
126
|
`).length,se=new Blob([r]).size;return(0,x.jsxs)(`div`,{className:Iw.card,children:[(0,x.jsxs)(`div`,{className:Iw.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:Iw.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:Iw.lead,children:[`Write or import a scenario JSON draft. Add seed text or a URL to ground it, then compile or export.`,!t.adminWrite&&` Disk saves are disabled on this instance.`]})]}),(0,x.jsxs)(`div`,{className:Iw.btnRow,children:[(0,x.jsx)(`button`,{onClick:ne,className:[Iw.btn,Iw.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:N,className:Iw.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:P,className:Iw.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:ie,className:Iw.btn,disabled:!r.trim()||!!a,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,onChange:re,className:Iw.fileInput})]})]}),(0,x.jsxs)(`div`,{className:Iw.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:ee,value:r,onChange:e=>i(e.target.value),placeholder:`{\\n "id": "my-scenario",\\n "labels": { "name": "My World" },\\n "departments": [...]\\n}`,spellCheck:!1,"aria-label":`Scenario JSON editor`,className:Iw.editor}),(0,x.jsxs)(`div`,{className:Iw.statusBar,style:{"--status-color":a?`var(--rust)`:`var(--text-3)`},children:[(0,x.jsx)(`span`,{children:a||(r.trim()?`Valid JSON`:`Empty`)}),(0,x.jsxs)(`span`,{children:[oe,` lines, `,(se/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:Iw.seedDetails,children:[(0,x.jsx)(`summary`,{className:Iw.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:Iw.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed Text`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`Paste a prompt, notes, a brief, or source text to turn into research facts and category mapping.`,className:Iw.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),placeholder:`https://example.com/article`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),inputMode:`numeric`,placeholder:`5`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),placeholder:`anthropic or openai (optional)`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Model Override`}),(0,x.jsx)(`input`,{value:_,onChange:e=>v(e.target.value),placeholder:`gpt-5.4-mini, claude-sonnet-4-6, etc. (optional)`,className:Iw.input})]}),(0,x.jsxs)(`label`,{className:Iw.checkboxLabel,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Web search enrichment (requires Serper/Tavily/Firecrawl API keys)`]}),(0,x.jsx)(`p`,{className:Iw.fineprint,children:`If both seed text and a seed URL are provided, the URL takes precedence and the compiler ingests the fetched page.`})]})]}),T.length>0&&(0,x.jsx)(`div`,{className:Iw.progressWrap,children:T.map(e=>(0,x.jsxs)(`div`,{className:Iw.progressRow,children:[(0,x.jsx)(`span`,{children:e.status===`done`?`✔`:e.status===`generating`?`⏳`:e.status===`cached`?`✔`:`•`}),(0,x.jsx)(`span`,{children:e.hook}),(0,x.jsx)(`span`,{className:Iw.progressStatus,children:e.status})]},e.hook))}),k&&(0,x.jsx)(`div`,{className:Iw.result,style:{"--result-color":k.success?`var(--green)`:`var(--rust)`,"--result-bg":k.success?`rgba(106,173,72,.06)`:`rgba(224,101,48,.06)`},children:k.message}),(0,x.jsxs)(`div`,{className:Iw.actions,children:[(0,x.jsx)(`button`,{onClick:F,disabled:!r.trim()||!!a||C,className:Iw.actionBtn,"aria-label":`Store scenario in memory`,children:C?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:ae,disabled:!r.trim()||!!a||y,className:[Iw.actionBtn,Iw.primary].join(` `),"aria-label":`Compile scenario`,children:y?`Compiling...`:`Compile Scenario`}),t.adminWrite&&(0,x.jsx)(`button`,{onClick:I,disabled:!r.trim()||!!a,className:[Iw.actionBtn,Iw.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:Iw.spacer}),t.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:Iw.memCount,children:[t.memoryScenarios.length,` in memory`]})]})]})}var Vw={intro:`_intro_v1quw_1`,label:`_label_v1quw_13`,row:`_row_v1quw_24`,input:`_input_v1quw_31`,btn:`_btn_v1quw_45`,amber:`_amber_v1quw_65`,status:`_status_v1quw_70`,refusal:`_refusal_v1quw_77`},Hw={none:`No token is saved in this browser.`,stored:`A token is saved in this browser. It is not shown back.`,held:`This browser could not store the token, so it is kept only until this page reloads.`};function Uw(){let e=(0,b.useRef)(null),[t,n]=(0,b.useState)(!1),[r,i]=(0,b.useState)(()=>ve()),[a,o]=(0,b.useState)(null);(0,b.useEffect)(()=>Se(()=>i(ve())),[]);let s=()=>{e.current&&(e.current.value=``),n(!1)},c=()=>{let t=e.current?.value??``;if(!t.trim())return;let n=ye(t);n===`unsendable`?o(z):(o(null),i(n),s())};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`p`,{className:Vw.intro,children:[`Admin writes on this server take its `,(0,x.jsx)(`code`,{children:`ADMIN_TOKEN`}),`: Save to Disk in the scenario editor below, Delete server data in the run actions menu, and Rename and Delete in a scenario's details. Enter the token once. The dashboard sends it only on those requests, as the `,(0,x.jsx)(`code`,{children:`X-Admin-Token`}),` header, and keeps it in this browser.`]}),(0,x.jsx)(`label`,{htmlFor:`admin-token`,className:Vw.label,children:`Token for this server`}),(0,x.jsxs)(`div`,{className:Vw.row,children:[(0,x.jsx)(`input`,{id:`admin-token`,type:`password`,autoComplete:`off`,spellCheck:!1,ref:e,onChange:e=>{n(e.target.value.trim()!==``),o(null)},onKeyDown:e=>{e.key===`Enter`&&c()},placeholder:r===`none`?`Not entered`:`Saved`,"aria-describedby":`admin-token-status`,className:Vw.input}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!t,className:[Vw.btn,Vw.amber].join(` `),"aria-label":`Save admin token`,children:`Save`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{be(),i(`none`),o(null),s()},disabled:r===`none`&&!t,className:Vw.btn,"aria-label":`Clear admin token`,children:`Clear`})]}),(0,x.jsx)(`div`,{id:`admin-token-status`,role:`status`,className:Vw.status,children:Hw[r]}),a&&(0,x.jsx)(`p`,{role:`alert`,className:Vw.refusal,children:a})]})}var Ww={bar:`_bar_127em_1`,topRow:`_topRow_127em_15`,searchWrap:`_searchWrap_127em_22`,searchIcon:`_searchIcon_127em_30`,searchInput:`_searchInput_127em_35`,resetButton:`_resetButton_127em_50`,facetsRow:`_facetsRow_127em_76`,facetLabel:`_facetLabel_127em_83`,checkboxGroup:`_checkboxGroup_127em_93`,checkbox:`_checkbox_127em_93`,active:`_active_127em_115`,leaderSelect:`_leaderSelect_127em_128`,rangeWrap:`_rangeWrap_127em_142`,rangeInput:`_rangeInput_127em_151`,toolChip:`_toolChip_127em_162`,chipClear:`_chipClear_127em_176`,emptyHint:`_emptyHint_127em_188`};function Gw(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function Kw({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>$m(e),[e]),i=Gw(t),a=e=>{n({...t,...e})},o=e=>{let n=new Set(t.types);n.has(e)?n.delete(e):n.add(e),a({types:n})},s=e=>t.types.size===0||t.types.has(e);return(0,x.jsxs)(`div`,{className:Ww.bar,children:[(0,x.jsxs)(`div`,{className:Ww.topRow,children:[(0,x.jsxs)(`div`,{className:Ww.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ww.searchIcon,children:`🔍`}),(0,x.jsx)(`input`,{type:`search`,"aria-label":`Filter log by text (type, leader, department, title, summary)`,placeholder:`Search type, leader, department, title, summary...`,value:t.query,onChange:e=>a({query:e.target.value}),className:Ww.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:Ww.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:Ww.chipClear,onClick:()=>a({toolHash:``,toolExact:!1}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:Ww.resetButton,disabled:!i,onClick:()=>n(Jm()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:Ww.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[Ww.checkbox,t?Ww.active:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>o(e)}),e]},e)})})]}),(r.actors.length>1||r.maxTurn>3)&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:Ww.leaderSelect,value:t.leader??``,onChange:e=>a({leader:e.target.value||null}),children:[(0,x.jsx)(`option`,{value:``,children:`all`}),r.actors.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),r.maxTurn>3&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:Ww.rangeWrap,children:[(0,x.jsx)(`input`,{type:`number`,"aria-label":`Min turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[0]:0,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let i=t.turnRange?.[1]??r.maxTurn;a({turnRange:[n,Math.max(n,i)]})},className:Ww.rangeInput}),(0,x.jsx)(`span`,{children:`to`}),(0,x.jsx)(`input`,{type:`number`,"aria-label":`Max turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[1]:r.maxTurn,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let r=t.turnRange?.[0]??0;a({turnRange:[Math.min(r,n),n]})},className:Ww.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:Ww.chipClear,"aria-label":`Clear turn range`,onClick:()=>a({turnRange:null}),children:`×`})]})]})]}),t.types.size>0&&t.types.size===r.types.length&&(0,x.jsx)(`div`,{className:Ww.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var qw={panel:`_panel_aavxx_1`,header:`_header_aavxx_6`,heading:`_heading_aavxx_15`,filterBar:`_filterBar_aavxx_26`,filterLabel:`_filterLabel_aavxx_34`,filterValue:`_filterValue_aavxx_38`,emptyState:`_emptyState_aavxx_43`,event:`_event_aavxx_48`,eventSummary:`_eventSummary_aavxx_53`,index:`_index_aavxx_61`,type:`_type_aavxx_67`,leader:`_leader_aavxx_73`,turn:`_turn_aavxx_81`,title:`_title_aavxx_85`,department:`_department_aavxx_89`,outcome:`_outcome_aavxx_93`,dataBlock:`_dataBlock_aavxx_98`},Jw={status:`var(--teal)`,turn_start:`var(--rust)`,turn_done:`var(--rust)`,specialist_start:`var(--text-3)`,specialist_done:`var(--green)`,decision_pending:`var(--amber)`,decision_made:`var(--amber)`,outcome:`#e8b44a`,drift:`var(--teal)`,agent_reactions:`#6aad48`,bulletin:`var(--text-2)`,promotion:`var(--teal)`};function Yw(){return typeof window>`u`?rh(``,``):rh(window.location.search,window.location.hash)}function Xw({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!1),[r,i]=(0,b.useState)(Yw);(0,b.useEffect)(()=>{let e=()=>i(Yw());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let a=(0,b.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},[]);(0,b.useEffect)(()=>{if(!n.current)return;let e=t.current;e&&(e.scrollTop=e.scrollHeight)},[e.length]);let o=(0,b.useCallback)(e=>{i(t=>{try{let n=t.toolHash!==``&&e.toolHash===``;window.history.replaceState({},``,nh(window.location.href,e,n))}catch{}return e})},[]),s=Ym(e,r),c=r.query!==``||r.types.size>0||r.leader!==null||r.turnRange!==null||r.toolHash!==``;return(0,x.jsxs)(`div`,{ref:t,onScroll:a,className:`flex-1 overflow-y-auto p-4 font-mono text-xs ${qw.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:qw.header,children:(0,x.jsxs)(`h2`,{className:qw.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(Kw,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:qw.emptyState,children:c?`No events matched the current filter. Adjust or press Reset.`:`No events yet. Run a simulation to see the raw SSE event stream.`}),s.map((e,t)=>{let n=Jw[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:qw.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:qw.eventSummary,children:[(0,x.jsx)(`span`,{className:qw.index,children:t}),(0,x.jsx)(`span`,{className:qw.type,children:e.type}),(0,x.jsx)(`span`,{className:qw.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:qw.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:qw.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:qw.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:qw.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:qw.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var Zw=[{value:`economy`,label:`Economy`,description:`Cheapest path: gated research, cheap verdicts, tighter spend controls.`},{value:`balanced`,label:`Balanced`,description:`Current default mix for good quality per dollar on normal runs.`},{value:`quality`,label:`Quality`,description:`Push strategic roles and verdict synthesis upward when quality matters more than spend.`},{value:`deterministic_first`,label:`Deterministic First`,description:`Skip verdict synthesis and live-search escalation to reduce variance and cost.`}];function Qw(e){switch(e){case`hosted_demo`:return{label:`Hosted demo`,description:`Host-billed runs are capped and forced onto the economy guardrails.`};case`platform_api`:return{label:`Platform API`,description:"Authenticated `/api/v1/*` routes are enabled; demo-only assumptions are off."};default:return{label:`Local demo`,description:`Single-process local server. Good for product exploration, not a hosted control plane.`}}}var Y={root:`_root_34x3m_1`,content:`_content_34x3m_9`,scenarioRow:`_scenarioRow_34x3m_17`,scenarioLabel:`_scenarioLabel_34x3m_29`,scenarioSelect:`_scenarioSelect_34x3m_34`,scenarioActiveTag:`_scenarioActiveTag_34x3m_45`,scenarioActiveValue:`_scenarioActiveValue_34x3m_51`,h2:`_h2_34x3m_55`,lead:`_lead_34x3m_62`,scenarioTagline:`_scenarioTagline_34x3m_68`,scenarioSourceLink:`_scenarioSourceLink_34x3m_77`,leadHint:`_leadHint_34x3m_92`,leadStrong:`_leadStrong_34x3m_99`,leadersGrid:`_leadersGrid_34x3m_103`,leaderCardWrap:`_leaderCardWrap_34x3m_120`,leaderRemoveBtn:`_leaderRemoveBtn_34x3m_124`,leadersAddRow:`_leadersAddRow_34x3m_153`,leaderAddBtn:`_leaderAddBtn_34x3m_162`,leaderAddCap:`_leaderAddCap_34x3m_191`,fieldset:`_fieldset_34x3m_199`,legend:`_legend_34x3m_208`,demoBanner:`_demoBanner_34x3m_212`,demoBannerLabel:`_demoBannerLabel_34x3m_223`,simRow5:`_simRow5_34x3m_227`,grid3:`_grid3_34x3m_233`,grid2:`_grid2_34x3m_240`,input:`_input_34x3m_246`,locked:`_locked_34x3m_258`,lockTag:`_lockTag_34x3m_263`,fieldHint:`_fieldHint_34x3m_270`,keysIntro:`_keysIntro_34x3m_277`,keysIntroPara:`_keysIntroPara_34x3m_284`,keysIntroParaLast:`_keysIntroParaLast_34x3m_288`,keysIntroBoldNeutral:`_keysIntroBoldNeutral_34x3m_292`,keysIntroBoldGreen:`_keysIntroBoldGreen_34x3m_296`,keysIntroBoldAmber:`_keysIntroBoldAmber_34x3m_300`,keysIntroBoldRust:`_keysIntroBoldRust_34x3m_304`,keyEnvTag:`_keyEnvTag_34x3m_308`,modelTiersIntro:`_modelTiersIntro_34x3m_316`,demoMode:`_demoMode_34x3m_323`,demoModeStrong:`_demoModeStrong_34x3m_333`,launchRow:`_launchRow_34x3m_337`,launchBtn:`_launchBtn_34x3m_346`,launchStatus:`_launchStatus_34x3m_364`},$w=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],eT={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},tT={openai:[{value:`gpt-5.4-nano`,label:`gpt-5.4-nano ($0.20 / $1.25 per 1M)`},{value:`gpt-5.4-mini`,label:`gpt-5.4-mini ($0.75 / $4.50 per 1M)`},{value:`gpt-5.4`,label:`gpt-5.4 ($2.50 / $15.00 per 1M)`},{value:`gpt-5.4-pro`,label:`gpt-5.4-pro ($30 / $180 per 1M — avoid)`}],anthropic:[{value:`claude-haiku-4-5-20251001`,label:`Haiku 4.5 ($1 / $5 per 1M)`},{value:`claude-sonnet-4-6`,label:`Sonnet 4.6 ($3 / $15 per 1M)`},{value:`claude-opus-4-7`,label:`Opus 4.7 ($5 / $25 per 1M)`}]},nT={openai:{departments:`gpt-5.4`,commander:`gpt-5.4-mini`,director:`gpt-5.4-mini`,judge:`gpt-5.4-mini`,agentReactions:`gpt-5.4-nano`},anthropic:{departments:`claude-sonnet-4-6`,commander:`claude-haiku-4-5-20251001`,director:`claude-haiku-4-5-20251001`,judge:`claude-haiku-4-5-20251001`,agentReactions:`claude-haiku-4-5-20251001`}},rT={departments:{label:`Departments (forges)`,help:`Writes code, schemas, test cases. Quality matters — cheap tier produces broken forges.`},commander:{label:`Commander`,help:`Picks option from department reports. Mid-tier is fine.`},director:{label:`Event Director`,help:`Generates crisis events as structured JSON batches.`},judge:{label:`Judge (code review)`,help:`Reviews forged tool code for safety + correctness.`},agentReactions:{label:`Agent Reactions`,help:`One to two sentences per colonist per turn. Highest volume — pick cheapest.`}},iT=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function aT(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:iT[e]??`The Strategist`,unit:se(t,e),instructions:``,hexaco:{...eT}}}function oT(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function sT(e,t,n,r,i){let a=oT(n);return e.map((e,o)=>{let s=i[o],c=a?.[o],l=e.unit===se(t,o);if(!c)return(a!==void 0&&r!==n.id||l)&&s?.unit===void 0?{...e,unit:se(n,o)}:e;let u=r===n.id&&!!e.unit&&!l;return{name:c.name,archetype:c.archetype,unit:u?e.unit:c.unit??se(n,o),instructions:c.instructions,hexaco:{...c.hexaco},...s}})}var cT=2,lT=8;function uT({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),dh(e===`config`?null:e)},[]),a=Qk(),o=eA(),s=Lm(),c=nA(),l=iA(),u=typeof window<`u`?gg(window.localStorage):null,[d]=(0,b.useState)(()=>typeof window<`u`?hg(window.localStorage):null),[f,p]=(0,b.useState)(()=>{let e=Math.max(cT,Math.min(lT,Math.max(oT(a)?.length??0,u?.length??0)));return sT(Array.from({length:e},(e,t)=>{let n=u?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??se(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??eT}}:aT(t,a)}),a,a,d,[])}),m=(0,b.useRef)([]),h=(0,b.useRef)(a);(0,b.useEffect)(()=>{let e=h.current;h.current=a,p(t=>sT(t,e,a,d,m.current))},[a.id,a.presets.length]);let g=(0,b.useCallback)((e,t)=>{p(n=>n.map((n,r)=>{if(r!==e)return n;let i=Object.keys(t).filter(e=>t[e]!==n[e]);return m.current[e]={...m.current[e],...Object.fromEntries(i.map(e=>[e,t[e]]))},t}))},[]),_=(0,b.useCallback)(()=>{p(e=>e.length<lT?[...e,aT(e.length,a)]:e)},[a]),v=(0,b.useCallback)(e=>{m.current.splice(e,1),p(t=>t.length>cT?t.filter((t,n)=>n!==e):t)},[]),[y,S]=(0,b.useState)(a.setup.defaultTurns),[C,w]=(0,b.useState)(a.setup.defaultSeed),[T,E]=(0,b.useState)(a.setup.defaultStartTime),[O,A]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[j,ee]=(0,b.useState)(a.setup.defaultPopulation),M=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=M.current;e.has(`turns`)||S(a.setup.defaultTurns),e.has(`seed`)||w(a.setup.defaultSeed),e.has(`startTime`)||E(a.setup.defaultStartTime),e.has(`timePerTurn`)||A(a.setup.defaultTimePerTurn||0),e.has(`population`)||ee(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[N,ne]=(0,b.useState)(`openai`),[P,re]=(0,b.useState)(!1),[ie,F]=(0,b.useState)(`balanced`),[I,ae]=(0,b.useState)(!1),[oe,ce]=(0,b.useState)(``),[le,L]=(0,b.useState)([]),[ue,de]=(0,b.useState)(a.id),[fe,R]=(0,b.useState)({}),[z,pe]=(0,b.useState)(!1),[me,he]=(0,b.useState)(!1),[ge,_e]=(0,b.useState)(`local_demo`),[B,ve]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[ye,be]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:keyOverrides`);if(e){let t=JSON.parse(e);return{openai:t.openai||``,anthropic:t.anthropic||``,serper:t.serper||``,firecrawl:t.firecrawl||``,tavily:t.tavily||``,cohere:t.cohere||``}}}catch{}return{openai:``,anthropic:``,serper:``,firecrawl:``,tavily:``,cohere:``}});(0,b.useEffect)(()=>{try{localStorage.setItem(`paracosm:keyOverrides`,JSON.stringify(ye))}catch{}},[ye]);let[xe,Se]=(0,b.useState)(nT[N]??nT.openai);(0,b.useEffect)(()=>{let e=N;nT[e]&&Se(nT[e])},[N]);let Ce=xg(ye),we=!!fe.openai||!!fe.anthropic,Te=Ce||!z&&we,Ee=Ce||!z&&we,De=z&&!Ce?`economy`:ie,Oe=Qw(ge),ke=z&&!Ce,Ae=ke?`openai`:N,je=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{L(e.scenarios||[]),de(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(je(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&R(e.keys),typeof e.hostedDemo==`boolean`&&pe(e.hostedDemo),typeof e.adminWrite==`boolean`&&he(e.adminWrite),typeof e.serverMode==`string`&&_e(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&ve({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),D(window,je)),[je]);let Me=async e=>{if(e!==ue)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(te(),window.location.reload())}catch{}},Ne=(0,b.useCallback)(async()=>{if(o){ae(!0),ce(`Starting...`);try{let e={actors:f.map(e=>({...e,hexaco:e.hexaco})),provider:Ae,turns:y,seed:C,startTime:T,timePerTurn:O||void 0,population:j,liveSearch:P,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:De},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}mg(window.localStorage,f,a.id),Object.assign(e,bg(ye)),ye.serper&&(e.serperKey=ye.serper),ye.firecrawl&&(e.firecrawlKey=ye.firecrawl),ye.tavily&&(e.tavilyKey=ye.tavily),ye.cohere&&(e.cohereKey=ye.cohere),Ee&&(e.models={...xe});let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,captureSnapshots:!0})}),n=await t.json();if(t.status===429){ce(`Rate limited: ${n.error||`too many simulations`}`),ae(!1);return}if(n.redirect){l(),ce(`Running...`),k(window,n.visitorId);let e=sh(fh(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else ce(`Error: ${n.error||`unknown`}`),ae(!1)}catch(e){ce(`Failed: ${e}`),ae(!1)}}},[f,y,C,T,O,j,Ae,P,c,l,a,o,ye,xe,Ee,De]),Fe=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(qm,{options:$w,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(Xw,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(OC,{}),le.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:Nw,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:ue,onChange:e=>Me(e.target.value),children:le.map(e=>{let t=e.description?.includes(`(memory)`)?` [memory]`:e.description?.includes(`(disk)`)?` [disk]`:e.description?.includes(`compiled`)?` [compiled]`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.id===ue?`● `:``,e.name,` (`,e.departments,` depts)`,t]},e.id)})}),(0,x.jsxs)(`span`,{className:Y.scenarioActiveTag,children:[`Active: `,(0,x.jsx)(`strong`,{className:Y.scenarioActiveValue,children:ue})]})]}),(0,x.jsx)(`h2`,{className:Y.h2,children:a.labels.name}),a.labels.tagline&&(0,x.jsx)(`p`,{className:Y.scenarioTagline,children:a.labels.tagline}),(0,x.jsxs)(`p`,{className:Y.lead,children:[`Configure your leaders and launch. `,a.departments.length,` departments: `,a.departments.map(e=>e.label).join(`, `),`.`]}),a.sourceUrl&&(0,x.jsx)(`p`,{className:Y.scenarioSourceLink,children:(0,x.jsx)(`a`,{href:a.sourceUrl,target:`_blank`,rel:`noopener noreferrer`,children:`View scenario JSON on GitHub →`})}),(0,x.jsxs)(`p`,{className:Y.leadHint,children:[`Server mode: `,(0,x.jsx)(`strong`,{className:Y.leadStrong,children:Oe.label}),`. `,Oe.description]}),(0,x.jsx)(`div`,{className:`${f.length>2?`responsive-grid-cohort`:`responsive-grid-2`} ${Y.leadersGrid}`,children:f.map((e,t)=>(0,x.jsxs)(`div`,{className:Y.leaderCardWrap,style:{position:`relative`},children:[(0,x.jsx)(Aw,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:Pe(t),data:e,onChange:e=>g(t,e)}),f.length>cT&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:Y.leaderRemoveBtn,"aria-label":`Remove ${e.name||`actor ${t+1}`} from the cohort`,title:`Remove this actor`,children:`✕`})]},t))}),(0,x.jsx)(`div`,{className:Y.leadersAddRow,children:f.length<lT?(0,x.jsxs)(`button`,{type:`button`,onClick:_,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,f.length,`/`,lT,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,lT,` actors from Settings · use Quickstart's generate-N flow for larger cohorts.`]})}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Simulation`}),ke&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,B.maxTurns,`, population to `,B.maxPopulation,`, active departments to `,B.maxActiveDepartments,`. Values you enter below are honored up to those ceilings. Add a session API key above to lift the caps.`]}),(0,x.jsxs)(`div`,{className:`responsive-grid-4 ${Y.simRow5}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`turns-input`,style:Nw,children:[`Turns`,ke&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${B.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,B.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:ke?B.maxTurns:y,onChange:e=>{M.current.add(`turns`),S(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:ke,className:Fe(ke),title:ke?`Locked at ${B.maxTurns} in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`ypt-input`,style:Nw,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:O,onChange:e=>{M.current.add(`timePerTurn`),A(parseInt(e.target.value)||0)},min:0,max:50,placeholder:`auto`,title:`${s.Times} per turn. 0 = accelerating schedule (default). 1 = 1 ${s.time} per turn. 5 = 5 ${s.times} per turn.`,className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`seed-input`,style:Nw,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:C,onChange:e=>{M.current.add(`seed`),w(parseInt(e.target.value)||a.setup.defaultSeed)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`time-input`,style:Nw,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:T,onChange:e=>{M.current.add(`startTime`),E(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:Nw,children:[`Population`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,title:`Hosted demo caps population at 30. Add a session API key to unlock.`,children:`🔒 demo:30`})]}),(0,x.jsx)(`input`,{id:`pop-input`,type:`number`,value:ke?30:j,onChange:e=>{M.current.add(`population`),ee(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:ke,className:Fe(ke),title:ke?`Locked at 30 in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]})]}),(0,x.jsxs)(`div`,{className:`responsive-grid-3 ${Y.grid3}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`provider-select`,style:Nw,children:[`Provider`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 demo:openai`})]}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Fe(ke)}`,value:Ae,onChange:e=>ne(e.target.value),disabled:ke,title:ke?`Locked to OpenAI in hosted demo mode. Add your own OpenAI or Anthropic key above to choose the provider.`:``,children:[(0,x.jsx)(`option`,{value:`openai`,children:`OpenAI`}),(0,x.jsx)(`option`,{value:`anthropic`,children:`Anthropic`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`search-select`,style:Nw,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(P),onChange:e=>re(e.target.value===`true`),children:[(0,x.jsx)(`option`,{value:`false`,children:`Off`}),(0,x.jsx)(`option`,{value:`true`,children:`On (requires search API keys)`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`economics-select`,style:Nw,children:[`Economics`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Fe(ke)}`,value:De,onChange:e=>F(e.target.value),disabled:ke,title:Zw.find(e=>e.value===De)?.description,children:Zw.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:Zw.find(e=>e.value===De)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`API Keys`}),(0,x.jsxs)(`div`,{className:Y.keysIntro,children:[(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldNeutral,children:`How key resolution works:`}),` The server checks for keys in this order: your session overrides below, then the server .env file. If a key exists in either place, it's used. Values entered here are never displayed back.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldGreen,children:`Rate limiting:`}),` The hosted demo limits simulations per IP per day when using the server's API keys. Provide your own `,(0,x.jsx)(`strong`,{children:`OpenAI`}),` or `,(0,x.jsx)(`strong`,{children:`Anthropic`}),` key to bypass the rate limit and run unlimited simulations. Only one LLM provider key is required. If both are provided, the simulation uses whichever you select as the provider.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldAmber,children:`Research and citations:`}),` Live web search requires at least one search key (Serper, Firecrawl, Tavily). Without any search key, departments fall back to the scenario's built-in research bundle. Cohere enables neural reranking of search results for higher-quality citations. These are optional enhancements, not required to run a simulation.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroParaLast,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldRust,children:`No keys at all?`}),` If neither a server .env key nor a session override exists for any LLM provider, the simulation cannot run. You need at least one OpenAI or Anthropic key configured somewhere.`]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:[[`openai`,`OpenAI`,`Required (or Anthropic). Powers commander, departments, crisis director.`],[`anthropic`,`Anthropic`,`Required (or OpenAI). Alternative LLM provider for all simulation roles.`],[`serper`,`Serper (search)`,`Optional. Enables live Google search for department research citations.`],[`firecrawl`,`Firecrawl (scrape)`,`Optional. Enables web page scraping for deeper research context.`],[`tavily`,`Tavily (search)`,`Optional. Additional search provider. Multiple providers improve coverage.`],[`cohere`,`Cohere (rerank)`,`Optional. Neural reranking of search results for citation quality.`]].map(([e,t,n])=>(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`key-${e}`,style:Nw,children:[t,fe[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:ye[e],onChange:t=>be(n=>({...n,[e]:t.target.value})),placeholder:fe[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),Te&&(N===`openai`||N===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Model Tiers`}),(0,x.jsx)(`div`,{className:Y.modelTiersIntro,children:`Assign a model to each agent tier. Departments do the forging and benefit most from the flagship class. Agent reactions fan out to hundreds of parallel calls per turn and should be the cheapest class available. These overrides are only used when you run against your own API key.`}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:Object.keys(rT).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:Nw,children:rT[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:xe[e],onChange:t=>Se(n=>({...n,[e]:t.target.value})),children:tT[N].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:rT[e].help})]},e))})]}),!Te&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,z?`Runs against the host API keys are capped to ${B.maxTurns} turns, ${B.maxPopulation} colonists, ${B.maxActiveDepartments} departments, and the cheapest model class. Add your own OpenAI or Anthropic key above to unlock full scope and per-tier model selection.`:`No API key configured. Add an OpenAI or Anthropic key above or set one in .env to enable simulations and the per-tier model picker.`]}),me&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Admin Token`}),(0,x.jsx)(Uw,{})]}),(0,x.jsx)(Bw,{onAdminWrite:he}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Ne,disabled:I||!o,"aria-label":I?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:I?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),oe&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:oe})]})]})]})}function dT(e){let t=t=>{let n=e[t];return Number.isFinite(n)?n:.5};return{openness:t(`openness`),conscientiousness:t(`conscientiousness`),extraversion:t(`extraversion`),agreeableness:t(`agreeableness`),emotionality:t(`emotionality`),honestyHumility:t(`honestyHumility`)}}function fT(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:dT(e.hexaco),instructions:e.instructions})),...t]}var pT={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function mT(e,t,n,r){let i=Math.max(0,t-e)*pT[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function hT(e){let t=[];for(let n of e.split(`
|
|
127
127
|
`)){let e=n.trim();if(!e)continue;let r=/^(\d+)\s*:\s*([^:]+?)\s*:\s*(.+)$/.exec(e);if(!r)continue;let i=parseInt(r[1],10),a=r[2].trim(),o=r[3].trim();a&&t.push({turn:i,title:a,description:o})}return t}var gT=new Set([`kernelSnapshotAtStart`,`kernelSnapshotsAfterProgression`]);function _T(e){let t=e.scenarioExtensions;if(!t||typeof t!=`object`)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>!gT.has(e)));return{...e,scenarioExtensions:n}}function vT(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function yT(e){let t=e.trajectory?.timepoints?.length??0,n=vT(e),r=Math.max(t,...n);return r>0?r:6}function bT(e,t){return vT(e).includes(t)&&t<yT(e)}var xT={forkButton:`_forkButton_14oeq_1`,backdrop:`_backdrop_14oeq_28`,dialog:`_dialog_14oeq_40`,header:`_header_14oeq_58`,closeButton:`_closeButton_14oeq_75`,field:`_field_14oeq_92`,hint:`_hint_14oeq_122`,warning:`_warning_14oeq_128`,advanced:`_advanced_14oeq_139`,costEstimate:`_costEstimate_14oeq_173`,costDetail:`_costDetail_14oeq_191`,footer:`_footer_14oeq_196`,cancelButton:`_cancelButton_14oeq_224`,confirmButton:`_confirmButton_14oeq_228`};function ST(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=Qk(),u=Lm(),d=Pt(!0),f=fT(l,o),[p,m]=(0,b.useState)(0),[h,g]=(0,b.useState)(``),[_,v]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&c()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]);let y=mT(n,r,i,a),S=Math.max(0,r-n),C=t.metadata.seed;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`fork-modal-title`,className:xT.backdrop,onClick:c,children:(0,x.jsxs)(`div`,{ref:d,tabIndex:-1,className:xT.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:xT.header,children:[(0,x.jsxs)(`h3`,{id:`fork-modal-title`,children:[`Fork at `,u.Time,` `,n]}),(0,x.jsx)(`button`,{type:`button`,className:xT.closeButton,onClick:c,"aria-label":`Close fork modal`,children:`×`})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-leader-select`,children:`Override leader`}),f.length===0?(0,x.jsx)(`p`,{className:xT.warning,children:`No preset leaders available for this scenario. Add leaders in Settings or pick a scenario with presets to continue.`}):(0,x.jsx)(`select`,{id:`fork-leader-select`,value:p,onChange:e=>m(parseInt(e.target.value,10)),children:f.map((e,t)=>(0,x.jsxs)(`option`,{value:t,children:[e.name,` (`,e.archetype,`)`]},`${e.name}-${t}`))})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-seed`,children:`Seed override (optional)`}),(0,x.jsx)(`input`,{id:`fork-seed`,type:`number`,placeholder:C===void 0?`(use parent seed)`:`Parent seed: ${C}`,value:h,onChange:e=>g(e.target.value)}),(0,x.jsx)(`span`,{className:xT.hint,children:`Leave blank to resume from the parent's RNG state.`})]}),(0,x.jsxs)(`details`,{className:xT.advanced,children:[(0,x.jsx)(`summary`,{children:`Advanced: custom events`}),(0,x.jsx)(`textarea`,{rows:4,placeholder:`One event per line, format: "turn: title: description"
|
|
128
|
-
Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:xT.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:xT.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:xT.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:xT.cancelButton,children:`Cancel`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=f[p];if(!e)return;let r=h.trim()?parseInt(h,10):void 0,i=r!==void 0&&Number.isFinite(r)?r:void 0,a=_.trim()?hT(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:xT.confirmButton,children:`Fork`})]})]})})}var CT=`/retry-stats`;function wT(e=!0){let[t,n]=(0,b.useState)(null),[r,i]=(0,b.useState)(!1),[a,o]=(0,b.useState)(null),s=(0,b.useCallback)(async()=>{i(!0),o(null);try{let e=await fetch(CT,{credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();n(t)}catch(e){o(e instanceof Error?e.message:String(e))}finally{i(!1)}},[]);return(0,b.useEffect)(()=>{e&&s()},[e,s]),{data:t,loading:r,error:a,refresh:s}}var X={backdrop:`_backdrop_vajsn_1`,dialog:`_dialog_vajsn_12`,titleRow:`_titleRow_vajsn_27`,title:`_title_vajsn_27`,escBtn:`_escBtn_vajsn_43`,totalLine:`_totalLine_vajsn_54`,totalAmount:`_totalAmount_vajsn_60`,cacheBlock:`_cacheBlock_vajsn_66`,cacheLabel:`_cacheLabel_vajsn_74`,cacheVerdict:`_cacheVerdict_vajsn_83`,cacheSubLine:`_cacheSubLine_vajsn_91`,cacheTokenRow:`_cacheTokenRow_vajsn_98`,cacheMultiplier:`_cacheMultiplier_vajsn_107`,emptyState:`_emptyState_vajsn_111`,table:`_table_vajsn_118`,tableSm:`_tableSm_vajsn_125`,headRow:`_headRow_vajsn_132`,th:`_th_vajsn_139`,thRight:`_thRight_vajsn_144`,bodyRow:`_bodyRow_vajsn_150`,stageCell:`_stageCell_vajsn_154`,stageLabel:`_stageLabel_vajsn_158`,stageDescription:`_stageDescription_vajsn_164`,bar:`_bar_vajsn_171`,barFill:`_barFill_vajsn_180`,numericCell:`_numericCell_vajsn_187`,numericCellGreen:`_numericCellGreen_vajsn_193`,numericCellMuted:`_numericCellMuted_vajsn_201`,section:`_section_vajsn_208`,sectionLabel:`_sectionLabel_vajsn_214`,sectionFootnote:`_sectionFootnote_vajsn_222`,sectionFootnoteTight:`_sectionFootnoteTight_vajsn_229`,subBlock:`_subBlock_vajsn_236`,subBlockLabel:`_subBlockLabel_vajsn_240`,cellSchemaName:`_cellSchemaName_vajsn_247`,cellNumericTight:`_cellNumericTight_vajsn_252`,cellAvgAttempts:`_cellAvgAttempts_vajsn_258`,cellFallback:`_cellFallback_vajsn_265`,cellRight1:`_cellRight1_vajsn_272`,cellRightGreen:`_cellRightGreen_vajsn_278`,cellRightRust:`_cellRightRust_vajsn_285`,cellRightMuted:`_cellRightMuted_vajsn_291`,cellRateColor:`_cellRateColor_vajsn_297`,cellConfColor:`_cellConfColor_vajsn_304`,statusInline:`_statusInline_vajsn_311`,statusErrorTag:`_statusErrorTag_vajsn_320`,rejectionWrap:`_rejectionWrap_vajsn_324`,rejectionLabel:`_rejectionLabel_vajsn_328`,rejectionCell:`_rejectionCell_vajsn_335`,perLeaderRow:`_perLeaderRow_vajsn_342`,leaderCard:`_leaderCard_vajsn_349`,leaderName:`_leaderName_vajsn_357`,leaderCost:`_leaderCost_vajsn_363`,leaderMeta:`_leaderMeta_vajsn_369`,perActorList:`_perActorList_vajsn_378`,perActorRow:`_perActorRow_vajsn_386`,perActorBarTrack:`_perActorBarTrack_vajsn_412`,perActorCost:`_perActorCost_vajsn_417`,perActorMeta:`_perActorMeta_vajsn_421`,perActorRank:`_perActorRank_vajsn_426`,perActorName:`_perActorName_vajsn_433`,perActorBarFill:`_perActorBarFill_vajsn_448`},TT={director:{label:`Event Director`,description:`Generates events each turn based on world state`},commander:{label:`Commander`,description:`Reads dept reports, picks options, promotes department heads`},departments:{label:`Department Analysis`,description:`5 specialists analyzing each event in parallel`},judge:{label:`Forge Judge`,description:`LLM safety + correctness review of every forged tool`},reactions:{label:`Agent Reactions`,description:`~100 colonists reacting to each turn's outcome`},other:{label:`Other`,description:`Uncategorized calls`}};function ET(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function DT(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function OT(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function kT(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function AT({combined:e,leaderA:t,leaderB:n,leaderAName:r,leaderBName:i,actors:a,onClose:o}){(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let s=Pt(!0),c=wT(!0),l=e.breakdown??{},u=Object.entries(l).map(([e,t])=>({site:e,...t})).sort((e,t)=>t.totalCostUSD-e.totalCostUSD),d=e.totalCostUSD||u.reduce((e,t)=>e+t.totalCostUSD,0),f=u[0]?.totalCostUSD??0;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Cost breakdown`,onClick:o,className:X.backdrop,children:(0,x.jsxs)(`div`,{ref:s,tabIndex:-1,onClick:e=>e.stopPropagation(),className:X.dialog,children:[(0,x.jsxs)(`div`,{className:X.titleRow,children:[(0,x.jsx)(`h3`,{className:X.title,children:`COST BREAKDOWN`}),(0,x.jsx)(`button`,{onClick:o,"aria-label":`Close cost breakdown`,className:X.escBtn,children:`ESC`})]}),(0,x.jsxs)(`div`,{className:X.totalLine,children:[`Total: `,(0,x.jsx)(`span`,{className:X.totalAmount,children:ET(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,DT(e.totalTokens),` tokens`]}),e.cacheReadTokens||e.cacheCreationTokens?(()=>{let t=e.cacheReadTokens??0,n=e.cacheCreationTokens??0,r=e.cacheSavingsUSD??0,i=t+n,a=i>0?t/i:0,o=`var(--text-3)`,s;return r>.001?(o=`var(--green)`,s=`Saved ${ET(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${ET(-r)} so far · reuse will repay this`):t>0?(o=`var(--green)`,s=`Cache reuse breaking even with priming cost`):(o=`var(--amber)`,s=`Cache filled but nothing reused yet · retry run or check prompt stability`),(0,x.jsxs)(`div`,{className:X.cacheBlock,children:[(0,x.jsx)(`div`,{className:X.cacheLabel,children:`PROMPT CACHING`}),(0,x.jsx)(`div`,{className:X.cacheVerdict,style:{"--cache-verdict-color":o},children:s}),(0,x.jsxs)(`div`,{className:X.cacheSubLine,children:[Math.round(a*100),`% hit rate on cached input (`,DT(t),` reused / `,DT(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,DT(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,DT(n),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@1.25×`})]})]})]})})():null,u.length===0?(0,x.jsx)(`div`,{className:X.emptyState,children:`No LLM calls have been billed yet. Start a simulation to see spend by pipeline stage.`}):(0,x.jsxs)(`table`,{className:X.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`STAGE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`COST`}),(0,x.jsx)(`th`,{className:X.thRight,children:`%`})]})}),(0,x.jsx)(`tbody`,{children:u.map(e=>{let t=TT[e.site]??{label:e.site,description:``},n=d>0?e.totalCostUSD/d*100:0,r=f>0?e.totalCostUSD/f*100:0;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.stageCell,children:[(0,x.jsx)(`div`,{className:X.stageLabel,children:t.label}),(0,x.jsx)(`div`,{className:X.stageDescription,children:t.description}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:X.bar,children:(0,x.jsx)(`div`,{className:X.barFill,style:{"--bar-pct":`${r}%`}})})]}),(0,x.jsx)(`td`,{className:X.numericCell,children:e.calls.toLocaleString()}),(0,x.jsx)(`td`,{className:X.numericCell,children:DT(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:ET(e.totalCostUSD)}),(0,x.jsxs)(`td`,{className:X.numericCellMuted,children:[n.toFixed(0),`%`]})]},e.site)})})]}),e.schemaRetries&&Object.keys(e.schemaRetries).length>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`SCHEMA RELIABILITY`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACKS`})]})}),(0,x.jsx)(`tbody`,{children:Object.entries(e.schemaRetries).sort((e,t)=>t[1].calls-e[1].calls).map(([e,t])=>{let n=t.calls>0?t.attempts/t.calls:0,r=OT(n),i=t.fallbacks>0?`var(--rust)`:`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":r},children:n.toFixed(2)}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":i,"--fb-weight":t.fallbacks>0?`700`:`400`},children:t.fallbacks})]},e)})})]}),(0,x.jsxs)(`div`,{className:X.sectionFootnote,children:[`1.00 = first-try success. Higher = model retrying on validation failures. Tune `,(0,x.jsx)(`code`,{className:`mono`,children:`maxRetries`}),` or tighten schema if a row stays above 1.3.`]})]}),e.forgeStats&&e.forgeStats.attempts>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`FORGE RELIABILITY`}),(()=>{let t=e.forgeStats,n=t.attempts>0?t.approved/t.attempts:0,r=t.approved>0?t.approvedConfidenceSum/t.approved:0,i=n<.5?`var(--rust)`:n<.75?`var(--amber)`:`var(--green)`,a=r>0&&r<.6?`var(--amber)`:`var(--text-1)`;return(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`REJECTED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVAL RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:t.attempts}),(0,x.jsx)(`td`,{className:X.cellRightGreen,children:t.approved}),(0,x.jsx)(`td`,{className:t.rejected>0?X.cellRightRust:X.cellRightMuted,children:t.rejected}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i},children:[(n*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellConfColor,style:{"--conf-color":a},children:r>0?r.toFixed(2):`—`})]})})]})})(),(0,x.jsx)(`div`,{className:X.sectionFootnote,children:`Rejections come from shape check OR judge verdict. Retry-with-feedback usually recovers; persistent low approval rate suggests the department model is weak at writing schema-compliant code.`})]}),(()=>{let e=c.data;if(c.loading&&!e)return(0,x.jsx)(`div`,{className:X.statusInline,children:`RECENT RUNS — loading…`});if(c.error)return(0,x.jsxs)(`div`,{className:X.statusInline,children:[`RECENT RUNS — `,(0,x.jsxs)(`span`,{className:X.statusErrorTag,children:[`fetch failed (`,c.error,`)`]})]});if(!e||e.runCount===0)return null;let t=Object.entries(e.schemas).filter(([e])=>!e.startsWith(`compile:`)),n=Object.entries(e.schemas).filter(([e])=>e.startsWith(`compile:`)).map(([e,t])=>[e.replace(/^compile:/,``),t]),r=e.forges,i=e.caches,a=e.providerErrors,o=([e,t])=>{let n=OT(t.avgAttempts),r=kT(t.fallbackRate);return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":n},children:t.avgAttempts.toFixed(2)}),(0,x.jsxs)(`td`,{className:X.cellFallback,style:{"--fb-color":r,"--fb-weight":t.fallbacks>0?`700`:`400`},children:[(t.fallbackRate*100).toFixed(2),`%`]})]},e)};return(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`RECENT RUNS (last `,e.runCount,`)`]}),t.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`RUNTIME SCHEMAS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:t.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),n.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`COMPILE HOOKS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`HOOK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:n.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),r&&r.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`FORGES`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPT RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`UNIQUE TOOLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`EVENTUALLY APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TERMINAL FAILS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:r.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalAttempts}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.approvalRate<.5?`var(--rust)`:r.approvalRate<.75?`var(--amber)`:`var(--green)`},children:[(r.approvalRate*100).toFixed(1),`%`]}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalUniqueNames}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.uniqueApprovalRate<.8?`var(--rust)`:r.uniqueApprovalRate<.95?`var(--amber)`:`var(--green)`},children:[r.totalUniqueApproved,` (`,(r.uniqueApprovalRate*100).toFixed(0),`%)`]}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":r.totalUniqueTerminalRejections>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":r.totalUniqueTerminalRejections>0?`700`:`400`},children:r.totalUniqueTerminalRejections}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:r.avgApprovedConfidence>0?r.avgApprovedConfidence.toFixed(2):`—`})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`ATTEMPT RATE counts every forge call including retries. EVENTUALLY APPROVED is the real quality signal — tools that landed in the toolbox. TERMINAL FAILS are tools the retry loop never recovered.`}),(()=>{let e=r.rejectionReasons,t=e.schema_extra_field+e.shape_check+e.parse_error+e.judge_correctness+e.other;if(t===0)return null;let n=e=>t>0?Math.round(e/t*100):0,i=(e,t)=>({"--rj-color":e>0?t:`var(--text-3)`,"--rj-weight":e>0?`700`:`400`});return(0,x.jsxs)(`div`,{className:X.rejectionWrap,children:[(0,x.jsxs)(`div`,{className:X.rejectionLabel,children:[`REJECTION REASONS (last `,r.runsPresent,` run`,r.runsPresent===1?``:`s`,`)`]}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`SCHEMA EXTRA FIELD`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SHAPE CHECK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`PARSE ERROR`}),(0,x.jsx)(`th`,{className:X.thRight,children:`JUDGE CORRECTNESS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.schema_extra_field,`var(--amber)`),children:[e.schema_extra_field,` (`,n(e.schema_extra_field),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.shape_check,`var(--amber)`),children:[e.shape_check,` (`,n(e.shape_check),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.parse_error,`var(--rust)`),children:[e.parse_error,` (`,n(e.parse_error),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.judge_correctness,`var(--rust)`),children:[e.judge_correctness,` (`,n(e.judge_correctness),`%)`]}),(0,x.jsxs)(`td`,{className:X.cellRightMuted,children:[e.other,` (`,n(e.other),`%)`]})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`SCHEMA EXTRA FIELD dominating means the LLM's return-keys don't match its declared outputSchema.properties — the target of the 2026-04-18 forge-guidance prompt fix. JUDGE CORRECTNESS = real logic bugs the judge caught.`})]})})()]}),a&&a.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROVIDER ERRORS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS W/ ERRORS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOTAL`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AUTH`}),(0,x.jsx)(`th`,{className:X.thRight,children:`QUOTA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`NET`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:a.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:a.total}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.auth>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.auth>0?`700`:`400`},children:a.auth}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.quota>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.quota>0?`700`:`400`},children:a.quota}),(0,x.jsx)(`td`,{className:a.rate_limit>0?X.cellFallback:X.cellRightMuted,style:a.rate_limit>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.rate_limit}),(0,x.jsx)(`td`,{className:a.network>0?X.cellFallback:X.cellRightMuted,style:a.network>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.network}),(0,x.jsx)(`td`,{className:a.unknown>0?X.cellFallback:X.cellRightMuted,style:a.unknown>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.unknown})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`AUTH/QUOTA are terminal (run aborts). RATE/NET/OTHER are non-terminal — the retry layer handles them.`})]}),i&&i.runsPresent>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROMPT CACHE`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS WITH CACHE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CREATE TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ RATIO`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SAVINGS`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:i.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:DT(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:DT(i.totalCreationTokens)}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.readRatio>=.7?`var(--green)`:i.readRatio>=.4?`var(--amber)`:`var(--rust)`},children:[(i.readRatio*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.totalSavingsUSD>0?`var(--green)`:`var(--text-2)`},children:ET(i.totalSavingsUSD)})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`Read ratio >= 70% is healthy. Lower ratios mean the cache keeps getting invalidated.`})]})]})})(),a&&a.length>2&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`PER ACTOR · `,a.length,` ACTORS`]}),(()=>{let e=[...a].sort((e,t)=>t.cost.totalCostUSD-e.cost.totalCostUSD),t=e[0]?.cost.totalCostUSD??0,n=e.reduce((e,t)=>e+t.cost.totalCostUSD,0);return(0,x.jsx)(`div`,{className:X.perActorList,children:e.map((e,r)=>{let i=t>0?e.cost.totalCostUSD/t*100:0,a=n>0?e.cost.totalCostUSD/n*100:0;return(0,x.jsxs)(`div`,{className:X.perActorRow,children:[(0,x.jsxs)(`div`,{className:X.perActorRank,children:[`#`,r+1]}),(0,x.jsx)(`div`,{className:X.perActorName,title:e.name,children:e.name}),(0,x.jsx)(`div`,{className:X.perActorBarTrack,"aria-hidden":`true`,children:(0,x.jsx)(`div`,{className:X.perActorBarFill,style:{width:`${i}%`}})}),(0,x.jsx)(`div`,{className:X.perActorCost,children:ET(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,DT(e.cost.totalTokens),` tok · `,a.toFixed(1),`%`]})]},e.actorId)})})})()]}),t&&n&&(t.totalCostUSD>0||n.totalCostUSD>0)&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`PER LEADER`}),(0,x.jsxs)(`div`,{className:X.perLeaderRow,children:[(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--vis)`},children:r||`Leader A`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,DT(t.totalTokens),` tok`]})]}),(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--eng)`},children:i||`Leader B`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,DT(n.totalTokens),` tok`]})]})]})]})]})})}var jT={card:`_card_mk5ry_1`,headerRow:`_headerRow_mk5ry_11`,title:`_title_mk5ry_18`,range:`_range_mk5ry_24`,legend:`_legend_mk5ry_28`,legendItem:`_legendItem_mk5ry_35`,legendSwatch:`_legendSwatch_mk5ry_41`,legendLabel:`_legendLabel_mk5ry_48`,legendValue:`_legendValue_mk5ry_52`},MT=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],NT={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},PT={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function FT(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function IT(e,t){let n=[];for(let r of e){if(r.type!==`personality_drift`||!r.data||r.leader!==void 0&&r.leader!==t)continue;let e=r.data.commander,i=r.data.turn;e&&typeof i==`number`&&n.push({turn:i,hexaco:e})}return n.sort((e,t)=>e.turn-t.turn)}function LT({events:e,actorName:t,baselineHexaco:n}){let r=FT(n),i=IT(e,t);if(i.length===0&&!r)return null;let a=r?[{turn:0,hexaco:r},...i]:i;if(a.length<2)return null;let o=a[0].turn,s=a[a.length-1].turn,c=Math.max(1,s-o),l=e=>6+68*(1-(Math.max(.05,Math.min(.95,e))-.05)/.9),u=e=>6+248*((e-o)/c);return(0,x.jsxs)(`div`,{className:jT.card,children:[(0,x.jsxs)(`div`,{className:jT.headerRow,children:[(0,x.jsx)(`span`,{className:jT.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:jT.range,children:[`turn `,o,` → `,s]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 260 80`,width:`100%`,height:80,role:`img`,"aria-label":`HEXACO trajectory for ${t}`,children:[(0,x.jsx)(`line`,{x1:6,y1:l(.5),x2:254,y2:l(.5),stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),MT.map(e=>{let t=a.map(t=>`${u(t.turn)},${l(t.hexaco[e])}`).join(` `);return(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:NT[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:jT.legend,children:MT.map(e=>(0,x.jsxs)(`span`,{className:jT.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:jT.legendSwatch,style:{"--trait-color":NT[e]}}),(0,x.jsx)(`span`,{className:jT.legendLabel,children:PT[e]}),(0,x.jsx)(`span`,{className:jT.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var RT={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},zT={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},BT=[`crisis`,`departments`,`decision`,`outcome`],VT=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function HT(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function UT(e){return e!==`quotes`}function WT(e){let t=[];for(let n of e??[])HT(n)&&!t.includes(n)&&t.push(n);return t}function GT(e){let t=WT(e.configuredSections),n=t.length>0?t:BT,r=n.filter(UT);for(let t of VT)t===`causality`&&!e.hasCausality||r.includes(t)||r.push(t);let i=e.hasQuotes?[`quotes`]:[],a=[`timeline`];return e.hasVerdict&&a.push(`verdict`),e.hasTrajectories&&a.push(`trajectory`),e.hasCost&&a.push(`cost`),e.hasToolbox&&a.push(`toolbox`),e.hasReferences&&a.push(`references`),{focusSections:n,eventSections:r,footerSections:i,artifacts:a}}var KT={section:`_section_36gyg_1`,header:`_header_36gyg_10`,kicker:`_kicker_36gyg_16`,winner:`_winner_36gyg_25`,headline:`_headline_36gyg_33`,divergence:`_divergence_36gyg_40`,body:`_body_36gyg_48`,bodyHeader:`_bodyHeader_36gyg_52`,nameA:`_nameA_36gyg_64`,nameB:`_nameB_36gyg_68`,statRow:`_statRow_36gyg_72`,statRowHead:`_statRowHead_36gyg_76`,statValueA:`_statValueA_36gyg_85`,statValueB:`_statValueB_36gyg_90`,statLabel:`_statLabel_36gyg_95`,bar:`_bar_36gyg_99`,barLeftWrap:`_barLeftWrap_36gyg_105`,barRightWrap:`_barRightWrap_36gyg_111`,barLeftFill:`_barLeftFill_36gyg_115`,barRightFill:`_barRightFill_36gyg_122`,viewWrap:`_viewWrap_36gyg_129`,viewBtn:`_viewBtn_36gyg_134`,empty:`_empty_36gyg_147`},qT=[{key:`population`,label:`Population`,format:`int`},{key:`morale`,label:`Morale`,format:`percent`},{key:`food`,label:`Food (mo)`,format:`decimal`},{key:`power`,label:`Power (kW)`,format:`decimal`},{key:`modules`,label:`Modules`,format:`decimal`},{key:`science`,label:`Science`,format:`int`},{key:`tools`,label:`Tools Forged`,format:`int`}];function JT(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function YT({a:e,b:t,winner:n}){let r=Math.max(Math.abs(e),Math.abs(t),1),i=Math.max(0,e/r*100),a=Math.max(0,t/r*100),o=n===`a`?`var(--vis)`:`var(--border-hl)`,s=n===`b`?`var(--eng)`:`var(--border-hl)`;return(0,x.jsxs)(`div`,{className:KT.bar,children:[(0,x.jsx)(`div`,{className:KT.barLeftWrap,children:(0,x.jsx)(`div`,{className:KT.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:KT.barRightWrap,children:(0,x.jsx)(`div`,{className:KT.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function XT(e){let t=e.verdict;if(t?.mode===`cohort`)return null;let n=t?.winnerName||``,r=t?.headline||t?.summary||``,i=t?.keyDivergence||``,a=t?.finalStats?.a,o=t?.finalStats?.b,s=vn(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:yn(e),a:e.a,b:e.b,text:t=>bn(t,e.format,e.currency),better:e.better})),{key:`tools`,label:`Tools Forged`,a:Number(a.tools??0),b:Number(o.tools??0),text:e=>JT(e??0,`int`)}]:qT.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>JT(t??0,e.format)})):[],l=e.onViewFullVerdict??(()=>{typeof document<`u`&&document.getElementById(`verdict`)?.scrollIntoView({behavior:`smooth`,block:`start`})});return(0,x.jsxs)(`section`,{"aria-label":`Run summary`,className:KT.section,children:[(0,x.jsxs)(`div`,{className:KT.header,children:[(0,x.jsx)(`div`,{className:KT.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:KT.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:KT.headline,children:r}),i&&(0,x.jsx)(`div`,{className:KT.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:KT.body,children:[(0,x.jsxs)(`div`,{className:KT.bodyHeader,children:[(0,x.jsx)(`span`,{className:KT.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:KT.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Sn(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:KT.statRow,children:[(0,x.jsxs)(`div`,{className:KT.statRowHead,children:[(0,x.jsx)(`span`,{className:KT.statValueA,style:{"--val-color":r===`a`?`var(--vis)`:`var(--text-2)`,"--val-weight":r===`a`?`700`:`500`},children:e.text(t)}),(0,x.jsx)(`span`,{className:KT.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:KT.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(YT,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:KT.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:KT.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:KT.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var ZT={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function QT(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function $T(e,t){switch(t){case`morale`:return e.morale;case`population`:return e.population;case`deaths`:return e.deaths;case`tools`:return e.tools;case`turn`:return e.turn}}function eE(e,t,n){let r=n??ZT[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>$T(e,t))].sort((e,t)=>e-t),a=QT(i,.25),o=QT(i,.75),s=QT(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=$T(n,t);r===`higher`?e>o?c.push(n):e<a?u.push(n):l.push(n):e<a?c.push(n):e>o?u.push(n):l.push(n)}return{metric:t,direction:r,top:c,middle:l,bottom:u,median:s}}function tE(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>i:r<i},i=(e,i)=>{let a=!1;for(let o of t){if(!n(e,i,o))return!1;r(e,i,o)&&(a=!0)}return a},a={};for(let t of e)a[t.id]=0;for(let t of e)for(let n of e)t.id!==n.id&&i(t,n)&&a[t.id]++;let o=[];for(let t of e){let n=!1;for(let r of e)if(t.id!==r.id&&i(r,t)){n=!0;break}n||o.push(t.id)}return{frontIds:o,dominationCount:a}}function nE(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=QT([...e.map(e=>$T(e,t))].sort((e,t)=>e-t),.5),r={},i=ZT[t]===`higher`?1:-1;for(let a of e){let e=($T(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function rE(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var iE={panel:`_panel_1c1w0_1`,header:`_header_1c1w0_12`,heading:`_heading_1c1w0_18`,subhead:`_subhead_1c1w0_26`,section:`_section_1c1w0_34`,sectionTitle:`_sectionTitle_1c1w0_40`,sectionHint:`_sectionHint_1c1w0_51`,quartileGrid:`_quartileGrid_1c1w0_59`,quartileBlock:`_quartileBlock_1c1w0_65`,metricHead:`_metricHead_1c1w0_75`,metricLabel:`_metricLabel_1c1w0_82`,metricMedian:`_metricMedian_1c1w0_89`,quartileRow:`_quartileRow_1c1w0_96`,quartileTag:`_quartileTag_1c1w0_102`,actorList:`_actorList_1c1w0_114`,actorPill:`_actorPill_1c1w0_124`,actorPillTop:`_actorPillTop_1c1w0_134`,actorPillBottom:`_actorPillBottom_1c1w0_140`,actorListEmpty:`_actorListEmpty_1c1w0_146`,paretoList:`_paretoList_1c1w0_153`,paretoItem:`_paretoItem_1c1w0_162`,paretoName:`_paretoName_1c1w0_176`,paretoArchetype:`_paretoArchetype_1c1w0_181`,paretoDominates:`_paretoDominates_1c1w0_185`,medianTable:`_medianTable_1c1w0_191`,medianHeaderRow:`_medianHeaderRow_1c1w0_201`,medianBodyRow:`_medianBodyRow_1c1w0_202`,medianActorCol:`_medianActorCol_1c1w0_215`,medianActorName:`_medianActorName_1c1w0_223`,medianActorArchetype:`_medianActorArchetype_1c1w0_228`,medianMetricCol:`_medianMetricCol_1c1w0_233`,deltaPositive:`_deltaPositive_1c1w0_252`,deltaNegative:`_deltaNegative_1c1w0_256`,deltaNeutral:`_deltaNeutral_1c1w0_260`},aE=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],oE=[`morale`,`population`,`deaths`,`tools`],sE=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function cE({state:e}){let t=(0,b.useMemo)(()=>YC(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>aE.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:eE(t,e)})),[t]),r=(0,b.useMemo)(()=>tE(t,oE),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>sE.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:nE(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:iE.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:iE.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:iE.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:iE.subhead,children:[t.length,` actors · ranked across morale, population, deaths, and forged tools. A single winner doesn't generalize past two — this is the cohort-aware reading.`]})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:iE.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:iE.quartileBlock,children:[(0,x.jsxs)(`div`,{className:iE.metricHead,children:[(0,x.jsx)(`span`,{className:iE.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:iE.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:iE.sectionHint,children:[i.length,` actor`,i.length===1?``:`s`,` not dominated by any other across all four metrics. Off-front actors are strictly worse than someone on it.`]}),(0,x.jsx)(`ul`,{className:iE.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:iE.paretoItem,children:[(0,x.jsx)(`span`,{className:iE.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:iE.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:iE.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:iE.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:iE.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:iE.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:iE.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:iE.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:iE.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:iE.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:iE.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:iE.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?iE.deltaPositive:n<0?iE.deltaNegative:iE.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${iE.medianMetricCol} ${r}`,role:`cell`,children:[rE(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function lE(e){switch(e){case`conservative_success`:return`var(--green)`;case`risky_success`:return`var(--amber)`;case`conservative_failure`:return`var(--rust-dim, var(--rust))`;case`risky_failure`:return`var(--rust)`;default:return`var(--text-3)`}}function uE(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var dE=[{id:`population`,label:`Population`},{id:`morale`,label:`Morale`},{id:`foodMonthsReserve`,label:`Food`,unit:`mo`},{id:`powerKw`,label:`Power`,unit:`kW`},{id:`infrastructureModules`,label:`Modules`},{id:`scienceOutput`,label:`Science`}];function fE(e,t){let n=[],r=new Set;for(let i of e){let e=i.data?.metrics;if(!e||typeof i.turn!=`number`)continue;let a=e[t];if(typeof a==`number`){if(r.has(i.turn)){let e=n.findIndex(e=>e.turn===i.turn);e>=0&&(n[e]={turn:i.turn,value:a})}else r.add(i.turn),n.push({turn:i.turn,value:a})}}return n}function pE(e,t,n){let r=t??e.actorIds[0],i=n??e.actorIds[1],a=r?e.actors[r]?.events:void 0,o=i?e.actors[i]?.events:void 0;return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?fE(a,e.id):[],b:o?fE(o,e.id):[]}))}function mE(e,t){let n=e.actorIds.map((n,r)=>{let i=e.actors[n]?.events;return{actorId:n,idx:r,name:e.actors[n]?.leader?.name??n,color:t(r),events:i}});return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:[],b:[],series:n.map(t=>({actorId:t.actorId,name:t.name,color:t.color,points:t.events?fE(t.events,e.id):[]}))}))}function hE(e){return e.map(([e,t])=>{let n=t.a.events.get(0),r=t.b.events.get(0);return{turn:e,time:t.a.time??t.b.time,diverged:uE(n?.title,r?.title)===`divergent`,a:{title:n?.title,outcome:n?.outcome,category:n?.category},b:{title:r?.title,outcome:r?.outcome,category:r?.category}}})}var gE={section:`_section_5eeou_1`,title:`_title_5eeou_10`,grid:`_grid_5eeou_20`,cell:`_cell_5eeou_26`,diverged:`_diverged_5eeou_40`,cellHead:`_cellHead_5eeou_45`,cellTurn:`_cellTurn_5eeou_53`,badge:`_badge_5eeou_57`,legend:`_legend_5eeou_71`},_E={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},vE={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function yE(e,t=!1){return e?t?vE[e]??`·`:_E[e]??e.replace(/_/g,` `).toUpperCase():`·`}function bE({outcome:e,sideColor:t,compact:n}){let r=lE(e);return(0,x.jsx)(`div`,{className:gE.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:yE(e,n)})}function xE(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=jy(Ny);if(t.length===0)return null;let o=e=>{i?i(e):typeof document<`u`&&document.getElementById(`turn-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})};return(0,x.jsxs)(`section`,{"aria-label":`Run timeline strip`,className:gE.section,children:[(0,x.jsx)(`div`,{className:gE.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:gE.grid,style:{"--turn-count":String(t.length)},children:t.map(e=>(0,x.jsxs)(`button`,{type:`button`,role:`listitem`,onClick:()=>o(e.turn),"aria-label":`Jump to turn ${e.turn}${e.time?`, time `+e.time:``}${e.diverged?`, divergent`:``}`,className:[gE.cell,e.diverged?gE.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:gE.cellHead,children:[(0,x.jsxs)(`span`,{className:gE.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(bE,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(bE,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:gE.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var SE={section:`_section_1aa2r_1`,sectionHeader:`_sectionHeader_1aa2r_10`,sectionTitle:`_sectionTitle_1aa2r_17`,legend:`_legend_1aa2r_26`,legendA:`_legendA_1aa2r_32`,legendB:`_legendB_1aa2r_37`,grid:`_grid_1aa2r_42`,card:`_card_1aa2r_48`,cardHeader:`_cardHeader_1aa2r_58`,cardLabel:`_cardLabel_1aa2r_65`,cardRange:`_cardRange_1aa2r_70`,cardFooter:`_cardFooter_1aa2r_74`,lastA:`_lastA_1aa2r_81`,lastB:`_lastB_1aa2r_86`,cardFooterCohort:`_cardFooterCohort_1aa2r_94`,lastCohort:`_lastCohort_1aa2r_103`,legendCohort:`_legendCohort_1aa2r_112`,legendCohortEntry:`_legendCohortEntry_1aa2r_122`,legendCohortSlot:`_legendCohortSlot_1aa2r_141`,lastCohortSlot:`_lastCohortSlot_1aa2r_153`};function CE(e,t){return t===`mo`||t===`kW`?`${e.toFixed(1)}${t?` `+t:``}`:e>0&&e<1?`${Math.round(e*100)}%`:`${Math.round(e)}${t?` `+t:``}`}function wE(e){let t=e,n=``;do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function TE({metric:e,sideAColor:t,sideBColor:n}){let r=Array.isArray(e.series)&&e.series.length>=2,i=r?e.series.flatMap(e=>e.points):[...e.a,...e.b];if(i.length===0)return null;let a=1/0,o=-1/0,s=1/0,c=-1/0;for(let e of i)e.turn<a&&(a=e.turn),e.turn>o&&(o=e.turn),e.value<s&&(s=e.value),e.value>c&&(c=e.value);let l=Math.max(1e-6,c-s),u=Math.max(1,o-a),d=e=>4+192*((e-a)/u),f=e=>6+38*(1-(e-s)/l);if(r)return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline (${e.series.length} actors)`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),e.series.map(e=>{let t=e.points.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `);return t?(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:e.color,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.78,children:(0,x.jsx)(`title`,{children:e.name})},e.actorId):null})]}),(0,x.jsx)(`div`,{className:SE.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=wE(n);return(0,x.jsxs)(`span`,{className:SE.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:SE.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:CE(r,e.unit)]},t.actorId)})})]});let p=e.a.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),m=e.b.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),h=e.a[e.a.length-1]?.value,g=e.b[e.b.length-1]?.value;return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),p&&(0,x.jsx)(`polyline`,{points:p,fill:`none`,stroke:t,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9}),m&&(0,x.jsx)(`polyline`,{points:m,fill:`none`,stroke:n,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9})]}),(0,x.jsxs)(`div`,{className:SE.cardFooter,children:[(0,x.jsx)(`span`,{className:SE.lastA,children:h==null?`·`:CE(h,e.unit)}),(0,x.jsx)(`span`,{className:SE.lastB,children:g==null?`·`:CE(g,e.unit)})]})]})}function EE(e){let{metrics:t,leaderAName:n,leaderBName:r}=e,i=e.sideAColor??`var(--vis)`,a=e.sideBColor??`var(--eng)`,o=t.length>0&&Array.isArray(t[0].series)&&t[0].series.length>=2,s=t.filter(e=>o?(e.series??[]).some(e=>e.points.length>0):e.a.length>0||e.b.length>0);if(s.length===0)return null;let c={"--side-a-color":i,"--side-b-color":a};return(0,x.jsxs)(`section`,{"aria-label":`Metric sparklines`,className:SE.section,style:c,children:[(0,x.jsxs)(`div`,{className:SE.sectionHeader,children:[(0,x.jsx)(`span`,{className:SE.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:SE.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:SE.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:SE.legendCohortSlot,"aria-hidden":`true`,children:wE(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:SE.legend,children:[(0,x.jsx)(`span`,{className:SE.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:SE.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${SE.grid}`,children:s.map(e=>(0,x.jsx)(TE,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function DE(e,t){let[n,r]=(0,b.useState)(()=>typeof window<`u`?window.matchMedia(e).matches:t);return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=window.matchMedia(e),n=()=>r(t.matches);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),n}function OE(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=DE(`(min-width: 1024px)`,!0),o=DE(`(max-width: 767.98px)`,!1);(0,b.useEffect)(()=>{if(typeof window>`u`||t.length===0)return;let e=t.map(e=>document.getElementById(e.id)).filter(e=>e!=null);if(e.length===0)return;let r=new IntersectionObserver(e=>{let t=e.filter(e=>e.isIntersecting).sort((e,t)=>t.intersectionRatio-e.intersectionRatio);t[0]&&i(t[0].target.id)},{root:n??null,rootMargin:`-80px 0px -60% 0px`,threshold:[0,.25,.5,.75,1]});return e.forEach(e=>r.observe(e)),()=>r.disconnect()},[t,n]);let s=(0,b.useMemo)(()=>({display:`block`,padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:700,letterSpacing:`0.04em`,textTransform:`uppercase`,color:`var(--text-3)`,textDecoration:`none`,borderRadius:3}),[]);return t.length===0?null:a?(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{position:`sticky`,top:12,alignSelf:`flex-start`,width:160,marginLeft:12,padding:`10px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:8,maxHeight:`calc(100vh - 40px)`,overflowY:`auto`},children:t.map(e=>(0,x.jsx)(`a`,{href:`#${e.id}`,style:{...s,color:r===e.id?`var(--amber)`:`var(--text-3)`,background:r===e.id?`color-mix(in srgb, var(--bg-canvas) 80%, var(--amber) 20%)`:`transparent`},children:e.label},e.id))}):(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{background:`var(--bg-panel)`,borderBottom:`1px solid var(--border)`,padding:o?`8px 10px`:`6px 8px`,marginBottom:12,overflowX:`auto`,WebkitOverflowScrolling:`touch`,display:`flex`,gap:o?6:4,flexShrink:0},children:t.map(e=>{let t=r===e.id,n={...s,flexShrink:0,padding:`8px 12px`,borderRadius:4,border:`1px solid ${t?`var(--amber)`:`var(--border)`}`,background:t?`var(--amber)`:`var(--bg-card)`,color:t?`var(--bg-deep)`:`var(--text-3)`},i={...s,flexShrink:0,color:t?`var(--amber)`:`var(--text-3)`,borderBottom:t?`2px solid var(--amber)`:`2px solid transparent`};return(0,x.jsx)(`a`,{href:`#${e.id}`,style:o?n:i,children:e.label},e.id)})})}var Z={empty:`_empty_1pipo_1`,emptyMsg:`_emptyMsg_1pipo_8`,emptyMsgRunning:`_emptyMsgRunning_1pipo_15`,emptySpinner:`_emptySpinner_1pipo_23`,reportEmptySpinnerRotate:`_reportEmptySpinnerRotate_1pipo_1`,layout:`_layout_1pipo_43`,scroll:`_scroll_1pipo_50`,tldr:`_tldr_1pipo_58`,tldrTopRow:`_tldrTopRow_1pipo_69`,tldrTag:`_tldrTag_1pipo_76`,tldrHeadline:`_tldrHeadline_1pipo_85`,tldrSub:`_tldrSub_1pipo_92`,tldrStats:`_tldrStats_1pipo_99`,tldrStatLabel:`_tldrStatLabel_1pipo_108`,tldrStatValue:`_tldrStatValue_1pipo_113`,headerRow:`_headerRow_1pipo_118`,headerTitle:`_headerTitle_1pipo_127`,jumpBtn:`_jumpBtn_1pipo_134`,actorPairPicker:`_actorPairPicker_1pipo_149`,actorPairPickerLabel:`_actorPairPickerLabel_1pipo_164`,actorPairPickerToggle:`_actorPairPickerToggle_1pipo_172`,actorPairPickerToggleText:`_actorPairPickerToggleText_1pipo_209`,actorPairPickerSelect:`_actorPairPickerSelect_1pipo_218`,actorPairPickerVs:`_actorPairPickerVs_1pipo_237`,actorPairPickerHint:`_actorPairPickerHint_1pipo_245`,jumpInlineBtn:`_jumpInlineBtn_1pipo_251`,trajectoryGrid:`_trajectoryGrid_1pipo_262`,costBar:`_costBar_1pipo_269`,costLabel:`_costLabel_1pipo_282`,costAmount:`_costAmount_1pipo_289`,costMeta:`_costMeta_1pipo_295`,costBtn:`_costBtn_1pipo_299`,turnSection:`_turnSection_1pipo_312`,diverged:`_diverged_1pipo_321`,turnHeader:`_turnHeader_1pipo_326`,turnTitle:`_turnTitle_1pipo_333`,turnEventCount:`_turnEventCount_1pipo_340`,turnHeaderRight:`_turnHeaderRight_1pipo_348`,divergenceFlag:`_divergenceFlag_1pipo_354`,eventGrid:`_eventGrid_1pipo_367`,eventGridSpaced:`_eventGridSpaced_1pipo_373`,footerGrid:`_footerGrid_1pipo_380`,nActorEventTrack:`_nActorEventTrack_1pipo_387`,nActorEventTrackSpaced:`_nActorEventTrackSpaced_1pipo_397`,nActorFooterTrack:`_nActorFooterTrack_1pipo_408`,summarySection:`_summarySection_1pipo_426`,summaryLabel:`_summaryLabel_1pipo_430`,summaryVerdictWrap:`_summaryVerdictWrap_1pipo_442`,aboutDetails:`_aboutDetails_1pipo_446`,aboutSummary:`_aboutSummary_1pipo_457`,aboutBody:`_aboutBody_1pipo_465`,aboutBlockTitle:`_aboutBlockTitle_1pipo_472`,aboutChips:`_aboutChips_1pipo_478`,aboutChip:`_aboutChip_1pipo_478`,aboutChipNeutral:`_aboutChipNeutral_1pipo_494`,eventCard:`_eventCard_1pipo_504`,eventHeading:`_eventHeading_1pipo_511`,eventSubLabel:`_eventSubLabel_1pipo_519`,eventAwaiting:`_eventAwaiting_1pipo_526`,eventTitle:`_eventTitle_1pipo_531`,categoryPill:`_categoryPill_1pipo_538`,emergentPill:`_emergentPill_1pipo_548`,eventDescription:`_eventDescription_1pipo_556`,eventDecision:`_eventDecision_1pipo_564`,eventOutcomeRow:`_eventOutcomeRow_1pipo_571`,eventPolicies:`_eventPolicies_1pipo_578`,eventDetails:`_eventDetails_1pipo_584`,eventDetailsSummary:`_eventDetailsSummary_1pipo_588`,eventRationale:`_eventRationale_1pipo_596`,deptList:`_deptList_1pipo_606`,deptItem:`_deptItem_1pipo_613`,deptHead:`_deptHead_1pipo_621`,deptName:`_deptName_1pipo_627`,deptMeta:`_deptMeta_1pipo_632`,deptSummary:`_deptSummary_1pipo_638`,footerCard:`_footerCard_1pipo_644`,footerDetails:`_footerDetails_1pipo_651`,footerDetailsLast:`_footerDetailsLast_1pipo_655`,footerSummary:`_footerSummary_1pipo_659`,systemsRow:`_systemsRow_1pipo_667`,systemItem:`_systemItem_1pipo_676`,systemKey:`_systemKey_1pipo_680`,systemValue:`_systemValue_1pipo_684`,reactionsList:`_reactionsList_1pipo_689`,reactionItem:`_reactionItem_1pipo_696`,reactionHead:`_reactionHead_1pipo_704`,reactionName:`_reactionName_1pipo_711`,moodPill:`_moodPill_1pipo_716`,reactionQuote:`_reactionQuote_1pipo_726`,reactionRole:`_reactionRole_1pipo_731`,forkNotice:`_forkNotice_1pipo_737`};function kE(e,t){let[n,r]=(0,b.useState)(()=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:n===`1`}catch{return t}});return[n,(0,b.useCallback)(t=>{r(t);try{window.localStorage.setItem(e,t?`1`:`0`)}catch{}},[e])]}function AE(){return{events:new Map,reactions:[],totalReactions:0}}function jE(e,t,n){let r=e.events.get(t);return r||(r={eventIndex:t,totalEvents:n,depts:{}},e.events.set(t,r)),n>r.totalEvents&&(r.totalEvents=n),r}function ME(e){let t=new Map;if(!e)return t;let n=new Map;for(let r of e){let e=r.turn;if(typeof e!=`number`)continue;let i=t.get(e);i||(i=AE(),t.set(e,i));let a=Number(r.data?.eventIndex??0),o=Number(r.data?.totalEvents??1);if(r.type===`turn_start`&&(r.data?.time!=null&&(i.time=r.data.time),r.data?.metrics&&(i.metrics=r.data.metrics),r.data?.title&&r.data?.title!==`Director generating...`&&!r.data?.totalEvents)){let e=jE(i,0,1);e.title=r.data.title,e.category=r.data.category,e.emergent=r.data.emergent,e.description=r.data.crisis||r.data.turnSummary||``}if(r.type===`event_start`){let e=jE(i,a,o);e.title=r.data?.title,e.category=r.data?.category,e.emergent=r.data?.emergent,e.description=r.data?.description||r.data?.turnSummary||``}if(r.type===`decision_made`&&n.set(a,{decision:String(r.data?.decision||``),rationale:String(r.data?.rationale||``),policies:Array.isArray(r.data?.selectedPolicies)?r.data.selectedPolicies.map(e=>typeof e==`string`?e:JSON.stringify(e)):[]}),r.type===`outcome`){let e=jE(i,a,o);e.outcome=String(r.data?.outcome||``);let t=n.get(a);t&&(e.decision=t.decision,e.rationale=t.rationale,e.policies=t.policies,n.delete(a))}if(r.type===`specialist_done`){let e=jE(i,a,o),t=r.data?.department;if(t){let n=(r.data?._filteredTools||[]).filter(e=>e?.approved!==!1).length;e.depts[t]={summary:r.data?.summary||``,tools:n,citations:Number(r.data?.citations??0),citationList:r.data?.citationList||[]}}}r.type===`agent_reactions`&&(i.reactions=(r.data?.reactions||[]).slice(0,3),i.totalReactions=Number(r.data?.totalReactions??0))}return t}function NE(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function PE({state:e,verdict:t,shownRun:n,reportSections:r}){let i=h_(),a=D_(),[o,s]=kE(`paracosm-reports-refs-open`,!1),[c,l]=kE(`paracosm-reports-tools-open`,!1),[u,d]=(0,b.useState)(!1),{state:f,dispatch:p}=Gn(),m=nA(),h=iA(),g=Lm(),[_,v]=(0,b.useState)(null),y=f.parent,S=Qk(),C=eA(),w=y?.metadata?.scenario,T=typeof w?.id==`string`&&w.id!==S.id,E=(0,b.useCallback)(t=>!y||e.isRunning||!C||T?!1:bT(y,t),[y,e.isRunning,C,T]),D=(0,b.useCallback)(async e=>{v(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;p({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=yT(e.parentArtifact),r=e.seedOverride??e.parentArtifact.metadata.seed??42;try{let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:[e.leader],turns:n,seed:r,captureSnapshots:!0,customEvents:e.customEvents,forkFrom:{parentArtifact:_T(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));p({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));k(window,a.visitorId),h(),m(`studio`)}catch(e){p({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[p,m,h]),O=e.actorIds[0]??null,A=e.actorIds[1]??null,[j,ee]=(0,b.useState)(O),[te,M]=(0,b.useState)(A);(0,b.useEffect)(()=>{j&&!e.actorIds.includes(j)&&ee(O),te&&!e.actorIds.includes(te)&&M(A)},[e.actorIds,j,te,O,A]);let N=j??O,ne=te??A,P=e.actorIds.length>2,[re,ie]=(0,b.useState)(!P);(0,b.useEffect)(()=>{ie(!P)},[P]);let F=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,ME(e.actors[n]?.events));return t},[e]),I=(0,b.useMemo)(()=>{let e=N&&F.get(N)||new Map,t=ne&&F.get(ne)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??AE(),b:t.get(n)??AE()}])},[F,N,ne]),ae=(0,b.useMemo)(()=>{if(!P)return[];let t=new Set;for(let e of F.values())for(let n of e.keys())t.add(n);return[...t].sort((e,t)=>e-t).map(t=>{let n=new Map;for(let r of e.actorIds)n.set(r,F.get(r)?.get(t)??AE());return[t,n]})},[P,F,e.actorIds]),oe=N,se=ne,ce=oe?e.actors[oe]:null,le=se?e.actors[se]:null,L=ce?.leader?.name||`Leader A`,ue=le?.leader?.name||`Leader B`,de=(ce?.events.some(e=>e.type===`personality_drift`)??!1)||(le?.events.some(e=>e.type===`personality_drift`)??!1),fe=I.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),R=I.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),z=(0,b.useMemo)(()=>GT({configuredSections:r,hasQuotes:fe,hasCausality:R,hasVerdict:!!t,hasTrajectories:de,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:a.list.length>0,hasReferences:i.list.length>0}),[r,fe,R,t,de,e.cost,a.list.length,i.list.length]),pe=(0,b.useMemo)(()=>hE(I),[I]),me=(0,b.useMemo)(()=>pE(e,N,ne),[e,N,ne]),he=(0,b.useMemo)(()=>P?mE(e,Pe):null,[P,e]),ge=(0,b.useMemo)(()=>{let e=[];pe.length>0&&e.push({id:`strip`,label:`Strip`}),me.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),de&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of I)e.push({id:`turn-${t}`,label:`Turn ${t}`});return a.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),i.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,pe.length,me,de,I,a.list.length,i.list.length]),_e=(0,b.useRef)(null),B=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{B.current&&_e.current&&I.length>0&&_e.current.scrollTo({top:_e.current.scrollHeight,behavior:`smooth`})},[I.length]),!(ce?.events.length??0)&&!(le?.events.length??0)?e.isRunning?(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsxs)(`div`,{className:`${Z.emptyMsg} ${Z.emptyMsgRunning??``}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:Z.emptySpinner,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`Awaiting first turn — the report populates once the kernel reports an event.`})]})}):(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsx)(`div`,{className:Z.emptyMsg,children:`Run a simulation first to see the report.`})}):(0,x.jsxs)(`div`,{className:`reports-layout ${Z.layout}`,children:[(0,x.jsxs)(`div`,{ref:_e,onScroll:()=>{let e=_e.current;e&&(B.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[C&&T&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,w?.name??w?.id,`, and a fork runs in its parent's scenario. Switch to `,w?.name??w?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&I.length===0)return null;let i=I.length,a=I[I.length-1],o=I[0],s=(e,t)=>{let n=e?.[t];return typeof n==`number`?n:0},c=s(a?.[1]?.a?.metrics,`population`),l=s(a?.[1]?.b?.metrics,`population`),u=s(a?.[1]?.a?.metrics,`morale`),d=s(a?.[1]?.b?.metrics,`morale`),f=s(o?.[1]?.a?.metrics,`population`)||c,p=s(o?.[1]?.b?.metrics,`population`)||l,m=ce?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=le?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,g=[{label:`Turns`,value:String(i)},{label:`Final pop`,value:`A ${c}${c<f?` (↓${f-c})`:``} · B ${l}${l<p?` (↓${p-l})`:``}`,tone:c+l<f+p?`neg`:`neutral`},{label:`Final morale`,value:`A ${Math.round(u*100)}% · B ${Math.round(d*100)}%`,tone:Math.min(u,d)<.3?`neg`:Math.min(u,d)>=.6?`pos`:`neutral`},{label:`Tools forged`,value:`A ${m} · B ${h}`}];return(0,x.jsxs)(`div`,{className:Z.tldr,children:[(0,x.jsxs)(`div`,{className:Z.tldrTopRow,children:[(0,x.jsx)(`span`,{className:Z.tldrTag,children:`TL;DR`}),n?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[n,` wins`]}):i>0?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[`Run `,i,` turn`,i===1?``:`s`,` — verdict pending`]}):null,r&&(0,x.jsx)(`span`,{className:Z.tldrSub,children:r})]}),(0,x.jsx)(`div`,{className:Z.tldrStats,children:g.map(e=>(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:Z.tldrStatLabel,children:[e.label,`:`]}),(0,x.jsx)(`span`,{className:Z.tldrStatValue,style:{"--tone-color":NE(e.tone)},children:e.value})]},e.label))})]})})(),(0,x.jsxs)(`div`,{className:Z.headerRow,children:[(0,x.jsx)(`h2`,{className:Z.headerTitle,children:`Turn-by-Turn Report`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=document.getElementById(`summary`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},className:Z.jumpBtn,children:t?`↓ See verdict + full summary`:`↓ Jump to summary`})]}),P&&(0,x.jsxs)(`div`,{className:Z.actorPairPicker,role:`region`,"aria-label":`Pair focus toggle`,children:[(0,x.jsxs)(`label`,{className:Z.actorPairPickerToggle,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:re,onChange:e=>ie(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),re?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:N??``,onChange:e=>ee(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:Z.actorPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right side actor`,className:Z.actorPairPickerSelect,value:ne??``,onChange:e=>M(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===N,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`strip + metrics + trajectory show this pair only · turn-by-turn below shows all `,e.actorIds.length,` actors`]})]}):(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`Showing all `,e.actorIds.length,` actors. Toggle on to focus on a 2-actor head-to-head view in the strip, sparklines, and trajectory cards.`]})]}),(!P||re)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(xE,{turns:pe,leaderAName:L,leaderBName:ue})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!P||re?(0,x.jsx)(EE,{metrics:me,leaderAName:L,leaderBName:ue}):he&&(0,x.jsx)(EE,{metrics:he,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[de&&re&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(LT,{events:ce?.events??[],actorName:L,baselineHexaco:ce?.leader?.hexaco}),(0,x.jsx)(LT,{events:le?.events??[],actorName:ue,baselineHexaco:le?.leader?.hexaco})]}),de&&!re&&(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:e.actorIds.map(t=>{let n=e.actors[t];return n?.events.length?(0,x.jsx)(LT,{events:n.events,actorName:n.leader?.name||t,baselineHexaco:n.leader?.hexaco},t):null})})]}),e.cost&&e.cost.llmCalls>0&&(0,x.jsxs)(`div`,{className:Z.costBar,children:[(0,x.jsx)(`span`,{className:Z.costLabel,children:`Run cost`}),(0,x.jsxs)(`span`,{className:Z.costAmount,children:[`$`,e.cost.totalCostUSD<.01?e.cost.totalCostUSD.toFixed(4):e.cost.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:Z.costMeta,children:[`· `,e.cost.llmCalls,` LLM calls · `,(e.cost.totalTokens/1e3).toFixed(1),`k tokens`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>d(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),u&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(AT,{combined:e.cost,leaderA:(oe?e.costByActor[oe]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(se?e.costByActor[se]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ce?.leader?.name,leaderBName:le?.leader?.name,actors:P?e.actorIds.map(t=>({actorId:t,name:e.actors[t]?.leader?.name||t,cost:e.costByActor[t]??{totalTokens:0,totalCostUSD:0,llmCalls:0}})):void 0,onClose:()=>d(!1)}),!P&&I.map(([e,t])=>{let n=t.a,r=t.b,i=n.time||r.time||`?`,a=Math.max(...[...n.events.values()].map(e=>e.totalEvents),...[...r.events.values()].map(e=>e.totalEvents),1),o=n.events.get(0)?.title,s=r.events.get(0)?.title,c=!!(o&&s&&o!==s);return(0,x.jsxs)(`section`,{id:`turn-${e}`,className:[Z.turnSection,c?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,e,` — Y`,i,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,c?Z.diverged:``].filter(Boolean).join(` `),children:c?`DIVERGENT`:`SHARED`}),E(e)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(e),"aria-label":`Fork at ${g.time} ${e}`,children:[`↳ Fork at `,g.Time,` `,e]})]})]}),Array.from({length:a}).map((e,t)=>(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${t<a-1?Z.eventGridSpaced:Z.eventGrid}`,children:[(0,x.jsx)(IE,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:L,sideColor:`var(--vis)`,sections:z.eventSections}),(0,x.jsx)(IE,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:ue,sideColor:`var(--eng)`,sections:z.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(LE,{data:n,name:L,sideColor:`var(--vis)`,showQuotes:z.footerSections.includes(`quotes`)}),(0,x.jsx)(LE,{data:r,name:ue,sideColor:`var(--eng)`,showQuotes:z.footerSections.includes(`quotes`)})]})]},e)}),P&&ae.map(([t,n])=>{let r=[],i,a=1;for(let t of e.actorIds){let e=n.get(t);if(!e)continue;i??=e.time;for(let t of e.events.values())t.totalEvents>a&&(a=t.totalEvents);let o=e.events.get(0)?.title;o&&r.push(o)}let o=new Set(r).size>1,s=i??`?`;return(0,x.jsxs)(`section`,{id:`turn-${t}`,className:[Z.turnSection,o?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,t,` — Y`,s,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,o?Z.diverged:``].filter(Boolean).join(` `),children:o?`DIVERGENT`:`SHARED`}),E(t)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(t),"aria-label":`Fork at ${g.time} ${t}`,children:[`↳ Fork at `,g.Time,` `,t]})]})]}),Array.from({length:a}).map((t,r)=>(0,x.jsx)(`div`,{className:r<a-1?Z.nActorEventTrackSpaced:Z.nActorEventTrack,children:e.actorIds.map((t,i)=>{let o=n.get(t)?.events.get(r),s=e.actors[t]?.leader?.name??t;return(0,x.jsx)(IE,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:z.eventSections},t)})},r)),(0,x.jsx)(`div`,{className:Z.nActorFooterTrack,children:e.actorIds.map((t,r)=>{let i=n.get(t);if(!i)return null;let a=e.actors[t]?.leader?.name??t;return(0,x.jsx)(LE,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:z.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:a.list.length>0&&(0,x.jsxs)(`details`,{open:c,onToggle:e=>{let t=e.currentTarget.open;t&&!c&&B_({name:`forge_toolbox_open`,from:`reports`}),l(t)},className:K.pageFold,children:[(0,x.jsx)(`summary`,{className:K.pageFoldSummary,children:`FORGED TOOLBOX`}),(0,x.jsx)(Nb,{inPage:!0})]})}),(0,x.jsxs)(`section`,{id:`summary`,className:Z.summarySection,children:[(0,x.jsx)(`div`,{className:Z.summaryLabel,children:`Run Summary · Verdict · Winner`}),(0,x.jsx)(XT,{verdict:t,leaderAName:L,leaderBName:ue}),(0,x.jsx)(cE,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(jn,{verdict:t,shownRun:n})})]}),(0,x.jsx)(`section`,{id:`references`,children:i.list.length>0&&(0,x.jsx)(hC,{registry:i,title:`References`,collapsible:!0,defaultOpen:o,onToggle:s})}),(0,x.jsxs)(`details`,{className:Z.aboutDetails,children:[(0,x.jsx)(`summary`,{className:Z.aboutSummary,children:`What's in this report?`}),(0,x.jsxs)(`div`,{className:Z.aboutBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`Scenario focus`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:RT[e]},e))})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`This run produced`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:zT[e]},e))})]})]})]})]}),(0,x.jsx)(OE,{items:ge,scrollRoot:_e.current}),_!==null&&y&&(0,x.jsx)(ST,{parentArtifact:y,atTurn:_,maxTurns:yT(y),costPreset:`economy`,provider:`openai`,onConfirm:D,onClose:()=>v(null)})]})}var FE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function IE({block:e,eventIndex:t,totalEvents:n,name:r,sideColor:i,sections:a}){let o={"--side-color":i};if(!e||!e.title)return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),(0,x.jsx)(`span`,{className:Z.eventAwaiting,children:`Awaiting data...`})]});let s={crisis:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Z.eventTitle,children:[e.title,e.category&&(0,x.jsx)(`span`,{className:Z.categoryPill,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:Z.emergentPill,children:`EMERGENT`})]}),e.description&&(0,x.jsx)(`div`,{className:Z.eventDescription,children:e.description})]},`crisis`),decision:e.decision?(0,x.jsx)(`div`,{className:Z.eventDecision,children:e.decision},`decision`):null,outcome:e.outcome?(0,x.jsxs)(`div`,{className:Z.eventOutcomeRow,children:[(0,x.jsx)(MS,{outcome:e.outcome}),Array.isArray(e.policies)&&e.policies.length>0&&(0,x.jsx)(`span`,{className:Z.eventPolicies,children:e.policies.map(e=>String(e)).join(` / `)})]},`outcome`):null,causality:e.rationale?(0,x.jsxs)(`details`,{className:Z.eventDetails,children:[(0,x.jsx)(`summary`,{className:Z.eventDetailsSummary,style:o,children:`Rationale`}),(0,x.jsx)(`div`,{className:Z.eventRationale,style:o,children:e.rationale})]},`causality`):null,departments:Object.keys(e.depts).length>0?(0,x.jsxs)(`details`,{className:Z.eventDetails,open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.eventDetailsSummary,style:o,children:[`Departments (`,Object.keys(e.depts).length,`)`]}),(0,x.jsx)(`div`,{className:Z.deptList,children:Object.entries(e.depts).map(([e,t])=>(0,x.jsxs)(`div`,{className:Z.deptItem,style:o,children:[(0,x.jsxs)(`div`,{className:Z.deptHead,children:[(0,x.jsx)(`span`,{className:Z.deptName,children:e.charAt(0).toUpperCase()+e.slice(1)}),(0,x.jsxs)(`span`,{className:Z.deptMeta,children:[t.citations,`c `,t.tools,`t`]})]}),t.summary&&(0,x.jsx)(`div`,{className:Z.deptSummary,children:t.summary}),(0,x.jsx)(PS,{citations:t.citationList,label:``})]},e))})]},`departments`):null};return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),a.map(e=>s[e]).filter(Boolean)]})}function LE({data:e,name:t,sideColor:n,showQuotes:r}){let i=e.metrics;if(!i&&(!r||e.reactions.length===0))return(0,x.jsx)(`div`,{});let a={"--side-color":n};return(0,x.jsxs)(`div`,{className:Z.footerCard,children:[i&&(0,x.jsxs)(`details`,{className:e.reactions.length?Z.footerDetails:Z.footerDetailsLast,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[t,` · Systems State`]}),(0,x.jsx)(`div`,{className:Z.systemsRow,children:Object.entries(i).map(([e,t])=>(0,x.jsxs)(`span`,{className:Z.systemItem,children:[(0,x.jsxs)(`span`,{className:Z.systemKey,children:[e,`: `]}),(0,x.jsx)(`span`,{className:Z.systemValue,children:typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):String(t)})]},e))})]}),r&&e.reactions.length>0&&(0,x.jsxs)(`details`,{open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[`Agent Voices (`,e.totalReactions||e.reactions.length,`)`]}),(0,x.jsx)(`div`,{className:Z.reactionsList,children:e.reactions.map((e,t)=>(0,x.jsxs)(`div`,{className:Z.reactionItem,children:[(0,x.jsxs)(`div`,{className:Z.reactionHead,children:[(0,x.jsx)(`span`,{className:Z.reactionName,style:a,children:String(e.name)}),(0,x.jsx)(`span`,{className:Z.moodPill,style:{"--mood-color":FE[String(e.mood)]||`var(--text-3)`},children:String(e.mood||``).toUpperCase()})]}),(0,x.jsxs)(`div`,{className:Z.reactionQuote,children:[`“`,String(e.quote||``),`”`]}),!!e.role&&(0,x.jsxs)(`div`,{className:Z.reactionRole,children:[String(e.role),` `,e.department?`in ${String(e.department)}`:``]})]},t))})]})]})}var Q={layout:`_layout_1l1dk_1`,sidebar:`_sidebar_1l1dk_15`,sidebarHeading:`_sidebarHeading_1l1dk_31`,sidebarLead:`_sidebarLead_1l1dk_38`,actorFilter:`_actorFilter_1l1dk_45`,actorFilterLabel:`_actorFilterLabel_1l1dk_64`,actorFilterSelect:`_actorFilterSelect_1l1dk_74`,agentBtn:`_agentBtn_1l1dk_96`,selected:`_selected_1l1dk_110`,agentName:`_agentName_1l1dk_115`,agentMeta:`_agentMeta_1l1dk_119`,agentMood:`_agentMood_1l1dk_124`,chatArea:`_chatArea_1l1dk_131`,memoryBar:`_memoryBar_1l1dk_138`,memoryLabel:`_memoryLabel_1l1dk_145`,memoryBelief:`_memoryBelief_1l1dk_152`,memoryStance:`_memoryStance_1l1dk_157`,hexacoStrip:`_hexacoStrip_1l1dk_162`,hexacoLabel:`_hexacoLabel_1l1dk_174`,hexacoTrait:`_hexacoTrait_1l1dk_180`,hexacoBar:`_hexacoBar_1l1dk_184`,healthSignal:`_healthSignal_1l1dk_188`,messages:`_messages_1l1dk_192`,emptyState:`_emptyState_1l1dk_207`,emptyTitle:`_emptyTitle_1l1dk_213`,emptyCopy:`_emptyCopy_1l1dk_218`,eventCtx:`_eventCtx_1l1dk_225`,eventGroup:`_eventGroup_1l1dk_235`,eventGroupLast:`_eventGroupLast_1l1dk_239`,eventGroupLabel:`_eventGroupLabel_1l1dk_243`,eventRow:`_eventRow_1l1dk_252`,eventTurn:`_eventTurn_1l1dk_258`,eventTitle:`_eventTitle_1l1dk_265`,eventCategory:`_eventCategory_1l1dk_270`,memoryItem:`_memoryItem_1l1dk_275`,memoryTime:`_memoryTime_1l1dk_282`,relationshipsRow:`_relationshipsRow_1l1dk_287`,relationshipChip:`_relationshipChip_1l1dk_293`,bubbleWrap:`_bubbleWrap_1l1dk_297`,fromUser:`_fromUser_1l1dk_301`,fromAgent:`_fromAgent_1l1dk_305`,bubbleName:`_bubbleName_1l1dk_309`,bubble:`_bubble_1l1dk_297`,user:`_user_1l1dk_327`,typingBubble:`_typingBubble_1l1dk_332`,typingLabel:`_typingLabel_1l1dk_344`,dot:`_dot_1l1dk_359`,"chat-dot-bounce":`_chat-dot-bounce_1l1dk_1`,inputRow:`_inputRow_1l1dk_375`,inputField:`_inputField_1l1dk_392`,sendBtn:`_sendBtn_1l1dk_412`},RE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function zE(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function BE({memory:e,events:t,scenario:n}){let r=[];for(let e of t.actorIds){let n=t.actors[e];if(n){for(let e of n.events)if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`){let t=e.data.turn;r.some(e=>e.turn===t)||r.push({turn:t,time:e.data.time||0,title:String(e.data.title),category:String(e.data.category||``)})}}}r.sort((e,t)=>e.turn-t.turn);let i=n.labels.eventNoun||`events`,a=e.recentMemories?.length>0,o=e.relationships?.length>0;return!r.length&&!a?null:(0,x.jsxs)(`div`,{className:Q.eventCtx,children:[r.length>0&&(0,x.jsxs)(`div`,{className:a?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsxs)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--rust)`},children:[i.toUpperCase(),` EXPERIENCED`]}),r.map(e=>(0,x.jsxs)(`div`,{className:Q.eventRow,children:[(0,x.jsxs)(`span`,{className:Q.eventTurn,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:Q.eventTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:Q.eventCategory,children:e.category})]},e.turn))]}),a&&(0,x.jsxs)(`div`,{className:o?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--amber)`},children:`RECENT MEMORIES`}),e.recentMemories.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:Q.memoryItem,style:{"--valence-border":zE(e.valence)},children:[(0,x.jsxs)(`span`,{className:Q.memoryTime,children:[`Y`,e.time]}),` `,e.content]},t))]}),o&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--teal)`},children:`RELATIONSHIPS`}),(0,x.jsx)(`div`,{className:Q.relationshipsRow,children:e.relationships.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.relationshipChip,style:{"--rel-color":e.sentiment>0?`var(--green)`:`var(--rust)`},children:[e.name,` `,e.sentiment>0?`+`:``,e.sentiment.toFixed(1)]},t))})]})]})}function VE({state:e,onChatUsage:t}){let n=Qk(),[r,i]=(0,b.useState)(null),[a,o]=(0,b.useState)(()=>new Map),[s,c]=(0,b.useState)(()=>new Map),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(null),m=(0,b.useRef)(!0),h=()=>{let e=p.current;e&&(m.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},g=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;let i=new Map;for(let e of r.events)if(e.type===`agent_reactions`){let t=e.data.reactions||[];for(let e of t)e.name&&i.set(e.name,{name:e.name,role:e.role||``,department:e.department||``,mood:e.mood||`neutral`,age:e.age,marsborn:e.marsborn,agentId:e.agentId,memory:e.memory,hexaco:e.hexaco,psychScore:e.psychScore,boneDensity:e.boneDensity,radiation:e.radiation})}i.size>0&&t.set(n,Array.from(i.values()))}return t},[e]),_=e.actorIds.length>=2,[v,y]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!_)v!==null&&y(null);else if(v!==`all`&&!(v&&g.has(v))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(g.get(e)?.length??0)>0);y(t??`all`)}else y(`all`)}},[_,g,e.actorIds,v]);let[S,C]=(0,b.useState)(null),w=(0,b.useMemo)(()=>{if(v&&v!==`all`)return g.get(v)??[];let e=[],t=new Set;for(let n of g.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[g,v]),T=(0,b.useMemo)(()=>{let e=new Set;for(let t of w){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[w]);(0,b.useEffect)(()=>{S&&!T.includes(S)&&C(null)},[T,S]);let E=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),D=E.find(e=>e.name===r),O=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},k=e=>{let t=O(e);return t?`${t}\u0000${e}`:e},A=r?a.get(k(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[A,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let j=e=>{i(e);let t=k(e);o(n=>{if(n.has(t))return n;let r=E.find(t=>t.name===e),i=r?{role:`agent`,name:r.name,text:`${r.role} in ${r.department}, age ${r.age||`?`}. I lived through this simulation — ask me about specific turns, the commander's decisions, crises I witnessed, people I worked with, or how my department handled what came up. Try: "what did you think of the commander's choice in turn 1?", "who do you trust on the team?", or "what was the worst moment for you?"`}:{role:`agent`,text:`Connected.`},a=new Map(n);return a.set(t,[i]),a})},ee=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},te=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},M=async()=>{if(!l.trim()||!r||d)return;let e=r,n=O(e),i=k(e),a=l.trim();u(``),f(!0),ee(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];te(i,()=>o);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),s=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,...n?{leader:n}:{},message:a,history:o,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(s.reply){ee(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),te(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ee(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ee(i,t=>[...t,{role:`agent`,text:`Chat failed: ${e}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),_&&g.size>0&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-actor-filter`,children:`Lead actor`}),(0,x.jsxs)(`select`,{id:`chat-actor-filter`,className:Q.actorFilterSelect,value:v??``,onChange:e=>y(e.target.value||null),"aria-label":`Filter chat agents by lead actor`,children:[(0,x.jsxs)(`option`,{value:`all`,children:[`All leaders (`,(()=>{let e=new Set;for(let t of g.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=g.get(t)?.length??0,r=e.actors[t]?.leader?.name||t;return(0,x.jsxs)(`option`,{value:t,disabled:n===0,children:[r,` (`,n,`)`]},t)})]})]}),T.length>1&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`chat-department-filter`,className:Q.actorFilterSelect,value:S??``,onChange:e=>C(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,w.length,`)`]}),T.map(e=>{let t=w.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>j(e.name),className:[Q.agentBtn,r===e.name?Q.selected:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:Q.agentName,children:e.name}),(0,x.jsxs)(`div`,{className:Q.agentMeta,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:Q.agentMood,style:{"--mood-color":RE[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(BE,{memory:D.memory,events:e,scenario:n}),A.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&M(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:M,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_1ur8r_2`,kbdKey:`_kbdKey_1ur8r_8`,kbdLabel:`_kbdLabel_1ur8r_18`,empty:`_empty_1ur8r_22`,emptySpinner:`_emptySpinner_1ur8r_34`,emptySpinnerRotate:`_emptySpinnerRotate_1ur8r_1`,root:`_root_1ur8r_54`,toolbarStrip:`_toolbarStrip_1ur8r_62`,toolbarTopRow:`_toolbarTopRow_1ur8r_71`,modePillsWrap:`_modePillsWrap_1ur8r_76`,overflowToggle:`_overflowToggle_1ur8r_95`,overflowToggleOpen:`_overflowToggleOpen_1ur8r_109`,helpBtn:`_helpBtn_1ur8r_114`,forgeToolboxKey:`_forgeToolboxKey_1ur8r_130`,toolsRow:`_toolsRow_1ur8r_163`,paletteBtn:`_paletteBtn_1ur8r_177`,toolBtn:`_toolBtn_1ur8r_191`,settingsBtn:`_settingsBtn_1ur8r_204`,settingsBtnOpen:`_settingsBtnOpen_1ur8r_217`,modeHint:`_modeHint_1ur8r_222`,ecologyNone:`_ecologyNone_1ur8r_232`,ecologyBack:`_ecologyBack_1ur8r_243`,diffLine:`_diffLine_1ur8r_255`,phoneTabRow:`_phoneTabRow_1ur8r_264`,phoneTab:`_phoneTab_1ur8r_264`,phoneTabActive:`_phoneTabActive_1ur8r_291`,leadersRow:`_leadersRow_1ur8r_297`,leadersRowNarrow:`_leadersRowNarrow_1ur8r_306`,sideWrap:`_sideWrap_1ur8r_311`,sideWrapHidden:`_sideWrapHidden_1ur8r_318`,leadersRowLinesBelow:`_leadersRowLinesBelow_1ur8r_322`,cohortWindow:`_cohortWindow_1ur8r_327`,cohortWindowLinesBelow:`_cohortWindowLinesBelow_1ur8r_331`,cohortTrackLinesBelow:`_cohortTrackLinesBelow_1ur8r_339`,turnLinesSlot:`_turnLinesSlot_1ur8r_344`,footerKeys:`_footerKeys_1ur8r_359`,srOnly:`_srOnly_1ur8r_372`,jumpLatest:`_jumpLatest_1ur8r_384`,"paracosm-jump-pulse":`_paracosm-jump-pulse_1ur8r_1`,jumpLatestBehind:`_jumpLatestBehind_1ur8r_407`,toast:`_toast_1ur8r_412`,"paracosm-toast-in":`_paracosm-toast-in_1ur8r_1`,toastKicker:`_toastKicker_1ur8r_433`,toastKickerMeta:`_toastKickerMeta_1ur8r_445`,toastBody:`_toastBody_1ur8r_449`,toastBodyMd:`_toastBodyMd_1ur8r_454`,vignette:`_vignette_1ur8r_459`,"paracosm-vignette":`_paracosm-vignette_1ur8r_1`,cohortViewBar:`_cohortViewBar_1ur8r_475`,cohortViewModeToggle:`_cohortViewModeToggle_1ur8r_486`,cohortViewModeButton:`_cohortViewModeButton_1ur8r_495`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_1ur8r_526`,cohortPairPicker:`_cohortPairPicker_1ur8r_535`,cohortPairPickerLabel:`_cohortPairPickerLabel_1ur8r_543`,cohortPairPickerSelect:`_cohortPairPickerSelect_1ur8r_552`,cohortPairPickerVs:`_cohortPairPickerVs_1ur8r_575`,cohortPairPickerHint:`_cohortPairPickerHint_1ur8r_583`};function HE(e){return(0,b.useMemo)(()=>UE(e),[e])}function UE(e){let t={};for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;t[n]=[];let i=new Map;for(let e of r.events)if((e.type===`event_start`||e.type===`turn_start`)&&e.turn!=null){let t=e.data?.category;if(typeof t==`string`&&t.length>0){let n=i.get(e.turn)??[];n.includes(t)||n.push(t),i.set(e.turn,n)}}let a=r.events.filter(e=>e.type===`systems_snapshot`);for(let e=0;e<r.agentSnapshots.length;e++){let o=r.agentSnapshots[e],s=a[e]?.data||{},c=s.turn||e+1,l=r.events.find(e=>e.type===`turn_done`&&e.data?.turn===c)?.data?.metrics??{},u=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,d=o.map(e=>({agentId:e.agentId,name:e.name,department:e.department,role:e.role,rank:e.rank,alive:e.alive,marsborn:e.marsborn,psychScore:e.psychScore,age:e.age,generation:e.generation,partnerId:e.partnerId,childrenIds:e.childrenIds||[],featured:e.featured,mood:e.mood,shortTermMemory:e.shortTermMemory||[]}));t[n].push({turn:c,time:s.time||0,cells:d,population:s.population||d.filter(e=>e.alive).length,morale:s.morale||0,foodReserve:typeof s.foodReserve==`number`?s.foodReserve:u(l.foodMonthsReserve),waterLitersPerDay:u(l.waterLitersPerDay),powerKw:u(l.powerKw),pressurizedVolumeM3:u(l.pressurizedVolumeM3),deaths:s.deaths||0,births:s.births||0,eventCategories:i.get(c)??[]})}}return t}var WE={region:`_region_1xlv9_1`,narrow:`_narrow_1xlv9_12`,canvasWrap:`_canvasWrap_1xlv9_18`,canvas:`_canvas_1xlv9_18`,revealCover:`_revealCover_1xlv9_38`,cornerBtn:`_cornerBtn_1xlv9_48`,focusBtn:`_focusBtn_1xlv9_70`,divergenceEmpty:`_divergenceEmpty_1xlv9_75`,divergenceEmptyMsg:`_divergenceEmptyMsg_1xlv9_86`,tileTooltip:`_tileTooltip_1xlv9_98`,tileKindLabel:`_tileKindLabel_1xlv9_117`,tileCoords:`_tileCoords_1xlv9_125`,tileNearestName:`_tileNearestName_1xlv9_131`,tileNearestRole:`_tileNearestRole_1xlv9_136`,tileNearestDeath:`_tileNearestDeath_1xlv9_142`,tileNearestBirth:`_tileNearestBirth_1xlv9_148`,tileNearestPattern:`_tileNearestPattern_1xlv9_154`,tileAmbient:`_tileAmbient_1xlv9_160`,hoverTooltip:`_hoverTooltip_1xlv9_164`,hoverHeader:`_hoverHeader_1xlv9_182`,hoverFeaturedPill:`_hoverFeaturedPill_1xlv9_192`,hoverRole:`_hoverRole_1xlv9_201`,hoverMood:`_hoverMood_1xlv9_209`,hoverMoodValue:`_hoverMoodValue_1xlv9_213`,psychBlock:`_psychBlock_1xlv9_217`,psychLabel:`_psychLabel_1xlv9_221`,psychSvg:`_psychSvg_1xlv9_227`,hoverHint:`_hoverHint_1xlv9_234`};function GE(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function KE(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}function qE(e,t,n,r,i=8){return{x:Math.max(i,Math.min(n-i,e)),y:Math.max(i,Math.min(r-i,t))}}function JE(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function YE(e,t,n){let r=new Map;if(n.length===0)return r;let i=e/2,a=t/2,o=Math.min(e,t)*.32,s=Math.min(e,t)*.14;if(n.length===1)return r.set(n[0],{cx:i,cy:a,r:s*1.5}),r;for(let e=0;e<n.length;e++){let t=Math.PI*2*e/n.length-Math.PI/2;r.set(n[e],{cx:i+Math.cos(t)*o,cy:a+Math.sin(t)*o,r:s})}return r}function XE(e,t,n){let r=YE(t,n,JE(e)),i=new Map;for(let a of e){let e=r.get(a.department||`unknown`)??{cx:t/2,cy:n/2,r:40},o=GE(KE(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,qE(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function ZE(e,t,n){let r=new Map,i=new Set,a=new Map(e.map(e=>[e.agentId,e])),o=[];for(let t of e)if(!i.has(t.agentId)&&t.partnerId&&a.has(t.partnerId)&&!i.has(t.partnerId)){let e=a.get(t.partnerId),n=t.childrenIds.map(e=>a.get(e)).filter(e=>!!e);o.push([t,e,...n]),i.add(t.agentId),i.add(e.agentId);for(let e of n)i.add(e.agentId)}let s=e.filter(e=>!i.has(e.agentId)),c=Math.max(50,(t-80)/Math.max(1,o.length));return o.forEach((e,i)=>{let a=40+c*i+c/2;e.forEach((i,o)=>{let s=GE(KE(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,qE(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=GE(KE(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,qE(o,c,t,n))}),r}function QE(e,t,n){let r={positive:-1,hopeful:-.6,neutral:0,anxious:.4,negative:.8,defiant:.6,resigned:.7},i=new Map;for(let a of e){let e=(r[a.mood]??0)*.5+.5,o=GE(KE(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,qE(s,c,t,n))}return i}function $E(e,t,n){let r=new Map;for(let i of e){let e=Math.max(0,Math.min(80,i.age??30))/80,a=GE(KE(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,qE(o,s,t,n))}return r}function eD(e,t,n,r){return t===`families`?ZE(e,n,r):t===`mood`?QE(e,n,r):t===`age`?$E(e,n,r):XE(e,n,r)}function tD(e,t,n,r,i=1,a,o=!1,s=0,c=``,l=!1,u=`rgba(216, 204, 176, 0.9)`,d=`rgba(10, 8, 6, 0.55)`){e.save(),.5+.5*Math.sin(s*.003);let f=c.trim().toLowerCase().split(/\s+/).filter(Boolean),p=f.length>0,m=e=>{if(!p)return!1;let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();return f.every(e=>t.includes(e))};for(let c of t){if(!c.alive)continue;let t=n.get(c.agentId);if(!t)continue;let l=a?.has(c.agentId)??!1;if(o&&!l)continue;let u=m(c),d=p&&!u,f=c.featured?5:3,h=c.featured?.95:.75,g=d?.25:1;if(c.featured&&!d){let n=f+6,a=.42*i;e.strokeStyle=r,e.lineWidth=1,e.globalAlpha=a,e.beginPath(),e.arc(t.x,t.y,n,0,Math.PI*2),e.stroke()}if(u){let n=.7+.3*Math.sin(s*.006);e.strokeStyle=`rgba(248, 225, 150, 1)`,e.lineWidth=2.2,e.globalAlpha=i*n,e.beginPath(),e.arc(t.x,t.y,f+6,0,Math.PI*2),e.stroke()}l&&!d&&(e.strokeStyle=`rgba(232, 180, 74, 0.9)`,e.lineWidth=2,e.globalAlpha=i,e.beginPath(),e.arc(t.x,t.y,f+3,0,Math.PI*2),e.stroke()),e.strokeStyle=l?`rgba(224, 101, 48, 1)`:r,e.lineWidth=c.featured||l||u?1.6:1,e.globalAlpha=(l?1:h)*i*g,e.beginPath(),e.arc(t.x,t.y,f,0,Math.PI*2),e.stroke()}if(l){e.font=`9px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`top`;for(let r of t){if(!r.alive)continue;let t=n.get(r.agentId);if(!t)continue;let s=a?.has(r.agentId)??!1;if(o&&!s||!r.featured&&!s)continue;let c=m(r);if(p&&!c)continue;let l=r.name.split(/\s+/)[0],f=t.y+(r.featured?12:10),h=e.measureText(l).width;e.fillStyle=d,e.fillRect(t.x-h/2-3,f-1,h+6,10),e.fillStyle=s?`rgba(232, 180, 74, 0.95)`:u,e.globalAlpha=i,e.fillText(l,t.x,f)}}e.restore()}var nD={birth:`rgba(154, 205, 96, 0.8)`,death:`rgba(168, 152, 120, 0.7)`,forge_approved:`rgba(232, 180, 74, 0.8)`,forge_rejected:`rgba(224, 101, 48, 0.7)`,reuse:`rgba(232, 180, 74, 0.6)`,crisis:`rgba(196, 74, 30, 0.8)`},rD=6;function iD(e,t){e.save();for(let n of t){let t=nD[n.kind]??`rgba(255,255,255,0.6)`,r=n.progress,i=1-r;if(e.globalAlpha=i,n.kind===`birth`||n.kind===`death`||n.kind===`crisis`){let a=4+r*14;if(e.strokeStyle=t,e.lineWidth=1.2,e.beginPath(),e.arc(n.x,n.y,a,0,Math.PI*2),e.stroke(),n.kind!==`crisis`){let a=2+r*22,o=n.kind===`birth`?1.8:1.4;e.fillStyle=t;for(let t=0;t<rD;t++){let r=t/rD*Math.PI*2+(n.kind===`birth`?.3:-.2),s=n.x+Math.cos(r)*a,c=n.y+Math.sin(r)*a;e.globalAlpha=i*.9,e.beginPath(),e.arc(s,c,o,0,Math.PI*2),e.fill()}}}else if(n.kind===`reuse`&&typeof n.endX==`number`&&typeof n.endY==`number`){let a=n.x+(n.endX-n.x)*r,o=n.y+(n.endY-n.y)*r,s=e.createRadialGradient(a,o,0,a,o,8);s.addColorStop(0,`rgba(248, 225, 150, 0.95)`),s.addColorStop(.4,t),s.addColorStop(1,`rgba(232, 180, 74, 0)`),e.fillStyle=s,e.globalAlpha=i,e.beginPath(),e.arc(a,o,8,0,Math.PI*2),e.fill(),e.fillStyle=`rgba(248, 225, 150, 0.95)`,e.beginPath(),e.arc(a,o,2,0,Math.PI*2),e.fill()}else e.fillStyle=t,e.beginPath(),e.arc(n.x,n.y,3,0,Math.PI*2),e.fill()}e.restore()}var aD={medical:`rgba(78, 205, 196, 0.9)`,engineering:`rgba(232, 180, 74, 0.9)`,agriculture:`rgba(106, 173, 72, 0.9)`,psychology:`rgba(155, 107, 158, 0.9)`,governance:`rgba(224, 101, 48, 0.9)`,research:`rgba(149, 107, 216, 0.9)`,science:`rgba(149, 107, 216, 0.9)`,ops:`rgba(200, 122, 58, 0.9)`,operations:`rgba(200, 122, 58, 0.9)`};function oD(e){return aD[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function sD(e,t,n){e.save(),e.font=`10px ui-monospace, monospace`,e.fillStyle=n.sideColor,e.textBaseline=`top`,e.textAlign=`left`;let r=n.actorName.toUpperCase();e.fillText(r,10,10);let i=e.measureText(r).width,a=(n.actorArchetype||``).trim().replace(/^The\s+/i,``);if(a){e.font=`bold 8px ui-monospace, monospace`;let t=a.toUpperCase(),r=e.measureText(t).width,o=10+i+8;e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.5)`,e.fillRect(o,9,r+10,13),e.strokeStyle=n.sideColor,e.lineWidth=1,e.strokeRect(o+.5,9.5,r+10-1,12),e.fillStyle=n.sideColor,e.textBaseline=`middle`,e.fillText(t,o+5,16),e.textBaseline=`top`,e.font=`10px ui-monospace, monospace`}e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.75)`;let o=t?.time,s=n.timeUnitShort??`t`,c=typeof o==`number`?typeof n.startTime==`number`?`T${t?.turn??0} · ${o} · ${s} ${Math.max(0,o-n.startTime)}`:`T${t?.turn??0} · ${o}`:`T${t?.turn??0}`;if(e.fillText(c,10,24),!t){e.restore();return}if(n.deptLabels&&n.cells&&n.positions&&n.cells.length>0){let t=new Map;for(let e of n.cells){if(!e.alive)continue;let r=n.positions.get(e.agentId);if(!r)continue;let i=(e.department||`unknown`).toLowerCase(),a=t.get(i)??{xs:[],ys:[]};a.xs.push(r.x),a.ys.push(r.y),t.set(i,a)}e.font=`bold 9px ui-monospace, monospace`,e.textBaseline=`middle`,e.textAlign=`center`;let r=[];for(let[n,i]of t.entries()){if(i.xs.length===0)continue;let t=i.xs.reduce((e,t)=>e+t,0)/i.xs.length,a=Math.min(...i.ys),o=Math.max(14,a-14),s=`${n.toUpperCase()} ${i.xs.length}`,c=e.measureText(s);r.push({dept:n,cx:t,w:c.width+8,h:14,label:s,idealY:o})}r.sort((e,t)=>e.idealY-t.idealY);let i=[],a=(e,t)=>Math.abs(e.cx-t.cx)<(e.w+t.w)/2+2&&Math.abs(e.y-t.y)<(e.h+t.h)/2+2;for(let e of r){let t=e.idealY;for(let n=0;n<10;n++){let r=e.idealY-n*16,o=e.idealY+n*16,s=n===0?e.idealY:r>=10?r:o;if(!i.some(t=>a({cx:e.cx,w:e.w,y:s,h:e.h},t))){t=s;break}}i.push({...e,y:t})}for(let t of i)e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.85)`,e.fillRect(t.cx-t.w/2,t.y-t.h/2,t.w,t.h),e.strokeStyle=oD(t.dept),e.lineWidth=1,e.strokeRect(t.cx-t.w/2+.5,t.y-t.h/2+.5,t.w-1,t.h-1),e.fillStyle=oD(t.dept),e.fillText(t.label,t.cx,t.y)}e.font=`10px ui-monospace, monospace`,e.textAlign=`left`,e.textBaseline=`bottom`,e.fillStyle=n.sideColor;let l=n.previousSnapshot?t.population-n.previousSnapshot.population:0,u=l>0?`↑`:l<0?`↓`:``,d=l>0?`rgba(106, 173, 72, 0.95)`:l<0?`rgba(196, 74, 30, 0.95)`:`rgba(216, 204, 176, 0.75)`;if(e.fillText(`POP ${t.population}`,10,n.height-20),u){let r=`POP ${t.population}`,i=e.measureText(r).width+6;e.fillStyle=d,e.fillText(`${u}${Math.abs(l)}`,10+i,n.height-20),e.fillStyle=n.sideColor}(t.deaths>0||t.births>0)&&(e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.65)`,e.fillText(`+${t.births} -${t.deaths}`,10,n.height-8)),n.lagTurns&&n.lagTurns>0&&(e.textAlign=`right`,e.fillStyle=`rgba(232, 180, 74, 0.75)`,e.fillText(`lagging ${n.lagTurns}`,n.width-10,n.height-8)),e.restore()}function cD(e,t,n,r,i){if(t.length===0||r.length===0)return;let a=new Map;for(let e of r){if(e.approved===!1)continue;let t=(e.department||`unknown`).toLowerCase();a.set(t,(a.get(t)??0)+1)}if(a.size===0)return;let o=new Map;for(let e of t){if(!e.alive)continue;let t=n.get(e.agentId);if(!t)continue;let r=(e.department||`unknown`).toLowerCase(),i=o.get(r)??{x:0,y:0,count:0};i.x+=t.x,i.y+=t.y,i.count+=1,o.set(r,i)}let s=Math.max(...a.values());e.save(),e.globalCompositeOperation=`lighter`;for(let[t,n]of a.entries()){let r=o.get(t);if(!r||r.count===0)continue;let a=r.x/r.count,c=r.y/r.count,l=n/s,u=30+l*50,d=.2+l*.25,f=e.createRadialGradient(a,c,0,a,c,u);f.addColorStop(0,dD(i,d)),f.addColorStop(.6,dD(i,d*.4)),f.addColorStop(1,dD(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=dD(i,.95),e.font=`bold 11px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${n}`,a,c),e.globalCompositeOperation=`lighter`}e.restore()}function lD(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=a(t.foodReserve),s=a(t.waterLitersPerDay),c=a(t.powerKw),l=a(t.pressurizedVolumeM3);if(o==null&&s==null&&c==null&&l==null)return;let u=(e,t,n)=>e<=t?1:e>=n?0:1-(e-t)/(n-t),d=e=>e<.33?`rgba(106, 173, 72, ${.06+e*.1})`:e<.66?`rgba(232, 180, 74, ${.08+(e-.33)*.2})`:`rgba(196, 74, 30, ${.12+(e-.66)*.3})`,f=n/2,p=r/2;e.save(),o!=null&&(e.fillStyle=d(u(o,3,18)),e.fillRect(0,0,f,p)),s!=null&&(e.fillStyle=d(u(s,200,1200)),e.fillRect(f,0,f,p)),c!=null&&(e.fillStyle=d(u(c,150,600)),e.fillRect(0,p,f,p)),l!=null&&(e.fillStyle=d(u(l,1500,4e3)),e.fillRect(f,p,f,p));let m=p+8;e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,o!=null&&e.fillText(`FOOD ${o.toFixed(1)}mo`,8,40),s!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(s)}L/d`,n-8,40)),c!=null&&(e.textAlign=`left`,e.fillText(`POWER ${Math.round(c)}kW`,8,m)),l!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(l)}m³`,n-8,m)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function uD(e,t,n,r,i,a){if(!r||r.size===0)return;let o=.6+.4*Math.sin(i*.004);e.save();for(let i of t){if(!i.alive||!r.has(i.agentId))continue;let t=n.get(i.agentId);t&&(e.strokeStyle=a,e.lineWidth=2,e.globalAlpha=.9,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.stroke(),e.lineWidth=1,e.globalAlpha=.45*o,e.beginPath(),e.arc(t.x,t.y,14+o*3,0,Math.PI*2),e.stroke(),e.globalAlpha=.2*o,e.beginPath(),e.arc(t.x,t.y,20+o*5,0,Math.PI*2),e.stroke())}e.restore()}function dD(e,t){let n=e.trim();if(n.startsWith(`#`)){let e=parseInt(n.slice(1),16);if(n.length===7)return`rgba(${e>>16&255},${e>>8&255},${e&255},${t})`}let r=n.match(/rgba?\(([^)]+)\)/);if(r){let e=r[1].split(`,`).map(e=>e.trim());if(e.length>=3)return`rgba(${e[0]},${e[1]},${e[2]},${t})`}return n}function fD(){return{items:[]}}function pD(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function mD(e){let t=[];for(let n of e.items){let e=n.age+1;e>=n.totalFrames||t.push({...n,age:e,progress:e/n.totalFrames})}e.items=t}function hD(e){return e.items}function gD(e,t){let n=new Map(e.map(e=>[e.agentId,e]));return{born:t.filter(e=>!n.has(e.agentId)&&e.alive&&!((e.age??0)>=18)),died:t.filter(e=>n.get(e.agentId)?.alive===!0&&!e.alive)}}var _D=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function vD(e,t,n,r){let i=(0,b.useRef)(fD()),a=(0,b.useRef)(new Set),[o,s]=(0,b.useState)(0),c=(0,b.useRef)(-1),l=(0,b.useRef)(!0),u=(0,b.useRef)(typeof document<`u`?!document.hidden:!0),d=jy(Fy);return(0,b.useEffect)(()=>{let t=e.snapshot,r=e.previousSnapshot;if(!t||t.turn===c.current||(c.current=t.turn,!r))return;let o=n(),{born:s,died:l}=gD(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&pD(i.current,{kind:`birth`,x:t.x,y:t.y,totalFrames:30,sourceId:e.agentId})}for(let e of l){let t=o.get(e.agentId);t&&pD(i.current,{kind:`death`,x:t.x,y:t.y,totalFrames:60,sourceId:e.agentId})}let u=e.eventCategories??t.eventCategories??[];if(u.length>0){let e=Array.from(o.values());if(e.length>0){let n=e.reduce((e,t)=>e+t.x,0)/e.length,r=e.reduce((e,t)=>e+t.y,0)/e.length;for(let e of u){let o=e.toLowerCase();if(!_D.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),pD(i.current,{kind:`crisis`,x:n,y:r,totalFrames:90}))}}}},[e.snapshot,e.previousSnapshot,e.eventCategories,n]),(0,b.useEffect)(()=>{if(!r)return;let t=r();if(t.size!==0){for(let n of e.forgeAttempts??[]){let e=`forge|${n.turn}|${n.eventIndex}|${n.department}|${n.name}|${n.approved?`a`:`r`}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.department||`unknown`).toLowerCase());r&&pD(i.current,{kind:n.approved?`forge_approved`:`forge_rejected`,x:r.x,y:r.y,totalFrames:n.approved?30:22})}for(let n of e.reuseCalls??[]){let e=`reuse|${n.turn}|${n.originDept}|${n.callingDept}|${n.name}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.originDept||`unknown`).toLowerCase()),o=t.get((n.callingDept||`unknown`).toLowerCase());r&&o&&pD(i.current,{kind:`reuse`,x:r.x,y:r.y,endX:o.x,endY:o.y,totalFrames:40})}}},[e.forgeAttempts,e.reuseCalls,r]),(0,b.useEffect)(()=>{let e=()=>{u.current=!document.hidden};document.addEventListener(`visibilitychange`,e);let n=t.current,r=null;return n&&(r=new IntersectionObserver(e=>{for(let t of e)l.current=t.isIntersecting},{threshold:0}),r.observe(n)),()=>{document.removeEventListener(`visibilitychange`,e),r?.disconnect()}},[t]),(0,b.useEffect)(()=>{if(d){s(e=>e+1);return}let e=0,t=performance.now(),n=r=>{!l.current||!u.current||r-t<33.333333333333336||(t=r,mD(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:hD(i.current),tickClock:o}}function yD(e,t){let n=new Map;for(let r of e){if(!r.alive)continue;let e=t.get(r.agentId);if(!e)continue;let i=(r.department||`unknown`).toLowerCase(),a=n.get(i)??{x:0,y:0,n:0};a.x+=e.x,a.y+=e.y,a.n+=1,n.set(i,a)}let r=new Map;for(let[e,t]of n.entries())r.set(e,{x:t.x/t.n,y:t.y/t.n});return r}var bD={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function xD(e){return bD[(e||``).toLowerCase()]??`#a89878`}function SD({cells:e,size:t=44}){let{slices:n,alive:r}=(0,b.useMemo)(()=>{let t=new Map,n=0;for(let r of e){if(!r.alive)continue;let e=(r.department||`unknown`).toLowerCase();t.set(e,(t.get(e)??0)+1),n+=1}let r=[...t.entries()].sort((e,t)=>t[1]-e[1]),i=[];for(let[e,t]of r)i.push({dept:e,count:t,frac:t/Math.max(1,n),color:xD(e)});return{slices:i,alive:n}},[e]);if(r===0)return(0,x.jsx)(`div`,{style:{width:t,height:t,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`var(--text-4)`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`},"aria-label":`No live members`,children:`—`});let i=t/2,a=i-6,o=i,s=i,c=-Math.PI/2;return(0,x.jsxs)(`svg`,{width:t,height:t,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`Department breakdown: ${n.map(e=>`${e.dept} ${e.count}`).join(`, `)}`,children:[n.map((e,t)=>{let n=e.frac*Math.PI*2,r=c,l=c+n;c=l;let u=o+Math.cos(r)*i,d=s+Math.sin(r)*i,f=o+Math.cos(l)*i,p=s+Math.sin(l)*i,m=o+Math.cos(r)*a,h=s+Math.sin(r)*a,g=o+Math.cos(l)*a,_=s+Math.sin(l)*a,v=+(n>Math.PI),y=[`M ${u.toFixed(2)} ${d.toFixed(2)}`,`A ${i} ${i} 0 ${v} 1 ${f.toFixed(2)} ${p.toFixed(2)}`,`L ${g.toFixed(2)} ${_.toFixed(2)}`,`A ${a} ${a} 0 ${v} 0 ${m.toFixed(2)} ${h.toFixed(2)}`,`Z`].join(` `);return(0,x.jsx)(`path`,{d:y,fill:e.color,opacity:.85,children:(0,x.jsx)(`title`,{children:`${e.dept}: ${e.count} (${Math.round(e.frac*100)}%)`})},`${e.dept}-${t}`)}),(0,x.jsx)(`text`,{x:o,y:s,textAnchor:`middle`,dominantBaseline:`central`,fontSize:10,fontFamily:`ui-monospace, monospace`,fontWeight:800,fill:`var(--text-1)`,children:r})]})}var CD={"tab.living":`Who's alive this turn — agents on the scenario grid.`,"tab.mood":`Aggregate mood mix per leader: hopeful / neutral / anxious / negative.`,"tab.forge":`Computational tools the agents forged in the QuickJS WebAssembly sandbox this turn.`,"tab.ecology":`Resource and environment metrics: power, food, water, radiation.`,"tab.divergence":`Per-metric A-vs-B deltas across all turns.`,"badge.forge":`Forge attempts on this turn — click FORGE for details.`,"badge.divergence":`Metrics diverged this turn — click DIVERGENCE for the rail.`,"stat.morale":`Aggregate morale across all alive agents (0–100%).`,"stat.moodMix":`Distribution of agents across the four mood tiers, weighted by morale.`,"stat.alive":`Living agents in this colony at the current turn.`,"stat.age":`Age distribution of living agents (4 bins: <20 / 20–40 / 40–60 / 60+).`,"stat.paired":`Alive agents currently in a partnership pair.`,"stat.earth":`Agents born on Earth (vs Native — born after the colony's first birth event).`,"stat.native":`Agents born in the colony itself (Marsborn / Lunarborn / scenario-specific).`,"stat.depts":`Agent count by department. Hover a wedge for the dept name.`,"chip.rising":`Aggregate morale trending up vs the previous turn.`},wD={strip:`_strip_1twpk_1`,narrow:`_narrow_1twpk_15`,col:`_col_1twpk_20`,colNarrow:`_colNarrow_1twpk_27`,colPaired:`_colPaired_1twpk_31`,row:`_row_1twpk_35`,rowBaseline:`_rowBaseline_1twpk_40`,label:`_label_1twpk_46`,moraleValue:`_moraleValue_1twpk_51`,bar:`_bar_1twpk_57`,moraleFill:`_moraleFill_1twpk_64`,value2:`_value2_1twpk_71`,valueRust:`_valueRust_1twpk_75`,valueNative:`_valueNative_1twpk_79`,moodHeader:`_moodHeader_1twpk_84`,moodEmpty:`_moodEmpty_1twpk_90`,moodBar:`_moodBar_1twpk_95`,moodSegment:`_moodSegment_1twpk_103`,moodLegend:`_moodLegend_1twpk_109`,ageBars:`_ageBars_1twpk_117`,ageBarCol:`_ageBarCol_1twpk_124`,ageBarFill:`_ageBarFill_1twpk_133`,ageScale:`_ageScale_1twpk_143`,deptBlock:`_deptBlock_1twpk_150`,deptLabel:`_deptLabel_1twpk_158`};function TD({snapshot:e,sideColor:t}){let n=jy(My),r=e.cells.filter(e=>e.alive),i=r.reduce((e,t)=>{let n=t.mood||`neutral`;return e[n]=(e[n]??0)+1,e},{}),a=[`positive`,`hopeful`,`neutral`,`anxious`,`negative`,`defiant`,`resigned`],o={positive:`var(--green)`,hopeful:`#9acd60`,neutral:`var(--text-4)`,anxious:`var(--amber)`,negative:`var(--rust)`,defiant:`#c44a1e`,resigned:`var(--text-3)`},s=r.length||1,c=[0,0,0,0];for(let e of r){let t=e.age??30;t<20?c[0]++:t<40?c[1]++:t<60?c[2]++:c[3]++}let l=Math.max(1,...c),u=r.filter(e=>!!e.partnerId).length,d=r.filter(e=>(e.generation??0)===0).length,f=Math.round(e.morale*100),p=f>=60?`var(--green)`:f>=30?`var(--amber)`:`var(--rust)`,m={"--side-color":t};return(0,x.jsxs)(`div`,{className:[wD.strip,n?wD.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[wD.col,wD.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.rowBaseline,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:wD.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:wD.bar,children:(0,x.jsx)(`div`,{className:wD.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:wD.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsxs)(`div`,{className:wD.moodHeader,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:wD.value2,title:CD[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:wD.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:wD.moodBar,children:a.map(e=>{let t=i[e]||0;if(t===0)return null;let n=t/s*100;return(0,x.jsx)(`div`,{title:`${e}: ${t}`,className:wD.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:wD.moodLegend,children:a.filter(e=>(i[e]||0)>0).map(e=>`${Math.round((i[e]||0)/s*100)}% ${e}`).slice(0,3).join(` · `)})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsx)(`div`,{className:wD.label,title:CD[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:wD.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:wD.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:wD.ageBarFill,style:{"--age-height":`${e/l*100}%`,"--age-min":e>0?`2px`:`0`,"--age-bg":e>0?t:`transparent`}})},n))}),(0,x.jsxs)(`div`,{className:wD.ageScale,children:[(0,x.jsx)(`span`,{children:`<20`}),(0,x.jsx)(`span`,{children:`20`}),(0,x.jsx)(`span`,{children:`40`}),(0,x.jsx)(`span`,{children:`60+`})]})]}),(0,x.jsxs)(`div`,{className:[wD.col,wD.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:wD.value2,children:d})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:wD.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:wD.deptBlock,"aria-label":`Department breakdown`,title:CD[`stat.depts`],children:[(0,x.jsx)(SD,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:wD.deptLabel,children:`Depts`})]})]})}var ED={cols:12,rows:6,seedRadius:2},DD=[[1,0],[2,1],[0,2],[1,2],[2,2]],OD=[[0,1],[1,1],[2,1]],kD=[[0,0],[1,0],[0,1],[1,1]],AD=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],jD=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],MD=[[1,0],[2,0],[0,1],[1,1],[1,2]];function ND(e){switch(e){case`positive`:case`hopeful`:return kD;case`neutral`:return AD;case`anxious`:return OD;case`resigned`:return jD;case`defiant`:case`negative`:return DD;default:return OD}}function PD(e,t,n,r,i,a,o){let s=r/a,c=i/o,l=Math.max(1,Math.min(s,c)-2);e.save(),e.fillStyle=`rgba(106, 173, 72, 0.25)`,e.strokeStyle=`rgba(154, 205, 96, 0.95)`,e.lineWidth=2;for(let u of t){if(!u.alive||(u.generation??0)===0)continue;let t=n.get(u.agentId);if(!t)continue;let d=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(s-l)/2,m=(c-l)/2,h=d*s+p,g=f*c+m;e.fillRect(h,g,l,l),e.strokeRect(h+.5,g+.5,l-1,l-1);let _=h+l/2,v=g+l/2,y=l*.4;e.beginPath(),e.moveTo(_-y,v),e.lineTo(_+y,v),e.moveTo(_,v-y),e.lineTo(_,v+y),e.stroke()}e.restore()}function FD(e,t,n,r,i,a,o,s=`rgba(168, 152, 120, 0.85)`,c=`rgba(168, 152, 120, 0.08)`){let l=r/a,u=i/o,d=Math.max(1,Math.min(l,u)-2);e.save(),e.lineWidth=2,e.strokeStyle=s,e.fillStyle=c;for(let s of t){if(s.alive)continue;let t=n.get(s.agentId);if(!t)continue;let c=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(l-d)/2,m=(u-d)/2,h=c*l+p,g=f*u+m;e.fillRect(h,g,d,d),e.strokeRect(h+.5,g+.5,d-1,d-1),e.beginPath(),e.moveTo(h+4,g+4),e.lineTo(h+d-4,g+d-4),e.moveTo(h+d-4,g+4),e.lineTo(h+4,g+d-4),e.stroke()}e.restore()}function ID(e,t,n,r,i){let{cols:a,rows:o,grid:s}=e,c=Math.floor(t/Math.max(1,r)*a),l=Math.floor(n/Math.max(1,i)*o);return c<0||c>=a||l<0||l>=o?null:s[l*a+c]>0?{col:c,row:l}:null}function LD(e,t,n,r,i){return{col:Math.floor(e.x/Math.max(1,t)*r),row:Math.floor(e.y/Math.max(1,n)*i)}}function RD(e){switch(e){case`birth`:return kD;case`forge`:return DD;case`crisis`:return MD;case`death`:return[];default:return null}}function zD(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function BD(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=RD(a);for(let e=0;e<t.length;e+=1){let a=t[e];if(!a.alive)continue;let u=n.get(a.agentId);if(!u)continue;let d=Math.floor(u.x/Math.max(1,r)*o),f=Math.floor(u.y/Math.max(1,i)*s),p=l??ND(a.mood);for(let[e,t]of p){let n=d+e-1,r=f+t-1;n<0||n>=o||r<0||r>=s||(c[r*o+n]=8)}}}function VD(e,t,n,r){let{cols:i,rows:a,grid:o}=e,s=Math.floor(t.x/Math.max(1,n)*i),c=Math.floor(t.y/Math.max(1,r)*a);if(t.kind===`death`){for(let e=-1;e<=1;e+=1)for(let t=-1;t<=1;t+=1){let n=s+t,r=c+e;n<0||n>=i||r<0||r>=a||(o[r*i+n]=0)}return}let l;switch(t.kind){case`birth`:l=kD;break;case`forge_approved`:l=DD;break;case`forge_rejected`:l=OD;break;case`reuse`:l=jD;break;case`crisis`:l=MD;break;default:l=OD}for(let[e,t]of l){let n=s+e-1,r=c+t-1;n<0||n>=i||r<0||r>=a||(o[r*i+n]=8)}}function HD(e){let{cols:t,rows:n,grid:r,next:i}=e;i.fill(0);for(let e=0;e<n;e++)for(let a=0;a<t;a++){let o=0;for(let i=-1;i<=1;i++)for(let s=-1;s<=1;s++){if(s===0&&i===0)continue;let c=a+s,l=e+i;c<0||c>=t||l<0||l>=n||r[l*t+c]>0&&(o+=1)}let s=r[e*t+a],c=s>0;c&&o===2||o===3?i[e*t+a]=c?Math.max(4,s):8:c&&s>1&&(i[e*t+a]=Math.max(0,s-2))}r.set(i),e.frame+=1}function UD(e,t,n,r,i,a=1){let{cols:o,rows:s,grid:c}=t;if(a<=0)return;let l=n/o,u=r/s,d=Math.max(1,Math.min(l,u)-2),f=(l-d)/2,p=(u-d)/2;e.save();for(let t=0;t<s;t++)for(let n=0;n<o;n++){let r=c[t*o+n];if(r===0)continue;let s=Math.min(1,r/8*.9*a);e.fillStyle=i,e.globalAlpha=s,e.fillRect(n*l+f,t*u+p,d,d)}e.restore()}function WD(e,t){return e<0||Math.abs(t-e)>1}function GD(e,t,n,r){return r||n<=0?e:e*(1-(1-Math.max(0,Math.min(1,t/n)))**3)}function KD(e,t,n,r){for(let i=e.length-1;i>=0;i--){let a=e[i];if(!a.alive)continue;let o=t.get(a.agentId);if(!o)continue;let s=(a.featured?5:3)+18,c=n-o.x,l=r-o.y;if(c*c+l*l<=s*s)return a}return null}var qD=[`O`,`C`,`E`,`A`,`Em`,`HH`];function JD(e,t){let n=t/2,r=t/2,i=t/2-8;return qD.map((t,a)=>{let o=Math.PI*2*a/qD.length-Math.PI/2,s=Math.max(0,Math.min(1,e[t])),c=i*s;return`${n+Math.cos(o)*c},${r+Math.sin(o)*c}`}).join(` `)}function YD(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/qD.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function XD({profile:e,colonyMean:t,size:n=160}){let r=JD(e,n),i=t?JD(t,n):null,a=n/2,o=n/2,s=n/2-8;return(0,x.jsxs)(`svg`,{width:n,height:n,role:`img`,"aria-label":`HEXACO profile radar`,children:[[.25,.5,.75,1].map(e=>(0,x.jsx)(`circle`,{cx:a,cy:o,r:s*e,fill:`none`,stroke:`var(--border)`,strokeDasharray:e===1?void 0:`2 3`},e)),qD.map((e,t)=>{let r=YD(e,n,t);return(0,x.jsx)(`text`,{x:r.x,y:r.y,fontSize:`9`,fontFamily:`var(--mono)`,fill:`var(--text-3)`,textAnchor:`middle`,dominantBaseline:`middle`,children:r.label},e)}),i&&(0,x.jsx)(`polygon`,{points:i,fill:`none`,stroke:`var(--text-3)`,strokeWidth:`1`,strokeDasharray:`3 3`}),(0,x.jsx)(`polygon`,{points:r,fill:`color-mix(in srgb, var(--amber) 25%, transparent)`,stroke:`var(--amber)`,strokeWidth:`1.5`})]})}var ZD={backdrop:`_backdrop_gccy2_1`,popover:`_popover_gccy2_8`,headerRow:`_headerRow_gccy2_25`,headerName:`_headerName_gccy2_34`,headerSubline:`_headerSubline_gccy2_42`,featuredPill:`_featuredPill_gccy2_49`,closeBtn:`_closeBtn_gccy2_59`,section:`_section_gccy2_72`,sectionLast:`_sectionLast_gccy2_77`,statsGrid:`_statsGrid_gccy2_81`,statKey:`_statKey_gccy2_88`,statValue:`_statValue_gccy2_92`,statValueUpper:`_statValueUpper_gccy2_96`,sectionLabel:`_sectionLabel_gccy2_101`,hexacoRow:`_hexacoRow_gccy2_110`,hexacoRadarWrap:`_hexacoRadarWrap_gccy2_116`,hexacoTopAxes:`_hexacoTopAxes_gccy2_120`,memoryList:`_memoryList_gccy2_126`,memoryItem:`_memoryItem_gccy2_132`,chatBtn:`_chatBtn_gccy2_143`},QD={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function $D(e){if(!e)return``;let t=Object.entries(e);return t.sort((e,t)=>t[1]-e[1]),t.slice(0,2).map(([e,t])=>`${QD[e]} ${t.toFixed(2)}`).join(` · `)}function eO(e){let{payload:t,containerW:n,containerH:r,sideColor:i,hexacoById:a,snapshots:o,onClose:s,onOpenChat:c}=e,l=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,s]);let u=(0,b.useMemo)(()=>{if(t&&a)return a.get(t.cell.agentId)??a.get(t.cell.name)},[t,a]),d=(0,b.useMemo)(()=>{if(!t)return[];let e=[...t.cell.shortTermMemory??[]];if(o)for(let n=o.length-1;n>=0&&e.length<3;n--){let r=o[n].cells.find(e=>e.agentId===t.cell.agentId);if(r){for(let t of r.shortTermMemory??[])if(t&&!e.includes(t)&&e.push(t),e.length>=3)break}}return e.slice(0,3)},[t,o]),f=jy(Ny);if(!t)return null;let p=f?Math.min(320,n-16):320,m=Math.min(360,r-20),h=f?Math.max(8,(n-p)/2):t.x+p+10>n?Math.max(10,t.x-p-10):Math.min(n-p-10,t.x+10),g=f?Math.max(8,(r-m)/2):t.y-m-10<0?Math.min(r-m-10,t.y+10):Math.max(10,t.y-m-10),_=t.cell,v=typeof _.psychScore==`number`?Math.round(_.psychScore*100):null,y=(()=>{let e=_.generation??0;return e===0?`Earth-born`:e===1?`First-native`:`Gen ${e}`})(),S=Math.max(120,r-g-10),C={"--side-color":i,"--pop-left":`${h}px`,"--pop-top":`${g}px`,"--pop-width":`${p}px`,"--pop-max-height":`${S}px`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:s,className:ZD.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:ZD.popover,style:C,children:[(0,x.jsxs)(`div`,{className:ZD.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:ZD.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:ZD.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:ZD.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:ZD.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:ZD.section,children:(0,x.jsxs)(`div`,{className:ZD.statsGrid,children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:ZD.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:ZD.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:y}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:ZD.hexacoRow,children:[(0,x.jsx)(`div`,{className:ZD.hexacoRadarWrap,children:(0,x.jsx)(XD,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:ZD.hexacoTopAxes,children:$D(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:ZD.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:ZD.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:ZD.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:ZD.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var tO={backdrop:`_backdrop_18xl4_1`,drawer:`_drawer_18xl4_8`,header:`_header_18xl4_25`,closeBtn:`_closeBtn_18xl4_32`,row:`_row_18xl4_45`,rowLabel:`_rowLabel_18xl4_53`,pillRow:`_pillRow_18xl4_58`,pill:`_pill_18xl4_58`,pillActive:`_pillActive_18xl4_76`,resetBtn:`_resetBtn_18xl4_81`},nO={deptLabels:!1,crosshair:!0,alerts:!0,sound:!1};function rO(e){let t={...nO};for(let n of Object.keys(nO))typeof e[n]==`boolean`&&(t[n]=e[n]);return t}function iO({open:e,settings:t,onChange:n,onClose:r}){let i=Pt(e);if((0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),!e)return null;let a=(e,r)=>{n({...t,[e]:r})};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:r,className:tO.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:tO.drawer,children:[(0,x.jsxs)(`div`,{className:tO.header,children:[(0,x.jsx)(`span`,{style:Pw,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:tO.closeBtn,children:`×`})]}),(0,x.jsxs)(aO,{label:`Dept labels`,children:[(0,x.jsx)(oO,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Crosshair`,children:[(0,x.jsx)(oO,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Alert toasts`,children:[(0,x.jsx)(oO,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Sound cues`,children:[(0,x.jsx)(oO,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(nO),style:Fw,className:tO.resetBtn,children:`Reset defaults`})]})]})}function aO({label:e,children:t}){return(0,x.jsxs)(`div`,{className:tO.row,children:[(0,x.jsx)(`span`,{style:Nw,className:tO.rowLabel,children:e}),(0,x.jsx)(`div`,{className:tO.pillRow,children:t})]})}function oO({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[tO.pill,e?tO.pillActive:``].filter(Boolean).join(` `),children:n})}var sO={drawer:`_drawer_tksc5_1`,header:`_header_tksc5_17`,headerLabel:`_headerLabel_tksc5_26`,closeBtn:`_closeBtn_tksc5_34`,sortRow:`_sortRow_tksc5_47`,sortChip:`_sortChip_tksc5_54`,active:`_active_tksc5_69`,body:`_body_tksc5_74`,empty:`_empty_tksc5_80`,deptHeader:`_deptHeader_tksc5_86`,row:`_row_tksc5_95`,deceased:`_deceased_tksc5_115`,swatch:`_swatch_tksc5_119`,rowName:`_rowName_tksc5_128`,featuredPill:`_featuredPill_tksc5_135`,deceasedToggle:`_deceasedToggle_tksc5_144`},cO={positive:`rgba(106, 173, 72, 1)`,hopeful:`rgba(154, 205, 96, 1)`,neutral:`rgba(107, 95, 80, 1)`,anxious:`rgba(232, 180, 74, 1)`,negative:`rgba(224, 101, 48, 1)`,defiant:`rgba(196, 74, 30, 1)`,resigned:`rgba(168, 152, 120, 1)`},lO=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function uO({open:e,cells:t,actorName:n,sideColor:r,searchQuery:i,hoveredId:a,onHover:o,onSelect:s,onClose:c}){let[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(`dept`),p=Lm(),{alive:m,deceased:h,matchSet:g}=(0,b.useMemo)(()=>{let e=[],n=[];for(let r of t)r.alive?e.push(r):n.push(r);d===`dept`?e.sort((e,t)=>e.department.localeCompare(t.department)||e.name.localeCompare(t.name)):d===`name`?e.sort((e,t)=>e.name.localeCompare(t.name)):d===`psych`?e.sort((e,t)=>(t.psychScore??0)-(e.psychScore??0)):d===`age`&&e.sort((e,t)=>(t.age??0)-(e.age??0)),n.sort((e,t)=>e.name.localeCompare(t.name));let r=i.trim().toLowerCase().split(/\s+/).filter(Boolean),a=new Set;if(r.length>0)for(let e of t){let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();r.every(e=>t.includes(e))&&a.add(e.agentId)}return{alive:e,deceased:n,matchSet:a}},[t,i,d]),_=(0,b.useMemo)(()=>{if(d!==`dept`)return[[`__flat__`,m]];let e=new Map;for(let t of m){let n=(t.department||`unknown`).toLowerCase(),r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))},[m,d]);if(!e)return null;let v={"--side-color":r},y=(e,t,n)=>({"--row-color":t?`var(--text-4)`:`var(--text-2)`,"--row-bg":n?`var(--bg-card)`:e?`color-mix(in srgb, ${r} 13%, transparent)`:`transparent`,"--row-border":e?r:`transparent`,"--row-opacity":t?`0.55`:`1`});return(0,x.jsxs)(`div`,{className:sO.drawer,children:[(0,x.jsxs)(`div`,{className:sO.header,style:v,children:[(0,x.jsxs)(`span`,{className:sO.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:sO.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:sO.sortRow,children:lO.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[sO.sortChip,t?sO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:sO.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:sO.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:sO.deptHeader,children:[e,` · `,t.length]}),t.map(e=>{let t=g.has(e.agentId),n=a===e.agentId,r=i.trim().length>0&&!t;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · ${e.mood}`,className:sO.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":cO[e.mood]??cO.neutral}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:sO.featuredPill,style:v,children:`★`})]},e.agentId)})]},e)),h.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:sO.deceasedToggle,children:[l?`▼`:`▶`,` Deceased · `,h.length]}),l&&h.map(e=>{let t=a===e.agentId;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · deceased`,className:[sO.row,sO.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name})]},e.agentId)})]})]})]})}function dO({snapshot:e,previousSnapshot:t,sideColor:n,onSelect:r}){let[i,a]=(0,b.useState)([]),o=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{if(!e)return;let n=e.cells.filter(e=>e.alive&&e.featured),r=t?new Set(t.cells.filter(e=>e.alive&&e.featured).map(e=>e.agentId)):o.current,i=n.filter(e=>!r.has(e.agentId));if(o.current=new Set(n.map(e=>e.agentId)),i.length===0)return;let s=performance.now()+6e3;a(i.slice(0,2).map(t=>({cell:t,turn:e.turn,expiresAt:s})))},[e,t]),(0,b.useEffect)(()=>{if(i.length===0)return;let e=Math.max(0,i[0].expiresAt-performance.now()),t=setTimeout(()=>a([]),e);return()=>clearTimeout(t)},[i]);let s=(0,b.useMemo)(()=>i,[i]);return s.length===0?null:(0,x.jsx)(`div`,{"aria-live":`polite`,style:{position:`absolute`,bottom:12,right:12,display:`flex`,flexDirection:`column`,gap:4,pointerEvents:`none`,zIndex:7,maxWidth:240},children:s.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>r?.(e.cell),"aria-label":`Spotlight: ${e.cell.name} · ${e.cell.department}`,title:`${e.cell.name} · ${e.cell.role} · ${e.cell.department} · mood: ${e.cell.mood}`,style:{pointerEvents:`auto`,display:`flex`,alignItems:`center`,gap:6,padding:`4px 10px`,background:`var(--bg-panel)`,border:`1px solid ${n}66`,borderLeft:`3px solid ${n}`,borderRadius:3,fontFamily:`var(--mono)`,fontSize:`var(--font-xs)`,color:`var(--text-2)`,textAlign:`left`,cursor:`pointer`,boxShadow:`0 4px 14px rgba(0, 0, 0, 0.4)`,animation:`paracosm-spotlight-in 380ms ease-out`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`,maxWidth:`100%`},children:[(0,x.jsx)(`span`,{style:{color:n,fontSize:`var(--font-2xs)`,flexShrink:0},"aria-hidden":`true`,children:`★`}),(0,x.jsx)(`span`,{style:{color:`var(--text-1)`,fontWeight:700,overflow:`hidden`,textOverflow:`ellipsis`},children:e.cell.name}),(0,x.jsx)(`span`,{style:{color:`var(--text-3)`,fontSize:`var(--font-2xs)`,flexShrink:0,textTransform:`uppercase`,letterSpacing:`0.04em`},children:e.cell.department})]},e.cell.agentId))})}function fO(e){let t=[];return typeof e.foodReserve==`number`&&t.push(`food reserve ${e.foodReserve.toFixed(1)} months`),typeof e.waterLitersPerDay==`number`&&t.push(`water ${Math.round(e.waterLitersPerDay)} litres a day`),typeof e.powerKw==`number`&&t.push(`power ${Math.round(e.powerKw)} kW`),typeof e.pressurizedVolumeM3==`number`&&t.push(`pressurized volume ${Math.round(e.pressurizedVolumeM3)} cubic metres`),t.map(e=>`, ${e}`).join(``)}function pO(e,t){if(e.startsWith(`var(`)&&t){let n=e.slice(4,-1).trim(),r=getComputedStyle(t).getPropertyValue(n).trim();if(r)return r}return e}function mO(e){let{snapshot:t,previousSnapshot:n,snapshotHistory:r,actorName:i,actorArchetype:a,startTime:o,sideColor:s,side:c,lagTurns:l,clusterMode:u=`departments`,initialPopulation:d=20,mode:f,hexacoById:p,leaderHexaco:m,forgeAttempts:h,reuseCalls:g,divergedIds:_,siblingHoveredId:v,onHoverChange:y,searchQuery:S=``,palette:C=0,settings:w=nO,focusedSide:T=null,onToggleFocus:E,onOpenChat:D,eventFilter:O=`all`,chronicleHover:k=null}=e,A=T===c,j=jy(My),ee=jy(Fy),te=Lm(),M=(0,b.useRef)(null),N=(0,b.useRef)(null),ne=(0,b.useRef)(null),[P,re]=(0,b.useState)({w:0,h:0}),[ie,F]=(0,b.useState)(null),[I,ae]=(0,b.useState)(null),[oe,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(!1),[L,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(ee){fe(!0);return}let e=requestAnimationFrame(()=>fe(!0));return()=>cancelAnimationFrame(e)},[ee]);let R=(0,b.useRef)(zD(ED.cols,ED.rows)),z=(0,b.useRef)(-1),pe=(0,b.useRef)(``),me=(0,b.useRef)(``),he=(0,b.useRef)(null),ge=(0,b.useRef)(null),_e=(0,b.useRef)(-1/0),B=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=N.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(0,Math.round(t.contentRect.width)),n=Math.max(0,Math.round(t.contentRect.height));re(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ne.current;if(!e||P.w===0||P.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(P.w*t),e.height=Math.round(P.h*t),e.style.width=`${P.w}px`,e.style.height=`${P.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[P.w,P.h]);let ve=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),ye=(0,b.useMemo)(()=>!t||P.w===0?new Map:eD(t.cells,ve,P.w,P.h),[t,ve,P.w,P.h]),be=(0,b.useMemo)(()=>t?yD(t.cells,ye):new Map,[t,ye]),xe=vD({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},N,()=>ye,()=>be),Se=f===`forge`?.7:f===`ecology`?0:1,Ce=(0,b.useMemo)(()=>{if(f!==`mood`||!t)return s;let e=t.cells.filter(e=>e.alive);if(e.length===0)return s;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=`neutral`,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);switch(r){case`positive`:case`hopeful`:return`var(--green)`;case`anxious`:return`var(--amber)`;case`negative`:case`defiant`:return`var(--rust)`;case`resigned`:return`var(--text-3)`;default:return s}},[f,t,s]);(0,b.useEffect)(()=>{let e=ne.current;if(!e||!t||P.w===0||P.h===0)return;let r=e.getContext(`2d`);if(!r)return;let c=xe.flares.filter(e=>O===`all`?!0:O===`birth`?e.kind===`birth`:O===`death`?e.kind===`death`:O===`crisis`?e.kind===`crisis`:O!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=pO(s,M.current),d=M.current?getComputedStyle(M.current):null,p=(e,t)=>{if(!e.startsWith(`#`)||e.length!==7)return null;let n=parseInt(e.slice(1),16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${t})`},m=d&&p(d.getPropertyValue(`--bg-deep`).trim(),.85)||`rgba(10, 8, 6, 0.85)`,g=d&&p(d.getPropertyValue(`--text-2`).trim(),.8)||`rgba(216, 204, 176, 0.75)`,y=d&&p(d.getPropertyValue(`--text-2`).trim(),.22)||`rgba(216, 204, 176, 0.22)`,b=d&&p(d.getPropertyValue(`--text-2`).trim(),.7)||`rgba(216, 204, 176, 0.7)`,x=d&&p(d.getPropertyValue(`--text-2`).trim(),.95)||`rgba(216, 204, 176, 0.95)`,C=d&&p(d.getPropertyValue(`--text-3`).trim(),.85)||`rgba(168, 152, 120, 0.85)`,T=d&&p(d.getPropertyValue(`--text-3`).trim(),.08)||`rgba(168, 152, 120, 0.08)`,E=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,P.w,P.h);let D=R.current,k=f!==pe.current,A=t.turn!==z.current,j=O!==me.current,N=i!==he.current,re=z.current;if(A||k||j||N){z.current=t.turn,pe.current=f,me.current=O,he.current=i,BD(D,t.cells,ye,P.w,P.h,O);let e;e=ee?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)HD(D);!ee&&(A&&WD(re,t.turn)||N)&&(_e.current=performance.now()),ge.current=c.length?`${c[0].kind}|${c[0].x}|${c[0].y}`:null}else if(c.length>0){let e=`${c[0].kind}|${c[0].x}|${c[0].y}`;e!==ge.current&&(ge.current=e,VD(D,c[0],P.w,P.h),ee||HD(D))}let F=GD(typeof document<`u`&&document.documentElement.classList.contains(`light`)?.22:.65,performance.now()-_e.current,500,ee);if(UD(r,D,P.w,P.h,u,F),O===`death`?FD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows,C,T):O===`birth`&&PD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows),iD(r,c),f!==`ecology`&&tD(r,t.cells,ye,u,Se,_,f===`divergence`,ee?0:performance.now(),S,!0,g,m),f===`forge`&&h&&h.length>0&&cD(r,t.cells,ye,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&lD(r,t,P.w,P.h,E),f===`divergence`&&uD(r,t.cells,ye,_,ee?0:performance.now(),u),sD(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:P.w,height:P.h,lagTurns:l,cells:t.cells,positions:ye,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:te.Time}),ie){let e=ye.get(ie.cell.agentId);e&&(r.save(),r.strokeStyle=u,r.lineWidth=2,r.globalAlpha=1,r.beginPath(),r.arc(e.x,e.y,10,0,Math.PI*2),r.stroke(),r.restore())}if(I&&!ie&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,I.y),r.lineTo(P.w,I.y),r.moveTo(I.x,0),r.lineTo(I.x,P.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=ye.get(n.agentId);if(!t)continue;let r=t.x-I.x,i=t.y-I.y,a=r*r+i*i;a>1600||(!e||a<e.d2)&&(e={id:n.agentId,name:n.name,dx:r,dy:i,d2:a})}e&&(r.save(),r.strokeStyle=b,r.setLineDash([2,3]),r.lineWidth=.6,r.beginPath(),r.moveTo(I.x,I.y),r.lineTo(I.x+e.dx,I.y+e.dy),r.stroke(),r.setLineDash([]),r.fillStyle=x,r.font=`bold 11px ui-monospace, monospace`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`\u2192 ${e.name.split(` `)[0]}`,I.x+6,I.y+6),r.restore())}if(v&&v!==ie?.cell.agentId){let e=ye.get(v);e&&(r.save(),r.strokeStyle=`rgba(232, 180, 74, 0.75)`,r.lineWidth=1.4,r.globalAlpha=.85,r.setLineDash([3,3]),r.beginPath(),r.arc(e.x,e.y,11,0,Math.PI*2),r.stroke(),r.setLineDash([]),r.restore())}},[xe.tickClock,t,ye,P.w,P.h,s,i,l,xe.flares,f,Se,ie,_,v,ee,S,I,w,a,o,h,O]);let we=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;ae({x:r,y:i});let a=KD(t.cells,ye,r,i);if(a){F(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ue(null),y?.(a.agentId);return}ie&&(F(null),y?.(null));let o=ED.cols,s=ED.rows,c=O===`death`||O===`birth`?(()=>{let e=Math.floor(r/Math.max(1,P.w)*o),n=Math.floor(i/Math.max(1,P.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(O===`death`&&r.alive||O===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:O===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=ID(R.current,r,i,P.w,P.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s),c=(i.col-e.col)**2+(i.row-e.row)**2;c<a&&(a=c,n=r)}return{col:e.col,row:e.row,kind:`life`,nearest:n}})();c?ue({x:r,y:i,...c}):L&&ue(null)},[t,ye,ie,y,O,P.w,P.h,L]),Te=(0,b.useCallback)(()=>{F(null),ue(null),ae(null),y?.(null)},[y]),Ee=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=KD(t.cells,ye,r,i);a?(se({cell:a,x:r,y:i}),F(null),ue(null),B.current={id:a.agentId,intensity:1}):L?.nearest&&(se({cell:L.nearest,x:r,y:i}),F(null),ue(null))},[t,ye,L]),De=(0,b.useRef)(null),Oe=(0,b.useCallback)(e=>{if(!t)return;let n=e.touches[0];if(!n)return;let r=e.currentTarget.getBoundingClientRect(),i=n.clientX-r.left,a=n.clientY-r.top,o=KD(t.cells,ye,i,a);o?De.current===o.agentId?(se({cell:o,x:i,y:a}),F(null),De.current=null,B.current={id:o.agentId,intensity:1}):(F({cell:o,x:i,y:a}),ae({x:i,y:a}),De.current=o.agentId,y?.(o.agentId)):(F(null),ae(null),De.current=null,y?.(null))},[t,ye,y]);(0,b.useEffect)(()=>{oe&&t&&(t.cells.find(e=>e.agentId===oe.cell.agentId)||se(null))},[oe,t]),(0,b.useEffect)(()=>{oe||(De.current=null)},[oe]);let ke=pO(f===`mood`?Ce:s,M.current),Ae={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},je={birth:`rgba(154, 205, 96, 0.55)`,death:`rgba(200, 95, 80, 0.55)`,forge:`rgba(232, 180, 74, 0.55)`,crisis:`rgba(196, 74, 30, 0.55)`},Me=k&&k.side===c?Ae[k.kind]:t?t.morale>=.6?`rgba(106, 173, 72, 0.55)`:t.morale>=.3?`rgba(232, 180, 74, 0.55)`:`rgba(196, 74, 30, 0.65)`:`${s}33`,Ne=k&&k.side===c?`0 0 24px ${je[k.kind]}`:t?t.morale>=.6?`0 0 16px rgba(106, 173, 72, 0.18)`:t.morale>=.3?`0 0 16px rgba(232, 180, 74, 0.12)`:`0 0 20px rgba(196, 74, 30, 0.25)`:`none`;return(0,x.jsxs)(`div`,{ref:M,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${te.place} viz`,className:[WE.region,j?WE.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(TD,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:N,className:WE.canvasWrap,style:{"--tint-color":ke,"--wrap-border":Me,"--wrap-glow":Ne},children:[(0,x.jsx)(`canvas`,{ref:ne,role:`img`,"aria-label":t?`${i} ${te.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${fO(t)}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${te.person} glyph for drilldown.`:`${i} ${te.place} — waiting for first turn.`,onMouseMove:we,onMouseLeave:Te,onClick:Ee,onTouchStart:Oe,className:WE.canvas,style:{"--canvas-cursor":ie?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:WE.revealCover,style:{"--reveal-opacity":de?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>le(e=>!e),"aria-label":ce?`Close roster`:`Open roster`,title:ce?`Close roster`:`Open roster`,className:WE.cornerBtn,style:{"--right-offset":E?`36px`:`8px`,"--btn-color":ce?`var(--amber)`:`var(--text-3)`,"--btn-border":ce?`var(--amber)`:`var(--border)`},children:`☰`}),E&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>E(c),"aria-label":A?`Restore split view`:`Focus this panel`,title:A?`Restore split view`:`Focus this panel`,className:`${WE.cornerBtn} ${WE.focusBtn}`,style:{"--btn-color":A?`var(--amber)`:`var(--text-3)`,"--btn-border":A?`var(--amber)`:`var(--border)`},children:A?`⤡`:`⤢`}),(0,x.jsx)(dO,{snapshot:t,previousSnapshot:n,sideColor:pO(s,M.current),onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(uO,{open:ce,cells:t?.cells??[],actorName:i,sideColor:pO(s,M.current),searchQuery:S,hoveredId:ie?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?ye.get(e):null;if(n&&r){F({cell:n,x:r.x,y:r.y}),y?.(e);return}}F(null),y?.(null)},onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})},onClose:()=>le(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:WE.divergenceEmpty,children:(0,x.jsx)(`div`,{className:WE.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),L&&!ie&&!oe&&(()=>{let e=Math.min(Math.max(8,L.x+12),Math.max(8,P.w-220-8)),t=Math.max(8,L.y-84),n=L.kind===`birth`?`+ BIRTH MARKER`:L.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=L.kind===`birth`?`rgba(154, 205, 96, 0.95)`:L.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:WE.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:WE.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:WE.tileCoords,children:[`tile (`,L.col,`, `,L.row,`)`]}),L.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:WE.tileNearestName,children:L.nearest.name}),(0,x.jsxs)(`div`,{className:WE.tileNearestRole,children:[L.nearest.role,` · `,L.nearest.department.toUpperCase()]}),L.kind===`death`?(0,x.jsxs)(`div`,{className:WE.tileNearestDeath,children:[`deceased · mood at death: `,L.nearest.mood]}):L.kind===`birth`?(0,x.jsxs)(`div`,{className:WE.tileNearestBirth,children:[`native-born · generation `,L.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,L.nearest.mood]})]}):(0,x.jsx)(`div`,{className:WE.tileAmbient,children:`ambient CA cell`}),L.kind===`life`&&(()=>{let e=R.current,t=e.cols,n=e.rows,r=e.grid[L.row*t+L.col]??0,i=0;for(let r=-1;r<=1;r++)for(let a=-1;a<=1;a++){if(r===0&&a===0)continue;let o=L.row+r,s=L.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),ie&&!oe&&(()=>{let e=Math.min(Math.max(8,ie.x+12),Math.max(8,P.w-200-8)),t=Math.min(Math.max(8,ie.y-80-8),Math.max(8,P.h-80-8));return(0,x.jsxs)(`div`,{className:WE.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:WE.hoverHeader,children:[ie.cell.name,ie.cell.featured&&(0,x.jsx)(`span`,{className:WE.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:WE.hoverRole,children:[ie.cell.department.toUpperCase(),` · `,ie.cell.role,typeof ie.cell.age==`number`?` · age ${ie.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:WE.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:WE.hoverMoodValue,children:ie.cell.mood}),typeof ie.cell.psychScore==`number`?` · psych ${Math.round(ie.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===ie.cell.agentId);n&&typeof n.psychScore==`number`&&e.push(Math.max(0,Math.min(1,n.psychScore)))}if(e.length<2)return null;let t=136/Math.max(1,e.length-1),n=e.map((e,n)=>{let r=2+n*t,i=2+(1-e)*16;return`${n===0?`M`:`L`}${r.toFixed(1)},${i.toFixed(1)}`}).join(` `);return(0,x.jsxs)(`div`,{className:WE.psychBlock,children:[(0,x.jsx)(`div`,{className:WE.psychLabel,children:`PSYCH TRAJECTORY`}),(0,x.jsxs)(`svg`,{viewBox:`0 0 140 20`,preserveAspectRatio:`none`,width:140,height:20,role:`img`,"aria-label":`Psychological trajectory across ${e.length} turns`,className:WE.psychSvg,children:[(0,x.jsx)(`line`,{x1:2,x2:138,y1:10,y2:10,stroke:`var(--border)`,strokeWidth:.4,strokeDasharray:`2 2`}),(0,x.jsx)(`path`,{d:n,fill:`none`,stroke:s,strokeWidth:1}),(0,x.jsx)(`circle`,{cx:2+(e.length-1)*t,cy:2+(1-e[e.length-1])*16,r:1.6,fill:s})]})]})})(),(0,x.jsx)(`div`,{className:WE.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(eO,{payload:oe,containerW:P.w,containerH:P.h,sideColor:pO(s,M.current),hexacoById:p,snapshots:r,onClose:()=>se(null),onOpenChat:D})]})]})}var hO={track:`_track_1u01e_1`,trackInner:`_trackInner_1u01e_29`,column:`_column_1u01e_38`,columnHeader:`_columnHeader_1u01e_64`,columnHeaderSlot:`_columnHeaderSlot_1u01e_80`,columnHeaderText:`_columnHeaderText_1u01e_89`,columnHeaderName:`_columnHeaderName_1u01e_96`,columnHeaderArchetype:`_columnHeaderArchetype_1u01e_105`,columnHeaderPop:`_columnHeaderPop_1u01e_116`,columnBody:`_columnBody_1u01e_125`,columnPlaceholder:`_columnPlaceholder_1u01e_133`,columnPlaceholderShimmer:`_columnPlaceholderShimmer_1u01e_145`,"cohort-shimmer":`_cohort-shimmer_1u01e_1`,columnPlaceholderLabel:`_columnPlaceholderLabel_1u01e_159`};function gO(e){let t=[],n=[],r=new Map;for(let i of e){if(i.type===`forge_attempt`){let e=i.data||{},n=e.approved===!0||e.approved===`true`;t.push({turn:Number(e.turn??0),eventIndex:Number(e.eventIndex??0),department:String(e.department||``),name:String(e.name||``),approved:n,confidence:typeof e.confidence==`number`?e.confidence:void 0}),e.name&&e.department&&n&&!r.has(String(e.name))&&r.set(String(e.name),String(e.department));continue}if(i.type!==`specialist_done`)continue;let e=i.data||{},a=String(e.department||``),o=Array.isArray(e.forgedTools)?e.forgedTools:[];for(let t of o){let o=t,s=String(o.name||``);if(!s||s===`unnamed`)continue;let c=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):r.get(s),l=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,u=Number(i.turn??e.turn??0);(c&&l!==void 0&&l<u||c&&c!==a)&&n.push({turn:u,originDept:c,callingDept:a,name:s})}}return{attempts:t,reuses:n}}function _O(e){let{actorIndex:t,actorId:n,state:r,snaps:i,currentTurn:a,gridMode:o,palette:s,gridSettings:c,hexacoById:l,searchQuery:u,chronicleFilter:d,chronicleHover:f,startTime:p,onOpenChat:m}=e,h=(0,b.useRef)(null),[g,_]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(g)return;let e=h.current;if(!e)return;if(typeof IntersectionObserver>`u`){_(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){_(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[g]);let v=r.actors[n]??null,y=v?.leader??null,S=i[a],C=a>0?i[a-1]:void 0,w=Pe(t),T=y?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>v?gO(v.events):{attempts:[],reuses:[]},[v]),D=y?.hexaco?{O:y.hexaco.O??y.hexaco.openness??.5,C:y.hexaco.C??y.hexaco.conscientiousness??.5,E:y.hexaco.E??y.hexaco.extraversion??.5,A:y.hexaco.A??y.hexaco.agreeableness??.5,Em:y.hexaco.Em??y.hexaco.emotionality??.5,HH:y.hexaco.HH??y.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:h,className:hO.column,style:{"--actor-color":w},"aria-label":`Living swarm grid for actor ${t+1}: ${T}`,children:[(0,x.jsxs)(`header`,{className:hO.columnHeader,children:[(0,x.jsxs)(`span`,{className:hO.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:hO.columnHeaderText,children:[(0,x.jsx)(`span`,{className:hO.columnHeaderName,children:T}),y?.archetype&&(0,x.jsx)(`span`,{className:hO.columnHeaderArchetype,children:y.archetype})]}),(0,x.jsxs)(`span`,{className:hO.columnHeaderPop,title:`Population alive · morale`,children:[S?.population??`—`,` · `,S?Math.round(S.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:hO.columnBody,children:g?(0,x.jsx)(mO,{snapshot:S,previousSnapshot:C,snapshotHistory:i,actorName:T,actorArchetype:y?.archetype??``,leaderUnit:y?.unit??``,sideColor:w,side:`a`,mode:o,hexacoById:l,leaderHexaco:D,forgeAttempts:E.attempts,reuseCalls:E.reuses,searchQuery:u,palette:s,settings:c,startTime:p,onOpenChat:m,eventFilter:d,chronicleHover:f}):(0,x.jsxs)(`div`,{className:hO.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:hO.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:hO.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function vO({state:e,snapshotMap:t,currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d,className:f}){let p=e.actorIds;return(0,x.jsx)(`div`,{className:[hO.track,f].filter(Boolean).join(` `),role:`region`,"aria-label":`Cohort swarm grid: ${p.length} actors`,children:(0,x.jsx)(`div`,{className:hO.trackInner,children:p.map((f,p)=>(0,x.jsx)(_O,{actorId:f,actorIndex:p,state:e,snaps:t[f]??[],currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d},f))})})}function yO(e){let t=(e.decision||``).split(/[.;]/)[0].trim(),n=t.length>80?t.slice(0,77)+`...`:t,r=e.outcome.startsWith(`risky`),i=e.outcome.endsWith(`success`),a=n.length===0?`held position`:r?i?`gambled on`:`took the risk of`:`chose`,o=n.length===0?``:n.replace(/^(select|implement|issue|move|expand|reduce|slow|initiate|start|deliver)\s+/i,``).replace(/\s+$/,``),s=o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`,c=typeof e.dominantDeaths==`number`&&e.dominantDeaths>0&&e.dominantDeaths<e.deaths;return`${s}${e.deaths>0&&e.dominantCause?c?`, ${e.deaths} lost, ${e.dominantDeaths} to ${e.dominantCause}`:`, ${e.deaths} lost to ${e.dominantCause}`:e.deaths>0?`, ${e.deaths} lost`:``}${e.moraleDelta<=-.08?`; morale cracked`:e.moraleDelta>=.08?`; morale steadied`:``}`}var bO={banner:`_banner_gzmtg_1`,headline:`_headline_gzmtg_12`,collapseBtn:`_collapseBtn_gzmtg_20`,turnLabel:`_turnLabel_gzmtg_39`,title:`_title_gzmtg_43`,categoryPill:`_categoryPill_gzmtg_48`,lineA:`_lineA_gzmtg_58`,lineB:`_lineB_gzmtg_62`,line:`_line_gzmtg_58`,lineLabel:`_lineLabel_gzmtg_78`,lineBody:`_lineBody_gzmtg_85`,lineMore:`_lineMore_gzmtg_91`};function xO(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=null,o=0,s=0,c=``,l=``,u=0;for(let n of e.events)if((n.data?.turn??-1)===t+1){if((n.type===`turn_start`||n.type===`event_start`)&&(c=String(n.data?.title??c),l=String(n.data?.category??l),u=Number(n.data?.time??u)),n.type===`outcome`){i=String(n.data?.outcome??i);let e=n.data?._decision;typeof e==`string`&&e.length>0&&(r=e);let t=n.data?.systemDeltas?.morale;typeof t==`number`&&Number.isFinite(t)&&(s+=t)}if(n.type===`turn_done`){let e=n.data?.deathCauses;e&&typeof e==`object`&&(a=e)}n.type===`systems_snapshot`&&(o=Number(n.data?.deaths)||0)}let d=o,f=null,p;if(a){let e=0,t=0;for(let[n,r]of Object.entries(a))typeof r!=`number`||r<=0||(e+=r,r>t&&(t=r,f=n));e>0&&(d=e,p=t)}return{actorName:n,decision:r,outcome:i,deaths:d,dominantCause:f,dominantDeaths:p,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}function SO(e,t){for(let n of e.actorIds){let r=e.actors[n],i=r?xO(r,t)?.eventTitle:``;if(i)return i}return``}var CO=6;function wO({state:e,currentTurn:t,linesTarget:n,cohortGridShown:r=!0}){let i=e.actorIds.length>2,[a,o]=(0,b.useState)(i),s=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?xO(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),c=s.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,l=s.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,u=s.find(e=>e.summary.time)?.summary.time||0;if(!c)return null;let d=s.slice(0,CO),f=s.length-d.length,p=!a,m=s.length>0,h=p?(0,x.jsxs)(x.Fragment,{children:[d.map((e,t)=>(0,x.jsxs)(`div`,{className:s.length<=2?t===0?bO.lineA:bO.lineB:bO.line,children:[(0,x.jsx)(`span`,{className:bO.lineLabel,children:s.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:bO.lineBody,children:[`: `,yO(e.summary)]})]},e.actorId)),f>0&&(0,x.jsxs)(`div`,{className:bO.lineMore,children:[`+`,f,` more `,`·`,` `,r?`see cohort grid ${n?`above`:`below`} for the rest`:`open All ${e.actorIds.length} actors for the rest`]})]}):null;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:bO.banner,children:[(0,x.jsxs)(`div`,{className:bO.headline,children:[(0,x.jsxs)(`span`,{className:bO.turnLabel,children:[`T`,t+1,u?` \u00b7 ${u}`:``]}),(0,x.jsx)(`span`,{className:bO.title,children:c}),l&&(0,x.jsx)(`span`,{className:bO.categoryPill,children:l}),m&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-expanded":!a,"aria-label":a?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:bO.collapseBtn,children:a?`\u25be ${s.length} actors`:`▴ hide`})]}),h&&(n?(0,Ay.createPortal)(h,n):h)]})}var TO={row:`_row_1jwlc_1`,key:`_key_1jwlc_16`,scrub:`_scrub_1jwlc_34`,turn:`_turn_1jwlc_39`,timeShownAbove:`_timeShownAbove_1jwlc_51`,speed:`_speed_1jwlc_56`},EO=[.5,1,2,4];function DO({currentTurn:e,maxTurn:t,time:n,timeInBanner:r=!1,playing:i,speed:a,onTurnChange:o,onPlayPause:s,onStepBack:c,onStepForward:l,onSpeedChange:u}){return(0,x.jsxs)(`div`,{className:TO.row,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:e<=0,"aria-label":`Previous turn`,className:TO.key,children:`<<`}),(0,x.jsx)(`button`,{type:`button`,onClick:s,disabled:t<=1,"aria-label":i?`Pause`:`Play`,className:TO.key,children:i?`■`:`▶`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:e>=t-1,"aria-label":`Next turn`,className:TO.key,children:`>>`}),(0,x.jsx)(`input`,{type:`range`,min:0,max:Math.max(0,t-1),value:e,onChange:e=>o(Number(e.target.value)),className:TO.scrub,"aria-label":`Scrub timeline`,"aria-valuetext":`Turn ${e+1} of ${t}`}),(0,x.jsxs)(`span`,{className:TO.turn,children:[`T`,e+1,`/`,t,n?(0,x.jsx)(`span`,{className:r?TO.timeShownAbove:void 0,children:` \u00b7 ${n}`}):null]}),(0,x.jsx)(`select`,{"aria-label":`Playback speed`,value:a,onChange:e=>u(Number(e.target.value)),className:TO.speed,children:EO.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var OO=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; food, water, power and volume tint a quadrant each`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function kO(e,t){return e.replace(/\{person\}/g,t.person).replace(/\{Person\}/g,t.Person).replace(/\{people\}/g,t.people).replace(/\{People\}/g,t.People)}function AO(e,t){return kO(OO.find(t=>t.key===e)?.hint??``,t)}function jO({mode:e,onChange:t,counts:n,labels:r}){if(jy(`(max-width: 480px)`)){let i=OO.find(t=>t.key===e),a=n?.[e],o=`calc(${`${i?.label??``}${typeof a==`number`&&a>0?` · ${a}`:``}`.length} * (1ch + 0.08em) + 44px)`;return(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:kO(OO.find(t=>t.key===e)?.hint??``,r),style:{flex:`1 1 auto`,width:o,minWidth:o,padding:`8px 10px`,fontSize:16,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,background:`var(--bg-card)`,color:`var(--text-1)`,border:`1px solid var(--border)`,borderRadius:6,cursor:`pointer`,minHeight:44},children:OO.map(e=>{let t=n?.[e.key],r=typeof t==`number`&&t>0?` · ${t}`:``;return(0,x.jsxs)(`option`,{value:e.key,children:[e.label,r]},e.key)})})}return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Grid viz mode`,style:{display:`flex`,gap:0,padding:`4px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:6,overflowX:`auto`,scrollbarWidth:`thin`},children:OO.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=kO(i.hint,r);return(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o,"data-grid-mode":i.key,onClick:()=>t(i.key),title:c,style:{flex:`1 0 auto`,padding:`5px 8px`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.1em`,border:`1px solid var(--border)`,borderLeft:a===0?`1px solid var(--border)`:`none`,borderRadius:a===0?`3px 0 0 3px`:a===OO.length-1?`0 3px 3px 0`:0,background:o?`var(--amber)`:`var(--bg-card)`,color:o?`var(--bg-deep)`:`var(--text-3)`,cursor:`pointer`,textTransform:`uppercase`,transition:`background 120ms, color 120ms`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:4,whiteSpace:`nowrap`},children:[(0,x.jsx)(`span`,{children:i.label}),typeof s==`number`&&s>0&&(0,x.jsx)(`span`,{style:{padding:`0 4px`,borderRadius:2,background:o?`rgba(10, 8, 6, 0.25)`:`var(--bg-deep)`,color:o?`var(--bg-deep)`:`var(--amber)`,fontSize:`var(--font-3xs)`,fontWeight:700,letterSpacing:`0.05em`,minWidth:14,textAlign:`center`},children:s})]},i.key)})})}var MO={backdrop:`_backdrop_bxhar_1`,dialog:`_dialog_bxhar_12`,phone:`_phone_bxhar_26`,header:`_header_bxhar_30`,title:`_title_bxhar_37`,closeBtn:`_closeBtn_bxhar_47`,section:`_section_bxhar_60`,sectionTitle:`_sectionTitle_bxhar_64`,rows:`_rows_bxhar_75`,row:`_row_bxhar_75`,rowKey:`_rowKey_bxhar_89`,rowVal:`_rowVal_bxhar_96`,swatchWrap:`_swatchWrap_bxhar_101`,swatch:`_swatch_bxhar_101`,footer:`_footer_bxhar_117`,kbd:`_kbd_bxhar_123`};function NO({open:e,onClose:t}){let n=jy(Ny),r=Lm();if(!e)return null;let i=[MO.dialog,n?MO.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:MO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:MO.header,children:[(0,x.jsxs)(`h2`,{className:MO.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:MO.closeBtn,children:`×`})]}),(0,x.jsxs)(PO,{title:`Modes`,children:[(0,x.jsx)(FO,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + event flares`}),(0,x.jsx)(FO,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(FO,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(FO,{k:`ECOLOGY`,v:`Hides glyphs; food, water, power and volume tint a quadrant each`}),(0,x.jsx)(FO,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(PO,{title:`Grid elements`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(FO,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(FO,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(FO,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(FO,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(PO,{title:`Event flares`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(PO,{title:`Keyboard`,children:[(0,x.jsx)(FO,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(FO,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(FO,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(FO,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(FO,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(FO,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:MO.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:MO.kbd,children:`?`}),` anytime to reopen.`]})]})})}function PO({title:e,children:t}){return(0,x.jsxs)(`div`,{className:MO.section,children:[(0,x.jsx)(`div`,{className:MO.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:MO.rows,children:t})]})}function FO({k:e,v:t}){return(0,x.jsxs)(`div`,{className:MO.row,children:[(0,x.jsx)(`span`,{className:MO.rowKey,children:e}),(0,x.jsx)(`span`,{className:MO.rowVal,children:t})]})}function IO({color:e}){return(0,x.jsx)(`span`,{className:MO.swatchWrap,children:(0,x.jsx)(`span`,{className:MO.swatch,style:{"--swatch-color":e}})})}var LO={wrap:`_wrap_10kb4_1`,legend:`_legend_10kb4_8`,legendRight:`_legendRight_10kb4_19`,legendA:`_legendA_10kb4_24`,legendB:`_legendB_10kb4_28`,legendKey:`_legendKey_10kb4_32`,svg:`_svg_10kb4_36`,tooltip:`_tooltip_10kb4_44`,tooltipTurn:`_tooltipTurn_10kb4_63`,tooltipRowA:`_tooltipRowA_10kb4_71`,tooltipRowB:`_tooltipRowB_10kb4_78`,tooltipBold:`_tooltipBold_10kb4_85`};function RO({snapsA:e,snapsB:t,currentTurn:n,onJumpToTurn:r,hoveredTurn:i,onHoverTurnChange:a}){let o=Math.max(e.length,t.length);if(o<2)return null;let s=(e,t)=>{if(e.length===0)return``;let n=588/Math.max(1,o-1),r=[],i=!1;return e.forEach((e,a)=>{let o=t(e);if(o===null){i=!1;return}let s=6+a*n,c=3+(1-o)*22;r.push(`${i?`L`:`M`}${s.toFixed(1)},${c.toFixed(1)}`),i=!0}),r.join(` `)},c=e.some(e=>typeof e.foodReserve==`number`),l=t.some(e=>typeof e.foodReserve==`number`),u=c||l,d=[...e,...t].map(e=>e.foodReserve).filter(e=>typeof e==`number`),f=Math.max(18,...d),p=Math.max(1,...e.map(e=>e.population),...t.map(e=>e.population)),m=e=>typeof e.foodReserve==`number`?Math.max(0,Math.min(1,e.foodReserve/f)):null,h=e=>Math.max(0,Math.min(1,e.population/p)),g=e=>Math.max(0,Math.min(1,e.morale)),_=6+n*(588/Math.max(1,o-1)),v=typeof i==`number`?6+i*(588/Math.max(1,o-1)):null,y=(e,t)=>{let n=(e-t.left)/t.width*600,r=Math.round((n-6)/588*(o-1));return Math.max(0,Math.min(o-1,r))};return(0,x.jsxs)(`div`,{className:LO.wrap,children:[(0,x.jsxs)(`div`,{className:LO.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:LO.legendRight,children:[(0,x.jsx)(`span`,{className:LO.legendA,children:`A`}),(0,x.jsx)(`span`,{className:LO.legendB,children:`B`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:LO.legendKey,children:`- - food`})]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 600 28`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Timeline sparkline of morale, population${u?`, and food`:``} across both leaders`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();r(y(e.clientX,t))},onMouseMove:e=>{if(!a)return;let t=e.currentTarget.getBoundingClientRect();a(y(e.clientX,t))},onMouseLeave:()=>{a?.(null)},className:LO.svg,height:28,children:[(0,x.jsx)(`line`,{x1:6,x2:594,y1:14,y2:14,stroke:`var(--border)`,strokeWidth:.5,strokeDasharray:`2 2`}),c&&(0,x.jsx)(`path`,{d:s(e,m),fill:`none`,stroke:`var(--vis)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),l&&(0,x.jsx)(`path`,{d:s(t,m),fill:`none`,stroke:`var(--eng)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),(0,x.jsx)(`path`,{d:s(e,h),fill:`none`,stroke:`var(--vis)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(t,h),fill:`none`,stroke:`var(--eng)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(e,g),fill:`none`,stroke:`var(--vis)`,strokeWidth:1.3}),(0,x.jsx)(`path`,{d:s(t,g),fill:`none`,stroke:`var(--eng)`,strokeWidth:1.3}),v!==null&&i!==n&&(0,x.jsx)(`line`,{x1:v,x2:v,y1:0,y2:28,stroke:`var(--text-3)`,strokeWidth:.75,strokeDasharray:`2 3`,opacity:.7}),(0,x.jsx)(`line`,{x1:_,x2:_,y1:0,y2:28,stroke:`var(--amber)`,strokeWidth:1})]}),typeof i==`number`&&(()=>{let n=e[i],r=t[i];if(!n&&!r)return null;let a=i/Math.max(1,o-1)*100,s={"--hover-left":`calc(${a}% + 8px)`,"--hover-translate":a>75?`translateX(calc(-100% - 16px))`:`none`};return(0,x.jsxs)(`div`,{className:LO.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:LO.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:LO.tooltipRowA,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`A`}),(0,x.jsxs)(`span`,{children:[`pop `,n.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(n.morale*100),`% mor`]}),typeof n.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,n.foodReserve.toFixed(1),`mo`]}),(n.births>0||n.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,n.births,`/-`,n.deaths]})]}),r&&(0,x.jsxs)(`div`,{className:LO.tooltipRowB,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`B`}),(0,x.jsxs)(`span`,{children:[`pop `,r.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(r.morale*100),`% mor`]}),typeof r.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,r.foodReserve.toFixed(1),`mo`]}),(r.births>0||r.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,r.births,`/-`,r.deaths]})]})]})})()]})}var zO={bar:`_bar_r8lgh_1`,barRow:`_barRow_r8lgh_7`,heading:`_heading_r8lgh_12`,filterRow:`_filterRow_r8lgh_22`,filterChip:`_filterChip_r8lgh_28`,active:`_active_r8lgh_43`,dotsRow:`_dotsRow_r8lgh_50`,dot:`_dot_r8lgh_50`,hovered:`_hovered_r8lgh_79`,current:`_current_r8lgh_85`},BO=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],VO={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},HO={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function UO({eventsA:e,eventsB:t,currentTurn:n,onJumpToTurn:r,onHoverTurnChange:i,hoveredTurn:a,onForgeSelect:o,filter:s,onFilterChange:c,onHoverEventChange:l,onJumpToReports:u}){let d=(0,b.useMemo)(()=>{let n=[],r=(e,t)=>{for(let r of e){let e=Number(r.turn??r.data?.turn??0);if(!(e<=0)){if(r.type===`birth`)n.push({turn:e,kind:`birth`,side:t,label:`T${e}: birth (${t.toUpperCase()})`});else if(r.type===`death`){let i=typeof r.data?.name==`string`?r.data.name:``;n.push({turn:e,kind:`death`,side:t,label:`T${e}: ${i?i+` died`:`death`} (${t.toUpperCase()})`})}else if(r.type===`forge_attempt`){let i=typeof r.data?.name==`string`?r.data.name:`tool`,a=r.data?.approved===!0;n.push({turn:e,kind:`forge`,side:t,label:`T${e}: ${a?`forged`:`rejected`} ${i} (${t.toUpperCase()})`,toolName:i,eventId:r.id})}else if(r.type===`event_start`||r.type===`director_crisis`){let i=typeof r.data?.category==`string`?r.data.category:``;i&&[`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`].includes(i)&&n.push({turn:e,kind:`crisis`,side:t,label:`T${e}: ${i} crisis (${t.toUpperCase()})`})}}}};return r(e,`a`),r(t,`b`),n.sort((e,t)=>e.turn-t.turn),n.slice(-60)},[e,t]),[f,p]=(0,b.useState)(`all`),m=s??f,h=e=>{s===void 0&&p(e),c?.(e)},g=(0,b.useMemo)(()=>m===`all`?d:d.filter(e=>e.kind===m),[d,m]);return d.length===0?null:(0,x.jsxs)(yC,{label:`events`,className:zO.bar,rowClassName:zO.barRow,role:`group`,ariaLabel:`Event filter`,children:[(0,x.jsxs)(`span`,{className:zO.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:zO.filterRow,children:BO.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[zO.filterChip,t?zO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:zO.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[zO.dot,c?zO.current:``,d?zO.hovered:``].filter(Boolean).join(` `),p={"--kind-color":VO[e.kind],"--side-shift":e.side===`a`?`-2px`:`2px`};return(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.shiftKey&&u?(t.preventDefault(),u(e.turn)):e.kind===`forge`&&e.toolName&&o&&o(e.toolName,e.side,e.eventId,t.currentTarget)!==!1||r(s)},onMouseEnter:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onMouseLeave:()=>{i?.(null),l?.(null)},onFocus:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onBlur:()=>{i?.(null),l?.(null)},title:`${e.label}${u?` · Shift+click to open in Reports`:``}`,"aria-label":e.label,className:f,style:p,children:HO[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var WO={bar:`_bar_n16b7_1`,row:`_row_n16b7_9`,label:`_label_n16b7_21`,track:`_track_n16b7_26`,fill:`_fill_n16b7_35`,count:`_count_n16b7_42`};function GO(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.type===`turn_done`){let e=Number(r.turn??r.data?.turn??0);if(e>0){t=e;break}}}let n=t+1,r=new Set,i=!1;for(let t of e){let e=Number(t.turn??t.data?.turn??0);if(t.type===`specialist_done`&&e===n){let e=typeof t.data?.department==`string`?t.data.department:``;e&&r.add(e),i=!0}if(t.type===`turn_done`&&e===n)return{inFlightTurn:null,deptsReported:new Set}}return{inFlightTurn:i?n:null,deptsReported:r}}function KO({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>GO(e),[e]),i=(0,b.useMemo)(()=>GO(t),[t]);if(r.inFlightTurn===null&&i.inFlightTurn===null)return null;let a=Math.max(1,n),o=(e,t,n)=>{if(n.inFlightTurn===null)return null;let r=Math.min(100,n.deptsReported.size/a*100);return(0,x.jsxs)(`div`,{className:WO.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:WO.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:WO.track,children:(0,x.jsx)(`div`,{className:WO.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:WO.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:WO.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var qO={bar:`_bar_3c24d_1`,icon:`_icon_3c24d_11`,label:`_label_3c24d_21`,input:`_input_3c24d_29`,dropdown:`_dropdown_3c24d_42`,option:`_option_3c24d_65`,sidePill:`_sidePill_3c24d_86`,optionName:`_optionName_3c24d_96`,optionMeta:`_optionMeta_3c24d_106`,featuredPill:`_featuredPill_3c24d_115`,moreNote:`_moreNote_3c24d_124`,matchCount:`_matchCount_3c24d_132`,clearBtn:`_clearBtn_3c24d_140`};function JO({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Lm();(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&e.key===`/`&&(e.preventDefault(),i.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let l=a&&e.trim().length>0&&n.length>0;return(0,x.jsxs)(`div`,{className:qO.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:qO.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:qO.label,children:`Find`}),(0,x.jsx)(`input`,{ref:i,type:`text`,value:e,onChange:e=>t(e.target.value),onFocus:()=>o(!0),onBlur:()=>setTimeout(()=>o(!1),120),placeholder:`${c.person} name, dept, mood… (space-separate to AND-match; / to focus)`,"aria-label":`Search ${c.people} by name, department, role, or mood`,className:qO.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:qO.dropdown,children:[n.slice(0,10).map((e,t)=>(0,x.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":`false`,onMouseDown:t=>{t.preventDefault(),r?.(e)},className:qO.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:qO.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:qO.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:qO.optionMeta,children:[e.cell.department?.toUpperCase?.()||``,` · `,e.cell.mood,typeof e.cell.age==`number`?` · age ${e.cell.age}`:``]}),e.cell.featured&&(0,x.jsx)(`span`,{className:qO.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:qO.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:qO.matchCount,style:{"--count-color":s>0?`var(--amber)`:`var(--rust)`},children:[s,` match`,s===1?``:`es`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>t(``),"aria-label":`Clear search`,className:qO.clearBtn,children:`clear`})]})]})}function YO(e,t,n,r=.04,i=`sine`){let a=e.currentTime,o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,a),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(r,a+.008),s.gain.exponentialRampToValueAtTime(1e-4,a+n),o.connect(s),s.connect(e.destination),o.start(a),o.stop(a+n+.02)}function XO(e,t){switch(t){case`birth`:YO(e,880,.18,.05,`triangle`),setTimeout(()=>YO(e,1320,.12,.03,`triangle`),70);break;case`death`:YO(e,160,.35,.05,`sine`);break;case`forge`:YO(e,660,.12,.04,`sine`);break;case`crisis`:YO(e,220,.22,.05,`sawtooth`),setTimeout(()=>YO(e,180,.18,.045,`sawtooth`),120)}}function ZO(e){let t=(0,b.useRef)(null),n=(0,b.useRef)(new Set),r=(0,b.useRef)(-1),i=(0,b.useRef)(-1),a=()=>{if(!e.enabled)return null;if(t.current)return t.current;try{let e=window.AudioContext??window.webkitAudioContext;return e?(t.current=new e,t.current):null}catch{return null}};(0,b.useEffect)(()=>{if(!e.enabled)return;let n=()=>{let e=t.current;e&&e.state===`suspended`&&e.resume().catch(()=>{})};return window.addEventListener(`click`,n),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`click`,n),window.removeEventListener(`keydown`,n)}},[e.enabled]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=(e,t,r,i)=>{if(!e||!t||e.turn===i.current)return;i.current=e.turn;let o=a();if(!o)return;let s=gD(t.cells,e.cells),c=0,l=0;for(let t of s.born){let i=`${r}|t${e.turn}|birth|${t.agentId}`;n.current.has(i)||(n.current.add(i),c+=1)}for(let t of s.died){let i=`${r}|t${e.turn}|death|${t.agentId}`;n.current.has(i)||(n.current.add(i),l+=1)}c>0&&XO(o,`birth`),l>0&&setTimeout(()=>XO(o,`death`),c>0?300:0)};t(e.snapshotA,e.prevSnapshotA,`a`,r),t(e.snapshotB,e.prevSnapshotB,`b`,i)},[e.enabled,e.snapshotA,e.prevSnapshotA,e.snapshotB,e.prevSnapshotB]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=a();if(!t)return;let r=(e,r)=>{for(let i of e){if(!i.approved)continue;let e=`${r}|forge|${i.turn}|${i.eventIndex}|${i.name}`;n.current.has(e)||(n.current.add(e),XO(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var QO={backdrop:`_backdrop_nnlpn_1`,dialog:`_dialog_nnlpn_12`,header:`_header_nnlpn_24`,title:`_title_nnlpn_31`,closeBtn:`_closeBtn_nnlpn_41`,sidesRow:`_sidesRow_nnlpn_54`,sideBlock:`_sideBlock_nnlpn_61`,sideName:`_sideName_nnlpn_71`,statsGrid:`_statsGrid_nnlpn_81`,cell:`_cell_nnlpn_87`,cellLabel:`_cellLabel_nnlpn_93`,cellValue:`_cellValue_nnlpn_101`,empty:`_empty_nnlpn_108`,divergenceBox:`_divergenceBox_nnlpn_113`,divergenceLabel:`_divergenceLabel_nnlpn_125`,divergenceCount:`_divergenceCount_nnlpn_132`,divergenceCopy:`_divergenceCopy_nnlpn_138`};function $O(e){if(e.length===0)return null;let t=0,n=0,r=0,i=0,a=0,o=0,s=1/0,c=1/0;for(let l of e)t+=l.births,n+=l.deaths,l.population>r&&(r=l.population),i+=l.morale,typeof l.foodReserve==`number`&&(a+=l.foodReserve,o++,l.foodReserve<c&&(c=l.foodReserve)),l.morale<s&&(s=l.morale);return{turns:e.length,totalBirths:t,totalDeaths:n,peakPop:r,finalPop:e[e.length-1].population,avgMorale:i/e.length,minMorale:s===1/0?0:s,avgFood:o>0?a/o:void 0,minFood:o>0?c:void 0}}function ek(e){let{open:t,onClose:n}=e,r=Lm();(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),n())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]);let i=(0,b.useMemo)(()=>$O(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>$O(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:QO.cell,children:[(0,x.jsx)(`span`,{className:QO.cellLabel,children:e}),(0,x.jsx)(`span`,{className:QO.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:QO.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:QO.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:QO.statsGrid,children:[o(`Turns`,`${n.turns}`),o(`Final pop`,`${n.finalPop}`,t),o(`Peak pop`,`${n.peakPop}`),o(`Total births`,`${n.totalBirths}`,`rgba(106, 173, 72, 0.95)`),o(`Total deaths`,`${n.totalDeaths}`,`rgba(200, 95, 80, 0.95)`),o(`Avg morale`,`${Math.round(n.avgMorale*100)}%`),o(`Min morale`,`${Math.round(n.minMorale*100)}%`,n.minMorale<.3?`var(--rust)`:`var(--text-1)`),n.minFood!==void 0&&o(`Min food`,`${n.minFood.toFixed(1)}mo`,n.minFood<3?`var(--rust)`:`var(--text-1)`),o(`Tools forged`,`${r}`,`var(--amber)`),o(`Tool reuses`,`${i}`,`var(--amber)`)]}):(0,x.jsx)(`div`,{className:QO.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:QO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:QO.dialog,children:[(0,x.jsxs)(`div`,{className:QO.header,children:[(0,x.jsxs)(`h2`,{className:QO.title,children:[`Run Summary · `,e.snapsA.length||e.snapsB.length,` turns`]}),(0,x.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close run summary`,className:QO.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:QO.sidesRow,children:[s(e.actorNameA,`var(--vis)`,i,e.forgeApprovedA,e.reuseCountA),s(e.actorNameB,`var(--eng)`,a,e.forgeApprovedB,e.reuseCountB)]}),(0,x.jsxs)(`div`,{className:QO.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:QO.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:QO.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:QO.divergenceCopy,children:[r.People,` alive on one side but dead on the other at the final snapshot — a measure of how much the two leaders' decisions diverged the outcomes.`]})]})]})})}var tk={anchor:`_anchor_ypvfl_1`,trigger:`_trigger_ypvfl_5`,triggerOpen:`_triggerOpen_ypvfl_21`,recDot:`_recDot_ypvfl_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ypvfl_1`,menu:`_menu_ypvfl_36`,item:`_item_ypvfl_51`,itemRecording:`_itemRecording_ypvfl_71`,itemKey:`_itemKey_ypvfl_75`,itemKeyRecording:`_itemKeyRecording_ypvfl_81`,itemDesc:`_itemDesc_ypvfl_85`},nk=8,rk=4,ik={top:0,left:0,visibility:`hidden`},ak=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function ok(e){let t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;if(n<0||r<0||n>window.innerWidth||r>window.innerHeight)return!1;for(let t=e.parentElement;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t);if(e.overflowX===`visible`&&e.overflowY===`visible`)continue;let i=t.getBoundingClientRect();if(n<i.left||n>i.right||r<i.top||r>i.bottom)return!1}return!0}function sk({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(null),d=(0,b.useRef)(!1),f=()=>Array.from(u.current?.querySelectorAll(`[role="menuitem"]`)??[]),p=(0,b.useCallback)(e=>{a(!1),e&&l.current?.focus()},[]);(0,b.useLayoutEffect)(()=>{if(!i){s(null);return}let e=()=>{let e=l.current;if(!e)return;if(!ok(e)){a(!1);return}let t=e.getBoundingClientRect(),n=window.innerHeight-t.bottom-rk-nk,r=t.top-rk-nk,i=(u.current?.scrollHeight??0)>n&&r>n;s({...i?{bottom:window.innerHeight-t.top+rk,maxHeight:Math.max(0,r)}:{top:t.bottom+rk,maxHeight:Math.max(0,n)},...t.right>=188?{right:Math.max(nk,window.innerWidth-t.right)}:{left:Math.max(nk,t.left)}})};e(),window.addEventListener(`resize`,e),document.addEventListener(`scroll`,e,!0);let t=()=>{let e=l.current?.getBoundingClientRect();return e?`${e.left} ${e.top} ${e.right} ${e.bottom}`:``},n=t(),r=0,o=()=>{let i=t();i!==n&&(n=i,e()),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>{cancelAnimationFrame(r),window.removeEventListener(`resize`,e),document.removeEventListener(`scroll`,e,!0)}},[i]),(0,b.useLayoutEffect)(()=>{i&&o&&d.current&&(d.current=!1,u.current?.querySelector(`[role="menuitem"]`)?.focus({preventScroll:!0}))},[i,o]),(0,b.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;c.current?.contains(t)||u.current?.contains(t)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]);let m=e=>{let t=f(),n=t.indexOf(document.activeElement);if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let r=e.key===`ArrowDown`?1:-1;t[n<0?r>0?0:t.length-1:(n+r+t.length)%t.length]?.focus()}else if(e.key===`Home`||e.key===`End`)e.preventDefault(),t[e.key===`Home`?0:t.length-1]?.focus();else if(e.key===`Escape`)e.preventDefault(),p(!0);else if(e.key===`Tab`){e.preventDefault();let t=l.current;if(p(!0),!e.shiftKey&&t){let e=Array.from(document.querySelectorAll(ak)).filter(e=>!u.current?.contains(e)&&e.getClientRects().length>0);e[e.indexOf(t)+1]?.focus()}}},h=e=>()=>{p(!0),e()};return(0,x.jsxs)(`div`,{ref:c,className:tk.anchor,children:[(0,x.jsxs)(`button`,{ref:l,type:`button`,onClick:()=>{i||(d.current=!0),a(e=>!e)},"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[tk.trigger,i?tk.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:tk.recDot}),`EXPORT ▼`]}),i&&(0,Ay.createPortal)((0,x.jsxs)(`div`,{ref:u,role:`menu`,className:tk.menu,style:o??ik,onKeyDown:m,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(t),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(r),className:[tk.item,e?tk.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[tk.itemKey,e?tk.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(n),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Replay snapshot`})]})]}),document.body)]})}var ck={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},lk=120;function uk({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>lk,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:ck.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:ck.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:ck.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var dk={bar:`_bar_1u6wg_1`,glyphRow:`_glyphRow_1u6wg_21`,label:`_label_1u6wg_28`,glyph:`_glyph_1u6wg_21`,band:`_band_1u6wg_39`,agent:`_agent_1u6wg_43`,featured:`_featured_1u6wg_49`,turn:`_turn_1u6wg_56`,fullLegend:`_fullLegend_1u6wg_68`,popover:`_popover_1u6wg_89`,popHeading:`_popHeading_1u6wg_107`,deptSwatch:`_deptSwatch_1u6wg_135`,closeBtn:`_closeBtn_1u6wg_145`};function fk({departments:e}){let[t,n]=(0,b.useState)(!1),r=Pt(t),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&n(!1)},r=e=>{let t=e.target;t&&i.current&&!i.current.contains(t)&&n(!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`mousedown`,r),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`mousedown`,r)}},[t]),(0,x.jsxs)(`div`,{className:dk.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:dk.glyphRow,children:[(0,x.jsx)(pk,{type:`band`}),(0,x.jsx)(`span`,{className:dk.label,children:`Department band`}),(0,x.jsx)(pk,{type:`agent`}),(0,x.jsx)(`span`,{className:dk.label,children:`Agent`}),(0,x.jsx)(pk,{type:`featured`}),(0,x.jsx)(`span`,{className:dk.label,children:`Featured agent`}),(0,x.jsx)(pk,{type:`turn`}),(0,x.jsx)(`span`,{className:dk.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:dk.popover,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`viz-legend-heading`,tabIndex:-1,ref:r,children:[(0,x.jsx)(`h3`,{id:`viz-legend-heading`,className:dk.popHeading,children:`What you’re looking at`}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Departments (tile color)`}),(0,x.jsx)(`ul`,{className:dk.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:dk.deptSwatch,style:{background:e.color},"aria-hidden":`true`}),e.label]},e.id))})]}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Mood tiers (chip glyph)`}),(0,x.jsxs)(`ul`,{className:dk.moodList,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▼`}),` low (under 25% morale)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▽`}),` tense (25–50%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`△`}),` steady (50–75%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▲`}),` rising (over 75%)`]})]})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function pk({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.turn}`,"aria-hidden":`true`,children:`T`})}}var mk={panel:`_panel_15qsw_1`,eyebrow:`_eyebrow_15qsw_15`,empty:`_empty_15qsw_23`,chipRow:`_chipRow_15qsw_27`,chip:`_chip_15qsw_27`,chipLight:`_chipLight_15qsw_47`,chipStrong:`_chipStrong_15qsw_53`,chipDept:`_chipDept_15qsw_59`,chipCount:`_chipCount_15qsw_63`},hk=8;function gk({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,hk);return n.length===0?(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:mk.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:mk.chipRow,children:n.map(([e,n])=>{let r=t[e]??e,i=n.magnitude>=.5,a=`${r}: A has ${n.aState.agentCount} agents (${n.aState.dominantMood} mood); B has ${n.bState.agentCount} agents (${n.bState.dominantMood} mood)`;return(0,x.jsxs)(`li`,{className:`${mk.chip} ${i?mk.chipStrong:mk.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:mk.chipDept,children:r}),(0,x.jsxs)(`span`,{className:mk.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var _k=.2;function vk(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths,birthsThisTurn:e.births,eventCategories:e.eventCategories??[],year:e.time}}var yk={nameA:`Leader A`,nameB:`Leader B`,person:`colonist`,people:`colonists`,places:`colonies`};function bk(e,t,n,r=yk){if(!e||!t)return`Awaiting first turn snapshot.`;let i=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let a=e.deathsThisTurn>t.deathsThisTurn,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=Math.max(e.deathsThisTurn,t.deathsThisTurn),l=Math.min(e.deathsThisTurn,t.deathsThisTurn),u=e=>e===0?`none`:`${e} ${e===1?r.person:r.people}`;return`Turn ${n}, year ${i}: ${o} lost ${u(c)}; ${s} lost ${u(l)}.`}if(Math.abs(e.morale-t.morale)>=_k){let a=e.morale<t.morale,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=a?e.morale:t.morale,l=a?t.morale:e.morale;return`Turn ${n}, year ${i}: ${o}'s morale collapsed to ${xk(c)}; ${s} held ${xk(l)}.`}let a=e.eventCategories.join(`|`),o=t.eventCategories.join(`|`);return a&&o&&a!==o?`Turn ${n}, year ${i}: different events. ${r.nameA}: ${e.eventCategories.join(`, `)}; ${r.nameB}: ${t.eventCategories.join(`, `)}.`:n===1&&a&&a===o?`Turn 1, year ${i}: identical first event (${e.eventCategories.join(`, `)}). Both ${r.places} start from the same state.`:`Turn ${n}, year ${i}: ${r.nameA} and ${r.nameB} tracked closely. See sub-tabs for details.`}function xk(e){return`${Math.round(e*100)}%`}function Sk(e,t){let n=new Map,r=new Map(e.map(e=>[e.cellKey,e])),i=new Map(t.map(e=>[e.cellKey,e])),a=new Set([...r.keys(),...i.keys()]);for(let e of a){let t=r.get(e)??Ck(e),a=i.get(e)??Ck(e),o=Math.max(t.agentCount,a.agentCount,1),s=Math.abs(t.agentCount-a.agentCount)/o,c=t.dominantMood===a.dominantMood?0:1,l=t.department===a.department?0:1,u=(s+c+l)/3;n.set(e,{magnitude:u,aState:t,bState:a})}return n}function Ck(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var wk={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function Tk(e,t){let n=new Set,r=new Set;if(!e||!t)return{aliveOnlyA:n,aliveOnlyB:r};let i=new Map(e.cells.map(e=>[e.agentId,e])),a=new Map(t.cells.map(e=>[e.agentId,e]));for(let[e,t]of i){let r=a.get(e);!t.alive||r&&r.alive||n.add(e)}for(let[e,t]of a){let n=i.get(e);!t.alive||n&&n.alive||r.add(e)}return{aliveOnlyA:n,aliveOnlyB:r}}function Ek(e){if(!e)return[];let t=new Map;for(let n of e.cells){if(!n.alive)continue;let e=n.department||`unknown`,r=t.get(e);r||(r={count:0,moods:{}},t.set(e,r)),r.count+=1;let i=n.mood||`neutral`;r.moods[i]=(r.moods[i]??0)+1}let n=[];for(let[e,r]of t){let t=Object.entries(r.moods).sort((e,t)=>t[1]-e[1])[0]?.[0]??`neutral`;n.push({cellKey:e,department:e,agentCount:r.count,dominantMood:t})}return n}function Dk({k:e,v:t}){return(0,x.jsxs)(`span`,{className:$.kbd,children:[(0,x.jsx)(`kbd`,{className:$.kbdKey,children:e}),(0,x.jsx)(`span`,{className:$.kbdLabel,children:t})]})}function Ok(e){return e?[e.foodReserve,e.waterLitersPerDay,e.powerKw,e.pressurizedVolumeM3].some(e=>typeof e==`number`):!1}var kk=`button, a[href], summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"]`;function Ak({state:e,onNavigateToChat:t}){let n=HE(e),r=e.actorIds[0],i=e.actorIds[1],[a,o]=(0,b.useState)(r),[s,c]=(0,b.useState)(i);(0,b.useEffect)(()=>{a&&!e.actorIds.includes(a)&&o(r),s&&!e.actorIds.includes(s)&&c(i)},[e.actorIds,a,s,r,i]);let l=a??r,u=s??i,d=(l?n[l]:void 0)??[],f=(u?n[u]:void 0)??[],p=l?e.actors[l]:null,m=u?e.actors[u]:null,h=e.actorIds.length>2,[g,_]=(0,b.useState)(h?`cohort`:`pair`);(0,b.useEffect)(()=>{_(h?`cohort`:`pair`)},[h]);let v=Math.max(d.length,f.length),[y,S]=(0,b.useState)(0),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(1),[D,O]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridMode`);if(e===`living`||e===`mood`||e===`forge`||e===`ecology`||e===`divergence`)return e}catch{}return`living`}),k=(0,b.useCallback)(e=>{O(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:A}=Ht(),j=(0,b.useRef)(0),ee=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ee.current;ee.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return j.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(j.current)},[C,T,v]);let te=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),M=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),N=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),ne=(0,b.useCallback)(e=>{w(!1),S(e)},[]),P=nA(),re=(0,b.useCallback)(e=>{P(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[P]),[ie,F]=(0,b.useState)(!1),I=Qk(),ae=Lm(),[oe,ce]=(0,b.useState)(null),[le,L]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,R]=(0,b.useState)(`all`),[z,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(``),[ge,_e]=(0,b.useState)(null),[B,ve]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3)return rO(t);localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return nO}),ye=(0,b.useCallback)(e=>{ve(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=new Set([`event_start`,`director_crisis`]),n=`paracosm:seenCrisisToasts`,r=()=>{try{let e=sessionStorage.getItem(n);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},i=e=>{try{let t=[...e].slice(-200);sessionStorage.setItem(n,JSON.stringify(t))}catch{}},a=r(),o=(()=>{let n=null,r=[];l&&r.push({side:`a`,actorName:l}),u&&r.push({side:`b`,actorName:u});for(let{side:i,actorName:o}of r){let r=e.actors[o];if(!r)continue;let s=r.events;for(let e=s.length-1;e>=0;e--){let r=s[e];if(!t.has(r.type))continue;let o=Number(r.turn??r.data?.turn??0),c=typeof r.data?.category==`string`?r.data.category:``;if(!c)continue;let l=`${i}:${o}:${c}`;if(a.has(l))continue;let u=typeof r.data?.title==`string`?r.data.title:``;(!n||o>n.turn)&&(n={key:l,side:i,turn:o,category:c,title:u});break}}return n})();o&&(a.add(o.key),i(a),_e(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,B.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!ge)return;let e=ge.expiresAt-performance.now();if(e<=0){_e(null);return}let t=setTimeout(()=>_e(null),e);return()=>clearTimeout(t)},[ge]);let[be,xe]=(0,b.useState)(null),Se=`paracosm:seenThresholdAlerts`,Ce=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Se);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),we=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Se,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=Ce(),n=(e,n)=>{t.has(e)||(t.add(e),xe({key:e,...n,expiresAt:performance.now()+5500}))},r=(e,t)=>{if(t.length<2)return;let r=t[t.length-1],i=t[t.length-2],a=i.morale-r.morale;a>=.2&&n(`${e}|${r.turn}|morale-crash`,{side:e,turn:r.turn,kind:`morale-crash`,message:`Morale crashed ${Math.round(a*100)}% → ${Math.round(r.morale*100)}% this turn`}),typeof r.foodReserve==`number`&&typeof i.foodReserve==`number`&&r.foodReserve<3&&i.foodReserve>=3&&n(`${e}|${r.turn}|food-low`,{side:e,turn:r.turn,kind:`food-low`,message:`Food reserve fell below 3mo (${r.foodReserve.toFixed(1)}mo remaining)`})};r(`a`,d),r(`b`,f),we(t)},[d,f,B.alerts,Ce,we,e.isRunning]),(0,b.useEffect)(()=>{if(!be)return;let e=be.expiresAt-performance.now();if(e<=0){xe(null);return}let t=setTimeout(()=>xe(null),e);return()=>clearTimeout(t)},[be]);let[Te,Ee]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),De=(0,b.useCallback)(e=>{Ee(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Oe=(0,b.useCallback)(()=>{De(Te===`amber`?`cool`:Te===`cool`?`mono`:`amber`)},[Te,De]),[ke,Ae]=(0,b.useState)(!1),[je,Me]=(0,b.useState)(!1),[Ne,Pe]=(0,b.useState)(!1),Fe=ev(),Ie=D_(),Le=(0,b.useCallback)((t,n,r,i)=>{let a=n===`a`?l:u,o=a?e.actorIds.indexOf(a):-1,s=o>=0?Ie.getEntryFor(o,t):void 0;if(!s)return!1;let c=s.attempts.find(e=>e.eventId===r)?.attempt;return Fe.openTrace({actorIndex:o,toolName:t,attempt:c},i,`viz`),!0},[l,u,e.actorIds,Ie,Fe]),[Re,ze]=(0,b.useState)(null),Be=(0,b.useCallback)(e=>{ze(t=>t===e?null:e)},[]),Ve=d[y]??d[d.length-1],He=f[y]??f[f.length-1],Ue=Ve?.turn??0,We=He?.turn??0,Ge=I.presets.find(e=>e.id==="default"),Ke=Ge?.leaders??Ge?.actors,qe=Ke?.[0]?{name:Ke[0].name,archetype:Ke[0].archetype,unit:se(I,0),hexaco:Ke[0].hexaco,instructions:Ke[0].instructions,quote:``}:null,Je=Ke?.[1]?{name:Ke[1].name,archetype:Ke[1].archetype,unit:se(I,1),hexaco:Ke[1].hexaco,instructions:Ke[1].instructions,quote:``}:null,Ye=p?.leader??qe,Xe=m?.leader??Je,Ze=(0,b.useRef)(null),[Qe,$e]=(0,b.useState)(!1),et=(0,b.useRef)(null),tt=(0,b.useRef)([]),nt=(0,b.useRef)(null),rt=(0,b.useRef)(0),it=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=e.getBoundingClientRect(),n=Math.max(640,Math.round(t.width)),r=Math.max(360,Math.round(t.height)),i=document.createElement(`canvas`);if(i.width=n,i.height=r,!i.getContext(`2d`))return;nt.current=i;let a=i.captureStream(30),o=`video/webm;codecs=vp9`;typeof MediaRecorder<`u`&&!MediaRecorder.isTypeSupported(o)&&(o=`video/webm;codecs=vp8`,MediaRecorder.isTypeSupported(o)||(o=`video/webm`));let s;try{s=new MediaRecorder(a,{mimeType:o,videoBitsPerSecond:4e6})}catch{console.warn(`MediaRecorder unavailable — timelapse skipped`);return}tt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&tt.current.push(e.data)},s.onstop=()=>{rt.current&&cancelAnimationFrame(rt.current),rt.current=0;let e=new Blob(tt.current,{type:o}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-timelapse-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.webm`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},et.current=s,$e(!0),s.start();let c=()=>{let e=nt.current,t=Ze.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.fillStyle=getComputedStyle(t).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,n.fillRect(0,0,e.width,e.height);let r=t.getBoundingClientRect(),i=e.width/Math.max(1,r.width),a=e.height/Math.max(1,r.height),o=Array.from(t.querySelectorAll(`canvas`));for(let e of o){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&n.drawImage(e,(t.left-r.left)*i,(t.top-r.top)*a,t.width*i,t.height*a)}rt.current=requestAnimationFrame(c)};rt.current=requestAnimationFrame(c)},[]),at=(0,b.useCallback)(()=>{let e=et.current;if(e){try{e.stop()}catch{}et.current=null,$e(!1)}},[]);(0,b.useEffect)(()=>()=>{if(et.current)try{et.current.stop()}catch{}rt.current&&cancelAnimationFrame(rt.current)},[]);let ot=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:Ye?.name??`Leader A`,archetype:Ye?.archetype??``},leaderB:{name:Xe?.name??`Leader B`,archetype:Xe?.archetype??``},currentTurn:y,snapshots:{a:d,b:f},events:{a:p?.events??[],b:m?.events??[]}},t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`paracosm-replay-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),1e3)},[y,Ye,Xe,d,f,p,m]),st=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=Array.from(e.querySelectorAll(`canvas`));if(t.length===0)return;let n=e.getBoundingClientRect(),r=document.createElement(`canvas`);r.width=Math.round(n.width*2),r.height=Math.round(n.height*2);let i=r.getContext(`2d`);if(i){i.fillStyle=getComputedStyle(e).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,i.fillRect(0,0,r.width,r.height),i.scale(2,2);for(let e of t){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&i.drawImage(e,t.left-n.left,t.top-n.top,t.width,t.height)}r.toBlob(e=>{if(!e)return;let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-viz-t${y+1}-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.png`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},`image/png`)}},[y]),[ct,lt]=(0,b.useState)(0),ut=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ut.current===-1||Math.abs(y-ut.current)>=2&<(e=>e+1),ut.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target instanceof Element?e.target:null,n=t?.tagName;n!==`INPUT`&&n!==`TEXTAREA`&&n!==`SELECT`&&(e.key!==`Escape`&&t?.closest(`[role="dialog"]`)||(e.key!==` `&&e.key!==`Spacebar`||!t?.closest(kk))&&(e.key===`ArrowLeft`?(e.preventDefault(),M()):e.key===`ArrowRight`?(e.preventDefault(),N()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),te()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),F(e=>!e)):e.key===`Escape`&&ie?(e.preventDefault(),F(!1)):e.key===`1`?(e.preventDefault(),k(`living`)):e.key===`2`?(e.preventDefault(),k(`mood`)):e.key===`3`?(e.preventDefault(),k(`forge`)):e.key===`4`?(e.preventDefault(),k(`ecology`)):e.key===`5`&&(e.preventDefault(),k(`divergence`))))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[M,N,te,ie,k]);let dt=(0,b.useMemo)(()=>{let e=me.trim().toLowerCase().split(/\s+/).filter(Boolean);if(e.length===0)return[];let t=t=>{let n=`${t.name} ${t.department} ${t.role} ${t.mood}`.toLowerCase();return e.every(e=>n.includes(e))};return[...(Ve?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:Ye?.name??`Leader A`,sideColor:`#e8b44a`})),...(He?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:Xe?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[me,Ve,He,Ye,Xe]),ft=(0,b.useMemo)(()=>Tk(Ve,He),[Ve,He]),pt=(0,b.useMemo)(()=>{let t={a:{attempts:[],reuses:[]},b:{attempts:[],reuses:[]}},n=[];l&&n.push({side:`a`,actorName:l}),u&&n.push({side:`b`,actorName:u});for(let{side:r,actorName:i}of n){let n=e.actors[i];if(!n)continue;let a=new Map;for(let e of n.events){if(e.type===`forge_attempt`){let n=e.data||{};t[r].attempts.push({turn:Number(n.turn??0),eventIndex:Number(n.eventIndex??0),department:String(n.department||``),name:String(n.name||``),approved:n.approved===!0||n.approved===`true`,confidence:typeof n.confidence==`number`?n.confidence:void 0}),n.name&&n.department&&n.approved===!0&&!a.has(String(n.name))&&a.set(String(n.name),String(n.department));continue}if(e.type!==`specialist_done`)continue;let n=e.data||{},i=String(n.department||``),o=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let s of o){let o=s,c=String(o.name||``);if(!c||c===`unnamed`)continue;let l=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):a.get(c),u=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,d=Number(e.turn??n.turn??0);(l&&u!==void 0&&u<d||l&&l!==i)&&t[r].reuses.push({turn:d,originDept:l,callingDept:i,name:c})}}}return t},[e]);ZO({enabled:B.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:pt.a.attempts,forgeAttemptsB:pt.b.attempts});let mt=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(r)for(let e of r.events){if(e.type!==`agent_reactions`)continue;let n=e.data?.reactions||[];for(let e of n){let n=e.hexaco;if(!n)continue;let r=e.agentId||e.name;r&&t.set(r,n)}}}return t},[e]),ht=(0,b.useCallback)(e=>{t?.(e)},[t]),gt=jy(My),_t=jy(Ny),vt=jy(Py),[yt,bt]=(0,b.useState)(null),xt=Ye?.name??`Leader A`,St=Xe?.name??`Leader B`,Ct=(0,b.useMemo)(()=>bk(d[y]?vk(d[y],d[y-1]):null,f[y]?vk(f[y],f[y-1]):null,y+1,{nameA:xt,nameB:St,person:ae.person,people:ae.people,places:ae.places}),[d,f,y,xt,St,ae.person,ae.people,ae.places]),wt=(0,b.useMemo)(()=>I.departments.map(e=>({id:e.id,label:e.label,color:wk[e.id]??`#a89878`})),[I.departments]),Tt=(0,b.useMemo)(()=>Object.fromEntries(I.departments.map(e=>[e.id,e.label])),[I.departments]),[Et,Dt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Ot=(0,b.useCallback)(e=>{Dt(e);try{window.localStorage.setItem(`paracosm:vizDiffOverlay`,e?`1`:`0`)}catch{}},[]);(0,b.useEffect)(()=>{let e=e=>{let t=e.target;t&&t.matches(`input, textarea, [contenteditable=true]`)||(e.key===`d`||e.key===`D`)&&(e.preventDefault(),Ot(!Et))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Et,Ot]);let kt=(0,b.useMemo)(()=>Et?Sk(Ek(d[y]),Ek(f[y])):null,[Et,d,f,y]);if(v===0)return e.isRunning?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Awaiting first turn snapshot — the `,ae.place,` viz will populate once the kernel reports state.`]})]}):typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Loading replay — the `,ae.place,` viz will populate as the cached events stream in.`]})]}):(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,children:[`Run a simulation to see the `,ae.place,` visualization.`]});let At=Ve&&He?`A vs B: ${He.population-Ve.population>=0?`+`:``}${He.population-Ve.population} pop, ${He.morale-Ve.morale>=0?`+`:``}${Math.round((He.morale-Ve.morale)*100)}% morale${typeof Ve.foodReserve==`number`&&typeof He.foodReserve==`number`?`, ${He.foodReserve-Ve.foodReserve>0?`+`:``}${(He.foodReserve-Ve.foodReserve).toFixed(1)}mo food`:``}`:``,jt=_t?Re??`a`:Re,Mt=y>0?d[y-1]??d[d.length-2]:void 0,Nt=y>0?f[y-1]??f[f.length-2]:void 0,Pt=dt,Ft=(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Ot(!Et),"aria-label":Et?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Et,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Et?`on`:`off`]}),It=(0,x.jsx)(`button`,{type:`button`,onClick:()=>F(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),Lt=_t,Rt=SO(e,y)!==``;return(0,x.jsxs)(`div`,{ref:Ze,className:`viz-content ${$.root}`,children:[h&&(0,x.jsxs)(`div`,{className:$.cohortViewBar,role:`region`,"aria-label":`Cohort view controls`,children:[(0,x.jsxs)(`div`,{className:$.cohortViewModeToggle,role:`tablist`,"aria-label":`Swarm grid view mode`,children:[(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`cohort`,onClick:()=>_(`cohort`),className:[$.cohortViewModeButton,g===`cohort`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Show every actor's living-swarm panel side-by-side with horizontal scroll`,children:[`All `,e.actorIds.length,` actors`]}),(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`pair`,onClick:()=>_(`pair`),className:[$.cohortViewModeButton,g===`pair`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Focus on a 2-actor head-to-head with the original pair-mode diff overlay + sympathy hover`,children:`Focus pair`})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:$.cohortPairPicker,children:[(0,x.jsx)(`select`,{"aria-label":`Left panel actor`,className:$.cohortPairPickerSelect,value:l??``,onChange:e=>o(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===u,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:$.cohortPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right panel actor`,className:$.cohortPairPickerSelect,value:u??``,onChange:e=>c(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===l,children:e.actors[t]?.leader?.name??t},t))})]})]}),(0,x.jsx)(wO,{state:e,currentTurn:y,linesTarget:Lt?yt:null,cohortGridShown:g===`cohort`}),(0,x.jsx)(uk,{text:Ct,turn:y+1}),(0,x.jsx)(fk,{departments:wt}),Et&&kt&&(0,x.jsx)(gk,{diff:kt,departmentLabels:Tt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(yC,{label:`toolbar keys`,rowClassName:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(jO,{mode:D,onChange:k,counts:{forge:pt.a.attempts.filter(e=>e.approved).length+pt.b.attempts.filter(e=>e.approved).length,divergence:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)},labels:ae})}),D===`forge`&&(0,x.jsx)(`button`,{type:`button`,"aria-haspopup":`dialog`,onClick:e=>Fe.openToolbox(e.currentTarget,`viz`),className:$.forgeToolboxKey,children:Qv(Ie.list.length)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>!e),"aria-label":Ne?vt?`Hide more tools`:`Hide advanced tools`:vt?`Show more tools (diff, help, palette, stats, export, settings)`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":Ne,title:Ne?`Hide tools`:vt?`Diff · Help · Palette · Stats · Export · Settings`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,Ne?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),!vt&&Ft,!vt&&It]}),Ne&&(0,x.jsxs)(yC,{label:`Viz tools`,role:`toolbar`,ariaLabel:`Viz tools`,rowClassName:$.toolsRow,children:[vt&&Ft,vt&&It,(0,x.jsx)(`button`,{type:`button`,onClick:Oe,"aria-label":`Palette: ${Te}. Click to cycle.`,title:`Palette: ${Te.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Te===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Te===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Te}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Me(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(sk,{recording:Qe,onExportPng:st,onExportJson:ot,onToggleRecording:Qe?at:it}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ae(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":ke,title:`Viz settings`,className:[$.settingsBtn,ke?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:AO(D,ae)}),D===`ecology`&&!e.actorIds.some(e=>{let t=n[e]??[];return Ok(t[y]??t[t.length-1])})&&(0,x.jsxs)(`div`,{role:`status`,className:$.ecologyNone,children:[(0,x.jsx)(`span`,{children:`ECOLOGY draws food, water, power and pressurized volume. This run holds none of them.`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>k(`living`),className:$.ecologyBack,children:`Back to LIVING`})]})]}),(0,x.jsx)(JO,{value:me,onChange:he,matches:Pt,onPick:e=>{he(e.cell.name)}}),(0,x.jsx)(KO,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:I.departments.length}),(0,x.jsx)(UO,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de,filter:fe,onFilterChange:R,onHoverEventChange:pe,onJumpToReports:re,onForgeSelect:Le}),(0,x.jsx)(RO,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de}),g===`pair`&&At&&(0,x.jsx)(`div`,{className:$.diffLine,children:At}),g===`pair`&&_t&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?Ye?.name??`Leader A`:Xe?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=jt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>ze(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsxs)(`div`,{className:[$.cohortWindow,Lt?$.cohortWindowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(vO,{className:Lt?$.cohortTrackLinesBelow:void 0,state:e,snapshotMap:n,currentTurn:y,gridMode:D,palette:Te===`cool`?1:Te===`mono`?2:0,gridSettings:B,hexacoById:mt,searchQuery:me,chronicleFilter:fe,chronicleHover:z,startTime:I.setup?.defaultStartTime,onOpenChat:ht}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,gt?$.leadersRowNarrow:``,Lt?$.leadersRowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:Ve,previousSnapshot:Mt,snapshotHistory:d,actorName:Ye?.name??`Leader A`,actorArchetype:Ye?.archetype??``,leaderUnit:Ye?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ue<We?We-Ue:0,mode:D,hexacoById:mt,leaderHexaco:Ye?.hexaco?{O:Ye.hexaco.O??Ye.hexaco.openness??.5,C:Ye.hexaco.C??Ye.hexaco.conscientiousness??.5,E:Ye.hexaco.E??Ye.hexaco.extraversion??.5,A:Ye.hexaco.A??Ye.hexaco.agreeableness??.5,Em:Ye.hexaco.Em??Ye.hexaco.emotionality??.5,HH:Ye.hexaco.HH??Ye.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.a.attempts,reuseCalls:pt.a.reuses,divergedIds:ft.aliveOnlyA,siblingHoveredId:le,onHoverChange:ce,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:He,previousSnapshot:Nt,snapshotHistory:f,actorName:Xe?.name??`Leader B`,actorArchetype:Xe?.archetype??``,leaderUnit:Xe?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:We<Ue?Ue-We:0,mode:D,hexacoById:mt,leaderHexaco:Xe?.hexaco?{O:Xe.hexaco.O??Xe.hexaco.openness??.5,C:Xe.hexaco.C??Xe.hexaco.conscientiousness??.5,E:Xe.hexaco.E??Xe.hexaco.extraversion??.5,A:Xe.hexaco.A??Xe.hexaco.agreeableness??.5,Em:Xe.hexaco.Em??Xe.hexaco.emotionality??.5,HH:Xe.hexaco.HH??Xe.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.b.attempts,reuseCalls:pt.b.reuses,divergedIds:ft.aliveOnlyB,siblingHoveredId:oe,onHoverChange:L,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),(0,x.jsx)(DO,{currentTurn:y,maxTurn:v,time:Ve?.time??He?.time??0,timeInBanner:Rt,playing:C,speed:T,onTurnChange:ne,onPlayPause:te,onStepBack:M,onStepForward:N,onSpeedChange:E}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(Dk,{k:`?`,v:`help`}),(0,x.jsx)(Dk,{k:`1-5`,v:`mode`}),(0,x.jsx)(Dk,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(Dk,{k:`space`,v:`play / pause`}),(0,x.jsx)(Dk,{k:`click`,v:`${ae.person} drilldown`}),(0,x.jsx)(Dk,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ve&&He?`Turn ${Math.max(Ve.turn,He.turn)}. ${Ye?.name??`A`} ${ae.place}: ${Ve.cells.filter(e=>e.alive).length} alive, ${Ve.births} born, ${Ve.deaths} died, morale ${Math.round(Ve.morale*100)}%. ${Xe?.name??`B`} ${ae.place}: ${He.cells.filter(e=>e.alive).length} alive, ${He.births} born, ${He.deaths} died, morale ${Math.round(He.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>ne(v-1),"aria-label":`Jump to latest turn (T${v})`,className:$.jumpLatest,children:[`↓`,` Latest · T`,v,(0,x.jsxs)(`span`,{className:$.jumpLatestBehind,children:[`(`,v-1-y,` turn`,v-1-y==1?``:`s`,` behind)`]})]}),(0,x.jsx)(NO,{open:ie,onClose:()=>F(!1)}),(0,x.jsx)(iO,{open:ke,settings:B,onChange:ye,onClose:()=>Ae(!1)}),(0,x.jsx)(ek,{open:je,onClose:()=>Me(!1),snapsA:d,snapsB:f,actorNameA:Ye?.name??`Leader A`,actorNameB:Xe?.name??`Leader B`,forgeApprovedA:pt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:pt.b.attempts.filter(e=>e.approved).length,reuseCountA:pt.a.reuses.length,reuseCountB:pt.b.reuses.length,divergedCount:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)}),be&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>xe(null),className:$.toast,style:{"--toast-top":ge?`68px`:`8px`,"--side-color":be.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:be.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[be.side.toUpperCase(),` · T`,be.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:be.message})]},be.key),ge&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>_e(null),className:$.toast,style:{"--side-color":ge.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":`var(--rust)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,children:[(0,x.jsx)(`span`,{children:`⚡ Crisis`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ge.side.toUpperCase(),` · T`,ge.turn,` · `,ge.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:ge.title||`${ge.category} crisis unfolding`})]},ge.key),ct>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},ct),(0,x.jsx)(`style`,{children:`
|
|
128
|
+
Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:xT.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:xT.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:xT.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:xT.cancelButton,children:`Cancel`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=f[p];if(!e)return;let r=h.trim()?parseInt(h,10):void 0,i=r!==void 0&&Number.isFinite(r)?r:void 0,a=_.trim()?hT(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:xT.confirmButton,children:`Fork`})]})]})})}var CT=`/retry-stats`;function wT(e=!0){let[t,n]=(0,b.useState)(null),[r,i]=(0,b.useState)(!1),[a,o]=(0,b.useState)(null),s=(0,b.useCallback)(async()=>{i(!0),o(null);try{let e=await fetch(CT,{credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();n(t)}catch(e){o(e instanceof Error?e.message:String(e))}finally{i(!1)}},[]);return(0,b.useEffect)(()=>{e&&s()},[e,s]),{data:t,loading:r,error:a,refresh:s}}var X={backdrop:`_backdrop_vajsn_1`,dialog:`_dialog_vajsn_12`,titleRow:`_titleRow_vajsn_27`,title:`_title_vajsn_27`,escBtn:`_escBtn_vajsn_43`,totalLine:`_totalLine_vajsn_54`,totalAmount:`_totalAmount_vajsn_60`,cacheBlock:`_cacheBlock_vajsn_66`,cacheLabel:`_cacheLabel_vajsn_74`,cacheVerdict:`_cacheVerdict_vajsn_83`,cacheSubLine:`_cacheSubLine_vajsn_91`,cacheTokenRow:`_cacheTokenRow_vajsn_98`,cacheMultiplier:`_cacheMultiplier_vajsn_107`,emptyState:`_emptyState_vajsn_111`,table:`_table_vajsn_118`,tableSm:`_tableSm_vajsn_125`,headRow:`_headRow_vajsn_132`,th:`_th_vajsn_139`,thRight:`_thRight_vajsn_144`,bodyRow:`_bodyRow_vajsn_150`,stageCell:`_stageCell_vajsn_154`,stageLabel:`_stageLabel_vajsn_158`,stageDescription:`_stageDescription_vajsn_164`,bar:`_bar_vajsn_171`,barFill:`_barFill_vajsn_180`,numericCell:`_numericCell_vajsn_187`,numericCellGreen:`_numericCellGreen_vajsn_193`,numericCellMuted:`_numericCellMuted_vajsn_201`,section:`_section_vajsn_208`,sectionLabel:`_sectionLabel_vajsn_214`,sectionFootnote:`_sectionFootnote_vajsn_222`,sectionFootnoteTight:`_sectionFootnoteTight_vajsn_229`,subBlock:`_subBlock_vajsn_236`,subBlockLabel:`_subBlockLabel_vajsn_240`,cellSchemaName:`_cellSchemaName_vajsn_247`,cellNumericTight:`_cellNumericTight_vajsn_252`,cellAvgAttempts:`_cellAvgAttempts_vajsn_258`,cellFallback:`_cellFallback_vajsn_265`,cellRight1:`_cellRight1_vajsn_272`,cellRightGreen:`_cellRightGreen_vajsn_278`,cellRightRust:`_cellRightRust_vajsn_285`,cellRightMuted:`_cellRightMuted_vajsn_291`,cellRateColor:`_cellRateColor_vajsn_297`,cellConfColor:`_cellConfColor_vajsn_304`,statusInline:`_statusInline_vajsn_311`,statusErrorTag:`_statusErrorTag_vajsn_320`,rejectionWrap:`_rejectionWrap_vajsn_324`,rejectionLabel:`_rejectionLabel_vajsn_328`,rejectionCell:`_rejectionCell_vajsn_335`,perLeaderRow:`_perLeaderRow_vajsn_342`,leaderCard:`_leaderCard_vajsn_349`,leaderName:`_leaderName_vajsn_357`,leaderCost:`_leaderCost_vajsn_363`,leaderMeta:`_leaderMeta_vajsn_369`,perActorList:`_perActorList_vajsn_378`,perActorRow:`_perActorRow_vajsn_386`,perActorBarTrack:`_perActorBarTrack_vajsn_412`,perActorCost:`_perActorCost_vajsn_417`,perActorMeta:`_perActorMeta_vajsn_421`,perActorRank:`_perActorRank_vajsn_426`,perActorName:`_perActorName_vajsn_433`,perActorBarFill:`_perActorBarFill_vajsn_448`},TT={director:{label:`Event Director`,description:`Generates events each turn based on world state`},commander:{label:`Commander`,description:`Reads dept reports, picks options, promotes department heads`},departments:{label:`Department Analysis`,description:`5 specialists analyzing each event in parallel`},judge:{label:`Forge Judge`,description:`LLM safety + correctness review of every forged tool`},reactions:{label:`Agent Reactions`,description:`~100 colonists reacting to each turn's outcome`},other:{label:`Other`,description:`Uncategorized calls`}};function ET(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function DT(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function OT(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function kT(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function AT({combined:e,leaderA:t,leaderB:n,leaderAName:r,leaderBName:i,actors:a,onClose:o}){(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let s=Pt(!0),c=wT(!0),l=e.breakdown??{},u=Object.entries(l).map(([e,t])=>({site:e,...t})).sort((e,t)=>t.totalCostUSD-e.totalCostUSD),d=e.totalCostUSD||u.reduce((e,t)=>e+t.totalCostUSD,0),f=u[0]?.totalCostUSD??0;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Cost breakdown`,onClick:o,className:X.backdrop,children:(0,x.jsxs)(`div`,{ref:s,tabIndex:-1,onClick:e=>e.stopPropagation(),className:X.dialog,children:[(0,x.jsxs)(`div`,{className:X.titleRow,children:[(0,x.jsx)(`h3`,{className:X.title,children:`COST BREAKDOWN`}),(0,x.jsx)(`button`,{onClick:o,"aria-label":`Close cost breakdown`,className:X.escBtn,children:`ESC`})]}),(0,x.jsxs)(`div`,{className:X.totalLine,children:[`Total: `,(0,x.jsx)(`span`,{className:X.totalAmount,children:ET(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,DT(e.totalTokens),` tokens`]}),e.cacheReadTokens||e.cacheCreationTokens?(()=>{let t=e.cacheReadTokens??0,n=e.cacheCreationTokens??0,r=e.cacheSavingsUSD??0,i=t+n,a=i>0?t/i:0,o=`var(--text-3)`,s;return r>.001?(o=`var(--green)`,s=`Saved ${ET(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${ET(-r)} so far · reuse will repay this`):t>0?(o=`var(--green)`,s=`Cache reuse breaking even with priming cost`):(o=`var(--amber)`,s=`Cache filled but nothing reused yet · retry run or check prompt stability`),(0,x.jsxs)(`div`,{className:X.cacheBlock,children:[(0,x.jsx)(`div`,{className:X.cacheLabel,children:`PROMPT CACHING`}),(0,x.jsx)(`div`,{className:X.cacheVerdict,style:{"--cache-verdict-color":o},children:s}),(0,x.jsxs)(`div`,{className:X.cacheSubLine,children:[Math.round(a*100),`% hit rate on cached input (`,DT(t),` reused / `,DT(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,DT(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,DT(n),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@1.25×`})]})]})]})})():null,u.length===0?(0,x.jsx)(`div`,{className:X.emptyState,children:`No LLM calls have been billed yet. Start a simulation to see spend by pipeline stage.`}):(0,x.jsxs)(`table`,{className:X.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`STAGE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`COST`}),(0,x.jsx)(`th`,{className:X.thRight,children:`%`})]})}),(0,x.jsx)(`tbody`,{children:u.map(e=>{let t=TT[e.site]??{label:e.site,description:``},n=d>0?e.totalCostUSD/d*100:0,r=f>0?e.totalCostUSD/f*100:0;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.stageCell,children:[(0,x.jsx)(`div`,{className:X.stageLabel,children:t.label}),(0,x.jsx)(`div`,{className:X.stageDescription,children:t.description}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:X.bar,children:(0,x.jsx)(`div`,{className:X.barFill,style:{"--bar-pct":`${r}%`}})})]}),(0,x.jsx)(`td`,{className:X.numericCell,children:e.calls.toLocaleString()}),(0,x.jsx)(`td`,{className:X.numericCell,children:DT(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:ET(e.totalCostUSD)}),(0,x.jsxs)(`td`,{className:X.numericCellMuted,children:[n.toFixed(0),`%`]})]},e.site)})})]}),e.schemaRetries&&Object.keys(e.schemaRetries).length>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`SCHEMA RELIABILITY`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACKS`})]})}),(0,x.jsx)(`tbody`,{children:Object.entries(e.schemaRetries).sort((e,t)=>t[1].calls-e[1].calls).map(([e,t])=>{let n=t.calls>0?t.attempts/t.calls:0,r=OT(n),i=t.fallbacks>0?`var(--rust)`:`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":r},children:n.toFixed(2)}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":i,"--fb-weight":t.fallbacks>0?`700`:`400`},children:t.fallbacks})]},e)})})]}),(0,x.jsxs)(`div`,{className:X.sectionFootnote,children:[`1.00 = first-try success. Higher = model retrying on validation failures. Tune `,(0,x.jsx)(`code`,{className:`mono`,children:`maxRetries`}),` or tighten schema if a row stays above 1.3.`]})]}),e.forgeStats&&e.forgeStats.attempts>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`FORGE RELIABILITY`}),(()=>{let t=e.forgeStats,n=t.attempts>0?t.approved/t.attempts:0,r=t.approved>0?t.approvedConfidenceSum/t.approved:0,i=n<.5?`var(--rust)`:n<.75?`var(--amber)`:`var(--green)`,a=r>0&&r<.6?`var(--amber)`:`var(--text-1)`;return(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`REJECTED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVAL RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:t.attempts}),(0,x.jsx)(`td`,{className:X.cellRightGreen,children:t.approved}),(0,x.jsx)(`td`,{className:t.rejected>0?X.cellRightRust:X.cellRightMuted,children:t.rejected}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i},children:[(n*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellConfColor,style:{"--conf-color":a},children:r>0?r.toFixed(2):`—`})]})})]})})(),(0,x.jsx)(`div`,{className:X.sectionFootnote,children:`Rejections come from shape check OR judge verdict. Retry-with-feedback usually recovers; persistent low approval rate suggests the department model is weak at writing schema-compliant code.`})]}),(()=>{let e=c.data;if(c.loading&&!e)return(0,x.jsx)(`div`,{className:X.statusInline,children:`RECENT RUNS — loading…`});if(c.error)return(0,x.jsxs)(`div`,{className:X.statusInline,children:[`RECENT RUNS — `,(0,x.jsxs)(`span`,{className:X.statusErrorTag,children:[`fetch failed (`,c.error,`)`]})]});if(!e||e.runCount===0)return null;let t=Object.entries(e.schemas).filter(([e])=>!e.startsWith(`compile:`)),n=Object.entries(e.schemas).filter(([e])=>e.startsWith(`compile:`)).map(([e,t])=>[e.replace(/^compile:/,``),t]),r=e.forges,i=e.caches,a=e.providerErrors,o=([e,t])=>{let n=OT(t.avgAttempts),r=kT(t.fallbackRate);return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":n},children:t.avgAttempts.toFixed(2)}),(0,x.jsxs)(`td`,{className:X.cellFallback,style:{"--fb-color":r,"--fb-weight":t.fallbacks>0?`700`:`400`},children:[(t.fallbackRate*100).toFixed(2),`%`]})]},e)};return(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`RECENT RUNS (last `,e.runCount,`)`]}),t.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`RUNTIME SCHEMAS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:t.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),n.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`COMPILE HOOKS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`HOOK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:n.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),r&&r.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`FORGES`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPT RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`UNIQUE TOOLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`EVENTUALLY APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TERMINAL FAILS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:r.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalAttempts}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.approvalRate<.5?`var(--rust)`:r.approvalRate<.75?`var(--amber)`:`var(--green)`},children:[(r.approvalRate*100).toFixed(1),`%`]}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalUniqueNames}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.uniqueApprovalRate<.8?`var(--rust)`:r.uniqueApprovalRate<.95?`var(--amber)`:`var(--green)`},children:[r.totalUniqueApproved,` (`,(r.uniqueApprovalRate*100).toFixed(0),`%)`]}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":r.totalUniqueTerminalRejections>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":r.totalUniqueTerminalRejections>0?`700`:`400`},children:r.totalUniqueTerminalRejections}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:r.avgApprovedConfidence>0?r.avgApprovedConfidence.toFixed(2):`—`})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`ATTEMPT RATE counts every forge call including retries. EVENTUALLY APPROVED is the real quality signal — tools that landed in the toolbox. TERMINAL FAILS are tools the retry loop never recovered.`}),(()=>{let e=r.rejectionReasons,t=e.schema_extra_field+e.shape_check+e.parse_error+e.judge_correctness+e.other;if(t===0)return null;let n=e=>t>0?Math.round(e/t*100):0,i=(e,t)=>({"--rj-color":e>0?t:`var(--text-3)`,"--rj-weight":e>0?`700`:`400`});return(0,x.jsxs)(`div`,{className:X.rejectionWrap,children:[(0,x.jsxs)(`div`,{className:X.rejectionLabel,children:[`REJECTION REASONS (last `,r.runsPresent,` run`,r.runsPresent===1?``:`s`,`)`]}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`SCHEMA EXTRA FIELD`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SHAPE CHECK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`PARSE ERROR`}),(0,x.jsx)(`th`,{className:X.thRight,children:`JUDGE CORRECTNESS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.schema_extra_field,`var(--amber)`),children:[e.schema_extra_field,` (`,n(e.schema_extra_field),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.shape_check,`var(--amber)`),children:[e.shape_check,` (`,n(e.shape_check),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.parse_error,`var(--rust)`),children:[e.parse_error,` (`,n(e.parse_error),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.judge_correctness,`var(--rust)`),children:[e.judge_correctness,` (`,n(e.judge_correctness),`%)`]}),(0,x.jsxs)(`td`,{className:X.cellRightMuted,children:[e.other,` (`,n(e.other),`%)`]})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`SCHEMA EXTRA FIELD dominating means the LLM's return-keys don't match its declared outputSchema.properties — the target of the 2026-04-18 forge-guidance prompt fix. JUDGE CORRECTNESS = real logic bugs the judge caught.`})]})})()]}),a&&a.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROVIDER ERRORS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS W/ ERRORS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOTAL`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AUTH`}),(0,x.jsx)(`th`,{className:X.thRight,children:`QUOTA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`NET`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:a.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:a.total}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.auth>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.auth>0?`700`:`400`},children:a.auth}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.quota>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.quota>0?`700`:`400`},children:a.quota}),(0,x.jsx)(`td`,{className:a.rate_limit>0?X.cellFallback:X.cellRightMuted,style:a.rate_limit>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.rate_limit}),(0,x.jsx)(`td`,{className:a.network>0?X.cellFallback:X.cellRightMuted,style:a.network>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.network}),(0,x.jsx)(`td`,{className:a.unknown>0?X.cellFallback:X.cellRightMuted,style:a.unknown>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.unknown})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`AUTH/QUOTA are terminal (run aborts). RATE/NET/OTHER are non-terminal — the retry layer handles them.`})]}),i&&i.runsPresent>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROMPT CACHE`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS WITH CACHE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CREATE TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ RATIO`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SAVINGS`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:i.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:DT(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:DT(i.totalCreationTokens)}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.readRatio>=.7?`var(--green)`:i.readRatio>=.4?`var(--amber)`:`var(--rust)`},children:[(i.readRatio*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.totalSavingsUSD>0?`var(--green)`:`var(--text-2)`},children:ET(i.totalSavingsUSD)})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`Read ratio >= 70% is healthy. Lower ratios mean the cache keeps getting invalidated.`})]})]})})(),a&&a.length>2&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`PER ACTOR · `,a.length,` ACTORS`]}),(()=>{let e=[...a].sort((e,t)=>t.cost.totalCostUSD-e.cost.totalCostUSD),t=e[0]?.cost.totalCostUSD??0,n=e.reduce((e,t)=>e+t.cost.totalCostUSD,0);return(0,x.jsx)(`div`,{className:X.perActorList,children:e.map((e,r)=>{let i=t>0?e.cost.totalCostUSD/t*100:0,a=n>0?e.cost.totalCostUSD/n*100:0;return(0,x.jsxs)(`div`,{className:X.perActorRow,children:[(0,x.jsxs)(`div`,{className:X.perActorRank,children:[`#`,r+1]}),(0,x.jsx)(`div`,{className:X.perActorName,title:e.name,children:e.name}),(0,x.jsx)(`div`,{className:X.perActorBarTrack,"aria-hidden":`true`,children:(0,x.jsx)(`div`,{className:X.perActorBarFill,style:{width:`${i}%`}})}),(0,x.jsx)(`div`,{className:X.perActorCost,children:ET(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,DT(e.cost.totalTokens),` tok · `,a.toFixed(1),`%`]})]},e.actorId)})})})()]}),t&&n&&(t.totalCostUSD>0||n.totalCostUSD>0)&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`PER LEADER`}),(0,x.jsxs)(`div`,{className:X.perLeaderRow,children:[(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--vis)`},children:r||`Leader A`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,DT(t.totalTokens),` tok`]})]}),(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--eng)`},children:i||`Leader B`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,DT(n.totalTokens),` tok`]})]})]})]})]})})}var jT={card:`_card_mk5ry_1`,headerRow:`_headerRow_mk5ry_11`,title:`_title_mk5ry_18`,range:`_range_mk5ry_24`,legend:`_legend_mk5ry_28`,legendItem:`_legendItem_mk5ry_35`,legendSwatch:`_legendSwatch_mk5ry_41`,legendLabel:`_legendLabel_mk5ry_48`,legendValue:`_legendValue_mk5ry_52`},MT=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],NT={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},PT={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function FT(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function IT(e,t){let n=[];for(let r of e){if(r.type!==`personality_drift`||!r.data||r.leader!==void 0&&r.leader!==t)continue;let e=r.data.commander,i=r.data.turn;e&&typeof i==`number`&&n.push({turn:i,hexaco:e})}return n.sort((e,t)=>e.turn-t.turn)}function LT({events:e,actorName:t,baselineHexaco:n}){let r=FT(n),i=IT(e,t);if(i.length===0&&!r)return null;let a=r?[{turn:0,hexaco:r},...i]:i;if(a.length<2)return null;let o=a[0].turn,s=a[a.length-1].turn,c=Math.max(1,s-o),l=e=>6+68*(1-(Math.max(.05,Math.min(.95,e))-.05)/.9),u=e=>6+248*((e-o)/c);return(0,x.jsxs)(`div`,{className:jT.card,children:[(0,x.jsxs)(`div`,{className:jT.headerRow,children:[(0,x.jsx)(`span`,{className:jT.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:jT.range,children:[`turn `,o,` → `,s]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 260 80`,width:`100%`,height:80,role:`img`,"aria-label":`HEXACO trajectory for ${t}`,children:[(0,x.jsx)(`line`,{x1:6,y1:l(.5),x2:254,y2:l(.5),stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),MT.map(e=>{let t=a.map(t=>`${u(t.turn)},${l(t.hexaco[e])}`).join(` `);return(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:NT[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:jT.legend,children:MT.map(e=>(0,x.jsxs)(`span`,{className:jT.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:jT.legendSwatch,style:{"--trait-color":NT[e]}}),(0,x.jsx)(`span`,{className:jT.legendLabel,children:PT[e]}),(0,x.jsx)(`span`,{className:jT.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var RT={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},zT={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},BT=[`crisis`,`departments`,`decision`,`outcome`],VT=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function HT(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function UT(e){return e!==`quotes`}function WT(e){let t=[];for(let n of e??[])HT(n)&&!t.includes(n)&&t.push(n);return t}function GT(e){let t=WT(e.configuredSections),n=t.length>0?t:BT,r=n.filter(UT);for(let t of VT)t===`causality`&&!e.hasCausality||r.includes(t)||r.push(t);let i=e.hasQuotes?[`quotes`]:[],a=[`timeline`];return e.hasVerdict&&a.push(`verdict`),e.hasTrajectories&&a.push(`trajectory`),e.hasCost&&a.push(`cost`),e.hasToolbox&&a.push(`toolbox`),e.hasReferences&&a.push(`references`),{focusSections:n,eventSections:r,footerSections:i,artifacts:a}}var KT={section:`_section_36gyg_1`,header:`_header_36gyg_10`,kicker:`_kicker_36gyg_16`,winner:`_winner_36gyg_25`,headline:`_headline_36gyg_33`,divergence:`_divergence_36gyg_40`,body:`_body_36gyg_48`,bodyHeader:`_bodyHeader_36gyg_52`,nameA:`_nameA_36gyg_64`,nameB:`_nameB_36gyg_68`,statRow:`_statRow_36gyg_72`,statRowHead:`_statRowHead_36gyg_76`,statValueA:`_statValueA_36gyg_85`,statValueB:`_statValueB_36gyg_90`,statLabel:`_statLabel_36gyg_95`,bar:`_bar_36gyg_99`,barLeftWrap:`_barLeftWrap_36gyg_105`,barRightWrap:`_barRightWrap_36gyg_111`,barLeftFill:`_barLeftFill_36gyg_115`,barRightFill:`_barRightFill_36gyg_122`,viewWrap:`_viewWrap_36gyg_129`,viewBtn:`_viewBtn_36gyg_134`,empty:`_empty_36gyg_147`},qT=[{key:`population`,label:`Population`,format:`int`},{key:`morale`,label:`Morale`,format:`percent`},{key:`food`,label:`Food (mo)`,format:`decimal`},{key:`power`,label:`Power (kW)`,format:`decimal`},{key:`modules`,label:`Modules`,format:`decimal`},{key:`science`,label:`Science`,format:`int`},{key:`tools`,label:`Tools Forged`,format:`int`}];function JT(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function YT({a:e,b:t,winner:n}){let r=Math.max(Math.abs(e),Math.abs(t),1),i=Math.max(0,e/r*100),a=Math.max(0,t/r*100),o=n===`a`?`var(--vis)`:`var(--border-hl)`,s=n===`b`?`var(--eng)`:`var(--border-hl)`;return(0,x.jsxs)(`div`,{className:KT.bar,children:[(0,x.jsx)(`div`,{className:KT.barLeftWrap,children:(0,x.jsx)(`div`,{className:KT.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:KT.barRightWrap,children:(0,x.jsx)(`div`,{className:KT.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function XT(e){let t=e.verdict;if(t?.mode===`cohort`)return null;let n=t?.winnerName||``,r=t?.headline||t?.summary||``,i=t?.keyDivergence||``,a=t?.finalStats?.a,o=t?.finalStats?.b,s=vn(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:yn(e),a:e.a,b:e.b,text:t=>bn(t,e.format,e.currency),better:e.better})),{key:`tools`,label:`Tools Forged`,a:Number(a.tools??0),b:Number(o.tools??0),text:e=>JT(e??0,`int`)}]:qT.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>JT(t??0,e.format)})):[],l=e.onViewFullVerdict??(()=>{typeof document<`u`&&document.getElementById(`verdict`)?.scrollIntoView({behavior:`smooth`,block:`start`})});return(0,x.jsxs)(`section`,{"aria-label":`Run summary`,className:KT.section,children:[(0,x.jsxs)(`div`,{className:KT.header,children:[(0,x.jsx)(`div`,{className:KT.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:KT.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:KT.headline,children:r}),i&&(0,x.jsx)(`div`,{className:KT.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:KT.body,children:[(0,x.jsxs)(`div`,{className:KT.bodyHeader,children:[(0,x.jsx)(`span`,{className:KT.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:KT.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Sn(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:KT.statRow,children:[(0,x.jsxs)(`div`,{className:KT.statRowHead,children:[(0,x.jsx)(`span`,{className:KT.statValueA,style:{"--val-color":r===`a`?`var(--vis)`:`var(--text-2)`,"--val-weight":r===`a`?`700`:`500`},children:e.text(t)}),(0,x.jsx)(`span`,{className:KT.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:KT.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(YT,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:KT.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:KT.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:KT.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var ZT={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function QT(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function $T(e,t){switch(t){case`morale`:return e.morale;case`population`:return e.population;case`deaths`:return e.deaths;case`tools`:return e.tools;case`turn`:return e.turn}}function eE(e,t,n){let r=n??ZT[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>$T(e,t))].sort((e,t)=>e-t),a=QT(i,.25),o=QT(i,.75),s=QT(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=$T(n,t);r===`higher`?e>o?c.push(n):e<a?u.push(n):l.push(n):e<a?c.push(n):e>o?u.push(n):l.push(n)}return{metric:t,direction:r,top:c,middle:l,bottom:u,median:s}}function tE(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>i:r<i},i=(e,i)=>{let a=!1;for(let o of t){if(!n(e,i,o))return!1;r(e,i,o)&&(a=!0)}return a},a={};for(let t of e)a[t.id]=0;for(let t of e)for(let n of e)t.id!==n.id&&i(t,n)&&a[t.id]++;let o=[];for(let t of e){let n=!1;for(let r of e)if(t.id!==r.id&&i(r,t)){n=!0;break}n||o.push(t.id)}return{frontIds:o,dominationCount:a}}function nE(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=QT([...e.map(e=>$T(e,t))].sort((e,t)=>e-t),.5),r={},i=ZT[t]===`higher`?1:-1;for(let a of e){let e=($T(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function rE(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var iE={panel:`_panel_1c1w0_1`,header:`_header_1c1w0_12`,heading:`_heading_1c1w0_18`,subhead:`_subhead_1c1w0_26`,section:`_section_1c1w0_34`,sectionTitle:`_sectionTitle_1c1w0_40`,sectionHint:`_sectionHint_1c1w0_51`,quartileGrid:`_quartileGrid_1c1w0_59`,quartileBlock:`_quartileBlock_1c1w0_65`,metricHead:`_metricHead_1c1w0_75`,metricLabel:`_metricLabel_1c1w0_82`,metricMedian:`_metricMedian_1c1w0_89`,quartileRow:`_quartileRow_1c1w0_96`,quartileTag:`_quartileTag_1c1w0_102`,actorList:`_actorList_1c1w0_114`,actorPill:`_actorPill_1c1w0_124`,actorPillTop:`_actorPillTop_1c1w0_134`,actorPillBottom:`_actorPillBottom_1c1w0_140`,actorListEmpty:`_actorListEmpty_1c1w0_146`,paretoList:`_paretoList_1c1w0_153`,paretoItem:`_paretoItem_1c1w0_162`,paretoName:`_paretoName_1c1w0_176`,paretoArchetype:`_paretoArchetype_1c1w0_181`,paretoDominates:`_paretoDominates_1c1w0_185`,medianTable:`_medianTable_1c1w0_191`,medianHeaderRow:`_medianHeaderRow_1c1w0_201`,medianBodyRow:`_medianBodyRow_1c1w0_202`,medianActorCol:`_medianActorCol_1c1w0_215`,medianActorName:`_medianActorName_1c1w0_223`,medianActorArchetype:`_medianActorArchetype_1c1w0_228`,medianMetricCol:`_medianMetricCol_1c1w0_233`,deltaPositive:`_deltaPositive_1c1w0_252`,deltaNegative:`_deltaNegative_1c1w0_256`,deltaNeutral:`_deltaNeutral_1c1w0_260`},aE=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],oE=[`morale`,`population`,`deaths`,`tools`],sE=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function cE({state:e}){let t=(0,b.useMemo)(()=>YC(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>aE.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:eE(t,e)})),[t]),r=(0,b.useMemo)(()=>tE(t,oE),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>sE.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:nE(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:iE.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:iE.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:iE.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:iE.subhead,children:[t.length,` actors · ranked across morale, population, deaths, and forged tools. A single winner doesn't generalize past two — this is the cohort-aware reading.`]})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:iE.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:iE.quartileBlock,children:[(0,x.jsxs)(`div`,{className:iE.metricHead,children:[(0,x.jsx)(`span`,{className:iE.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:iE.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:iE.sectionHint,children:[i.length,` actor`,i.length===1?``:`s`,` not dominated by any other across all four metrics. Off-front actors are strictly worse than someone on it.`]}),(0,x.jsx)(`ul`,{className:iE.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:iE.paretoItem,children:[(0,x.jsx)(`span`,{className:iE.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:iE.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:iE.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:iE.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:iE.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:iE.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:iE.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:iE.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:iE.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:iE.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:iE.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:iE.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?iE.deltaPositive:n<0?iE.deltaNegative:iE.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${iE.medianMetricCol} ${r}`,role:`cell`,children:[rE(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function lE(e){switch(e){case`conservative_success`:return`var(--green)`;case`risky_success`:return`var(--amber)`;case`conservative_failure`:return`var(--rust-dim, var(--rust))`;case`risky_failure`:return`var(--rust)`;default:return`var(--text-3)`}}function uE(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var dE=[{id:`population`,label:`Population`},{id:`morale`,label:`Morale`},{id:`foodMonthsReserve`,label:`Food`,unit:`mo`},{id:`powerKw`,label:`Power`,unit:`kW`},{id:`infrastructureModules`,label:`Modules`},{id:`scienceOutput`,label:`Science`}];function fE(e,t){let n=[],r=new Set;for(let i of e){let e=i.data?.metrics;if(!e||typeof i.turn!=`number`)continue;let a=e[t];if(typeof a==`number`){if(r.has(i.turn)){let e=n.findIndex(e=>e.turn===i.turn);e>=0&&(n[e]={turn:i.turn,value:a})}else r.add(i.turn),n.push({turn:i.turn,value:a})}}return n}function pE(e,t,n){let r=t??e.actorIds[0],i=n??e.actorIds[1],a=r?e.actors[r]?.events:void 0,o=i?e.actors[i]?.events:void 0;return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?fE(a,e.id):[],b:o?fE(o,e.id):[]}))}function mE(e,t){let n=e.actorIds.map((n,r)=>{let i=e.actors[n]?.events;return{actorId:n,idx:r,name:e.actors[n]?.leader?.name??n,color:t(r),events:i}});return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:[],b:[],series:n.map(t=>({actorId:t.actorId,name:t.name,color:t.color,points:t.events?fE(t.events,e.id):[]}))}))}function hE(e){return e.map(([e,t])=>{let n=t.a.events.get(0),r=t.b.events.get(0);return{turn:e,time:t.a.time??t.b.time,diverged:uE(n?.title,r?.title)===`divergent`,a:{title:n?.title,outcome:n?.outcome,category:n?.category},b:{title:r?.title,outcome:r?.outcome,category:r?.category}}})}var gE={section:`_section_5eeou_1`,title:`_title_5eeou_10`,grid:`_grid_5eeou_20`,cell:`_cell_5eeou_26`,diverged:`_diverged_5eeou_40`,cellHead:`_cellHead_5eeou_45`,cellTurn:`_cellTurn_5eeou_53`,badge:`_badge_5eeou_57`,legend:`_legend_5eeou_71`},_E={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},vE={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function yE(e,t=!1){return e?t?vE[e]??`·`:_E[e]??e.replace(/_/g,` `).toUpperCase():`·`}function bE({outcome:e,sideColor:t,compact:n}){let r=lE(e);return(0,x.jsx)(`div`,{className:gE.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:yE(e,n)})}function xE(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=My(Py);if(t.length===0)return null;let o=e=>{i?i(e):typeof document<`u`&&document.getElementById(`turn-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})};return(0,x.jsxs)(`section`,{"aria-label":`Run timeline strip`,className:gE.section,children:[(0,x.jsx)(`div`,{className:gE.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:gE.grid,style:{"--turn-count":String(t.length)},children:t.map(e=>(0,x.jsxs)(`button`,{type:`button`,role:`listitem`,onClick:()=>o(e.turn),"aria-label":`Jump to turn ${e.turn}${e.time?`, time `+e.time:``}${e.diverged?`, divergent`:``}`,className:[gE.cell,e.diverged?gE.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:gE.cellHead,children:[(0,x.jsxs)(`span`,{className:gE.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(bE,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(bE,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:gE.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var SE={section:`_section_1aa2r_1`,sectionHeader:`_sectionHeader_1aa2r_10`,sectionTitle:`_sectionTitle_1aa2r_17`,legend:`_legend_1aa2r_26`,legendA:`_legendA_1aa2r_32`,legendB:`_legendB_1aa2r_37`,grid:`_grid_1aa2r_42`,card:`_card_1aa2r_48`,cardHeader:`_cardHeader_1aa2r_58`,cardLabel:`_cardLabel_1aa2r_65`,cardRange:`_cardRange_1aa2r_70`,cardFooter:`_cardFooter_1aa2r_74`,lastA:`_lastA_1aa2r_81`,lastB:`_lastB_1aa2r_86`,cardFooterCohort:`_cardFooterCohort_1aa2r_94`,lastCohort:`_lastCohort_1aa2r_103`,legendCohort:`_legendCohort_1aa2r_112`,legendCohortEntry:`_legendCohortEntry_1aa2r_122`,legendCohortSlot:`_legendCohortSlot_1aa2r_141`,lastCohortSlot:`_lastCohortSlot_1aa2r_153`};function CE(e,t){return t===`mo`||t===`kW`?`${e.toFixed(1)}${t?` `+t:``}`:e>0&&e<1?`${Math.round(e*100)}%`:`${Math.round(e)}${t?` `+t:``}`}function wE(e){let t=e,n=``;do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function TE({metric:e,sideAColor:t,sideBColor:n}){let r=Array.isArray(e.series)&&e.series.length>=2,i=r?e.series.flatMap(e=>e.points):[...e.a,...e.b];if(i.length===0)return null;let a=1/0,o=-1/0,s=1/0,c=-1/0;for(let e of i)e.turn<a&&(a=e.turn),e.turn>o&&(o=e.turn),e.value<s&&(s=e.value),e.value>c&&(c=e.value);let l=Math.max(1e-6,c-s),u=Math.max(1,o-a),d=e=>4+192*((e-a)/u),f=e=>6+38*(1-(e-s)/l);if(r)return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline (${e.series.length} actors)`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),e.series.map(e=>{let t=e.points.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `);return t?(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:e.color,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.78,children:(0,x.jsx)(`title`,{children:e.name})},e.actorId):null})]}),(0,x.jsx)(`div`,{className:SE.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=wE(n);return(0,x.jsxs)(`span`,{className:SE.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:SE.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:CE(r,e.unit)]},t.actorId)})})]});let p=e.a.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),m=e.b.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),h=e.a[e.a.length-1]?.value,g=e.b[e.b.length-1]?.value;return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),p&&(0,x.jsx)(`polyline`,{points:p,fill:`none`,stroke:t,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9}),m&&(0,x.jsx)(`polyline`,{points:m,fill:`none`,stroke:n,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9})]}),(0,x.jsxs)(`div`,{className:SE.cardFooter,children:[(0,x.jsx)(`span`,{className:SE.lastA,children:h==null?`·`:CE(h,e.unit)}),(0,x.jsx)(`span`,{className:SE.lastB,children:g==null?`·`:CE(g,e.unit)})]})]})}function EE(e){let{metrics:t,leaderAName:n,leaderBName:r}=e,i=e.sideAColor??`var(--vis)`,a=e.sideBColor??`var(--eng)`,o=t.length>0&&Array.isArray(t[0].series)&&t[0].series.length>=2,s=t.filter(e=>o?(e.series??[]).some(e=>e.points.length>0):e.a.length>0||e.b.length>0);if(s.length===0)return null;let c={"--side-a-color":i,"--side-b-color":a};return(0,x.jsxs)(`section`,{"aria-label":`Metric sparklines`,className:SE.section,style:c,children:[(0,x.jsxs)(`div`,{className:SE.sectionHeader,children:[(0,x.jsx)(`span`,{className:SE.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:SE.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:SE.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:SE.legendCohortSlot,"aria-hidden":`true`,children:wE(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:SE.legend,children:[(0,x.jsx)(`span`,{className:SE.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:SE.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${SE.grid}`,children:s.map(e=>(0,x.jsx)(TE,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function DE(e,t){let[n,r]=(0,b.useState)(()=>typeof window<`u`?window.matchMedia(e).matches:t);return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=window.matchMedia(e),n=()=>r(t.matches);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),n}function OE(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=DE(`(min-width: 1024px)`,!0),o=DE(`(max-width: 767.98px)`,!1);(0,b.useEffect)(()=>{if(typeof window>`u`||t.length===0)return;let e=t.map(e=>document.getElementById(e.id)).filter(e=>e!=null);if(e.length===0)return;let r=new IntersectionObserver(e=>{let t=e.filter(e=>e.isIntersecting).sort((e,t)=>t.intersectionRatio-e.intersectionRatio);t[0]&&i(t[0].target.id)},{root:n??null,rootMargin:`-80px 0px -60% 0px`,threshold:[0,.25,.5,.75,1]});return e.forEach(e=>r.observe(e)),()=>r.disconnect()},[t,n]);let s=(0,b.useMemo)(()=>({display:`block`,padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:700,letterSpacing:`0.04em`,textTransform:`uppercase`,color:`var(--text-3)`,textDecoration:`none`,borderRadius:3}),[]);return t.length===0?null:a?(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{position:`sticky`,top:12,alignSelf:`flex-start`,width:160,marginLeft:12,padding:`10px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:8,maxHeight:`calc(100vh - 40px)`,overflowY:`auto`},children:t.map(e=>(0,x.jsx)(`a`,{href:`#${e.id}`,style:{...s,color:r===e.id?`var(--amber)`:`var(--text-3)`,background:r===e.id?`color-mix(in srgb, var(--bg-canvas) 80%, var(--amber) 20%)`:`transparent`},children:e.label},e.id))}):(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{background:`var(--bg-panel)`,borderBottom:`1px solid var(--border)`,padding:o?`8px 10px`:`6px 8px`,marginBottom:12,overflowX:`auto`,WebkitOverflowScrolling:`touch`,display:`flex`,gap:o?6:4,flexShrink:0},children:t.map(e=>{let t=r===e.id,n={...s,flexShrink:0,padding:`8px 12px`,borderRadius:4,border:`1px solid ${t?`var(--amber)`:`var(--border)`}`,background:t?`var(--amber)`:`var(--bg-card)`,color:t?`var(--bg-deep)`:`var(--text-3)`},i={...s,flexShrink:0,color:t?`var(--amber)`:`var(--text-3)`,borderBottom:t?`2px solid var(--amber)`:`2px solid transparent`};return(0,x.jsx)(`a`,{href:`#${e.id}`,style:o?n:i,children:e.label},e.id)})})}var Z={empty:`_empty_1pipo_1`,emptyMsg:`_emptyMsg_1pipo_8`,emptyMsgRunning:`_emptyMsgRunning_1pipo_15`,emptySpinner:`_emptySpinner_1pipo_23`,reportEmptySpinnerRotate:`_reportEmptySpinnerRotate_1pipo_1`,layout:`_layout_1pipo_43`,scroll:`_scroll_1pipo_50`,tldr:`_tldr_1pipo_58`,tldrTopRow:`_tldrTopRow_1pipo_69`,tldrTag:`_tldrTag_1pipo_76`,tldrHeadline:`_tldrHeadline_1pipo_85`,tldrSub:`_tldrSub_1pipo_92`,tldrStats:`_tldrStats_1pipo_99`,tldrStatLabel:`_tldrStatLabel_1pipo_108`,tldrStatValue:`_tldrStatValue_1pipo_113`,headerRow:`_headerRow_1pipo_118`,headerTitle:`_headerTitle_1pipo_127`,jumpBtn:`_jumpBtn_1pipo_134`,actorPairPicker:`_actorPairPicker_1pipo_149`,actorPairPickerLabel:`_actorPairPickerLabel_1pipo_164`,actorPairPickerToggle:`_actorPairPickerToggle_1pipo_172`,actorPairPickerToggleText:`_actorPairPickerToggleText_1pipo_209`,actorPairPickerSelect:`_actorPairPickerSelect_1pipo_218`,actorPairPickerVs:`_actorPairPickerVs_1pipo_237`,actorPairPickerHint:`_actorPairPickerHint_1pipo_245`,jumpInlineBtn:`_jumpInlineBtn_1pipo_251`,trajectoryGrid:`_trajectoryGrid_1pipo_262`,costBar:`_costBar_1pipo_269`,costLabel:`_costLabel_1pipo_282`,costAmount:`_costAmount_1pipo_289`,costMeta:`_costMeta_1pipo_295`,costBtn:`_costBtn_1pipo_299`,turnSection:`_turnSection_1pipo_312`,diverged:`_diverged_1pipo_321`,turnHeader:`_turnHeader_1pipo_326`,turnTitle:`_turnTitle_1pipo_333`,turnEventCount:`_turnEventCount_1pipo_340`,turnHeaderRight:`_turnHeaderRight_1pipo_348`,divergenceFlag:`_divergenceFlag_1pipo_354`,eventGrid:`_eventGrid_1pipo_367`,eventGridSpaced:`_eventGridSpaced_1pipo_373`,footerGrid:`_footerGrid_1pipo_380`,nActorEventTrack:`_nActorEventTrack_1pipo_387`,nActorEventTrackSpaced:`_nActorEventTrackSpaced_1pipo_397`,nActorFooterTrack:`_nActorFooterTrack_1pipo_408`,summarySection:`_summarySection_1pipo_426`,summaryLabel:`_summaryLabel_1pipo_430`,summaryVerdictWrap:`_summaryVerdictWrap_1pipo_442`,aboutDetails:`_aboutDetails_1pipo_446`,aboutSummary:`_aboutSummary_1pipo_457`,aboutBody:`_aboutBody_1pipo_465`,aboutBlockTitle:`_aboutBlockTitle_1pipo_472`,aboutChips:`_aboutChips_1pipo_478`,aboutChip:`_aboutChip_1pipo_478`,aboutChipNeutral:`_aboutChipNeutral_1pipo_494`,eventCard:`_eventCard_1pipo_504`,eventHeading:`_eventHeading_1pipo_511`,eventSubLabel:`_eventSubLabel_1pipo_519`,eventAwaiting:`_eventAwaiting_1pipo_526`,eventTitle:`_eventTitle_1pipo_531`,categoryPill:`_categoryPill_1pipo_538`,emergentPill:`_emergentPill_1pipo_548`,eventDescription:`_eventDescription_1pipo_556`,eventDecision:`_eventDecision_1pipo_564`,eventOutcomeRow:`_eventOutcomeRow_1pipo_571`,eventPolicies:`_eventPolicies_1pipo_578`,eventDetails:`_eventDetails_1pipo_584`,eventDetailsSummary:`_eventDetailsSummary_1pipo_588`,eventRationale:`_eventRationale_1pipo_596`,deptList:`_deptList_1pipo_606`,deptItem:`_deptItem_1pipo_613`,deptHead:`_deptHead_1pipo_621`,deptName:`_deptName_1pipo_627`,deptMeta:`_deptMeta_1pipo_632`,deptSummary:`_deptSummary_1pipo_638`,footerCard:`_footerCard_1pipo_644`,footerDetails:`_footerDetails_1pipo_651`,footerDetailsLast:`_footerDetailsLast_1pipo_655`,footerSummary:`_footerSummary_1pipo_659`,systemsRow:`_systemsRow_1pipo_667`,systemItem:`_systemItem_1pipo_676`,systemKey:`_systemKey_1pipo_680`,systemValue:`_systemValue_1pipo_684`,reactionsList:`_reactionsList_1pipo_689`,reactionItem:`_reactionItem_1pipo_696`,reactionHead:`_reactionHead_1pipo_704`,reactionName:`_reactionName_1pipo_711`,moodPill:`_moodPill_1pipo_716`,reactionQuote:`_reactionQuote_1pipo_726`,reactionRole:`_reactionRole_1pipo_731`,forkNotice:`_forkNotice_1pipo_737`};function kE(e,t){let[n,r]=(0,b.useState)(()=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:n===`1`}catch{return t}});return[n,(0,b.useCallback)(t=>{r(t);try{window.localStorage.setItem(e,t?`1`:`0`)}catch{}},[e])]}function AE(){return{events:new Map,reactions:[],totalReactions:0}}function jE(e,t,n){let r=e.events.get(t);return r||(r={eventIndex:t,totalEvents:n,depts:{}},e.events.set(t,r)),n>r.totalEvents&&(r.totalEvents=n),r}function ME(e){let t=new Map;if(!e)return t;let n=new Map;for(let r of e){let e=r.turn;if(typeof e!=`number`)continue;let i=t.get(e);i||(i=AE(),t.set(e,i));let a=Number(r.data?.eventIndex??0),o=Number(r.data?.totalEvents??1);if(r.type===`turn_start`&&(r.data?.time!=null&&(i.time=r.data.time),r.data?.metrics&&(i.metrics=r.data.metrics),r.data?.title&&r.data?.title!==`Director generating...`&&!r.data?.totalEvents)){let e=jE(i,0,1);e.title=r.data.title,e.category=r.data.category,e.emergent=r.data.emergent,e.description=r.data.crisis||r.data.turnSummary||``}if(r.type===`event_start`){let e=jE(i,a,o);e.title=r.data?.title,e.category=r.data?.category,e.emergent=r.data?.emergent,e.description=r.data?.description||r.data?.turnSummary||``}if(r.type===`decision_made`&&n.set(a,{decision:String(r.data?.decision||``),rationale:String(r.data?.rationale||``),policies:Array.isArray(r.data?.selectedPolicies)?r.data.selectedPolicies.map(e=>typeof e==`string`?e:JSON.stringify(e)):[]}),r.type===`outcome`){let e=jE(i,a,o);e.outcome=String(r.data?.outcome||``);let t=n.get(a);t&&(e.decision=t.decision,e.rationale=t.rationale,e.policies=t.policies,n.delete(a))}if(r.type===`specialist_done`){let e=jE(i,a,o),t=r.data?.department;if(t){let n=(r.data?._filteredTools||[]).filter(e=>e?.approved!==!1).length;e.depts[t]={summary:r.data?.summary||``,tools:n,citations:Number(r.data?.citations??0),citationList:r.data?.citationList||[]}}}r.type===`agent_reactions`&&(i.reactions=(r.data?.reactions||[]).slice(0,3),i.totalReactions=Number(r.data?.totalReactions??0))}return t}function NE(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function PE({state:e,verdict:t,shownRun:n,reportSections:r}){let i=h_(),a=D_(),[o,s]=kE(`paracosm-reports-refs-open`,!1),[c,l]=kE(`paracosm-reports-tools-open`,!1),[u,d]=(0,b.useState)(!1),{state:f,dispatch:p}=Gn(),m=nA(),h=iA(),g=Lm(),[_,v]=(0,b.useState)(null),y=f.parent,S=Qk(),C=eA(),w=y?.metadata?.scenario,T=typeof w?.id==`string`&&w.id!==S.id,E=(0,b.useCallback)(t=>!y||e.isRunning||!C||T?!1:bT(y,t),[y,e.isRunning,C,T]),D=(0,b.useCallback)(async e=>{v(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;p({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=yT(e.parentArtifact),r=e.seedOverride??e.parentArtifact.metadata.seed??42;try{let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:[e.leader],turns:n,seed:r,captureSnapshots:!0,customEvents:e.customEvents,forkFrom:{parentArtifact:_T(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));p({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));k(window,a.visitorId),h(),m(`studio`)}catch(e){p({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[p,m,h]),O=e.actorIds[0]??null,A=e.actorIds[1]??null,[j,ee]=(0,b.useState)(O),[te,M]=(0,b.useState)(A);(0,b.useEffect)(()=>{j&&!e.actorIds.includes(j)&&ee(O),te&&!e.actorIds.includes(te)&&M(A)},[e.actorIds,j,te,O,A]);let N=j??O,ne=te??A,P=e.actorIds.length>2,[re,ie]=(0,b.useState)(!P);(0,b.useEffect)(()=>{ie(!P)},[P]);let F=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,ME(e.actors[n]?.events));return t},[e]),I=(0,b.useMemo)(()=>{let e=N&&F.get(N)||new Map,t=ne&&F.get(ne)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??AE(),b:t.get(n)??AE()}])},[F,N,ne]),ae=(0,b.useMemo)(()=>{if(!P)return[];let t=new Set;for(let e of F.values())for(let n of e.keys())t.add(n);return[...t].sort((e,t)=>e-t).map(t=>{let n=new Map;for(let r of e.actorIds)n.set(r,F.get(r)?.get(t)??AE());return[t,n]})},[P,F,e.actorIds]),oe=N,se=ne,ce=oe?e.actors[oe]:null,le=se?e.actors[se]:null,L=ce?.leader?.name||`Leader A`,ue=le?.leader?.name||`Leader B`,de=(ce?.events.some(e=>e.type===`personality_drift`)??!1)||(le?.events.some(e=>e.type===`personality_drift`)??!1),fe=I.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),R=I.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),z=(0,b.useMemo)(()=>GT({configuredSections:r,hasQuotes:fe,hasCausality:R,hasVerdict:!!t,hasTrajectories:de,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:a.list.length>0,hasReferences:i.list.length>0}),[r,fe,R,t,de,e.cost,a.list.length,i.list.length]),pe=(0,b.useMemo)(()=>hE(I),[I]),me=(0,b.useMemo)(()=>pE(e,N,ne),[e,N,ne]),he=(0,b.useMemo)(()=>P?mE(e,Pe):null,[P,e]),ge=(0,b.useMemo)(()=>{let e=[];pe.length>0&&e.push({id:`strip`,label:`Strip`}),me.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),de&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of I)e.push({id:`turn-${t}`,label:`Turn ${t}`});return a.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),i.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,pe.length,me,de,I,a.list.length,i.list.length]),_e=(0,b.useRef)(null),B=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{B.current&&_e.current&&I.length>0&&_e.current.scrollTo({top:_e.current.scrollHeight,behavior:`smooth`})},[I.length]),!(ce?.events.length??0)&&!(le?.events.length??0)?e.isRunning?(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsxs)(`div`,{className:`${Z.emptyMsg} ${Z.emptyMsgRunning??``}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:Z.emptySpinner,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`Awaiting first turn — the report populates once the kernel reports an event.`})]})}):(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsx)(`div`,{className:Z.emptyMsg,children:`Run a simulation first to see the report.`})}):(0,x.jsxs)(`div`,{className:`reports-layout ${Z.layout}`,children:[(0,x.jsxs)(`div`,{ref:_e,onScroll:()=>{let e=_e.current;e&&(B.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[C&&T&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,w?.name??w?.id,`, and a fork runs in its parent's scenario. Switch to `,w?.name??w?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&I.length===0)return null;let i=I.length,a=I[I.length-1],o=I[0],s=(e,t)=>{let n=e?.[t];return typeof n==`number`?n:0},c=s(a?.[1]?.a?.metrics,`population`),l=s(a?.[1]?.b?.metrics,`population`),u=s(a?.[1]?.a?.metrics,`morale`),d=s(a?.[1]?.b?.metrics,`morale`),f=s(o?.[1]?.a?.metrics,`population`)||c,p=s(o?.[1]?.b?.metrics,`population`)||l,m=ce?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=le?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,g=[{label:`Turns`,value:String(i)},{label:`Final pop`,value:`A ${c}${c<f?` (↓${f-c})`:``} · B ${l}${l<p?` (↓${p-l})`:``}`,tone:c+l<f+p?`neg`:`neutral`},{label:`Final morale`,value:`A ${Math.round(u*100)}% · B ${Math.round(d*100)}%`,tone:Math.min(u,d)<.3?`neg`:Math.min(u,d)>=.6?`pos`:`neutral`},{label:`Tools forged`,value:`A ${m} · B ${h}`}];return(0,x.jsxs)(`div`,{className:Z.tldr,children:[(0,x.jsxs)(`div`,{className:Z.tldrTopRow,children:[(0,x.jsx)(`span`,{className:Z.tldrTag,children:`TL;DR`}),n?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[n,` wins`]}):i>0?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[`Run `,i,` turn`,i===1?``:`s`,` — verdict pending`]}):null,r&&(0,x.jsx)(`span`,{className:Z.tldrSub,children:r})]}),(0,x.jsx)(`div`,{className:Z.tldrStats,children:g.map(e=>(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:Z.tldrStatLabel,children:[e.label,`:`]}),(0,x.jsx)(`span`,{className:Z.tldrStatValue,style:{"--tone-color":NE(e.tone)},children:e.value})]},e.label))})]})})(),(0,x.jsxs)(`div`,{className:Z.headerRow,children:[(0,x.jsx)(`h2`,{className:Z.headerTitle,children:`Turn-by-Turn Report`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=document.getElementById(`summary`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},className:Z.jumpBtn,children:t?`↓ See verdict + full summary`:`↓ Jump to summary`})]}),P&&(0,x.jsxs)(`div`,{className:Z.actorPairPicker,role:`region`,"aria-label":`Pair focus toggle`,children:[(0,x.jsxs)(`label`,{className:Z.actorPairPickerToggle,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:re,onChange:e=>ie(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),re?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:N??``,onChange:e=>ee(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:Z.actorPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right side actor`,className:Z.actorPairPickerSelect,value:ne??``,onChange:e=>M(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===N,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`strip + metrics + trajectory show this pair only · turn-by-turn below shows all `,e.actorIds.length,` actors`]})]}):(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`Showing all `,e.actorIds.length,` actors. Toggle on to focus on a 2-actor head-to-head view in the strip, sparklines, and trajectory cards.`]})]}),(!P||re)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(xE,{turns:pe,leaderAName:L,leaderBName:ue})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!P||re?(0,x.jsx)(EE,{metrics:me,leaderAName:L,leaderBName:ue}):he&&(0,x.jsx)(EE,{metrics:he,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[de&&re&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(LT,{events:ce?.events??[],actorName:L,baselineHexaco:ce?.leader?.hexaco}),(0,x.jsx)(LT,{events:le?.events??[],actorName:ue,baselineHexaco:le?.leader?.hexaco})]}),de&&!re&&(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:e.actorIds.map(t=>{let n=e.actors[t];return n?.events.length?(0,x.jsx)(LT,{events:n.events,actorName:n.leader?.name||t,baselineHexaco:n.leader?.hexaco},t):null})})]}),e.cost&&e.cost.llmCalls>0&&(0,x.jsxs)(`div`,{className:Z.costBar,children:[(0,x.jsx)(`span`,{className:Z.costLabel,children:`Run cost`}),(0,x.jsxs)(`span`,{className:Z.costAmount,children:[`$`,e.cost.totalCostUSD<.01?e.cost.totalCostUSD.toFixed(4):e.cost.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:Z.costMeta,children:[`· `,e.cost.llmCalls,` LLM calls · `,(e.cost.totalTokens/1e3).toFixed(1),`k tokens`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>d(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),u&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(AT,{combined:e.cost,leaderA:(oe?e.costByActor[oe]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(se?e.costByActor[se]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ce?.leader?.name,leaderBName:le?.leader?.name,actors:P?e.actorIds.map(t=>({actorId:t,name:e.actors[t]?.leader?.name||t,cost:e.costByActor[t]??{totalTokens:0,totalCostUSD:0,llmCalls:0}})):void 0,onClose:()=>d(!1)}),!P&&I.map(([e,t])=>{let n=t.a,r=t.b,i=n.time||r.time||`?`,a=Math.max(...[...n.events.values()].map(e=>e.totalEvents),...[...r.events.values()].map(e=>e.totalEvents),1),o=n.events.get(0)?.title,s=r.events.get(0)?.title,c=!!(o&&s&&o!==s);return(0,x.jsxs)(`section`,{id:`turn-${e}`,className:[Z.turnSection,c?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,e,` — Y`,i,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,c?Z.diverged:``].filter(Boolean).join(` `),children:c?`DIVERGENT`:`SHARED`}),E(e)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(e),"aria-label":`Fork at ${g.time} ${e}`,children:[`↳ Fork at `,g.Time,` `,e]})]})]}),Array.from({length:a}).map((e,t)=>(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${t<a-1?Z.eventGridSpaced:Z.eventGrid}`,children:[(0,x.jsx)(IE,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:L,sideColor:`var(--vis)`,sections:z.eventSections}),(0,x.jsx)(IE,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:ue,sideColor:`var(--eng)`,sections:z.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(LE,{data:n,name:L,sideColor:`var(--vis)`,showQuotes:z.footerSections.includes(`quotes`)}),(0,x.jsx)(LE,{data:r,name:ue,sideColor:`var(--eng)`,showQuotes:z.footerSections.includes(`quotes`)})]})]},e)}),P&&ae.map(([t,n])=>{let r=[],i,a=1;for(let t of e.actorIds){let e=n.get(t);if(!e)continue;i??=e.time;for(let t of e.events.values())t.totalEvents>a&&(a=t.totalEvents);let o=e.events.get(0)?.title;o&&r.push(o)}let o=new Set(r).size>1,s=i??`?`;return(0,x.jsxs)(`section`,{id:`turn-${t}`,className:[Z.turnSection,o?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,t,` — Y`,s,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,o?Z.diverged:``].filter(Boolean).join(` `),children:o?`DIVERGENT`:`SHARED`}),E(t)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(t),"aria-label":`Fork at ${g.time} ${t}`,children:[`↳ Fork at `,g.Time,` `,t]})]})]}),Array.from({length:a}).map((t,r)=>(0,x.jsx)(`div`,{className:r<a-1?Z.nActorEventTrackSpaced:Z.nActorEventTrack,children:e.actorIds.map((t,i)=>{let o=n.get(t)?.events.get(r),s=e.actors[t]?.leader?.name??t;return(0,x.jsx)(IE,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:z.eventSections},t)})},r)),(0,x.jsx)(`div`,{className:Z.nActorFooterTrack,children:e.actorIds.map((t,r)=>{let i=n.get(t);if(!i)return null;let a=e.actors[t]?.leader?.name??t;return(0,x.jsx)(LE,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:z.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:a.list.length>0&&(0,x.jsxs)(`details`,{open:c,onToggle:e=>{let t=e.currentTarget.open;t&&!c&&B_({name:`forge_toolbox_open`,from:`reports`}),l(t)},className:K.pageFold,children:[(0,x.jsx)(`summary`,{className:K.pageFoldSummary,children:`FORGED TOOLBOX`}),(0,x.jsx)(Pb,{inPage:!0})]})}),(0,x.jsxs)(`section`,{id:`summary`,className:Z.summarySection,children:[(0,x.jsx)(`div`,{className:Z.summaryLabel,children:`Run Summary · Verdict · Winner`}),(0,x.jsx)(XT,{verdict:t,leaderAName:L,leaderBName:ue}),(0,x.jsx)(cE,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(jn,{verdict:t,shownRun:n})})]}),(0,x.jsx)(`section`,{id:`references`,children:i.list.length>0&&(0,x.jsx)(hC,{registry:i,title:`References`,collapsible:!0,defaultOpen:o,onToggle:s})}),(0,x.jsxs)(`details`,{className:Z.aboutDetails,children:[(0,x.jsx)(`summary`,{className:Z.aboutSummary,children:`What's in this report?`}),(0,x.jsxs)(`div`,{className:Z.aboutBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`Scenario focus`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:RT[e]},e))})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`This run produced`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:zT[e]},e))})]})]})]})]}),(0,x.jsx)(OE,{items:ge,scrollRoot:_e.current}),_!==null&&y&&(0,x.jsx)(ST,{parentArtifact:y,atTurn:_,maxTurns:yT(y),costPreset:`economy`,provider:`openai`,onConfirm:D,onClose:()=>v(null)})]})}var FE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function IE({block:e,eventIndex:t,totalEvents:n,name:r,sideColor:i,sections:a}){let o={"--side-color":i};if(!e||!e.title)return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),(0,x.jsx)(`span`,{className:Z.eventAwaiting,children:`Awaiting data...`})]});let s={crisis:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Z.eventTitle,children:[e.title,e.category&&(0,x.jsx)(`span`,{className:Z.categoryPill,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:Z.emergentPill,children:`EMERGENT`})]}),e.description&&(0,x.jsx)(`div`,{className:Z.eventDescription,children:e.description})]},`crisis`),decision:e.decision?(0,x.jsx)(`div`,{className:Z.eventDecision,children:e.decision},`decision`):null,outcome:e.outcome?(0,x.jsxs)(`div`,{className:Z.eventOutcomeRow,children:[(0,x.jsx)(MS,{outcome:e.outcome}),Array.isArray(e.policies)&&e.policies.length>0&&(0,x.jsx)(`span`,{className:Z.eventPolicies,children:e.policies.map(e=>String(e)).join(` / `)})]},`outcome`):null,causality:e.rationale?(0,x.jsxs)(`details`,{className:Z.eventDetails,children:[(0,x.jsx)(`summary`,{className:Z.eventDetailsSummary,style:o,children:`Rationale`}),(0,x.jsx)(`div`,{className:Z.eventRationale,style:o,children:e.rationale})]},`causality`):null,departments:Object.keys(e.depts).length>0?(0,x.jsxs)(`details`,{className:Z.eventDetails,open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.eventDetailsSummary,style:o,children:[`Departments (`,Object.keys(e.depts).length,`)`]}),(0,x.jsx)(`div`,{className:Z.deptList,children:Object.entries(e.depts).map(([e,t])=>(0,x.jsxs)(`div`,{className:Z.deptItem,style:o,children:[(0,x.jsxs)(`div`,{className:Z.deptHead,children:[(0,x.jsx)(`span`,{className:Z.deptName,children:e.charAt(0).toUpperCase()+e.slice(1)}),(0,x.jsxs)(`span`,{className:Z.deptMeta,children:[t.citations,`c `,t.tools,`t`]})]}),t.summary&&(0,x.jsx)(`div`,{className:Z.deptSummary,children:t.summary}),(0,x.jsx)(PS,{citations:t.citationList,label:``})]},e))})]},`departments`):null};return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),a.map(e=>s[e]).filter(Boolean)]})}function LE({data:e,name:t,sideColor:n,showQuotes:r}){let i=e.metrics;if(!i&&(!r||e.reactions.length===0))return(0,x.jsx)(`div`,{});let a={"--side-color":n};return(0,x.jsxs)(`div`,{className:Z.footerCard,children:[i&&(0,x.jsxs)(`details`,{className:e.reactions.length?Z.footerDetails:Z.footerDetailsLast,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[t,` · Systems State`]}),(0,x.jsx)(`div`,{className:Z.systemsRow,children:Object.entries(i).map(([e,t])=>(0,x.jsxs)(`span`,{className:Z.systemItem,children:[(0,x.jsxs)(`span`,{className:Z.systemKey,children:[e,`: `]}),(0,x.jsx)(`span`,{className:Z.systemValue,children:typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):String(t)})]},e))})]}),r&&e.reactions.length>0&&(0,x.jsxs)(`details`,{open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[`Agent Voices (`,e.totalReactions||e.reactions.length,`)`]}),(0,x.jsx)(`div`,{className:Z.reactionsList,children:e.reactions.map((e,t)=>(0,x.jsxs)(`div`,{className:Z.reactionItem,children:[(0,x.jsxs)(`div`,{className:Z.reactionHead,children:[(0,x.jsx)(`span`,{className:Z.reactionName,style:a,children:String(e.name)}),(0,x.jsx)(`span`,{className:Z.moodPill,style:{"--mood-color":FE[String(e.mood)]||`var(--text-3)`},children:String(e.mood||``).toUpperCase()})]}),(0,x.jsxs)(`div`,{className:Z.reactionQuote,children:[`“`,String(e.quote||``),`”`]}),!!e.role&&(0,x.jsxs)(`div`,{className:Z.reactionRole,children:[String(e.role),` `,e.department?`in ${String(e.department)}`:``]})]},t))})]})]})}var Q={layout:`_layout_1l1dk_1`,sidebar:`_sidebar_1l1dk_15`,sidebarHeading:`_sidebarHeading_1l1dk_31`,sidebarLead:`_sidebarLead_1l1dk_38`,actorFilter:`_actorFilter_1l1dk_45`,actorFilterLabel:`_actorFilterLabel_1l1dk_64`,actorFilterSelect:`_actorFilterSelect_1l1dk_74`,agentBtn:`_agentBtn_1l1dk_96`,selected:`_selected_1l1dk_110`,agentName:`_agentName_1l1dk_115`,agentMeta:`_agentMeta_1l1dk_119`,agentMood:`_agentMood_1l1dk_124`,chatArea:`_chatArea_1l1dk_131`,memoryBar:`_memoryBar_1l1dk_138`,memoryLabel:`_memoryLabel_1l1dk_145`,memoryBelief:`_memoryBelief_1l1dk_152`,memoryStance:`_memoryStance_1l1dk_157`,hexacoStrip:`_hexacoStrip_1l1dk_162`,hexacoLabel:`_hexacoLabel_1l1dk_174`,hexacoTrait:`_hexacoTrait_1l1dk_180`,hexacoBar:`_hexacoBar_1l1dk_184`,healthSignal:`_healthSignal_1l1dk_188`,messages:`_messages_1l1dk_192`,emptyState:`_emptyState_1l1dk_207`,emptyTitle:`_emptyTitle_1l1dk_213`,emptyCopy:`_emptyCopy_1l1dk_218`,eventCtx:`_eventCtx_1l1dk_225`,eventGroup:`_eventGroup_1l1dk_235`,eventGroupLast:`_eventGroupLast_1l1dk_239`,eventGroupLabel:`_eventGroupLabel_1l1dk_243`,eventRow:`_eventRow_1l1dk_252`,eventTurn:`_eventTurn_1l1dk_258`,eventTitle:`_eventTitle_1l1dk_265`,eventCategory:`_eventCategory_1l1dk_270`,memoryItem:`_memoryItem_1l1dk_275`,memoryTime:`_memoryTime_1l1dk_282`,relationshipsRow:`_relationshipsRow_1l1dk_287`,relationshipChip:`_relationshipChip_1l1dk_293`,bubbleWrap:`_bubbleWrap_1l1dk_297`,fromUser:`_fromUser_1l1dk_301`,fromAgent:`_fromAgent_1l1dk_305`,bubbleName:`_bubbleName_1l1dk_309`,bubble:`_bubble_1l1dk_297`,user:`_user_1l1dk_327`,typingBubble:`_typingBubble_1l1dk_332`,typingLabel:`_typingLabel_1l1dk_344`,dot:`_dot_1l1dk_359`,"chat-dot-bounce":`_chat-dot-bounce_1l1dk_1`,inputRow:`_inputRow_1l1dk_375`,inputField:`_inputField_1l1dk_392`,sendBtn:`_sendBtn_1l1dk_412`},RE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function zE(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function BE({memory:e,events:t,scenario:n}){let r=[];for(let e of t.actorIds){let n=t.actors[e];if(n){for(let e of n.events)if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`){let t=e.data.turn;r.some(e=>e.turn===t)||r.push({turn:t,time:e.data.time||0,title:String(e.data.title),category:String(e.data.category||``)})}}}r.sort((e,t)=>e.turn-t.turn);let i=n.labels.eventNoun||`events`,a=e.recentMemories?.length>0,o=e.relationships?.length>0;return!r.length&&!a?null:(0,x.jsxs)(`div`,{className:Q.eventCtx,children:[r.length>0&&(0,x.jsxs)(`div`,{className:a?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsxs)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--rust)`},children:[i.toUpperCase(),` EXPERIENCED`]}),r.map(e=>(0,x.jsxs)(`div`,{className:Q.eventRow,children:[(0,x.jsxs)(`span`,{className:Q.eventTurn,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:Q.eventTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:Q.eventCategory,children:e.category})]},e.turn))]}),a&&(0,x.jsxs)(`div`,{className:o?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--amber)`},children:`RECENT MEMORIES`}),e.recentMemories.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:Q.memoryItem,style:{"--valence-border":zE(e.valence)},children:[(0,x.jsxs)(`span`,{className:Q.memoryTime,children:[`Y`,e.time]}),` `,e.content]},t))]}),o&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--teal)`},children:`RELATIONSHIPS`}),(0,x.jsx)(`div`,{className:Q.relationshipsRow,children:e.relationships.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.relationshipChip,style:{"--rel-color":e.sentiment>0?`var(--green)`:`var(--rust)`},children:[e.name,` `,e.sentiment>0?`+`:``,e.sentiment.toFixed(1)]},t))})]})]})}function VE({state:e,onChatUsage:t}){let n=Qk(),[r,i]=(0,b.useState)(null),[a,o]=(0,b.useState)(()=>new Map),[s,c]=(0,b.useState)(()=>new Map),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(null),m=(0,b.useRef)(!0),h=()=>{let e=p.current;e&&(m.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},g=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;let i=new Map;for(let e of r.events)if(e.type===`agent_reactions`){let t=e.data.reactions||[];for(let e of t)e.name&&i.set(e.name,{name:e.name,role:e.role||``,department:e.department||``,mood:e.mood||`neutral`,age:e.age,marsborn:e.marsborn,agentId:e.agentId,memory:e.memory,hexaco:e.hexaco,psychScore:e.psychScore,boneDensity:e.boneDensity,radiation:e.radiation})}i.size>0&&t.set(n,Array.from(i.values()))}return t},[e]),_=e.actorIds.length>=2,[v,y]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!_)v!==null&&y(null);else if(v!==`all`&&!(v&&g.has(v))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(g.get(e)?.length??0)>0);y(t??`all`)}else y(`all`)}},[_,g,e.actorIds,v]);let[S,C]=(0,b.useState)(null),w=(0,b.useMemo)(()=>{if(v&&v!==`all`)return g.get(v)??[];let e=[],t=new Set;for(let n of g.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[g,v]),T=(0,b.useMemo)(()=>{let e=new Set;for(let t of w){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[w]);(0,b.useEffect)(()=>{S&&!T.includes(S)&&C(null)},[T,S]);let E=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),D=E.find(e=>e.name===r),O=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},k=e=>{let t=O(e);return t?`${t}\u0000${e}`:e},A=r?a.get(k(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[A,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let j=e=>{i(e);let t=k(e);o(n=>{if(n.has(t))return n;let r=E.find(t=>t.name===e),i=r?{role:`agent`,name:r.name,text:`${r.role} in ${r.department}, age ${r.age||`?`}. I lived through this simulation — ask me about specific turns, the commander's decisions, crises I witnessed, people I worked with, or how my department handled what came up. Try: "what did you think of the commander's choice in turn 1?", "who do you trust on the team?", or "what was the worst moment for you?"`}:{role:`agent`,text:`Connected.`},a=new Map(n);return a.set(t,[i]),a})},ee=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},te=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},M=async()=>{if(!l.trim()||!r||d)return;let e=r,n=O(e),i=k(e),a=l.trim();u(``),f(!0),ee(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];te(i,()=>o);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),s=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,...n?{leader:n}:{},message:a,history:o,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(s.reply){ee(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),te(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ee(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ee(i,t=>[...t,{role:`agent`,text:`Chat failed: ${e}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),_&&g.size>0&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-actor-filter`,children:`Lead actor`}),(0,x.jsxs)(`select`,{id:`chat-actor-filter`,className:Q.actorFilterSelect,value:v??``,onChange:e=>y(e.target.value||null),"aria-label":`Filter chat agents by lead actor`,children:[(0,x.jsxs)(`option`,{value:`all`,children:[`All leaders (`,(()=>{let e=new Set;for(let t of g.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=g.get(t)?.length??0,r=e.actors[t]?.leader?.name||t;return(0,x.jsxs)(`option`,{value:t,disabled:n===0,children:[r,` (`,n,`)`]},t)})]})]}),T.length>1&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`chat-department-filter`,className:Q.actorFilterSelect,value:S??``,onChange:e=>C(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,w.length,`)`]}),T.map(e=>{let t=w.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>j(e.name),className:[Q.agentBtn,r===e.name?Q.selected:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:Q.agentName,children:e.name}),(0,x.jsxs)(`div`,{className:Q.agentMeta,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:Q.agentMood,style:{"--mood-color":RE[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(BE,{memory:D.memory,events:e,scenario:n}),A.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&M(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:M,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_1ur8r_2`,kbdKey:`_kbdKey_1ur8r_8`,kbdLabel:`_kbdLabel_1ur8r_18`,empty:`_empty_1ur8r_22`,emptySpinner:`_emptySpinner_1ur8r_34`,emptySpinnerRotate:`_emptySpinnerRotate_1ur8r_1`,root:`_root_1ur8r_54`,toolbarStrip:`_toolbarStrip_1ur8r_62`,toolbarTopRow:`_toolbarTopRow_1ur8r_71`,modePillsWrap:`_modePillsWrap_1ur8r_76`,overflowToggle:`_overflowToggle_1ur8r_95`,overflowToggleOpen:`_overflowToggleOpen_1ur8r_109`,helpBtn:`_helpBtn_1ur8r_114`,forgeToolboxKey:`_forgeToolboxKey_1ur8r_130`,toolsRow:`_toolsRow_1ur8r_163`,paletteBtn:`_paletteBtn_1ur8r_177`,toolBtn:`_toolBtn_1ur8r_191`,settingsBtn:`_settingsBtn_1ur8r_204`,settingsBtnOpen:`_settingsBtnOpen_1ur8r_217`,modeHint:`_modeHint_1ur8r_222`,ecologyNone:`_ecologyNone_1ur8r_232`,ecologyBack:`_ecologyBack_1ur8r_243`,diffLine:`_diffLine_1ur8r_255`,phoneTabRow:`_phoneTabRow_1ur8r_264`,phoneTab:`_phoneTab_1ur8r_264`,phoneTabActive:`_phoneTabActive_1ur8r_291`,leadersRow:`_leadersRow_1ur8r_297`,leadersRowNarrow:`_leadersRowNarrow_1ur8r_306`,sideWrap:`_sideWrap_1ur8r_311`,sideWrapHidden:`_sideWrapHidden_1ur8r_318`,leadersRowLinesBelow:`_leadersRowLinesBelow_1ur8r_322`,cohortWindow:`_cohortWindow_1ur8r_327`,cohortWindowLinesBelow:`_cohortWindowLinesBelow_1ur8r_331`,cohortTrackLinesBelow:`_cohortTrackLinesBelow_1ur8r_339`,turnLinesSlot:`_turnLinesSlot_1ur8r_344`,footerKeys:`_footerKeys_1ur8r_359`,srOnly:`_srOnly_1ur8r_372`,jumpLatest:`_jumpLatest_1ur8r_384`,"paracosm-jump-pulse":`_paracosm-jump-pulse_1ur8r_1`,jumpLatestBehind:`_jumpLatestBehind_1ur8r_407`,toast:`_toast_1ur8r_412`,"paracosm-toast-in":`_paracosm-toast-in_1ur8r_1`,toastKicker:`_toastKicker_1ur8r_433`,toastKickerMeta:`_toastKickerMeta_1ur8r_445`,toastBody:`_toastBody_1ur8r_449`,toastBodyMd:`_toastBodyMd_1ur8r_454`,vignette:`_vignette_1ur8r_459`,"paracosm-vignette":`_paracosm-vignette_1ur8r_1`,cohortViewBar:`_cohortViewBar_1ur8r_475`,cohortViewModeToggle:`_cohortViewModeToggle_1ur8r_486`,cohortViewModeButton:`_cohortViewModeButton_1ur8r_495`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_1ur8r_526`,cohortPairPicker:`_cohortPairPicker_1ur8r_535`,cohortPairPickerLabel:`_cohortPairPickerLabel_1ur8r_543`,cohortPairPickerSelect:`_cohortPairPickerSelect_1ur8r_552`,cohortPairPickerVs:`_cohortPairPickerVs_1ur8r_575`,cohortPairPickerHint:`_cohortPairPickerHint_1ur8r_583`};function HE(e){return(0,b.useMemo)(()=>UE(e),[e])}function UE(e){let t={};for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;t[n]=[];let i=new Map;for(let e of r.events)if((e.type===`event_start`||e.type===`turn_start`)&&e.turn!=null){let t=e.data?.category;if(typeof t==`string`&&t.length>0){let n=i.get(e.turn)??[];n.includes(t)||n.push(t),i.set(e.turn,n)}}let a=r.events.filter(e=>e.type===`systems_snapshot`);for(let e=0;e<r.agentSnapshots.length;e++){let o=r.agentSnapshots[e],s=a[e]?.data||{},c=s.turn||e+1,l=r.events.find(e=>e.type===`turn_done`&&e.data?.turn===c)?.data?.metrics??{},u=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,d=o.map(e=>({agentId:e.agentId,name:e.name,department:e.department,role:e.role,rank:e.rank,alive:e.alive,marsborn:e.marsborn,psychScore:e.psychScore,age:e.age,generation:e.generation,partnerId:e.partnerId,childrenIds:e.childrenIds||[],featured:e.featured,mood:e.mood,shortTermMemory:e.shortTermMemory||[]}));t[n].push({turn:c,time:s.time||0,cells:d,population:s.population||d.filter(e=>e.alive).length,morale:s.morale||0,foodReserve:typeof s.foodReserve==`number`?s.foodReserve:u(l.foodMonthsReserve),waterLitersPerDay:u(l.waterLitersPerDay),powerKw:u(l.powerKw),pressurizedVolumeM3:u(l.pressurizedVolumeM3),deaths:s.deaths||0,births:s.births||0,eventCategories:i.get(c)??[]})}}return t}var WE={region:`_region_1xlv9_1`,narrow:`_narrow_1xlv9_12`,canvasWrap:`_canvasWrap_1xlv9_18`,canvas:`_canvas_1xlv9_18`,revealCover:`_revealCover_1xlv9_38`,cornerBtn:`_cornerBtn_1xlv9_48`,focusBtn:`_focusBtn_1xlv9_70`,divergenceEmpty:`_divergenceEmpty_1xlv9_75`,divergenceEmptyMsg:`_divergenceEmptyMsg_1xlv9_86`,tileTooltip:`_tileTooltip_1xlv9_98`,tileKindLabel:`_tileKindLabel_1xlv9_117`,tileCoords:`_tileCoords_1xlv9_125`,tileNearestName:`_tileNearestName_1xlv9_131`,tileNearestRole:`_tileNearestRole_1xlv9_136`,tileNearestDeath:`_tileNearestDeath_1xlv9_142`,tileNearestBirth:`_tileNearestBirth_1xlv9_148`,tileNearestPattern:`_tileNearestPattern_1xlv9_154`,tileAmbient:`_tileAmbient_1xlv9_160`,hoverTooltip:`_hoverTooltip_1xlv9_164`,hoverHeader:`_hoverHeader_1xlv9_182`,hoverFeaturedPill:`_hoverFeaturedPill_1xlv9_192`,hoverRole:`_hoverRole_1xlv9_201`,hoverMood:`_hoverMood_1xlv9_209`,hoverMoodValue:`_hoverMoodValue_1xlv9_213`,psychBlock:`_psychBlock_1xlv9_217`,psychLabel:`_psychLabel_1xlv9_221`,psychSvg:`_psychSvg_1xlv9_227`,hoverHint:`_hoverHint_1xlv9_234`};function GE(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function KE(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}function qE(e,t,n,r,i=8){return{x:Math.max(i,Math.min(n-i,e)),y:Math.max(i,Math.min(r-i,t))}}function JE(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function YE(e,t,n){let r=new Map;if(n.length===0)return r;let i=e/2,a=t/2,o=Math.min(e,t)*.32,s=Math.min(e,t)*.14;if(n.length===1)return r.set(n[0],{cx:i,cy:a,r:s*1.5}),r;for(let e=0;e<n.length;e++){let t=Math.PI*2*e/n.length-Math.PI/2;r.set(n[e],{cx:i+Math.cos(t)*o,cy:a+Math.sin(t)*o,r:s})}return r}function XE(e,t,n){let r=YE(t,n,JE(e)),i=new Map;for(let a of e){let e=r.get(a.department||`unknown`)??{cx:t/2,cy:n/2,r:40},o=GE(KE(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,qE(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function ZE(e,t,n){let r=new Map,i=new Set,a=new Map(e.map(e=>[e.agentId,e])),o=[];for(let t of e)if(!i.has(t.agentId)&&t.partnerId&&a.has(t.partnerId)&&!i.has(t.partnerId)){let e=a.get(t.partnerId),n=t.childrenIds.map(e=>a.get(e)).filter(e=>!!e);o.push([t,e,...n]),i.add(t.agentId),i.add(e.agentId);for(let e of n)i.add(e.agentId)}let s=e.filter(e=>!i.has(e.agentId)),c=Math.max(50,(t-80)/Math.max(1,o.length));return o.forEach((e,i)=>{let a=40+c*i+c/2;e.forEach((i,o)=>{let s=GE(KE(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,qE(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=GE(KE(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,qE(o,c,t,n))}),r}function QE(e,t,n){let r={positive:-1,hopeful:-.6,neutral:0,anxious:.4,negative:.8,defiant:.6,resigned:.7},i=new Map;for(let a of e){let e=(r[a.mood]??0)*.5+.5,o=GE(KE(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,qE(s,c,t,n))}return i}function $E(e,t,n){let r=new Map;for(let i of e){let e=Math.max(0,Math.min(80,i.age??30))/80,a=GE(KE(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,qE(o,s,t,n))}return r}function eD(e,t,n,r){return t===`families`?ZE(e,n,r):t===`mood`?QE(e,n,r):t===`age`?$E(e,n,r):XE(e,n,r)}function tD(e,t,n,r,i=1,a,o=!1,s=0,c=``,l=!1,u=`rgba(216, 204, 176, 0.9)`,d=`rgba(10, 8, 6, 0.55)`){e.save(),.5+.5*Math.sin(s*.003);let f=c.trim().toLowerCase().split(/\s+/).filter(Boolean),p=f.length>0,m=e=>{if(!p)return!1;let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();return f.every(e=>t.includes(e))};for(let c of t){if(!c.alive)continue;let t=n.get(c.agentId);if(!t)continue;let l=a?.has(c.agentId)??!1;if(o&&!l)continue;let u=m(c),d=p&&!u,f=c.featured?5:3,h=c.featured?.95:.75,g=d?.25:1;if(c.featured&&!d){let n=f+6,a=.42*i;e.strokeStyle=r,e.lineWidth=1,e.globalAlpha=a,e.beginPath(),e.arc(t.x,t.y,n,0,Math.PI*2),e.stroke()}if(u){let n=.7+.3*Math.sin(s*.006);e.strokeStyle=`rgba(248, 225, 150, 1)`,e.lineWidth=2.2,e.globalAlpha=i*n,e.beginPath(),e.arc(t.x,t.y,f+6,0,Math.PI*2),e.stroke()}l&&!d&&(e.strokeStyle=`rgba(232, 180, 74, 0.9)`,e.lineWidth=2,e.globalAlpha=i,e.beginPath(),e.arc(t.x,t.y,f+3,0,Math.PI*2),e.stroke()),e.strokeStyle=l?`rgba(224, 101, 48, 1)`:r,e.lineWidth=c.featured||l||u?1.6:1,e.globalAlpha=(l?1:h)*i*g,e.beginPath(),e.arc(t.x,t.y,f,0,Math.PI*2),e.stroke()}if(l){e.font=`9px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`top`;for(let r of t){if(!r.alive)continue;let t=n.get(r.agentId);if(!t)continue;let s=a?.has(r.agentId)??!1;if(o&&!s||!r.featured&&!s)continue;let c=m(r);if(p&&!c)continue;let l=r.name.split(/\s+/)[0],f=t.y+(r.featured?12:10),h=e.measureText(l).width;e.fillStyle=d,e.fillRect(t.x-h/2-3,f-1,h+6,10),e.fillStyle=s?`rgba(232, 180, 74, 0.95)`:u,e.globalAlpha=i,e.fillText(l,t.x,f)}}e.restore()}var nD={birth:`rgba(154, 205, 96, 0.8)`,death:`rgba(168, 152, 120, 0.7)`,forge_approved:`rgba(232, 180, 74, 0.8)`,forge_rejected:`rgba(224, 101, 48, 0.7)`,reuse:`rgba(232, 180, 74, 0.6)`,crisis:`rgba(196, 74, 30, 0.8)`},rD=6;function iD(e,t){e.save();for(let n of t){let t=nD[n.kind]??`rgba(255,255,255,0.6)`,r=n.progress,i=1-r;if(e.globalAlpha=i,n.kind===`birth`||n.kind===`death`||n.kind===`crisis`){let a=4+r*14;if(e.strokeStyle=t,e.lineWidth=1.2,e.beginPath(),e.arc(n.x,n.y,a,0,Math.PI*2),e.stroke(),n.kind!==`crisis`){let a=2+r*22,o=n.kind===`birth`?1.8:1.4;e.fillStyle=t;for(let t=0;t<rD;t++){let r=t/rD*Math.PI*2+(n.kind===`birth`?.3:-.2),s=n.x+Math.cos(r)*a,c=n.y+Math.sin(r)*a;e.globalAlpha=i*.9,e.beginPath(),e.arc(s,c,o,0,Math.PI*2),e.fill()}}}else if(n.kind===`reuse`&&typeof n.endX==`number`&&typeof n.endY==`number`){let a=n.x+(n.endX-n.x)*r,o=n.y+(n.endY-n.y)*r,s=e.createRadialGradient(a,o,0,a,o,8);s.addColorStop(0,`rgba(248, 225, 150, 0.95)`),s.addColorStop(.4,t),s.addColorStop(1,`rgba(232, 180, 74, 0)`),e.fillStyle=s,e.globalAlpha=i,e.beginPath(),e.arc(a,o,8,0,Math.PI*2),e.fill(),e.fillStyle=`rgba(248, 225, 150, 0.95)`,e.beginPath(),e.arc(a,o,2,0,Math.PI*2),e.fill()}else e.fillStyle=t,e.beginPath(),e.arc(n.x,n.y,3,0,Math.PI*2),e.fill()}e.restore()}var aD={medical:`rgba(78, 205, 196, 0.9)`,engineering:`rgba(232, 180, 74, 0.9)`,agriculture:`rgba(106, 173, 72, 0.9)`,psychology:`rgba(155, 107, 158, 0.9)`,governance:`rgba(224, 101, 48, 0.9)`,research:`rgba(149, 107, 216, 0.9)`,science:`rgba(149, 107, 216, 0.9)`,ops:`rgba(200, 122, 58, 0.9)`,operations:`rgba(200, 122, 58, 0.9)`};function oD(e){return aD[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function sD(e,t,n){e.save(),e.font=`10px ui-monospace, monospace`,e.fillStyle=n.sideColor,e.textBaseline=`top`,e.textAlign=`left`;let r=n.actorName.toUpperCase();e.fillText(r,10,10);let i=e.measureText(r).width,a=(n.actorArchetype||``).trim().replace(/^The\s+/i,``);if(a){e.font=`bold 8px ui-monospace, monospace`;let t=a.toUpperCase(),r=e.measureText(t).width,o=10+i+8;e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.5)`,e.fillRect(o,9,r+10,13),e.strokeStyle=n.sideColor,e.lineWidth=1,e.strokeRect(o+.5,9.5,r+10-1,12),e.fillStyle=n.sideColor,e.textBaseline=`middle`,e.fillText(t,o+5,16),e.textBaseline=`top`,e.font=`10px ui-monospace, monospace`}e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.75)`;let o=t?.time,s=n.timeUnitShort??`t`,c=typeof o==`number`?typeof n.startTime==`number`?`T${t?.turn??0} · ${o} · ${s} ${Math.max(0,o-n.startTime)}`:`T${t?.turn??0} · ${o}`:`T${t?.turn??0}`;if(e.fillText(c,10,24),!t){e.restore();return}if(n.deptLabels&&n.cells&&n.positions&&n.cells.length>0){let t=new Map;for(let e of n.cells){if(!e.alive)continue;let r=n.positions.get(e.agentId);if(!r)continue;let i=(e.department||`unknown`).toLowerCase(),a=t.get(i)??{xs:[],ys:[]};a.xs.push(r.x),a.ys.push(r.y),t.set(i,a)}e.font=`bold 9px ui-monospace, monospace`,e.textBaseline=`middle`,e.textAlign=`center`;let r=[];for(let[n,i]of t.entries()){if(i.xs.length===0)continue;let t=i.xs.reduce((e,t)=>e+t,0)/i.xs.length,a=Math.min(...i.ys),o=Math.max(14,a-14),s=`${n.toUpperCase()} ${i.xs.length}`,c=e.measureText(s);r.push({dept:n,cx:t,w:c.width+8,h:14,label:s,idealY:o})}r.sort((e,t)=>e.idealY-t.idealY);let i=[],a=(e,t)=>Math.abs(e.cx-t.cx)<(e.w+t.w)/2+2&&Math.abs(e.y-t.y)<(e.h+t.h)/2+2;for(let e of r){let t=e.idealY;for(let n=0;n<10;n++){let r=e.idealY-n*16,o=e.idealY+n*16,s=n===0?e.idealY:r>=10?r:o;if(!i.some(t=>a({cx:e.cx,w:e.w,y:s,h:e.h},t))){t=s;break}}i.push({...e,y:t})}for(let t of i)e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.85)`,e.fillRect(t.cx-t.w/2,t.y-t.h/2,t.w,t.h),e.strokeStyle=oD(t.dept),e.lineWidth=1,e.strokeRect(t.cx-t.w/2+.5,t.y-t.h/2+.5,t.w-1,t.h-1),e.fillStyle=oD(t.dept),e.fillText(t.label,t.cx,t.y)}e.font=`10px ui-monospace, monospace`,e.textAlign=`left`,e.textBaseline=`bottom`,e.fillStyle=n.sideColor;let l=n.previousSnapshot?t.population-n.previousSnapshot.population:0,u=l>0?`↑`:l<0?`↓`:``,d=l>0?`rgba(106, 173, 72, 0.95)`:l<0?`rgba(196, 74, 30, 0.95)`:`rgba(216, 204, 176, 0.75)`;if(e.fillText(`POP ${t.population}`,10,n.height-20),u){let r=`POP ${t.population}`,i=e.measureText(r).width+6;e.fillStyle=d,e.fillText(`${u}${Math.abs(l)}`,10+i,n.height-20),e.fillStyle=n.sideColor}(t.deaths>0||t.births>0)&&(e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.65)`,e.fillText(`+${t.births} -${t.deaths}`,10,n.height-8)),n.lagTurns&&n.lagTurns>0&&(e.textAlign=`right`,e.fillStyle=`rgba(232, 180, 74, 0.75)`,e.fillText(`lagging ${n.lagTurns}`,n.width-10,n.height-8)),e.restore()}function cD(e,t,n,r,i){if(t.length===0||r.length===0)return;let a=new Map;for(let e of r){if(e.approved===!1)continue;let t=(e.department||`unknown`).toLowerCase();a.set(t,(a.get(t)??0)+1)}if(a.size===0)return;let o=new Map;for(let e of t){if(!e.alive)continue;let t=n.get(e.agentId);if(!t)continue;let r=(e.department||`unknown`).toLowerCase(),i=o.get(r)??{x:0,y:0,count:0};i.x+=t.x,i.y+=t.y,i.count+=1,o.set(r,i)}let s=Math.max(...a.values());e.save(),e.globalCompositeOperation=`lighter`;for(let[t,n]of a.entries()){let r=o.get(t);if(!r||r.count===0)continue;let a=r.x/r.count,c=r.y/r.count,l=n/s,u=30+l*50,d=.2+l*.25,f=e.createRadialGradient(a,c,0,a,c,u);f.addColorStop(0,dD(i,d)),f.addColorStop(.6,dD(i,d*.4)),f.addColorStop(1,dD(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=dD(i,.95),e.font=`bold 11px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${n}`,a,c),e.globalCompositeOperation=`lighter`}e.restore()}function lD(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=a(t.foodReserve),s=a(t.waterLitersPerDay),c=a(t.powerKw),l=a(t.pressurizedVolumeM3);if(o==null&&s==null&&c==null&&l==null)return;let u=(e,t,n)=>e<=t?1:e>=n?0:1-(e-t)/(n-t),d=e=>e<.33?`rgba(106, 173, 72, ${.06+e*.1})`:e<.66?`rgba(232, 180, 74, ${.08+(e-.33)*.2})`:`rgba(196, 74, 30, ${.12+(e-.66)*.3})`,f=n/2,p=r/2;e.save(),o!=null&&(e.fillStyle=d(u(o,3,18)),e.fillRect(0,0,f,p)),s!=null&&(e.fillStyle=d(u(s,200,1200)),e.fillRect(f,0,f,p)),c!=null&&(e.fillStyle=d(u(c,150,600)),e.fillRect(0,p,f,p)),l!=null&&(e.fillStyle=d(u(l,1500,4e3)),e.fillRect(f,p,f,p));let m=p+8;e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,o!=null&&e.fillText(`FOOD ${o.toFixed(1)}mo`,8,40),s!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(s)}L/d`,n-8,40)),c!=null&&(e.textAlign=`left`,e.fillText(`POWER ${Math.round(c)}kW`,8,m)),l!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(l)}m³`,n-8,m)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function uD(e,t,n,r,i,a){if(!r||r.size===0)return;let o=.6+.4*Math.sin(i*.004);e.save();for(let i of t){if(!i.alive||!r.has(i.agentId))continue;let t=n.get(i.agentId);t&&(e.strokeStyle=a,e.lineWidth=2,e.globalAlpha=.9,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.stroke(),e.lineWidth=1,e.globalAlpha=.45*o,e.beginPath(),e.arc(t.x,t.y,14+o*3,0,Math.PI*2),e.stroke(),e.globalAlpha=.2*o,e.beginPath(),e.arc(t.x,t.y,20+o*5,0,Math.PI*2),e.stroke())}e.restore()}function dD(e,t){let n=e.trim();if(n.startsWith(`#`)){let e=parseInt(n.slice(1),16);if(n.length===7)return`rgba(${e>>16&255},${e>>8&255},${e&255},${t})`}let r=n.match(/rgba?\(([^)]+)\)/);if(r){let e=r[1].split(`,`).map(e=>e.trim());if(e.length>=3)return`rgba(${e[0]},${e[1]},${e[2]},${t})`}return n}function fD(){return{items:[]}}function pD(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function mD(e){let t=[];for(let n of e.items){let e=n.age+1;e>=n.totalFrames||t.push({...n,age:e,progress:e/n.totalFrames})}e.items=t}function hD(e){return e.items}function gD(e,t){let n=new Map(e.map(e=>[e.agentId,e]));return{born:t.filter(e=>!n.has(e.agentId)&&e.alive&&!((e.age??0)>=18)),died:t.filter(e=>n.get(e.agentId)?.alive===!0&&!e.alive)}}var _D=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function vD(e,t,n,r){let i=(0,b.useRef)(fD()),a=(0,b.useRef)(new Set),[o,s]=(0,b.useState)(0),c=(0,b.useRef)(-1),l=(0,b.useRef)(!0),u=(0,b.useRef)(typeof document<`u`?!document.hidden:!0),d=My(Iy);return(0,b.useEffect)(()=>{let t=e.snapshot,r=e.previousSnapshot;if(!t||t.turn===c.current||(c.current=t.turn,!r))return;let o=n(),{born:s,died:l}=gD(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&pD(i.current,{kind:`birth`,x:t.x,y:t.y,totalFrames:30,sourceId:e.agentId})}for(let e of l){let t=o.get(e.agentId);t&&pD(i.current,{kind:`death`,x:t.x,y:t.y,totalFrames:60,sourceId:e.agentId})}let u=e.eventCategories??t.eventCategories??[];if(u.length>0){let e=Array.from(o.values());if(e.length>0){let n=e.reduce((e,t)=>e+t.x,0)/e.length,r=e.reduce((e,t)=>e+t.y,0)/e.length;for(let e of u){let o=e.toLowerCase();if(!_D.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),pD(i.current,{kind:`crisis`,x:n,y:r,totalFrames:90}))}}}},[e.snapshot,e.previousSnapshot,e.eventCategories,n]),(0,b.useEffect)(()=>{if(!r)return;let t=r();if(t.size!==0){for(let n of e.forgeAttempts??[]){let e=`forge|${n.turn}|${n.eventIndex}|${n.department}|${n.name}|${n.approved?`a`:`r`}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.department||`unknown`).toLowerCase());r&&pD(i.current,{kind:n.approved?`forge_approved`:`forge_rejected`,x:r.x,y:r.y,totalFrames:n.approved?30:22})}for(let n of e.reuseCalls??[]){let e=`reuse|${n.turn}|${n.originDept}|${n.callingDept}|${n.name}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.originDept||`unknown`).toLowerCase()),o=t.get((n.callingDept||`unknown`).toLowerCase());r&&o&&pD(i.current,{kind:`reuse`,x:r.x,y:r.y,endX:o.x,endY:o.y,totalFrames:40})}}},[e.forgeAttempts,e.reuseCalls,r]),(0,b.useEffect)(()=>{let e=()=>{u.current=!document.hidden};document.addEventListener(`visibilitychange`,e);let n=t.current,r=null;return n&&(r=new IntersectionObserver(e=>{for(let t of e)l.current=t.isIntersecting},{threshold:0}),r.observe(n)),()=>{document.removeEventListener(`visibilitychange`,e),r?.disconnect()}},[t]),(0,b.useEffect)(()=>{if(d){s(e=>e+1);return}let e=0,t=performance.now(),n=r=>{!l.current||!u.current||r-t<33.333333333333336||(t=r,mD(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:hD(i.current),tickClock:o}}function yD(e,t){let n=new Map;for(let r of e){if(!r.alive)continue;let e=t.get(r.agentId);if(!e)continue;let i=(r.department||`unknown`).toLowerCase(),a=n.get(i)??{x:0,y:0,n:0};a.x+=e.x,a.y+=e.y,a.n+=1,n.set(i,a)}let r=new Map;for(let[e,t]of n.entries())r.set(e,{x:t.x/t.n,y:t.y/t.n});return r}var bD={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function xD(e){return bD[(e||``).toLowerCase()]??`#a89878`}function SD({cells:e,size:t=44}){let{slices:n,alive:r}=(0,b.useMemo)(()=>{let t=new Map,n=0;for(let r of e){if(!r.alive)continue;let e=(r.department||`unknown`).toLowerCase();t.set(e,(t.get(e)??0)+1),n+=1}let r=[...t.entries()].sort((e,t)=>t[1]-e[1]),i=[];for(let[e,t]of r)i.push({dept:e,count:t,frac:t/Math.max(1,n),color:xD(e)});return{slices:i,alive:n}},[e]);if(r===0)return(0,x.jsx)(`div`,{style:{width:t,height:t,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`var(--text-4)`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`},"aria-label":`No live members`,children:`—`});let i=t/2,a=i-6,o=i,s=i,c=-Math.PI/2;return(0,x.jsxs)(`svg`,{width:t,height:t,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`Department breakdown: ${n.map(e=>`${e.dept} ${e.count}`).join(`, `)}`,children:[n.map((e,t)=>{let n=e.frac*Math.PI*2,r=c,l=c+n;c=l;let u=o+Math.cos(r)*i,d=s+Math.sin(r)*i,f=o+Math.cos(l)*i,p=s+Math.sin(l)*i,m=o+Math.cos(r)*a,h=s+Math.sin(r)*a,g=o+Math.cos(l)*a,_=s+Math.sin(l)*a,v=+(n>Math.PI),y=[`M ${u.toFixed(2)} ${d.toFixed(2)}`,`A ${i} ${i} 0 ${v} 1 ${f.toFixed(2)} ${p.toFixed(2)}`,`L ${g.toFixed(2)} ${_.toFixed(2)}`,`A ${a} ${a} 0 ${v} 0 ${m.toFixed(2)} ${h.toFixed(2)}`,`Z`].join(` `);return(0,x.jsx)(`path`,{d:y,fill:e.color,opacity:.85,children:(0,x.jsx)(`title`,{children:`${e.dept}: ${e.count} (${Math.round(e.frac*100)}%)`})},`${e.dept}-${t}`)}),(0,x.jsx)(`text`,{x:o,y:s,textAnchor:`middle`,dominantBaseline:`central`,fontSize:10,fontFamily:`ui-monospace, monospace`,fontWeight:800,fill:`var(--text-1)`,children:r})]})}var CD={"tab.living":`Who's alive this turn — agents on the scenario grid.`,"tab.mood":`Aggregate mood mix per leader: hopeful / neutral / anxious / negative.`,"tab.forge":`Computational tools the agents forged in the QuickJS WebAssembly sandbox this turn.`,"tab.ecology":`Resource and environment metrics: power, food, water, radiation.`,"tab.divergence":`Per-metric A-vs-B deltas across all turns.`,"badge.forge":`Forge attempts on this turn — click FORGE for details.`,"badge.divergence":`Metrics diverged this turn — click DIVERGENCE for the rail.`,"stat.morale":`Aggregate morale across all alive agents (0–100%).`,"stat.moodMix":`Distribution of agents across the four mood tiers, weighted by morale.`,"stat.alive":`Living agents in this colony at the current turn.`,"stat.age":`Age distribution of living agents (4 bins: <20 / 20–40 / 40–60 / 60+).`,"stat.paired":`Alive agents currently in a partnership pair.`,"stat.earth":`Agents born on Earth (vs Native — born after the colony's first birth event).`,"stat.native":`Agents born in the colony itself (Marsborn / Lunarborn / scenario-specific).`,"stat.depts":`Agent count by department. Hover a wedge for the dept name.`,"chip.rising":`Aggregate morale trending up vs the previous turn.`},wD={strip:`_strip_1twpk_1`,narrow:`_narrow_1twpk_15`,col:`_col_1twpk_20`,colNarrow:`_colNarrow_1twpk_27`,colPaired:`_colPaired_1twpk_31`,row:`_row_1twpk_35`,rowBaseline:`_rowBaseline_1twpk_40`,label:`_label_1twpk_46`,moraleValue:`_moraleValue_1twpk_51`,bar:`_bar_1twpk_57`,moraleFill:`_moraleFill_1twpk_64`,value2:`_value2_1twpk_71`,valueRust:`_valueRust_1twpk_75`,valueNative:`_valueNative_1twpk_79`,moodHeader:`_moodHeader_1twpk_84`,moodEmpty:`_moodEmpty_1twpk_90`,moodBar:`_moodBar_1twpk_95`,moodSegment:`_moodSegment_1twpk_103`,moodLegend:`_moodLegend_1twpk_109`,ageBars:`_ageBars_1twpk_117`,ageBarCol:`_ageBarCol_1twpk_124`,ageBarFill:`_ageBarFill_1twpk_133`,ageScale:`_ageScale_1twpk_143`,deptBlock:`_deptBlock_1twpk_150`,deptLabel:`_deptLabel_1twpk_158`};function TD({snapshot:e,sideColor:t}){let n=My(Ny),r=e.cells.filter(e=>e.alive),i=r.reduce((e,t)=>{let n=t.mood||`neutral`;return e[n]=(e[n]??0)+1,e},{}),a=[`positive`,`hopeful`,`neutral`,`anxious`,`negative`,`defiant`,`resigned`],o={positive:`var(--green)`,hopeful:`#9acd60`,neutral:`var(--text-4)`,anxious:`var(--amber)`,negative:`var(--rust)`,defiant:`#c44a1e`,resigned:`var(--text-3)`},s=r.length||1,c=[0,0,0,0];for(let e of r){let t=e.age??30;t<20?c[0]++:t<40?c[1]++:t<60?c[2]++:c[3]++}let l=Math.max(1,...c),u=r.filter(e=>!!e.partnerId).length,d=r.filter(e=>(e.generation??0)===0).length,f=Math.round(e.morale*100),p=f>=60?`var(--green)`:f>=30?`var(--amber)`:`var(--rust)`,m={"--side-color":t};return(0,x.jsxs)(`div`,{className:[wD.strip,n?wD.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[wD.col,wD.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.rowBaseline,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:wD.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:wD.bar,children:(0,x.jsx)(`div`,{className:wD.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:wD.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsxs)(`div`,{className:wD.moodHeader,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:wD.value2,title:CD[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:wD.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:wD.moodBar,children:a.map(e=>{let t=i[e]||0;if(t===0)return null;let n=t/s*100;return(0,x.jsx)(`div`,{title:`${e}: ${t}`,className:wD.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:wD.moodLegend,children:a.filter(e=>(i[e]||0)>0).map(e=>`${Math.round((i[e]||0)/s*100)}% ${e}`).slice(0,3).join(` · `)})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsx)(`div`,{className:wD.label,title:CD[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:wD.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:wD.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:wD.ageBarFill,style:{"--age-height":`${e/l*100}%`,"--age-min":e>0?`2px`:`0`,"--age-bg":e>0?t:`transparent`}})},n))}),(0,x.jsxs)(`div`,{className:wD.ageScale,children:[(0,x.jsx)(`span`,{children:`<20`}),(0,x.jsx)(`span`,{children:`20`}),(0,x.jsx)(`span`,{children:`40`}),(0,x.jsx)(`span`,{children:`60+`})]})]}),(0,x.jsxs)(`div`,{className:[wD.col,wD.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:wD.value2,children:d})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:wD.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:wD.deptBlock,"aria-label":`Department breakdown`,title:CD[`stat.depts`],children:[(0,x.jsx)(SD,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:wD.deptLabel,children:`Depts`})]})]})}var ED={cols:12,rows:6,seedRadius:2},DD=[[1,0],[2,1],[0,2],[1,2],[2,2]],OD=[[0,1],[1,1],[2,1]],kD=[[0,0],[1,0],[0,1],[1,1]],AD=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],jD=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],MD=[[1,0],[2,0],[0,1],[1,1],[1,2]];function ND(e){switch(e){case`positive`:case`hopeful`:return kD;case`neutral`:return AD;case`anxious`:return OD;case`resigned`:return jD;case`defiant`:case`negative`:return DD;default:return OD}}function PD(e,t,n,r,i,a,o){let s=r/a,c=i/o,l=Math.max(1,Math.min(s,c)-2);e.save(),e.fillStyle=`rgba(106, 173, 72, 0.25)`,e.strokeStyle=`rgba(154, 205, 96, 0.95)`,e.lineWidth=2;for(let u of t){if(!u.alive||(u.generation??0)===0)continue;let t=n.get(u.agentId);if(!t)continue;let d=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(s-l)/2,m=(c-l)/2,h=d*s+p,g=f*c+m;e.fillRect(h,g,l,l),e.strokeRect(h+.5,g+.5,l-1,l-1);let _=h+l/2,v=g+l/2,y=l*.4;e.beginPath(),e.moveTo(_-y,v),e.lineTo(_+y,v),e.moveTo(_,v-y),e.lineTo(_,v+y),e.stroke()}e.restore()}function FD(e,t,n,r,i,a,o,s=`rgba(168, 152, 120, 0.85)`,c=`rgba(168, 152, 120, 0.08)`){let l=r/a,u=i/o,d=Math.max(1,Math.min(l,u)-2);e.save(),e.lineWidth=2,e.strokeStyle=s,e.fillStyle=c;for(let s of t){if(s.alive)continue;let t=n.get(s.agentId);if(!t)continue;let c=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(l-d)/2,m=(u-d)/2,h=c*l+p,g=f*u+m;e.fillRect(h,g,d,d),e.strokeRect(h+.5,g+.5,d-1,d-1),e.beginPath(),e.moveTo(h+4,g+4),e.lineTo(h+d-4,g+d-4),e.moveTo(h+d-4,g+4),e.lineTo(h+4,g+d-4),e.stroke()}e.restore()}function ID(e,t,n,r,i){let{cols:a,rows:o,grid:s}=e,c=Math.floor(t/Math.max(1,r)*a),l=Math.floor(n/Math.max(1,i)*o);return c<0||c>=a||l<0||l>=o?null:s[l*a+c]>0?{col:c,row:l}:null}function LD(e,t,n,r,i){return{col:Math.floor(e.x/Math.max(1,t)*r),row:Math.floor(e.y/Math.max(1,n)*i)}}function RD(e){switch(e){case`birth`:return kD;case`forge`:return DD;case`crisis`:return MD;case`death`:return[];default:return null}}function zD(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function BD(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=RD(a);for(let e=0;e<t.length;e+=1){let a=t[e];if(!a.alive)continue;let u=n.get(a.agentId);if(!u)continue;let d=Math.floor(u.x/Math.max(1,r)*o),f=Math.floor(u.y/Math.max(1,i)*s),p=l??ND(a.mood);for(let[e,t]of p){let n=d+e-1,r=f+t-1;n<0||n>=o||r<0||r>=s||(c[r*o+n]=8)}}}function VD(e,t,n,r){let{cols:i,rows:a,grid:o}=e,s=Math.floor(t.x/Math.max(1,n)*i),c=Math.floor(t.y/Math.max(1,r)*a);if(t.kind===`death`){for(let e=-1;e<=1;e+=1)for(let t=-1;t<=1;t+=1){let n=s+t,r=c+e;n<0||n>=i||r<0||r>=a||(o[r*i+n]=0)}return}let l;switch(t.kind){case`birth`:l=kD;break;case`forge_approved`:l=DD;break;case`forge_rejected`:l=OD;break;case`reuse`:l=jD;break;case`crisis`:l=MD;break;default:l=OD}for(let[e,t]of l){let n=s+e-1,r=c+t-1;n<0||n>=i||r<0||r>=a||(o[r*i+n]=8)}}function HD(e){let{cols:t,rows:n,grid:r,next:i}=e;i.fill(0);for(let e=0;e<n;e++)for(let a=0;a<t;a++){let o=0;for(let i=-1;i<=1;i++)for(let s=-1;s<=1;s++){if(s===0&&i===0)continue;let c=a+s,l=e+i;c<0||c>=t||l<0||l>=n||r[l*t+c]>0&&(o+=1)}let s=r[e*t+a],c=s>0;c&&o===2||o===3?i[e*t+a]=c?Math.max(4,s):8:c&&s>1&&(i[e*t+a]=Math.max(0,s-2))}r.set(i),e.frame+=1}function UD(e,t,n,r,i,a=1){let{cols:o,rows:s,grid:c}=t;if(a<=0)return;let l=n/o,u=r/s,d=Math.max(1,Math.min(l,u)-2),f=(l-d)/2,p=(u-d)/2;e.save();for(let t=0;t<s;t++)for(let n=0;n<o;n++){let r=c[t*o+n];if(r===0)continue;let s=Math.min(1,r/8*.9*a);e.fillStyle=i,e.globalAlpha=s,e.fillRect(n*l+f,t*u+p,d,d)}e.restore()}function WD(e,t){return e<0||Math.abs(t-e)>1}function GD(e,t,n,r){return r||n<=0?e:e*(1-(1-Math.max(0,Math.min(1,t/n)))**3)}function KD(e,t,n,r){for(let i=e.length-1;i>=0;i--){let a=e[i];if(!a.alive)continue;let o=t.get(a.agentId);if(!o)continue;let s=(a.featured?5:3)+18,c=n-o.x,l=r-o.y;if(c*c+l*l<=s*s)return a}return null}var qD=[`O`,`C`,`E`,`A`,`Em`,`HH`];function JD(e,t){let n=t/2,r=t/2,i=t/2-8;return qD.map((t,a)=>{let o=Math.PI*2*a/qD.length-Math.PI/2,s=Math.max(0,Math.min(1,e[t])),c=i*s;return`${n+Math.cos(o)*c},${r+Math.sin(o)*c}`}).join(` `)}function YD(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/qD.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function XD({profile:e,colonyMean:t,size:n=160}){let r=JD(e,n),i=t?JD(t,n):null,a=n/2,o=n/2,s=n/2-8;return(0,x.jsxs)(`svg`,{width:n,height:n,role:`img`,"aria-label":`HEXACO profile radar`,children:[[.25,.5,.75,1].map(e=>(0,x.jsx)(`circle`,{cx:a,cy:o,r:s*e,fill:`none`,stroke:`var(--border)`,strokeDasharray:e===1?void 0:`2 3`},e)),qD.map((e,t)=>{let r=YD(e,n,t);return(0,x.jsx)(`text`,{x:r.x,y:r.y,fontSize:`9`,fontFamily:`var(--mono)`,fill:`var(--text-3)`,textAnchor:`middle`,dominantBaseline:`middle`,children:r.label},e)}),i&&(0,x.jsx)(`polygon`,{points:i,fill:`none`,stroke:`var(--text-3)`,strokeWidth:`1`,strokeDasharray:`3 3`}),(0,x.jsx)(`polygon`,{points:r,fill:`color-mix(in srgb, var(--amber) 25%, transparent)`,stroke:`var(--amber)`,strokeWidth:`1.5`})]})}var ZD={backdrop:`_backdrop_gccy2_1`,popover:`_popover_gccy2_8`,headerRow:`_headerRow_gccy2_25`,headerName:`_headerName_gccy2_34`,headerSubline:`_headerSubline_gccy2_42`,featuredPill:`_featuredPill_gccy2_49`,closeBtn:`_closeBtn_gccy2_59`,section:`_section_gccy2_72`,sectionLast:`_sectionLast_gccy2_77`,statsGrid:`_statsGrid_gccy2_81`,statKey:`_statKey_gccy2_88`,statValue:`_statValue_gccy2_92`,statValueUpper:`_statValueUpper_gccy2_96`,sectionLabel:`_sectionLabel_gccy2_101`,hexacoRow:`_hexacoRow_gccy2_110`,hexacoRadarWrap:`_hexacoRadarWrap_gccy2_116`,hexacoTopAxes:`_hexacoTopAxes_gccy2_120`,memoryList:`_memoryList_gccy2_126`,memoryItem:`_memoryItem_gccy2_132`,chatBtn:`_chatBtn_gccy2_143`},QD={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function $D(e){if(!e)return``;let t=Object.entries(e);return t.sort((e,t)=>t[1]-e[1]),t.slice(0,2).map(([e,t])=>`${QD[e]} ${t.toFixed(2)}`).join(` · `)}function eO(e){let{payload:t,containerW:n,containerH:r,sideColor:i,hexacoById:a,snapshots:o,onClose:s,onOpenChat:c}=e,l=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,s]);let u=(0,b.useMemo)(()=>{if(t&&a)return a.get(t.cell.agentId)??a.get(t.cell.name)},[t,a]),d=(0,b.useMemo)(()=>{if(!t)return[];let e=[...t.cell.shortTermMemory??[]];if(o)for(let n=o.length-1;n>=0&&e.length<3;n--){let r=o[n].cells.find(e=>e.agentId===t.cell.agentId);if(r){for(let t of r.shortTermMemory??[])if(t&&!e.includes(t)&&e.push(t),e.length>=3)break}}return e.slice(0,3)},[t,o]),f=My(Py);if(!t)return null;let p=f?Math.min(320,n-16):320,m=Math.min(360,r-20),h=f?Math.max(8,(n-p)/2):t.x+p+10>n?Math.max(10,t.x-p-10):Math.min(n-p-10,t.x+10),g=f?Math.max(8,(r-m)/2):t.y-m-10<0?Math.min(r-m-10,t.y+10):Math.max(10,t.y-m-10),_=t.cell,v=typeof _.psychScore==`number`?Math.round(_.psychScore*100):null,y=(()=>{let e=_.generation??0;return e===0?`Earth-born`:e===1?`First-native`:`Gen ${e}`})(),S=Math.max(120,r-g-10),C={"--side-color":i,"--pop-left":`${h}px`,"--pop-top":`${g}px`,"--pop-width":`${p}px`,"--pop-max-height":`${S}px`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:s,className:ZD.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:ZD.popover,style:C,children:[(0,x.jsxs)(`div`,{className:ZD.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:ZD.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:ZD.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:ZD.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:ZD.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:ZD.section,children:(0,x.jsxs)(`div`,{className:ZD.statsGrid,children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:ZD.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:ZD.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:y}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:ZD.hexacoRow,children:[(0,x.jsx)(`div`,{className:ZD.hexacoRadarWrap,children:(0,x.jsx)(XD,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:ZD.hexacoTopAxes,children:$D(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:ZD.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:ZD.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:ZD.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:ZD.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var tO={backdrop:`_backdrop_18xl4_1`,drawer:`_drawer_18xl4_8`,header:`_header_18xl4_25`,closeBtn:`_closeBtn_18xl4_32`,row:`_row_18xl4_45`,rowLabel:`_rowLabel_18xl4_53`,pillRow:`_pillRow_18xl4_58`,pill:`_pill_18xl4_58`,pillActive:`_pillActive_18xl4_76`,resetBtn:`_resetBtn_18xl4_81`},nO={deptLabels:!1,crosshair:!0,alerts:!0,sound:!1};function rO(e){let t={...nO};for(let n of Object.keys(nO))typeof e[n]==`boolean`&&(t[n]=e[n]);return t}function iO({open:e,settings:t,onChange:n,onClose:r}){let i=Pt(e);if((0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),!e)return null;let a=(e,r)=>{n({...t,[e]:r})};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:r,className:tO.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:tO.drawer,children:[(0,x.jsxs)(`div`,{className:tO.header,children:[(0,x.jsx)(`span`,{style:Pw,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:tO.closeBtn,children:`×`})]}),(0,x.jsxs)(aO,{label:`Dept labels`,children:[(0,x.jsx)(oO,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Crosshair`,children:[(0,x.jsx)(oO,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Alert toasts`,children:[(0,x.jsx)(oO,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Sound cues`,children:[(0,x.jsx)(oO,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(nO),style:Fw,className:tO.resetBtn,children:`Reset defaults`})]})]})}function aO({label:e,children:t}){return(0,x.jsxs)(`div`,{className:tO.row,children:[(0,x.jsx)(`span`,{style:Nw,className:tO.rowLabel,children:e}),(0,x.jsx)(`div`,{className:tO.pillRow,children:t})]})}function oO({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[tO.pill,e?tO.pillActive:``].filter(Boolean).join(` `),children:n})}var sO={drawer:`_drawer_tksc5_1`,header:`_header_tksc5_17`,headerLabel:`_headerLabel_tksc5_26`,closeBtn:`_closeBtn_tksc5_34`,sortRow:`_sortRow_tksc5_47`,sortChip:`_sortChip_tksc5_54`,active:`_active_tksc5_69`,body:`_body_tksc5_74`,empty:`_empty_tksc5_80`,deptHeader:`_deptHeader_tksc5_86`,row:`_row_tksc5_95`,deceased:`_deceased_tksc5_115`,swatch:`_swatch_tksc5_119`,rowName:`_rowName_tksc5_128`,featuredPill:`_featuredPill_tksc5_135`,deceasedToggle:`_deceasedToggle_tksc5_144`},cO={positive:`rgba(106, 173, 72, 1)`,hopeful:`rgba(154, 205, 96, 1)`,neutral:`rgba(107, 95, 80, 1)`,anxious:`rgba(232, 180, 74, 1)`,negative:`rgba(224, 101, 48, 1)`,defiant:`rgba(196, 74, 30, 1)`,resigned:`rgba(168, 152, 120, 1)`},lO=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function uO({open:e,cells:t,actorName:n,sideColor:r,searchQuery:i,hoveredId:a,onHover:o,onSelect:s,onClose:c}){let[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(`dept`),p=Lm(),{alive:m,deceased:h,matchSet:g}=(0,b.useMemo)(()=>{let e=[],n=[];for(let r of t)r.alive?e.push(r):n.push(r);d===`dept`?e.sort((e,t)=>e.department.localeCompare(t.department)||e.name.localeCompare(t.name)):d===`name`?e.sort((e,t)=>e.name.localeCompare(t.name)):d===`psych`?e.sort((e,t)=>(t.psychScore??0)-(e.psychScore??0)):d===`age`&&e.sort((e,t)=>(t.age??0)-(e.age??0)),n.sort((e,t)=>e.name.localeCompare(t.name));let r=i.trim().toLowerCase().split(/\s+/).filter(Boolean),a=new Set;if(r.length>0)for(let e of t){let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();r.every(e=>t.includes(e))&&a.add(e.agentId)}return{alive:e,deceased:n,matchSet:a}},[t,i,d]),_=(0,b.useMemo)(()=>{if(d!==`dept`)return[[`__flat__`,m]];let e=new Map;for(let t of m){let n=(t.department||`unknown`).toLowerCase(),r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))},[m,d]);if(!e)return null;let v={"--side-color":r},y=(e,t,n)=>({"--row-color":t?`var(--text-4)`:`var(--text-2)`,"--row-bg":n?`var(--bg-card)`:e?`color-mix(in srgb, ${r} 13%, transparent)`:`transparent`,"--row-border":e?r:`transparent`,"--row-opacity":t?`0.55`:`1`});return(0,x.jsxs)(`div`,{className:sO.drawer,children:[(0,x.jsxs)(`div`,{className:sO.header,style:v,children:[(0,x.jsxs)(`span`,{className:sO.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:sO.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:sO.sortRow,children:lO.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[sO.sortChip,t?sO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:sO.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:sO.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:sO.deptHeader,children:[e,` · `,t.length]}),t.map(e=>{let t=g.has(e.agentId),n=a===e.agentId,r=i.trim().length>0&&!t;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · ${e.mood}`,className:sO.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":cO[e.mood]??cO.neutral}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:sO.featuredPill,style:v,children:`★`})]},e.agentId)})]},e)),h.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:sO.deceasedToggle,children:[l?`▼`:`▶`,` Deceased · `,h.length]}),l&&h.map(e=>{let t=a===e.agentId;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · deceased`,className:[sO.row,sO.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name})]},e.agentId)})]})]})]})}function dO({snapshot:e,previousSnapshot:t,sideColor:n,onSelect:r}){let[i,a]=(0,b.useState)([]),o=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{if(!e)return;let n=e.cells.filter(e=>e.alive&&e.featured),r=t?new Set(t.cells.filter(e=>e.alive&&e.featured).map(e=>e.agentId)):o.current,i=n.filter(e=>!r.has(e.agentId));if(o.current=new Set(n.map(e=>e.agentId)),i.length===0)return;let s=performance.now()+6e3;a(i.slice(0,2).map(t=>({cell:t,turn:e.turn,expiresAt:s})))},[e,t]),(0,b.useEffect)(()=>{if(i.length===0)return;let e=Math.max(0,i[0].expiresAt-performance.now()),t=setTimeout(()=>a([]),e);return()=>clearTimeout(t)},[i]);let s=(0,b.useMemo)(()=>i,[i]);return s.length===0?null:(0,x.jsx)(`div`,{"aria-live":`polite`,style:{position:`absolute`,bottom:12,right:12,display:`flex`,flexDirection:`column`,gap:4,pointerEvents:`none`,zIndex:7,maxWidth:240},children:s.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>r?.(e.cell),"aria-label":`Spotlight: ${e.cell.name} · ${e.cell.department}`,title:`${e.cell.name} · ${e.cell.role} · ${e.cell.department} · mood: ${e.cell.mood}`,style:{pointerEvents:`auto`,display:`flex`,alignItems:`center`,gap:6,padding:`4px 10px`,background:`var(--bg-panel)`,border:`1px solid ${n}66`,borderLeft:`3px solid ${n}`,borderRadius:3,fontFamily:`var(--mono)`,fontSize:`var(--font-xs)`,color:`var(--text-2)`,textAlign:`left`,cursor:`pointer`,boxShadow:`0 4px 14px rgba(0, 0, 0, 0.4)`,animation:`paracosm-spotlight-in 380ms ease-out`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`,maxWidth:`100%`},children:[(0,x.jsx)(`span`,{style:{color:n,fontSize:`var(--font-2xs)`,flexShrink:0},"aria-hidden":`true`,children:`★`}),(0,x.jsx)(`span`,{style:{color:`var(--text-1)`,fontWeight:700,overflow:`hidden`,textOverflow:`ellipsis`},children:e.cell.name}),(0,x.jsx)(`span`,{style:{color:`var(--text-3)`,fontSize:`var(--font-2xs)`,flexShrink:0,textTransform:`uppercase`,letterSpacing:`0.04em`},children:e.cell.department})]},e.cell.agentId))})}function fO(e){let t=[];return typeof e.foodReserve==`number`&&t.push(`food reserve ${e.foodReserve.toFixed(1)} months`),typeof e.waterLitersPerDay==`number`&&t.push(`water ${Math.round(e.waterLitersPerDay)} litres a day`),typeof e.powerKw==`number`&&t.push(`power ${Math.round(e.powerKw)} kW`),typeof e.pressurizedVolumeM3==`number`&&t.push(`pressurized volume ${Math.round(e.pressurizedVolumeM3)} cubic metres`),t.map(e=>`, ${e}`).join(``)}function pO(e,t){if(e.startsWith(`var(`)&&t){let n=e.slice(4,-1).trim(),r=getComputedStyle(t).getPropertyValue(n).trim();if(r)return r}return e}function mO(e){let{snapshot:t,previousSnapshot:n,snapshotHistory:r,actorName:i,actorArchetype:a,startTime:o,sideColor:s,side:c,lagTurns:l,clusterMode:u=`departments`,initialPopulation:d=20,mode:f,hexacoById:p,leaderHexaco:m,forgeAttempts:h,reuseCalls:g,divergedIds:_,siblingHoveredId:v,onHoverChange:y,searchQuery:S=``,palette:C=0,settings:w=nO,focusedSide:T=null,onToggleFocus:E,onOpenChat:D,eventFilter:O=`all`,chronicleHover:k=null}=e,A=T===c,j=My(Ny),ee=My(Iy),te=Lm(),M=(0,b.useRef)(null),N=(0,b.useRef)(null),ne=(0,b.useRef)(null),[P,re]=(0,b.useState)({w:0,h:0}),[ie,F]=(0,b.useState)(null),[I,ae]=(0,b.useState)(null),[oe,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(!1),[L,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(ee){fe(!0);return}let e=requestAnimationFrame(()=>fe(!0));return()=>cancelAnimationFrame(e)},[ee]);let R=(0,b.useRef)(zD(ED.cols,ED.rows)),z=(0,b.useRef)(-1),pe=(0,b.useRef)(``),me=(0,b.useRef)(``),he=(0,b.useRef)(null),ge=(0,b.useRef)(null),_e=(0,b.useRef)(-1/0),B=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=N.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(0,Math.round(t.contentRect.width)),n=Math.max(0,Math.round(t.contentRect.height));re(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ne.current;if(!e||P.w===0||P.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(P.w*t),e.height=Math.round(P.h*t),e.style.width=`${P.w}px`,e.style.height=`${P.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[P.w,P.h]);let ve=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),ye=(0,b.useMemo)(()=>!t||P.w===0?new Map:eD(t.cells,ve,P.w,P.h),[t,ve,P.w,P.h]),be=(0,b.useMemo)(()=>t?yD(t.cells,ye):new Map,[t,ye]),xe=vD({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},N,()=>ye,()=>be),Se=f===`forge`?.7:f===`ecology`?0:1,Ce=(0,b.useMemo)(()=>{if(f!==`mood`||!t)return s;let e=t.cells.filter(e=>e.alive);if(e.length===0)return s;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=`neutral`,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);switch(r){case`positive`:case`hopeful`:return`var(--green)`;case`anxious`:return`var(--amber)`;case`negative`:case`defiant`:return`var(--rust)`;case`resigned`:return`var(--text-3)`;default:return s}},[f,t,s]);(0,b.useEffect)(()=>{let e=ne.current;if(!e||!t||P.w===0||P.h===0)return;let r=e.getContext(`2d`);if(!r)return;let c=xe.flares.filter(e=>O===`all`?!0:O===`birth`?e.kind===`birth`:O===`death`?e.kind===`death`:O===`crisis`?e.kind===`crisis`:O!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=pO(s,M.current),d=M.current?getComputedStyle(M.current):null,p=(e,t)=>{if(!e.startsWith(`#`)||e.length!==7)return null;let n=parseInt(e.slice(1),16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${t})`},m=d&&p(d.getPropertyValue(`--bg-deep`).trim(),.85)||`rgba(10, 8, 6, 0.85)`,g=d&&p(d.getPropertyValue(`--text-2`).trim(),.8)||`rgba(216, 204, 176, 0.75)`,y=d&&p(d.getPropertyValue(`--text-2`).trim(),.22)||`rgba(216, 204, 176, 0.22)`,b=d&&p(d.getPropertyValue(`--text-2`).trim(),.7)||`rgba(216, 204, 176, 0.7)`,x=d&&p(d.getPropertyValue(`--text-2`).trim(),.95)||`rgba(216, 204, 176, 0.95)`,C=d&&p(d.getPropertyValue(`--text-3`).trim(),.85)||`rgba(168, 152, 120, 0.85)`,T=d&&p(d.getPropertyValue(`--text-3`).trim(),.08)||`rgba(168, 152, 120, 0.08)`,E=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,P.w,P.h);let D=R.current,k=f!==pe.current,A=t.turn!==z.current,j=O!==me.current,N=i!==he.current,re=z.current;if(A||k||j||N){z.current=t.turn,pe.current=f,me.current=O,he.current=i,BD(D,t.cells,ye,P.w,P.h,O);let e;e=ee?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)HD(D);!ee&&(A&&WD(re,t.turn)||N)&&(_e.current=performance.now()),ge.current=c.length?`${c[0].kind}|${c[0].x}|${c[0].y}`:null}else if(c.length>0){let e=`${c[0].kind}|${c[0].x}|${c[0].y}`;e!==ge.current&&(ge.current=e,VD(D,c[0],P.w,P.h),ee||HD(D))}let F=GD(typeof document<`u`&&document.documentElement.classList.contains(`light`)?.22:.65,performance.now()-_e.current,500,ee);if(UD(r,D,P.w,P.h,u,F),O===`death`?FD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows,C,T):O===`birth`&&PD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows),iD(r,c),f!==`ecology`&&tD(r,t.cells,ye,u,Se,_,f===`divergence`,ee?0:performance.now(),S,!0,g,m),f===`forge`&&h&&h.length>0&&cD(r,t.cells,ye,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&lD(r,t,P.w,P.h,E),f===`divergence`&&uD(r,t.cells,ye,_,ee?0:performance.now(),u),sD(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:P.w,height:P.h,lagTurns:l,cells:t.cells,positions:ye,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:te.Time}),ie){let e=ye.get(ie.cell.agentId);e&&(r.save(),r.strokeStyle=u,r.lineWidth=2,r.globalAlpha=1,r.beginPath(),r.arc(e.x,e.y,10,0,Math.PI*2),r.stroke(),r.restore())}if(I&&!ie&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,I.y),r.lineTo(P.w,I.y),r.moveTo(I.x,0),r.lineTo(I.x,P.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=ye.get(n.agentId);if(!t)continue;let r=t.x-I.x,i=t.y-I.y,a=r*r+i*i;a>1600||(!e||a<e.d2)&&(e={id:n.agentId,name:n.name,dx:r,dy:i,d2:a})}e&&(r.save(),r.strokeStyle=b,r.setLineDash([2,3]),r.lineWidth=.6,r.beginPath(),r.moveTo(I.x,I.y),r.lineTo(I.x+e.dx,I.y+e.dy),r.stroke(),r.setLineDash([]),r.fillStyle=x,r.font=`bold 11px ui-monospace, monospace`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`\u2192 ${e.name.split(` `)[0]}`,I.x+6,I.y+6),r.restore())}if(v&&v!==ie?.cell.agentId){let e=ye.get(v);e&&(r.save(),r.strokeStyle=`rgba(232, 180, 74, 0.75)`,r.lineWidth=1.4,r.globalAlpha=.85,r.setLineDash([3,3]),r.beginPath(),r.arc(e.x,e.y,11,0,Math.PI*2),r.stroke(),r.setLineDash([]),r.restore())}},[xe.tickClock,t,ye,P.w,P.h,s,i,l,xe.flares,f,Se,ie,_,v,ee,S,I,w,a,o,h,O]);let we=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;ae({x:r,y:i});let a=KD(t.cells,ye,r,i);if(a){F(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ue(null),y?.(a.agentId);return}ie&&(F(null),y?.(null));let o=ED.cols,s=ED.rows,c=O===`death`||O===`birth`?(()=>{let e=Math.floor(r/Math.max(1,P.w)*o),n=Math.floor(i/Math.max(1,P.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(O===`death`&&r.alive||O===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:O===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=ID(R.current,r,i,P.w,P.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s),c=(i.col-e.col)**2+(i.row-e.row)**2;c<a&&(a=c,n=r)}return{col:e.col,row:e.row,kind:`life`,nearest:n}})();c?ue({x:r,y:i,...c}):L&&ue(null)},[t,ye,ie,y,O,P.w,P.h,L]),Te=(0,b.useCallback)(()=>{F(null),ue(null),ae(null),y?.(null)},[y]),Ee=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=KD(t.cells,ye,r,i);a?(se({cell:a,x:r,y:i}),F(null),ue(null),B.current={id:a.agentId,intensity:1}):L?.nearest&&(se({cell:L.nearest,x:r,y:i}),F(null),ue(null))},[t,ye,L]),De=(0,b.useRef)(null),Oe=(0,b.useCallback)(e=>{if(!t)return;let n=e.touches[0];if(!n)return;let r=e.currentTarget.getBoundingClientRect(),i=n.clientX-r.left,a=n.clientY-r.top,o=KD(t.cells,ye,i,a);o?De.current===o.agentId?(se({cell:o,x:i,y:a}),F(null),De.current=null,B.current={id:o.agentId,intensity:1}):(F({cell:o,x:i,y:a}),ae({x:i,y:a}),De.current=o.agentId,y?.(o.agentId)):(F(null),ae(null),De.current=null,y?.(null))},[t,ye,y]);(0,b.useEffect)(()=>{oe&&t&&(t.cells.find(e=>e.agentId===oe.cell.agentId)||se(null))},[oe,t]),(0,b.useEffect)(()=>{oe||(De.current=null)},[oe]);let ke=pO(f===`mood`?Ce:s,M.current),Ae={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},je={birth:`rgba(154, 205, 96, 0.55)`,death:`rgba(200, 95, 80, 0.55)`,forge:`rgba(232, 180, 74, 0.55)`,crisis:`rgba(196, 74, 30, 0.55)`},Me=k&&k.side===c?Ae[k.kind]:t?t.morale>=.6?`rgba(106, 173, 72, 0.55)`:t.morale>=.3?`rgba(232, 180, 74, 0.55)`:`rgba(196, 74, 30, 0.65)`:`${s}33`,Ne=k&&k.side===c?`0 0 24px ${je[k.kind]}`:t?t.morale>=.6?`0 0 16px rgba(106, 173, 72, 0.18)`:t.morale>=.3?`0 0 16px rgba(232, 180, 74, 0.12)`:`0 0 20px rgba(196, 74, 30, 0.25)`:`none`;return(0,x.jsxs)(`div`,{ref:M,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${te.place} viz`,className:[WE.region,j?WE.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(TD,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:N,className:WE.canvasWrap,style:{"--tint-color":ke,"--wrap-border":Me,"--wrap-glow":Ne},children:[(0,x.jsx)(`canvas`,{ref:ne,role:`img`,"aria-label":t?`${i} ${te.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${fO(t)}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${te.person} glyph for drilldown.`:`${i} ${te.place} — waiting for first turn.`,onMouseMove:we,onMouseLeave:Te,onClick:Ee,onTouchStart:Oe,className:WE.canvas,style:{"--canvas-cursor":ie?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:WE.revealCover,style:{"--reveal-opacity":de?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>le(e=>!e),"aria-label":ce?`Close roster`:`Open roster`,title:ce?`Close roster`:`Open roster`,className:WE.cornerBtn,style:{"--right-offset":E?`36px`:`8px`,"--btn-color":ce?`var(--amber)`:`var(--text-3)`,"--btn-border":ce?`var(--amber)`:`var(--border)`},children:`☰`}),E&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>E(c),"aria-label":A?`Restore split view`:`Focus this panel`,title:A?`Restore split view`:`Focus this panel`,className:`${WE.cornerBtn} ${WE.focusBtn}`,style:{"--btn-color":A?`var(--amber)`:`var(--text-3)`,"--btn-border":A?`var(--amber)`:`var(--border)`},children:A?`⤡`:`⤢`}),(0,x.jsx)(dO,{snapshot:t,previousSnapshot:n,sideColor:pO(s,M.current),onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(uO,{open:ce,cells:t?.cells??[],actorName:i,sideColor:pO(s,M.current),searchQuery:S,hoveredId:ie?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?ye.get(e):null;if(n&&r){F({cell:n,x:r.x,y:r.y}),y?.(e);return}}F(null),y?.(null)},onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})},onClose:()=>le(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:WE.divergenceEmpty,children:(0,x.jsx)(`div`,{className:WE.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),L&&!ie&&!oe&&(()=>{let e=Math.min(Math.max(8,L.x+12),Math.max(8,P.w-220-8)),t=Math.max(8,L.y-84),n=L.kind===`birth`?`+ BIRTH MARKER`:L.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=L.kind===`birth`?`rgba(154, 205, 96, 0.95)`:L.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:WE.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:WE.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:WE.tileCoords,children:[`tile (`,L.col,`, `,L.row,`)`]}),L.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:WE.tileNearestName,children:L.nearest.name}),(0,x.jsxs)(`div`,{className:WE.tileNearestRole,children:[L.nearest.role,` · `,L.nearest.department.toUpperCase()]}),L.kind===`death`?(0,x.jsxs)(`div`,{className:WE.tileNearestDeath,children:[`deceased · mood at death: `,L.nearest.mood]}):L.kind===`birth`?(0,x.jsxs)(`div`,{className:WE.tileNearestBirth,children:[`native-born · generation `,L.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,L.nearest.mood]})]}):(0,x.jsx)(`div`,{className:WE.tileAmbient,children:`ambient CA cell`}),L.kind===`life`&&(()=>{let e=R.current,t=e.cols,n=e.rows,r=e.grid[L.row*t+L.col]??0,i=0;for(let r=-1;r<=1;r++)for(let a=-1;a<=1;a++){if(r===0&&a===0)continue;let o=L.row+r,s=L.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),ie&&!oe&&(()=>{let e=Math.min(Math.max(8,ie.x+12),Math.max(8,P.w-200-8)),t=Math.min(Math.max(8,ie.y-80-8),Math.max(8,P.h-80-8));return(0,x.jsxs)(`div`,{className:WE.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:WE.hoverHeader,children:[ie.cell.name,ie.cell.featured&&(0,x.jsx)(`span`,{className:WE.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:WE.hoverRole,children:[ie.cell.department.toUpperCase(),` · `,ie.cell.role,typeof ie.cell.age==`number`?` · age ${ie.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:WE.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:WE.hoverMoodValue,children:ie.cell.mood}),typeof ie.cell.psychScore==`number`?` · psych ${Math.round(ie.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===ie.cell.agentId);n&&typeof n.psychScore==`number`&&e.push(Math.max(0,Math.min(1,n.psychScore)))}if(e.length<2)return null;let t=136/Math.max(1,e.length-1),n=e.map((e,n)=>{let r=2+n*t,i=2+(1-e)*16;return`${n===0?`M`:`L`}${r.toFixed(1)},${i.toFixed(1)}`}).join(` `);return(0,x.jsxs)(`div`,{className:WE.psychBlock,children:[(0,x.jsx)(`div`,{className:WE.psychLabel,children:`PSYCH TRAJECTORY`}),(0,x.jsxs)(`svg`,{viewBox:`0 0 140 20`,preserveAspectRatio:`none`,width:140,height:20,role:`img`,"aria-label":`Psychological trajectory across ${e.length} turns`,className:WE.psychSvg,children:[(0,x.jsx)(`line`,{x1:2,x2:138,y1:10,y2:10,stroke:`var(--border)`,strokeWidth:.4,strokeDasharray:`2 2`}),(0,x.jsx)(`path`,{d:n,fill:`none`,stroke:s,strokeWidth:1}),(0,x.jsx)(`circle`,{cx:2+(e.length-1)*t,cy:2+(1-e[e.length-1])*16,r:1.6,fill:s})]})]})})(),(0,x.jsx)(`div`,{className:WE.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(eO,{payload:oe,containerW:P.w,containerH:P.h,sideColor:pO(s,M.current),hexacoById:p,snapshots:r,onClose:()=>se(null),onOpenChat:D})]})]})}var hO={track:`_track_1u01e_1`,trackInner:`_trackInner_1u01e_29`,column:`_column_1u01e_38`,columnHeader:`_columnHeader_1u01e_64`,columnHeaderSlot:`_columnHeaderSlot_1u01e_80`,columnHeaderText:`_columnHeaderText_1u01e_89`,columnHeaderName:`_columnHeaderName_1u01e_96`,columnHeaderArchetype:`_columnHeaderArchetype_1u01e_105`,columnHeaderPop:`_columnHeaderPop_1u01e_116`,columnBody:`_columnBody_1u01e_125`,columnPlaceholder:`_columnPlaceholder_1u01e_133`,columnPlaceholderShimmer:`_columnPlaceholderShimmer_1u01e_145`,"cohort-shimmer":`_cohort-shimmer_1u01e_1`,columnPlaceholderLabel:`_columnPlaceholderLabel_1u01e_159`};function gO(e){let t=[],n=[],r=new Map;for(let i of e){if(i.type===`forge_attempt`){let e=i.data||{},n=e.approved===!0||e.approved===`true`;t.push({turn:Number(e.turn??0),eventIndex:Number(e.eventIndex??0),department:String(e.department||``),name:String(e.name||``),approved:n,confidence:typeof e.confidence==`number`?e.confidence:void 0}),e.name&&e.department&&n&&!r.has(String(e.name))&&r.set(String(e.name),String(e.department));continue}if(i.type!==`specialist_done`)continue;let e=i.data||{},a=String(e.department||``),o=Array.isArray(e.forgedTools)?e.forgedTools:[];for(let t of o){let o=t,s=String(o.name||``);if(!s||s===`unnamed`)continue;let c=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):r.get(s),l=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,u=Number(i.turn??e.turn??0);(c&&l!==void 0&&l<u||c&&c!==a)&&n.push({turn:u,originDept:c,callingDept:a,name:s})}}return{attempts:t,reuses:n}}function _O(e){let{actorIndex:t,actorId:n,state:r,snaps:i,currentTurn:a,gridMode:o,palette:s,gridSettings:c,hexacoById:l,searchQuery:u,chronicleFilter:d,chronicleHover:f,startTime:p,onOpenChat:m}=e,h=(0,b.useRef)(null),[g,_]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(g)return;let e=h.current;if(!e)return;if(typeof IntersectionObserver>`u`){_(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){_(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[g]);let v=r.actors[n]??null,y=v?.leader??null,S=i[a],C=a>0?i[a-1]:void 0,w=Pe(t),T=y?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>v?gO(v.events):{attempts:[],reuses:[]},[v]),D=y?.hexaco?{O:y.hexaco.O??y.hexaco.openness??.5,C:y.hexaco.C??y.hexaco.conscientiousness??.5,E:y.hexaco.E??y.hexaco.extraversion??.5,A:y.hexaco.A??y.hexaco.agreeableness??.5,Em:y.hexaco.Em??y.hexaco.emotionality??.5,HH:y.hexaco.HH??y.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:h,className:hO.column,style:{"--actor-color":w},"aria-label":`Living swarm grid for actor ${t+1}: ${T}`,children:[(0,x.jsxs)(`header`,{className:hO.columnHeader,children:[(0,x.jsxs)(`span`,{className:hO.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:hO.columnHeaderText,children:[(0,x.jsx)(`span`,{className:hO.columnHeaderName,children:T}),y?.archetype&&(0,x.jsx)(`span`,{className:hO.columnHeaderArchetype,children:y.archetype})]}),(0,x.jsxs)(`span`,{className:hO.columnHeaderPop,title:`Population alive · morale`,children:[S?.population??`—`,` · `,S?Math.round(S.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:hO.columnBody,children:g?(0,x.jsx)(mO,{snapshot:S,previousSnapshot:C,snapshotHistory:i,actorName:T,actorArchetype:y?.archetype??``,leaderUnit:y?.unit??``,sideColor:w,side:`a`,mode:o,hexacoById:l,leaderHexaco:D,forgeAttempts:E.attempts,reuseCalls:E.reuses,searchQuery:u,palette:s,settings:c,startTime:p,onOpenChat:m,eventFilter:d,chronicleHover:f}):(0,x.jsxs)(`div`,{className:hO.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:hO.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:hO.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function vO({state:e,snapshotMap:t,currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d,className:f}){let p=e.actorIds;return(0,x.jsx)(`div`,{className:[hO.track,f].filter(Boolean).join(` `),role:`region`,"aria-label":`Cohort swarm grid: ${p.length} actors`,children:(0,x.jsx)(`div`,{className:hO.trackInner,children:p.map((f,p)=>(0,x.jsx)(_O,{actorId:f,actorIndex:p,state:e,snaps:t[f]??[],currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d},f))})})}function yO(e){let t=(e.decision||``).split(/[.;]/)[0].trim(),n=t.length>80?t.slice(0,77)+`...`:t,r=e.outcome.startsWith(`risky`),i=e.outcome.endsWith(`success`),a=n.length===0?`held position`:r?i?`gambled on`:`took the risk of`:`chose`,o=n.length===0?``:n.replace(/^(select|implement|issue|move|expand|reduce|slow|initiate|start|deliver)\s+/i,``).replace(/\s+$/,``),s=o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`,c=typeof e.dominantDeaths==`number`&&e.dominantDeaths>0&&e.dominantDeaths<e.deaths;return`${s}${e.deaths>0&&e.dominantCause?c?`, ${e.deaths} lost, ${e.dominantDeaths} to ${e.dominantCause}`:`, ${e.deaths} lost to ${e.dominantCause}`:e.deaths>0?`, ${e.deaths} lost`:``}${e.moraleDelta<=-.08?`; morale cracked`:e.moraleDelta>=.08?`; morale steadied`:``}`}var bO={banner:`_banner_gzmtg_1`,headline:`_headline_gzmtg_12`,collapseBtn:`_collapseBtn_gzmtg_20`,turnLabel:`_turnLabel_gzmtg_39`,title:`_title_gzmtg_43`,categoryPill:`_categoryPill_gzmtg_48`,lineA:`_lineA_gzmtg_58`,lineB:`_lineB_gzmtg_62`,line:`_line_gzmtg_58`,lineLabel:`_lineLabel_gzmtg_78`,lineBody:`_lineBody_gzmtg_85`,lineMore:`_lineMore_gzmtg_91`};function xO(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=null,o=0,s=0,c=``,l=``,u=0;for(let n of e.events)if((n.data?.turn??-1)===t+1){if((n.type===`turn_start`||n.type===`event_start`)&&(c=String(n.data?.title??c),l=String(n.data?.category??l),u=Number(n.data?.time??u)),n.type===`outcome`){i=String(n.data?.outcome??i);let e=n.data?._decision;typeof e==`string`&&e.length>0&&(r=e);let t=n.data?.systemDeltas?.morale;typeof t==`number`&&Number.isFinite(t)&&(s+=t)}if(n.type===`turn_done`){let e=n.data?.deathCauses;e&&typeof e==`object`&&(a=e)}n.type===`systems_snapshot`&&(o=Number(n.data?.deaths)||0)}let d=o,f=null,p;if(a){let e=0,t=0;for(let[n,r]of Object.entries(a))typeof r!=`number`||r<=0||(e+=r,r>t&&(t=r,f=n));e>0&&(d=e,p=t)}return{actorName:n,decision:r,outcome:i,deaths:d,dominantCause:f,dominantDeaths:p,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}function SO(e,t){for(let n of e.actorIds){let r=e.actors[n],i=r?xO(r,t)?.eventTitle:``;if(i)return i}return``}var CO=6;function wO({state:e,currentTurn:t,linesTarget:n,cohortGridShown:r=!0}){let i=e.actorIds.length>2,[a,o]=(0,b.useState)(i),s=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?xO(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),c=s.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,l=s.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,u=s.find(e=>e.summary.time)?.summary.time||0;if(!c)return null;let d=s.slice(0,CO),f=s.length-d.length,p=!a,m=s.length>0,h=p?(0,x.jsxs)(x.Fragment,{children:[d.map((e,t)=>(0,x.jsxs)(`div`,{className:s.length<=2?t===0?bO.lineA:bO.lineB:bO.line,children:[(0,x.jsx)(`span`,{className:bO.lineLabel,children:s.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:bO.lineBody,children:[`: `,yO(e.summary)]})]},e.actorId)),f>0&&(0,x.jsxs)(`div`,{className:bO.lineMore,children:[`+`,f,` more `,`·`,` `,r?`see cohort grid ${n?`above`:`below`} for the rest`:`open All ${e.actorIds.length} actors for the rest`]})]}):null;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:bO.banner,children:[(0,x.jsxs)(`div`,{className:bO.headline,children:[(0,x.jsxs)(`span`,{className:bO.turnLabel,children:[`T`,t+1,u?` \u00b7 ${u}`:``]}),(0,x.jsx)(`span`,{className:bO.title,children:c}),l&&(0,x.jsx)(`span`,{className:bO.categoryPill,children:l}),m&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-expanded":!a,"aria-label":a?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:bO.collapseBtn,children:a?`\u25be ${s.length} actors`:`▴ hide`})]}),h&&(n?(0,jy.createPortal)(h,n):h)]})}var TO={row:`_row_1jwlc_1`,key:`_key_1jwlc_16`,scrub:`_scrub_1jwlc_34`,turn:`_turn_1jwlc_39`,timeShownAbove:`_timeShownAbove_1jwlc_51`,speed:`_speed_1jwlc_56`},EO=[.5,1,2,4];function DO({currentTurn:e,maxTurn:t,time:n,timeInBanner:r=!1,playing:i,speed:a,onTurnChange:o,onPlayPause:s,onStepBack:c,onStepForward:l,onSpeedChange:u}){return(0,x.jsxs)(`div`,{className:TO.row,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:e<=0,"aria-label":`Previous turn`,className:TO.key,children:`<<`}),(0,x.jsx)(`button`,{type:`button`,onClick:s,disabled:t<=1,"aria-label":i?`Pause`:`Play`,className:TO.key,children:i?`■`:`▶`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:e>=t-1,"aria-label":`Next turn`,className:TO.key,children:`>>`}),(0,x.jsx)(`input`,{type:`range`,min:0,max:Math.max(0,t-1),value:e,onChange:e=>o(Number(e.target.value)),className:TO.scrub,"aria-label":`Scrub timeline`,"aria-valuetext":`Turn ${e+1} of ${t}`}),(0,x.jsxs)(`span`,{className:TO.turn,children:[`T`,e+1,`/`,t,n?(0,x.jsx)(`span`,{className:r?TO.timeShownAbove:void 0,children:` \u00b7 ${n}`}):null]}),(0,x.jsx)(`select`,{"aria-label":`Playback speed`,value:a,onChange:e=>u(Number(e.target.value)),className:TO.speed,children:EO.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var OO=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; food, water, power and volume tint a quadrant each`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function kO(e,t){return e.replace(/\{person\}/g,t.person).replace(/\{Person\}/g,t.Person).replace(/\{people\}/g,t.people).replace(/\{People\}/g,t.People)}function AO(e,t){return kO(OO.find(t=>t.key===e)?.hint??``,t)}function jO({mode:e,onChange:t,counts:n,labels:r}){if(My(`(max-width: 480px)`)){let i=OO.find(t=>t.key===e),a=n?.[e],o=`calc(${`${i?.label??``}${typeof a==`number`&&a>0?` · ${a}`:``}`.length} * (1ch + 0.08em) + 44px)`;return(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:kO(OO.find(t=>t.key===e)?.hint??``,r),style:{flex:`1 1 auto`,width:o,minWidth:o,padding:`8px 10px`,fontSize:16,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,background:`var(--bg-card)`,color:`var(--text-1)`,border:`1px solid var(--border)`,borderRadius:6,cursor:`pointer`,minHeight:44},children:OO.map(e=>{let t=n?.[e.key],r=typeof t==`number`&&t>0?` · ${t}`:``;return(0,x.jsxs)(`option`,{value:e.key,children:[e.label,r]},e.key)})})}return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Grid viz mode`,style:{display:`flex`,gap:0,padding:`4px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:6,overflowX:`auto`,scrollbarWidth:`thin`},children:OO.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=kO(i.hint,r);return(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o,"data-grid-mode":i.key,onClick:()=>t(i.key),title:c,style:{flex:`1 0 auto`,padding:`5px 8px`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.1em`,border:`1px solid var(--border)`,borderLeft:a===0?`1px solid var(--border)`:`none`,borderRadius:a===0?`3px 0 0 3px`:a===OO.length-1?`0 3px 3px 0`:0,background:o?`var(--amber)`:`var(--bg-card)`,color:o?`var(--bg-deep)`:`var(--text-3)`,cursor:`pointer`,textTransform:`uppercase`,transition:`background 120ms, color 120ms`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:4,whiteSpace:`nowrap`},children:[(0,x.jsx)(`span`,{children:i.label}),typeof s==`number`&&s>0&&(0,x.jsx)(`span`,{style:{padding:`0 4px`,borderRadius:2,background:o?`rgba(10, 8, 6, 0.25)`:`var(--bg-deep)`,color:o?`var(--bg-deep)`:`var(--amber)`,fontSize:`var(--font-3xs)`,fontWeight:700,letterSpacing:`0.05em`,minWidth:14,textAlign:`center`},children:s})]},i.key)})})}var MO={backdrop:`_backdrop_bxhar_1`,dialog:`_dialog_bxhar_12`,phone:`_phone_bxhar_26`,header:`_header_bxhar_30`,title:`_title_bxhar_37`,closeBtn:`_closeBtn_bxhar_47`,section:`_section_bxhar_60`,sectionTitle:`_sectionTitle_bxhar_64`,rows:`_rows_bxhar_75`,row:`_row_bxhar_75`,rowKey:`_rowKey_bxhar_89`,rowVal:`_rowVal_bxhar_96`,swatchWrap:`_swatchWrap_bxhar_101`,swatch:`_swatch_bxhar_101`,footer:`_footer_bxhar_117`,kbd:`_kbd_bxhar_123`};function NO({open:e,onClose:t}){let n=My(Py),r=Lm();if(!e)return null;let i=[MO.dialog,n?MO.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:MO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:MO.header,children:[(0,x.jsxs)(`h2`,{className:MO.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:MO.closeBtn,children:`×`})]}),(0,x.jsxs)(PO,{title:`Modes`,children:[(0,x.jsx)(FO,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + event flares`}),(0,x.jsx)(FO,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(FO,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(FO,{k:`ECOLOGY`,v:`Hides glyphs; food, water, power and volume tint a quadrant each`}),(0,x.jsx)(FO,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(PO,{title:`Grid elements`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(FO,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(FO,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(FO,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(FO,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(PO,{title:`Event flares`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(PO,{title:`Keyboard`,children:[(0,x.jsx)(FO,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(FO,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(FO,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(FO,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(FO,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(FO,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:MO.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:MO.kbd,children:`?`}),` anytime to reopen.`]})]})})}function PO({title:e,children:t}){return(0,x.jsxs)(`div`,{className:MO.section,children:[(0,x.jsx)(`div`,{className:MO.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:MO.rows,children:t})]})}function FO({k:e,v:t}){return(0,x.jsxs)(`div`,{className:MO.row,children:[(0,x.jsx)(`span`,{className:MO.rowKey,children:e}),(0,x.jsx)(`span`,{className:MO.rowVal,children:t})]})}function IO({color:e}){return(0,x.jsx)(`span`,{className:MO.swatchWrap,children:(0,x.jsx)(`span`,{className:MO.swatch,style:{"--swatch-color":e}})})}var LO={wrap:`_wrap_10kb4_1`,legend:`_legend_10kb4_8`,legendRight:`_legendRight_10kb4_19`,legendA:`_legendA_10kb4_24`,legendB:`_legendB_10kb4_28`,legendKey:`_legendKey_10kb4_32`,svg:`_svg_10kb4_36`,tooltip:`_tooltip_10kb4_44`,tooltipTurn:`_tooltipTurn_10kb4_63`,tooltipRowA:`_tooltipRowA_10kb4_71`,tooltipRowB:`_tooltipRowB_10kb4_78`,tooltipBold:`_tooltipBold_10kb4_85`};function RO({snapsA:e,snapsB:t,currentTurn:n,onJumpToTurn:r,hoveredTurn:i,onHoverTurnChange:a}){let o=Math.max(e.length,t.length);if(o<2)return null;let s=(e,t)=>{if(e.length===0)return``;let n=588/Math.max(1,o-1),r=[],i=!1;return e.forEach((e,a)=>{let o=t(e);if(o===null){i=!1;return}let s=6+a*n,c=3+(1-o)*22;r.push(`${i?`L`:`M`}${s.toFixed(1)},${c.toFixed(1)}`),i=!0}),r.join(` `)},c=e.some(e=>typeof e.foodReserve==`number`),l=t.some(e=>typeof e.foodReserve==`number`),u=c||l,d=[...e,...t].map(e=>e.foodReserve).filter(e=>typeof e==`number`),f=Math.max(18,...d),p=Math.max(1,...e.map(e=>e.population),...t.map(e=>e.population)),m=e=>typeof e.foodReserve==`number`?Math.max(0,Math.min(1,e.foodReserve/f)):null,h=e=>Math.max(0,Math.min(1,e.population/p)),g=e=>Math.max(0,Math.min(1,e.morale)),_=6+n*(588/Math.max(1,o-1)),v=typeof i==`number`?6+i*(588/Math.max(1,o-1)):null,y=(e,t)=>{let n=(e-t.left)/t.width*600,r=Math.round((n-6)/588*(o-1));return Math.max(0,Math.min(o-1,r))};return(0,x.jsxs)(`div`,{className:LO.wrap,children:[(0,x.jsxs)(`div`,{className:LO.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:LO.legendRight,children:[(0,x.jsx)(`span`,{className:LO.legendA,children:`A`}),(0,x.jsx)(`span`,{className:LO.legendB,children:`B`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:LO.legendKey,children:`- - food`})]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 600 28`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Timeline sparkline of morale, population${u?`, and food`:``} across both leaders`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();r(y(e.clientX,t))},onMouseMove:e=>{if(!a)return;let t=e.currentTarget.getBoundingClientRect();a(y(e.clientX,t))},onMouseLeave:()=>{a?.(null)},className:LO.svg,height:28,children:[(0,x.jsx)(`line`,{x1:6,x2:594,y1:14,y2:14,stroke:`var(--border)`,strokeWidth:.5,strokeDasharray:`2 2`}),c&&(0,x.jsx)(`path`,{d:s(e,m),fill:`none`,stroke:`var(--vis)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),l&&(0,x.jsx)(`path`,{d:s(t,m),fill:`none`,stroke:`var(--eng)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),(0,x.jsx)(`path`,{d:s(e,h),fill:`none`,stroke:`var(--vis)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(t,h),fill:`none`,stroke:`var(--eng)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(e,g),fill:`none`,stroke:`var(--vis)`,strokeWidth:1.3}),(0,x.jsx)(`path`,{d:s(t,g),fill:`none`,stroke:`var(--eng)`,strokeWidth:1.3}),v!==null&&i!==n&&(0,x.jsx)(`line`,{x1:v,x2:v,y1:0,y2:28,stroke:`var(--text-3)`,strokeWidth:.75,strokeDasharray:`2 3`,opacity:.7}),(0,x.jsx)(`line`,{x1:_,x2:_,y1:0,y2:28,stroke:`var(--amber)`,strokeWidth:1})]}),typeof i==`number`&&(()=>{let n=e[i],r=t[i];if(!n&&!r)return null;let a=i/Math.max(1,o-1)*100,s={"--hover-left":`calc(${a}% + 8px)`,"--hover-translate":a>75?`translateX(calc(-100% - 16px))`:`none`};return(0,x.jsxs)(`div`,{className:LO.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:LO.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:LO.tooltipRowA,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`A`}),(0,x.jsxs)(`span`,{children:[`pop `,n.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(n.morale*100),`% mor`]}),typeof n.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,n.foodReserve.toFixed(1),`mo`]}),(n.births>0||n.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,n.births,`/-`,n.deaths]})]}),r&&(0,x.jsxs)(`div`,{className:LO.tooltipRowB,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`B`}),(0,x.jsxs)(`span`,{children:[`pop `,r.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(r.morale*100),`% mor`]}),typeof r.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,r.foodReserve.toFixed(1),`mo`]}),(r.births>0||r.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,r.births,`/-`,r.deaths]})]})]})})()]})}var zO={bar:`_bar_r8lgh_1`,barRow:`_barRow_r8lgh_7`,heading:`_heading_r8lgh_12`,filterRow:`_filterRow_r8lgh_22`,filterChip:`_filterChip_r8lgh_28`,active:`_active_r8lgh_43`,dotsRow:`_dotsRow_r8lgh_50`,dot:`_dot_r8lgh_50`,hovered:`_hovered_r8lgh_79`,current:`_current_r8lgh_85`},BO=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],VO={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},HO={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function UO({eventsA:e,eventsB:t,currentTurn:n,onJumpToTurn:r,onHoverTurnChange:i,hoveredTurn:a,onForgeSelect:o,filter:s,onFilterChange:c,onHoverEventChange:l,onJumpToReports:u}){let d=(0,b.useMemo)(()=>{let n=[],r=(e,t)=>{for(let r of e){let e=Number(r.turn??r.data?.turn??0);if(!(e<=0)){if(r.type===`birth`)n.push({turn:e,kind:`birth`,side:t,label:`T${e}: birth (${t.toUpperCase()})`});else if(r.type===`death`){let i=typeof r.data?.name==`string`?r.data.name:``;n.push({turn:e,kind:`death`,side:t,label:`T${e}: ${i?i+` died`:`death`} (${t.toUpperCase()})`})}else if(r.type===`forge_attempt`){let i=typeof r.data?.name==`string`?r.data.name:`tool`,a=r.data?.approved===!0;n.push({turn:e,kind:`forge`,side:t,label:`T${e}: ${a?`forged`:`rejected`} ${i} (${t.toUpperCase()})`,toolName:i,eventId:r.id})}else if(r.type===`event_start`||r.type===`director_crisis`){let i=typeof r.data?.category==`string`?r.data.category:``;i&&[`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`].includes(i)&&n.push({turn:e,kind:`crisis`,side:t,label:`T${e}: ${i} crisis (${t.toUpperCase()})`})}}}};return r(e,`a`),r(t,`b`),n.sort((e,t)=>e.turn-t.turn),n.slice(-60)},[e,t]),[f,p]=(0,b.useState)(`all`),m=s??f,h=e=>{s===void 0&&p(e),c?.(e)},g=(0,b.useMemo)(()=>m===`all`?d:d.filter(e=>e.kind===m),[d,m]);return d.length===0?null:(0,x.jsxs)(yC,{label:`events`,className:zO.bar,rowClassName:zO.barRow,role:`group`,ariaLabel:`Event filter`,children:[(0,x.jsxs)(`span`,{className:zO.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:zO.filterRow,children:BO.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[zO.filterChip,t?zO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:zO.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[zO.dot,c?zO.current:``,d?zO.hovered:``].filter(Boolean).join(` `),p={"--kind-color":VO[e.kind],"--side-shift":e.side===`a`?`-2px`:`2px`};return(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.shiftKey&&u?(t.preventDefault(),u(e.turn)):e.kind===`forge`&&e.toolName&&o&&o(e.toolName,e.side,e.eventId,t.currentTarget)!==!1||r(s)},onMouseEnter:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onMouseLeave:()=>{i?.(null),l?.(null)},onFocus:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onBlur:()=>{i?.(null),l?.(null)},title:`${e.label}${u?` · Shift+click to open in Reports`:``}`,"aria-label":e.label,className:f,style:p,children:HO[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var WO={bar:`_bar_n16b7_1`,row:`_row_n16b7_9`,label:`_label_n16b7_21`,track:`_track_n16b7_26`,fill:`_fill_n16b7_35`,count:`_count_n16b7_42`};function GO(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.type===`turn_done`){let e=Number(r.turn??r.data?.turn??0);if(e>0){t=e;break}}}let n=t+1,r=new Set,i=!1;for(let t of e){let e=Number(t.turn??t.data?.turn??0);if(t.type===`specialist_done`&&e===n){let e=typeof t.data?.department==`string`?t.data.department:``;e&&r.add(e),i=!0}if(t.type===`turn_done`&&e===n)return{inFlightTurn:null,deptsReported:new Set}}return{inFlightTurn:i?n:null,deptsReported:r}}function KO({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>GO(e),[e]),i=(0,b.useMemo)(()=>GO(t),[t]);if(r.inFlightTurn===null&&i.inFlightTurn===null)return null;let a=Math.max(1,n),o=(e,t,n)=>{if(n.inFlightTurn===null)return null;let r=Math.min(100,n.deptsReported.size/a*100);return(0,x.jsxs)(`div`,{className:WO.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:WO.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:WO.track,children:(0,x.jsx)(`div`,{className:WO.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:WO.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:WO.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var qO={bar:`_bar_3c24d_1`,icon:`_icon_3c24d_11`,label:`_label_3c24d_21`,input:`_input_3c24d_29`,dropdown:`_dropdown_3c24d_42`,option:`_option_3c24d_65`,sidePill:`_sidePill_3c24d_86`,optionName:`_optionName_3c24d_96`,optionMeta:`_optionMeta_3c24d_106`,featuredPill:`_featuredPill_3c24d_115`,moreNote:`_moreNote_3c24d_124`,matchCount:`_matchCount_3c24d_132`,clearBtn:`_clearBtn_3c24d_140`};function JO({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Lm();(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&e.key===`/`&&(e.preventDefault(),i.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let l=a&&e.trim().length>0&&n.length>0;return(0,x.jsxs)(`div`,{className:qO.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:qO.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:qO.label,children:`Find`}),(0,x.jsx)(`input`,{ref:i,type:`text`,value:e,onChange:e=>t(e.target.value),onFocus:()=>o(!0),onBlur:()=>setTimeout(()=>o(!1),120),placeholder:`${c.person} name, dept, mood… (space-separate to AND-match; / to focus)`,"aria-label":`Search ${c.people} by name, department, role, or mood`,className:qO.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:qO.dropdown,children:[n.slice(0,10).map((e,t)=>(0,x.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":`false`,onMouseDown:t=>{t.preventDefault(),r?.(e)},className:qO.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:qO.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:qO.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:qO.optionMeta,children:[e.cell.department?.toUpperCase?.()||``,` · `,e.cell.mood,typeof e.cell.age==`number`?` · age ${e.cell.age}`:``]}),e.cell.featured&&(0,x.jsx)(`span`,{className:qO.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:qO.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:qO.matchCount,style:{"--count-color":s>0?`var(--amber)`:`var(--rust)`},children:[s,` match`,s===1?``:`es`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>t(``),"aria-label":`Clear search`,className:qO.clearBtn,children:`clear`})]})]})}function YO(e,t,n,r=.04,i=`sine`){let a=e.currentTime,o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,a),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(r,a+.008),s.gain.exponentialRampToValueAtTime(1e-4,a+n),o.connect(s),s.connect(e.destination),o.start(a),o.stop(a+n+.02)}function XO(e,t){switch(t){case`birth`:YO(e,880,.18,.05,`triangle`),setTimeout(()=>YO(e,1320,.12,.03,`triangle`),70);break;case`death`:YO(e,160,.35,.05,`sine`);break;case`forge`:YO(e,660,.12,.04,`sine`);break;case`crisis`:YO(e,220,.22,.05,`sawtooth`),setTimeout(()=>YO(e,180,.18,.045,`sawtooth`),120)}}function ZO(e){let t=(0,b.useRef)(null),n=(0,b.useRef)(new Set),r=(0,b.useRef)(-1),i=(0,b.useRef)(-1),a=()=>{if(!e.enabled)return null;if(t.current)return t.current;try{let e=window.AudioContext??window.webkitAudioContext;return e?(t.current=new e,t.current):null}catch{return null}};(0,b.useEffect)(()=>{if(!e.enabled)return;let n=()=>{let e=t.current;e&&e.state===`suspended`&&e.resume().catch(()=>{})};return window.addEventListener(`click`,n),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`click`,n),window.removeEventListener(`keydown`,n)}},[e.enabled]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=(e,t,r,i)=>{if(!e||!t||e.turn===i.current)return;i.current=e.turn;let o=a();if(!o)return;let s=gD(t.cells,e.cells),c=0,l=0;for(let t of s.born){let i=`${r}|t${e.turn}|birth|${t.agentId}`;n.current.has(i)||(n.current.add(i),c+=1)}for(let t of s.died){let i=`${r}|t${e.turn}|death|${t.agentId}`;n.current.has(i)||(n.current.add(i),l+=1)}c>0&&XO(o,`birth`),l>0&&setTimeout(()=>XO(o,`death`),c>0?300:0)};t(e.snapshotA,e.prevSnapshotA,`a`,r),t(e.snapshotB,e.prevSnapshotB,`b`,i)},[e.enabled,e.snapshotA,e.prevSnapshotA,e.snapshotB,e.prevSnapshotB]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=a();if(!t)return;let r=(e,r)=>{for(let i of e){if(!i.approved)continue;let e=`${r}|forge|${i.turn}|${i.eventIndex}|${i.name}`;n.current.has(e)||(n.current.add(e),XO(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var QO={backdrop:`_backdrop_nnlpn_1`,dialog:`_dialog_nnlpn_12`,header:`_header_nnlpn_24`,title:`_title_nnlpn_31`,closeBtn:`_closeBtn_nnlpn_41`,sidesRow:`_sidesRow_nnlpn_54`,sideBlock:`_sideBlock_nnlpn_61`,sideName:`_sideName_nnlpn_71`,statsGrid:`_statsGrid_nnlpn_81`,cell:`_cell_nnlpn_87`,cellLabel:`_cellLabel_nnlpn_93`,cellValue:`_cellValue_nnlpn_101`,empty:`_empty_nnlpn_108`,divergenceBox:`_divergenceBox_nnlpn_113`,divergenceLabel:`_divergenceLabel_nnlpn_125`,divergenceCount:`_divergenceCount_nnlpn_132`,divergenceCopy:`_divergenceCopy_nnlpn_138`};function $O(e){if(e.length===0)return null;let t=0,n=0,r=0,i=0,a=0,o=0,s=1/0,c=1/0;for(let l of e)t+=l.births,n+=l.deaths,l.population>r&&(r=l.population),i+=l.morale,typeof l.foodReserve==`number`&&(a+=l.foodReserve,o++,l.foodReserve<c&&(c=l.foodReserve)),l.morale<s&&(s=l.morale);return{turns:e.length,totalBirths:t,totalDeaths:n,peakPop:r,finalPop:e[e.length-1].population,avgMorale:i/e.length,minMorale:s===1/0?0:s,avgFood:o>0?a/o:void 0,minFood:o>0?c:void 0}}function ek(e){let{open:t,onClose:n}=e,r=Lm();(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),n())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]);let i=(0,b.useMemo)(()=>$O(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>$O(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:QO.cell,children:[(0,x.jsx)(`span`,{className:QO.cellLabel,children:e}),(0,x.jsx)(`span`,{className:QO.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:QO.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:QO.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:QO.statsGrid,children:[o(`Turns`,`${n.turns}`),o(`Final pop`,`${n.finalPop}`,t),o(`Peak pop`,`${n.peakPop}`),o(`Total births`,`${n.totalBirths}`,`rgba(106, 173, 72, 0.95)`),o(`Total deaths`,`${n.totalDeaths}`,`rgba(200, 95, 80, 0.95)`),o(`Avg morale`,`${Math.round(n.avgMorale*100)}%`),o(`Min morale`,`${Math.round(n.minMorale*100)}%`,n.minMorale<.3?`var(--rust)`:`var(--text-1)`),n.minFood!==void 0&&o(`Min food`,`${n.minFood.toFixed(1)}mo`,n.minFood<3?`var(--rust)`:`var(--text-1)`),o(`Tools forged`,`${r}`,`var(--amber)`),o(`Tool reuses`,`${i}`,`var(--amber)`)]}):(0,x.jsx)(`div`,{className:QO.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:QO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:QO.dialog,children:[(0,x.jsxs)(`div`,{className:QO.header,children:[(0,x.jsxs)(`h2`,{className:QO.title,children:[`Run Summary · `,e.snapsA.length||e.snapsB.length,` turns`]}),(0,x.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close run summary`,className:QO.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:QO.sidesRow,children:[s(e.actorNameA,`var(--vis)`,i,e.forgeApprovedA,e.reuseCountA),s(e.actorNameB,`var(--eng)`,a,e.forgeApprovedB,e.reuseCountB)]}),(0,x.jsxs)(`div`,{className:QO.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:QO.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:QO.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:QO.divergenceCopy,children:[r.People,` alive on one side but dead on the other at the final snapshot — a measure of how much the two leaders' decisions diverged the outcomes.`]})]})]})})}var tk={anchor:`_anchor_ypvfl_1`,trigger:`_trigger_ypvfl_5`,triggerOpen:`_triggerOpen_ypvfl_21`,recDot:`_recDot_ypvfl_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ypvfl_1`,menu:`_menu_ypvfl_36`,item:`_item_ypvfl_51`,itemRecording:`_itemRecording_ypvfl_71`,itemKey:`_itemKey_ypvfl_75`,itemKeyRecording:`_itemKeyRecording_ypvfl_81`,itemDesc:`_itemDesc_ypvfl_85`},nk=8,rk=4,ik={top:0,left:0,visibility:`hidden`},ak=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function ok(e){let t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;if(n<0||r<0||n>window.innerWidth||r>window.innerHeight)return!1;for(let t=e.parentElement;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t);if(e.overflowX===`visible`&&e.overflowY===`visible`)continue;let i=t.getBoundingClientRect();if(n<i.left||n>i.right||r<i.top||r>i.bottom)return!1}return!0}function sk({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(null),d=(0,b.useRef)(!1),f=()=>Array.from(u.current?.querySelectorAll(`[role="menuitem"]`)??[]),p=(0,b.useCallback)(e=>{a(!1),e&&l.current?.focus()},[]);(0,b.useLayoutEffect)(()=>{if(!i){s(null);return}let e=()=>{let e=l.current;if(!e)return;if(!ok(e)){a(!1);return}let t=e.getBoundingClientRect(),n=window.innerHeight-t.bottom-rk-nk,r=t.top-rk-nk,i=(u.current?.scrollHeight??0)>n&&r>n;s({...i?{bottom:window.innerHeight-t.top+rk,maxHeight:Math.max(0,r)}:{top:t.bottom+rk,maxHeight:Math.max(0,n)},...t.right>=188?{right:Math.max(nk,window.innerWidth-t.right)}:{left:Math.max(nk,t.left)}})};e(),window.addEventListener(`resize`,e),document.addEventListener(`scroll`,e,!0);let t=()=>{let e=l.current?.getBoundingClientRect();return e?`${e.left} ${e.top} ${e.right} ${e.bottom}`:``},n=t(),r=0,o=()=>{let i=t();i!==n&&(n=i,e()),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>{cancelAnimationFrame(r),window.removeEventListener(`resize`,e),document.removeEventListener(`scroll`,e,!0)}},[i]),(0,b.useLayoutEffect)(()=>{i&&o&&d.current&&(d.current=!1,u.current?.querySelector(`[role="menuitem"]`)?.focus({preventScroll:!0}))},[i,o]),(0,b.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;c.current?.contains(t)||u.current?.contains(t)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]);let m=e=>{let t=f(),n=t.indexOf(document.activeElement);if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let r=e.key===`ArrowDown`?1:-1;t[n<0?r>0?0:t.length-1:(n+r+t.length)%t.length]?.focus()}else if(e.key===`Home`||e.key===`End`)e.preventDefault(),t[e.key===`Home`?0:t.length-1]?.focus();else if(e.key===`Escape`)e.preventDefault(),p(!0);else if(e.key===`Tab`){e.preventDefault();let t=l.current;if(p(!0),!e.shiftKey&&t){let e=Array.from(document.querySelectorAll(ak)).filter(e=>!u.current?.contains(e)&&e.getClientRects().length>0);e[e.indexOf(t)+1]?.focus()}}},h=e=>()=>{p(!0),e()};return(0,x.jsxs)(`div`,{ref:c,className:tk.anchor,children:[(0,x.jsxs)(`button`,{ref:l,type:`button`,onClick:()=>{i||(d.current=!0),a(e=>!e)},"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[tk.trigger,i?tk.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:tk.recDot}),`EXPORT ▼`]}),i&&(0,jy.createPortal)((0,x.jsxs)(`div`,{ref:u,role:`menu`,className:tk.menu,style:o??ik,onKeyDown:m,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(t),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(r),className:[tk.item,e?tk.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[tk.itemKey,e?tk.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(n),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Replay snapshot`})]})]}),document.body)]})}var ck={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},lk=120;function uk({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>lk,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:ck.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:ck.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:ck.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var dk={bar:`_bar_1u6wg_1`,glyphRow:`_glyphRow_1u6wg_21`,label:`_label_1u6wg_28`,glyph:`_glyph_1u6wg_21`,band:`_band_1u6wg_39`,agent:`_agent_1u6wg_43`,featured:`_featured_1u6wg_49`,turn:`_turn_1u6wg_56`,fullLegend:`_fullLegend_1u6wg_68`,popover:`_popover_1u6wg_89`,popHeading:`_popHeading_1u6wg_107`,deptSwatch:`_deptSwatch_1u6wg_135`,closeBtn:`_closeBtn_1u6wg_145`};function fk({departments:e}){let[t,n]=(0,b.useState)(!1),r=Pt(t),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&n(!1)},r=e=>{let t=e.target;t&&i.current&&!i.current.contains(t)&&n(!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`mousedown`,r),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`mousedown`,r)}},[t]),(0,x.jsxs)(`div`,{className:dk.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:dk.glyphRow,children:[(0,x.jsx)(pk,{type:`band`}),(0,x.jsx)(`span`,{className:dk.label,children:`Department band`}),(0,x.jsx)(pk,{type:`agent`}),(0,x.jsx)(`span`,{className:dk.label,children:`Agent`}),(0,x.jsx)(pk,{type:`featured`}),(0,x.jsx)(`span`,{className:dk.label,children:`Featured agent`}),(0,x.jsx)(pk,{type:`turn`}),(0,x.jsx)(`span`,{className:dk.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:dk.popover,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`viz-legend-heading`,tabIndex:-1,ref:r,children:[(0,x.jsx)(`h3`,{id:`viz-legend-heading`,className:dk.popHeading,children:`What you’re looking at`}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Departments (tile color)`}),(0,x.jsx)(`ul`,{className:dk.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:dk.deptSwatch,style:{background:e.color},"aria-hidden":`true`}),e.label]},e.id))})]}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Mood tiers (chip glyph)`}),(0,x.jsxs)(`ul`,{className:dk.moodList,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▼`}),` low (under 25% morale)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▽`}),` tense (25–50%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`△`}),` steady (50–75%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▲`}),` rising (over 75%)`]})]})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function pk({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.turn}`,"aria-hidden":`true`,children:`T`})}}var mk={panel:`_panel_15qsw_1`,eyebrow:`_eyebrow_15qsw_15`,empty:`_empty_15qsw_23`,chipRow:`_chipRow_15qsw_27`,chip:`_chip_15qsw_27`,chipLight:`_chipLight_15qsw_47`,chipStrong:`_chipStrong_15qsw_53`,chipDept:`_chipDept_15qsw_59`,chipCount:`_chipCount_15qsw_63`},hk=8;function gk({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,hk);return n.length===0?(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:mk.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:mk.chipRow,children:n.map(([e,n])=>{let r=t[e]??e,i=n.magnitude>=.5,a=`${r}: A has ${n.aState.agentCount} agents (${n.aState.dominantMood} mood); B has ${n.bState.agentCount} agents (${n.bState.dominantMood} mood)`;return(0,x.jsxs)(`li`,{className:`${mk.chip} ${i?mk.chipStrong:mk.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:mk.chipDept,children:r}),(0,x.jsxs)(`span`,{className:mk.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var _k=.2;function vk(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths,birthsThisTurn:e.births,eventCategories:e.eventCategories??[],year:e.time}}var yk={nameA:`Leader A`,nameB:`Leader B`,person:`colonist`,people:`colonists`,places:`colonies`};function bk(e,t,n,r=yk){if(!e||!t)return`Awaiting first turn snapshot.`;let i=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let a=e.deathsThisTurn>t.deathsThisTurn,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=Math.max(e.deathsThisTurn,t.deathsThisTurn),l=Math.min(e.deathsThisTurn,t.deathsThisTurn),u=e=>e===0?`none`:`${e} ${e===1?r.person:r.people}`;return`Turn ${n}, year ${i}: ${o} lost ${u(c)}; ${s} lost ${u(l)}.`}if(Math.abs(e.morale-t.morale)>=_k){let a=e.morale<t.morale,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=a?e.morale:t.morale,l=a?t.morale:e.morale;return`Turn ${n}, year ${i}: ${o}'s morale collapsed to ${xk(c)}; ${s} held ${xk(l)}.`}let a=e.eventCategories.join(`|`),o=t.eventCategories.join(`|`);return a&&o&&a!==o?`Turn ${n}, year ${i}: different events. ${r.nameA}: ${e.eventCategories.join(`, `)}; ${r.nameB}: ${t.eventCategories.join(`, `)}.`:n===1&&a&&a===o?`Turn 1, year ${i}: identical first event (${e.eventCategories.join(`, `)}). Both ${r.places} start from the same state.`:`Turn ${n}, year ${i}: ${r.nameA} and ${r.nameB} tracked closely. See sub-tabs for details.`}function xk(e){return`${Math.round(e*100)}%`}function Sk(e,t){let n=new Map,r=new Map(e.map(e=>[e.cellKey,e])),i=new Map(t.map(e=>[e.cellKey,e])),a=new Set([...r.keys(),...i.keys()]);for(let e of a){let t=r.get(e)??Ck(e),a=i.get(e)??Ck(e),o=Math.max(t.agentCount,a.agentCount,1),s=Math.abs(t.agentCount-a.agentCount)/o,c=t.dominantMood===a.dominantMood?0:1,l=t.department===a.department?0:1,u=(s+c+l)/3;n.set(e,{magnitude:u,aState:t,bState:a})}return n}function Ck(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var wk={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function Tk(e,t){let n=new Set,r=new Set;if(!e||!t)return{aliveOnlyA:n,aliveOnlyB:r};let i=new Map(e.cells.map(e=>[e.agentId,e])),a=new Map(t.cells.map(e=>[e.agentId,e]));for(let[e,t]of i){let r=a.get(e);!t.alive||r&&r.alive||n.add(e)}for(let[e,t]of a){let n=i.get(e);!t.alive||n&&n.alive||r.add(e)}return{aliveOnlyA:n,aliveOnlyB:r}}function Ek(e){if(!e)return[];let t=new Map;for(let n of e.cells){if(!n.alive)continue;let e=n.department||`unknown`,r=t.get(e);r||(r={count:0,moods:{}},t.set(e,r)),r.count+=1;let i=n.mood||`neutral`;r.moods[i]=(r.moods[i]??0)+1}let n=[];for(let[e,r]of t){let t=Object.entries(r.moods).sort((e,t)=>t[1]-e[1])[0]?.[0]??`neutral`;n.push({cellKey:e,department:e,agentCount:r.count,dominantMood:t})}return n}function Dk({k:e,v:t}){return(0,x.jsxs)(`span`,{className:$.kbd,children:[(0,x.jsx)(`kbd`,{className:$.kbdKey,children:e}),(0,x.jsx)(`span`,{className:$.kbdLabel,children:t})]})}function Ok(e){return e?[e.foodReserve,e.waterLitersPerDay,e.powerKw,e.pressurizedVolumeM3].some(e=>typeof e==`number`):!1}var kk=`button, a[href], summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"]`;function Ak({state:e,onNavigateToChat:t}){let n=HE(e),r=e.actorIds[0],i=e.actorIds[1],[a,o]=(0,b.useState)(r),[s,c]=(0,b.useState)(i);(0,b.useEffect)(()=>{a&&!e.actorIds.includes(a)&&o(r),s&&!e.actorIds.includes(s)&&c(i)},[e.actorIds,a,s,r,i]);let l=a??r,u=s??i,d=(l?n[l]:void 0)??[],f=(u?n[u]:void 0)??[],p=l?e.actors[l]:null,m=u?e.actors[u]:null,h=e.actorIds.length>2,[g,_]=(0,b.useState)(h?`cohort`:`pair`);(0,b.useEffect)(()=>{_(h?`cohort`:`pair`)},[h]);let v=Math.max(d.length,f.length),[y,S]=(0,b.useState)(0),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(1),[D,O]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridMode`);if(e===`living`||e===`mood`||e===`forge`||e===`ecology`||e===`divergence`)return e}catch{}return`living`}),k=(0,b.useCallback)(e=>{O(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:A}=Ht(),j=(0,b.useRef)(0),ee=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ee.current;ee.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return j.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(j.current)},[C,T,v]);let te=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),M=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),N=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),ne=(0,b.useCallback)(e=>{w(!1),S(e)},[]),P=nA(),re=(0,b.useCallback)(e=>{P(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[P]),[ie,F]=(0,b.useState)(!1),I=Qk(),ae=Lm(),[oe,ce]=(0,b.useState)(null),[le,L]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,R]=(0,b.useState)(`all`),[z,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(``),[ge,_e]=(0,b.useState)(null),[B,ve]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3)return rO(t);localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return nO}),ye=(0,b.useCallback)(e=>{ve(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=new Set([`event_start`,`director_crisis`]),n=`paracosm:seenCrisisToasts`,r=()=>{try{let e=sessionStorage.getItem(n);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},i=e=>{try{let t=[...e].slice(-200);sessionStorage.setItem(n,JSON.stringify(t))}catch{}},a=r(),o=(()=>{let n=null,r=[];l&&r.push({side:`a`,actorName:l}),u&&r.push({side:`b`,actorName:u});for(let{side:i,actorName:o}of r){let r=e.actors[o];if(!r)continue;let s=r.events;for(let e=s.length-1;e>=0;e--){let r=s[e];if(!t.has(r.type))continue;let o=Number(r.turn??r.data?.turn??0),c=typeof r.data?.category==`string`?r.data.category:``;if(!c)continue;let l=`${i}:${o}:${c}`;if(a.has(l))continue;let u=typeof r.data?.title==`string`?r.data.title:``;(!n||o>n.turn)&&(n={key:l,side:i,turn:o,category:c,title:u});break}}return n})();o&&(a.add(o.key),i(a),_e(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,B.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!ge)return;let e=ge.expiresAt-performance.now();if(e<=0){_e(null);return}let t=setTimeout(()=>_e(null),e);return()=>clearTimeout(t)},[ge]);let[be,xe]=(0,b.useState)(null),Se=`paracosm:seenThresholdAlerts`,Ce=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Se);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),we=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Se,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=Ce(),n=(e,n)=>{t.has(e)||(t.add(e),xe({key:e,...n,expiresAt:performance.now()+5500}))},r=(e,t)=>{if(t.length<2)return;let r=t[t.length-1],i=t[t.length-2],a=i.morale-r.morale;a>=.2&&n(`${e}|${r.turn}|morale-crash`,{side:e,turn:r.turn,kind:`morale-crash`,message:`Morale crashed ${Math.round(a*100)}% → ${Math.round(r.morale*100)}% this turn`}),typeof r.foodReserve==`number`&&typeof i.foodReserve==`number`&&r.foodReserve<3&&i.foodReserve>=3&&n(`${e}|${r.turn}|food-low`,{side:e,turn:r.turn,kind:`food-low`,message:`Food reserve fell below 3mo (${r.foodReserve.toFixed(1)}mo remaining)`})};r(`a`,d),r(`b`,f),we(t)},[d,f,B.alerts,Ce,we,e.isRunning]),(0,b.useEffect)(()=>{if(!be)return;let e=be.expiresAt-performance.now();if(e<=0){xe(null);return}let t=setTimeout(()=>xe(null),e);return()=>clearTimeout(t)},[be]);let[Te,Ee]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),De=(0,b.useCallback)(e=>{Ee(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Oe=(0,b.useCallback)(()=>{De(Te===`amber`?`cool`:Te===`cool`?`mono`:`amber`)},[Te,De]),[ke,Ae]=(0,b.useState)(!1),[je,Me]=(0,b.useState)(!1),[Ne,Pe]=(0,b.useState)(!1),Fe=ev(),Ie=D_(),Le=(0,b.useCallback)((t,n,r,i)=>{let a=n===`a`?l:u,o=a?e.actorIds.indexOf(a):-1,s=o>=0?Ie.getEntryFor(o,t):void 0;if(!s)return!1;let c=s.attempts.find(e=>e.eventId===r)?.attempt;return Fe.openTrace({actorIndex:o,toolName:t,attempt:c},i,`viz`),!0},[l,u,e.actorIds,Ie,Fe]),[Re,ze]=(0,b.useState)(null),Be=(0,b.useCallback)(e=>{ze(t=>t===e?null:e)},[]),Ve=d[y]??d[d.length-1],He=f[y]??f[f.length-1],Ue=Ve?.turn??0,We=He?.turn??0,Ge=I.presets.find(e=>e.id==="default"),Ke=Ge?.leaders??Ge?.actors,qe=Ke?.[0]?{name:Ke[0].name,archetype:Ke[0].archetype,unit:se(I,0),hexaco:Ke[0].hexaco,instructions:Ke[0].instructions,quote:``}:null,Je=Ke?.[1]?{name:Ke[1].name,archetype:Ke[1].archetype,unit:se(I,1),hexaco:Ke[1].hexaco,instructions:Ke[1].instructions,quote:``}:null,Ye=p?.leader??qe,Xe=m?.leader??Je,Ze=(0,b.useRef)(null),[Qe,$e]=(0,b.useState)(!1),et=(0,b.useRef)(null),tt=(0,b.useRef)([]),nt=(0,b.useRef)(null),rt=(0,b.useRef)(0),it=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=e.getBoundingClientRect(),n=Math.max(640,Math.round(t.width)),r=Math.max(360,Math.round(t.height)),i=document.createElement(`canvas`);if(i.width=n,i.height=r,!i.getContext(`2d`))return;nt.current=i;let a=i.captureStream(30),o=`video/webm;codecs=vp9`;typeof MediaRecorder<`u`&&!MediaRecorder.isTypeSupported(o)&&(o=`video/webm;codecs=vp8`,MediaRecorder.isTypeSupported(o)||(o=`video/webm`));let s;try{s=new MediaRecorder(a,{mimeType:o,videoBitsPerSecond:4e6})}catch{console.warn(`MediaRecorder unavailable — timelapse skipped`);return}tt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&tt.current.push(e.data)},s.onstop=()=>{rt.current&&cancelAnimationFrame(rt.current),rt.current=0;let e=new Blob(tt.current,{type:o}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-timelapse-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.webm`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},et.current=s,$e(!0),s.start();let c=()=>{let e=nt.current,t=Ze.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.fillStyle=getComputedStyle(t).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,n.fillRect(0,0,e.width,e.height);let r=t.getBoundingClientRect(),i=e.width/Math.max(1,r.width),a=e.height/Math.max(1,r.height),o=Array.from(t.querySelectorAll(`canvas`));for(let e of o){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&n.drawImage(e,(t.left-r.left)*i,(t.top-r.top)*a,t.width*i,t.height*a)}rt.current=requestAnimationFrame(c)};rt.current=requestAnimationFrame(c)},[]),at=(0,b.useCallback)(()=>{let e=et.current;if(e){try{e.stop()}catch{}et.current=null,$e(!1)}},[]);(0,b.useEffect)(()=>()=>{if(et.current)try{et.current.stop()}catch{}rt.current&&cancelAnimationFrame(rt.current)},[]);let ot=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:Ye?.name??`Leader A`,archetype:Ye?.archetype??``},leaderB:{name:Xe?.name??`Leader B`,archetype:Xe?.archetype??``},currentTurn:y,snapshots:{a:d,b:f},events:{a:p?.events??[],b:m?.events??[]}},t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`paracosm-replay-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),1e3)},[y,Ye,Xe,d,f,p,m]),st=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=Array.from(e.querySelectorAll(`canvas`));if(t.length===0)return;let n=e.getBoundingClientRect(),r=document.createElement(`canvas`);r.width=Math.round(n.width*2),r.height=Math.round(n.height*2);let i=r.getContext(`2d`);if(i){i.fillStyle=getComputedStyle(e).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,i.fillRect(0,0,r.width,r.height),i.scale(2,2);for(let e of t){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&i.drawImage(e,t.left-n.left,t.top-n.top,t.width,t.height)}r.toBlob(e=>{if(!e)return;let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-viz-t${y+1}-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.png`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},`image/png`)}},[y]),[ct,lt]=(0,b.useState)(0),ut=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ut.current===-1||Math.abs(y-ut.current)>=2&<(e=>e+1),ut.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target instanceof Element?e.target:null,n=t?.tagName;n!==`INPUT`&&n!==`TEXTAREA`&&n!==`SELECT`&&(e.key!==`Escape`&&t?.closest(`[role="dialog"]`)||(e.key!==` `&&e.key!==`Spacebar`||!t?.closest(kk))&&(e.key===`ArrowLeft`?(e.preventDefault(),M()):e.key===`ArrowRight`?(e.preventDefault(),N()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),te()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),F(e=>!e)):e.key===`Escape`&&ie?(e.preventDefault(),F(!1)):e.key===`1`?(e.preventDefault(),k(`living`)):e.key===`2`?(e.preventDefault(),k(`mood`)):e.key===`3`?(e.preventDefault(),k(`forge`)):e.key===`4`?(e.preventDefault(),k(`ecology`)):e.key===`5`&&(e.preventDefault(),k(`divergence`))))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[M,N,te,ie,k]);let dt=(0,b.useMemo)(()=>{let e=me.trim().toLowerCase().split(/\s+/).filter(Boolean);if(e.length===0)return[];let t=t=>{let n=`${t.name} ${t.department} ${t.role} ${t.mood}`.toLowerCase();return e.every(e=>n.includes(e))};return[...(Ve?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:Ye?.name??`Leader A`,sideColor:`#e8b44a`})),...(He?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:Xe?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[me,Ve,He,Ye,Xe]),ft=(0,b.useMemo)(()=>Tk(Ve,He),[Ve,He]),pt=(0,b.useMemo)(()=>{let t={a:{attempts:[],reuses:[]},b:{attempts:[],reuses:[]}},n=[];l&&n.push({side:`a`,actorName:l}),u&&n.push({side:`b`,actorName:u});for(let{side:r,actorName:i}of n){let n=e.actors[i];if(!n)continue;let a=new Map;for(let e of n.events){if(e.type===`forge_attempt`){let n=e.data||{};t[r].attempts.push({turn:Number(n.turn??0),eventIndex:Number(n.eventIndex??0),department:String(n.department||``),name:String(n.name||``),approved:n.approved===!0||n.approved===`true`,confidence:typeof n.confidence==`number`?n.confidence:void 0}),n.name&&n.department&&n.approved===!0&&!a.has(String(n.name))&&a.set(String(n.name),String(n.department));continue}if(e.type!==`specialist_done`)continue;let n=e.data||{},i=String(n.department||``),o=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let s of o){let o=s,c=String(o.name||``);if(!c||c===`unnamed`)continue;let l=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):a.get(c),u=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,d=Number(e.turn??n.turn??0);(l&&u!==void 0&&u<d||l&&l!==i)&&t[r].reuses.push({turn:d,originDept:l,callingDept:i,name:c})}}}return t},[e]);ZO({enabled:B.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:pt.a.attempts,forgeAttemptsB:pt.b.attempts});let mt=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(r)for(let e of r.events){if(e.type!==`agent_reactions`)continue;let n=e.data?.reactions||[];for(let e of n){let n=e.hexaco;if(!n)continue;let r=e.agentId||e.name;r&&t.set(r,n)}}}return t},[e]),ht=(0,b.useCallback)(e=>{t?.(e)},[t]),gt=My(Ny),_t=My(Py),vt=My(Fy),[yt,bt]=(0,b.useState)(null),xt=Ye?.name??`Leader A`,St=Xe?.name??`Leader B`,Ct=(0,b.useMemo)(()=>bk(d[y]?vk(d[y],d[y-1]):null,f[y]?vk(f[y],f[y-1]):null,y+1,{nameA:xt,nameB:St,person:ae.person,people:ae.people,places:ae.places}),[d,f,y,xt,St,ae.person,ae.people,ae.places]),wt=(0,b.useMemo)(()=>I.departments.map(e=>({id:e.id,label:e.label,color:wk[e.id]??`#a89878`})),[I.departments]),Tt=(0,b.useMemo)(()=>Object.fromEntries(I.departments.map(e=>[e.id,e.label])),[I.departments]),[Et,Dt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Ot=(0,b.useCallback)(e=>{Dt(e);try{window.localStorage.setItem(`paracosm:vizDiffOverlay`,e?`1`:`0`)}catch{}},[]);(0,b.useEffect)(()=>{let e=e=>{let t=e.target;t&&t.matches(`input, textarea, [contenteditable=true]`)||(e.key===`d`||e.key===`D`)&&(e.preventDefault(),Ot(!Et))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Et,Ot]);let kt=(0,b.useMemo)(()=>Et?Sk(Ek(d[y]),Ek(f[y])):null,[Et,d,f,y]);if(v===0)return e.isRunning?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Awaiting first turn snapshot — the `,ae.place,` viz will populate once the kernel reports state.`]})]}):typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Loading replay — the `,ae.place,` viz will populate as the cached events stream in.`]})]}):(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,children:[`Run a simulation to see the `,ae.place,` visualization.`]});let At=Ve&&He?`A vs B: ${He.population-Ve.population>=0?`+`:``}${He.population-Ve.population} pop, ${He.morale-Ve.morale>=0?`+`:``}${Math.round((He.morale-Ve.morale)*100)}% morale${typeof Ve.foodReserve==`number`&&typeof He.foodReserve==`number`?`, ${He.foodReserve-Ve.foodReserve>0?`+`:``}${(He.foodReserve-Ve.foodReserve).toFixed(1)}mo food`:``}`:``,jt=_t?Re??`a`:Re,Mt=y>0?d[y-1]??d[d.length-2]:void 0,Nt=y>0?f[y-1]??f[f.length-2]:void 0,Pt=dt,Ft=(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Ot(!Et),"aria-label":Et?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Et,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Et?`on`:`off`]}),It=(0,x.jsx)(`button`,{type:`button`,onClick:()=>F(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),Lt=_t,Rt=SO(e,y)!==``;return(0,x.jsxs)(`div`,{ref:Ze,className:`viz-content ${$.root}`,children:[h&&(0,x.jsxs)(`div`,{className:$.cohortViewBar,role:`region`,"aria-label":`Cohort view controls`,children:[(0,x.jsxs)(`div`,{className:$.cohortViewModeToggle,role:`tablist`,"aria-label":`Swarm grid view mode`,children:[(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`cohort`,onClick:()=>_(`cohort`),className:[$.cohortViewModeButton,g===`cohort`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Show every actor's living-swarm panel side-by-side with horizontal scroll`,children:[`All `,e.actorIds.length,` actors`]}),(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`pair`,onClick:()=>_(`pair`),className:[$.cohortViewModeButton,g===`pair`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Focus on a 2-actor head-to-head with the original pair-mode diff overlay + sympathy hover`,children:`Focus pair`})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:$.cohortPairPicker,children:[(0,x.jsx)(`select`,{"aria-label":`Left panel actor`,className:$.cohortPairPickerSelect,value:l??``,onChange:e=>o(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===u,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:$.cohortPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right panel actor`,className:$.cohortPairPickerSelect,value:u??``,onChange:e=>c(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===l,children:e.actors[t]?.leader?.name??t},t))})]})]}),(0,x.jsx)(wO,{state:e,currentTurn:y,linesTarget:Lt?yt:null,cohortGridShown:g===`cohort`}),(0,x.jsx)(uk,{text:Ct,turn:y+1}),(0,x.jsx)(fk,{departments:wt}),Et&&kt&&(0,x.jsx)(gk,{diff:kt,departmentLabels:Tt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(yC,{label:`toolbar keys`,rowClassName:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(jO,{mode:D,onChange:k,counts:{forge:pt.a.attempts.filter(e=>e.approved).length+pt.b.attempts.filter(e=>e.approved).length,divergence:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)},labels:ae})}),D===`forge`&&(0,x.jsx)(`button`,{type:`button`,"aria-haspopup":`dialog`,onClick:e=>Fe.openToolbox(e.currentTarget,`viz`),className:$.forgeToolboxKey,children:$v(Ie.list.length)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>!e),"aria-label":Ne?vt?`Hide more tools`:`Hide advanced tools`:vt?`Show more tools (diff, help, palette, stats, export, settings)`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":Ne,title:Ne?`Hide tools`:vt?`Diff · Help · Palette · Stats · Export · Settings`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,Ne?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),!vt&&Ft,!vt&&It]}),Ne&&(0,x.jsxs)(yC,{label:`Viz tools`,role:`toolbar`,ariaLabel:`Viz tools`,rowClassName:$.toolsRow,children:[vt&&Ft,vt&&It,(0,x.jsx)(`button`,{type:`button`,onClick:Oe,"aria-label":`Palette: ${Te}. Click to cycle.`,title:`Palette: ${Te.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Te===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Te===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Te}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Me(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(sk,{recording:Qe,onExportPng:st,onExportJson:ot,onToggleRecording:Qe?at:it}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ae(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":ke,title:`Viz settings`,className:[$.settingsBtn,ke?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:AO(D,ae)}),D===`ecology`&&!e.actorIds.some(e=>{let t=n[e]??[];return Ok(t[y]??t[t.length-1])})&&(0,x.jsxs)(`div`,{role:`status`,className:$.ecologyNone,children:[(0,x.jsx)(`span`,{children:`ECOLOGY draws food, water, power and pressurized volume. This run holds none of them.`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>k(`living`),className:$.ecologyBack,children:`Back to LIVING`})]})]}),(0,x.jsx)(JO,{value:me,onChange:he,matches:Pt,onPick:e=>{he(e.cell.name)}}),(0,x.jsx)(KO,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:I.departments.length}),(0,x.jsx)(UO,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de,filter:fe,onFilterChange:R,onHoverEventChange:pe,onJumpToReports:re,onForgeSelect:Le}),(0,x.jsx)(RO,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de}),g===`pair`&&At&&(0,x.jsx)(`div`,{className:$.diffLine,children:At}),g===`pair`&&_t&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?Ye?.name??`Leader A`:Xe?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=jt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>ze(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsxs)(`div`,{className:[$.cohortWindow,Lt?$.cohortWindowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(vO,{className:Lt?$.cohortTrackLinesBelow:void 0,state:e,snapshotMap:n,currentTurn:y,gridMode:D,palette:Te===`cool`?1:Te===`mono`?2:0,gridSettings:B,hexacoById:mt,searchQuery:me,chronicleFilter:fe,chronicleHover:z,startTime:I.setup?.defaultStartTime,onOpenChat:ht}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,gt?$.leadersRowNarrow:``,Lt?$.leadersRowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:Ve,previousSnapshot:Mt,snapshotHistory:d,actorName:Ye?.name??`Leader A`,actorArchetype:Ye?.archetype??``,leaderUnit:Ye?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ue<We?We-Ue:0,mode:D,hexacoById:mt,leaderHexaco:Ye?.hexaco?{O:Ye.hexaco.O??Ye.hexaco.openness??.5,C:Ye.hexaco.C??Ye.hexaco.conscientiousness??.5,E:Ye.hexaco.E??Ye.hexaco.extraversion??.5,A:Ye.hexaco.A??Ye.hexaco.agreeableness??.5,Em:Ye.hexaco.Em??Ye.hexaco.emotionality??.5,HH:Ye.hexaco.HH??Ye.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.a.attempts,reuseCalls:pt.a.reuses,divergedIds:ft.aliveOnlyA,siblingHoveredId:le,onHoverChange:ce,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:He,previousSnapshot:Nt,snapshotHistory:f,actorName:Xe?.name??`Leader B`,actorArchetype:Xe?.archetype??``,leaderUnit:Xe?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:We<Ue?Ue-We:0,mode:D,hexacoById:mt,leaderHexaco:Xe?.hexaco?{O:Xe.hexaco.O??Xe.hexaco.openness??.5,C:Xe.hexaco.C??Xe.hexaco.conscientiousness??.5,E:Xe.hexaco.E??Xe.hexaco.extraversion??.5,A:Xe.hexaco.A??Xe.hexaco.agreeableness??.5,Em:Xe.hexaco.Em??Xe.hexaco.emotionality??.5,HH:Xe.hexaco.HH??Xe.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.b.attempts,reuseCalls:pt.b.reuses,divergedIds:ft.aliveOnlyB,siblingHoveredId:oe,onHoverChange:L,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),(0,x.jsx)(DO,{currentTurn:y,maxTurn:v,time:Ve?.time??He?.time??0,timeInBanner:Rt,playing:C,speed:T,onTurnChange:ne,onPlayPause:te,onStepBack:M,onStepForward:N,onSpeedChange:E}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(Dk,{k:`?`,v:`help`}),(0,x.jsx)(Dk,{k:`1-5`,v:`mode`}),(0,x.jsx)(Dk,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(Dk,{k:`space`,v:`play / pause`}),(0,x.jsx)(Dk,{k:`click`,v:`${ae.person} drilldown`}),(0,x.jsx)(Dk,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ve&&He?`Turn ${Math.max(Ve.turn,He.turn)}. ${Ye?.name??`A`} ${ae.place}: ${Ve.cells.filter(e=>e.alive).length} alive, ${Ve.births} born, ${Ve.deaths} died, morale ${Math.round(Ve.morale*100)}%. ${Xe?.name??`B`} ${ae.place}: ${He.cells.filter(e=>e.alive).length} alive, ${He.births} born, ${He.deaths} died, morale ${Math.round(He.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>ne(v-1),"aria-label":`Jump to latest turn (T${v})`,className:$.jumpLatest,children:[`↓`,` Latest · T`,v,(0,x.jsxs)(`span`,{className:$.jumpLatestBehind,children:[`(`,v-1-y,` turn`,v-1-y==1?``:`s`,` behind)`]})]}),(0,x.jsx)(NO,{open:ie,onClose:()=>F(!1)}),(0,x.jsx)(iO,{open:ke,settings:B,onChange:ye,onClose:()=>Ae(!1)}),(0,x.jsx)(ek,{open:je,onClose:()=>Me(!1),snapsA:d,snapsB:f,actorNameA:Ye?.name??`Leader A`,actorNameB:Xe?.name??`Leader B`,forgeApprovedA:pt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:pt.b.attempts.filter(e=>e.approved).length,reuseCountA:pt.a.reuses.length,reuseCountB:pt.b.reuses.length,divergedCount:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)}),be&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>xe(null),className:$.toast,style:{"--toast-top":ge?`68px`:`8px`,"--side-color":be.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:be.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[be.side.toUpperCase(),` · T`,be.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:be.message})]},be.key),ge&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>_e(null),className:$.toast,style:{"--side-color":ge.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":`var(--rust)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,children:[(0,x.jsx)(`span`,{children:`⚡ Crisis`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ge.side.toUpperCase(),` · T`,ge.turn,` · `,ge.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:ge.title||`${ge.category} crisis unfolding`})]},ge.key),ct>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},ct),(0,x.jsx)(`style`,{children:`
|
|
129
129
|
@keyframes paracosm-vignette {
|
|
130
130
|
0% { opacity: 0; }
|
|
131
131
|
25% { opacity: 1; }
|
|
@@ -148,7 +148,7 @@ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange
|
|
|
148
148
|
100% { opacity: 1; transform: translateY(0); }
|
|
149
149
|
}
|
|
150
150
|
`})]})}var jk={footer:`_footer_c3dep_1`,phone:`_phone_c3dep_14`,nav:`_nav_c3dep_18`,navLink:`_navLink_c3dep_23`,consentSlot:`_consentSlot_c3dep_28`,statusChip:`_statusChip_c3dep_37`,cost:`_cost_c3dep_48`,costAmount:`_costAmount_c3dep_57`,costMuted:`_costMuted_c3dep_63`,brand:`_brand_c3dep_67`,brandAccent:`_brandAccent_c3dep_74`,brandLink:`_brandLink_c3dep_78`};function Mk(e){switch(e){case`client_disconnected`:return`browser tab closed before the sim finished`;case`quota_exhausted`:return`provider credits exhausted`;case`user_aborted`:return`cancelled by the user`;case`provider_error`:return`provider returned an unrecoverable error`;case`another_run_started`:return`you started another run`;case`server_restarted`:return`the server restarted before the run finished`;case`unknown`:return`reason not recorded by the server`;default:return e}}function Nk({s:e}){let t=e.isAborted?`var(--amber)`:e.isComplete?`var(--green)`:e.isRunning?`var(--color-success, var(--green))`:(e.connectionStatus,`var(--text-3)`),n=e.isAborted?`Interrupted`:e.isComplete?`Complete`:e.isRunning?`Running`:e.connectionStatus===`connected`?`Idle`:e.connectionStatus===`error`?`Reconnecting`:`Connecting`,r=e.isRunning&&!e.isComplete&&!e.isAborted?`●`:`○`,i=e.isAborted?(()=>{if(e.providerError)return`Run interrupted: ${e.providerError.message}. Click Clear to reset.`;let t=e.abortReason;if(!t)return`Run was interrupted before finishing all turns. Click Clear to reset.`;let n=typeof t.completedTurns==`number`?` after ${t.completedTurns} turn${t.completedTurns===1?``:`s`}`:``;return`Run interrupted: ${Mk(t.reason)}${n}. Click Clear to reset.`})():e.isComplete?`Run finished all turns. Verdict is broadcast in Reports.`:e.isRunning?`Simulation in progress.`:e.connectionStatus===`connected`?`Connected to the simulation server. Press RUN to start.`:e.connectionStatus===`error`?`Reconnecting to the simulation server.`:`Connecting to the simulation server.`;return(0,x.jsxs)(`span`,{className:jk.statusChip,style:{"--status-color":t},role:`status`,"aria-live":`polite`,"aria-label":`Simulation status: ${n}. ${i}`,title:i,children:[r,` `,n]})}function Pk(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Fk(e,t){let n=[`Total: ${Pk(e.totalCostUSD)} · ${e.totalTokens.toLocaleString()} tokens · ${e.llmCalls} calls`];if(t){let e=t.simUSD??0,r=t.chatUSD??0;e>0&&n.push(`• Simulation: ${Pk(e)}${t.simCalls==null?``:` (${t.simCalls} calls)`}`),r>0&&n.push(`• Chat: ${Pk(r)}${t.chatCalls==null?``:` (${t.chatCalls} calls)`}`)}return n.join(`
|
|
151
|
-
`)}function Ik(){return typeof document<`u`&&document.getElementById(`paracosm-consent-config`)!==null}function Lk(){let e=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let t=document.getElementById(`pcc-reopen`),n=document.getElementById(`pcc-shell`),r=e.current;if(t&&n&&r)return r.appendChild(t),()=>{n.appendChild(t)}},[]),e}function Rk({cost:e,costBreakdown:t,simStatus:n}){let r=jy(Ny),i=Ik(),a=Lk(),o=[`shrink-0`,jk.footer,r?jk.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:o,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:jk.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:jk.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`blog`})]}),n&&(0,x.jsx)(Nk,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:jk.cost,title:Fk(e,t),children:[(0,x.jsxs)(`span`,{className:jk.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:jk.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:jk.costMuted,children:[e.llmCalls,` calls`]})]}),i&&(0,x.jsx)(`span`,{ref:a,className:jk.consentSlot}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:jk.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:jk.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:jk.brandLink,children:`Frame.dev`})]})]})}var zk={backdrop:`_backdrop_1do5l_1`,dialog:`_dialog_1do5l_12`,header:`_header_1do5l_26`,title:`_title_1do5l_33`,closeBtn:`_closeBtn_1do5l_43`,section:`_section_1do5l_53`,scopeTitle:`_scopeTitle_1do5l_57`,list:`_list_1do5l_67`,row:`_row_1do5l_73`,keys:`_keys_1do5l_82`,kbd:`_kbd_1do5l_88`,description:`_description_1do5l_102`,footer:`_footer_1do5l_107`,kbdInline:`_kbdInline_1do5l_117`},Bk=[{keys:[`?`],description:`Open this shortcuts overlay`,scope:`Global`},{keys:[`Esc`],description:`Close overlays / drilldown panel`,scope:`Global`},{keys:[`←`],description:`Previous turn`,scope:`Visualization`},{keys:[`→`],description:`Next turn`,scope:`Visualization`},{keys:[`Space`],description:`Play / pause playback`,scope:`Visualization`},{keys:[`M`],description:`Cycle cluster mode (families · departments · mood · age)`,scope:`Visualization`},{keys:[`D`],description:`Toggle divergence tint overlay`,scope:`Visualization`},{keys:[`A`],description:`Collapse / expand the automaton band`,scope:`Visualization`},{keys:[`1`],description:`Automaton: mood propagation`,scope:`Visualization`},{keys:[`2`],description:`Automaton: forge flow`,scope:`Visualization`},{keys:[`3`],description:`Automaton: ecology grid`,scope:`Visualization`},{keys:[`Enter`],description:`Send chat message`,scope:`Chat`}];function Vk(){let[e,t]=(0,b.useState)(!1);return(0,b.useEffect)(()=>{let n=n=>{let r=n.target?.tagName,i=r===`INPUT`||r===`TEXTAREA`||r===`SELECT`||n.target?.isContentEditable;n.key===`?`&&!n.metaKey&&!n.ctrlKey&&!i?(n.preventDefault(),t(e=>!e)):n.key===`Escape`&&e&&(n.preventDefault(),t(!1))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e]),e?(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,onClick:()=>t(!1),className:zk.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:zk.dialog,children:[(0,x.jsxs)(`div`,{className:zk.header,children:[(0,x.jsx)(`h2`,{className:zk.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:zk.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=Bk.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:zk.section,children:[(0,x.jsx)(`h3`,{className:zk.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:zk.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:zk.row,children:[(0,x.jsx)(`span`,{className:zk.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:zk.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:zk.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:zk.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`Esc`}),` to close`]})]})}):null}var Hk={svgOverlay:`_svgOverlay_aob9y_1`,svgFill:`_svgFill_aob9y_8`,clickAway:`_clickAway_aob9y_13`,card:`_card_aob9y_19`,mobile:`_mobile_aob9y_41`,cardHeader:`_cardHeader_aob9y_54`,stepCount:`_stepCount_aob9y_62`,tabBadge:`_tabBadge_aob9y_69`,closeBtn:`_closeBtn_aob9y_82`,title:`_title_aob9y_93`,description:`_description_aob9y_105`,actions:`_actions_aob9y_116`,actionsRight:`_actionsRight_aob9y_124`,skipBtn:`_skipBtn_aob9y_129`,compact:`_compact_aob9y_141`,navBtn:`_navBtn_aob9y_146`,primaryBtn:`_primaryBtn_aob9y_163`,final:`_final_aob9y_180`,progressBar:`_progressBar_aob9y_185`,progressBarFill:`_progressBarFill_aob9y_193`,dotRow:`_dotRow_aob9y_200`,dot:`_dot_aob9y_200`,kbHint:`_kbHint_aob9y_219`},Uk=[{target:`[data-quickstart-seed]`,tab:`quickstart`,title:`Quickstart — author from a brief`,description:`Paste a brief, drop a PDF, or supply a URL. Paracosm grounds the prompt with web research, generates three distinct actors with HEXACO personalities, and runs them against the same scenario in parallel. The Twin demo card below runs a single subject against a single intervention if that's your use case.`},{target:`[role="tablist"][aria-label="Studio sub-navigation"]`,tab:`studio`,title:`Studio — author + branches`,description:`Drop any saved Paracosm artifact or bundle here to inspect, fork, and re-run. The Branches sub-tab forks an actor at any turn N and re-runs from that checkpoint with a new HEXACO profile, so you can probe alternate histories from a shared starting state.`},{target:`.topbar`,tab:`sim`,title:`Top Bar`,description:`Scenario name on the left. RUN, status, theme toggle, and HOW IT WORKS (replay this tour) on the right. The T / Y / S tokens in the center show turn, in-sim time, and deterministic seed — hover each for what they mean. A "⋯" menu reveals Save / Copy / Clear once a run has started.`},{target:`.tab-bar`,tab:`sim`,title:`Navigation`,description:`Quickstart and Studio for authoring. Sim, Viz, Chat for the live run. Reports and Library for analysis. Settings holds config (Event Log lives there as a sub-tab). Labels collapse to icons below 900px so the row never wraps onto two lines.`},{target:`[role="group"][aria-label="Sim layout"]`,tab:`sim`,title:`Sim layout`,description:`Side-by-side for 2 actors, Constellation for 3+. Constellation auto-engages above 3 actors because two columns physically can't fit them. Click any node in the Constellation graph to drill into one actor's decisions, departments, and tools. The tour pins side-by-side so you can see leader cards and event streams as they'd render for a 2-actor run.`},{target:`.leaders-row`,tab:`sim`,title:`Leader cards`,description:`Each actor renders with its name, archetype, HEXACO profile, and a population + morale sparkline. Left is amber, right is teal. Glyph color, Conway tiles, and chronicle pills downstream all pick up these same colors so you always know which side you're looking at.`},{target:`.sim-columns`,tab:`sim`,title:`Event streams`,description:`Each turn, both leaders face events the Director generated based on accumulated state. Departments analyze in parallel and may forge new tools. Commanders decide. Tools tint by side. INSPECT on a forged tool opens it on its line of five stations, and its Record holds Show in Event Log.`},{target:`[aria-label="Divergence rail"]`,tab:`sim`,title:`Divergence rail`,description:`How far the actors have diverged at the current turn. Shows decision texts and outcomes side by side in plain language. Same seed, different histories — because HEXACO shaped every LLM call.`},{target:`.viz-content`,tab:`viz`,title:`Viz — living canvas`,description:`Mirrored canvases, one per actor. Conway-style cellular tiles render underneath to encode mood (BLOCK = calm, GLIDER = agitated) while colonist glyphs sit on top as the primary signal. Hover a tile or a glyph for a tooltip; click either to drill into the colonist. Use the mode pills (LIVING / MOOD / FORGE / ECOLOGY / DIVERGENCE) and event filters above the canvas to reshape the read.`},{target:`.chat-layout`,tab:`chat`,title:`Character chat`,description:`Talk to any colonist from the run. Each carries their HEXACO profile, the memories they formed during the sim, and their relationships. The Viz drilldown popover has a direct Chat handoff that preselects the colonist here.`},{target:`.reports-content`,tab:`reports`,title:`Reports`,description:`Turn-by-turn rollup: commander decisions, department analyses, forged toolbox across both sides, agent reactions, verdict comparison. Each forged tool opens from its row, and its Record holds Show in Event Log for that tool's events.`},{target:`[role="group"][aria-label="View mode"]`,tab:`library`,title:`Library — saved runs`,description:`Every run you launch is saved here. Filter by scenario, leader configuration, or free-text search. Gallery view shows hero stats; Table view shows everything. Open any run to inspect, or promote it into Studio to fork a new branch.`},{target:`[role="tablist"][aria-label="Settings sub-navigation"]`,tab:`settings`,title:`Settings + event log`,description:`Configure actors with HEXACO sliders, pick a scenario, set turns and population, and drop in your own OpenAI or Anthropic key to bypass the hosted-demo caps. The Event Log sub-tab shows the raw SSE stream (status, turn_start, specialist_done, decision_made, outcome, reaction, forge_attempt) and is where a forged tool's Show in Event Log leads.`},{target:`.topbar`,tab:`sim`,title:`Ready to launch`,description:`That was demo data. Hit RUN in the top bar to launch a live simulation against the host caps, or paste your own API key in Settings for full-scope runs. When the run finishes, a "Run Complete" banner lands at the top with the verdict and a jump to the Reports tab.`}],Wk=360,Gk=`tour-highlight`,Kk=`
|
|
151
|
+
`)}function Ik(){return typeof document<`u`&&document.getElementById(`paracosm-consent-config`)!==null}function Lk(){let e=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let t=document.getElementById(`pcc-reopen`),n=document.getElementById(`pcc-shell`),r=e.current;if(t&&n&&r)return r.appendChild(t),()=>{n.appendChild(t)}},[]),e}function Rk({cost:e,costBreakdown:t,simStatus:n}){let r=My(Py),i=Ik(),a=Lk(),o=[`shrink-0`,jk.footer,r?jk.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:o,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:jk.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:jk.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`blog`})]}),n&&(0,x.jsx)(Nk,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:jk.cost,title:Fk(e,t),children:[(0,x.jsxs)(`span`,{className:jk.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:jk.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:jk.costMuted,children:[e.llmCalls,` calls`]})]}),i&&(0,x.jsx)(`span`,{ref:a,className:jk.consentSlot}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:jk.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:jk.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:jk.brandLink,children:`Frame.dev`})]})]})}var zk={backdrop:`_backdrop_1do5l_1`,dialog:`_dialog_1do5l_12`,header:`_header_1do5l_26`,title:`_title_1do5l_33`,closeBtn:`_closeBtn_1do5l_43`,section:`_section_1do5l_53`,scopeTitle:`_scopeTitle_1do5l_57`,list:`_list_1do5l_67`,row:`_row_1do5l_73`,keys:`_keys_1do5l_82`,kbd:`_kbd_1do5l_88`,description:`_description_1do5l_102`,footer:`_footer_1do5l_107`,kbdInline:`_kbdInline_1do5l_117`},Bk=[{keys:[`?`],description:`Open this shortcuts overlay`,scope:`Global`},{keys:[`Esc`],description:`Close overlays / drilldown panel`,scope:`Global`},{keys:[`←`],description:`Previous turn`,scope:`Visualization`},{keys:[`→`],description:`Next turn`,scope:`Visualization`},{keys:[`Space`],description:`Play / pause playback`,scope:`Visualization`},{keys:[`M`],description:`Cycle cluster mode (families · departments · mood · age)`,scope:`Visualization`},{keys:[`D`],description:`Toggle divergence tint overlay`,scope:`Visualization`},{keys:[`A`],description:`Collapse / expand the automaton band`,scope:`Visualization`},{keys:[`1`],description:`Automaton: mood propagation`,scope:`Visualization`},{keys:[`2`],description:`Automaton: forge flow`,scope:`Visualization`},{keys:[`3`],description:`Automaton: ecology grid`,scope:`Visualization`},{keys:[`Enter`],description:`Send chat message`,scope:`Chat`}];function Vk(){let[e,t]=(0,b.useState)(!1);return(0,b.useEffect)(()=>{let n=n=>{let r=n.target?.tagName,i=r===`INPUT`||r===`TEXTAREA`||r===`SELECT`||n.target?.isContentEditable;n.key===`?`&&!n.metaKey&&!n.ctrlKey&&!i?(n.preventDefault(),t(e=>!e)):n.key===`Escape`&&e&&(n.preventDefault(),t(!1))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e]),e?(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,onClick:()=>t(!1),className:zk.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:zk.dialog,children:[(0,x.jsxs)(`div`,{className:zk.header,children:[(0,x.jsx)(`h2`,{className:zk.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:zk.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=Bk.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:zk.section,children:[(0,x.jsx)(`h3`,{className:zk.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:zk.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:zk.row,children:[(0,x.jsx)(`span`,{className:zk.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:zk.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:zk.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:zk.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`Esc`}),` to close`]})]})}):null}var Hk={svgOverlay:`_svgOverlay_aob9y_1`,svgFill:`_svgFill_aob9y_8`,clickAway:`_clickAway_aob9y_13`,card:`_card_aob9y_19`,mobile:`_mobile_aob9y_41`,cardHeader:`_cardHeader_aob9y_54`,stepCount:`_stepCount_aob9y_62`,tabBadge:`_tabBadge_aob9y_69`,closeBtn:`_closeBtn_aob9y_82`,title:`_title_aob9y_93`,description:`_description_aob9y_105`,actions:`_actions_aob9y_116`,actionsRight:`_actionsRight_aob9y_124`,skipBtn:`_skipBtn_aob9y_129`,compact:`_compact_aob9y_141`,navBtn:`_navBtn_aob9y_146`,primaryBtn:`_primaryBtn_aob9y_163`,final:`_final_aob9y_180`,progressBar:`_progressBar_aob9y_185`,progressBarFill:`_progressBarFill_aob9y_193`,dotRow:`_dotRow_aob9y_200`,dot:`_dot_aob9y_200`,kbHint:`_kbHint_aob9y_219`},Uk=[{target:`[data-quickstart-seed]`,tab:`quickstart`,title:`Quickstart — author from a brief`,description:`Paste a brief, drop a PDF, or supply a URL. Paracosm grounds the prompt with web research, generates three distinct actors with HEXACO personalities, and runs them against the same scenario in parallel. The Twin demo card below runs a single subject against a single intervention if that's your use case.`},{target:`[role="tablist"][aria-label="Studio sub-navigation"]`,tab:`studio`,title:`Studio — author + branches`,description:`Drop any saved Paracosm artifact or bundle here to inspect, fork, and re-run. The Branches sub-tab forks an actor at any turn N and re-runs from that checkpoint with a new HEXACO profile, so you can probe alternate histories from a shared starting state.`},{target:`.topbar`,tab:`sim`,title:`Top Bar`,description:`Scenario name on the left. RUN, status, theme toggle, and HOW IT WORKS (replay this tour) on the right. The T / Y / S tokens in the center show turn, in-sim time, and deterministic seed — hover each for what they mean. A "⋯" menu reveals Save / Copy / Clear once a run has started.`},{target:`.tab-bar`,tab:`sim`,title:`Navigation`,description:`Quickstart and Studio for authoring. Sim, Viz, Chat for the live run. Reports and Library for analysis. Settings holds config (Event Log lives there as a sub-tab). Labels collapse to icons below 900px so the row never wraps onto two lines.`},{target:`[role="group"][aria-label="Sim layout"]`,tab:`sim`,title:`Sim layout`,description:`Side-by-side for 2 actors, Constellation for 3+. Constellation auto-engages above 3 actors because two columns physically can't fit them. Click any node in the Constellation graph to drill into one actor's decisions, departments, and tools. The tour pins side-by-side so you can see leader cards and event streams as they'd render for a 2-actor run.`},{target:`.leaders-row`,tab:`sim`,title:`Leader cards`,description:`Each actor renders with its name, archetype, HEXACO profile, and a population + morale sparkline. Left is amber, right is teal. Glyph color, Conway tiles, and chronicle pills downstream all pick up these same colors so you always know which side you're looking at.`},{target:`.sim-columns`,tab:`sim`,title:`Event streams`,description:`Each turn, both leaders face events the Director generated based on accumulated state. Departments analyze in parallel and may forge new tools. Commanders decide. Tools tint by side. INSPECT on a forged tool opens it on its line of five stations, and its Record holds Show in Event Log.`},{target:`[aria-label="Divergence rail"]`,tab:`sim`,title:`Divergence rail`,description:`How far the actors have diverged at the current turn. Shows decision texts and outcomes side by side in plain language. Same seed, different histories — because HEXACO shaped every LLM call.`},{target:`.viz-content`,tab:`viz`,title:`Viz — living canvas`,description:`Mirrored canvases, one per actor. Conway-style cellular tiles render underneath to encode mood (BLOCK = calm, GLIDER = agitated) while colonist glyphs sit on top as the primary signal. Hover a tile or a glyph for a tooltip; click either to drill into the colonist. Use the mode pills (LIVING / MOOD / FORGE / ECOLOGY / DIVERGENCE) and event filters above the canvas to reshape the read.`},{target:`.chat-layout`,tab:`chat`,title:`Character chat`,description:`Talk to any colonist from the run. Each carries their HEXACO profile, the memories they formed during the sim, and their relationships. The Viz drilldown popover has a direct Chat handoff that preselects the colonist here.`},{target:`.reports-content`,tab:`reports`,title:`Reports`,description:`Turn-by-turn rollup: commander decisions, department analyses, forged toolbox across both sides, agent reactions, verdict comparison. Each forged tool opens from its row, and its Record holds Show in Event Log for that tool's events.`},{target:`[role="group"][aria-label="View mode"]`,tab:`library`,title:`Library — saved runs`,description:`Every run you launch is saved here. Filter by scenario, leader configuration, or free-text search. Gallery view shows hero stats; Table view shows everything. Open any run to inspect, or promote it into Studio to fork a new branch.`},{target:`[role="tablist"][aria-label="Settings sub-navigation"]`,tab:`settings`,title:`Settings + event log`,description:`Configure actors with HEXACO sliders, pick a scenario, set turns and population, and drop in your own OpenAI or Anthropic key to bypass the hosted-demo caps. The Event Log sub-tab shows the raw SSE stream (status, turn_start, specialist_done, decision_made, outcome, reaction, forge_attempt) and is where a forged tool's Show in Event Log leads.`},{target:`.topbar`,tab:`sim`,title:`Ready to launch`,description:`That was demo data. Hit RUN in the top bar to launch a live simulation against the host caps, or paste your own API key in Settings for full-scope runs. When the run finishes, a "Run Complete" banner lands at the top with the verdict and a jump to the Reports tab.`}],Wk=360,Gk=`tour-highlight`,Kk=`
|
|
152
152
|
/* The highlighted element gets a bright luminous amber glow */
|
|
153
153
|
.${Gk} {
|
|
154
154
|
outline: 3px solid var(--amber) !important;
|