Files
tiny-worlds/web/app.mjs
T
mute ba72d2ed1f substrate: server, housekeeping job, spa - the mvp complete
- prompt split, GM's cut: system.md = opening + guards (glossary, purpose, input validation; repo-fed, per-project); invariants.md = substrate (syntax markers, tools, memory, records, the paper + its three-part gate; repo-fed, travels with the code); handbook.md = craft copy (shape of play, thoughts, purview, time skips, continuity, stance, hard limits; copied per run). One system message: system -> invariants -> the run's handbook. OOC is a single open paren, closing optional, match the GM's style; a lone paren is an empty OOC line, skipped by the parser. housekeeper.md aligned: the paper holds acute states, relational shifts are recorded as the facts behind them, and dates are story dates (follow the rings' calendar, never the wall clock - the seed is 2069 now, per canon)
- server/ (phase 2, zero-dep node:http): REST spine per the sketch, per-run session machine with ask_gm pause/resume (the whole tool-call batch waits, pairing stays sound), view renderer (thinking-strip, tool-result elision with ask answers exempt, old status/conflict blocks stripped), boot-rebuild from the typed jsonl, lazy seed + turn-0 ingestion at window-open with the unhousekept refuse-and-override guard, usage tracking + context meter, tool-pairing validation, scripted mock model. The clerk gained --json (packages/runs/status); tool/bridge.mjs deleted at mock-parity per the retirement decision
- housekeeping job (phase 3, server/housekeeping.mjs): trigger ends the window and runs the chain async - transcript with labeled thinking, run-state injection (records availability; the ring views stay pure memory), housekeeper on a fresh context, manifest saved (raw output too if unparseable), clerk apply (writes the window log, snapshots dumps/<window>.sql), state.json lastHousekeptSession, autorestart. Rejection holds the restart and surfaces why; the apply endpoint is the recovery path and the manual-relay close. Live-proven twice: both manifests sound (ring-B classification, first-person voice, precise touches, story-dated)
- spa (phase 4, web/ - no build, vanilla es modules, served at /): three-register transcript per the ruled markers incl. multi-line narration blocks, bundle as a collapsed card with turn-0 as the opening GM turn, paper tags as chips, status pane with conflict surfacing, context meter hot past 85 percent, gm line input, ask modal re-presented from pendingAsk, housekeeping button with two-click arm + poll + inline log. No js alert/confirm (they block the embedded pane) - in-page banner instead. Driven end to end through the ui on a disposable live run
- seed: date fixed to the 2069 story calendar (was a real-world date; real dates never surface to the player)
- docs: README goal states the mvp is complete, layout covers server/ and web/, protocol and substrate sections rewritten for the server; ROADMAP phases 0-4 done, harness decisions current; QUESTIONS #4 #7 #10 #12 #16-mechanism #19a #20 #21 resolved; HANDOFF is the handoff map; AGENTS carries the working lessons (tokens are free, no screenshots - not multimodal, no js dialogs, external state survives rewinds)
2026-11-14 03:15:53 +00:00

483 lines
14 KiB
JavaScript

// web/app.mjs — the SPA: strictly a client of the REST API.
//
// The transcript renders three registers by the ruled markers: plain
// text is speech, *italics* is narration, a line opening with `(` is
// OOC (closing paren optional; a lone paren is an empty OOC line and
// is skipped). The <status> blocks riding GM turns and the paper tags
// on player turns are machinery, not prose — they render as chips and
// pane state, mirroring the live-context policy.
const $ = (id) => document.getElementById(id);
const state = { runId: null, runs: [], packages: [], poll: null };
async function api(path, opts = {}) {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: opts.body !== undefined ? { 'content-type': 'application/json' } : {},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const e = new Error(data.error ?? `${res.status}`);
e.detail = data.detail;
e.status = res.status;
throw e;
}
return data;
}
// --- register rendering -------------------------------------------------------
// splits text into spans: *italics* = narration, **bold** = emphasis
function renderSpans(el, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) {
if (!p) continue;
if (p.startsWith('**') && p.endsWith('**')) {
const b = document.createElement('strong');
b.textContent = p.slice(2, -2);
el.appendChild(b);
} else if (p.startsWith('*') && p.endsWith('*') && p.length > 2) {
const i = document.createElement('em');
i.className = 'narration';
i.textContent = p.slice(1, -1);
el.appendChild(i);
} else {
el.appendChild(document.createTextNode(p));
}
}
}
// one content block (a GM or player turn) -> DOM lines
function renderContent(el, text, { extract }) {
let body = String(text ?? '');
let status = null;
let conflict = null;
if (extract) {
const sm = body.match(/<status>([\s\S]*?)<\/status>/);
if (sm) { status = sm[1]; body = body.replace(sm[0], ''); }
const cm = body.match(/<conflict>([\s\S]*?)<\/conflict>/);
if (cm) { conflict = cm[1]; body = body.replace(cm[0], ''); }
}
const tags = [];
for (const m of body.matchAll(/<(lost|gained)>([\s\S]*?)<\/\1>/g)) {
tags.push({ kind: m[1], items: m[2].split('\n').flatMap((l) => l.split(',')).map((x) => x.trim()).filter(Boolean) });
}
for (const t of tags) body = body.replace(new RegExp(`<${t.kind}>[\\s\\S]*?</${t.kind}>`), '');
let narr = false; // multi-line narration blocks: open on a leading *, close on a trailing *
for (const line of body.split('\n')) {
const t = line.trim();
if (!t) { el.appendChild(document.createElement('br')); continue; }
if (t.startsWith('(')) {
if (t === '(') continue; // empty OOC — skip
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
el.appendChild(d);
continue;
}
let isNarr = narr;
let content = line;
if (!narr && t.startsWith('*') && !t.startsWith('**')) {
isNarr = true;
narr = true;
content = line.replace(/^\s*\*/, '');
if (content.trimEnd().endsWith('*')) {
narr = false;
content = content.trimEnd().slice(0, -1);
}
} else if (narr) {
if (t.endsWith('*')) {
narr = false;
content = line.trimEnd().slice(0, -1);
}
}
const d = document.createElement('div');
d.className = `line ${isNarr ? 'narration' : 'speech'}`;
renderSpans(d, content);
el.appendChild(d);
}
if (tags.length) {
const wrap = document.createElement('div');
wrap.className = 'tags';
for (const t of tags) {
for (const item of t.items) {
const c = document.createElement('span');
c.className = `chip ${t.kind}`;
c.textContent = item;
wrap.appendChild(c);
}
}
el.appendChild(wrap);
}
return { status, conflict };
}
// --- transcript ---------------------------------------------------------------
function el(tag, cls, text) {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}
function renderTranscript(entries) {
const t = $('transcript');
t.textContent = '';
const bundleParts = [];
let flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `window bundle — ${bundleParts.map((p) => p.part).join(', ')}`));
for (const p of bundleParts) {
const sec = el('details');
sec.appendChild(el('summary', null, p.part));
sec.appendChild(el('pre', null, p.m.content));
d.appendChild(sec);
}
t.appendChild(d);
bundleParts.length = 0;
};
for (const e of entries) {
if (e.t === 'bundle') {
if (e.part === 'turn-0') {
// the opening beat is fiction: it renders as the first GM turn
gmTurn(e.m.content, 'turn-0');
continue;
}
if (e.part !== 'system') bundleParts.push(e);
continue;
}
flushBundle();
if (e.t === 'msg') {
if (e.m.role === 'user') gmTurn(e.m.content, 'GM');
else if (e.m.role === 'assistant') playerTurn(e);
continue;
}
if (e.t === 'tool') {
t.appendChild(el('div', 'machinery', `${e.ask ? '[ruling] ' : '[tool result] '}${String(e.m.content).split('\n')[0]}`));
continue;
}
if (e.t === 'note') renderNote(e);
}
flushBundle();
t.scrollTop = t.scrollHeight;
function gmTurn(content, who) {
const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who));
const body = el('div');
d.appendChild(body);
const { conflict } = renderContent(body, content, { extract: true });
if (conflict) showConflict(conflict);
t.appendChild(d);
}
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
const body = el('div');
d.appendChild(body);
if (e.m.reasoning_content) d.appendChild(el('div', 'machinery', '[thinking is logged for the housekeeper, not shown]'));
renderContent(body, e.m.content, { extract: false });
for (const c of e.m.tool_calls ?? []) {
d.appendChild(el('div', 'machinery', `[tool call] ${c.function.name}`));
}
t.appendChild(d);
}
function renderNote(e) {
let text = null;
if (e.kind === 'window') text = `window opened ${e.at}${e.fresh ? ' — fresh' : ''}`;
else if (e.kind === 'seed') text = `seed ${e.ok ? 'applied' : 'failed'}: ${e.detail}`;
else if (e.kind === 'ingest') text = `turn-0 paper ingested`;
else if (e.kind === 'ask') text = `ask_gm: ${e.question}`;
else if (e.kind === 'paper') text = `paper: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
if (text) t.appendChild(el('div', 'machinery', text));
}
}
// --- panes --------------------------------------------------------------------
function renderPaper(paper) {
const ul = $('paper');
ul.textContent = '';
if (!paper?.length) {
ul.appendChild(el('li', 'empty', 'a blank sheet'));
return;
}
for (const p of paper) ul.appendChild(el('li', null, p));
}
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
c.hidden = false;
}
function renderMeter(detail) {
const fill = $('context-fill');
const label = $('context-label');
const c = detail?.context;
if (!c || c.used == null) {
fill.style.width = '0';
label.textContent = '';
return;
}
const pct = c.pct ?? 0;
fill.style.width = `${Math.min(100, pct)}%`;
fill.classList.toggle('hot', pct > 85);
label.textContent = c.window ? `${pct}% — close & housekeep past 85%` : '';
}
function setHk(stateText, cls) {
const h = $('hk-state');
h.textContent = stateText;
h.className = cls ?? '';
}
// --- data flow ----------------------------------------------------------------
async function loadRuns() {
state.runs = await api('/runs');
state.packages = await api('/packages');
const sel = $('run-select');
sel.textContent = '';
if (!state.runs.length) {
sel.appendChild(el('option', null, '(no runs — create one)'));
return;
}
for (const r of state.runs) {
const o = el('option', null, `${r.id} [${r.package}]`);
o.value = r.id;
sel.appendChild(o);
}
const saved = localStorage.getItem('run');
if (state.runs.some((r) => r.id === saved)) sel.value = saved;
state.runId = sel.value || null;
}
async function selectRun(id) {
state.runId = id;
localStorage.setItem('run', id);
stopPoll();
await refresh();
}
async function refresh() {
if (!state.runId) {
$('window-info').textContent = '';
$('transcript').textContent = '';
renderPaper([]);
renderMeter(null);
setInput(false);
return;
}
const detail = await api(`/runs/${state.runId}`);
$('window-info').textContent = detail.open
? `window ${detail.window}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: 'no open window';
renderMeter(detail);
renderPaper(detail.paper);
$('conflict').hidden = true;
if (detail.open) {
const session = await api(`/runs/${state.runId}/session`);
renderTranscript(session.entries);
} else {
$('transcript').textContent = '';
}
// controls
$('window-open').hidden = detail.open;
$('hk-run').hidden = !detail.open;
const inputOk = detail.open && !detail.pendingAsk;
setInput(inputOk);
// pending ask: the modal re-presents after a refresh
if (detail.pendingAsk) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
} else {
$('ask-modal').close();
}
// housekeeping state
const hk = await api(`/runs/${state.runId}/housekeeping`);
renderHk(hk, detail);
}
function renderHk(hk, detail) {
if (hk.state === 'running') {
setHk('housekeeping…', '');
startPoll();
return;
}
stopPoll();
if (hk.state === 'applied') {
setHk(`applied — window ${hk.window ?? ''}\nnext window open`, 'applied');
} else if (hk.state === 'rejected') {
setHk(`rejected — held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
} else {
setHk('idle', '');
}
}
function setInput(ok) {
$('gm-input').disabled = !ok;
$('gm-send').disabled = !ok;
}
// in-page notices — no JS alert()/confirm(): they block the embedded pane
let bannerTimer = null;
function banner(text, kind = 'error') {
const b = $('banner');
b.textContent = text;
b.className = kind;
b.hidden = false;
clearTimeout(bannerTimer);
bannerTimer = setTimeout(() => { b.hidden = true; }, 10000);
}
function hideBanner() {
$('banner').hidden = true;
}
// --- actions ------------------------------------------------------------------
async function sendTurn() {
const line = $('gm-input').value.trim();
if (!line || !state.runId) return;
$('gm-input').value = '';
setInput(false);
try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
} catch (e) {
$('transcript').appendChild(el('div', 'error-line machinery', `error: ${e.message}`));
}
await refresh();
}
async function sendAnswer() {
const answer = $('ask-answer').value.trim();
if (!answer || !state.runId) return;
$('ask-answer').value = '';
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) {
banner(e.message);
}
await refresh();
}
async function openWindow() {
const override = $('hk-override').checked;
hideBanner();
try {
await api(`/runs/${state.runId}/windows`, { method: 'POST', body: { override } });
$('hk-override').checked = false;
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
banner(`${e.message}\n${e.detail.hint}`, 'info');
} else {
banner(e.message);
}
}
await refresh();
}
// two-click confirm — the second click within 5s fires; anything else disarms
let hkArmed = null;
async function runHousekeeping() {
const btn = $('hk-run');
if (hkArmed === null) {
btn.textContent = 'sure? click again to close & housekeep';
hkArmed = setTimeout(() => {
hkArmed = null;
btn.textContent = 'close window & housekeep';
}, 5000);
return;
}
clearTimeout(hkArmed);
hkArmed = null;
btn.textContent = 'close window & housekeep';
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('housekeeping…', '');
startPoll();
} catch (e) {
banner(e.message);
}
await refresh();
}
function startPoll() {
stopPoll();
state.poll = setInterval(async () => {
if (!state.runId) return stopPoll();
const hk = await api(`/runs/${state.runId}/housekeeping`).catch(() => null);
if (!hk || hk.state !== 'running') {
await refresh();
if (hk?.state === 'applied') loadLog();
}
}, 3000);
}
function stopPoll() {
if (state.poll) clearInterval(state.poll);
state.poll = null;
}
async function loadLog() {
try {
const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content;
$('hk-log').hidden = false;
$('hk-log').open = true;
} catch {
$('hk-log').hidden = true;
}
}
// --- wiring -------------------------------------------------------------------
$('run-select').addEventListener('change', (e) => selectRun(e.target.value));
$('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
});
$('ask-send').addEventListener('click', sendAnswer);
$('ask-answer').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
});
$('window-open').addEventListener('click', openWindow);
$('hk-run').addEventListener('click', runHousekeeping);
$('new-run-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('new-run-name').value.trim();
const pkg = $('new-run-package').value;
if (!name || !pkg) return;
try {
await api('/runs', { method: 'POST', body: { package: pkg, name } });
$('new-run-name').value = '';
$('new-run').removeAttribute('open');
await loadRuns();
await selectRun(name);
} catch (err) {
banner(err.message);
}
});
(async function init() {
await loadRuns();
const pkgSel = $('new-run-package');
for (const p of state.packages) {
const o = el('option', null, p.name);
o.value = p.name;
pkgSel.appendChild(o);
}
if (state.runId) await selectRun(state.runId);
else refresh();
})();