Files
tiny-worlds/server/housekeeping.mjs
T
mute 894737fcf3 the 2026-11-16 rounds, the whole day in one commit: model discovery (the two-step op act -- discover scrapes the provider metadata, refine runs the deterministic battery over every id and hands the adjudicated results to the best passing model for the curated registry; state/models.json is the truth of selectable models and gates all model use, a fresh deployment has none; the five named sampling knobs ride run.json params over server.json params, sent only when set; the curator call retries once on the host's network hiccups, its output strictly validated with the machine-list fallback, and the do-not-deliberate line keeps its thinking tokens down); the pick rule reworked on the GM's rulings -- the dv endpoint's 5.2/5.3-max flip was an alias (one model behind both ids), the rank keys on the reasoning bucket not the raw token count (within-bucket differences are sampling noise, the thresholds sit in the endpoint's observed gaps) and full ties settle sort-lex-pick-bottom, with the mock registry carrying a canned tie pair (mock/mock-tie) and the smoke asserting the lex-bottom pick; the play-protocol batch (OOC GM turns carry no cache blocks, memory.json is authored draft applied by the start gate's reapply over a fresh db, /story filters OOC whole, the per-turn raw control on the table); the tunables UX round (web/knobs.mjs: the definitions table with the GM's hint texts and the probed this-endpoint bounds, the per-knob explicit override toggle replacing implicit empty-means-unset diffing, the shared focus-driven hint bar; the run detail and /model responses carry paramDefaults, the deployment layer -- the only default anyone can honestly name); request recording (every provider call lands its resolved model + effective params on the msg event as via, a failed call lands a req event with the failure, both surface on the raw tab and the per-turn raw control on no model-facing surface, a req riding the slidwin tail passes the start lint as conversation machinery; the housekeeping pass log names its model via the clerk's --model flag); the mind verb (<mind> JSON in a player turn sets its sampling for its next turn -- one-shot, max_tokens excluded, a budget not a mind; bounds enforced in KNOB_BOUNDS with the range named in the conflict and the heal restatement the statement that counts; derive() makes a statement live until a player reply consumes it, honest across restarts, session boundaries and forks -- an unconsumed mind rides on); the full-block protocol (the GM rewrote system/invariants/reminder to eliminate the diff verbs: she emits whole <status>/<agenda> at her turn tail, a present block is a whole-list set, absent means unchanged never blank, over-cap agendas evict from the bottom silently -- ruled a feature, silent to her, the note shows the GM; renderView strips every copy and stamps the newest of each kind at the tail of her most recent prose turn, her own emission, so the context reads as the same sequence of events the game had; GM prose goes pure, old logs' composited rides strip, they were never GM words; <mind> is write-only, its tags strip from the view; every turn of hers carries its <model> block -- the params it rode, bare JSON from the via record, the current call included, suppressed when nothing is set, emitting one refused with a pointer at <mind>; the clerk's status-apply/agenda-apply delta verbs RETIRED with their dispatch and collectors, status-set/agenda-set are the player path now; the story strips her blocks, the table chips them; the smoke imports renderView and asserts the view policy directly -- the pattern for testing view-only policy no API exposes); and the opening event RETIRED (the start gate seeds the clerk from her last authored turn's blocks -- the GM moved la-caramba's initial status into her opening turn; old carryovers keep their events as inert history; the event's pre-existing double-landing in every started log, pre-bundle and in-carry, died with the branch); smoke ALL PASS + restart + reminder + repo checks green, browser passes over the knob UX and the new chips and notes with zero console errors, typecheck green on both programs; README and DICTIONARY carry the durable design, HANDOFF trimmed to the map
2026-11-16 21:32:02 +00:00

330 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 (her status
// and agenda carry; the rings reset to the base the manifest lands
// on) -- 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 };