Files
tiny-worlds/server/housekeeping.mjs
T
mute 5ffecee935 the state-scan round: the log is the one truth for status and agenda, the db tiers retired -- scanState (server/session.mjs) derives each kind newest-wins across her emissions (the picked variant's text), the GM's override records, and the boundary state notes; the panes, the run detail, and the stamp all read it, GET /status and detail.status are derived reads, no clerk call, no db copy; the agenda cap is a derivation rule (GM, 2026-11-16: we log all seven items on reception, but the only way to see all seven is the raw event -- at no point an over-cap list can be derived), the reception note still shows the GM what sank; the stamp renders the canonical grammar -- status comma-separated, agenda markdown bullets, matching the line the GM added to invariants; the GM's block edits are overrides (GM, 2026-11-16: mutate during the contwin composition, the logs record the overrides arriving with the GM's turn as they should, the model sees the blocks overwritten with GM's edits attached to her turn, append if empty): the pane editors STAGE (paneEditor reworked -- no save callback, staged state, pending marker, discard), the send attaches them to POST /turn, node logs the override field on the GM turn, the composition renders it as hers -- the log never mutates, her words stay verbatim, the raw surfaces show the record; OOC turns refuse edits client and server both, the out-of-band POST /status and /agenda routes retired; stop writes the boundary state note at the carry head always (the crash-reconcile filters it before comparing), the start gate's n=1 seeding is dead (her authored opening turn IS the seed, the lint keeps requiring it), continuation carryovers are writable in the file editor during dormancy -- the review window's one editing surface, blocks included, no new pane; the clerk lost the tiers wholesale (schema tables, four verbs, canon status/agenda views, dump sections, report fields; the events CHECK keeps the historical op names; old dbs keep dead tables, never read, never dropped -- Irene is hands-off, and by the same day's ruling she is broken and never runs again: logs and db kept as they are, no replay, no continuation, no compatibility designed for her); Chloe hand-migrated to the new protocol -- her most recent turn carries the whole-list blocks applied from her db's exact values, her next context stamps them, her older lost/gained tags stay as history; the mock's agenda blocks went bullet, a new script position for the override turn's reply restates the mind so the boundary assert holds; smoke reworked to the scan battery (+ the 10f override block: the record rides its turn, the composition stamps at her canon point, the log keeps her emission verbatim, the OOC refusal, the boundary note at the carry head, the retired routes 404) -- ALL PASS; restart + reminder + repo checks green; the browser pass caught and fixed two real bugs (the pending marker's display:flex beat the hidden attribute -- any display rule needs a [hidden] override; setEditable(true) never ran the widget sync so the edit button stayed hidden) and proved the whole UX end to end with zero console errors -- staging, send-with-turn, the machinery lines on the table and raw, the OOC gate banner, discard, dormant read-only panes, the boundary note in the dormant preview; typecheck green on both programs; README/DICTIONARY carry the single-truth design, HANDOFF the round record and the Irene rewording, AGENTS the state pointer and the browser lessons
2026-11-16 22:49:50 +00:00

331 lines
16 KiB
JavaScript

// 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, resolveParams } from './loop.mjs';
import { registry, usable } from './discovery.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
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') {
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') {
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]`, '');
} 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) {
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;
// 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`;
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
* @returns {Promise<{ content: string, model: string }>}
*/
async function callHousekeeper(ctx, runId, messages, user) {
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
const reg = registry();
const model = meta.models?.housekeeper
?? ctx.cfg.models?.housekeeper
?? ctx.cfg.models?.player
?? reg?.defaults.housekeeper
?? reg?.defaults.player
?? null;
if (!model) throw new Error('no housekeeper model resolved (a per-run override, server.json models, or the registry\'s discovered default)');
if (!usable(reg, model)) {
throw new Error(`model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ' -- the op has not run discovery yet'}`);
}
const params = resolveParams(ctx, runId, 'housekeeper');
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, messages, undefined, params);
return { content: data.choices[0].message.content ?? '', 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
// 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
// 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.
/** @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'));
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 };