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
+340 -98
View File
@@ -1,60 +1,87 @@
// server/session.mjs — a session's live state.
// server/session.mjs -- a session's lifecycle and live state.
//
// A session is a stateful entity -- dormant -> live -> finished --
// owning its material under sessions/<n>/: the bundle (frozen prompt
// copies), the rings db, the canon views, the dumps, the carryover.
// Dormant is the review window (everything editable); start lints the
// carryover, freezes the bundle, consumes the carryover into the log
// and goes live; stop moves the tail into the next dormant session's
// carryover and freezes this one. No contwin before live.
//
// The append-only jsonl is the truth; the in-memory context is a view
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
// note) so later features (turn surgery) can append their own kinds
// without a format migration. The view renderer is pure policy over
// the log: thinking never goes back, old tool results elide to stubs
// note / opening) so later features (turn surgery) can append their
// own kinds without a format migration. The view renderer is pure
// policy over the log: thinking never goes back, variant turns render
// only the picked variant, old tool results elide to stubs
// (the last few and every ask_gm answer stay), old GM-side
// <status>/<conflict> blocks elide — the current status rides the
// <status>/<conflict> blocks elide -- the current status rides the
// newest GM turn.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { clerk, clerkTry, clerkJson } from './clerk.mjs';
import { runDir, requireRun, assembleSystem, assembleBundle } from './bundle.mjs';
import { runDir, requireRun, assembleSystem, assembleBundle, expandVars } from './bundle.mjs';
import { parseVariants, pickVariant, effectiveContents } from './variants.mjs';
import { tailStart } from './carry.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const sessionsDir = (runId) => path.join(runDir(runId), 'sessions');
const sessionFile = (runId, s) => path.join(sessionsDir(runId), `${s}.jsonl`);
export const sessionDir = (runId, n) => path.join(sessionsDir(runId), String(n));
const logFile = (runId, n) => path.join(sessionDir(runId, n), 'log.jsonl');
const carryFile = (runId, n) => path.join(sessionDir(runId, n), 'carryover.jsonl');
export function latestSession(runId) {
const dir = sessionsDir(runId);
if (!fs.existsSync(dir)) return null;
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')).sort();
return files.length ? files[files.length - 1].replace(/\.jsonl$/, '') : null;
export function listSessions(runId) {
if (!fs.existsSync(sessionsDir(runId))) return [];
return fs.readdirSync(sessionsDir(runId), { withFileTypes: true })
.filter((d) => d.isDirectory() && /^\d+$/.test(d.name))
.map((d) => Number(d.name)).sort((a, b) => a - b);
}
function readState(runId) {
export const latestSession = (runId) => {
const ns = listSessions(runId);
return ns.length ? ns[ns.length - 1] : null;
};
export function sessionMeta(runId, n) {
try {
return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'state.json'), 'utf8'));
return JSON.parse(fs.readFileSync(path.join(sessionDir(runId, n), 'session.json'), 'utf8'));
} catch {
return {};
}
}
export const lastHousekept = (runId) => readState(runId).lastHousekeptSession ?? null;
export function markHousekept(runId, stamp) {
const state = readState(runId);
state.lastHousekeptSession = stamp;
fs.writeFileSync(path.join(runDir(runId), 'state.json'), JSON.stringify(state, null, 2) + '\n');
export function writeMeta(runId, n, patch) {
const m = { ...sessionMeta(runId, n), ...patch };
fs.writeFileSync(path.join(sessionDir(runId, n), 'session.json'), JSON.stringify(m, null, 2) + '\n');
return m;
}
// the run's state is its latest session's: live while one plays,
// else dormant (the review window). At most one live session exists.
export function liveSession(runId) {
return listSessions(runId).find((n) => sessionMeta(runId, n).phase === 'live') ?? null;
}
const err = (status, message, detail) => {
const e = new Error(message);
e.status = status;
if (detail) e.detail = detail;
return e;
};
// --- session object ----------------------------------------------------------
function makeSession(runId, st) {
function makeSession(runId, n) {
return {
runId,
stamp: st,
file: sessionFile(runId, st),
n,
stamp: String(n),
file: logFile(runId, n),
lines: [],
pendingAsk: null, // { callId, question, calls } — the whole batch pauses
pendingAsk: null, // { callId, question, calls } -- the whole batch pauses
usage: null, // { promptTokens, completionTokens } from the last response
fresh: false,
append(entry) {
this.lines.push(entry);
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
@@ -62,80 +89,33 @@ function makeSession(runId, st) {
};
}
// --- open a session -----------------------------------------------------------
// The #21 guard: opening over an unhousekept session means that
// transcript never reaches the rings — refuse and name it, unless the
// caller explicitly overrides (the deliberate skip).
export function openSession(runId, override = false) {
requireRun(runId);
const latest = latestSession(runId);
if (latest && latest !== (readState(runId).lastHousekeptSession ?? null) && !override) {
const err = new Error(`the previous session (${latest}) was never housekept — its transcript would never reach the rings`);
err.status = 409;
err.detail = { session: latest, hint: 'housekeep it first, or POST with {"override": true} to deliberately skip it' };
throw err;
function readLogLines(file) {
if (!fs.existsSync(file)) {
throw err(404, `no session log: ${path.relative(ROOT, file)}`);
}
const notes = [];
const fresh = latest === null;
if (fresh) {
// lazy seed: applies at the first session-open, before render and
// assembly, so the bundle sees populated rings. The clerk refuses
// on history (a hand-prepped run), which is the opt-out.
if (fs.existsSync(path.join(runDir(runId), 'seed.json'))) {
const r = clerkTry(runId, 'seed');
notes.push({ kind: 'seed', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
if (fs.existsSync(path.join(runDir(runId), 'turn-0.md'))) {
const r = clerkTry(runId, 'status-ingest', path.join(runDir(runId), 'turn-0.md'));
notes.push({ kind: 'ingest', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
}
const r = clerkTry(runId, 'render');
if (r.code !== 0) {
const err = new Error(r.err || 'render failed');
err.status = 500;
throw err;
}
const system = { role: 'system', content: assembleSystem(runId) };
const bundle = assembleBundle(runId);
// turn-0 is not a bundle part: the opening beat is sent as the
// first GM turn (POST /api/runs/<id>/turn0) when play starts
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
const s = makeSession(runId, stamp());
s.fresh = fresh;
fs.mkdirSync(sessionsDir(runId), { recursive: true });
s.append({ t: 'note', kind: 'session', at: s.stamp, fresh });
for (const n of notes) s.append({ t: 'note', kind: n.kind, ok: n.ok, detail: n.detail });
s.append({ t: 'bundle', m: system, part: 'system' });
for (let i = 0; i < bundle.length; i++) s.append({ t: 'bundle', m: bundle[i], part: partNames[i] });
return s;
}
// --- boot-rebuild ------------------------------------------------------------
export function loadSession(runId, st) {
const s = makeSession(runId, st);
if (!fs.existsSync(s.file)) {
const err = new Error(`no session log: ${path.relative(ROOT, s.file)}`);
err.status = 404;
throw err;
}
for (const line of fs.readFileSync(s.file, 'utf8').split('\n')) {
const out = [];
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
if (!line.trim()) continue;
try {
s.lines.push(JSON.parse(line));
out.push(JSON.parse(line));
} catch {
// a torn tail line (crash mid-append) is skipped, not fatal
}
}
return out;
}
function writeLog(file, lines) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.tmp`;
fs.writeFileSync(tmp, lines.map((e) => JSON.stringify(e)).join('\n') + (lines.length ? '\n' : ''));
fs.renameSync(tmp, file); // atomic: a crash never leaves a torn log
}
export function loadSession(runId, n) {
const s = makeSession(runId, n);
s.lines = readLogLines(s.file);
derive(s);
// fresh survives a restart: this session is the run's first iff no
// earlier session log exists (derive() can't know — it sees one log)
const files = fs.readdirSync(sessionsDir(runId)).filter((f) => f.endsWith('.jsonl')).sort();
s.fresh = files.length === 1 && files[0] === `${st}.jsonl`;
return s;
}
@@ -157,6 +137,265 @@ function derive(s) {
}
}
s.pendingAsk = pending;
// a final variant turn that never got its pick (crash between the
// message and its note) resolves at boot: a fresh random pick,
// appended as the note it always should have had. Malformed content
// can't reach the log (the loop validates pre-append), so this only
// fires on a well-formed block; if it ever doesn't, warn and leave
// the message stripped-in-view rather than dying on rebuild
const last = s.lines[s.lines.length - 1];
if (last?.t === 'msg' && last.m.role === 'assistant' && !last.m.tool_calls?.length
&& typeof last.m.content === 'string' && /<\/?variants?>/.test(last.m.content)) {
try {
const v = parseVariants(last.m.content);
s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
} catch (e) {
console.warn(`boot: an unresolved variant turn in session ${s.n} was left as-is: ${e.message}`);
}
}
}
// --- stop: the manual close ----------------------------------------------------
//
// (1) move N's tail into the new dormant N+1 as its carryover;
// (2) freeze N; then the rest -- N+1's bundle and db are copies of
// N's. The move is at stop: each line exists in exactly one jsonl,
// ever, no markers on the lines. Crash-safe: a stop.json marker is
// written before anything is touched, and every step is idempotent --
// boot resumes a half-finished stop by re-running this over the
// on-disk state (the move step reconciles against what already
// landed, so it never moves anything twice).
export function stopSession(runId, N) {
const dir = sessionDir(runId, N + 1);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'stop.json'), JSON.stringify({ from: N }) + '\n');
const src = sessionDir(runId, N);
const carry = path.join(dir, 'carryover.jsonl');
const lines = readLogLines(logFile(runId, N));
if (fs.existsSync(carry)) {
// the crash landed mid-move: the carryover is written; truncate
// the log to match it (the moved lines are the carryover now)
const carried = fs.readFileSync(carry, 'utf8').split('\n').filter((l) => l.trim());
const k = carried.length;
if (lines.length > k) {
const tail = lines.slice(lines.length - k).map((e) => JSON.stringify(e));
if (JSON.stringify(tail) !== JSON.stringify(carried)) {
throw err(500, `stop cannot resume: session ${N}'s log does not end with its own carryover -- fix by hand`);
}
writeLog(logFile(runId, N), lines.slice(0, lines.length - k));
} // else: already truncated -- nothing to move
} else {
const start = tailStart(lines);
fs.writeFileSync(carry, lines.slice(start).map((e) => JSON.stringify(e)).join('\n') + (start < lines.length ? '\n' : ''));
writeLog(logFile(runId, N), lines.slice(0, start));
}
// (2) freeze N; the rest: the copies that make N+1 a real session
writeMeta(runId, N, { phase: 'finished' });
fs.cpSync(path.join(src, 'bundle'), path.join(dir, 'bundle'), { recursive: true });
fs.mkdirSync(path.join(dir, 'db'), { recursive: true });
// the db copy carries her status and agenda; the rings are the base
// the housekeeping apply lands on (each run re-copies, so re-runs
// never double-apply)
fs.copyFileSync(path.join(src, 'db', 'memory.db'), path.join(dir, 'db', 'memory.db'));
writeMeta(runId, N + 1, { phase: 'dormant', ready: false });
fs.rmSync(path.join(dir, 'stop.json'));
}
// a stop that died in flight leaves its marker; boot finishes it
export function findStalledStop(runId) {
for (const n of listSessions(runId)) {
const p = path.join(sessionDir(runId, n), 'stop.json');
if (fs.existsSync(p)) {
try {
return { from: JSON.parse(fs.readFileSync(p, 'utf8')).from, dir: n };
} catch {
return { from: n - 1, dir: n };
}
}
}
return null;
}
// --- start: lint, freeze, consume, go live -------------------------------------
// the authored carryover's event vocabulary: her opening as msg
// events (user = the GM, assistant = her), plus at most one opening
// event (her opening status). A continuation carryover is real
// conversation: msg, tool, and note events, read as recorded.
// Exported for the file editor's save-time check: only clean
// openings land.
export function lintCarryover(lines, { authored }) {
const errors = [];
let openings = 0;
lines.forEach((e, i) => {
const at = `line ${i + 1}`;
if (authored) {
if (e.t === 'msg') {
const m = e.m ?? {};
if (m.role !== 'user' && m.role !== 'assistant') errors.push(`${at}: role must be user (the GM) or assistant (her)`);
if (typeof m.content !== 'string' || !m.content.trim()) errors.push(`${at}: content must be a non-empty string`);
if (m.tool_calls?.length) errors.push(`${at}: tool calls are runtime artifacts -- the opening never calls tools`);
if (m.usage) errors.push(`${at}: usage is runtime metadata`);
if (m.reasoning_content) errors.push(`${at}: thinking is runtime metadata`);
if (e.reminder) errors.push(`${at}: the reminder rides every GM turn on its own`);
if (e.conflictOnly) errors.push(`${at}: conflict traffic is runtime machinery`);
} else if (e.t === 'opening') {
openings++;
if (!Array.isArray(e.status)) errors.push(`${at}: opening.status must be an array of descriptions`);
else for (const it of e.status) {
if (typeof it !== 'string' || !it.trim()) errors.push(`${at}: opening.status items must be non-empty strings`);
else if (it.includes(',')) errors.push(`${at}: descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
}
} else {
errors.push(`${at}: authored events are msg or opening only (got ${JSON.stringify(e.t)})`);
}
} else if (!['msg', 'tool', 'note'].includes(e.t)) {
errors.push(`${at}: a carryover holds conversation events only (got ${JSON.stringify(e.t)})`);
}
// both kinds: a variants message must parse strict -- nothing
// malformed reaches a contwin
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
&& /<\/?variants?>/.test(e.m.content)) {
try {
parseVariants(e.m.content);
} catch (e2) {
errors.push(`${at}: malformed variants block -- ${e2.message}`);
}
}
});
if (authored && openings > 1) errors.push('at most one opening event');
return errors;
}
// the authored carryover is prompt-side: sigils and $vars resolve at
// freeze, exactly like every bundle file. A continuation carryover is
// live prose and NEVER expands -- a literal $word typed in play would
// bomb the unresolved-token check, and the words are already real.
function expandCarryover(runId, lines) {
return lines.map((e) => {
if (e.t === 'msg') return { ...e, m: { ...e.m, content: expandVars(runId, e.m.content) } };
if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) };
return e;
});
}
// an unpicked variants event gets its crypto pick at start -- the
// same dice the loop rolls on reception; a pick already adjacent
// (real history) is final, re-rolls do not exist
function resolvePicks(lines) {
const out = [];
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
out.push(e);
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
&& /<\/?variants?>/.test(e.m.content)
&& !(lines[i + 1]?.t === 'note' && lines[i + 1].kind === 'pick')) {
const v = parseVariants(e.m.content); // lint already validated
out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
}
}
return out;
}
function readCarryover(runId, n) {
const p = carryFile(runId, n);
if (!fs.existsSync(p)) return [];
const out = [];
const raw = fs.readFileSync(p, 'utf8').split('\n');
for (let i = 0; i < raw.length; i++) {
if (!raw[i].trim()) continue;
try {
out.push(JSON.parse(raw[i]));
} catch {
throw err(422, `the carryover is not valid JSONL (line ${i + 1} does not parse)`);
}
}
return out;
}
export function startSession(runId, { override = false } = {}) {
requireRun(runId);
const n = latestSession(runId);
if (n == null) throw err(409, 'this run has no sessions -- create builds session one');
const meta = sessionMeta(runId, n);
if (meta.phase === 'live') throw err(409, `session ${n} is already live`);
if (meta.phase !== 'dormant') {
throw err(409, `session ${n} is ${meta.phase || 'unmarked'} -- a stop died in flight; restart the server to resume it`);
}
if (meta.ready !== true && n > 1 && !override) {
// the deliberate-skip guard: session N-1's transcript never
// reached the rings. The normal path cannot hit this (N+1's
// rings do not exist until housekeeping of N produces them).
throw err(409, `session ${n}'s rings are not ready -- session ${n - 1} was never housekept`, {
hint: 're-run housekeeping, or POST with {"override": true} to deliberately skip it',
});
}
const dir = sessionDir(runId, n);
const authored = n === 1;
let carry = readCarryover(runId, n);
const errors = lintCarryover(carry, { authored });
if (authored) {
try {
carry = expandCarryover(runId, carry);
} catch (e) {
errors.push(e.message);
}
}
if (errors.length) {
throw err(422, 'the carryover did not pass the start lint -- nothing started', { errors });
}
carry = resolvePicks(carry);
// the opening event: her opening status, set before the first turn
// (set semantics, journaled by the clerk)
const opening = carry.find((e) => e.t === 'opening');
if (opening) {
const r = clerkTry(runId, '--session', String(n), 'status-set', ...opening.status);
if (r.code !== 0) {
throw err(422, `the opening status did not apply: ${(r.err || r.out).split('\n')[0]}`);
}
}
// fresh views, then the bundle: one assembly, baked here and
// nowhere else -- the frozen snapshot every call of this session
// renders from
const rr = clerkTry(runId, '--session', String(n), 'render');
if (rr.code !== 0) throw err(500, `render failed: ${(rr.err || rr.out).split('\n')[0]}`);
const system = { role: 'system', content: assembleSystem(runId, dir) };
const bundle = assembleBundle(runId, dir);
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
const lines = [
{ t: 'note', kind: 'session', n },
...(opening ? [opening] : []),
{ t: 'bundle', m: system, part: 'system' },
...bundle.map((m, i) => ({ t: 'bundle', m, part: partNames[i] })),
...carry,
];
// the assembled context must be sound before anything lands:
// tool pairing, variants resolution, every render invariant
try {
renderView({ lines, pendingAsk: null });
} catch (e) {
throw err(422, `the assembled context is not sound: ${e.message}`);
}
// land: the log written whole, the phase flipped, the carryover
// consumed (its lines live in the log now -- exactly one jsonl)
const s = makeSession(runId, n);
s.lines = lines;
writeLog(s.file, lines);
writeMeta(runId, n, { phase: 'live' });
fs.rmSync(carryFile(runId, n), { force: true });
derive(s);
// the opening flow: a carryover ending on a GM turn is her cue --
// it sends automatically as the first request of the assembled
// contwin; otherwise the table waits for the GM's input
const lastMsg = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder);
return { session: s, autoSend: lastMsg?.m?.role === 'user' };
}
// --- the view renderer: log + policy -> per-call context ---------------------
@@ -164,6 +403,7 @@ function derive(s) {
const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g;
export function renderView(s, keepToolResults = 4) {
const eff = effectiveContents(s.lines);
const toolIdx = [];
const reminderIdx = [];
let lastGmIdx = -1;
@@ -181,18 +421,20 @@ export function renderView(s, keepToolResults = 4) {
} else if (e.t === 'msg') {
if (e.reminder) {
// the per-turn reminder: only the newest copy lives in the
// context — superseded ones elide (identical content, freshest
// context -- superseded ones elide (identical content, freshest
// position, exactly like the status/agenda blocks)
if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() });
} else if (e.m.role === 'assistant') {
// thinking never goes back; the log keeps it
const m = { role: 'assistant', content: e.m.content ?? null };
// thinking never goes back; the log keeps it. Variant turns
// render their picked variant -- the unpicked rest never reach
// a model (the log keeps them)
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;
msgs.push(m);
} else if (e.conflictOnly) {
// transient error traffic: visible while it is the latest word
// (the model answers it), elided entirely once the story moves
// on — the log keeps it for provenance
// on -- the log keeps it for provenance
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else if (i === lastGmIdx) {
// the newest GM turn keeps its blocks as-sent: the current
@@ -215,7 +457,7 @@ export function renderView(s, keepToolResults = 4) {
}
// tool-call pairing is never broken (the endpoint tolerates orphans
// silently — probed 2026-11-12 — so this one fails quiet unless we check)
// silently -- probed 2026-11-12 -- so this one fails quiet unless we check)
function validatePairing(msgs, pendingCallId) {
const calls = new Set();
const results = new Set();