ba72d2ed1f
- prompt split, GM's cut: system.md = opening + guards (glossary, purpose, input validation; repo-fed, per-project); invariants.md = substrate (syntax markers, tools, memory, records, the paper + its three-part gate; repo-fed, travels with the code); handbook.md = craft copy (shape of play, thoughts, purview, time skips, continuity, stance, hard limits; copied per run). One system message: system -> invariants -> the run's handbook. OOC is a single open paren, closing optional, match the GM's style; a lone paren is an empty OOC line, skipped by the parser. housekeeper.md aligned: the paper holds acute states, relational shifts are recorded as the facts behind them, and dates are story dates (follow the rings' calendar, never the wall clock - the seed is 2069 now, per canon) - server/ (phase 2, zero-dep node:http): REST spine per the sketch, per-run session machine with ask_gm pause/resume (the whole tool-call batch waits, pairing stays sound), view renderer (thinking-strip, tool-result elision with ask answers exempt, old status/conflict blocks stripped), boot-rebuild from the typed jsonl, lazy seed + turn-0 ingestion at window-open with the unhousekept refuse-and-override guard, usage tracking + context meter, tool-pairing validation, scripted mock model. The clerk gained --json (packages/runs/status); tool/bridge.mjs deleted at mock-parity per the retirement decision - housekeeping job (phase 3, server/housekeeping.mjs): trigger ends the window and runs the chain async - transcript with labeled thinking, run-state injection (records availability; the ring views stay pure memory), housekeeper on a fresh context, manifest saved (raw output too if unparseable), clerk apply (writes the window log, snapshots dumps/<window>.sql), state.json lastHousekeptSession, autorestart. Rejection holds the restart and surfaces why; the apply endpoint is the recovery path and the manual-relay close. Live-proven twice: both manifests sound (ring-B classification, first-person voice, precise touches, story-dated) - spa (phase 4, web/ - no build, vanilla es modules, served at /): three-register transcript per the ruled markers incl. multi-line narration blocks, bundle as a collapsed card with turn-0 as the opening GM turn, paper tags as chips, status pane with conflict surfacing, context meter hot past 85 percent, gm line input, ask modal re-presented from pendingAsk, housekeeping button with two-click arm + poll + inline log. No js alert/confirm (they block the embedded pane) - in-page banner instead. Driven end to end through the ui on a disposable live run - seed: date fixed to the 2069 story calendar (was a real-world date; real dates never surface to the player) - docs: README goal states the mvp is complete, layout covers server/ and web/, protocol and substrate sections rewritten for the server; ROADMAP phases 0-4 done, harness decisions current; QUESTIONS #4 #7 #10 #12 #16-mechanism #19a #20 #21 resolved; HANDOFF is the handoff map; AGENTS carries the working lessons (tokens are free, no screenshots - not multimodal, no js dialogs, external state survives rewinds)
216 lines
8.4 KiB
JavaScript
216 lines
8.4 KiB
JavaScript
// server/session.mjs — a window's live state.
|
|
//
|
|
// 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
|
|
// (the last few and every ask_gm answer stay), old GM-side
|
|
// <status>/<conflict> blocks elide — the current paper 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';
|
|
|
|
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 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;
|
|
}
|
|
|
|
function readState(runId) {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'state.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');
|
|
}
|
|
|
|
// --- session object ----------------------------------------------------------
|
|
|
|
function makeSession(runId, st) {
|
|
return {
|
|
runId,
|
|
stamp: st,
|
|
file: sessionFile(runId, st),
|
|
lines: [],
|
|
pendingAsk: null, // { callId, question, calls } — the whole batch pauses
|
|
conflict: null, // carried to the next GM turn as a <conflict> block
|
|
usage: null, // { promptTokens, completionTokens } from the last response
|
|
fresh: false,
|
|
append(entry) {
|
|
this.lines.push(entry);
|
|
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
|
|
},
|
|
};
|
|
}
|
|
|
|
// --- open a window -----------------------------------------------------------
|
|
|
|
// 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 openWindow(runId, override = false) {
|
|
requireRun(runId);
|
|
const latest = latestSession(runId);
|
|
if (latest && latest !== (readState(runId).lastHousekeptSession ?? null) && !override) {
|
|
const err = new Error(`the previous window (${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;
|
|
}
|
|
|
|
const notes = [];
|
|
const fresh = latest === null;
|
|
if (fresh) {
|
|
// lazy seed: applies at the first window-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, 'paper-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, fresh);
|
|
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a', ...(fresh ? ['turn-0'] : [])];
|
|
const s = makeSession(runId, stamp());
|
|
s.fresh = fresh;
|
|
fs.mkdirSync(sessionsDir(runId), { recursive: true });
|
|
s.append({ t: 'note', kind: 'window', 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')) {
|
|
if (!line.trim()) continue;
|
|
try {
|
|
s.lines.push(JSON.parse(line));
|
|
} catch {
|
|
// a torn tail line (crash mid-append) is skipped, not fatal
|
|
}
|
|
}
|
|
derive(s);
|
|
return s;
|
|
}
|
|
|
|
// rebuild the derived state from the log alone
|
|
function derive(s) {
|
|
let pending = null;
|
|
for (const e of s.lines) {
|
|
if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) {
|
|
const ask = e.m.tool_calls.find((c) => c.function.name === 'ask_gm');
|
|
if (ask) {
|
|
let q = '(no question)';
|
|
try { q = JSON.parse(ask.function.arguments || '{}').question ?? q; } catch {}
|
|
pending = { callId: ask.id, question: q, calls: e.m.tool_calls };
|
|
}
|
|
} else if (e.t === 'tool' && pending && e.m.tool_call_id === pending.callId) {
|
|
pending = null;
|
|
} else if (e.t === 'note' && e.kind === 'paper') {
|
|
s.conflict = e.conflicts?.length ? e.conflicts.join('; ') : null;
|
|
} else if (e.t === 'msg' && e.m.role === 'user') {
|
|
s.conflict = null; // it rode this GM turn
|
|
} else if (e.t === 'msg' && e.usage) {
|
|
s.usage = { promptTokens: e.usage.prompt_tokens, completionTokens: e.usage.completion_tokens };
|
|
}
|
|
}
|
|
s.pendingAsk = pending;
|
|
}
|
|
|
|
// --- the view renderer: log + policy -> per-call context ---------------------
|
|
|
|
const STRIP_BLOCKS = /\n?<(status|conflict)>[\s\S]*?<\/\1>\n?/g;
|
|
|
|
export function renderView(s, keepToolResults = 4) {
|
|
const toolIdx = [];
|
|
s.lines.forEach((e, i) => { if (e.t === 'tool') toolIdx.push(i); });
|
|
const keep = new Set(toolIdx.slice(-keepToolResults));
|
|
const msgs = [];
|
|
for (const e of s.lines) {
|
|
if (e.t === 'bundle') {
|
|
msgs.push({ role: e.m.role, content: e.m.content });
|
|
} else if (e.t === 'msg') {
|
|
if (e.m.role === 'assistant') {
|
|
// thinking never goes back; the log keeps it
|
|
const m = { role: 'assistant', content: e.m.content ?? null };
|
|
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
|
msgs.push(m);
|
|
} else {
|
|
// GM-side: old status/conflict blocks elide — the current
|
|
// paper rides the newest GM turn
|
|
msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() });
|
|
}
|
|
} else if (e.t === 'tool') {
|
|
if (e.ask || keep.has(s.lines.indexOf(e))) {
|
|
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: e.m.content });
|
|
} else {
|
|
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: '[elided: earlier tool result]' });
|
|
}
|
|
}
|
|
}
|
|
validatePairing(msgs, s.pendingAsk?.callId);
|
|
return msgs;
|
|
}
|
|
|
|
// tool-call pairing is never broken (the endpoint tolerates orphans
|
|
// 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();
|
|
for (const m of msgs) {
|
|
if (m.role === 'assistant' && m.tool_calls) for (const c of m.tool_calls) calls.add(c.id);
|
|
if (m.role === 'tool') results.add(m.tool_call_id);
|
|
}
|
|
for (const id of results) {
|
|
if (!calls.has(id)) throw new Error(`context invariant violated: orphaned tool result ${id}`);
|
|
}
|
|
for (const id of calls) {
|
|
if (!results.has(id) && id !== pendingCallId) {
|
|
throw new Error(`context invariant violated: tool call ${id} has no result`);
|
|
}
|
|
}
|
|
}
|
|
|
|
export { clerkJson };
|