278 lines
13 KiB
JavaScript
278 lines
13 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.
|
|
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 } from './loop.mjs';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
|
|
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.
|
|
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 === 'msg') {
|
|
if (e.m.role === 'user' && e.conflictOnly) {
|
|
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, '');
|
|
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(`[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('; ')}` : ''}`, '');
|
|
} 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]`, '');
|
|
}
|
|
}
|
|
}
|
|
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.
|
|
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
|
|
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, 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 = { 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);
|
|
ctx.enqueue(runId, () => runPass(ctx, runId, latest - 1, user));
|
|
return job;
|
|
}
|
|
|
|
async function runStop(ctx, runId, n, user) {
|
|
const job = 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
|
|
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
|
|
?? ctx.cfg.models?.housekeeper
|
|
?? ctx.cfg.models?.player
|
|
?? null;
|
|
if (!model) throw new Error('no housekeeper model resolved (server.json models.housekeeper, or a per-run override)');
|
|
// 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, ctx.cfg.params ?? {});
|
|
return data.choices[0].message.content ?? '';
|
|
}
|
|
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). 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}`);
|
|
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: 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
|
|
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.
|
|
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 };
|