Files
tiny-worlds/web/transcript.mjs
T
mute e763d6c146 the access round: spectator mode removed and reads made story-only -- the table, raw session, carryover, files, status, and the notepad are owner-only; the story is the one public read (any signed-in user, fork button on it that copies the run that made the story, never the view); #28's human-side open read overturned with the ruling, gm.md stays never model-facing; non-owners land in the story view (play/setup redirect on the 403, home cards link there directly), the story view names its owner and stands alone on the story response, which now carries display/owner/ownerName; the table gains a raw tab -- the whole log as it rode the wire (thinking, every variant block, every reminder copy, full tool results, rides inline) next to the curated projection, live sessions only, sticky across turn re-renders; --debug mode for easy testing: every request is a fixed superuser that bypasses the users db entirely, no invite dance, loopback-bound regardless of config (found live: the SPA boot only asked the server who it was when a token existed, so tokenless browsers never learned they were the debug user -- boot now always asks); lint rule 10: no laptop-visible facts anywhere and all commits always from Mute -- the username and home paths are derived at runtime so the checker never contains them, scanned over the tracked tree, every historical blob, and commit messages, identity enforced on author and committer on every ref plus git config; the queue split: resolved questions relocated to DECISIONS.md verbatim by number (day's words kept, reversals annotate never rewrite, the agenda/reminder trio gets its own section), QUESTIONS is open items only (stale OPENs resolved on the way: #10 by the 2026-11-13 pairing default, #11 by the raw tab); smoke reworked to the story-only battery -- ash 403s on every run surface, 200 on the story alone, the ownerless-run check rides the runs list; all twelve QUESTIONS-number citations re-pointed at DECISIONS; smoke ALL PASS in a worktree (111 checks), two-user browser pass (the non-owner's whole run surface is a 403 detail and a 200 story, back-to-table hidden, owner views intact), raw-tab browser pass (curated table leak-free, raw shows the whole variants block, tabs vanish on dormancy), typecheck green on both programs, check-repo clean
2026-11-15 22:37:06 +00:00

309 lines
12 KiB
JavaScript

// web/transcript.mjs -- the transcript: register rendering and the
// entry walk.
//
// 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>/<agenda> blocks riding GM turns and the
// delta tags on player turns are machinery, not prose -- they render
// as chips and pane state, mirroring the live-context policy.
/** @typedef {import('../server/shapes.mjs').LogEvent} LogEvent */
/** @typedef {import('../server/shapes.mjs').BundleEvent} BundleEvent */
/** @typedef {import('../server/shapes.mjs').MsgEvent} MsgEvent */
/** @typedef {import('../server/shapes.mjs').NoteEvent} NoteEvent */
import { $, el } from './dom.mjs';
// splits text into spans: *italics* = narration, **bold** = emphasis
/** @param {HTMLElement} target @param {string} text */
function renderSpans(target, 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);
target.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);
target.appendChild(i);
} else {
target.appendChild(document.createTextNode(p));
}
}
}
// one content block (a GM or player turn) -> DOM lines. extract pulls
// the riding blocks (status/conflict/agenda) out of GM prose; the
// delta tags on player turns always render as chips. Exported for
// the story view, which renders the same registers.
/** @param {HTMLElement} target @param {?string} text @param {{ extract?: boolean }} opts @returns {{ status: ?string, conflict: ?string, agenda: ?string }} */
export function renderContent(target, text, { extract }) {
let body = String(text ?? '');
let status = null;
let conflict = null;
let agenda = 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 am = body.match(/<agenda>([\s\S]*?)<\/agenda>/);
if (am) { agenda = am[1]; body = body.replace(am[0], ''); }
}
const tags = [];
for (const m of body.matchAll(/<(lost|gained|add|drop)>([\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; // an open multi-line narration block
for (const line of body.split('\n')) {
const t = line.trim();
if (!t) { target.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;
target.appendChild(d);
continue;
}
if (t.startsWith('<')) {
// substrate lines: an opening <tag> is always OOC (invariants.md).
// Known blocks were extracted above; whatever remains is an
// unknown or unbalanced tag -- keep it visible, styled as OOC
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
target.appendChild(d);
continue;
}
const stars = (line.match(/\*/g) ?? []).length;
if (!narr && stars % 2 === 0) {
// balanced: spans carry the registers -- mixed lines
// (`*foo* bar *baz*`), whole-line narration (`*she sleeps.*`),
// bold -- all render correctly
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
target.appendChild(d);
continue;
}
if (!narr && !(t.startsWith('*') && !t.startsWith('**'))) {
// a stray unpaired * mid-line is not a block opener -- render
// as-is; the stray stays literal
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
target.appendChild(d);
continue;
}
// block narration: an unpaired leading * opens a multi-line
// block, a trailing * closes it
let content = line.replace(/^\s*\*/, '');
narr = true;
if (t.endsWith('*') && !t.endsWith('**')) {
narr = false;
content = content.trimEnd().slice(0, -1);
}
const d = document.createElement('div');
d.className = 'line narration';
renderSpans(d, content);
target.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);
}
}
target.appendChild(wrap);
}
return { status, conflict, agenda };
}
// the note line, shared by both walks
/** @param {NoteEvent} e @returns {?string} */
function noteText(e) {
if (e.kind === 'session') return `session ${e.n} opened`;
if (e.kind === 'ask') return `ask_gm: ${e.question}`;
if (e.kind === 'status') return `status: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
if (e.kind === 'agenda') return `agenda: added ${JSON.stringify(e.applied?.added ?? [])}, dropped ${JSON.stringify(e.applied?.dropped ?? [])}`;
if (e.kind === 'pick') return `variant literature: ${e.count} offered, #${e.chosen + 1} picked`;
return null;
}
// the raw walk: the audit surface over the same log -- everything as
// it rode the wire. Thinking, whole variant blocks, every reminder
// copy, full tool results, the rides inline in the GM prose; plain
// labeled blocks, no register rendering -- the table is the reading
// surface, this is the wire.
/** @param {LogEvent[]} entries */
export function renderRaw(entries) {
const t = $('transcript');
t.textContent = '';
/** @param {string} who @returns {HTMLElement} */
const block = (who) => {
const d = el('div', 'raw-block');
d.appendChild(el('div', 'who', who));
t.appendChild(d);
return d;
};
for (const e of entries) {
if (e.t === 'bundle') {
// the bundle rides collapsed here too -- it is the same content
// the table shows, and it is huge
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `bundle -- ${e.part}`));
d.appendChild(el('pre', null, e.m.content));
t.appendChild(d);
continue;
}
if (e.t === 'opening') {
t.appendChild(el('div', 'machinery', `her opening status: ${JSON.stringify(e.status)}`));
continue;
}
if (e.t === 'note') {
const text = noteText(e);
if (text) t.appendChild(el('div', 'machinery', text));
continue;
}
if (e.t === 'tool') {
const d = block(e.ask ? 'ruling' : 'tool result');
d.appendChild(el('pre', null, String(e.m.content)));
continue;
}
if (e.t === 'msg' && e.reminder) {
// every copy shows: the raw log keeps each as-sent chunk, and
// the audit surface keeps them all (the table elides superseded
// ones)
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder -- as sent'));
d.appendChild(el('pre', null, String(e.m.content ?? '')));
t.appendChild(d);
continue;
}
if (e.t === 'msg' && e.m.role === 'user') {
const d = block(e.conflictOnly ? 'gm -- conflict only' : 'gm');
d.appendChild(el('pre', null, String(e.m.content ?? '')));
continue;
}
if (e.t === 'msg' && e.m.role === 'assistant') {
const d = block('player');
if (e.m.reasoning_content) d.appendChild(el('pre', 'raw-thinking', e.m.reasoning_content));
d.appendChild(el('pre', null, String(e.m.content ?? '')));
for (const c of e.m.tool_calls ?? []) {
d.appendChild(el('div', 'machinery', `[tool call] ${c.function.name}`));
if (c.function.arguments) d.appendChild(el('pre', null, String(c.function.arguments)));
}
continue;
}
}
t.scrollTop = t.scrollHeight;
}
// the entry walk. onConflict receives a conflict block found on a GM
// turn -- the play view owns where it lands (the status pane). The
// opening event (her opening status) renders as machinery, mirroring
// the wire policy: it is set once, never re-sent.
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void }} [opts] */
export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript');
t.textContent = '';
/** @type {BundleEvent[]} */ const bundleParts = [];
const flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `session 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') {
// every part is inspectable, read-only: system (guards +
// substrate + craft), backdrop, character, the rings
bundleParts.push(e);
continue;
}
flushBundle();
if (e.t === 'msg' && e.reminder) {
// the turn reminder: the transcript mirrors the live-context
// policy -- one collapsed card for the newest copy, superseded
// ones elide (the log keeps every as-sent chunk)
const newest = [...entries].reverse().find((x) => x.t === 'msg' && x.reminder);
if (e === newest) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder -- rides every GM turn'));
d.appendChild(el('pre', null, e.m.content));
t.appendChild(d);
}
continue;
}
if (e.t === 'opening') {
t.appendChild(el('div', 'machinery', `her opening status: ${JSON.stringify(e.status)}`));
continue;
}
if (e.t === 'msg') {
if (e.m.role === 'user' && e.conflictOnly) {
// the self-heal message: error traffic on its own, never GM prose
t.appendChild(el('div', 'machinery', `[conflict] ${String(e.m.content).replace(/<\/?conflict>/g, '').trim()}`));
continue;
}
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;
/** @param {?string} content @param {string} who */
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) onConflict?.(conflict);
t.appendChild(d);
}
/** @param {MsgEvent} e */
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
const body = el('div');
d.appendChild(body);
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);
}
/** @param {NoteEvent} e */
function renderNote(e) {
const text = noteText(e);
if (text) t.appendChild(el('div', 'machinery', text));
}
}