Files
tiny-worlds/server/housekeeping.mjs
T

197 lines
8.5 KiB
JavaScript
Raw Normal View History

// 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') continue; // context, not exchange — provided as separate inputs
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, fs.readFileSync(path.join(ROOT, 'housekeeper.md'), 'utf8').trim()) }, // substrate-internal, repo-fed
{ 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 ?? '';
}
export { callHousekeeper };
// 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(),
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',
}],
});
}
export { mockManifest };