import { downloadVerdictPdf } from "./pdf.js";
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[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 EXAMPLE = "I run a coaching business at $30k a month with 15 clients at $2,000 each. Should I raise to $3,500 for everyone, raise for new clients only, or keep $2,000? Close rate is about 50% and I have $40k in the bank. Success is $45k a month by March. I'm leaning toward raising for everyone because I'm underpaid.";
// The how-to, shown in the side panel while the room is empty and in "How it works".
const GUIDE = `
How to use the Roast Room
Open Claude Code in this folder.
Type /roast-room and your decision.
Answer the Chair's questions. Then watch the council argue it out here.
When the verdict lands, download it as a PDF.
What to put in your question
The decision in one line.
Your options. Two or three. "Keep doing what I do now" counts.
Your numbers. Revenue, cash, and team size.
Your limits. Deadline, hours, and budget.
What success looks like , and by when.
Which way you're leaning , and why. The council tests it.
Left something out? The Chair asks before the council starts.
Example
/roast-room ${EXAMPLE.replace(/&/g, "&").replace(/
Copy this example
Good to know
Full council: 7 advisors, 3 rounds. For big calls that are hard to undo.
Quick: add --quick for 4 advisors and 2 rounds. Uses far less of your plan.
Every council is saved. Open Past sessions to replay one or download its PDF.
`;
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: {}, setup: null, wait: null,
};
// ------------------------------------------------------------- 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);
setInterval(tickWait, 1000);
}
// 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");
// characters sit inside a nowrap span per word, so lines only break between words
let i = 0;
el.innerHTML = text.split(" ").map((word) => `${[...word].map((c) => `${esc(c)} `).join("")} `).join(" ");
el.setAttribute("aria-label", text);
}
function renderSamples() {
$("#samples").innerHTML = SAMPLES.map(([t], i) => `${esc(t)} `).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, i) => `
${SHAPES.map((sh) => `
`).join("")}
`).join("");
$("#plates").innerHTML = state.seats.map((s) => `
${esc(s.short === "Gary V" ? "Gary V" : s.name)}
${esc(s.pillar)}
`).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);
$("#waitGuide").addEventListener("click", openGuide);
$("#guideBtn").addEventListener("click", openGuide);
document.addEventListener("click", async (e) => {
if (e.target.closest("[data-copy-example]")) {
try { await navigator.clipboard.writeText("/roast-room " + EXAMPLE); toast("Copied. Paste it into Claude Code."); }
catch { toast("Copy didn't work here. Select the text and copy it."); }
}
if (e.target.closest("[data-pdf]")) savePdf(e.target.closest("[data-pdf]"));
});
$("#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();
hideWait();
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, setup: null, wait: null });
hideWait();
$("#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;
$("#panelHead").textContent = "Getting started";
$("#feed").innerHTML = GUIDE;
$$(".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;
$("#panelHead").textContent = "Key points";
$("#feed").innerHTML = 'One line per seat as the council talks. Click a seat to read its full card.
';
$("#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": {
state.wait = { phase: ev.phase, at: ev.at || Date.now() };
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": state.setup = ev; 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": state.wait = null; updateOptions(ev.scores); break;
case "cruxes": await onCruxes(ev); break;
case "draft": await onDraft(ev.draft); break;
case "verdict": state.wait = null; onVerdict(ev); break;
case "error": state.wait = null; 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) => `
${o.id} ${esc(o.label)} -
`).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 = ` `;
$("#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 ? ' ' : "");
$("#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) => `${esc(w)} `).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) => ` `;
async function onCruxes(ev) {
setSpeaker(null);
$("#caption").hidden = true;
const c = $("#cruxes");
c.hidden = false;
c.innerHTML = `${ev.unanimous ? "Too much agreement. The Chair pushes back." : "What they're fighting about"}
` +
ev.cruxes.map((x, i) => `${esc(x.question)} ${x.sides.map((sd) => `${sd.seats.filter((k) => state.byKey[k]).map(face).join("")} ${esc(shorten(sd.position, 48))} `).join("")}
`).join("");
const f = document.createElement("div");
f.className = "feed-note";
f.innerHTML = `The fight: ${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 = `Up for a vote: ${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 = ` ` +
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 ` `;
}).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 = `${esc(s.short)}${esc(what)}
${esc(lineFor(round, parsed, 105))}
`;
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 = `
${esc(s.pillar)}
${esc(s.name)} Owns the question: ${esc(s.question)}
${rounds.length > 1 ? `${rounds.slice().reverse().map((x) => `${ROUND_NAME[x]} `).join("")}
` : ""}
${c ? `${esc(c.text)} ${c.quotes.length ? `${c.quotes.map((q) => `"${esc(shorten(q.quote, 110))}" (${q.source}) ${q.verified ? "verified in the brain" : "not found in the brain"} `).join("")} ` : ""}` : `This seat has not spoken yet.
`}
A simulated advisor built from ${esc(s.name)}'s public work. Not the person.
`;
$$("#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 = `
The council's verdict
${esc(v.label)}
Download PDF Back to the table
${esc(v.call)}
Scores ${state.options.map((o) => `
${o.id} ${esc(o.label)} ${v.scores[o.id]?.score ?? "-"}
`).join("")}
Confidence ${v.confidence ?? "-"}/10${v.votes ? ` · ${v.votes.endorse || 0} endorse, ${v.votes.amend || 0} amend, ${v.votes.dissent || 0} dissent` : ""}
Why ${v.why.slice(0, 3).map((w) => { const k = seatKey(w.seat); return `${k ? ` ` : ""}${short(w.point, 150)} `; }).join("")}
Watch out ${mk ? `
` : ""}${esc(seatName(v.minority.seat))}
${short(v.minority.quote, 170)}
Next steps ${v.next_steps.slice(0, 3).map((n) => `${esc(n.when)} ${short(n.action, 120)} `).join("")}
Kill it if: ${short(v.kill_criteria, 140)}
Full detail
Where they fought ${v.fights.map((f) => `${esc(f.crux)} ${esc(f.story)} `).join("")}
Conditions ${v.conditions.map((c) => `${esc(c)} `).join("")}
Scorecard
Seat Weight ${state.options.map((o) => `${o.id} `).join("")}Their line
${seats.map((x) => { const s = state.byKey[x.key]; return ` ${esc(s.short)}${x.weight} ${state.options.map((o) => `${x.optionScores?.[o.id] ?? "-"} `).join("")}${short(x.oneLine, 150)} `; }).join("")}
Weighted by how much each pillar matters here. ${state.options.map((o) => `${o.id}: ${esc(v.scores[o.id]?.math || "")}`).join(" · ")}
Cheapest test ${esc(v.cheapest_test)}
Revisit ${esc(v.revisit)}
The strongest objection in full ${esc(v.minority.quote)}
For this to be right: ${esc(v.minority.would_have_to_be_true)}
${v.amendments?.length ? `
Amendments ${v.amendments.map((a) => `${esc(seatName(a.seat))}: ${esc(a.amendment)} ${a.adopted ? "Adopted" : "Not adopted"}: ${esc(a.reason)} `).join("")} ` : ""}
`;
$("#verdictBody").innerHTML = html;
const plate = $("#plate");
plate.hidden = false;
plate.innerHTML = `The council's verdict
${esc(v.label)} ${esc(firstSentences(clean(v.call), 150))}
Read the verdict Download PDF Replay this council
`;
$("#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 = `Verdict: ${esc(v.label)}. ${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) => `${esc(s.title)} ${esc(s.id.slice(0, 10))} · ${esc(s.mode)} · ${esc(s.status)} ${s.status === "done" ? `PDF ` : ""} `).join("")
: 'No sessions yet. Convene the council once and it shows up here. ';
$$("#historyList button[data-id]").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);
}
}
// ------------------------------------------------------------- waiting on Claude Code
// A live council goes quiet for minutes while the seats write in parallel. Instead of a
// frozen table, say what is happening, how long it has been, and what each seat is weighing.
const SAME_TIME = "The advisors all write at the same time in Claude Code. Their lines play here as soon as the round is in.";
function waitCopy(phase) {
const n = state.setup?.mode === "quick" ? 2 : 3;
return {
setup: ["Setting the table", "The Chair is seating the council.", ""],
round1: ["Round 1 of " + n, "The advisors are writing their opening positions.", SAME_TIME],
round2: ["Round 2 of " + n, "The advisors are reading each other's openings and firing back.", SAME_TIME],
round3: ["Round 3 of " + n, "The advisors are voting on the Chair's proposal.", SAME_TIME],
cruxes: ["Between rounds", "The Chair is reading the openings and finding where they disagree.", "The fight shows up here next, then the debate starts."],
draft: ["Between rounds", "The Chair is turning the debate into a proposal for the vote.", "Next, every advisor votes on it."],
skip3: ["Last step", "The Chair is scoring the room and writing the verdict.", "When it lands, you can download it as a PDF."],
verdict: ["Last step", "The Chair is scoring the room and writing the verdict.", "When it lands, you can download it as a PDF."],
}[phase] || ["Working", "The council is working.", ""];
}
const clock = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0"); };
function hideWait() {
const w = $("#waitcard");
if (w.hidden) return;
w.hidden = true;
$$(".seat.musing").forEach((e) => e.classList.remove("musing"));
if (state.capWasShown) $("#caption").hidden = false;
if (state.playbarWasShown) $("#playbar").hidden = false;
}
function tickWait() {
const w = state.wait;
const idle = !player.busy && !player.q.length;
if (!w || !idle || state.replaying || !state.session || state.verdict) return hideWait();
const card = $("#waitcard");
if (card.hidden) {
state.capWasShown = !$("#caption").hidden;
$("#caption").hidden = true;
$("#cruxes").hidden = true;
// speed controls do nothing while the room waits, and they would cover the card
state.playbarWasShown = !$("#playbar").hidden;
$("#playbar").hidden = true;
card.hidden = false;
state.museAt = 0;
}
const [step, head, sub] = waitCopy(w.phase);
const elapsed = Date.now() - w.at;
$("#wcStep").textContent = step;
$("#wcTime").textContent = clock(elapsed);
$("#wcHead").textContent = head;
$("#wcSub").textContent = sub;
$("#wcNudge").hidden = elapsed < 4 * 60 * 1000;
const round = Number((w.phase.match(/^round(\d)$/) || [])[1]) || 0;
const bar = $("#wcBar").parentElement;
const muse = $("#wcMuse");
if (round) {
const seats = state.active.length ? state.active : state.seats.map((s) => s.key);
const done = seats.filter((k) => state.cards[round][k]).length;
bar.classList.toggle("indeterminate", done === 0);
$("#wcBar").style.width = done ? Math.round((done / seats.length) * 100) + "%" : "";
// every few seconds, show what one of the still-thinking seats is weighing
const pending = seats.filter((k) => !state.cards[round][k]);
if (pending.length && Date.now() - (state.museAt || 0) > 5200) {
state.museAt = Date.now();
state.museIdx = ((state.museIdx ?? -1) + 1) % pending.length;
const s = state.byKey[pending[state.museIdx]];
muse.classList.add("fade");
setTimeout(() => {
muse.innerHTML = "" + esc(s.short) + " is weighing: " + esc(s.question.replace(/^./, (c) => c.toLowerCase())) + (done ? " · " + done + " of " + seats.length + " in" : "");
muse.classList.remove("fade");
$$(".seat").forEach((el) => el.classList.toggle("musing", el.dataset.seat === s.key));
}, 300);
}
} else {
bar.classList.add("indeterminate");
$("#wcBar").style.width = "";
muse.textContent = "";
$$(".seat.musing").forEach((e) => e.classList.remove("musing"));
}
}
function openGuide() {
$("#guideBody").innerHTML = GUIDE;
const d = $("#guideDialog");
if (!d.open) d.showModal();
}
// ------------------------------------------------------------- PDF
async function savePdf(btn) {
const id = btn.dataset.pdf;
btn.disabled = true;
const old = btn.textContent;
btn.textContent = "Making PDF...";
try {
let setup = state.setup, verdict = state.verdict;
if (id) { // a past session from the history list
const j = await fetch("/api/sessions/" + encodeURIComponent(id)).then((x) => x.json());
setup = j.events.find((e) => e.type === "setup");
verdict = [...j.events].reverse().find((e) => e.type === "verdict");
}
if (!setup || !verdict) throw new Error("This council has no verdict yet.");
await downloadVerdictPdf({ setup, verdict, byKey: state.byKey, id: id || state.session });
} catch (e) {
console.error(e);
toast("Couldn't make the PDF: " + (e.message || e));
} finally {
btn.disabled = false;
btn.textContent = old;
}
}
// ------------------------------------------------------------- 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();