variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout

This commit is contained in:
2026-11-15 14:35:00 +00:00
parent c51d31078e
commit fa3f23b474
51 changed files with 3477 additions and 1719 deletions
+148 -82
View File
@@ -1,47 +1,66 @@
// server/housekeeping.mjs — the session-close ritual, as an async job.
// server/housekeeping.mjs -- the pass that turns a finished session's
// log into the next session's rings, 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 session log, snapshots the dump) -> mark the session housekept ->
// autorestart: a fresh session 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.
// 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.
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 { openSession, markHousekept, latestSession, lastHousekept } from './session.mjs';
import {
latestSession, sessionMeta, sessionDir, listSessions, loadSession, stopSession, writeMeta,
} from './session.mjs';
import { effectiveContents } from './variants.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();
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); turn-0
// is fiction and stays. GM turns keep their <status> blocks and the
// player's thinking is labeled — both are evidence, never fiction.
// (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.
export function renderTranscript(lines) {
const eff = effectiveContents(lines);
const L = [];
for (const e of lines) {
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
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 === 'msg') {
if (e.m.role === 'user' && e.conflictOnly) {
L.push('[conflict — answered in-band]', e.m.content.replace(/<\/?conflict>/g, '').trim(), '');
L.push('[conflict -- answered in-band]', 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, '');
if (e.m.content) L.push('[player]', e.m.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;
@@ -52,34 +71,37 @@ export function renderTranscript(lines) {
}
if (e.t === 'note') {
if (e.kind === 'status') {
L.push(`[status] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
L.push(`[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(`[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('; ')}` : ''}`, '');
L.push(`[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 opened ${e.at}${e.fresh ? ' — fresh' : ''}]`, '');
} else if (e.kind === 'seed' || e.kind === 'ingest') {
L.push(`[${e.kind}] ${e.ok ? 'ok' : 'failed'}: ${e.detail}`, '');
L.push(`[session ${e.n} opened]`, '');
}
}
}
return L.join('\n');
}
// the housekeeper's fresh context; run state rides alongside the prompt
export function buildMessages(runId, lines, stamp) {
// 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.
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 ${stamp}.`;
? '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, 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: 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) },
];
}
@@ -105,46 +127,70 @@ export function parseManifest(text) {
export function trigger(ctx, runId, user) {
requireRun(runId);
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open session for '${runId}' — housekeeping is the session-close ritual`);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it before closing the session');
ctx.sessions.delete(runId); // the session is closed from here on
const job = { state: 'running', session: s.stamp, started: new Date().toISOString() };
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 = { 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 package\'s memory.json -- edit them in setup; there is no session zero to re-run');
}
const job = { state: 'running', phase: 'rerun', session: latest - 1, target: latest, started: new Date().toISOString() };
ctx.jobs.set(runId, job);
// the whole async chain holds the run's activity lock — a fork
// enqueued behind it copies the post-apply state, never a half-apply
ctx.enqueue(runId, () => runJob(ctx, runId, s.stamp, s.lines, user));
ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user));
return job;
}
async function runJob(ctx, runId, stamp, lines, user) {
async function runStop(ctx, runId, n, user) {
const job = ctx.jobs.get(runId);
try {
const text = ctx.mock
? mockManifest(stamp)
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp), user);
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.session = mf.session;
job.next = next.stamp;
job.state = 'applied';
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
async function runPass(ctx, runId, n, user) {
const job = ctx.jobs.get(runId);
const lines = loadSession(runId, n).lines;
const text = ctx.mock
? mockManifest(n)
: await callHousekeeper(ctx, runId, buildMessages(runId, n, lines), user);
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);
job.target = n + 1;
job.state = 'applied';
}
async function callHousekeeper(ctx, runId, messages, user) {
const meta = ctx.runMeta?.(runId) ?? {};
const model = meta.models?.housekeeper
@@ -159,36 +205,56 @@ async function callHousekeeper(ctx, runId, messages, user) {
}
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);
// The apply: rebase + apply + ready, into the dormant session n+1.
// Shared by the chain and the manual apply endpoint (hand-edited
// manifests). 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.
export function applyToDormant(runId, manifestPath, n) {
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), 'apply', manifestPath);
if (r.code !== 0) throw new Error(`apply rejected:\n${r.err || r.out}`);
markHousekept(runId, sessionStamp);
const s = openSession(runId); // the #21 guard passes now
ctx.sessions.set(runId, s);
return s;
writeMeta(runId, n + 1, { ready: true });
}
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
// 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);
const hk = lastHousekept(runId);
if (latest && latest === hk) return { state: 'applied', session: hk };
return { state: 'idle' };
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
export function latestLog(runId) {
const dir = path.join(runDir(runId), 'log');
if (!fs.existsSync(dir)) throw new HttpError(404, 'no session logs yet');
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
if (!files.length) throw new HttpError(404, 'no session logs yet');
const f = files[files.length - 1];
return { session: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
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 ----------------------------------------------------
@@ -196,9 +262,9 @@ export function latestLog(runId) {
// 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) {
function mockManifest(n) {
return JSON.stringify({
session: stamp.toLowerCase(),
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: [{