substrate: server, housekeeping job, spa - the mvp complete

- 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)
This commit is contained in:
2026-11-14 03:15:53 +00:00
parent 530170224f
commit ba72d2ed1f
22 changed files with 2418 additions and 838 deletions
+136
View File
@@ -0,0 +1,136 @@
// server/loop.mjs — the turn loop.
//
// Synchronous REST: a POST runs the tool loop and returns. ask_gm
// pauses mid-turn — the whole tool-call batch waits (pairing stays
// sound), the request returns with the pending question, and the
// answer call resumes the loop. The paper is re-read from the clerk
// before every GM turn and rides it as a <status> block; the player's
// <lost>/<gained> deltas apply after its final message, and any
// conflicts ride the next GM turn as a <conflict> block.
import { clerkJson } from './clerk.mjs';
import { toolList, runTool, readSettings } from './bundle.mjs';
import { renderView } from './session.mjs';
export class HttpError extends Error {
constructor(status, message, detail) {
super(message);
this.status = status;
this.detail = detail;
}
}
function needSession(ctx, runId) {
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for run '${runId}' — POST /api/runs/${runId}/windows first`);
return s;
}
export async function gmTurn(ctx, runId, line) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
const paper = clerkJson(runId, 'paper'); // fresh per turn
let content = `${line.trim()}\n\n<status>${paper.join(', ')}</status>`;
if (s.conflict) {
content += `\n<conflict>${s.conflict}</conflict>`;
s.conflict = null;
}
s.append({ t: 'msg', m: { role: 'user', content } });
return runLoop(ctx, runId);
}
export async function answerAsk(ctx, runId, answer) {
const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
// execute the paused batch: the ask gets the answer, its siblings
// (if any) get dispatched now — pairing stays whole
for (const call of s.pendingAsk.calls) {
if (call.id === s.pendingAsk.callId) {
s.append({ t: 'tool', ask: true, m: { role: 'tool', tool_call_id: call.id, content: answer } });
} else {
s.append({ t: 'tool', m: { role: 'tool', tool_call_id: call.id, content: runTool(runId, call) } });
}
}
s.pendingAsk = null;
return runLoop(ctx, runId);
}
async function runLoop(ctx, runId) {
const s = ctx.sessions.get(runId);
const tools = toolList(runId);
const model = s.pendingAsk ? null : resolveModel(ctx, runId);
const out = { tools: [] };
for (;;) {
const view = renderView(s);
let msg;
if (ctx.mock) {
msg = mockModel(s, view);
} else {
const data = await ctx.provider.chat(model, view, tools, ctx.cfg.params ?? {});
msg = data.choices[0].message;
s.usage = data.usage
? { promptTokens: data.usage.prompt_tokens, completionTokens: data.usage.completion_tokens }
: null;
}
s.append({ t: 'msg', m: msg, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
if (msg.tool_calls?.length) {
const ask = msg.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 {}
s.pendingAsk = { callId: ask.id, question: q, calls: msg.tool_calls };
s.append({ t: 'note', kind: 'ask', question: q });
out.pendingAsk = q;
return out; // the turn request returns with the question
}
for (const call of msg.tool_calls) {
out.tools.push(call.function.name);
s.append({ t: 'tool', m: { role: 'tool', tool_call_id: call.id, content: runTool(runId, call) } });
}
continue; // let the model see the results before ending its turn
}
// final player message — paper deltas ride the turn text itself
const text = msg.content ?? '';
if (/<(lost|gained)>/.test(text)) {
const r = clerkJson(runId, 'paper-apply', text);
s.append({ t: 'note', kind: 'paper', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
if (r.conflicts?.length) s.conflict = r.conflicts.join('; ');
}
out.player = text;
return out;
}
}
function resolveModel(ctx, runId) {
const meta = ctx.runMeta(runId) ?? {};
return meta.model ?? ctx.cfg.models?.player ?? null;
}
// --- the mock model ----------------------------------------------------------
//
// A scripted stand-in that exercises the loop without a key: turn one
// rolls, turn two asks (the pause/resume path), the answer lands with
// paper deltas (the tag transport), everything after is plain prose.
function mockModel(s, view) {
const call = (name, args, id) => ({
role: 'assistant',
content: null,
tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
});
const assistantCount = s.lines.filter((e) => e.t === 'msg' && e.m.role === 'assistant').length;
const toolResults = view.filter((m) => m.role === 'tool').length;
if (assistantCount === 0 && toolResults === 0) {
return call('roll', { options: ['press on along the hull', 'double back to the container'] }, `mock-roll-${s.lines.length}`);
}
if (assistantCount === 1 && toolResults >= 1) {
return { role: 'assistant', content: 'Mock: the coin says press on. *She presses on, palms flat against the warm metal.*' };
}
if (assistantCount === 2) {
return call('ask_gm', { question: 'From where she stands, does the deck look clear toward the bow?' }, `mock-ask-${s.lines.length}`);
}
if (assistantCount === 3) {
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<lost>worried</lost>\n<gained>settled</gained>' };
}
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
}