Files
tiny-worlds/server/housekeeping.mjs
T

331 lines
16 KiB
JavaScript
Raw Normal View History

// server/housekeeping.mjs -- the pass that turns a finished session's
// log into the next session's rings, as an async job.
//
// One trigger, two behaviors. With a live session it is STOP: close
// the session, move the tail into the new dormant session's
// carryover, freeze the finished one, then run the pass. With a
// dormant latest it is the RE-RUN: rebase the dormant session's db
// from the finished one's frozen copy and apply a fresh manifest.
// Re-enterable by ruling: a fresh LLM call each time (non-
// idempotent), but never double-applying -- the rebase resets, and
// hand edits made in between are overwritten (the armed button warns).
//
// The pass: 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 into the dormant session (which
// validates, writes the log, snapshots the dump) -> mark ready. A
// rejection at any step holds the state and surfaces why; the
// manifest (or the raw output, if unparseable) stays on disk for a
// hand edit and POST .../housekeeping/apply.
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').JobState} JobState */
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
/** @typedef {import('./shapes.mjs').Manifest} Manifest */
/** @typedef {import('./shapes.mjs').Actor} Actor */
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 {
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
} from './session.mjs';
import { effectiveContents } from './variants.mjs';
import { HttpError, specFromMeta, gateSpec, resolveSpec } from './loop.mjs';
import { providerFor } from './provider.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
/** @param {string} dir @param {string} f @returns {string} */
const readAt = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').trim();
// --- transcript --------------------------------------------------------------
// The effective view for the housekeeper: the exchange, not the bundle
// (card, backdrop and rings are provided as separate inputs); the
// opening is fiction and stays. GM turns keep their <status> blocks
// and the player's thinking is labeled -- both are evidence, never
// fiction. Variant turns render only the picked variant: the unpicked
// branches never happened, and must never enter memory. The log is
// read as it was left -- stop already truncated it at the slidwin
// boundary, so the rings never overlap the carried prose.
/** @param {LogEvent[]} lines @returns {string} */
export function renderTranscript(lines) {
const eff = effectiveContents(lines);
const L = [];
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
if (e.t === 'bundle') continue; // context, not exchange -- provided as separate inputs
if (e.t === 'msg' && e.reminder) continue; // identical every turn -- context, not exchange
2026-11-16 21:32:02 +00:00
if (e.t === 'req') continue; // a failed request's record -- machinery, not exchange
if (e.t === 'msg') {
if (e.m.role === 'user' && e.conflictOnly) {
L.push('[conflict -- answered in-band]', String(e.m.content ?? '').replace(/<\/?conflict>/g, '').trim(), '');
continue;
}
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, '');
const content = eff.has(i) ? eff.get(i) : e.m.content;
if (content) L.push('[player]', 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 === 'status') {
2026-11-16 21:32:02 +00:00
L.push(e.set
? `[status] set: ${JSON.stringify(e.set)}`
: `[status] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` -- conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
} else if (e.kind === 'agenda') {
2026-11-16 21:32:02 +00:00
L.push(e.set
? `[agenda] set: ${JSON.stringify(e.set)}${e.evicted?.length ? ` -- evicted: ${JSON.stringify(e.evicted)}` : ''}`
: `[agenda] added: ${JSON.stringify(e.applied?.added ?? [])}, dropped: ${JSON.stringify(e.applied?.dropped ?? [])}, evicted: ${JSON.stringify(e.applied?.evicted ?? [])}${e.conflicts?.length ? ` -- conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
} else if (e.kind === 'pick') {
L.push(`[variant pick] ${e.count} candidate turns offered, #${e.chosen + 1} picked`, '');
} else if (e.kind === 'ask') {
L.push(`[ask_gm pending] ${e.question}`, '');
} else if (e.kind === 'session') {
L.push(`[session ${e.n} opened]`, '');
2026-11-16 21:32:02 +00:00
} else if (e.kind === 'mind') {
L.push(`[mind] ${Object.entries(e.params ?? {}).map(([k, v]) => `${k} ${v}`).join(', ')} -- set for her next turn`, '');
}
}
}
return L.join('\n');
}
// the housekeeper's fresh context; run state rides alongside the
// prompt. The card, backdrop and rings are the FINISHED session's
// own frozen material -- exactly what it played with.
/** @param {string} runId @param {number} n @param {LogEvent[]} lines @returns {{ role: 'system'|'user', content: string }[]} */
export function buildMessages(runId, n, lines) {
const dir = sessionDir(runId, n);
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 number ${n}.`;
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, readAt(dir, path.join('bundle', 'character.md'))) },
{ role: 'user', content: expandVars(runId, readAt(dir, path.join('bundle', 'backdrop.md'))) },
{ role: 'user', content: readAt(dir, path.join('canon', 'ring-a.md')) },
{ role: 'user', content: readAt(dir, path.join('canon', 'ring-b.md')) },
{ role: 'user', content: renderTranscript(lines) },
];
}
// --- the manifest ------------------------------------------------------------
// the housekeeper emits one JSON manifest; tolerate fences and prose
/** @param {?string} text @returns {Manifest} */
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 -----------------------------------------------------------------
/**
* @param {Ctx} ctx @param {string} runId @param {?Actor} user
* @returns {JobState}
*/
export function trigger(ctx, runId, user) {
requireRun(runId);
const live = ctx.sessions.get(runId);
const latest = latestSession(runId);
if (latest == null) throw new HttpError(409, 'this run has no sessions');
if (live) {
// STOP: the manual close. The move and the freeze happen inside
// the job (under the run's activity lock), then the pass runs.
if (live.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it before stopping the session');
ctx.sessions.delete(runId); // the session is closed from here on
const job = /** @type {JobState} */ ({ state: 'running', phase: 'stop', session: live.n, started: new Date().toISOString() });
ctx.jobs.set(runId, job);
ctx.enqueue(runId, () => runStop(ctx, runId, live.n, user));
return job;
}
// the RE-RUN: housekeeping over the finished predecessor, applying
// into the dormant latest. Session one has no predecessor -- its
// rings are its package's memory.json, edited in setup.
const meta = sessionMeta(runId, latest);
if (meta.phase !== 'dormant') throw new HttpError(409, `session ${latest} is ${meta.phase || 'unmarked'} -- nothing to housekeep`);
if (latest === 1) {
2026-11-16 21:32:02 +00:00
throw new HttpError(409, 'session one\'s memories are its memory.json -- edit it in setup and start (the start gate applies it); there is no session zero to re-run');
}
const job = /** @type {JobState} */ ({ state: 'running', phase: 'rerun', session: latest - 1, target: latest, started: new Date().toISOString() });
ctx.jobs.set(runId, job);
ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user));
return job;
}
/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise<void>} */
async function runStop(ctx, runId, n, user) {
const job = /** @type {JobState} */ (ctx.jobs.get(runId));
try {
stopSession(runId, n); // the move, the freeze, the copies
job.stopped = true;
await runPass(ctx, runId, n, user);
} catch (e) {
job.state = 'rejected';
job.reason = e.message;
}
}
// one housekeeping pass: session n's log -> manifest -> apply into
// the dormant session n+1 -> ready
/** @param {Ctx} ctx @param {string} runId @param {number} n @param {?Actor} user @returns {Promise<void>} */
async function runPass(ctx, runId, n, user) {
const job = /** @type {JobState} */ (ctx.jobs.get(runId));
const lines = loadSession(runId, n).lines;
2026-11-16 21:32:02 +00:00
// the pass names its model: the real pass resolves it, the mock
// pass marks itself
let text;
let model = 'mock';
if (ctx.mock) {
text = mockManifest(n);
} else {
const r = await callHousekeeper(ctx, runId, buildMessages(runId, n, lines), user);
text = r.content;
model = r.model;
}
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, `${n}.raw.md`), String(text));
throw new Error(`${e.message} -- raw output saved to manifests/${n}.raw.md`);
}
const manifestPath = path.join(dir, `${n}.json`);
fs.writeFileSync(manifestPath, JSON.stringify(mf, null, 2) + '\n');
job.manifest = `manifests/${n}.json`;
2026-11-16 21:32:02 +00:00
applyToDormant(runId, manifestPath, n, model);
job.target = n + 1;
job.state = 'applied';
}
/** @typedef {import('./shapes.mjs').RunMeta} RunMeta */
/**
* @param {Ctx} ctx @param {string} runId
* @param {import('./shapes.mjs').ViewMessage[]} messages @param {?Actor} user
2026-11-16 21:32:02 +00:00
* @returns {Promise<{ content: string, model: string }>}
*/
async function callHousekeeper(ctx, runId, messages, user) {
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
// the run's own housekeeper pick, else the player spec's provider's
// default (GM, 2026-11-18: the housekeeper inherits -- per-provider
// defaults mean no separate deployment default exists to fall to)
let spec = specFromMeta(meta.models?.housekeeper, 'housekeeper');
if (!spec) {
const player = resolveSpec(ctx, runId, 'player');
const def = ctx.providerCfg.providers.find((p) => p.slug === player.provider)?.default ?? null;
if (def) spec = { provider: player.provider, model: def.model, effort: def.effort };
2026-11-16 21:32:02 +00:00
}
if (!spec) throw new Error('no housekeeper model resolved (the run\'s housekeeper pick, or its player provider\'s default)');
gateSpec(ctx, spec, 'housekeeper');
const params = { reasoning_effort: spec.effort };
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${spec.model} u:${user?.id ?? '?'}`);
const data = await providerFor(ctx, spec.provider).chat(spec.model, messages, undefined, params);
return { content: data.choices[0].message.content ?? '', model: spec.model };
}
export { callHousekeeper };
// The apply: rebase + apply + ready, into the dormant session n+1.
// Shared by the chain and the manual apply endpoint (hand-edited
2026-11-16 21:32:02 +00:00
// manifests). model, when given, is the pass's model -- the apply
// log names it (a hand apply has none). The rebase is the
// re-enterability: every run starts
2026-11-16 22:49:50 +00:00
// from a fresh copy of the finished session's frozen db (the rings
// carry, the manifest lands on them; her status and agenda never
// lived here -- the log is their one truth) -- so re-runs never
// double-apply, and hand edits made in between are overwritten,
// ruled fine.
2026-11-16 21:32:02 +00:00
/** @param {string} runId @param {string} manifestPath @param {number} n @param {?string} [model] */
export function applyToDormant(runId, manifestPath, n, model = null) {
const target = sessionDir(runId, n + 1);
if (sessionMeta(runId, n + 1).phase !== 'dormant') {
throw new Error(`session ${n + 1} is not dormant -- housekeeping applies into the dormant session`);
}
fs.rmSync(path.join(target, 'dumps'), { recursive: true, force: true });
fs.rmSync(path.join(target, 'log'), { recursive: true, force: true }); // superseded attempts
fs.rmSync(path.join(target, 'canon'), { recursive: true, force: true });
fs.mkdirSync(path.join(target, 'db'), { recursive: true });
fs.copyFileSync(path.join(sessionDir(runId, n), 'db', 'memory.db'), path.join(target, 'db', 'memory.db'));
2026-11-16 21:32:02 +00:00
const r = clerk(runId, '--session', String(n + 1), ...(model ? ['--model', model] : []), 'apply', manifestPath);
if (r.code !== 0) throw new Error(`apply rejected:\n${r.err || r.out}`);
writeMeta(runId, n + 1, { ready: true });
}
/** @param {Ctx} ctx @param {string} runId @returns {JobState} */
export function jobState(ctx, runId) {
requireRun(runId);
const job = ctx.jobs.get(runId);
if (job) return job;
// derive from disk after a restart: the latest session tells the
// story. Session one is born ready -- its rings are its own.
const latest = latestSession(runId);
if (latest == null || latest === 1) return { state: 'idle' };
const meta = sessionMeta(runId, latest);
if (meta.phase === 'live') return { state: 'idle' };
return meta.ready === true
? { state: 'applied', session: latest - 1, target: latest }
: { state: 'pending', session: latest - 1, target: latest };
}
// the newest housekeeping record on disk
/** @param {string} runId @returns {{ session: number, pass: string, content: string }} */
export function latestLog(runId) {
const ns = listSessions(runId);
for (let i = ns.length - 1; i >= 0; i--) {
const dir = path.join(sessionDir(runId, ns[i]), 'log');
if (!fs.existsSync(dir)) continue;
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
if (files.length) {
const f = files[files.length - 1];
return { session: ns[i], pass: f.replace(/\.md$/, ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
}
}
throw new HttpError(404, 'no housekeeping logs yet');
}
// --- 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.
/** @param {number} n @returns {string} */
function mockManifest(n) {
return JSON.stringify({
session: String(n),
summary: 'Mock housekeeping: 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 };