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:
@@ -0,0 +1,198 @@
|
||||
// server/housekeeping.mjs — the window-close ritual, as an async job.
|
||||
//
|
||||
// The chain, unattended: render the transcript -> invoke the
|
||||
// housekeeper on a fresh context (its prompt, run state, the card, the
|
||||
// backdrop, both ring views, the transcript with labeled thinking) ->
|
||||
// save the manifest -> apply via the clerk (which validates, writes
|
||||
// the window log, snapshots the dump) -> mark the session housekept ->
|
||||
// autorestart: a fresh window opens with fresh views. A rejection at
|
||||
// any step holds the restart and surfaces why; the manifest (or the
|
||||
// raw output, if unparseable) stays on disk for a hand edit and
|
||||
// POST .../housekeeping/apply.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { clerk } from './clerk.mjs';
|
||||
import { runDir, requireRun, readSettings, expandVars } from './bundle.mjs';
|
||||
import { openWindow, markHousekept, latestSession, lastHousekept } from './session.mjs';
|
||||
import { HttpError } from './loop.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
const readRun = (runId, f) => fs.readFileSync(path.join(runDir(runId), f), 'utf8').trim();
|
||||
|
||||
// --- transcript --------------------------------------------------------------
|
||||
|
||||
// The effective view for the housekeeper: the exchange, not the bundle
|
||||
// (card, backdrop and rings are provided as separate inputs); turn-0
|
||||
// is fiction and stays. GM turns keep their <status> blocks and the
|
||||
// player's thinking is labeled — both are evidence, never fiction.
|
||||
export function renderTranscript(lines) {
|
||||
const L = [];
|
||||
for (const e of lines) {
|
||||
if (e.t === 'bundle') {
|
||||
if (e.part === 'turn-0') L.push('[GM: opening beat]', e.m.content, '');
|
||||
continue;
|
||||
}
|
||||
if (e.t === 'msg') {
|
||||
if (e.m.role === 'user') {
|
||||
L.push('[GM]', e.m.content, '');
|
||||
} else if (e.m.role === 'assistant') {
|
||||
if (e.m.reasoning_content) L.push('[thinking]', e.m.reasoning_content, '');
|
||||
if (e.m.content) L.push('[player]', e.m.content, '');
|
||||
for (const c of e.m.tool_calls ?? []) L.push(`[tool call] ${c.function.name} ${c.function.arguments}`, '');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (e.t === 'tool') {
|
||||
L.push(e.ask ? '[GM ruling]' : '[tool result]', e.m.content, '');
|
||||
continue;
|
||||
}
|
||||
if (e.t === 'note') {
|
||||
if (e.kind === 'paper') {
|
||||
L.push(`[paper] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
|
||||
} else if (e.kind === 'ask') {
|
||||
L.push(`[ask_gm pending] ${e.question}`, '');
|
||||
} else if (e.kind === 'window') {
|
||||
L.push(`[window opened ${e.at}${e.fresh ? ' — fresh' : ''}]`, '');
|
||||
} else if (e.kind === 'seed' || e.kind === 'ingest') {
|
||||
L.push(`[${e.kind}] ${e.ok ? 'ok' : 'failed'}: ${e.detail}`, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
// the housekeeper's fresh context; run state rides alongside the prompt
|
||||
export function buildMessages(runId, lines, stamp) {
|
||||
const settings = readSettings(runId);
|
||||
const runState = `Run state: records ${settings.records === true
|
||||
? 'available — this character keeps files; the archive op is valid'
|
||||
: 'none — this character keeps no files; the archive op is invalid'}. The ended session is ${stamp}.`;
|
||||
return [
|
||||
{ role: 'system', content: expandVars(runId, readRun(runId, 'housekeeper.md')) },
|
||||
{ role: 'user', content: runState },
|
||||
{ role: 'user', content: expandVars(runId, readRun(runId, 'character.md')) },
|
||||
{ role: 'user', content: expandVars(runId, readRun(runId, 'backdrop.md')) },
|
||||
{ role: 'user', content: readRun(runId, path.join('canon', 'ring-a.md')) },
|
||||
{ role: 'user', content: readRun(runId, path.join('canon', 'ring-b.md')) },
|
||||
{ role: 'user', content: renderTranscript(lines) },
|
||||
];
|
||||
}
|
||||
|
||||
// --- the manifest ------------------------------------------------------------
|
||||
|
||||
// the housekeeper emits one JSON manifest; tolerate fences and prose
|
||||
export function parseManifest(text) {
|
||||
const fences = [...String(text ?? '').matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1]);
|
||||
for (const c of [...fences, String(text ?? '')]) {
|
||||
const t = c.trim();
|
||||
try { return JSON.parse(t); } catch {}
|
||||
const a = t.indexOf('{');
|
||||
const b = t.lastIndexOf('}');
|
||||
if (a !== -1 && b > a) {
|
||||
try { return JSON.parse(t.slice(a, b + 1)); } catch {}
|
||||
}
|
||||
}
|
||||
throw new Error('the housekeeper emitted no parseable JSON manifest');
|
||||
}
|
||||
|
||||
// --- the job -----------------------------------------------------------------
|
||||
|
||||
export function trigger(ctx, runId) {
|
||||
requireRun(runId);
|
||||
const s = ctx.sessions.get(runId);
|
||||
if (!s) throw new HttpError(409, `no open window for '${runId}' — housekeeping is the window-close ritual`);
|
||||
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it before closing the window');
|
||||
ctx.sessions.delete(runId); // the window is closed from here on
|
||||
const job = { state: 'running', session: s.stamp, started: new Date().toISOString() };
|
||||
ctx.jobs.set(runId, job);
|
||||
runJob(ctx, runId, s.stamp, s.lines); // async; catches its own errors
|
||||
return job;
|
||||
}
|
||||
|
||||
async function runJob(ctx, runId, stamp, lines) {
|
||||
const job = ctx.jobs.get(runId);
|
||||
try {
|
||||
const text = ctx.mock
|
||||
? mockManifest(stamp)
|
||||
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp));
|
||||
const dir = path.join(runDir(runId), 'manifests');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
let mf;
|
||||
try {
|
||||
mf = parseManifest(text);
|
||||
} catch (e) {
|
||||
fs.writeFileSync(path.join(dir, `${stamp}.raw.md`), String(text));
|
||||
throw new Error(`${e.message} — raw output saved to manifests/${stamp}.raw.md`);
|
||||
}
|
||||
const manifestPath = path.join(dir, `${stamp}.json`);
|
||||
fs.writeFileSync(manifestPath, JSON.stringify(mf, null, 2) + '\n');
|
||||
job.manifest = `manifests/${stamp}.json`;
|
||||
const next = applyAndRestart(ctx, runId, manifestPath, stamp);
|
||||
job.window = mf.window;
|
||||
job.next = next.stamp;
|
||||
job.state = 'applied';
|
||||
} catch (e) {
|
||||
job.state = 'rejected';
|
||||
job.reason = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function callHousekeeper(ctx, runId, messages) {
|
||||
const model = ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player ?? null;
|
||||
if (!model) throw new Error('no housekeeper model configured (server.json models.housekeeper)');
|
||||
const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {});
|
||||
return data.choices[0].message.content ?? '';
|
||||
}
|
||||
|
||||
// apply -> mark housekept -> autorestart. Shared by the chain and the
|
||||
// manual apply endpoint (hand-edited manifests).
|
||||
export function applyAndRestart(ctx, runId, manifestPath, sessionStamp) {
|
||||
const r = clerk(runId, 'apply', manifestPath);
|
||||
if (r.code !== 0) throw new Error(`apply rejected:\n${r.err || r.out}`);
|
||||
markHousekept(runId, sessionStamp);
|
||||
const s = openWindow(runId); // the #21 guard passes now
|
||||
ctx.sessions.set(runId, s);
|
||||
return s;
|
||||
}
|
||||
|
||||
export function jobState(ctx, runId) {
|
||||
requireRun(runId);
|
||||
const job = ctx.jobs.get(runId);
|
||||
if (job) return job;
|
||||
// derive from disk after a restart: applied iff the latest session is
|
||||
// the one marked housekept
|
||||
const latest = latestSession(runId);
|
||||
const hk = lastHousekept(runId);
|
||||
if (latest && latest === hk) return { state: 'applied', session: hk };
|
||||
return { state: 'idle' };
|
||||
}
|
||||
|
||||
export function latestLog(runId) {
|
||||
const dir = path.join(runDir(runId), 'log');
|
||||
if (!fs.existsSync(dir)) throw new HttpError(404, 'no window logs yet');
|
||||
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
|
||||
if (!files.length) throw new HttpError(404, 'no window logs yet');
|
||||
const f = files[files.length - 1];
|
||||
return { window: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
|
||||
}
|
||||
|
||||
// --- the mock housekeeper ----------------------------------------------------
|
||||
//
|
||||
// A canned but valid manifest keyed to the mock player's script: touches
|
||||
// the cuffs (they shaped every move) and files the dark hold as a new
|
||||
// ring-B memory. Exercises the whole chain without a key.
|
||||
function mockManifest(stamp) {
|
||||
return JSON.stringify({
|
||||
window: stamp.toLowerCase(),
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.',
|
||||
touch: [{ id: 'e1', reason: 'the cuffs shaped every move she made' }],
|
||||
insert: [{
|
||||
ring: 'b', type: 'place', label: 'The dark hold',
|
||||
detail: 'I ducked into an open hatch in the hull. Something in there clicks, steady like a clock.',
|
||||
reason: 'she went in',
|
||||
}],
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user