variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout

This commit is contained in:
2026-11-15 14:35:00 +00:00
parent c51d31078e
commit fa3f23b474
51 changed files with 3477 additions and 1719 deletions
+5 -2
View File
@@ -1,8 +1,9 @@
// web/app.mjs — the SPA entry: view registration and boot.
// web/app.mjs -- the SPA entry: view registration and boot.
//
// The SPA is strictly a client of the REST API. Path-routed views
// (router.mjs): / (home: runs to pick up), /new (package picker),
// /runs/<id>/setup (the editor; start = open session + send turn-0),
// /runs/<id>/setup (the dormancy editor; start freezes the bundle and
// consumes the carryover),
// /runs/<id> (play). The server serves the shell for any
// extensionless path.
@@ -15,6 +16,7 @@ import * as home from './view-home.mjs';
import * as newRun from './view-new.mjs';
import * as setup from './view-setup.mjs';
import * as play from './view-play.mjs';
import * as story from './view-story.mjs';
$('home-link').addEventListener('click', (e) => { e.preventDefault(); navigate('/'); });
@@ -24,6 +26,7 @@ registerViews({
new: { el: 'view-new', enter: newRun.enter },
setup: { el: 'view-setup', enter: setup.enter },
play: { el: 'view-play', enter: play.enter, leave: play.leave },
story: { el: 'view-story', enter: story.enter },
});
// boot: restore the session from the stored token; a rejected or
+7 -7
View File
@@ -1,7 +1,7 @@
// web/chrome.mjs — the shared page chrome: header identity, session
// web/chrome.mjs -- the shared page chrome: header identity, session
// info, the context meter, the busy note, the notice banner.
//
// In-page notices only — no JS alert()/confirm(): they block the
// In-page notices only -- no JS alert()/confirm(): they block the
// embedded browser pane. Errors and notices land in the banner
// instead; destructive confirms are two-click armed (widgets.mjs).
@@ -9,9 +9,9 @@ import { $ } from './dom.mjs';
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// — the lifecycle story is a roadmap extension point
// -- the lifecycle story is a roadmap extension point
export function setWho(me) {
$('who').textContent = me ? `${me.name}${me.superuser ? ' · op' : ''}` : '';
$('who').textContent = me ? `${me.name}${me.superuser ? ' \u00b7 op' : ''}` : '';
$('who').title = me?.id ?? '';
}
@@ -31,11 +31,11 @@ export function renderMeter(detail) {
const pct = c.pct ?? 0;
fill.style.width = `${Math.min(100, pct)}%`;
fill.classList.toggle('hot', pct > 85);
label.textContent = c.contwin ? `${pct}% — close & housekeep past 85%` : '';
label.textContent = c.contwin ? `${pct}% -- close & housekeep past 85%` : '';
}
export function setBusy(on, text = 'her turn…') {
$('busy').hidden = !on; // model calls take their time — say so
export function setBusy(on, text = 'her turn...') {
$('busy').hidden = !on; // model calls take their time -- say so
if (on) $('busy').textContent = text;
}
+6 -6
View File
@@ -1,7 +1,7 @@
// web/client.mjs — the REST client: the one fetch choke point.
// web/client.mjs -- the REST client: the one fetch choke point.
//
// Every call is logged to the diagnostics (status + duration); a
// rejected token ends the session — drop it and show the claim view;
// rejected token ends the session -- drop it and show the claim view;
// every path leads there until a fresh one is claimed.
import { logEvent } from './log.mjs';
@@ -11,7 +11,7 @@ import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked — the session just won't persist */ } };
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked -- the session just won't persist */ } };
export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
export async function api(path, opts = {}) {
@@ -25,14 +25,14 @@ export async function api(path, opts = {}) {
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page — the notepad flush
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page -- the notepad flush
});
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;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms — ${e.message}`);
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms -- ${e.message}`);
if (res.status === 401 && path !== '/session' && authToken()) {
clearToken();
state.me = null;
@@ -44,7 +44,7 @@ export async function api(path, opts = {}) {
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
return data;
} catch (e) {
if (!e.status) logEvent('api', `${label} FAILED ${Math.round(performance.now() - started)}ms — ${e.message}`); // network level
if (!e.status) logEvent('api', `${label} FAILED ${Math.round(performance.now() - started)}ms -- ${e.message}`); // network level
throw e;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// web/dom.mjs — the two DOM helpers everything else builds on.
// web/dom.mjs -- the two DOM helpers everything else builds on.
export const $ = (id) => document.getElementById(id);
+24 -11
View File
@@ -49,7 +49,7 @@
<section id="view-new" hidden>
<h1>new run</h1>
<div id="package-pick">
<p class="hint">a run is a copy of the package — everything stays editable until the session opens</p>
<p class="hint">a run is a copy of the package -- everything stays editable until the session opens</p>
<div id="package-list"></div>
</div>
<form id="create-form" hidden>
@@ -71,7 +71,7 @@
<button id="setup-start" class="primary">start</button>
</div>
<div id="setup-vars" hidden>
<h2>prompt variables — declared by the prompts, filled per run</h2>
<h2>prompt variables -- declared by the prompts, filled per run</h2>
<div id="setup-vars-list"></div>
<div class="form-actions">
<button id="setup-vars-save">save variables</button>
@@ -102,6 +102,14 @@
<section id="view-play" hidden>
<div id="transcript" aria-live="polite"></div>
</section>
<section id="view-story" hidden>
<div class="story-head">
<h1 id="story-title"></h1>
<button id="story-back">back to the table</button>
</div>
<div id="story"></div>
</section>
</main>
<aside id="play-aside">
@@ -123,29 +131,34 @@
<h2>gm notes</h2>
<span id="notes-state"></span>
</div>
<textarea id="gm-notes" placeholder="yours alone — never sent to the model"></textarea>
<textarea id="gm-notes" placeholder="yours alone -- never sent to the model"></textarea>
</section>
<section id="housekeeping">
<h2>housekeeping</h2>
<div id="hk-state"></div>
<button id="hk-run" hidden>close session &amp; housekeep</button>
<label id="hk-override-row"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
<button id="session-open" hidden>open session</button>
<button id="hk-replay" hidden title="run the housekeeper over the session log — nothing applied">dry-run housekeeping</button>
<button id="hk-run" hidden>stop session</button>
<label id="hk-override-row" hidden><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
<button id="session-open" hidden>start session</button>
<button id="hk-rerun" hidden title="a fresh pass over the finished predecessor -- the dormant session's rings are replaced">re-run housekeeping</button>
<button id="hk-replay" hidden title="run the housekeeper over a session log -- nothing applied">dry-run housekeeping</button>
<details id="hk-log" hidden><summary>session log</summary><pre id="hk-log-content"></pre></details>
<details id="hk-replay-log" hidden><summary>replay manifest</summary><pre id="hk-replay-content"></pre></details>
</section>
<section id="story-pane">
<h2>the story</h2>
<button id="story-link">read the story so far</button>
</section>
<section id="fork-pane">
<h2>fork</h2>
<p class="hint">a copy of this run — yours to continue</p>
<p class="hint">a copy of this run -- yours to continue</p>
<button id="fork-btn">fork this run</button>
</section>
<section id="models-pane" hidden></section>
</aside>
<footer>
<textarea id="gm-input" rows="2" placeholder="GM line — Enter sends, Shift+Enter newlines" disabled></textarea>
<span id="busy" hidden>her turn…</span>
<textarea id="gm-input" rows="2" placeholder="GM line -- Enter sends, Shift+Enter newlines" disabled></textarea>
<span id="busy" hidden>her turn...</span>
<button id="gm-send" disabled>send</button>
</footer>
@@ -155,7 +168,7 @@
<dialog id="ask-modal">
<h2>the player asks</h2>
<p id="ask-question"></p>
<textarea id="ask-answer" rows="3" placeholder="your ruling — Enter sends"></textarea>
<textarea id="ask-answer" rows="3" placeholder="your ruling -- Enter sends"></textarea>
<button id="ask-send">answer</button>
</dialog>
+4 -4
View File
@@ -1,20 +1,20 @@
// web/log.mjs — diagnostics: a rolling event log that survives
// web/log.mjs -- diagnostics: a rolling event log that survives
// refreshes.
//
// The api() choke point records every server call (status + duration),
// uncaught errors land here, and so do navigation ejections — the
// uncaught errors land here, and so do navigation ejections -- the
// "why did the app throw me out" history the ten-second banner loses.
// Kept in sessionStorage; the header's "log" button shows it.
import { $ } from './dom.mjs';
const log = [];
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt — start empty */ }
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt -- start empty */ }
export function logEvent(kind, text) {
log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
if (log.length > 300) log.splice(0, log.length - 300);
try { sessionStorage.setItem('diag', JSON.stringify(log)); } catch { /* storage full or blocked — the in-memory copy lives on */ }
try { sessionStorage.setItem('diag', JSON.stringify(log)); } catch { /* storage full or blocked -- the in-memory copy lives on */ }
}
function renderDiag() {
+5 -4
View File
@@ -1,8 +1,8 @@
// web/router.mjs — path routing and the view lifecycle.
// web/router.mjs -- path routing and the view lifecycle.
//
// Views register { el, enter, leave? } at boot (app.mjs). render()
// routes the path, then show() runs the previous view's leave and
// the next view's enter — each view owns its own teardown, so the
// the next view's enter -- each view owns its own teardown, so the
// router never has to know a pane's internals. Stale async work is
// dropped by the seq guard: a view captures seq at enter and checks
// it after every await.
@@ -32,6 +32,7 @@ export async function render() {
if (p === '/') name = 'home';
else if (p === '/new') name = 'new';
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) { name = 'setup'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
else return navigate('/');
if (!state.me) name = 'claim'; // signed out: every path leads to the claim
@@ -51,9 +52,9 @@ async function show(name, arg, seq) {
}
// a run that vanished under us (deleted, 404): leave loudly for home.
// render() clears the banner first — set it after the navigate.
// render() clears the banner first -- set it after the navigate.
export function runGone(id, from) {
navigate('/');
banner(`run ${id} is gone — deleted?`);
banner(`run ${id} is gone -- deleted?`);
logEvent('nav', `left ${from} for home: run gone (404)`);
}
+3 -3
View File
@@ -1,8 +1,8 @@
// web/state.mjs — the shared runtime state.
// web/state.mjs -- the shared runtime state.
//
// Deliberately small: auth (me), the render sequence (seq — the
// Deliberately small: auth (me), the render sequence (seq -- the
// async race guard; a view captures it at enter and checks it after
// every await), and the currently addressed run (runId — setup and
// every await), and the currently addressed run (runId -- setup and
// play both write here; saves address it). Everything else is
// module-local to the view or widget that owns it.
+30 -14
View File
@@ -1,4 +1,4 @@
/* rp-test SPA — dark, quiet, fiction-first. Three registers: speech is
/* rp-test SPA -- dark, quiet, fiction-first. Three registers: speech is
plain, narration is italic (rendered dimmer), OOC is boxed. Machinery
(tools, notes, deltas) stays small and muted. Home / setup views are
workbenches: cards, a file editor, read-only context. */
@@ -100,11 +100,11 @@ button.primary { border-color: var(--accent); color: var(--accent); }
main { grid-area: main; overflow-y: auto; padding: 18px 22px; }
h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); font-weight: normal; margin: 4px 0 14px; }
h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: normal; margin: 4px 0 14px; }
.hint { color: var(--dim); font-size: 13px; font-style: italic; }
/* cards: runs on home, packages on /new — real buttons, left-aligned */
/* cards: runs on home, packages on /new -- real buttons, left-aligned */
.card {
display: block;
width: 100%;
@@ -137,7 +137,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
#admin { max-width: 560px; margin-top: 28px; border-top: 1px solid var(--line); padding-top: 14px; }
#admin h2 {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
color: var(--dim); font-weight: normal;
}
#invite-code { font: 12px ui-monospace, Consolas, monospace; color: var(--accent); word-break: break-all; }
.admin-row { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); padding: 3px 0; }
@@ -157,6 +157,9 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
#fork-pane .hint { margin: 0 0 8px; }
#fork-pane button { width: 100%; }
#story-pane { margin-top: 22px; }
#story-pane button { width: 100%; }
#models-pane { margin-top: 22px; }
#models-pane .field { margin-bottom: 6px; }
#models-pane .field select { flex: 1; }
@@ -179,7 +182,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
}
#setup-vars h2, #setup-models h2 {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
color: var(--dim); font-weight: normal;
}
#setup-vars-state, .save-state { color: var(--dim); font-size: 12px; }
#setup-models .field select { flex: 1; }
@@ -220,12 +223,12 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
.file-item.current { border-color: var(--accent); }
.file-item.absent { color: var(--dim); font-style: italic; }
.file-item.ro { color: var(--dim); }
.file-item.dirty .file-dirty::after { content: "*"; color: var(--accent); }
.file-item.dirty .file-dirty { color: var(--accent); }
#setup-editor { display: flex; flex-direction: column; min-width: 0; }
#edit-stack { position: relative; flex: 1; min-height: 0; }
/* the highlight overlay: a pre behind a transparent-text textarea,
identical metrics, scroll-synced — sigils and vars light up in place */
identical metrics, scroll-synced -- sigils and vars light up in place */
#edit-hl, #setup-edit {
position: absolute;
inset: 0;
@@ -254,7 +257,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
/* --- transcript (play) --- */
.turn { margin: 0 0 20px; max-width: 760px; }
.turn .who { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; }
.turn .who { font-size: 11px; letter-spacing: 0.12em; color: var(--dim); margin-bottom: 3px; }
.turn.gm .who { color: var(--accent); }
.turn.player .who { color: var(--ok); }
@@ -279,7 +282,8 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
}
.machinery .head { color: var(--text); }
/* the opening beat, when the window opened but the beat never sent */
/* the dormant bar: the review window's banner over the carryover
preview, with the start button */
.beat {
display: flex; align-items: center; gap: 14px;
border: 1px solid var(--accent); border-radius: 6px;
@@ -288,7 +292,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
}
.beat button { margin-left: auto; }
/* the bundle: a collapsed card, per part — the system message is
/* the bundle: a collapsed card, per part -- the system message is
inspectable like the rest, read-only */
details.bundle {
margin: 14px 0; border: 1px solid var(--line); border-radius: 6px;
@@ -299,6 +303,18 @@ details.bundle pre { margin: 0; padding: 0 12px 10px; white-space: pre-wrap; fon
.error-line { color: var(--danger); }
/* --- the story view --- */
.story-head {
display: flex;
align-items: baseline;
gap: 14px;
margin-bottom: 14px;
}
.story-head h1 { margin: 0; }
#story { max-width: 760px; }
.session-break { margin: 26px 0 12px; border-top: 1px solid var(--line); }
/* --- aside (play) --- */
#play-aside {
@@ -314,7 +330,7 @@ body.play #play-aside { display: block; }
#play-aside h2 {
margin: 4px 0 8px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
color: var(--dim); font-weight: normal;
}
.pane-head { display: flex; align-items: baseline; gap: 8px; }
@@ -325,7 +341,7 @@ body.play #play-aside { display: block; }
#status.empty { color: var(--dim); font-style: italic; }
#agenda-pane { margin-top: 16px; }
#agenda { margin: 0; line-height: 1.5; }
#agenda { margin: 0; line-height: 1.5; white-space: pre-wrap; }
#agenda.empty { color: var(--dim); font-style: italic; }
.pane-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
.pane-editor-actions { display: flex; gap: 6px; margin-top: 6px; }
@@ -369,7 +385,7 @@ body.play footer { display: flex; }
#gm-send { padding: 5px 18px; }
#busy { color: var(--dim); font-size: 12px; font-style: italic; white-space: nowrap; align-self: center; }
/* in-page banner — replaces JS alert()/confirm() (they block the
/* in-page banner -- replaces JS alert()/confirm() (they block the
embedded pane); errors and notices land here instead */
#banner {
position: fixed; left: 50%; top: 12px; transform: translateX(-50%);
@@ -387,7 +403,7 @@ dialog {
min-width: 380px; max-width: 560px; padding: 18px 20px;
}
dialog::backdrop { background: rgba(0,0,0,0.6); }
dialog h2 { margin: 0 0 8px; font-size: 12px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); }
dialog h2 { margin: 0 0 8px; font-size: 12px; letter-spacing: 0.14em; color: var(--accent); }
dialog p { margin: 0 0 12px; }
dialog textarea { width: 100%; }
dialog button { margin-top: 10px; }
+23 -17
View File
@@ -1,11 +1,11 @@
// web/transcript.mjs — the transcript: register rendering and the
// 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
// delta tags on player turns are machinery, not prose -- they render
// as chips and pane state, mirroring the live-context policy.
import { $, el } from './dom.mjs';
@@ -32,8 +32,9 @@ function renderSpans(target, text) {
// 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.
function renderContent(target, text, { extract }) {
// delta tags on player turns always render as chips. Exported for
// the story view, which renders the same registers.
export function renderContent(target, text, { extract }) {
let body = String(text ?? '');
let status = null;
let conflict = null;
@@ -57,7 +58,7 @@ function renderContent(target, text, { extract }) {
const t = line.trim();
if (!t) { target.appendChild(document.createElement('br')); continue; }
if (t.startsWith('(')) {
if (t === '(') continue; // empty OOC — skip
if (t === '(') continue; // empty OOC -- skip
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
@@ -67,7 +68,7 @@ function renderContent(target, text, { extract }) {
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
// unknown or unbalanced tag -- keep it visible, styled as OOC
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
@@ -76,9 +77,9 @@ function renderContent(target, text, { extract }) {
}
const stars = (line.match(/\*/g) ?? []).length;
if (!narr && stars % 2 === 0) {
// balanced: spans carry the registers — mixed lines
// balanced: spans carry the registers -- mixed lines
// (`*foo* bar *baz*`), whole-line narration (`*she sleeps.*`),
// bold — all render correctly
// bold -- all render correctly
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
@@ -86,7 +87,7 @@ function renderContent(target, text, { extract }) {
continue;
}
if (!narr && !(t.startsWith('*') && !t.startsWith('**'))) {
// a stray unpaired * mid-line is not a block opener — render
// 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';
@@ -124,7 +125,9 @@ function renderContent(target, text, { extract }) {
}
// the entry walk. onConflict receives a conflict block found on a GM
// turn — the play view owns where it lands (the status pane).
// 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.
export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript');
t.textContent = '';
@@ -132,7 +135,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
const flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `session bundle — ${bundleParts.map((p) => p.part).join(', ')}`));
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));
@@ -153,17 +156,21 @@ export function renderTranscript(entries, { onConflict } = {}) {
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
// 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.reminder);
if (e === newest) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder — rides every GM turn'));
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
@@ -197,7 +204,6 @@ export function renderTranscript(entries, { onConflict } = {}) {
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}`));
@@ -206,11 +212,11 @@ export function renderTranscript(entries, { onConflict } = {}) {
}
function renderNote(e) {
let text = null;
if (e.kind === 'session') text = `session 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 status ${e.ok === false ? 'INGEST FAILED' : 'ingested'}${e.ok === false ? `: ${(e.detail ?? '').split('\n')[0]}` : ''}`;
if (e.kind === 'session') text = `session ${e.n} opened`;
else if (e.kind === 'ask') text = `ask_gm: ${e.question}`;
else if (e.kind === 'status') text = `status: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
else if (e.kind === 'agenda') text = `agenda: added ${JSON.stringify(e.applied?.added ?? [])}, dropped ${JSON.stringify(e.applied?.dropped ?? [])}`;
else if (e.kind === 'pick') text = `variant literature: ${e.count} offered, #${e.chosen + 1} picked`;
if (text) t.appendChild(el('div', 'machinery', text));
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
// web/view-claim.mjs — the invite claim: the only public screen.
// web/view-claim.mjs -- the invite claim: the only public screen.
// A single-use invite code is exchanged for a persistent token; the
// display name is a freeform label, collisions allowed.
@@ -16,7 +16,7 @@ export async function enter(arg, seq) {
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? 'this deployment has no users yet — the superuser invite is in state/bootstrap-invite.txt on the server'
? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-code').focus();
}
+19 -17
View File
@@ -1,4 +1,4 @@
// web/view-home.mjs — home: the run list (display names, live state,
// web/view-home.mjs -- home: the run list (display names, live state,
// the ownership garnish) plus the superuser admin (invites, users).
import { $, el } from './dom.mjs';
@@ -14,25 +14,25 @@ export async function enter(arg, seq) {
const list = $('run-list');
list.textContent = '';
if (!runs.length) {
list.appendChild(el('div', 'hint', 'no runs yet — start one from a package'));
list.appendChild(el('div', 'hint', 'no runs yet -- start one from a package'));
}
for (const r of runs) {
const mine = state.me && r.owner === state.me.id;
const card = el('button', 'card run-card');
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta — chrome, never model-facing
// started-or-forked rides the meta -- chrome, never model-facing
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.models?.player ? ` · ${r.models.player}` : ''}`));
card.appendChild(el('span', 'card-meta', `${r.package} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${r.models?.player ? ` \u00b7 ${r.models.player}` : ''}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
// another user's draft is read-only: the play view says so; your own opens the editor
card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
card.addEventListener('click', () => navigate(r.phase === 'dormant' && r.sessions === 1 && mine ? `/runs/${r.id}/setup` : `/runs/${r.id}`));
list.appendChild(card);
}
await renderAdmin(seq);
}
const ownershipTag = (r, mine) =>
(mine ? ' · yours' : r.owner == null ? ' · ownerless' : ` · ${r.ownerName ?? 'someone'}'s`);
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
function fmtUnix(t) {
@@ -41,16 +41,18 @@ function fmtUnix(t) {
}
function runStateText(r) {
if (!r.lastSession) return 'draft — not started yet';
if (r.open) return `session open${r.pendingAsk ? ' — waiting for your answer' : ''}`;
if (r.lastSession !== r.lastHousekept) return 'session closed, never housekept';
return 'session closed';
if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`;
if (r.phase === 'dormant') {
if (r.sessions === 1) return 'draft -- not started yet';
return r.ready === false ? 'dormant -- housekeeping pending' : `dormant -- session ${r.sessions} waits`;
}
return 'no sessions';
}
function runStateClass(r) {
if (!r.lastSession) return 'draft';
if (r.pendingAsk) return 'attention';
if (r.open) return 'ok';
if (r.lastSession !== r.lastHousekept) return 'attention';
if (r.phase === 'live') return 'ok';
if (r.phase === 'dormant' && r.sessions > 1 && r.ready === false) return 'attention';
if (r.sessions === 1 && r.phase === 'dormant') return 'draft';
return '';
}
@@ -64,7 +66,7 @@ async function renderAdmin(seq) {
invList.textContent = '';
for (const i of inv.invites) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} — ${i.state}`));
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} -- ${i.state}`));
if (i.state === 'unclaimed') {
const b = el('button', null, 'revoke');
b.addEventListener('click', async () => {
@@ -78,10 +80,10 @@ async function renderAdmin(seq) {
userList.textContent = '';
for (const u of us.users) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `${u.name} · ${u.id}${u.superuser ? ' · op' : ''}`));
row.appendChild(el('span', 'grow', `${u.name} \u00b7 ${u.id}${u.superuser ? ' \u00b7 op' : ''}`));
if (u.id !== state.me.id) {
const b = el('button', 'danger', 'revoke');
// revocation destroys the identity — two-click armed, like
// revocation destroys the identity -- two-click armed, like
// every destructive act
armedButton(b, {
label: 'revoke',
@@ -101,7 +103,7 @@ $('new-run-btn').addEventListener('click', () => navigate('/new'));
$('invite-mint').addEventListener('click', async () => {
try {
const r = await api('/invites', { method: 'POST', body: {} });
$('invite-code').textContent = r.code; // shown once — it is never listed again
$('invite-code').textContent = r.code; // shown once -- it is never listed again
render();
} catch (e) {
banner(e.message);
+7 -7
View File
@@ -1,5 +1,5 @@
// web/view-new.mjs — new run: the package picker, then the naming
// form — the package display name plus the main character's name,
// web/view-new.mjs -- new run: the package picker, then the naming
// form -- the package display name plus the main character's name,
// rolled from the dictionary, unused by any run. Runs of the same
// package need distinct pc names.
@@ -9,7 +9,7 @@ import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
let pkg = null; // the picked package — the view owns it
let pkg = null; // the picked package -- the view owns it
export async function enter(arg, seq) {
$('package-pick').hidden = false;
@@ -22,8 +22,8 @@ export async function enter(arg, seq) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} · ${origin} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete — missing backdrop or character'));
card.appendChild(el('span', 'card-meta', `${p.name} \u00b7 ${origin} \u00b7 records ${p.records ? 'on' : 'off'} \u00b7 carryover ${p.carryover ? 'yes' : 'no'} \u00b7 memory ${p.memory ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete -- missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
}
@@ -33,10 +33,10 @@ async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start — ${p.display}`;
$('create-title').textContent = `start -- ${p.display}`;
$('create-name').value = p.display;
$('create-pc').value = '';
$('create-pc').placeholder = 'rolling a name…';
$('create-pc').placeholder = 'rolling a name...';
$('create-pc').focus();
const roll = await api('/names').catch(() => null);
if (state.view !== 'new' || $('create-form').hidden) return;
+106 -78
View File
@@ -1,5 +1,5 @@
// web/view-play.mjs — the play surface: the transcript, her two
// blocks (the status pane and the agenda pane — one widget, two
// web/view-play.mjs -- the play surface: the transcript, her two
// blocks (the status pane and the agenda pane -- one widget, two
// instances), the GM notepad, housekeeping (close session, the
// dry-run replay), fork, and the input line.
@@ -19,7 +19,7 @@ const statusPane = paneEditor({
section: 'status-pane',
body: 'status',
empty: 'a blank sheet',
placeholder: 'one description per line — empty clears the status',
placeholder: 'one description per line -- empty clears the status',
rows: 5,
format: (items) => items.join(', '), // compact, mirroring the <status> wire format
toText: (items) => items.join('\n'),
@@ -32,10 +32,11 @@ const agendaPane = paneEditor({
section: 'agenda-pane',
body: 'agenda',
empty: 'a clear head',
placeholder: 'one item per line, top first — empty clears the agenda',
placeholder: 'one item per line, top first -- empty clears the agenda',
rows: 4,
// the queue numbered from the top, exactly as the model cites it
format: (items) => items.map((d, i) => `${i}. ${d}`).join('; '),
// the pane renders bullets; the wire keeps the numbered form the
// model cites (drops reference the indexes it was shown)
format: (items) => items.map((d) => `- ${d}`).join('\n'),
toText: (items) => items.join('\n'),
fromText: (text) => text
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
@@ -69,55 +70,65 @@ async function refreshPlay(id, seq) {
detail = await api(`/runs/${id}`);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
return banner(`could not reach the server: ${e.message}`); // stay put — transient
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
const mine = state.me && detail.run.owner === state.me.id;
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
setSessionInfo(`${detail.display} — a draft, not yours`);
setSessionInfo(`${detail.display} -- a draft, not yours`);
$('transcript').textContent = '';
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft — fork it to make it yours and edit it'));
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft -- fork it to make it yours and edit it'));
return;
}
setSessionInfo((detail.open
? `${detail.display} — session ${detail.session}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: `${detail.display} — no open session`)
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating'));
setSessionInfo((detail.phase === 'live'
? `${detail.display} -- session ${detail.session}${detail.pendingAsk ? ' -- waiting for your answer' : ''}`
: `${detail.display} -- session ${detail.sessions} dormant`)
+ (mine ? '' : detail.run.owner == null ? ' -- ownerless' : ' -- spectating'));
renderMeter(detail);
statusPane.set(detail.status);
agendaPane.set(detail.agenda);
$('conflict').hidden = true;
// spectator mode: read everything, mutate nothing — the fork is the
// spectator mode: read everything, mutate nothing -- the fork is the
// way in. Ownerless runs are spectators for everyone alike.
statusPane.setEditable(mine);
agendaPane.setEditable(mine);
$('gm-notes').readOnly = !mine;
let beatNeeded = false;
if (detail.open) {
const session = await api(`/runs/${id}/session`);
if (detail.phase === 'live') {
// the table: the live session's projection -- thinking never
// crosses the wire, variant turns carry only the picked one (the
// raw /session is the audit surface, one fetch away)
const session = await api(`/runs/${id}/table`);
if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict });
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
} else if (detail.phase === 'dormant') {
// the review window: the carryover is the preview of the next
// contwin's opening, rendered exactly as the table will hold it
const carry = await api(`/runs/${id}/carryover`).catch(() => null);
if (seq !== state.seq) return;
$('transcript').textContent = '';
if (carry && carry.entries.length) renderTranscript(carry.entries, {});
else $('transcript').appendChild(el('div', 'hint', 'nothing carries -- the next session opens on the bundle alone'));
if (mine) $('transcript').prepend(dormantBar(detail, carry));
} else {
$('transcript').textContent = '';
}
// the opening beat, if start was interrupted or the session was opened directly
if (beatNeeded) await offerBeat(id, seq);
// controls
$('session-open').hidden = detail.open || !mine;
$('hk-run').hidden = !detail.open || !mine;
$('hk-replay').hidden = !detail.lastSession || !mine; // any session log is replayable, by the owner
setInput(detail.open && !detail.pendingAsk && mine);
$('session-open').hidden = detail.phase !== 'dormant' || !mine;
if (!$('session-open').hidden) $('session-open').textContent = `start session ${detail.sessions}`;
$('hk-run').hidden = detail.phase !== 'live' || !mine;
$('hk-rerun').hidden = !(detail.phase === 'dormant' && detail.sessions >= 2) || !mine;
$('hk-replay').hidden = !((detail.phase === 'live') || (detail.phase === 'dormant' && detail.sessions >= 2)) || !mine;
$('hk-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false) || !mine;
setInput(detail.phase === 'live' && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
? 'GM line — Enter sends, Shift+Enter newlines'
: 'spectating — fork this run to continue it as yours';
? 'GM line -- Enter sends, Shift+Enter newlines'
: 'spectating -- fork this run to continue it as yours';
// models: the owner's per-run overrides
$('models-pane').hidden = !mine;
@@ -127,7 +138,7 @@ async function refreshPlay(id, seq) {
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
}
// pending ask: the modal re-presents after a refresh — the owner's
// pending ask: the modal re-presents after a refresh -- the owner's
// to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
@@ -142,10 +153,24 @@ async function refreshPlay(id, seq) {
if (seq !== state.seq) return;
renderHk(hk);
// the GM's notepad — skip the reload if a save failed (dirty wins)
// the GM's notepad -- skip the reload if a save failed (dirty wins)
await loadNotes(id, seq);
}
// the dormant bar: the review window's banner over the carryover
// preview, with the one button that leaves it
function dormantBar(detail, carry) {
const bar = el('div', 'beat');
const ending = carry?.ends === 'gm'
? 'the carryover ends on your turn -- start sends it automatically as her cue'
: 'the table waits for your input once the session is live';
bar.appendChild(el('span', null, `session ${detail.sessions} is dormant -- the review window. ${ending}`));
const b = el('button', 'primary', `start session ${detail.sessions}`);
b.addEventListener('click', startRun);
bar.appendChild(b);
return bar;
}
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
@@ -156,7 +181,7 @@ function showConflict(text) {
//
// A debounced save (1s after the last keystroke, immediate on blur),
// flushed when leaving the play view or switching runs. gm.md never
// reaches any model — this is the GM's own notes.
// reaches any model -- this is the GM's own notes.
let notesTimer = null;
let notesDirty = false;
@@ -189,29 +214,27 @@ async function saveNotes() {
}
}
async function offerBeat(id, seq) {
let hasTurn0 = true;
// start: the dormant session goes live. If the carryover ends on a GM
// turn, the server sends it automatically as her cue.
async function startRun() {
const override = $('hk-override').checked;
hideBanner();
setBusy(true, 'starting...');
try {
const files = await api(`/runs/${id}/files`);
if (seq !== state.seq) return;
hasTurn0 = files.files['turn-0.md']?.exists === true;
} catch { /* try the endpoint anyway */ }
if (!hasTurn0) return;
const bar = el('div', 'beat');
bar.appendChild(el('span', null, 'the session is open; the opening beat has not been sent'));
const b = el('button', 'primary', 'send the opening beat');
b.addEventListener('click', async () => {
setBusy(true);
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
const r = await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
$('hk-override').checked = false;
if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue');
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
banner(`${e.message}\n${e.detail.hint}`, 'info');
} else if (e.status === 422 && e.detail?.errors) {
banner(`the carryover did not pass the start lint:\n${e.detail.errors.join('\n')}`);
} else {
banner(e.message);
}
setBusy(false);
render();
});
bar.appendChild(b);
$('transcript').prepend(bar);
}
setBusy(false);
render();
}
function setHk(stateText, cls) {
@@ -222,16 +245,18 @@ function setHk(stateText, cls) {
function renderHk(hk) {
if (hk.state === 'running') {
setHk('housekeeping…', '');
setHk(hk.phase === 'rerun' ? 're-running housekeeping...' : 'stopping & housekeeping...', '');
startPoll();
return;
}
stopPoll();
if (hk.state === 'applied') {
setHk(`applied — session ${hk.session ?? ''}\nnext session open`, 'applied');
loadLog(); // idempotent — also covers a refresh while applied
setHk(`applied -- session ${hk.session} housekept\nsession ${hk.target} is ready to start`, 'applied');
loadLog(); // idempotent -- also covers a refresh while applied
} else if (hk.state === 'pending') {
setHk(`housekeeping of session ${hk.session} never finished -- re-run it, apply a manifest by hand, or start with the override`, 'rejected');
} else if (hk.state === 'rejected') {
setHk(`rejected — held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
setHk(`rejected -- held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
} else {
setHk('idle', '');
}
@@ -275,11 +300,11 @@ async function sendAnswer() {
render();
}
// fork: a copy of this run under you — any run, anyone's, including
// fork: a copy of this run under you -- any run, anyone's, including
// yours. Lands you in the fork.
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking…');
setBusy(true, 'forking...');
try {
const r = await api(`/runs/${state.runId}/fork`, { method: 'POST', body: {} });
setBusy(false);
@@ -291,26 +316,10 @@ async function forkRun() {
}
}
async function openSession() {
const override = $('hk-override').checked;
hideBanner();
try {
await api(`/runs/${state.runId}/sessions`, { 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);
}
}
render();
}
// dry-run: the housekeeper reads the session log, the manifest lands
// in the pane — nothing applied, the session stays open
// in the pane -- nothing applied, the session stays open
async function replayHousekeeping() {
setBusy(true, 'the housekeeper reads…');
setBusy(true, 'the housekeeper reads...');
try {
const r = await api(`/runs/${state.runId}/housekeeping/replay`, { method: 'POST', body: {} });
$('hk-replay-content').textContent = r.parsed
@@ -355,13 +364,31 @@ async function loadLog() {
// --- wiring ---
armedButton($('hk-run'), {
label: 'close session & housekeep',
confirm: 'sure? click again to close & housekeep',
label: 'stop session',
confirm: 'sure? click again to stop, carry & housekeep',
fire: async () => {
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('housekeeping…', '');
setHk('stopping & housekeeping...', '');
startPoll();
} catch (e) {
banner(e.message);
}
render();
},
});
// the re-run: a fresh housekeeping pass over the finished predecessor,
// rebased -- the dormant session's rings are replaced, hand edits and all
armedButton($('hk-rerun'), {
label: 're-run housekeeping',
confirm: 'sure? click again -- the dormant session\'s rings are replaced, hand edits included',
fire: async () => {
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('re-running housekeeping...', '');
startPoll();
} catch (e) {
banner(e.message);
@@ -378,9 +405,10 @@ $('ask-send').addEventListener('click', sendAnswer);
$('ask-answer').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
});
$('session-open').addEventListener('click', openSession);
$('session-open').addEventListener('click', startRun);
$('hk-replay').addEventListener('click', replayHousekeeping);
$('fork-btn').addEventListener('click', forkRun);
$('story-link').addEventListener('click', () => { if (state.runId) navigate(`/runs/${state.runId}/story`); });
$('gm-notes').addEventListener('input', notesInput);
$('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
+59 -43
View File
@@ -1,21 +1,23 @@
// web/view-setup.mjs — the draft editor: the full assembly in bundle
// order (the repo-fed prompts read-only, the run's craft editable,
// config read-only), the prompt-declared $TOKEN inputs, per-run
// models, and the two exits — save as package (publishes it) or
// start (opens the session, sends turn-0).
// web/view-setup.mjs -- the dormancy editor: the full assembly in
// bundle order (the repo-fed prompts read-only, the session's craft
// editable while dormant), the prompt-declared $TOKEN inputs, per-run
// models, and the exits -- save as package (a draft act, publishes
// it) or start (the dormant session goes live; a carryover ending on
// a GM turn sends automatically as her cue).
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs';
import { logEvent } from './log.mjs';
import { armedButton, modelList, modelsBox } from './widgets.mjs';
// one list, in bundle-assembly order: the repo-fed system message
// parts (read-only — the user should understand how the model is
// prompted), the craft tail and GM messages (editable), then the
// initial state, then run config (read-only). Everything the run
// sends, nothing it doesn't.
// parts (read-only -- the user should understand how the model is
// prompted), the craft tail and GM messages (editable while the
// session is dormant), then the opening material, then run config
// (read-only). Everything the session sends, nothing it doesn't.
const EDIT_LIST = [
{ name: 'system.md', mode: 'ro', source: 'repo' },
{ name: 'invariants.md', mode: 'ro', source: 'repo' },
@@ -23,20 +25,20 @@ const EDIT_LIST = [
{ name: 'handbook.md', mode: 'rw', source: 'run' },
{ name: 'backdrop.md', mode: 'rw', source: 'run' },
{ name: 'character.md', mode: 'rw', source: 'run' },
{ name: 'seed.json', mode: 'rw', source: 'run' }, // the rings it seeds — turn-0 wakes into them
{ name: 'turn-0.md', mode: 'rw', source: 'run' },
{ name: 'memory.json', mode: 'ro', source: 'run' }, // the session-0 manifest, applied at creation -- provenance
{ name: 'carryover.jsonl', mode: 'rw', source: 'run' }, // the opening log -- raw events, linted on save
{ name: 'settings.json', mode: 'ro', source: 'run' },
{ name: 'run.json', mode: 'ro', source: 'run' },
];
// the editor's working set — module-local, reset on every enter
// the editor's working set -- module-local, reset on every enter
let files = null; // { name: { content, exists } }
let drafts = {}; // unsaved edits by file name
let currentFile = null;
let fileSpecs = {};
let repoPrompts = {};
const models = modelsBox('setup-models', { title: 'models — per-run, over the deployment defaults' });
const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' });
export async function enter(id, seq) {
state.runId = id;
@@ -51,11 +53,11 @@ export async function enter(id, seq) {
]);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
return banner(`could not reach the server: ${e.message}`); // stay put — transient
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
if (!detail.draft) return navigate(`/runs/${id}`); // started runs live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only — fork to edit
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only -- fork to edit
files = filesResp.files;
repoPrompts = {
@@ -64,14 +66,20 @@ export async function enter(id, seq) {
'reminder.md': prompts.reminder ?? '',
};
$('setup-title').textContent = detail.display;
$('setup-state').textContent = `${detail.run.package} · ${id} — draft; edits land when the session opens`;
$('setup-state').textContent = detail.draft
? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts`
: `${detail.run.package} \u00b7 ${id} -- session ${detail.sessions} dormant, the review window`;
$('setup-start').disabled = false;
$('setup-start').textContent = 'start';
$('setup-start').textContent = `start session ${detail.sessions}`;
// draft-only affordances: deletion and save-as-package (a package is
// a starting point, never a snapshot)
$('setup-delete').hidden = !detail.draft;
$('setup-savepkg').hidden = !detail.draft;
// prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, files);
let currentVars = {};
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings — empty vars */ }
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ }
const varsList = $('setup-vars-list');
varsList.textContent = '';
$('setup-vars').hidden = !vars.length;
@@ -97,11 +105,14 @@ export async function enter(id, seq) {
const runFile = files[e.name];
const spec = {
...e,
// the API carries the phase's truth: rw only while dormant, and
// a continuation carryover is conversation -- read-only
mode: e.source === 'repo' ? 'ro' : (runFile?.mode ?? e.mode),
exists: e.source === 'repo' ? true : !!runFile?.exists,
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
};
fileSpecs[e.name] = spec;
const item = el('button', `file-item${e.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
const item = el('button', `file-item${spec.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
item.appendChild(el('span', 'file-name', e.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => selectFile(e.name));
@@ -113,12 +124,14 @@ export async function enter(id, seq) {
}
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or run copy) becomes a fillable input in setup
// file (repo-fed or the session's own, the carryover included -- it
// expands at start like every authored surface) becomes a fillable
// input in setup
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
files['handbook.md']?.content,
files['backdrop.md']?.content, files['character.md']?.content, files['turn-0.md']?.content,
files['backdrop.md']?.content, files['character.md']?.content, files['carryover.jsonl']?.content,
];
const found = new Set();
for (const t of texts) {
@@ -160,7 +173,7 @@ function selectFile(f) {
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain — @ syntax is not owned here
// stay plain -- @ syntax is not owned here
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
@@ -187,7 +200,11 @@ function markNav() {
const items = $('setup-files').children;
for (const item of items) {
const name = item.querySelector('.file-name').textContent.replace(' (new)', '');
item.classList.toggle('dirty', drafts[name] !== undefined);
const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15)
item.querySelector('.file-dirty').textContent = dirty ? '*' : '';
item.classList.toggle('current', name === currentFile);
}
}
@@ -221,18 +238,18 @@ async function saveDirty() {
markNav();
}
// save the run's craft as a new user package — published to every user
// save the run's craft as a new user package -- published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true;
$('savepkg-state').textContent = 'saving…';
$('savepkg-state').textContent = 'saving...';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved — ${r.package.id}`;
$('savepkg-state').textContent = `saved -- ${r.package.id}`;
$('savepkg-name').value = '';
} catch (e) {
banner(e.message);
@@ -244,38 +261,37 @@ async function saveAsPackage() {
async function startRun() {
const id = state.runId;
const btn = $('setup-start');
// the prompts' own inputs must be filled — the guard at session-open
// is the backstop, not the first line of defense
// the prompts' own inputs must be filled -- the guard at start is
// the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) {
if (!v) {
banner(`$${tok} is unfilled — a prompt declares it, the run needs it`);
banner(`$${tok} is unfilled -- a prompt declares it, the run needs it`);
return;
}
}
btn.disabled = true;
btn.textContent = 'starting…';
btn.textContent = 'starting...';
try {
await saveVars();
await saveDirty();
} catch (e) {
banner(`did not start — ${e.message}`);
banner(`did not start -- ${e.message}`);
btn.disabled = false;
btn.textContent = 'start';
return;
}
let opened = false;
try {
await api(`/runs/${id}/sessions`, { method: 'POST', body: {} });
opened = true;
const r = await api(`/runs/${id}/sessions`, { method: 'POST', body: {} });
if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue');
} catch (e) {
banner(e.message);
}
if (opened && files['turn-0.md']?.exists) {
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
banner(`${e.message} — the beat can be sent from the play view`);
if (e.status === 422 && e.detail?.errors) {
banner(`the carryover did not pass the start lint:\n${e.detail.errors.join('\n')}`);
} else {
banner(e.message);
}
btn.disabled = false;
btn.textContent = 'start';
return;
}
navigate(`/runs/${id}`);
}
@@ -283,7 +299,7 @@ async function startRun() {
// --- wiring ---
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side — stories are deleted by hand.
// A played run refuses server-side -- stories are deleted by hand.
armedButton($('setup-delete'), {
label: 'delete draft',
confirm: 'sure? click again to delete',
+56
View File
@@ -0,0 +1,56 @@
// web/view-story.mjs -- the story: the whole deliverable, read-only.
//
// Every non-dropped literature turn from turn-0 to the last
// recorded, across all sessions in order -- the reading surface the
// adjudication review reads ("machinery seams show as prose seams").
// OOC, tools, verbs, thinking, rings: all out, by ruling; carried
// copies never re-render, each turn appears once from its home
// session. Readable by anyone signed in -- spectators read
// everything.
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs';
import { renderContent } from './transcript.mjs';
let storyRun = null;
export async function enter(id, seq) {
storyRun = id;
let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
if (e.status === 404) return runGone(id, 'the story view');
return banner(`could not reach the server: ${e.message}`);
}
if (seq !== state.seq) return;
$('story-title').textContent = `${detail.display} -- the story`;
const story = await api(`/runs/${id}/story`).catch(() => null);
if (seq !== state.seq) return;
if (!story) return banner('the story could not be read');
const box = $('story');
box.textContent = '';
if (!story.sessions.length) {
box.appendChild(el('div', 'hint', 'nothing has happened yet -- the story begins at the table'));
return;
}
for (const [si, s] of story.sessions.entries()) {
if (si > 0) box.appendChild(el('div', 'session-break'));
for (const turn of s.turns) {
const d = el('div', `turn ${turn.who}`);
d.appendChild(el('div', 'who', turn.who === 'gm' ? 'GM' : 'player'));
const body = el('div');
d.appendChild(body);
renderContent(body, turn.text, { extract: turn.who === 'gm' });
box.appendChild(d);
}
}
}
// wired once at module load: the back button returns to the table
$('story-back').addEventListener('click', () => {
if (storyRun) navigate(`/runs/${storyRun}`);
});
+9 -9
View File
@@ -1,9 +1,9 @@
// web/widgets.mjs — the small factories the views share.
// web/widgets.mjs -- the small factories the views share.
//
// Three patterns that were hand-copied per use, now one each:
// - armedButton: the two-click confirm (no JS confirm() — it blocks
// - armedButton: the two-click confirm (no JS confirm() -- it blocks
// the embedded pane; every destructive act is armed instead)
// - paneEditor: the status/agenda pattern — a body line, an edit
// - paneEditor: the status/agenda pattern -- a body line, an edit
// button, an inline editor; the section shell stays in index.html
// - modelsBox: the per-run player/housekeeper selects over the
// upstream listing; setup and the play aside each carry one
@@ -14,7 +14,7 @@ import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { render } from './router.mjs';
// two-click confirm — the second click within 5s fires; anything
// two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
export function armedButton(btn, { label, confirm, fire }) {
let timer = null;
@@ -32,7 +32,7 @@ export function armedButton(btn, { label, confirm, fire }) {
}
// a pane: body line + edit button + inline editor. save(items)
// resolves on success and throws on failure — a failed save keeps
// resolves on success and throws on failure -- a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the
// spectator state: no edit button, an open editor cancels.
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
@@ -80,7 +80,7 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
await save(next);
} catch (e) {
banner(e.message);
return; // stay in the editor — nothing was changed
return; // stay in the editor -- nothing was changed
}
items = next;
cancel();
@@ -99,7 +99,7 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
};
}
// the upstream model listing, fetched once per session — a live
// the upstream model listing, fetched once per session -- a live
// /models call every render would hammer the endpoint for a list
// that rarely changes
let cachedModels = null;
@@ -118,7 +118,7 @@ function fillSelect(sel, current, list, def) {
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` — ${def}` : ' (unset)'}`);
mk('', `deployment default${def ? ` -- ${def}` : ' (unset)'}`);
const opts = [...list];
if (current && !opts.includes(current)) opts.push(current);
for (const m of opts) mk(m, m);
@@ -126,7 +126,7 @@ function fillSelect(sel, current, list, def) {
}
// the models box: player/housekeeper selects + save, posting the
// per-run overrides. The mount keeps its id — the CSS panels it.
// per-run overrides. The mount keeps its id -- the CSS panels it.
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';