jsdoc typing round, phases 1-2: tsc as a no-emit checker over plain mjs (checkJs, strict), the shared shapes in server/shapes.mjs (log events as a tagged union, wire messages, manifests, job state, the ctx), all 12 server modules annotated; requireOwner/requireSuperuser as JSDoc assertion functions so the router guarantee narrows without callsite churn; runtime stays zero-dependency (typescript + @types/node as pinned devDeps, node_modules gitignored, QUESTIONS #4 amended: dev tooling exempt); every non-annotation delta audited onto a small intended list (clerk status ?? 1, dead 401 guards, async wraps on enqueue callsites); smoke 105/105 + restart + repo checks green; the clerk and web/ are the next phases

This commit is contained in:
2026-11-15 15:28:56 +00:00
parent d737e47f82
commit f81b188ce1
22 changed files with 594 additions and 90 deletions
+33 -6
View File
@@ -18,6 +18,12 @@
// 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';
@@ -31,6 +37,7 @@ import { HttpError } from './loop.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 --------------------------------------------------------------
@@ -43,6 +50,7 @@ const readAt = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8').trim();
// 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 = [];
@@ -52,7 +60,7 @@ export function renderTranscript(lines) {
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]', String(e.m.content ?? '').replace(/<\/?conflict>/g, '').trim(), '');
continue;
}
if (e.m.role === 'user') {
@@ -89,6 +97,7 @@ export function renderTranscript(lines) {
// 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);
@@ -109,6 +118,7 @@ export function buildMessages(runId, n, 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 ?? '')]) {
@@ -125,6 +135,10 @@ export function parseManifest(text) {
// --- 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);
@@ -135,7 +149,7 @@ export function trigger(ctx, runId, user) {
// 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() };
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;
@@ -148,14 +162,15 @@ export function trigger(ctx, runId, user) {
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() };
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 = ctx.jobs.get(runId);
const job = /** @type {JobState} */ (ctx.jobs.get(runId));
try {
stopSession(runId, n); // the move, the freeze, the copies
job.stopped = true;
@@ -168,8 +183,9 @@ async function runStop(ctx, runId, n, user) {
// 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 = ctx.jobs.get(runId);
const job = /** @type {JobState} */ (ctx.jobs.get(runId));
const lines = loadSession(runId, n).lines;
const text = ctx.mock
? mockManifest(n)
@@ -191,8 +207,15 @@ async function runPass(ctx, runId, n, user) {
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<string>}
*/
async function callHousekeeper(ctx, runId, messages, user) {
const meta = ctx.runMeta?.(runId) ?? {};
const meta = ctx.runMeta?.(runId) ?? /** @type {RunMeta} */ ({});
const model = meta.models?.housekeeper
?? ctx.cfg.models?.housekeeper
?? ctx.cfg.models?.player
@@ -212,6 +235,7 @@ export { callHousekeeper };
// 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 */
export function applyToDormant(runId, manifestPath, n) {
const target = sessionDir(runId, n + 1);
if (sessionMeta(runId, n + 1).phase !== 'dormant') {
@@ -227,6 +251,7 @@ export function applyToDormant(runId, manifestPath, n) {
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);
@@ -243,6 +268,7 @@ export function jobState(ctx, runId) {
}
// 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--) {
@@ -262,6 +288,7 @@ 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.
/** @param {number} n @returns {string} */
function mockManifest(n) {
return JSON.stringify({
session: String(n),