From 164605be857453e87cf3b8f8f0311686b9acd3e2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 19 Aug 2026 00:11:39 +0200 Subject: [PATCH] Provision reusable batches of single-use invites --- crates/ghostlight-dungeon/src/main.rs | 61 ++++++++++++++++--- docs/architecture/ghostlight-dungeon-mvp.md | 2 +- notes/ghostlight-dungeon.md | 2 +- .../{index-B_0anyiQ.js => index-DT1ZfEs6.js} | 2 +- web/dist/index.html | 2 +- web/src/main.ts | 2 +- 6 files changed, 59 insertions(+), 12 deletions(-) rename web/dist/assets/{index-B_0anyiQ.js => index-DT1ZfEs6.js} (84%) diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 83044e4..768965f 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -129,6 +129,8 @@ struct ProviderParallelismRequest { struct AuthState { schema: String, unused_invite_hashes: BTreeSet, + #[serde(default)] + provisioned_invite_hashes: BTreeSet, session_hashes: BTreeSet, #[serde(default)] session_campaigns: BTreeMap, @@ -163,6 +165,21 @@ impl AuthOwner { } } +fn provision_invite_hashes(state: &mut AuthState, supplied: &BTreeSet) -> bool { + let new_hashes: BTreeSet = supplied + .difference(&state.provisioned_invite_hashes) + .cloned() + .collect(); + if new_hashes.is_empty() { + return false; + } + state.unused_invite_hashes.extend(new_hashes); + state + .provisioned_invite_hashes + .extend(supplied.iter().cloned()); + true +} + #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() @@ -194,22 +211,31 @@ async fn main() -> anyhow::Result<()> { .filter(|s| !s.is_empty()) .map(str::to_owned) .collect(); - if invite_tokens.len() != 2 { + if invite_tokens.is_empty() || invite_tokens.len() > 128 { return Err(anyhow::anyhow!( - "GhostlightDungeon requires exactly two unused invite tokens" + "GhostlightDungeon requires between 1 and 128 distinct invite tokens" )); } + let supplied_invite_hashes: BTreeSet = invite_tokens + .iter() + .map(|token| secret_hash(token)) + .collect(); std::fs::create_dir_all(runtime_root.join("service"))?; let auth_store = CampaignStore::open(runtime_root.join("service/auth.cc"))?; let (auth_row, auth_state) = match auth_store.load::("auth_state.v1", "primary")? { - Some(existing) => existing, + Some((row, mut state)) => { + if !provision_invite_hashes(&mut state, &supplied_invite_hashes) { + (row, state) + } else { + let next_row = auth_store.replace(&row, "ghostlight.auth_state.v1", &state)?; + (next_row, state) + } + } None => { let state = AuthState { schema: "ghostlight.auth_state.v1".into(), - unused_invite_hashes: invite_tokens - .iter() - .map(|token| secret_hash(token)) - .collect(), + unused_invite_hashes: supplied_invite_hashes.clone(), + provisioned_invite_hashes: supplied_invite_hashes, session_hashes: BTreeSet::new(), session_campaigns: BTreeMap::new(), session_campaign_ids: BTreeMap::new(), @@ -2486,6 +2512,7 @@ mod tests { let auth_state = AuthState { schema: "ghostlight.auth_state.v1".into(), unused_invite_hashes: BTreeSet::new(), + provisioned_invite_hashes: BTreeSet::new(), session_hashes: BTreeSet::new(), session_campaigns: BTreeMap::new(), session_campaign_ids: BTreeMap::new(), @@ -2841,6 +2868,7 @@ mod tests { let auth_state = AuthState { schema: "ghostlight.auth_state.v1".into(), unused_invite_hashes: BTreeSet::new(), + provisioned_invite_hashes: BTreeSet::new(), session_hashes: BTreeSet::from(["left".into(), "right".into()]), session_campaigns: BTreeMap::from([ ("left".into(), left.id), @@ -2899,6 +2927,7 @@ mod tests { let original = AuthState { schema: "ghostlight.auth_state.v1".into(), unused_invite_hashes: BTreeSet::from(["invite".into()]), + provisioned_invite_hashes: BTreeSet::from(["invite".into()]), session_hashes: BTreeSet::new(), session_campaigns: BTreeMap::new(), session_campaign_ids: BTreeMap::new(), @@ -2935,6 +2964,24 @@ mod tests { assert_eq!(owner.row, row); } + #[test] + fn invite_provisioning_adds_new_hashes_without_resurrecting_consumed_ones() { + let mut state = AuthState { + schema: "ghostlight.auth_state.v1".into(), + unused_invite_hashes: BTreeSet::new(), + provisioned_invite_hashes: BTreeSet::from(["consumed".into()]), + session_hashes: BTreeSet::new(), + session_campaigns: BTreeMap::new(), + session_campaign_ids: BTreeMap::new(), + }; + let supplied = BTreeSet::from(["consumed".into(), "fresh".into()]); + + assert!(provision_invite_hashes(&mut state, &supplied)); + assert_eq!(state.unused_invite_hashes, BTreeSet::from(["fresh".into()])); + assert!(!provision_invite_hashes(&mut state, &supplied)); + assert_eq!(state.unused_invite_hashes, BTreeSet::from(["fresh".into()])); + } + #[tokio::test] async fn campaign_selection_reloads_stale_auth_without_losing_concurrent_state() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 48c3ae7..34ee3a5 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -771,7 +771,7 @@ Live model allocation: The daemon serves the embedded browser bundle on TCP 8831. Firewall scope is Starfire's private LAN and `10.77.0.0/24`; there is no public listener or -Yggdrasil web gateway. Two single-use invites establish separate HttpOnly +Yggdrasil web gateway. Provisioned single-use invites establish separate HttpOnly sessions. Campaigns remain single-player in the MVP. This is a product-scope constraint, not a WorldKernel identity: the intended post-solo extension maps multiple authenticated members to distinct player-controlled actors while all diff --git a/notes/ghostlight-dungeon.md b/notes/ghostlight-dungeon.md index 74082da..9c039f1 100644 --- a/notes/ghostlight-dungeon.md +++ b/notes/ghostlight-dungeon.md @@ -228,7 +228,7 @@ stake prose alone never impersonates world mutation. - optional operator inspector for evidence, topology, state versions, model receipts, rejected proposals, and private spoiler traces. - Do not expose model chain-of-thought or secrets. - Serve the embedded web bundle on TCP `8831`. Firewall access is limited to Starfire’s private LAN and `10.77.0.0/24`; no public listener or Yggdrasil web gateway is added. -- Use two single-use invite links that establish separate HttpOnly sessions. Campaigns are single-player; simultaneous co-op is outside the MVP. +- Use provisioned single-use invite links that establish separate HttpOnly sessions. Campaigns are single-player; simultaneous co-op is outside the MVP. - Run `GhostlightDungeon` as a normal detached process under the Starfire operator account. Record its PID, executable, and logs; explicit start, stop, health, release, and rollback scripts own lifecycle. ACL the runtime root to administrators and that operator account. - Read the DeepSeek key from stdin during setup, protect it with machine-scoped DPAPI plus file ACLs, and never place it in source, arguments, logs, or environment projections. - Build immutable release directories from the exact Git commit, switch the active release through the guarded junction, and record provenance in CultCache plus the immutable release manifest. Process restart is explicit; Windows service installation and automatic boot recovery are outside this MVP by operator choice. diff --git a/web/dist/assets/index-B_0anyiQ.js b/web/dist/assets/index-DT1ZfEs6.js similarity index 84% rename from web/dist/assets/index-B_0anyiQ.js rename to web/dist/assets/index-DT1ZfEs6.js index 3f24b1c..f5c0fa1 100644 --- a/web/dist/assets/index-B_0anyiQ.js +++ b/web/dist/assets/index-DT1ZfEs6.js @@ -150,4 +150,4 @@ void main() { YBXA - `}function Rn(e,t=document.body){const n=qe(e),i=document.documentElement.style;$n(n.assets.fontCss);for(const[c,r]of Object.entries(fn))i.setProperty(c,r);const o={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[c,r]of Object.entries(o)){const d=n.tokens[c];d!==void 0&&i.setProperty(r,String(d))}const a=n.tokens.fontBody,l=n.tokens.fontDisplay,s=n.tokens.fontTitle,f=n.tokens.fontMono;a&&i.setProperty("--font-body",be(String(a))),l&&i.setProperty("--font-title",be(String(l))),s&&i.setProperty("--font-title",be(String(s))),f&&i.setProperty("--font-mono",be(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),t.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",t.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function le(e,t={},n=z){const i=w(t.action),o=n.provider?.providerId||se?.providerId||"surface unknown",a=n.activeSurfaceId||se?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||o,l=Fn(n,a),s=p(l.commandBoundary,t.commandBoundary,i.commandBoundary,i.target),f=p(l.receiptSchema,t.receiptSchema,i.receiptSchema),c={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:o,surfaceId:a,command:e||g(i.type,"invoke"),payload:{...i,transport:t.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return s&&(c.commandBoundary=s),f&&(c.receiptSchema=f),c}function Fn(e,t){const n=[...e.provider?.surfaces||[],...e.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===t&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function Ze(e,t){const n=w(e.action);return g(e.command,g(e.commandId,g(n.command,g(n.target,g(n.type,t?.commandId||"")))))}function H(e){const t=m("section","pane");return t.append(m("h2","","No Surface")),t.append(m("div","detail",e)),t}function Qe(e,t,n,i,o){e.dataset.commandId=n,e.tabIndex=e instanceof HTMLButtonElement?e.tabIndex:0;const a=()=>{const l=le(n,i,o);o.commandSink?.(l,t)};e.addEventListener("click",a),e.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),a())})}function Pn(e,t,n){const i=Ln(e,t),o=w(i.find(u=>u.kind==="control.box")?.props),a=i.filter(u=>u.kind==="control.part"),l=Number(e.min??0),s=Number(e.max??1),f=m("div","cultui-slider");f.dataset.skin=g(e.skin,"default"),f.dataset.bind=g(e.bind,""),Nn(f,o);const c=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(l),r.max=String(s),r.step=String(e.step??.01),r.setAttribute("aria-label",g(e.bind,"slider"));for(const u of a){const h=w(u.props),y=m("span",`cultui-slider-part ${g(h.name,"part")}`);Dn(y,h),c.append(y)}return a.some(u=>w(u.props).name==="track")||c.append(m("span","cultui-slider-part track")),a.some(u=>w(u.props).name==="fill")||c.append(m("span","cultui-slider-part fill")),a.some(u=>w(u.props).name==="thumb")||c.append(m("span","cultui-slider-part thumb")),f.append(c,r),(u=>{const h=Number(u??l),y=Math.max(l,Math.min(s,Number.isFinite(h)?h:l)),b=s===l?0:(y-l)/(s-l)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(e.value??l),r.addEventListener("input",()=>{const u=le(g(e.command,"control.slider.input"),{...e,action:{...w(e.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:e})}),f}function Ln(e,t){const n=typeof e.skin=="string"?e.skin:"",o=[...n?at.controlSkins[n]?.children||[]:[],...t];return o.length?o:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function qe(e){if(Array.isArray(e)){const t={},n={};for(const i of e)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:t[i.name]=i.value);return{tokens:t,assets:n,controlSkins:{}}}return{tokens:w(e?.tokens),assets:w(e?.assets),controlSkins:w(e?.controlSkins)}}function ae(e){if(!e)return"";const t=z.assetUrlResolver;return t?t(e,se):/^(https?:|data:|blob:)/i.test(e)?e:z.assetBaseUrl&&e.startsWith("/")?`${z.assetBaseUrl.replace(/\/+$/,"")}${e}`:e}function $n(e){const t=typeof e=="string"?e.trim():"";if(he?.dataset.href===t||(he?.remove(),he=void 0,!t))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=t,i.dataset.href=t,document.head.append(i),he=i}function Mn(e,t,n){const i=[];return(e==="text.title"||t.role==="title")&&i.push("cultui-title","eve-text-title"),e==="text.subtitle"&&i.push("eve-text-subtitle"),e==="label"&&i.push("cultui-label"),t.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function Nn(e,t){t.height!==void 0&&(e.style.minHeight=R(t.height)),t.width!==void 0&&(e.style.width=R(t.width)),typeof t.overflow=="string"&&(e.style.overflow=t.overflow)}function Dn(e,t){const n=Array.isArray(t.size)?t.size:[t.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(e.style.width=R(n[0])),n[1]!==void 0&&(e.style.height=R(n[1])),t.radius!==void 0&&(e.style.borderRadius=R(t.radius)),t.fill!==void 0&&(e.style.background=xe(String(t.fill))),t.bleed!==void 0&&e.style.setProperty("--part-bleed",R(t.bleed)),(Array.isArray(t.anchor)?t.anchor:[t.anchor]).includes("value")&&(e.dataset.anchorValue="true")}function ye(e,t){t.gap!==void 0&&(e.style.gap=R(t.gap)),t.padding!==void 0&&(e.style.padding=R(t.padding)),t.size!==void 0&&(e.style.flex=Bn(t.size)),t.min!==void 0&&(e.style.minWidth=R(t.min)),t.max!==void 0&&(e.style.maxWidth=R(t.max)),t.align!==void 0&&(e.style.alignItems=t.align==="end"?"flex-end":String(t.align)),(t.clip==="true"||t.clip===!0)&&(e.style.overflow="hidden"),t.scroll==="y"&&(e.style.overflowY="auto"),t.scroll==="x"&&(e.style.overflowX="auto")}function Bn(e){return typeof e=="string"&&e.endsWith("fr")?`${Number(e.slice(0,-2))||1} 1 0`:e==="auto"||e==="content"?"0 0 auto":`0 0 ${R(e)}`}function R(e){return Array.isArray(e)?e.map(R).join(" "):typeof e=="number"?`${e}px`:typeof e=="string"&&/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:String(e??"")}function xe(e){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[e]||e}function be(e){return e.includes("Zen Kaku Gothic New")||e.includes("M PLUS 1")?e:e.includes("Montserrat")?`${e}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:e.includes("Ubuntu")?`${e}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${e}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function S(e,t){t.id&&(e.id=t.id),t.id&&(e.dataset.eveNodeId=t.id),t.kind&&(e.dataset.eveKind=t.kind)}function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qn(e){return Array.isArray(e)?e:[]}function Un(e){return qn(e).map((t,n)=>lt({kind:"list.item",props:w(t)}))}function g(e,t){return e==null?t:String(e)}function p(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function Ue(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?["1","true","yes","on"].includes(e.trim().toLowerCase()):!1}function q(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}function Wn(e){const t=e.toLowerCase();return t.includes("sensor")?"S":t.includes("thermal")?"T":t.includes("fuel")?"F":t.includes("cargo")?"C":t.includes("weapon")?"W":e.trim().slice(0,1).toUpperCase()||"?"}function On(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length&&t.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function et(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function m(e,t="",n=""){const i=document.createElement(e);return t&&(i.className=t),n&&(i.textContent=n),i}const _e=document.querySelector("#surface"),F=document.querySelector("#status"),U=document.querySelector("#receipt"),mt=document.querySelector("#compiler"),We=document.querySelector("#composer"),Ee=document.querySelector("#destination-form"),pt=document.querySelector("#compiler-results"),ht=document.querySelector("#campaign-lab"),zn=document.querySelector("#campaign-list"),Gn=document.querySelector("#operator-lab");Gn.hidden=!["127.0.0.1","localhost","::1"].includes(window.location.hostname);let de=0,Ce="",Ne=0,gt=0,ke=!1;const Re=new Set;class yt extends Error{}async function ue(e){if(ke)throw new Error("A Ghostlight request is already in progress.");ke=!0,document.body.setAttribute("aria-busy","true");for(const t of document.querySelectorAll("button, input, textarea, select"))t.disabled||(t.disabled=!0,Re.add(t));try{return await e()}finally{for(const t of Re)t.disabled=!1;Re.clear(),document.body.removeAttribute("aria-busy"),ke=!1}}function v(e,t,n){const i=document.createElement(e);return t!==void 0&&(i.textContent=t),n&&(i.className=n),i}function B(e,t){const n=[v("h3",e)];for(const i of t.filter(Boolean))n.push(v("p",i));U.replaceChildren(...n),U.hidden=!1}async function ie(e){return e.status===204?null:(e.headers.get("content-type")??"").includes("json")?e.json():e.text()}function re(e,t){return typeof e=="string"&&e.trim()?e.trim():e&&typeof e.error=="string"&&e.error.trim()?e.error.trim():t}function bt(e){const t=e instanceof Error&&e.message.trim()?e.message.trim():"The Ghostlight connection failed before a response arrived.";if(F.textContent=t,e instanceof yt){B("Request refused",[t,"The server returned an error response. Refresh campaign state before retrying."]);return}B("Request did not complete",[t,"The server remains authoritative. Refresh the campaign before retrying; the lost response may have followed a commit."])}window.addEventListener("unhandledrejection",e=>{e.preventDefault(),bt(e.reason)});function Kn(e){if(e?.kind==="assessed"){const t=e.assessment,n=[v("h3",t.admissible?"Action assessment":"That attempt is not possible")];if(t.admissible){n.push(v("p",`DC ${t.dc} · modifier ${t.modifier_total>=0?"+":""}${t.modifier_total}`));const i=v("ul");for(const o of t.modifiers??[])i.append(v("li",`${o.label}: ${o.value>=0?"+":""}${o.value}`));n.push(i),n.push(v("p",`Strong/success: ${t.success_stake}`)),n.push(v("p",`Mixed: ${t.mixed_stake}`)),n.push(v("p",`Failure: ${t.failure_stake}`)),n.push(v("p",`Effect ceiling: ${t.effect_ceiling}`,"quiet"))}else{n.push(v("p",t.missing_permission??"The attempt has no admissible path from current state."));for(const i of t.bargains??[])n.push(v("p",`Possible bargain: ${i}`))}U.replaceChildren(...n),U.hidden=!1;return}if(e?.kind==="committed"){const t=e.receipt?.roll;if(t){const n=String(t.outcome).replaceAll("_"," ");B(n.charAt(0).toUpperCase()+n.slice(1),[`d20 ${t.d20} ${t.modifier_total>=0?"+":"−"} ${Math.abs(t.modifier_total)} = ${t.total} against DC ${t.dc}`])}else B("World advanced",[`Revision ${e.revision}`]);return}if(e?.kind==="resolution_updated"){B("World resolution updated",[`Resolution epoch ${e.receipt?.resolution_epoch??"advanced"}`]);return}B("Command result",[e?.error??"The world returned no player-facing detail."])}function Xn(){const e="This laboratory requires an unused invite link.";F.textContent=e,mt.hidden=!0,We.hidden=!0,Ee.hidden=!0,ht.hidden=!0,U.hidden=!0,_e.hidden=!1;const t=v("article",void 0,"card");t.append(v("h2","Private campaign laboratory"),v("p",e),v("p","Open one of the two single-use tester invitations on this device. The resulting session stays separate from the other player's campaigns.","quiet")),_e.replaceChildren(t)}async function ce(){const e=await fetch("/api/surface");if(e.status===401){Xn();return}const t=await ie(e);if(!e.ok){F.textContent=re(t,"The campaign surface is temporarily unavailable.");return}const n=t.surface_id==="ghostlight.compiler";if(mt.hidden=!n,We.hidden=n,Ee.hidden=n,_e.hidden=n,ht.hidden=n,n){F.textContent="No campaign exists. Retrieve the Vault and approve a world seed.";return}if(de=Number(t.world_revision??t.version??0),Ce=String(t.player_actor_id??""),!Ce)throw new Error("Campaign surface omitted its canonical player actor ID.");const i=String(t.player_location_id??"");if(!i)throw new Error("Campaign surface omitted its canonical player location ID.");document.querySelector("#destination-origin").value=i,Ne=Number(t.resolution?.policy?.resolution_epoch??0),gt=Number(t.resolution?.policy?.provider_configuration_epoch??0);const o=Number(t.resolution?.policy?.active_cell_budget??8),a=document.querySelector("#active-cell-budget");a.value=String(o),document.querySelector("#active-cell-budget-value").value=String(o),document.querySelector("#resolution-status").textContent=`${t.resolution?.effective_budget??o} effective cells · ${t.resolution?.mandatory_overage??0} temporary overage · epoch ${Ne}`;const l=Number(t.resolution?.policy?.provider_parallelism??8);document.querySelector("#provider-parallelism").value=String(l),document.querySelector("#provider-parallelism-value").value=String(l);const s=document.querySelector("#fission-parent");s.replaceChildren(...(t.resolution?.fission_targets??[]).map(r=>{const d=v("option",`${r.name} · ${r.id}`);return d.value=r.id,d})),document.querySelector("#fission-form").hidden=s.options.length===0,st(t,_e,{body:document.body,clientId:"ghostlight.browser",statusElement:F});const f=await fetch("/api/campaigns"),c=await ie(f);if(!f.ok){F.textContent=re(c,"The campaign list is temporarily unavailable.");return}zn.replaceChildren(...c.campaigns.map(r=>{const d=v("button",`${r.selected?"●":"○"} ${r.name} · revision ${r.revision}`);return d.type="button",d.disabled=!!r.selected,r.selected||d.addEventListener("click",async()=>{await oe(`/api/campaigns/select/${r.id}`,{})}),d}))}async function vt(e,t){F.textContent="Retrieving evidence and compiling…";const n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await ie(n);if(!n.ok)throw F.textContent=re(i,"Compilation failed"),new yt(F.textContent);return i}async function ne(e,t){return ue(()=>vt(e,t))}async function oe(e,t){return ue(async()=>{const n=await vt(e,t);return await ce(),n})}function tt(e,t,n){const i=v("div",void 0,"cards");e.forEach((o,a)=>{const l=v("article",void 0,"card");l.append(v("h3",o.title??o.name),v("p",o.player_hook??o.premise)),o.era&&l.append(v("p",`${o.era} · ${o.place} · ${o.pressure}`));const s=v("button",t);s.type="button",s.addEventListener("click",()=>n(e[a])),l.append(s),i.append(l)}),pt.replaceChildren(i)}function W(e,t,n){const i=v("details");i.append(v("summary",t));const o=v("ul");for(const a of n)o.append(v("li",a));n.length===0&&o.append(v("li","None declared.")),i.append(o),e.append(i)}document.querySelector("#suggest-form").addEventListener("submit",async e=>{e.preventDefault();const t=await ne("/api/compiler/openings",{setting:document.querySelector("#setting").value,constraints:[]});tt(t.openings,"Choose opening",async n=>{const i=await ne("/api/compiler/roles",{opening_id:n.id});tt(i.roles,"Choose role",async o=>xt(await ne("/api/compiler/selected",{campaign_name:n.title,opening_id:n.id,role_id:o.id})))})});document.querySelector("#custom-form").addEventListener("submit",async e=>{e.preventDefault(),await xt(await ne("/api/compiler/custom",Object.fromEntries(new FormData(e.currentTarget))))});async function xt(e){const t=e.preview,n=Array.isArray(t.evidence_coverage)?t.evidence_coverage:[],i=n.reduce((s,f)=>{const c=String(f?.lane??"excluded");return s[c]=(s[c]??0)+1,s},{}),o=v("article",void 0,"card");o.append(v("h3",t.title),v("p",t.opening??""),v("p",`${t.locations?.length??0} locations · ${(t.cast?.length??0)+1} actors · ${t.institutions?.length??0} institutions`),v("p",t.gaps.length?`Material gaps: ${t.gaps.join("; ")}`:"No declared material gaps.","warning"),v("p",`Branch assumptions: ${t.branch_assumptions.join("; ")||"none"}`),v("p",n.length?`Evidence use: ${i.direct_seed??0} direct · ${i.setting_background??0} background · ${i.excluded??0} excluded`:"Evidence use: no retrieved sources were admitted to this seed.","quiet"));const a=t.player_role??{};W(o,`Player role · ${a.name??"unnamed"}`,[`Starts at ${a.location_id??"an unspecified location"}`,...(a.capabilities??[]).map(s=>`Capability: ${s}`),...(a.equipment??[]).map(s=>`Equipment: ${s}`),...(a.conditions??[]).map(s=>`Condition: ${s}`),...(a.obligations??[]).map(s=>`Obligation: ${s}`)]),W(o,`Initial topology · ${t.locations?.length??0} locations`,(t.locations??[]).map(s=>{const f=Object.keys(s.routes??{});return`${s.name} · ${s.id}${s.container_id?` · inside ${s.container_id}`:""}${f.length?` · routes to ${f.join(", ")}`:" · no compiled route"}`})),W(o,`Present cast · ${t.cast?.length??0}`,(t.cast??[]).map(s=>`${s.name} · ${s.id} · at ${s.location_id}`)),W(o,`Institutions · ${t.institutions?.length??0}`,(t.institutions??[]).map(s=>`${s.name} · ${s.id}`)),W(o,`Populations · ${t.populations?.length??0}`,(t.populations??[]).map(s=>`${s.name} · ${s.id} · at ${s.home_location_id}`)),W(o,`World clocks · ${t.clocks?.length??0}`,(t.clocks??[]).map(s=>`${s.name} · ${s.progress}/${s.threshold} · ${s.trigger}`)),W(o,`Evidence coverage · ${n.length}`,n.map(s=>`${s.source_id} · ${String(s.lane).replaceAll("_"," ")} · ${s.rationale}`));const l=v("button","Approve and enter");l.type="button",l.addEventListener("click",async()=>{await oe(`/api/compiler/approve/${e.preview_id}`,{})}),o.append(l),pt.replaceChildren(o),F.textContent="Preview compiled. Nothing has entered world state yet."}async function fe(e){return ue(async()=>{F.textContent="The world is considering the command…";const t=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await ie(t);if(!t.ok){const i=re(n,"The command was refused.");return B("Command refused",[i]),F.textContent=i,await ce(),n}return Kn(n),await ce(),n})}function wt(e){if(e?.kind!=="assessed")return;const t=document.createElement("button");t.type="button",t.textContent=e.assessment.admissible?"Confirm server roll":"Revise attempt",t.addEventListener("click",async()=>{if(!e.assessment.admissible){document.querySelector("#attempt").focus();return}const n=await fe({type:"attempt",assessment_digest:e.assessment.digest});wt(n)}),U.append(t)}We.addEventListener("submit",async e=>{e.preventDefault();const t=document.querySelector("#attempt").value.trim(),n=document.querySelector("#intended-effect"),i=n.value.trim();if(t){if(!i){F.textContent="Describe the uncertain outcome you want assessed, or use Speak for words that need no roll.",n.focus();return}wt(await fe({type:"assess",expected_revision:de,intent:{actor_id:Ce,description:t,intended_effect:i}}))}});document.querySelector("#speak").addEventListener("click",async()=>{const e=document.querySelector("#attempt"),t=e.value.trim();if(!t){F.textContent="Write what your character says first.",e.focus();return}(await fe({type:"speak",expected_revision:de,actor_id:Ce,text:t,intended_effect:null}))?.kind==="committed"&&(e.value="")});document.querySelector("#wait").addEventListener("click",()=>{fe({type:"wait",expected_revision:de,minutes:60})});document.querySelector("#active-cell-budget").addEventListener("input",e=>{document.querySelector("#active-cell-budget-value").value=e.currentTarget.value});document.querySelector("#resolution-form").addEventListener("submit",async e=>{e.preventDefault(),await fe({type:"set_resolution_budget",expected_revision:de,expected_resolution_epoch:Ne,active_cell_budget:Number(document.querySelector("#active-cell-budget").value)})});document.querySelector("#provider-parallelism").addEventListener("input",e=>{document.querySelector("#provider-parallelism-value").value=e.currentTarget.value});document.querySelector("#provider-parallelism-form").addEventListener("submit",async e=>{e.preventDefault(),await ue(async()=>{F.textContent="Applying the provider concurrency limit…";const t=await fetch("/api/operator/provider-parallelism",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({expected_provider_configuration_epoch:gt,provider_parallelism:Number(document.querySelector("#provider-parallelism").value)})}),n=await ie(t),i=re(n,"The operator limit was refused.");B(t.ok?"Provider concurrency updated":"Provider concurrency refused",[t.ok?`Parallel requests: ${n?.receipt?.provider_parallelism??n?.provider_parallelism??"updated"}`:i]),t.ok||(F.textContent=i),await ce()})});Ee.addEventListener("submit",async e=>{e.preventDefault();const t=await ne("/api/compiler/destination",Object.fromEntries(new FormData(Ee))),n=t.preview;B("Destination preview",(n.gaps??[]).map(o=>`Material gap: ${o}`)),W(U,`Compiled topology · ${n.locations?.length??0} locations`,(n.locations??[]).map(o=>{const a=Object.keys(o.routes??{}),l=[...o.persistent_features??[]];return`${o.name} · ${o.id}${o.container_id?` · inside ${o.container_id}`:""}${a.length?` · routes to ${a.join(", ")}`:" · no compiled route"}${l.length?` · ${l.join(", ")}`:""}`})),F.textContent="Destination preview compiled; topology is unchanged until approval.";const i=v("button","Approve destination");i.type="button",i.addEventListener("click",async()=>{await oe(`/api/compiler/destination/approve/${t.preview_id}`,{}),i.remove()}),U.append(i)});document.querySelector("#fission-form").addEventListener("submit",async e=>{e.preventDefault();const t=new FormData(e.currentTarget),n=String(t.get("requested_partition_values")??"").split(",").map(a=>a.trim()).filter(Boolean);if(n.length>16||n.some(a=>[...a].length>160)){F.textContent="Use at most 16 named cuts, with at most 160 characters in each cut.",document.querySelector("#fission-values").focus();return}const i=await ne("/api/compiler/gestalt/fission",{parent_gestalt_id:t.get("parent_gestalt_id"),partition_axis:t.get("partition_axis"),requested_partition_values:n,reason:t.get("reason")});B("Population fission preview",[...(i.preview?.gaps??[]).map(a=>`Material gap: ${a}`)]),W(U,`Canonical child leaves · ${i.preview?.children?.length??0}`,(i.preview?.children??[]).map(a=>`${a.name} · ${a.id} · ${a.partition_value??"other/unknown"} · at ${a.home_location_id}`)),F.textContent="Fission preview compiled. Canonical leaves are unchanged until approval.";const o=document.createElement("button");o.type="button",o.textContent="Approve population fission",o.addEventListener("click",async()=>{await oe(`/api/compiler/gestalt/fission/approve/${i.preview_id}`,{}),o.remove()}),U.append(o)});document.querySelector("#fork-form").addEventListener("submit",async e=>{e.preventDefault(),await oe("/api/campaigns/fork",Object.fromEntries(new FormData(e.currentTarget)))});document.querySelector("#reset-form").addEventListener("submit",async e=>{e.preventDefault(),await oe("/api/campaigns/reset",Object.fromEntries(new FormData(e.currentTarget)))});document.querySelector("#load-operator").addEventListener("click",async()=>{await ue(async()=>{const e=await fetch("/api/operator"),t=await ie(e);if(!e.ok){const n=re(t,"The operator surface is unavailable.");B("Operator inspector refused",[n]),F.textContent=n;return}st(t,document.querySelector("#operator-output"),{body:document.body,clientId:"ghostlight.operator",statusElement:F})})});ce().catch(bt); + `}function Rn(e,t=document.body){const n=qe(e),i=document.documentElement.style;$n(n.assets.fontCss);for(const[c,r]of Object.entries(fn))i.setProperty(c,r);const o={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[c,r]of Object.entries(o)){const d=n.tokens[c];d!==void 0&&i.setProperty(r,String(d))}const a=n.tokens.fontBody,l=n.tokens.fontDisplay,s=n.tokens.fontTitle,f=n.tokens.fontMono;a&&i.setProperty("--font-body",be(String(a))),l&&i.setProperty("--font-title",be(String(l))),s&&i.setProperty("--font-title",be(String(s))),f&&i.setProperty("--font-mono",be(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),t.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",t.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function le(e,t={},n=z){const i=w(t.action),o=n.provider?.providerId||se?.providerId||"surface unknown",a=n.activeSurfaceId||se?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||o,l=Fn(n,a),s=p(l.commandBoundary,t.commandBoundary,i.commandBoundary,i.target),f=p(l.receiptSchema,t.receiptSchema,i.receiptSchema),c={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:o,surfaceId:a,command:e||g(i.type,"invoke"),payload:{...i,transport:t.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return s&&(c.commandBoundary=s),f&&(c.receiptSchema=f),c}function Fn(e,t){const n=[...e.provider?.surfaces||[],...e.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===t&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function Ze(e,t){const n=w(e.action);return g(e.command,g(e.commandId,g(n.command,g(n.target,g(n.type,t?.commandId||"")))))}function H(e){const t=m("section","pane");return t.append(m("h2","","No Surface")),t.append(m("div","detail",e)),t}function Qe(e,t,n,i,o){e.dataset.commandId=n,e.tabIndex=e instanceof HTMLButtonElement?e.tabIndex:0;const a=()=>{const l=le(n,i,o);o.commandSink?.(l,t)};e.addEventListener("click",a),e.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),a())})}function Pn(e,t,n){const i=Ln(e,t),o=w(i.find(u=>u.kind==="control.box")?.props),a=i.filter(u=>u.kind==="control.part"),l=Number(e.min??0),s=Number(e.max??1),f=m("div","cultui-slider");f.dataset.skin=g(e.skin,"default"),f.dataset.bind=g(e.bind,""),Nn(f,o);const c=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(l),r.max=String(s),r.step=String(e.step??.01),r.setAttribute("aria-label",g(e.bind,"slider"));for(const u of a){const h=w(u.props),y=m("span",`cultui-slider-part ${g(h.name,"part")}`);Dn(y,h),c.append(y)}return a.some(u=>w(u.props).name==="track")||c.append(m("span","cultui-slider-part track")),a.some(u=>w(u.props).name==="fill")||c.append(m("span","cultui-slider-part fill")),a.some(u=>w(u.props).name==="thumb")||c.append(m("span","cultui-slider-part thumb")),f.append(c,r),(u=>{const h=Number(u??l),y=Math.max(l,Math.min(s,Number.isFinite(h)?h:l)),b=s===l?0:(y-l)/(s-l)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(e.value??l),r.addEventListener("input",()=>{const u=le(g(e.command,"control.slider.input"),{...e,action:{...w(e.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:e})}),f}function Ln(e,t){const n=typeof e.skin=="string"?e.skin:"",o=[...n?at.controlSkins[n]?.children||[]:[],...t];return o.length?o:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function qe(e){if(Array.isArray(e)){const t={},n={};for(const i of e)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:t[i.name]=i.value);return{tokens:t,assets:n,controlSkins:{}}}return{tokens:w(e?.tokens),assets:w(e?.assets),controlSkins:w(e?.controlSkins)}}function ae(e){if(!e)return"";const t=z.assetUrlResolver;return t?t(e,se):/^(https?:|data:|blob:)/i.test(e)?e:z.assetBaseUrl&&e.startsWith("/")?`${z.assetBaseUrl.replace(/\/+$/,"")}${e}`:e}function $n(e){const t=typeof e=="string"?e.trim():"";if(he?.dataset.href===t||(he?.remove(),he=void 0,!t))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=t,i.dataset.href=t,document.head.append(i),he=i}function Mn(e,t,n){const i=[];return(e==="text.title"||t.role==="title")&&i.push("cultui-title","eve-text-title"),e==="text.subtitle"&&i.push("eve-text-subtitle"),e==="label"&&i.push("cultui-label"),t.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function Nn(e,t){t.height!==void 0&&(e.style.minHeight=R(t.height)),t.width!==void 0&&(e.style.width=R(t.width)),typeof t.overflow=="string"&&(e.style.overflow=t.overflow)}function Dn(e,t){const n=Array.isArray(t.size)?t.size:[t.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(e.style.width=R(n[0])),n[1]!==void 0&&(e.style.height=R(n[1])),t.radius!==void 0&&(e.style.borderRadius=R(t.radius)),t.fill!==void 0&&(e.style.background=xe(String(t.fill))),t.bleed!==void 0&&e.style.setProperty("--part-bleed",R(t.bleed)),(Array.isArray(t.anchor)?t.anchor:[t.anchor]).includes("value")&&(e.dataset.anchorValue="true")}function ye(e,t){t.gap!==void 0&&(e.style.gap=R(t.gap)),t.padding!==void 0&&(e.style.padding=R(t.padding)),t.size!==void 0&&(e.style.flex=Bn(t.size)),t.min!==void 0&&(e.style.minWidth=R(t.min)),t.max!==void 0&&(e.style.maxWidth=R(t.max)),t.align!==void 0&&(e.style.alignItems=t.align==="end"?"flex-end":String(t.align)),(t.clip==="true"||t.clip===!0)&&(e.style.overflow="hidden"),t.scroll==="y"&&(e.style.overflowY="auto"),t.scroll==="x"&&(e.style.overflowX="auto")}function Bn(e){return typeof e=="string"&&e.endsWith("fr")?`${Number(e.slice(0,-2))||1} 1 0`:e==="auto"||e==="content"?"0 0 auto":`0 0 ${R(e)}`}function R(e){return Array.isArray(e)?e.map(R).join(" "):typeof e=="number"?`${e}px`:typeof e=="string"&&/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:String(e??"")}function xe(e){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[e]||e}function be(e){return e.includes("Zen Kaku Gothic New")||e.includes("M PLUS 1")?e:e.includes("Montserrat")?`${e}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:e.includes("Ubuntu")?`${e}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${e}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function S(e,t){t.id&&(e.id=t.id),t.id&&(e.dataset.eveNodeId=t.id),t.kind&&(e.dataset.eveKind=t.kind)}function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qn(e){return Array.isArray(e)?e:[]}function Un(e){return qn(e).map((t,n)=>lt({kind:"list.item",props:w(t)}))}function g(e,t){return e==null?t:String(e)}function p(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function Ue(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?["1","true","yes","on"].includes(e.trim().toLowerCase()):!1}function q(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}function Wn(e){const t=e.toLowerCase();return t.includes("sensor")?"S":t.includes("thermal")?"T":t.includes("fuel")?"F":t.includes("cargo")?"C":t.includes("weapon")?"W":e.trim().slice(0,1).toUpperCase()||"?"}function On(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length&&t.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function et(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function m(e,t="",n=""){const i=document.createElement(e);return t&&(i.className=t),n&&(i.textContent=n),i}const _e=document.querySelector("#surface"),F=document.querySelector("#status"),U=document.querySelector("#receipt"),mt=document.querySelector("#compiler"),We=document.querySelector("#composer"),Ee=document.querySelector("#destination-form"),pt=document.querySelector("#compiler-results"),ht=document.querySelector("#campaign-lab"),zn=document.querySelector("#campaign-list"),Gn=document.querySelector("#operator-lab");Gn.hidden=!["127.0.0.1","localhost","::1"].includes(window.location.hostname);let de=0,Ce="",Ne=0,gt=0,ke=!1;const Re=new Set;class yt extends Error{}async function ue(e){if(ke)throw new Error("A Ghostlight request is already in progress.");ke=!0,document.body.setAttribute("aria-busy","true");for(const t of document.querySelectorAll("button, input, textarea, select"))t.disabled||(t.disabled=!0,Re.add(t));try{return await e()}finally{for(const t of Re)t.disabled=!1;Re.clear(),document.body.removeAttribute("aria-busy"),ke=!1}}function v(e,t,n){const i=document.createElement(e);return t!==void 0&&(i.textContent=t),n&&(i.className=n),i}function B(e,t){const n=[v("h3",e)];for(const i of t.filter(Boolean))n.push(v("p",i));U.replaceChildren(...n),U.hidden=!1}async function ie(e){return e.status===204?null:(e.headers.get("content-type")??"").includes("json")?e.json():e.text()}function re(e,t){return typeof e=="string"&&e.trim()?e.trim():e&&typeof e.error=="string"&&e.error.trim()?e.error.trim():t}function bt(e){const t=e instanceof Error&&e.message.trim()?e.message.trim():"The Ghostlight connection failed before a response arrived.";if(F.textContent=t,e instanceof yt){B("Request refused",[t,"The server returned an error response. Refresh campaign state before retrying."]);return}B("Request did not complete",[t,"The server remains authoritative. Refresh the campaign before retrying; the lost response may have followed a commit."])}window.addEventListener("unhandledrejection",e=>{e.preventDefault(),bt(e.reason)});function Kn(e){if(e?.kind==="assessed"){const t=e.assessment,n=[v("h3",t.admissible?"Action assessment":"That attempt is not possible")];if(t.admissible){n.push(v("p",`DC ${t.dc} · modifier ${t.modifier_total>=0?"+":""}${t.modifier_total}`));const i=v("ul");for(const o of t.modifiers??[])i.append(v("li",`${o.label}: ${o.value>=0?"+":""}${o.value}`));n.push(i),n.push(v("p",`Strong/success: ${t.success_stake}`)),n.push(v("p",`Mixed: ${t.mixed_stake}`)),n.push(v("p",`Failure: ${t.failure_stake}`)),n.push(v("p",`Effect ceiling: ${t.effect_ceiling}`,"quiet"))}else{n.push(v("p",t.missing_permission??"The attempt has no admissible path from current state."));for(const i of t.bargains??[])n.push(v("p",`Possible bargain: ${i}`))}U.replaceChildren(...n),U.hidden=!1;return}if(e?.kind==="committed"){const t=e.receipt?.roll;if(t){const n=String(t.outcome).replaceAll("_"," ");B(n.charAt(0).toUpperCase()+n.slice(1),[`d20 ${t.d20} ${t.modifier_total>=0?"+":"−"} ${Math.abs(t.modifier_total)} = ${t.total} against DC ${t.dc}`])}else B("World advanced",[`Revision ${e.revision}`]);return}if(e?.kind==="resolution_updated"){B("World resolution updated",[`Resolution epoch ${e.receipt?.resolution_epoch??"advanced"}`]);return}B("Command result",[e?.error??"The world returned no player-facing detail."])}function Xn(){const e="This laboratory requires an unused invite link.";F.textContent=e,mt.hidden=!0,We.hidden=!0,Ee.hidden=!0,ht.hidden=!0,U.hidden=!0,_e.hidden=!1;const t=v("article",void 0,"card");t.append(v("h2","Private campaign laboratory"),v("p",e),v("p","Open a single-use tester invitation on this device. The resulting session stays separate from every other player's campaigns.","quiet")),_e.replaceChildren(t)}async function ce(){const e=await fetch("/api/surface");if(e.status===401){Xn();return}const t=await ie(e);if(!e.ok){F.textContent=re(t,"The campaign surface is temporarily unavailable.");return}const n=t.surface_id==="ghostlight.compiler";if(mt.hidden=!n,We.hidden=n,Ee.hidden=n,_e.hidden=n,ht.hidden=n,n){F.textContent="No campaign exists. Retrieve the Vault and approve a world seed.";return}if(de=Number(t.world_revision??t.version??0),Ce=String(t.player_actor_id??""),!Ce)throw new Error("Campaign surface omitted its canonical player actor ID.");const i=String(t.player_location_id??"");if(!i)throw new Error("Campaign surface omitted its canonical player location ID.");document.querySelector("#destination-origin").value=i,Ne=Number(t.resolution?.policy?.resolution_epoch??0),gt=Number(t.resolution?.policy?.provider_configuration_epoch??0);const o=Number(t.resolution?.policy?.active_cell_budget??8),a=document.querySelector("#active-cell-budget");a.value=String(o),document.querySelector("#active-cell-budget-value").value=String(o),document.querySelector("#resolution-status").textContent=`${t.resolution?.effective_budget??o} effective cells · ${t.resolution?.mandatory_overage??0} temporary overage · epoch ${Ne}`;const l=Number(t.resolution?.policy?.provider_parallelism??8);document.querySelector("#provider-parallelism").value=String(l),document.querySelector("#provider-parallelism-value").value=String(l);const s=document.querySelector("#fission-parent");s.replaceChildren(...(t.resolution?.fission_targets??[]).map(r=>{const d=v("option",`${r.name} · ${r.id}`);return d.value=r.id,d})),document.querySelector("#fission-form").hidden=s.options.length===0,st(t,_e,{body:document.body,clientId:"ghostlight.browser",statusElement:F});const f=await fetch("/api/campaigns"),c=await ie(f);if(!f.ok){F.textContent=re(c,"The campaign list is temporarily unavailable.");return}zn.replaceChildren(...c.campaigns.map(r=>{const d=v("button",`${r.selected?"●":"○"} ${r.name} · revision ${r.revision}`);return d.type="button",d.disabled=!!r.selected,r.selected||d.addEventListener("click",async()=>{await oe(`/api/campaigns/select/${r.id}`,{})}),d}))}async function vt(e,t){F.textContent="Retrieving evidence and compiling…";const n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=await ie(n);if(!n.ok)throw F.textContent=re(i,"Compilation failed"),new yt(F.textContent);return i}async function ne(e,t){return ue(()=>vt(e,t))}async function oe(e,t){return ue(async()=>{const n=await vt(e,t);return await ce(),n})}function tt(e,t,n){const i=v("div",void 0,"cards");e.forEach((o,a)=>{const l=v("article",void 0,"card");l.append(v("h3",o.title??o.name),v("p",o.player_hook??o.premise)),o.era&&l.append(v("p",`${o.era} · ${o.place} · ${o.pressure}`));const s=v("button",t);s.type="button",s.addEventListener("click",()=>n(e[a])),l.append(s),i.append(l)}),pt.replaceChildren(i)}function W(e,t,n){const i=v("details");i.append(v("summary",t));const o=v("ul");for(const a of n)o.append(v("li",a));n.length===0&&o.append(v("li","None declared.")),i.append(o),e.append(i)}document.querySelector("#suggest-form").addEventListener("submit",async e=>{e.preventDefault();const t=await ne("/api/compiler/openings",{setting:document.querySelector("#setting").value,constraints:[]});tt(t.openings,"Choose opening",async n=>{const i=await ne("/api/compiler/roles",{opening_id:n.id});tt(i.roles,"Choose role",async o=>xt(await ne("/api/compiler/selected",{campaign_name:n.title,opening_id:n.id,role_id:o.id})))})});document.querySelector("#custom-form").addEventListener("submit",async e=>{e.preventDefault(),await xt(await ne("/api/compiler/custom",Object.fromEntries(new FormData(e.currentTarget))))});async function xt(e){const t=e.preview,n=Array.isArray(t.evidence_coverage)?t.evidence_coverage:[],i=n.reduce((s,f)=>{const c=String(f?.lane??"excluded");return s[c]=(s[c]??0)+1,s},{}),o=v("article",void 0,"card");o.append(v("h3",t.title),v("p",t.opening??""),v("p",`${t.locations?.length??0} locations · ${(t.cast?.length??0)+1} actors · ${t.institutions?.length??0} institutions`),v("p",t.gaps.length?`Material gaps: ${t.gaps.join("; ")}`:"No declared material gaps.","warning"),v("p",`Branch assumptions: ${t.branch_assumptions.join("; ")||"none"}`),v("p",n.length?`Evidence use: ${i.direct_seed??0} direct · ${i.setting_background??0} background · ${i.excluded??0} excluded`:"Evidence use: no retrieved sources were admitted to this seed.","quiet"));const a=t.player_role??{};W(o,`Player role · ${a.name??"unnamed"}`,[`Starts at ${a.location_id??"an unspecified location"}`,...(a.capabilities??[]).map(s=>`Capability: ${s}`),...(a.equipment??[]).map(s=>`Equipment: ${s}`),...(a.conditions??[]).map(s=>`Condition: ${s}`),...(a.obligations??[]).map(s=>`Obligation: ${s}`)]),W(o,`Initial topology · ${t.locations?.length??0} locations`,(t.locations??[]).map(s=>{const f=Object.keys(s.routes??{});return`${s.name} · ${s.id}${s.container_id?` · inside ${s.container_id}`:""}${f.length?` · routes to ${f.join(", ")}`:" · no compiled route"}`})),W(o,`Present cast · ${t.cast?.length??0}`,(t.cast??[]).map(s=>`${s.name} · ${s.id} · at ${s.location_id}`)),W(o,`Institutions · ${t.institutions?.length??0}`,(t.institutions??[]).map(s=>`${s.name} · ${s.id}`)),W(o,`Populations · ${t.populations?.length??0}`,(t.populations??[]).map(s=>`${s.name} · ${s.id} · at ${s.home_location_id}`)),W(o,`World clocks · ${t.clocks?.length??0}`,(t.clocks??[]).map(s=>`${s.name} · ${s.progress}/${s.threshold} · ${s.trigger}`)),W(o,`Evidence coverage · ${n.length}`,n.map(s=>`${s.source_id} · ${String(s.lane).replaceAll("_"," ")} · ${s.rationale}`));const l=v("button","Approve and enter");l.type="button",l.addEventListener("click",async()=>{await oe(`/api/compiler/approve/${e.preview_id}`,{})}),o.append(l),pt.replaceChildren(o),F.textContent="Preview compiled. Nothing has entered world state yet."}async function fe(e){return ue(async()=>{F.textContent="The world is considering the command…";const t=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await ie(t);if(!t.ok){const i=re(n,"The command was refused.");return B("Command refused",[i]),F.textContent=i,await ce(),n}return Kn(n),await ce(),n})}function wt(e){if(e?.kind!=="assessed")return;const t=document.createElement("button");t.type="button",t.textContent=e.assessment.admissible?"Confirm server roll":"Revise attempt",t.addEventListener("click",async()=>{if(!e.assessment.admissible){document.querySelector("#attempt").focus();return}const n=await fe({type:"attempt",assessment_digest:e.assessment.digest});wt(n)}),U.append(t)}We.addEventListener("submit",async e=>{e.preventDefault();const t=document.querySelector("#attempt").value.trim(),n=document.querySelector("#intended-effect"),i=n.value.trim();if(t){if(!i){F.textContent="Describe the uncertain outcome you want assessed, or use Speak for words that need no roll.",n.focus();return}wt(await fe({type:"assess",expected_revision:de,intent:{actor_id:Ce,description:t,intended_effect:i}}))}});document.querySelector("#speak").addEventListener("click",async()=>{const e=document.querySelector("#attempt"),t=e.value.trim();if(!t){F.textContent="Write what your character says first.",e.focus();return}(await fe({type:"speak",expected_revision:de,actor_id:Ce,text:t,intended_effect:null}))?.kind==="committed"&&(e.value="")});document.querySelector("#wait").addEventListener("click",()=>{fe({type:"wait",expected_revision:de,minutes:60})});document.querySelector("#active-cell-budget").addEventListener("input",e=>{document.querySelector("#active-cell-budget-value").value=e.currentTarget.value});document.querySelector("#resolution-form").addEventListener("submit",async e=>{e.preventDefault(),await fe({type:"set_resolution_budget",expected_revision:de,expected_resolution_epoch:Ne,active_cell_budget:Number(document.querySelector("#active-cell-budget").value)})});document.querySelector("#provider-parallelism").addEventListener("input",e=>{document.querySelector("#provider-parallelism-value").value=e.currentTarget.value});document.querySelector("#provider-parallelism-form").addEventListener("submit",async e=>{e.preventDefault(),await ue(async()=>{F.textContent="Applying the provider concurrency limit…";const t=await fetch("/api/operator/provider-parallelism",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({expected_provider_configuration_epoch:gt,provider_parallelism:Number(document.querySelector("#provider-parallelism").value)})}),n=await ie(t),i=re(n,"The operator limit was refused.");B(t.ok?"Provider concurrency updated":"Provider concurrency refused",[t.ok?`Parallel requests: ${n?.receipt?.provider_parallelism??n?.provider_parallelism??"updated"}`:i]),t.ok||(F.textContent=i),await ce()})});Ee.addEventListener("submit",async e=>{e.preventDefault();const t=await ne("/api/compiler/destination",Object.fromEntries(new FormData(Ee))),n=t.preview;B("Destination preview",(n.gaps??[]).map(o=>`Material gap: ${o}`)),W(U,`Compiled topology · ${n.locations?.length??0} locations`,(n.locations??[]).map(o=>{const a=Object.keys(o.routes??{}),l=[...o.persistent_features??[]];return`${o.name} · ${o.id}${o.container_id?` · inside ${o.container_id}`:""}${a.length?` · routes to ${a.join(", ")}`:" · no compiled route"}${l.length?` · ${l.join(", ")}`:""}`})),F.textContent="Destination preview compiled; topology is unchanged until approval.";const i=v("button","Approve destination");i.type="button",i.addEventListener("click",async()=>{await oe(`/api/compiler/destination/approve/${t.preview_id}`,{}),i.remove()}),U.append(i)});document.querySelector("#fission-form").addEventListener("submit",async e=>{e.preventDefault();const t=new FormData(e.currentTarget),n=String(t.get("requested_partition_values")??"").split(",").map(a=>a.trim()).filter(Boolean);if(n.length>16||n.some(a=>[...a].length>160)){F.textContent="Use at most 16 named cuts, with at most 160 characters in each cut.",document.querySelector("#fission-values").focus();return}const i=await ne("/api/compiler/gestalt/fission",{parent_gestalt_id:t.get("parent_gestalt_id"),partition_axis:t.get("partition_axis"),requested_partition_values:n,reason:t.get("reason")});B("Population fission preview",[...(i.preview?.gaps??[]).map(a=>`Material gap: ${a}`)]),W(U,`Canonical child leaves · ${i.preview?.children?.length??0}`,(i.preview?.children??[]).map(a=>`${a.name} · ${a.id} · ${a.partition_value??"other/unknown"} · at ${a.home_location_id}`)),F.textContent="Fission preview compiled. Canonical leaves are unchanged until approval.";const o=document.createElement("button");o.type="button",o.textContent="Approve population fission",o.addEventListener("click",async()=>{await oe(`/api/compiler/gestalt/fission/approve/${i.preview_id}`,{}),o.remove()}),U.append(o)});document.querySelector("#fork-form").addEventListener("submit",async e=>{e.preventDefault(),await oe("/api/campaigns/fork",Object.fromEntries(new FormData(e.currentTarget)))});document.querySelector("#reset-form").addEventListener("submit",async e=>{e.preventDefault(),await oe("/api/campaigns/reset",Object.fromEntries(new FormData(e.currentTarget)))});document.querySelector("#load-operator").addEventListener("click",async()=>{await ue(async()=>{const e=await fetch("/api/operator"),t=await ie(e);if(!e.ok){const n=re(t,"The operator surface is unavailable.");B("Operator inspector refused",[n]),F.textContent=n;return}st(t,document.querySelector("#operator-output"),{body:document.body,clientId:"ghostlight.operator",statusElement:F})})});ce().catch(bt); diff --git a/web/dist/index.html b/web/dist/index.html index add47b8..107cbc4 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -1,5 +1,5 @@ -GhostlightDungeon +GhostlightDungeon

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

diff --git a/web/src/main.ts b/web/src/main.ts index 137b5b5..8dd4d17 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -145,7 +145,7 @@ function showAuthenticationGate() { gate.append( node("h2", "Private campaign laboratory"), node("p", message), - node("p", "Open one of the two single-use tester invitations on this device. The resulting session stays separate from the other player's campaigns.", "quiet"), + node("p", "Open a single-use tester invitation on this device. The resulting session stays separate from every other player's campaigns.", "quiet"), ); host.replaceChildren(gate); }