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
+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`);
});