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
+310 -127
View File
@@ -1,10 +1,10 @@
// server/main.mjs — entry + REST spine.
// server/main.mjs -- entry + REST spine.
//
// Synchronous JSON over HTTP; the SPA and curl are both just clients.
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// session back from the jsonl — the log is the truth, the context is a
// session back from the jsonl -- the log is the truth, the context is a
// view.
//
// usage: node server/main.mjs [--mock]
@@ -17,7 +17,8 @@ import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
import * as bundle from './bundle.mjs';
import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs';
import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
import { effectiveContents } from './variants.mjs';
import { gmTurn, answerAsk, openingCall, HttpError } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
@@ -26,7 +27,7 @@ const MOCK = process.argv.includes('--mock');
const CONFIG_PATH = path.join(ROOT, 'server.json');
if (!fs.existsSync(CONFIG_PATH)) {
console.error('no server.json — copy server.example.json and set your key in it (or via apiKeyEnv)');
console.error('no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)');
process.exit(1);
}
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
@@ -36,7 +37,7 @@ const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), r
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, turn0, the
// Serializes every async mutation span (turn, ask, start, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (status-set, file writes) need no lock: they
@@ -53,22 +54,29 @@ ctx.enqueue = (runId, fn) => {
const boot = users.bootstrap();
if (boot?.code) {
console.log(`fresh deployment — the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`);
console.log(`fresh deployment -- the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`);
console.log(` ${boot.code}`);
} else if (boot?.reused) {
console.log(`fresh deployment — the superuser invite waits at ${path.relative(ROOT, users.bootstrapFile)}`);
console.log(`fresh deployment -- the superuser invite waits at ${path.relative(ROOT, users.bootstrapFile)}`);
}
// --- boot-rebuild ------------------------------------------------------------
// --- boot --------------------------------------------------------------------
//
// The log is the truth, the context is a view. A stop that died in
// flight resumes first (every step idempotent); then every live
// session reopens from its jsonl.
if (fs.existsSync(path.join(ROOT, 'runs'))) {
for (const d of fs.readdirSync(path.join(ROOT, 'runs'), { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
if (!fs.existsSync(path.join(ROOT, 'runs', d.name, 'run.json'))) continue;
const latest = session.latestSession(d.name);
if (latest && latest !== session.lastHousekept(d.name)) {
ctx.sessions.set(d.name, session.loadSession(d.name, latest));
const stalled = session.findStalledStop(d.name);
if (stalled) {
session.stopSession(d.name, stalled.from);
console.log(`boot: resumed the interrupted stop of session ${stalled.from} in '${d.name}' -- housekeeping is pending, re-run it`);
}
const live = session.liveSession(d.name);
if (live != null) ctx.sessions.set(d.name, session.loadSession(d.name, live));
}
}
@@ -133,7 +141,7 @@ function serveStatic(pathname, res) {
if (!rel) rel = 'index.html';
const file = path.resolve(WEB_DIR, rel);
if (!file.startsWith(WEB_DIR + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
// SPA fallback: client-side routes are extensionless paths —
// SPA fallback: client-side routes are extensionless paths --
// serve the shell; anything that looks like a file stays a 404
if (path.extname(rel)) { send(res, 404, { error: `no such file: ${rel}` }); return; }
const shell = fs.readFileSync(path.join(WEB_DIR, 'index.html'));
@@ -150,12 +158,12 @@ function serveStatic(pathname, res) {
//
// Identity is a bearer token (server/users.mjs). Two routes are
// public: reading your own session (null when signed out) and
// claiming an invite. Everything else — reads included — requires a
// claiming an invite. Everything else -- reads included -- requires a
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
route('GET', '/api/session', async ({ user }) => ({
// the public shape only — the stored row (token hash) never leaves
// the public shape only -- the stored row (token hash) never leaves
user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null,
fresh: users.userCount() === 0,
}), { public: true });
@@ -165,13 +173,13 @@ route('POST', '/api/claim', async ({ body }) => {
return { token: r.token, user: r.user };
}, { public: true });
// superuser: mint an invite — the code is returned once, never stored
// superuser: mint an invite -- the code is returned once, never stored
route('POST', '/api/invites', async ({ user }) => {
requireSuperuser(user);
return users.mintInvite(user.id);
});
// superuser: the invite ledger, hashes only — codes are never listed
// superuser: the invite ledger, hashes only -- codes are never listed
route('GET', '/api/invites', async ({ user }) => {
requireSuperuser(user);
const list = users.listInvites().map((i) => ({
@@ -196,7 +204,7 @@ route('GET', '/api/users', async ({ user }) => {
});
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched — the record of ownership
// runs and packages stay on disk untouched -- the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open sessions close.
route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
@@ -218,17 +226,17 @@ function requireSuperuser(user) {
// absent. The API never exposes a dangling id.
const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null);
// ownership: every GM action — every mutation, every model call — is
// ownership: every GM action -- every mutation, every model call -- is
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
// one uniform state: readable by all, forkable, never re-claimed.
function requireOwner(user, runId) {
bundle.requireRun(runId); // 404 when it doesn't exist
const meta = bundle.runMeta(runId) ?? {};
if (resolveOwner(meta.owner) == null) {
throw new HttpError(403, `run '${runId}' is ownerless — fork it to make it yours`);
throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`);
}
if (meta.owner !== user.id) {
throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s — fork it to continue as yours`);
throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`);
}
return meta;
}
@@ -237,8 +245,8 @@ function requireOwner(user, runId) {
route('GET', '/api', async () => ({
service: 'rp-test', mock: MOCK, openSessions: ctx.sessions.size,
// the live session inventory — debugging state divergence at a glance
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
// the live session inventory -- debugging state divergence at a glance
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, session: s.n, pendingAsk: !!s.pendingAsk })),
}));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
@@ -255,7 +263,7 @@ route('GET', '/api/packages', async () => {
});
// save a run's craft as a new user package, published to every user
// (gm.md included — saving is the act of publishing). The pc never
// (gm.md included -- saving is the act of publishing). The pc never
// rides: the next create asks for one.
route('POST', '/api/packages', async ({ body, user }) => {
const from = String(body.from ?? '').trim();
@@ -269,7 +277,7 @@ route('POST', '/api/packages', async ({ body, user }) => {
});
// the repo-fed prompts, read-only: per-project opening + guards,
// substrate invariants, and the per-turn reminder — never copied into
// substrate invariants, and the per-turn reminder -- never copied into
// a run, so the editor shows them as context, not as something to edit
route('GET', '/api/prompts', async () => {
const readOpt = (f) => (fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), 'utf8').trim() : null);
@@ -281,18 +289,16 @@ route('GET', '/api/prompts', async () => {
});
// the clerk's list, enriched with what the server already knows: the
// open session, the pending ask, and the housekeeping bookkeeping. A
// run with no sessions is a draft — created, never started.
// live session, the pending ask, and the phase bookkeeping. A run's
// state is its latest session's -- live while one plays, else dormant
// (the review window); a draft is a dormant session one.
route('GET', '/api/runs', async () => {
const runs = clerkRawJson('runs');
for (const r of runs) {
const s = ctx.sessions.get(r.id);
r.open = !!s;
r.session = s?.stamp ?? null;
r.fresh = s?.fresh ?? false;
r.session = s?.n ?? null;
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
r.lastHousekept = session.lastHousekept(r.id);
r.owner = resolveOwner(r.owner);
r.ownerName = r.owner == null ? null : users.userName(r.owner);
}
@@ -305,10 +311,10 @@ route('GET', '/api/runs', async () => {
route('POST', '/api/runs', async ({ body, user }) => {
const pkg = String(body.package ?? '').trim();
const pc = String(body.pc ?? '').trim();
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages');
if (!pc) throw new HttpError(400, 'pc is required — the main character\'s name, distinct per package');
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug -- see GET /api/packages');
if (!pc) throw new HttpError(400, 'pc is required -- the main character\'s name, distinct per package');
const name = body.name === undefined ? undefined : String(body.name);
const r = clerkRaw('--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
const run = JSON.parse(r.out);
return { run, dir: `runs/${run.id}` };
@@ -330,6 +336,9 @@ route('GET', '/api/runs/:id', async ({ params }) => {
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
const latest = session.latestSession(id);
const sm = latest == null ? {} : session.sessionMeta(id, latest);
const phase = s ? 'live' : (sm.phase ?? null);
return {
run: {
id,
@@ -343,10 +352,11 @@ route('GET', '/api/runs/:id', async ({ params }) => {
},
display: bundle.runDisplay(id),
open: !!s,
draft: session.latestSession(id) === null,
lastSession: session.latestSession(id),
session: s?.stamp ?? null,
fresh: s?.fresh ?? false,
phase,
session: s?.n ?? null,
sessions: latest ?? 0,
draft: phase === 'dormant' && latest === 1, // a never-started run
ready: sm.ready ?? null,
status: st.status,
agenda: st.agenda,
records: st.records,
@@ -365,46 +375,77 @@ route('GET', '/api/runs/:id', async ({ params }) => {
// --- run files: the editor's surface ------------------------------------------
//
// A fixed whitelist, not a path API: state dirs are the clerk's
// alone. Craft files are writable; housekeeper.md is substrate-
// internal (repo-fed at housekeeping, never copied, not exposed here) and
// gm.md lives only in the notepad endpoints (the play-view pad);
// config is read-only (vars and lineage are easy to break blind).
// JSON writes are validated before landing.
// alone. The ADDRESSED session is the live one while one plays, else
// the latest (the dormant one during the review window). Its bundle
// (the frozen craft) is writable only while dormant; the authored
// carryover of session one is authoring material (writable), a
// continuation carryover is conversation (read-only until the editor
// task); memory.json is inert provenance, read-only. housekeeper.md
// is substrate-internal (repo-fed at housekeeping, never copied, not
// exposed here) and gm.md lives only in the notepad endpoints (the
// play-view pad); config is read-only (vars and lineage are easy to
// break blind).
const RUN_FILES = {
'backdrop.md': 'rw',
'character.md': 'rw',
'turn-0.md': 'rw',
'seed.json': 'rw',
'handbook.md': 'rw',
'settings.json': 'ro',
'run.json': 'ro',
};
function fileSurface(runId) {
const live = ctx.sessions.get(runId);
const latest = session.latestSession(runId);
if (latest == null) throw new HttpError(409, 'this run has no sessions');
const n = live?.n ?? latest;
const dir = session.sessionDir(runId, n);
const phase = live ? 'live' : session.sessionMeta(runId, n).phase;
const dormant = phase === 'dormant';
const rw = dormant ? 'rw' : 'ro';
const root = bundle.runDir(runId);
const spec = {
'handbook.md': { mode: rw, path: path.join(dir, 'bundle', 'handbook.md') },
'backdrop.md': { mode: rw, path: path.join(dir, 'bundle', 'backdrop.md') },
'character.md': { mode: rw, path: path.join(dir, 'bundle', 'character.md') },
'carryover.jsonl': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'carryover.jsonl') },
'memory.json': { mode: 'ro', path: path.join(dir, 'memory.json') }, // session one's provenance; absent later
'settings.json': { mode: 'ro', path: path.join(root, 'settings.json') },
'run.json': { mode: 'ro', path: path.join(root, 'run.json') },
};
return { n, phase, files: spec };
}
route('GET', '/api/runs/:id/files', async ({ params }) => {
const dir = bundle.requireRun(params.id);
bundle.requireRun(params.id);
const surf = fileSurface(params.id);
const files = {};
for (const [f, mode] of Object.entries(RUN_FILES)) {
const p = path.join(dir, f);
files[f] = fs.existsSync(p)
? { mode, exists: true, content: fs.readFileSync(p, 'utf8') }
: { mode, exists: false };
for (const [f, spec] of Object.entries(surf.files)) {
files[f] = fs.existsSync(spec.path)
? { mode: spec.mode, exists: true, content: fs.readFileSync(spec.path, 'utf8') }
: { mode: spec.mode, exists: false };
}
return { files };
return { session: surf.n, phase: surf.phase, files };
});
route('PUT', '/api/runs/:id/files/:path', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
bundle.requireRun(params.id);
requireOwner(user, params.id);
const surf = fileSurface(params.id);
const f = params.path;
const mode = RUN_FILES[f];
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
if (mode !== 'rw') throw new HttpError(403, `${f} is read-only`);
const spec = surf.files[f];
if (!spec) throw new HttpError(404, `no such run file in the API surface: ${f}`);
if (spec.mode !== 'rw') throw new HttpError(403, `${f} is read-only (session ${surf.n} is ${surf.phase})`);
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
if (f.endsWith('.json')) {
try { JSON.parse(body.content); } catch { throw new HttpError(400, `${f} rejected: not valid JSON`); }
if (f === 'carryover.jsonl') {
// the save-time lint: only clean openings land (the start lint is
// the backstop, not the first line of defense)
const lines = [];
const raw = body.content.split('\n');
for (let i = 0; i < raw.length; i++) {
if (!raw[i].trim()) continue;
try {
lines.push(JSON.parse(raw[i]));
} catch {
throw new HttpError(400, `not valid JSONL: line ${i + 1} does not parse`);
}
}
const errors = session.lintCarryover(lines, { authored: surf.n === 1 });
if (errors.length) throw new HttpError(400, `the carryover did not pass the lint: ${errors.join('; ')}`);
}
fs.writeFileSync(path.join(dir, f), body.content);
fs.writeFileSync(spec.path, body.content);
return { ok: true, file: f, bytes: Buffer.byteLength(body.content) };
});
@@ -427,7 +468,7 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
// the run's models: per-run overrides of the deployment defaults
// (server.json), selected from the upstream listing (GET /api/models).
// Owner-only, changeable at any time — every call resolves fresh, so a
// Owner-only, changeable at any time -- every call resolves fresh, so a
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default.
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
@@ -435,7 +476,7 @@ route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
bundle.requireRun(id);
requireOwner(user, id);
for (const k of Object.keys(body)) {
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} — player and housekeeper`);
if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} -- player and housekeeper`);
}
const meta = bundle.runMeta(id) ?? {};
const models = meta.models ?? {};
@@ -452,7 +493,7 @@ route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
return { ok: true, models: meta.models ?? {}, defaults: ctx.cfg.models ?? {} };
});
// the GM's notepad: the run's gm.md — always editable in the SPA,
// the GM's notepad: the run's gm.md -- always editable in the SPA,
// never in any bundle, never sent to any model (no assembly path
// reads it). Seeded from the package at creation, the GM's to keep.
route('GET', '/api/runs/:id/notes', async ({ params }) => {
@@ -464,50 +505,192 @@ route('GET', '/api/runs/:id/notes', async ({ params }) => {
route('PUT', '/api/runs/:id/notes', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id); // spectators read the pad, the owner writes it
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required -- empty clears the pad');
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
return { ok: true };
});
// delete a DRAFT: a run with no sessions holds nothing but its copy,
// so the directory is the whole run and removal is complete. A played
// run is a story — deleting one is a deliberate act that stays by
// hand (Remove-Item runs/<id>), not a button.
// delete a DRAFT: a run whose sessions were never started holds
// nothing but its copy, so the directory is the whole run and removal
// is complete. A played run is a story -- deleting one is a
// deliberate act that stays by hand (Remove-Item runs/<id>), not a
// button.
route('DELETE', '/api/runs/:id', async ({ params, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
if (session.latestSession(params.id) !== null) {
throw new HttpError(409, `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
const played = session.listSessions(params.id).some((n) => fs.existsSync(path.join(session.sessionDir(params.id, n), 'log.jsonl')));
if (played) {
throw new HttpError(409, `this run has been played -- its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
}
fs.rmSync(dir, { recursive: true, force: true });
return { ok: true, deleted: params.id };
});
// start: the dormant session goes live -- lint the carryover, freeze
// the bundle, consume the carryover into the log. If the carryover
// ends on a GM turn, that turn is her cue: the first request of the
// assembled contwin fires automatically. Everything rides the run's
// activity lock (serialized with turns and the housekeeping job).
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `a session is already open for '${id}' — one active session per run`);
const s = session.openSession(id, body.override === true);
ctx.sessions.set(id, s);
return {
session: s.stamp,
fresh: s.fresh,
notes: s.lines.filter((e) => e.t === 'note').map((e) => ({ kind: e.kind, ok: e.ok, detail: e.detail })),
};
if (ctx.sessions.has(id)) throw new HttpError(409, `session ${ctx.sessions.get(id).n} is already live -- one active session per run`);
return ctx.enqueue(id, async () => {
const { session: s, autoSend } = session.startSession(id, { override: body.override === true });
ctx.sessions.set(id, s);
const out = { ok: true, session: s.n, autoSend };
if (autoSend) return { ...out, ...(await openingCall(ctx, id, user)) };
return out;
});
});
route('GET', '/api/runs/:id/session', async ({ params }) => {
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no open session for '${params.id}'`);
if (!s) throw new HttpError(404, `no live session for '${params.id}'`);
return {
run: params.id,
session: s.stamp,
session: s.n,
entries: s.lines,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
};
});
// the carryover: the dormant session's opening material, raw and
// read-only -- the review window's preview of the next contwin. Same
// projection as the table (the picked variant only, thinking stays in
// the raw log), plus the ending that decides the opening flow.
route('GET', '/api/runs/:id/carryover', async ({ params }) => {
bundle.requireRun(params.id);
const live = ctx.sessions.get(params.id);
if (live) throw new HttpError(409, `session ${live.n} is live -- the table is the surface`);
const latest = session.latestSession(params.id);
if (latest == null) throw new HttpError(404, 'no sessions');
const meta = session.sessionMeta(params.id, latest);
if (meta.phase !== 'dormant') throw new HttpError(409, `session ${latest} is ${meta.phase || 'unmarked'}`);
const p = path.join(session.sessionDir(params.id, latest), 'carryover.jsonl');
const lines = [];
if (fs.existsSync(p)) {
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
if (!l.trim()) continue;
try {
lines.push(JSON.parse(l));
} catch {
throw new HttpError(422, 'the carryover is not valid JSONL -- fix it before start');
}
}
}
const eff = effectiveContents(lines);
const entries = lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) };
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
return { ...e, m };
}
return e;
});
const lastMsg = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder);
return {
run: params.id,
session: latest,
ready: meta.ready === true,
entries,
ends: lastMsg == null ? null : (lastMsg.m.role === 'user' ? 'gm' : 'player'),
};
});
// the table: the play surface's projection of the live session --
// what the GM needs at the table. Same envelope as /session,
// different policy over the same log: thinking never crosses the
// wire, variant turns carry only the picked variant. The raw
// /session stays whole as the audit surface; during dormancy the
// /carryover endpoint is the table's stand-in.
route('GET', '/api/runs/:id/table', async ({ params }) => {
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no live session for '${params.id}'`);
const eff = effectiveContents(s.lines);
const entries = s.lines.map((e, i) => {
if (e.t === 'msg' && e.m.role === 'assistant') {
const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) };
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
return { ...e, m };
}
return e;
});
// the variantary metric: how variant she tends to be, straight off
// the pick notes (counted, never content)
const picks = s.lines.filter((e) => e.t === 'note' && e.kind === 'pick');
return {
run: params.id,
session: s.n,
entries,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
variance: {
picks: picks.length,
offered: picks.reduce((a, p) => a + (p.count ?? 0), 0),
maxVariants: picks.reduce((a, p) => Math.max(a, p.count ?? 0), 0),
},
};
});
// the story: the whole deliverable, read-only -- every non-dropped
// literature turn from the opening to the last recorded, across all
// sessions in order. OOC, tool calls, substrate verbs, thinking,
// rings, machinery: all out; load-bearing prose living inside OOC
// only is a GM protocol violation, and the story enforces that by
// omission. A dormant session's carryover is the story's live edge:
// its raw lines project like any log's, at the chronological end --
// GM edits during dormancy show, because the carryover is the current
// truth of where the story stands.
route('GET', '/api/runs/:id/story', async ({ params }) => {
bundle.requireRun(params.id);
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g;
const verbs = /<(lost|gained|add|drop)>[\s\S]*?<\/\1>/g;
const project = (lines) => {
const eff = effectiveContents(lines);
const turns = [];
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
if (e.t !== 'msg' || e.reminder) continue;
if (e.m.role === 'user' && !e.conflictOnly) {
const text = String(e.m.content ?? '').replace(rides, '').trim();
if (text) turns.push({ who: 'gm', text });
} else if (e.m.role === 'assistant' && !e.m.tool_calls?.length) {
// tool prose is for the tool result turn, not the story
const text = String(eff.has(i) ? eff.get(i) : (e.m.content ?? '')).replace(verbs, '').trim();
if (text) turns.push({ who: 'player', text });
}
}
return turns;
};
const readJsonl = (p) => {
const out = [];
if (!fs.existsSync(p)) return out;
for (const l of fs.readFileSync(p, 'utf8').split('\n')) {
if (!l.trim()) continue;
try {
out.push(JSON.parse(l));
} catch {
// a malformed line fails loud at start; the story skips it
}
}
return out;
};
const sessions = [];
for (const n of session.listSessions(params.id)) {
const dir = session.sessionDir(params.id, n);
const meta = session.sessionMeta(params.id, n);
const lines = readJsonl(path.join(dir, 'log.jsonl'));
const turns = project(lines);
if (meta.phase === 'dormant') {
turns.push(...project(readJsonl(path.join(dir, 'carryover.jsonl'))));
}
if (turns.length) sessions.push({ session: n, turns });
}
return { run: params.id, sessions };
});
route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
const line = String(body.line ?? '').trim();
if (!line) throw new HttpError(400, 'line is required');
@@ -515,13 +698,6 @@ route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
return { ok: true, ...(await ctx.enqueue(params.id, () => gmTurn(ctx, params.id, line, user))) };
});
// the opening beat as its own action: sent as the first GM turn on a
// fresh session — "start" is this right after session-open
route('POST', '/api/runs/:id/turn0', async ({ params, user }) => {
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => turn0(ctx, params.id, user))) };
});
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required');
@@ -529,7 +705,7 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
return { ok: true, ...(await ctx.enqueue(params.id, () => answerAsk(ctx, params.id, answer, user))) };
});
// fork: any user, any run — a mechanical atomic copy with the owner
// fork: any user, any run -- a mechanical atomic copy with the owner
// replaced (server/fork.mjs). The source's activity lock is held, so
// the copy is never taken mid-turn.
route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
@@ -544,14 +720,14 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
// the GM's out-of-band status override: whole-status replace via the
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// commas -- the transport is comma-separated -- so a comma inside an
// item is a 400, not a silent corruption later.
route('POST', '/api/runs/:id/status', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the status');
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required -- an empty array clears the status');
for (const it of items) {
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
@@ -562,14 +738,14 @@ route('POST', '/api/runs/:id/status', async ({ params, body, user }) => {
// the GM's out-of-band agenda override: whole-queue replace via the
// clerk (journaled). Items land in written order, first = top; an
// empty array clears it. Commas are the add transport's separator —
// empty array clears it. Commas are the add transport's separator --
// an item containing one is a 400, not a silent split later.
route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the agenda');
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required -- an empty array clears the agenda');
for (const it of items) {
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
if (it.includes(',')) throw new HttpError(400, `items never contain commas (the add transport is comma-separated): ${JSON.stringify(it)}`);
@@ -579,46 +755,52 @@ route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
});
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// ends the session and kicks the async chain; poll GET for the outcome
// with a live session this is STOP (close, move the tail, freeze,
// then the pass); with a dormant latest it is the RE-RUN. Poll GET
// for the outcome.
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
return { state: job.state, session: job.session };
return { state: job.state, phase: job.phase, session: job.session, target: job.target ?? null };
});
// dry-run the housekeeper over a session log: the same transcript
// assembly the real housekeeping uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no session ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open session too.
// saved for review -- but nothing applied, no state touched. The way
// to iterate on housekeeper.md against real data without playing
// more; works on the live session and on finished ones alike.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id); // a replay spends a model call on the shared key
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
const latest = session.latestSession(id);
if (latest == null) throw new HttpError(409, 'no session to replay -- this run has none');
// default: the newest session that has a log -- the live one, else
// the finished predecessor of a dormant latest
const n = body?.session != null ? Number(body.session) : (ctx.sessions.get(id)?.n ?? latest - 1);
if (!Number.isInteger(n) || n < 1) throw new HttpError(409, 'no session log to replay yet');
let lines;
try {
lines = session.loadSession(id, stamp).lines;
lines = session.loadSession(id, n).lines;
} catch {
throw new HttpError(404, `no such session: ${stamp}`);
throw new HttpError(404, `no such session log: ${n}`);
}
if (!lines.some((e) => e.t === 'msg')) throw new HttpError(409, 'that session has no exchange to review');
const dir = path.join(bundle.runDir(id), 'manifests');
fs.mkdirSync(dir, { recursive: true });
const text = ctx.mock
? housekeeping.mockManifest(stamp)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp), user);
? housekeeping.mockManifest(n)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, n, lines), user);
let mf;
try {
mf = housekeeping.parseManifest(text);
} catch (e) {
const raw = path.join(dir, `${stamp}.replay.raw.md`);
const raw = path.join(dir, `${n}.replay.raw.md`);
fs.writeFileSync(raw, String(text));
return { ok: true, parsed: false, session: stamp, file: `manifests/${stamp}.replay.raw.md`, reason: e.message };
return { ok: true, parsed: false, session: n, file: `manifests/${n}.replay.raw.md`, reason: e.message };
}
const file = path.join(dir, `${stamp}.replay.json`);
const file = path.join(dir, `${n}.replay.json`);
fs.writeFileSync(file, JSON.stringify(mf, null, 2) + '\n');
return { ok: true, parsed: true, session: stamp, file: `manifests/${stamp}.replay.json`, manifest: mf };
return { ok: true, parsed: true, session: n, file: `manifests/${n}.replay.json`, manifest: mf };
});
route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id));
@@ -626,27 +808,28 @@ route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jo
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open session, marks the latest session housekept, autorestarts
// the recovery path: apply a (hand-edited) manifest directly -- the
// rebase + apply + ready, into the dormant continuation session
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const file = String(body.file ?? '').trim();
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<session>.json');
if (!file) throw new HttpError(400, 'file is required -- a manifest path relative to the run dir, e.g. manifests/<session>.json');
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
if (!manifestPath.startsWith(path.join(ROOT, 'runs', id))) throw new HttpError(400, 'file must stay inside the run dir');
if (!fs.existsSync(manifestPath)) throw new HttpError(404, `no such manifest: ${file}`);
const latest = session.latestSession(id);
if (!latest) throw new HttpError(409, 'no session to mark housekept');
ctx.sessions.delete(id); // housekeeping always ends the session
try {
const next = housekeeping.applyAndRestart(ctx, id, manifestPath, latest);
return { ok: true, housekept: latest, session: next.stamp };
} catch (e) {
const job = { state: 'rejected', session: latest, reason: e.message };
ctx.jobs.set(id, job);
throw new HttpError(422, e.message);
}
if (latest == null || latest < 2) throw new HttpError(409, 'no dormant continuation session to apply into');
if (session.sessionMeta(id, latest).phase !== 'dormant') throw new HttpError(409, `session ${latest} is not dormant`);
return ctx.enqueue(id, () => {
try {
housekeeping.applyToDormant(id, manifestPath, latest - 1);
return { ok: true, housekept: latest - 1, target: latest };
} catch (e) {
ctx.jobs.set(id, { state: 'rejected', session: latest - 1, reason: e.message });
throw new HttpError(422, e.message);
}
});
});
// --- dispatch -------------------------------------------------------------------
@@ -662,7 +845,7 @@ const server = http.createServer(async (req, res) => {
let user = null;
try {
const url = new URL(req.url, 'http://localhost');
// the request log: one line per API call — reconstruct any session
// the request log: one line per API call -- reconstruct any session
// from the console output after the fact; the acting user rides
// every line (attribution, #22)
res.on('finish', () => {
@@ -679,7 +862,7 @@ const server = http.createServer(async (req, res) => {
if (!m) throw new HttpError(404, `no such route: ${req.method} ${url.pathname}`);
const body = (req.method === 'POST' || req.method === 'PUT') ? await readBody(req) : {};
user = authenticate(req);
if (!m.publicRoute && !user) throw new HttpError(401, 'not signed in — claim an invite first (POST /api/claim)');
if (!m.publicRoute && !user) throw new HttpError(401, 'not signed in -- claim an invite first (POST /api/claim)');
send(res, 200, await m.handler({ params: m.params, body, req, user }));
} catch (e) {
const status = e.status ?? 500;