spa modules and terminology: app.mjs split into flat es modules (router lifecycle, shared widgets, views own their state), mock smoke in test/; DICTIONARY.md rules the terms, four renames swept clean through the machinery - paper->status (run summary command is report now), window->session, wrap->housekeeping, context window->contwin; no dual-accepts by ruling, old data migrates once in the clerk (restore self-heals old dumps)

This commit is contained in:
2026-11-14 23:48:27 +00:00
parent 89a2c161b3
commit c51d31078e
36 changed files with 2643 additions and 1779 deletions
+2 -2
View File
@@ -7,7 +7,7 @@
// lands staged under a dot-name and is swapped in by a same-volume
// rename, which is atomic — no reader ever sees a half-run. The
// caller holds the source run's activity lock, so the copy is never
// taken mid-turn; a copied open window reopens honestly in the fork
// taken mid-turn; a copied open session reopens honestly in the fork
// (the log is the truth, same as boot-rebuild).
import fs from 'node:fs';
import path from 'node:path';
@@ -34,7 +34,7 @@ export function forkRun(ctx, srcId, user) {
meta.forked = Math.floor(Date.now() / 1000); // unixtime, UTC by definition
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
fs.renameSync(staging, path.join(RUNS_DIR, id)); // same-volume rename: the atomic swap-in
// an open, unhousekept window in the source is an open window in the
// an open, unhousekept session in the source is an open session in the
// fork — its transcript reaches the fork's rings only after the fork
// housekeeps it, same rule as the original
const latest = latestSession(id);
+19 -19
View File
@@ -1,11 +1,11 @@
// server/housekeeping.mjs — the window-close ritual, as an async job.
// server/housekeeping.mjs — the session-close ritual, 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 window log, snapshots the dump) -> mark the session housekept ->
// autorestart: a fresh window opens with fresh views. A rejection at
// 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.
@@ -14,7 +14,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { clerk } from './clerk.mjs';
import { runDir, requireRun, readSettings, expandVars } from './bundle.mjs';
import { openWindow, markHousekept, latestSession, lastHousekept } from './session.mjs';
import { openSession, markHousekept, latestSession, lastHousekept } from './session.mjs';
import { HttpError } from './loop.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -51,14 +51,14 @@ export function renderTranscript(lines) {
continue;
}
if (e.t === 'note') {
if (e.kind === 'paper') {
L.push(`[paper] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
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 === 'ask') {
L.push(`[ask_gm pending] ${e.question}`, '');
} else if (e.kind === 'window') {
L.push(`[window opened ${e.at}${e.fresh ? ' — fresh' : ''}]`, '');
} 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}`, '');
}
@@ -106,13 +106,13 @@ 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 window for '${runId}' — housekeeping is the window-close ritual`);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it before closing the window');
ctx.sessions.delete(runId); // the window is closed from here on
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() };
ctx.jobs.set(runId, job);
// the whole async chain holds the run's activity lock — a fork
// enqueued behind it copies the post-wrap state, never a half-apply
// enqueued behind it copies the post-apply state, never a half-apply
ctx.enqueue(runId, () => runJob(ctx, runId, s.stamp, s.lines, user));
return job;
}
@@ -136,7 +136,7 @@ async function runJob(ctx, runId, stamp, lines, user) {
fs.writeFileSync(manifestPath, JSON.stringify(mf, null, 2) + '\n');
job.manifest = `manifests/${stamp}.json`;
const next = applyAndRestart(ctx, runId, manifestPath, stamp);
job.window = mf.window;
job.session = mf.session;
job.next = next.stamp;
job.state = 'applied';
} catch (e) {
@@ -165,7 +165,7 @@ export function applyAndRestart(ctx, runId, manifestPath, sessionStamp) {
const r = clerk(runId, 'apply', manifestPath);
if (r.code !== 0) throw new Error(`apply rejected:\n${r.err || r.out}`);
markHousekept(runId, sessionStamp);
const s = openWindow(runId); // the #21 guard passes now
const s = openSession(runId); // the #21 guard passes now
ctx.sessions.set(runId, s);
return s;
}
@@ -184,11 +184,11 @@ export function jobState(ctx, runId) {
export function latestLog(runId) {
const dir = path.join(runDir(runId), 'log');
if (!fs.existsSync(dir)) throw new HttpError(404, 'no window logs yet');
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 window logs yet');
if (!files.length) throw new HttpError(404, 'no session logs yet');
const f = files[files.length - 1];
return { window: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
return { session: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
}
// --- the mock housekeeper ----------------------------------------------------
@@ -198,8 +198,8 @@ export function latestLog(runId) {
// ring-B memory. Exercises the whole chain without a key.
function mockManifest(stamp) {
return JSON.stringify({
window: stamp.toLowerCase(),
summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.',
session: stamp.toLowerCase(),
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',
+11 -11
View File
@@ -3,7 +3,7 @@
// Synchronous REST: a POST runs the tool loop and returns. ask_gm
// pauses mid-turn — the whole tool-call batch waits (pairing stays
// sound), the request returns with the pending question, and the
// answer call resumes the loop. The paper is re-read from the clerk
// answer call resumes the loop. The status is re-read from the clerk
// before every GM turn and rides it as a <status> block; the player's
// <lost>/<gained> deltas apply after its final message, and any
// conflicts ride the next GM turn as a <conflict> block.
@@ -23,18 +23,18 @@ export class HttpError extends Error {
function needSession(ctx, runId) {
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for run '${runId}' — POST /api/runs/${runId}/windows first`);
if (!s) throw new HttpError(409, `no open session for run '${runId}' — POST /api/runs/${runId}/sessions first`);
return s;
}
export async function gmTurn(ctx, runId, line, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
const paper = clerkJson(runId, 'paper'); // fresh per turn
const status = clerkJson(runId, 'status'); // fresh per turn
const agenda = clerkJson(runId, 'agenda'); // fresh per turn
// the wire renders the queue as the model cites it: numbered from the top
const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; ');
const content = `${line.trim()}\n\n<status>${paper.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
const content = `${line.trim()}\n\n<status>${status.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
s.append({ t: 'msg', m: { role: 'user', content } });
// the reminder follows the GM's prose as its own system chunk —
// every turn, one live copy (older ones elide in the view)
@@ -44,9 +44,9 @@ export async function gmTurn(ctx, runId, line, user) {
}
// the opening beat: turn-0 sent as the first GM turn, separate from
// the bundle (start = open window, then this). Its trailing <status>
// block was ingested as her opening paper at window-open — stripped
// here, since the normal ride carries the current paper on every GM
// the bundle (start = open session, then this). Its trailing <status>
// block was ingested as her opening status at session-open — stripped
// here, since the normal ride carries the current status on every GM
// turn, the beat included.
export async function turn0(ctx, runId, user) {
const s = needSession(ctx, runId);
@@ -118,15 +118,15 @@ async function runLoop(ctx, runId, user) {
continue; // let the model see the results before ending its turn
}
// final player message — the paper and agenda deltas ride the turn
// final player message — the status and agenda deltas ride the turn
// text. Same-verb blocks combine into one apply (the clerk's
// collectors gather every block before executing anything), never a
// sequence of applies.
const text = msg.content ?? '';
const carry = [];
if (/<(lost|gained)>/.test(text)) {
const r = clerkJson(runId, 'paper-apply', text);
s.append({ t: 'note', kind: 'paper', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
const r = clerkJson(runId, 'status-apply', text);
s.append({ t: 'note', kind: 'status', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
carry.push(...(r.conflicts ?? []));
}
if (/<(add|drop)>/.test(text)) {
@@ -157,7 +157,7 @@ function resolveModel(ctx, runId) {
//
// A scripted stand-in that exercises the loop without a key: turn one
// rolls, turn two asks (the pause/resume path), the answer lands with
// paper deltas (the tag transport), everything after is plain prose.
// status deltas (the tag transport), everything after is plain prose.
function mockModel(s, view) {
const call = (name, args, id) => ({
role: 'assistant',
+38 -37
View File
@@ -4,7 +4,7 @@
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// window back from the jsonl — the log is the truth, the context is a
// session back from the jsonl — the log is the truth, the context is a
// view.
//
// usage: node server/main.mjs [--mock]
@@ -30,6 +30,7 @@ if (!fs.existsSync(CONFIG_PATH)) {
process.exit(1);
}
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
const provider = makeProvider(cfg.endpoint ?? {});
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
@@ -38,7 +39,7 @@ const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), r
// Serializes every async mutation span (turn, ask, turn0, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (paper-set, file writes) need no lock: they
// Sync-only handlers (status-set, file writes) need no lock: they
// block the event loop and are atomic by construction.
ctx.locks = new Map();
ctx.enqueue = (runId, fn) => {
@@ -197,7 +198,7 @@ route('GET', '/api/users', async ({ user }) => {
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched — the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open windows close.
// read. Only the live map is reconciled: their open sessions close.
route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
requireSuperuser(user);
if (params.id === user.id) throw new HttpError(409, 'revoking yourself would lock the deployment out of its superuser');
@@ -235,9 +236,9 @@ function requireOwner(user, runId) {
// --- routes -------------------------------------------------------------------
route('GET', '/api', async () => ({
service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size,
// the live window inventory — debugging state divergence at a glance
windows: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
service: 'rp-test', mock: MOCK, openSessions: ctx.sessions.size,
// the live session inventory — debugging state divergence at a glance
sessions: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
}));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
@@ -280,14 +281,14 @@ route('GET', '/api/prompts', async () => {
});
// the clerk's list, enriched with what the server already knows: the
// open window, the pending ask, and the housekeeping bookkeeping. A
// open session, the pending ask, and the housekeeping bookkeeping. A
// run with no sessions is a draft — created, never started.
route('GET', '/api/runs', async () => {
const runs = clerkRawJson('runs');
for (const r of runs) {
const s = ctx.sessions.get(r.id);
r.open = !!s;
r.window = s?.stamp ?? null;
r.session = s?.stamp ?? null;
r.fresh = s?.fresh ?? false;
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
@@ -325,7 +326,7 @@ route('GET', '/api/names', async () => {
route('GET', '/api/runs/:id', async ({ params }) => {
const id = params.id;
bundle.requireRun(id);
const st = clerkJson(id, '--json', 'status');
const st = clerkJson(id, '--json', 'report');
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
@@ -344,9 +345,9 @@ route('GET', '/api/runs/:id', async ({ params }) => {
open: !!s,
draft: session.latestSession(id) === null,
lastSession: session.latestSession(id),
window: s?.stamp ?? null,
session: s?.stamp ?? null,
fresh: s?.fresh ?? false,
paper: st.paper,
status: st.status,
agenda: st.agenda,
records: st.records,
fill: st.rings,
@@ -355,8 +356,8 @@ route('GET', '/api/runs/:id', async ({ params }) => {
usage: s?.usage ?? null,
context: s?.usage ? {
used: s.usage.promptTokens,
window: cfg.contextWindow ?? null,
pct: cfg.contextWindow ? Math.round((100 * s.usage.promptTokens) / cfg.contextWindow) : null,
contwin: cfg.contwin ?? null,
pct: cfg.contwin ? Math.round((100 * s.usage.promptTokens) / cfg.contwin) : null,
} : null,
};
});
@@ -365,7 +366,7 @@ route('GET', '/api/runs/:id', async ({ params }) => {
//
// A fixed whitelist, not a path API: state dirs are the clerk's
// alone. Craft files are writable; housekeeper.md is substrate-
// internal (repo-fed at wrap, never copied, not exposed here) and
// internal (repo-fed at housekeeping, never copied, not exposed here) and
// gm.md lives only in the notepad endpoints (the play-view pad);
// config is read-only (vars and lineage are easy to break blind).
// JSON writes are validated before landing.
@@ -427,7 +428,7 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
// the run's models: per-run overrides of the deployment defaults
// (server.json), selected from the upstream listing (GET /api/models).
// Owner-only, changeable at any time — every call resolves fresh, so a
// mid-window switch simply takes the next turn. null clears a role
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default.
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
const id = params.id;
@@ -482,14 +483,14 @@ route('DELETE', '/api/runs/:id', async ({ params, user }) => {
return { ok: true, deleted: params.id };
});
route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
const s = session.openWindow(id, body.override === true);
if (ctx.sessions.has(id)) throw new HttpError(409, `a session is already open for '${id}' — one active session per run`);
const s = session.openSession(id, body.override === true);
ctx.sessions.set(id, s);
return {
window: s.stamp,
session: s.stamp,
fresh: s.fresh,
notes: s.lines.filter((e) => e.t === 'note').map((e) => ({ kind: e.kind, ok: e.ok, detail: e.detail })),
};
@@ -497,10 +498,10 @@ route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
route('GET', '/api/runs/:id/session', async ({ params }) => {
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no open window for '${params.id}'`);
if (!s) throw new HttpError(404, `no open session for '${params.id}'`);
return {
run: params.id,
window: s.stamp,
session: s.stamp,
entries: s.lines,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
@@ -515,7 +516,7 @@ route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
});
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
// fresh session — "start" is this right after session-open
route('POST', '/api/runs/:id/turn0', async ({ params, user }) => {
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => turn0(ctx, params.id, user))) };
@@ -538,25 +539,25 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
route('GET', '/api/runs/:id/status', async ({ params }) => {
bundle.requireRun(params.id);
return { paper: clerkJson(params.id, 'paper'), agenda: clerkJson(params.id, 'agenda') };
return { status: clerkJson(params.id, 'status'), agenda: clerkJson(params.id, 'agenda') };
});
// the GM's out-of-band paper override: whole-paper replace via the
// the GM's out-of-band status override: whole-status replace via the
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// item is a 400, not a silent corruption later.
route('POST', '/api/runs/:id/paper', async ({ params, body, user }) => {
route('POST', '/api/runs/:id/status', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the status');
for (const it of items) {
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
}
const paper = clerkJson(id, '--gm', 'paper-set', ...items);
return { ok: true, paper };
const status = clerkJson(id, '--gm', 'status-set', ...items);
return { ok: true, status };
});
// the GM's out-of-band agenda override: whole-queue replace via the
@@ -578,17 +579,17 @@ route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
});
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// ends the window and kicks the async chain; poll GET for the outcome
// ends the session and kicks the async chain; poll GET for the outcome
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
return { state: job.state, session: job.session };
});
// dry-run the housekeeper over a session log: the same transcript
// assembly the real wrap uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no window ended, no state
// assembly the real housekeeping uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no session ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
// without playing more; works on the open session too.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
@@ -626,21 +627,21 @@ route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeepin
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open window, marks the latest session housekept, autorestarts
// any open session, marks the latest session housekept, autorestarts
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const file = String(body.file ?? '').trim();
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json');
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<session>.json');
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
if (!manifestPath.startsWith(path.join(ROOT, 'runs', id))) throw new HttpError(400, 'file must stay inside the run dir');
if (!fs.existsSync(manifestPath)) throw new HttpError(404, `no such manifest: ${file}`);
const latest = session.latestSession(id);
if (!latest) throw new HttpError(409, 'no session to mark housekept');
ctx.sessions.delete(id); // housekeeping always ends the window
ctx.sessions.delete(id); // housekeeping always ends the session
try {
const next = housekeeping.applyAndRestart(ctx, id, manifestPath, latest);
return { ok: true, housekept: latest, window: next.stamp };
return { ok: true, housekept: latest, session: next.stamp };
} catch (e) {
const job = { state: 'rejected', session: latest, reason: e.message };
ctx.jobs.set(id, job);
@@ -689,5 +690,5 @@ const server = http.createServer(async (req, res) => {
const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
server.listen(Number(port), host, () => {
console.log(`rp-test server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} window(s) rebuilt`);
console.log(`rp-test server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt`);
});
+11 -11
View File
@@ -1,4 +1,4 @@
// server/session.mjs — a window's live state.
// server/session.mjs — a session's live state.
//
// The append-only jsonl is the truth; the in-memory context is a view
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
@@ -6,7 +6,7 @@
// without a format migration. The view renderer is pure policy over
// the log: thinking never goes back, old tool results elide to stubs
// (the last few and every ask_gm answer stay), old GM-side
// <status>/<conflict> blocks elide — the current paper rides the
// <status>/<conflict> blocks elide — the current status rides the
// newest GM turn.
import fs from 'node:fs';
import path from 'node:path';
@@ -62,16 +62,16 @@ function makeSession(runId, st) {
};
}
// --- open a window -----------------------------------------------------------
// --- open a session -----------------------------------------------------------
// The #21 guard: opening over an unhousekept session means that
// transcript never reaches the rings — refuse and name it, unless the
// caller explicitly overrides (the deliberate skip).
export function openWindow(runId, override = false) {
export function openSession(runId, override = false) {
requireRun(runId);
const latest = latestSession(runId);
if (latest && latest !== (readState(runId).lastHousekeptSession ?? null) && !override) {
const err = new Error(`the previous window (${latest}) was never housekept — its transcript would never reach the rings`);
const err = new Error(`the previous session (${latest}) was never housekept — its transcript would never reach the rings`);
err.status = 409;
err.detail = { session: latest, hint: 'housekeep it first, or POST with {"override": true} to deliberately skip it' };
throw err;
@@ -80,7 +80,7 @@ export function openWindow(runId, override = false) {
const notes = [];
const fresh = latest === null;
if (fresh) {
// lazy seed: applies at the first window-open, before render and
// lazy seed: applies at the first session-open, before render and
// assembly, so the bundle sees populated rings. The clerk refuses
// on history (a hand-prepped run), which is the opt-out.
if (fs.existsSync(path.join(runDir(runId), 'seed.json'))) {
@@ -88,7 +88,7 @@ export function openWindow(runId, override = false) {
notes.push({ kind: 'seed', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
if (fs.existsSync(path.join(runDir(runId), 'turn-0.md'))) {
const r = clerkTry(runId, 'paper-ingest', path.join(runDir(runId), 'turn-0.md'));
const r = clerkTry(runId, 'status-ingest', path.join(runDir(runId), 'turn-0.md'));
notes.push({ kind: 'ingest', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
}
@@ -107,7 +107,7 @@ export function openWindow(runId, override = false) {
const s = makeSession(runId, stamp());
s.fresh = fresh;
fs.mkdirSync(sessionsDir(runId), { recursive: true });
s.append({ t: 'note', kind: 'window', at: s.stamp, fresh });
s.append({ t: 'note', kind: 'session', at: s.stamp, fresh });
for (const n of notes) s.append({ t: 'note', kind: n.kind, ok: n.ok, detail: n.detail });
s.append({ t: 'bundle', m: system, part: 'system' });
for (let i = 0; i < bundle.length; i++) s.append({ t: 'bundle', m: bundle[i], part: partNames[i] });
@@ -132,7 +132,7 @@ export function loadSession(runId, st) {
}
}
derive(s);
// fresh survives a restart: this window is the run's first iff no
// fresh survives a restart: this session is the run's first iff no
// earlier session log exists (derive() can't know — it sees one log)
const files = fs.readdirSync(sessionsDir(runId)).filter((f) => f.endsWith('.jsonl')).sort();
s.fresh = files.length === 1 && files[0] === `${st}.jsonl`;
@@ -182,7 +182,7 @@ export function renderView(s, keepToolResults = 4) {
if (e.reminder) {
// the per-turn reminder: only the newest copy lives in the
// context — superseded ones elide (identical content, freshest
// position, exactly like the papers)
// position, exactly like the status/agenda blocks)
if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() });
} else if (e.m.role === 'assistant') {
// thinking never goes back; the log keeps it
@@ -196,7 +196,7 @@ export function renderView(s, keepToolResults = 4) {
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else if (i === lastGmIdx) {
// the newest GM turn keeps its blocks as-sent: the current
// paper and agenda ride it
// status and agenda ride it
msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else {
// older GM turns: status/agenda/conflict blocks elide