Files
roast-room/app/public/app.js
T
Nate HerkandClaude Opus 5.5 8a6b473934 Founder Council: seven AI advisors debate your decision in Claude Code
- /founder-council skill: three-round protocol, scoring, and verdict
- Seven seat agents with brains built from each expert's public work
- The room: a zero-dependency local app that plays councils live from sessions/
- Three example councils to watch before running your own

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:38:54 -05:00

676 lines
34 KiB
JavaScript

const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const SAMPLES = [
["Raise my prices?", "I run a coaching business doing $30k a month with 15 active clients at $2,000 each. I want to raise the price to $3,500. Options: raise for everyone now, raise for new clients only, or keep $2,000. Close rate is about 50% on sales calls. I'm leaning toward raising for everyone because I'm underpaid."],
["First salesperson?", "I'm a solo founder of a B2B SaaS at $25k MRR growing 5% a month. I do every sales call myself (about 20 hours a week) and I'm burning out. Should I hire a full-time account executive at $120k base, hire a part-time commission-only closer, or keep selling myself for six more months? I have $150k in the bank."],
["Second product?", "My agency makes $80k a month building AI automations for dentists. A few clients asked for an AI receptionist product. Should I build the receptionist as a separate SaaS, offer it as an add-on to existing clients only, or stay focused on the agency? Team of 6, about $200k cash."],
["Quit my job?", "I make $180k a year at a tech company. My side business (a paid newsletter) makes $6k a month and grew 8% a month this year. I have 9 months of expenses saved. Should I quit now, quit in 6 months, or keep both and hire a writer?"],
];
const SHAPES = ["base", "open", "mid", "blink"];
const portrait = (key, shape = "base") => `/portraits/${key}-${shape}.webp`;
const ROUND_NAME = ["", "Opening", "Debate", "Vote"];
const state = {
seats: [], byKey: {}, session: null, options: [], weights: {}, active: [], round: 0,
cards: { 1: {}, 2: {}, 3: {} }, replaying: false, verdict: null, links: [], geo: {},
};
// ------------------------------------------------------------- boot
async function boot() {
const r = await fetch("/api/seats").then((x) => x.json());
state.seats = r.seats;
state.byKey = Object.fromEntries(r.seats.map((s) => [s.key, s]));
state.runner = r.runner;
if (r.runner === "api" && !r.hasKey) toast("No ANTHROPIC_API_KEY found in .env. Add it and restart the server.");
renderSeats();
renderSamples();
bindUI();
new ResizeObserver(() => { layoutStage(); drawLinks(); }).observe($("#stage"));
startBlinking();
reset();
typeIn($("#composer h2"));
typeIn($("#waiting h2"));
const ss = await fetch("/api/sessions").then((x) => x.json());
if (ss.running) attach(ss.running);
else if (ss.live) attach(ss.live);
refreshUsage();
setInterval(watchForLive, 2500);
}
// a council started in Claude Code shows up here on its own
const seenLive = new Set();
async function watchForLive() {
const ss = await fetch("/api/sessions").then((x) => x.json()).catch(() => null);
const id = ss?.live || ss?.running;
if (!id || seenLive.has(id) || id === state.session) return;
seenLive.add(id);
attach(id);
}
// AIS arrival: a heading types in a character at a time, blur to sharp
function typeIn(el) {
if (!el) return;
const text = el.textContent;
el.classList.add("typein");
el.innerHTML = [...text].map((c, i) => `<span class="ch" style="animation-delay:${i * 22}ms">${c === " " ? " " : esc(c)}</span>`).join("");
el.setAttribute("aria-label", text);
}
function renderSamples() {
$("#samples").innerHTML = SAMPLES.map(([t], i) => `<button type="button" data-i="${i}">${esc(t)}</button>`).join("");
$("#samples").addEventListener("click", (e) => {
const b = e.target.closest("button"); if (!b) return;
$("#prompt").value = SAMPLES[b.dataset.i][1];
$("#prompt").focus();
});
}
function renderSeats() {
$("#seats").innerHTML = state.seats.map((s) => `
<div class="seat" id="seat-${s.key}" data-seat="${s.key}" tabindex="0" role="button" aria-label="${esc(s.name)}, ${esc(s.pillar)}. Open card.">
<div class="think" aria-hidden="true"><i></i><i></i><i></i></div>
<div class="bust" data-shape="base">${SHAPES.map((sh) => `<img class="${sh}" src="${portrait(s.key, sh)}" alt="" draggable="false">`).join("")}</div>
</div>`).join("");
$("#plates").innerHTML = state.seats.map((s) => `
<div class="nameplate" id="plate-${s.key}" data-seat="${s.key}">
<b>${esc(s.short === "Gary V" ? "Gary V" : s.name)}</b>
<small>${esc(s.pillar)}</small>
<div class="meta"><span class="pips" title="Weight on this decision"></span><span class="chip" hidden></span><span class="score" hidden></span></div>
</div>`).join("");
layoutStage();
}
// The table is an ellipse seen from the front. Seats sit along its far edge: the
// middle seat is farthest (higher, smaller), the end seats nearest (lower, bigger).
function layoutStage() {
const stage = $("#stage");
const W = stage.clientWidth;
const narrow = matchMedia("(max-width: 820px)").matches;
const H = narrow ? Math.round(W * 0.62) : stage.clientHeight;
const cx = W / 2, cy = H * (narrow ? 0.98 : 0.9), rx = W * 0.48, ry = H * (narrow ? 0.46 : 0.42);
const t = $("#table");
Object.assign(t.style, { left: `${cx - rx}px`, top: `${cy - ry}px`, width: `${rx * 2}px`, height: `${ry * 2}px` });
const edge = (x) => cy - ry * Math.sqrt(Math.max(0, 1 - ((x - cx) / rx) ** 2));
const xs = [0.085, 0.222, 0.361, 0.5, 0.639, 0.778, 0.915];
state.seats.forEach((s, i) => {
const x = W * xs[i];
const d = ((x - cx) / rx) ** 2;
const size = H * (narrow ? 0.5 + 0.08 * d : 0.37 + 0.07 * d);
const bottom = edge(x) + size * 0.2;
const el = $(`#seat-${s.key}`);
Object.assign(el.style, { left: `${x - size / 2}px`, top: `${bottom - size}px`, width: `${size}px`, height: `${size}px`, zIndex: 10 + Math.round(d * 10) });
const pl = $(`#plate-${s.key}`);
pl.style.left = `${x}px`;
pl.style.top = `${edge(x) + H * 0.01}px`; // straddles the table edge, over the chest
state.geo[s.key] = { x, head: bottom - size * 0.72, top: bottom - size * 0.9, size };
});
const c = $("#center");
if (narrow) {
stage.style.paddingTop = `${H}px`; // the scene sits on top; captions flow below it
} else {
stage.style.paddingTop = "";
// the captions start below the lowest nameplate they could collide with
const inner = [1, 2, 3, 4, 5].map((i) => $(`#plate-${state.seats[i].key}`));
const top = Math.max(...inner.map((p) => p.offsetTop + p.offsetHeight / 2)) + H * 0.035;
Object.assign(c.style, { left: `${W * 0.2}px`, width: `${W * 0.6}px`, top: `${top}px`, height: `${H - top - H * 0.09}px` });
}
const sp = state.speaking ? state.geo[state.speaking] : null;
if (sp) moveSpot(state.speaking);
}
function moveSpot(key) {
const g = state.geo[key]; const spot = $("#spot");
if (!g) { spot.classList.remove("on"); return; }
spot.style.left = `${g.x}px`;
spot.style.top = `${g.head}px`;
spot.style.width = spot.style.height = `${g.size * 1.9}px`;
spot.classList.add("on");
}
function bindUI() {
$("#composer").addEventListener("submit", async (e) => {
e.preventDefault();
const prompt = $("#prompt").value.trim();
if (prompt.length < 10) return toast("Give the council a real decision, at least a sentence.");
const mode = $('input[name="mode"]:checked').value;
$("#convene").disabled = true;
const r = await fetch("/api/council", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt, mode }) });
const j = await r.json();
$("#convene").disabled = false;
if (!r.ok) return toast(j.error || "Could not start the council.");
attach(j.id);
});
const openFrom = (e) => { const b = e.target.closest("[data-seat]"); if (b) openCard(b.dataset.seat); };
$("#seats").addEventListener("click", openFrom);
$("#plates").addEventListener("click", openFrom);
$("#seats").addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openFrom(e); } });
$("#feed").addEventListener("click", (e) => { const c = e.target.closest(".feed-card"); if (c) openCard(c.dataset.seat, Number(c.dataset.round)); });
$("#waitHistory").addEventListener("click", openHistory);
$("#historyBtn").addEventListener("click", openHistory);
$("#newBtn").addEventListener("click", reset);
$("#verdictSheet").addEventListener("click", (e) => { if (e.target.id === "verdictSheet" || e.target.closest("[data-close]")) $("#verdictSheet").hidden = true; });
document.addEventListener("keydown", (e) => { if (e.key === "Escape") $("#verdictSheet").hidden = true; });
$$(".speed button").forEach((b) => b.addEventListener("click", () => {
player.speed = Number(b.dataset.speed);
$$(".speed button").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
}));
$("#skipBtn").addEventListener("click", () => player.skip());
}
// ------------------------------------------------------------- the player
// Every event goes through one ordered queue. Seats speak one at a time, at a
// readable pace, even though the API answers them in parallel. Skip ahead drains
// whatever is queued instantly; new events after that animate again.
const player = {
q: [], busy: false, epoch: 0, speed: 1, fast: false, timers: new Set(),
push(ev) { this.q.push(ev); this.info(); this.pump(); },
async pump() {
if (this.busy) return;
this.busy = true;
const my = this.epoch;
while (this.q.length && my === this.epoch) {
const ev = this.q.shift();
this.info();
try { await handle(ev); } catch (e) { console.error(e); }
}
if (my === this.epoch) { this.busy = false; this.fast = false; this.info(); }
},
sleep(ms) {
if (this.fast || ms <= 0) return Promise.resolve();
return new Promise((res) => { const t = setTimeout(() => { this.timers.delete(o); res(); }, ms / this.speed); const o = { t, res }; this.timers.add(o); });
},
flushTimers() { for (const o of this.timers) { clearTimeout(o.t); o.res(); } this.timers.clear(); },
skip() { this.fast = true; this.flushTimers(); },
reset() { this.epoch++; this.q.length = 0; this.fast = true; this.flushTimers(); this.busy = false; this.fast = false; this.info(); },
info() {
const waiting = this.q.filter((e) => e.type === "seat_done").length;
$("#queueInfo").textContent = waiting ? `${waiting} lines up next` : "";
},
};
// ------------------------------------------------------------- session wiring
function reset() {
state.es?.close();
player.reset();
Object.assign(state, { session: null, options: [], weights: {}, active: [], round: 0, cards: { 1: {}, 2: {}, 3: {} }, replaying: false, verdict: null, links: [], speaking: null });
$("#stage").classList.remove("live");
$("#topic").hidden = true;
$("#composer").hidden = state.runner !== "api";
$("#waiting").hidden = state.runner === "api";
$("#caption").hidden = true;
$("#cruxes").hidden = true;
$("#plate").hidden = true;
$("#playbar").hidden = true;
$("#newBtn").hidden = true;
$("#verdictSheet").hidden = true;
$("#feed").innerHTML = '<div class="empty">One line per seat as the council talks. Click a seat to read its full card.</div>';
$$(".vote").forEach((b) => b.remove());
$$(".seat").forEach((el) => { el.classList.remove("absent", "speaking", "thinking", "addressed"); $(".bust", el).dataset.shape = "base"; });
$$(".nameplate").forEach((el) => { el.classList.remove("absent", "speaking"); $(".chip", el).hidden = true; $(".score", el).hidden = true; $(".pips", el).innerHTML = ""; });
$("#spot").classList.remove("on");
$$(".stepper li").forEach((li) => li.classList.remove("active", "done"));
drawLinks();
}
function begin(id) {
reset();
state.session = id;
$("#composer").hidden = true;
$("#waiting").hidden = true;
$("#newBtn").hidden = false;
$("#playbar").hidden = false;
$("#stage").classList.add("live");
chairSays("The council is taking their seats", { dots: true });
}
function attach(id) {
begin(id);
const es = new EventSource(`/api/stream/${id}`);
state.es = es;
es.onmessage = (m) => {
const ev = JSON.parse(m.data);
if (ev.type === "end") { es.close(); refreshUsage(); return; }
if (ev.type === "delta") return; // seats speak from their finished cards
if (ev.type === "usage") return refreshUsage();
if (ev.type === "seat_error") return toast(`${state.byKey[ev.seat].short} hit an error: ${ev.error}`);
player.push(ev);
};
es.onerror = () => { /* the browser retries; the server replays from the start */ };
}
// ------------------------------------------------------------- event handling
const STEP_OF = { setup: "setup", round1: "round1", cruxes: "cruxes", round2: "round2", draft: "round3", round3: "round3", skip3: "round3", verdict: "verdict" };
const ORDER = ["setup", "round1", "cruxes", "round2", "round3", "verdict"];
function setStep(step) {
const idx = ORDER.indexOf(step);
$$(".stepper li").forEach((li) => {
const i = ORDER.indexOf(li.dataset.step);
li.classList.toggle("done", i < idx);
li.classList.toggle("active", i === idx);
});
}
async function handle(ev) {
switch (ev.type) {
case "phase": {
setStep(STEP_OF[ev.phase] || "setup");
feedPhase(ev.label);
const thinking = ["setup", "cruxes", "draft", "verdict"].includes(ev.phase);
if (thinking || ev.phase === "skip3") {
chairSays(ev.label.replace(/^The Chair is /, "").replace(/^./, (c) => c.toUpperCase()), { dots: thinking });
await player.sleep(1400);
}
break;
}
case "setup": onSetup(ev); await player.sleep(1800); break;
case "round_start": onRoundStart(ev.round); break;
case "seat_start": $(`#seat-${ev.seat}`)?.classList.add("thinking"); break;
case "seat_done": await onSeatDone(ev); break;
case "round_done": updateOptions(ev.scores); break;
case "cruxes": await onCruxes(ev); break;
case "draft": await onDraft(ev.draft); break;
case "verdict": onVerdict(ev); break;
case "error": toast(`The council stopped: ${ev.error}`); chairSays(`The council stopped: ${ev.error}`); break;
}
}
function onSetup(ev) {
state.options = ev.options;
state.weights = ev.weights;
state.active = ev.seats;
$("#topic").hidden = false;
$("#topicTitle").textContent = ev.title;
typeIn($("#topicTitle"));
$("#options").innerHTML = ev.options.map((o) => `
<div class="opt" data-opt="${o.id}"><span class="id">${o.id}</span><span class="label">${esc(o.label)}</span><span class="val">-</span><span class="bar"><i></i></span></div>`).join("");
for (const s of state.seats) {
const absent = !ev.seats.includes(s.key);
$(`#seat-${s.key}`).classList.toggle("absent", absent);
const pl = $(`#plate-${s.key}`);
pl.classList.toggle("absent", absent);
const w = ev.weights[s.key]?.weight || 1;
pl.title = `Weight ${w} of 3: ${ev.weights[s.key]?.reason || ""}`;
}
chairSays(ev.title, { tag: ev.mode === "quick" ? "Quick council" : "Full council" });
}
function updateOptions(scores) {
const best = Object.entries(scores).sort((a, b) => (b[1].score ?? 0) - (a[1].score ?? 0))[0]?.[0];
for (const [id, v] of Object.entries(scores)) {
const el = $(`.opt[data-opt="${id}"]`); if (!el) continue;
$(".val", el).textContent = v.score ?? "-";
$(".bar i", el).style.width = `${(v.score || 0) * 10}%`;
el.classList.toggle("lead", id === best);
el.title = v.math;
}
}
function onRoundStart(round) {
state.round = round;
state.links = [];
drawLinks();
$("#cruxes").hidden = true;
chairSays(`${["", "Round 1: opening positions", "Round 2: the debate", "Round 3: the vote"][round]}`, { dots: true, tag: "The floor is open" });
}
// ------------------------------------------------------------- talking
const clean = (t) => String(t || "").replace(/\s*\((?:S\d+|source[^)]*)[^)]*\)/gi, "").replace(/\*\*/g, "").replace(/\s+/g, " ").trim();
function firstSentences(t, max) {
const parts = t.match(/[^.!?]+[.!?]+["”)]?\s*|[^.!?]+$/g) || [t];
let out = "";
for (const p of parts) { if (out && (out + p).length > max) break; out += p; }
return shorten(out.trim(), max + 40);
}
/** The line a seat says out loud: the headline of its card, not the whole card. */
function lineFor(round, p, max = 170) {
if (round === 1) return firstSentences(clean(p.call || p.stance), max);
if (round === 2) {
let t = clean(p.disagreeLine || p.stance);
// "Graham. His argument..." reads as talking to him: "Graham, his argument..."
t = t.replace(/^([A-Za-z][\w.' ]{0,24})[.:,]\s+(\S+)/, (m, name, next) => !seatKey(name) ? m : `${state.byKey[seatKey(name)].short}, ${/^I('|$)/.test(next) ? next : next[0].toLowerCase() + next.slice(1)}`);
return firstSentences(t, max);
}
return firstSentences(clean(p.oneLine || p.amendment), max);
}
function shapesFor(word) {
const out = [];
for (const ch of word.toLowerCase()) {
const s = "aei".includes(ch) ? "open" : "ouwy".includes(ch) ? "mid" : "mbpf".includes(ch) ? "base" : null;
if (s && s !== out[out.length - 1]) out.push(s);
}
return out.length ? out : ["mid"];
}
function setShape(key, shape) { const b = $(`#seat-${key} .bust`); if (b) b.dataset.shape = shape; }
function setSpeaker(key, target) {
state.speaking = key;
$$(".seat").forEach((el) => { el.classList.toggle("speaking", el.dataset.seat === key); el.classList.toggle("addressed", el.dataset.seat === target); });
$$(".nameplate").forEach((el) => el.classList.toggle("speaking", el.dataset.seat === key));
const el = key && $(`#seat-${key}`);
if (el) {
el.classList.remove("thinking");
// lean toward whoever they're answering
const g = state.geo[key], tg = target && state.geo[target];
el.style.transform = tg ? `translateX(${Math.sign(tg.x - g.x) * g.size * 0.04}px) rotate(${Math.sign(tg.x - g.x) * 2.5}deg) scale(1.05)` : "scale(1.05)";
moveSpot(key);
} else $("#spot").classList.remove("on");
$$(".seat").forEach((s) => { if (s.dataset.seat !== key) s.style.transform = ""; });
}
function captionFor(who) {
$("#cruxes").hidden = true;
$("#plate").hidden = true;
const c = $("#caption");
c.hidden = false;
c.style.animation = "none"; void c.offsetWidth; c.style.animation = "";
const s = state.byKey[who];
$("#capAv").className = `cap-av${s ? "" : " chair"}`;
$("#capAv").innerHTML = `<img src="${s ? portrait(who) : "/brand/ais-symbol.png"}" alt="">`;
$("#capWho").textContent = s ? s.name : "The Chair";
}
function chairSays(text, { dots = false, tag = "" } = {}) {
setSpeaker(null);
captionFor(null);
$("#capTag").textContent = tag;
const p = $("#capText");
p.className = "cap-text chair";
p.innerHTML = esc(text) + (dots ? '<span class="dots"><i></i><i></i><i></i></span>' : "");
$("#capSub").textContent = "";
}
async function speak(key, text, { tag = "", target = null, sub = "" } = {}) {
setSpeaker(key, target);
captionFor(key);
$("#capTag").textContent = tag;
$("#capSub").textContent = "";
const p = $("#capText");
p.className = "cap-text";
const words = text.split(" ").filter(Boolean);
p.innerHTML = words.map((w) => `<span class="w">${esc(w)}</span> `).join("");
const spans = $$(".w", p);
for (let i = 0; i < words.length; i++) {
if (player.fast) break;
const w = words[i];
spans[i].classList.add("on");
const shapes = shapesFor(w.replace(/[^a-z]/gi, ""));
const dur = Math.max(170, w.length * 52);
const per = dur / (shapes.length + 1);
for (const sh of shapes) { setShape(key, sh); await player.sleep(per); }
setShape(key, "base");
await player.sleep(per + (/[.!?]["”)]?$/.test(w) ? 340 : /[,;:]$/.test(w) ? 170 : 25));
}
spans.forEach((s) => s.classList.add("on"));
setShape(key, "base");
$("#capSub").innerHTML = sub;
await player.sleep(1300);
}
// idle blinking for everyone, so the room feels alive between lines
function startBlinking() {
const blink = (key) => {
const b = $(`#seat-${key} .bust`);
if (b && b.dataset.shape === "base") {
b.dataset.shape = "blink";
setTimeout(() => { if (b.dataset.shape === "blink") b.dataset.shape = "base"; }, 130);
}
setTimeout(() => blink(key), 2400 + Math.random() * 4200);
};
state.seats.forEach((s, i) => setTimeout(() => blink(s.key), 600 + i * 530));
}
async function onSeatDone(ev) {
const { round, seat, text, parsed, quotes } = ev;
state.cards[round][seat] = { text, parsed, quotes };
const s = state.byKey[seat];
const top = topOption(parsed.optionScores);
const line = lineFor(round, parsed);
let tag = ROUND_NAME[round], sub = "", target = null;
if (round === 1) {
tag = `${stanceWord(parsed.stance)}${top ? ` · backs ${top.id} (${top.v}/10)` : ""}`;
} else if (round === 2) {
const tgt = parsed.disagreeWith ? state.byKey[parsed.disagreeWith] : null;
if (tgt) {
target = tgt.key;
tag = `Pushes back on ${tgt.short}`;
state.links = state.links.filter((l) => l.from !== seat);
state.links.push({ from: seat, to: tgt.key });
drawLinks();
}
sub = /^yes/i.test(parsed.moved) ? "Changed position" : "";
} else {
const v = parsed.vote || "endorse";
tag = `Votes ${v}`;
}
feedCard(round, seat, parsed);
await speak(seat, line || "I'll put it in my card.", { tag, target, sub });
const pl = $(`#plate-${seat}`);
const chip = $(".chip", pl);
chip.hidden = round === 3; // the vote stamp says it
chip.className = "chip";
if (round === 3) {
const v = parsed.vote || "endorse";
chip.textContent = v;
chip.classList.add(v);
$(`#seat-${seat} .vote`)?.remove();
const stamp = document.createElement("div");
stamp.className = `vote ${v}`;
stamp.textContent = v.toUpperCase();
$(`#seat-${seat}`).appendChild(stamp);
} else chip.textContent = stanceWord(parsed.stance);
if (top) { const sc = $(".score", pl); sc.hidden = false; sc.textContent = `${top.id} ${top.v}`; sc.title = `Highest score: option ${top.id}`; }
setSpeaker(null);
void s;
}
function stanceWord(t = "") {
const m = t.match(/strong yes|conditional yes|strong no|yes|no/i);
if (!m) return "Spoke";
const w = m[0].toLowerCase();
return w === "conditional yes" ? "Yes, if" : w[0].toUpperCase() + w.slice(1);
}
function topOption(scores = {}) {
const e = Object.entries(scores).sort((a, b) => b[1] - a[1])[0];
return e ? { id: e[0], v: e[1] } : null;
}
const shorten = (t, n) => (t.length > n ? t.slice(0, n - 1).replace(/\s+\S*$/, "") + "…" : t);
const face = (k) => `<img src="${portrait(k)}" alt="${esc(state.byKey[k]?.short || k)}" title="${esc(state.byKey[k]?.short || k)}">`;
async function onCruxes(ev) {
setSpeaker(null);
$("#caption").hidden = true;
const c = $("#cruxes");
c.hidden = false;
c.innerHTML = `<div class="head">${ev.unanimous ? "Too much agreement. The Chair pushes back." : "What they're fighting about"}</div>` +
ev.cruxes.map((x, i) => `<div class="crux" style="animation-delay:${i * 0.18}s"><b>${esc(x.question)}</b><div class="sides">${x.sides.map((sd) => `<span class="side"><span class="faces">${sd.seats.filter((k) => state.byKey[k]).map(face).join("")}</span>${esc(shorten(sd.position, 48))}</span>`).join("")}</div></div>`).join("");
const f = document.createElement("div");
f.className = "feed-note";
f.innerHTML = `<b>The fight:</b> ${ev.cruxes.map((x) => esc(x.question)).join(" ")}`;
feedAppend(f);
await player.sleep(3500 + 1800 * ev.cruxes.length);
}
async function onDraft(d) {
chairSays(`Proposal: ${d.label} on option ${d.option}. ${firstSentences(clean(d.recommendation), 140)}`, { tag: "Up for a vote" });
const f = document.createElement("div");
f.className = "feed-note";
f.innerHTML = `<b>Up for a vote:</b> ${esc(d.label)} on option ${esc(d.option)}.`;
feedAppend(f);
await player.sleep(4200);
}
// ------------------------------------------------------------- rebuttal arcs
function drawLinks() {
const svg = $("#links");
const stage = $("#stage");
const w = stage.clientWidth, h = stage.clientHeight;
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
const links = state.links || [];
const col = "#38bdf8";
svg.innerHTML = `<defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="${col}"/></marker></defs>` +
links.map(({ from, to }, i) => {
const a = state.geo[from], b = state.geo[to];
if (!a || !b) return "";
const y1 = a.top - 6, y2 = b.top - 6;
const mx = (a.x + b.x) / 2, my = Math.min(y1, y2) - Math.min(90, Math.abs(a.x - b.x) * 0.22) - 10;
return `<path class="${i < links.length - 1 ? "old" : ""}" d="M${a.x},${y1} Q${mx},${my} ${b.x},${y2}" stroke="${col}" marker-end="url(#arrow)"/>`;
}).join("");
}
// ------------------------------------------------------------- feed + cards
function feedAppend(node) {
const feed = $("#feed");
$(".empty", feed)?.remove();
feed.appendChild(node);
feed.scrollTop = feed.scrollHeight;
}
function feedPhase(label) {
const d = document.createElement("div");
d.className = "feed-phase";
d.textContent = label.replace(/^The Chair is /, "Chair: ");
feedAppend(d);
}
function feedCard(round, seat, parsed) {
const s = state.byKey[seat];
const d = document.createElement("div");
d.className = "feed-card";
d.dataset.seat = seat;
d.dataset.round = round;
const top = topOption(parsed.optionScores);
const tgt = parsed.disagreeWith ? state.byKey[parsed.disagreeWith]?.short : "";
const what = round === 1 ? `${stanceWord(parsed.stance)}${top ? `, backs ${top.id}` : ""}` : round === 2 ? (tgt ? `vs ${tgt}` : "Debate") : `Votes ${parsed.vote || "endorse"}`;
d.innerHTML = `<img class="av" src="${portrait(seat)}" alt=""><div><div class="h">${esc(s.short)}<span class="r">${esc(what)}</span></div><p>${esc(lineFor(round, parsed, 105))}</p></div>`;
feedAppend(d);
}
function openCard(seat, round) {
const s = state.byKey[seat];
const rounds = [3, 2, 1].filter((r) => state.cards[r][seat]);
const r = round || rounds[0];
const c = state.cards[r]?.[seat];
$("#cardBody").innerHTML = `
<div class="card-head"><img src="${portrait(seat)}" alt=""><div><div class="label">${esc(s.pillar)}</div><h3>${esc(s.name)}</h3><p class="muted" style="margin:0">Owns the question: ${esc(s.question)}</p></div></div>
${rounds.length > 1 ? `<p style="margin:0 0 6px">${rounds.slice().reverse().map((x) => `<button class="ghost" data-r="${x}" style="margin-right:6px">${ROUND_NAME[x]}</button>`).join("")}</p>` : ""}
${c ? `<pre>${esc(c.text)}</pre>${c.quotes.length ? `<ul class="qcheck">${c.quotes.map((q) => `<li class="${q.verified ? "" : "bad"}">"${esc(shorten(q.quote, 110))}" (${q.source}) ${q.verified ? "verified in the brain" : "not found in the brain"}</li>`).join("")}</ul>` : ""}` : `<p class="muted">This seat has not spoken yet.</p>`}
<p class="muted" style="font-size:12px">A simulated advisor built from ${esc(s.name)}'s public work. Not the person.</p>`;
$$("#cardBody [data-r]").forEach((b) => b.addEventListener("click", () => openCard(seat, Number(b.dataset.r))));
const dlg = $("#cardDialog");
if (!dlg.open) dlg.showModal();
}
// ------------------------------------------------------------- verdict
// the Chair should write display names; map any raw seat key just in case
const seatKey = (x) => { const k = String(x).toLowerCase().replace(/\s+/g, ""); return state.byKey[k] ? k : state.seats.find((s) => s.short.toLowerCase() === String(x).toLowerCase() || s.name.toLowerCase() === String(x).toLowerCase())?.key; };
const seatName = (x) => state.byKey[seatKey(x)]?.short || x;
function labelClass(l) { return /DON'T/.test(l) ? "dont" : /RESHAPE/.test(l) ? "reshape" : /WAIT/.test(l) ? "wait" : "go"; }
function onVerdict(ev) {
const v = ev.verdict;
state.verdict = ev;
setStep("verdict");
setSpeaker(null);
$("#caption").hidden = true;
$("#cruxes").hidden = true;
state.links = [];
drawLinks();
$("#stage").classList.remove("live");
updateOptions(v.scores);
const opt = (id) => state.options.find((o) => o.id === id)?.label || id;
const seats = ev.seats;
const mk = seatKey(v.minority.seat);
const short = (t, n) => esc(shorten(clean(t || ""), n));
const html = `
<div class="v-top">
<div><div class="label">The council's verdict</div><span class="v-label ${labelClass(v.label)}">${esc(v.label)}</span></div>
<button class="ghost" data-close>Back to the table</button>
</div>
<p class="v-call">${esc(v.call)}</p>
<div class="v-grid">
<div class="v-sec"><h3>Scores</h3><div class="v-opts">${state.options.map((o) => `
<div class="opt ${o.id === v.recommended ? "lead" : ""}"><span class="id">${o.id}</span><span class="label">${esc(o.label)}</span><span class="val">${v.scores[o.id]?.score ?? "-"}</span><span class="bar"><i style="width:${(v.scores[o.id]?.score || 0) * 10}%"></i></span></div>`).join("")}</div>
<p class="v-meta">Confidence ${v.confidence ?? "-"}/10${v.votes ? ` · ${v.votes.endorse || 0} endorse, ${v.votes.amend || 0} amend, ${v.votes.dissent || 0} dissent` : ""}</p>
</div>
<div class="v-sec"><h3>Why</h3><ul class="v-why">${v.why.slice(0, 3).map((w) => { const k = seatKey(w.seat); return `<li>${k ? `<img class="av" src="${portrait(k)}" alt="">` : ""}<span>${short(w.point, 150)}</span></li>`; }).join("")}</ul></div>
<div class="v-sec"><h3>Watch out</h3><div class="minority"><div class="who">${mk ? `<img class="av" src="${portrait(mk)}" alt="">` : ""}${esc(seatName(v.minority.seat))}</div><q>${short(v.minority.quote, 170)}</q></div></div>
<div class="v-sec"><h3>Next steps</h3><ul class="v-steps">${v.next_steps.slice(0, 3).map((n) => `<li><b>${esc(n.when)}</b> ${short(n.action, 120)}</li>`).join("")}</ul>
<p class="v-meta"><b>Kill it if:</b> ${short(v.kill_criteria, 140)}</p></div>
</div>
<details class="v-more"><summary>Full detail</summary>
<div class="v-grid">
<div class="v-sec"><h3>Where they fought</h3><ul>${v.fights.map((f) => `<li><b>${esc(f.crux)}</b> ${esc(f.story)}</li>`).join("")}</ul></div>
<div class="v-sec"><h3>Conditions</h3><ol>${v.conditions.map((c) => `<li>${esc(c)}</li>`).join("")}</ol></div>
<div class="v-sec v-wide"><h3>Scorecard</h3>
<table class="scorecard"><thead><tr><th>Seat</th><th>Weight</th>${state.options.map((o) => `<th>${o.id}</th>`).join("")}<th>Their line</th></tr></thead><tbody>
${seats.map((x) => { const s = state.byKey[x.key]; return `<tr><td><span class="who"><img class="av" src="${portrait(x.key)}" alt="">${esc(s.short)}</span></td><td class="n">${x.weight}</td>${state.options.map((o) => `<td class="n">${x.optionScores?.[o.id] ?? "-"}</td>`).join("")}<td class="line">${short(x.oneLine, 150)}</td></tr>`; }).join("")}
</tbody></table>
<p class="muted" style="font-size:11.5px;margin-top:8px">Weighted by how much each pillar matters here. ${state.options.map((o) => `${o.id}: ${esc(v.scores[o.id]?.math || "")}`).join(" · ")}</p></div>
<div class="v-sec"><h3>Cheapest test</h3><p>${esc(v.cheapest_test)}</p><h3>Revisit</h3><p>${esc(v.revisit)}</p></div>
<div class="v-sec"><h3>The strongest objection in full</h3><p>${esc(v.minority.quote)}</p><p class="muted">For this to be right: ${esc(v.minority.would_have_to_be_true)}</p></div>
${v.amendments?.length ? `<div class="v-sec v-wide"><h3>Amendments</h3><ul>${v.amendments.map((a) => `<li><b>${esc(seatName(a.seat))}:</b> ${esc(a.amendment)} <span class="tag">${a.adopted ? "Adopted" : "Not adopted"}: ${esc(a.reason)}</span></li>`).join("")}</ul></div>` : ""}
</div>
</details>
<div class="v-foot"><span class="muted">${esc(v.disclaimer)}</span><button class="ghost" data-close>Back to the table</button></div>`;
$("#verdictBody").innerHTML = html;
const plate = $("#plate");
plate.hidden = false;
plate.innerHTML = `<div class="label">The council's verdict</div><span class="v-label ${labelClass(v.label)}">${esc(v.label)}</span><p>${esc(firstSentences(clean(v.call), 150))}</p><div class="row"><button type="button" id="plateOpen">Read the verdict</button><button type="button" class="alt" id="plateReplay">Replay this council</button></div>`;
$("#plateOpen").addEventListener("click", () => ($("#verdictSheet").hidden = false));
$("#plateReplay").addEventListener("click", () => replay(state.session));
$("#playbar").hidden = true;
const f = document.createElement("div");
f.className = "feed-note";
f.innerHTML = `<b>Verdict: ${esc(v.label)}.</b> ${esc(firstSentences(clean(v.call), 160))}`;
feedAppend(f);
setTimeout(() => { if (state.verdict === ev) $("#verdictSheet").hidden = false; }, 1600);
}
// ------------------------------------------------------------- history + replay
async function openHistory() {
const { sessions } = await fetch("/api/sessions").then((x) => x.json());
$("#historyList").innerHTML = sessions.length
? sessions.map((s) => `<li><button data-id="${esc(s.id)}"><b>${esc(s.title)}</b><small>${esc(s.id.slice(0, 10))} · ${esc(s.mode)} · ${esc(s.status)}</small></button></li>`).join("")
: '<li class="muted">No sessions yet. Convene the council once and it shows up here.</li>';
$$("#historyList button").forEach((b) => b.addEventListener("click", () => { $("#historyDialog").close(); replay(b.dataset.id); }));
$("#historyDialog").showModal();
}
async function replay(id) {
const j = await fetch(`/api/sessions/${encodeURIComponent(id)}`).then((x) => x.json());
begin(id);
state.replaying = true;
for (const ev of j.events) {
if (["delta", "usage", "seat_error", "end"].includes(ev.type)) continue;
player.push(ev);
}
}
// ------------------------------------------------------------- misc
let toastTimer;
function toast(msg) {
const t = $("#toast");
t.textContent = msg;
t.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (t.hidden = true), 6000);
}
async function refreshUsage() {
const u = await fetch("/api/usage").then((x) => x.json()).catch(() => null);
if (!u || !u.calls) { $("#usage").textContent = ""; return; }
const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
$("#usage").textContent = `${u.calls} calls · ${k(u.input + u.cacheRead + u.cacheWrite)} in · ${k(u.output)} out`;
}
boot();