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:
+73
-15
@@ -17,6 +17,13 @@
|
||||
// (the last few and every ask_gm answer stay), old GM-side
|
||||
// <status>/<conflict> blocks elide -- the current status rides the
|
||||
// newest GM turn.
|
||||
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
|
||||
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
|
||||
/** @typedef {import('./shapes.mjs').PendingAsk} PendingAsk */
|
||||
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
|
||||
/** @typedef {import('./shapes.mjs').OpeningEvent} OpeningEvent */
|
||||
/** @typedef {import('./shapes.mjs').HttpError} HttpError */
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -27,11 +34,16 @@ import { tailStart } from './carry.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** @param {string} runId */
|
||||
const sessionsDir = (runId) => path.join(runDir(runId), 'sessions');
|
||||
/** @param {string} runId @param {number} n */
|
||||
export const sessionDir = (runId, n) => path.join(sessionsDir(runId), String(n));
|
||||
/** @param {string} runId @param {number} n */
|
||||
const logFile = (runId, n) => path.join(sessionDir(runId, n), 'log.jsonl');
|
||||
/** @param {string} runId @param {number} n */
|
||||
const carryFile = (runId, n) => path.join(sessionDir(runId, n), 'carryover.jsonl');
|
||||
|
||||
/** @param {string} runId @returns {number[]} */
|
||||
export function listSessions(runId) {
|
||||
if (!fs.existsSync(sessionsDir(runId))) return [];
|
||||
return fs.readdirSync(sessionsDir(runId), { withFileTypes: true })
|
||||
@@ -39,11 +51,13 @@ export function listSessions(runId) {
|
||||
.map((d) => Number(d.name)).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/** @param {string} runId @returns {?number} */
|
||||
export const latestSession = (runId) => {
|
||||
const ns = listSessions(runId);
|
||||
return ns.length ? ns[ns.length - 1] : null;
|
||||
};
|
||||
|
||||
/** @param {string} runId @param {number} n @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }} */
|
||||
export function sessionMeta(runId, n) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(sessionDir(runId, n), 'session.json'), 'utf8'));
|
||||
@@ -52,6 +66,10 @@ export function sessionMeta(runId, n) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} runId @param {number} n @param {Record<string, unknown>} patch
|
||||
* @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }}
|
||||
*/
|
||||
export function writeMeta(runId, n, patch) {
|
||||
const m = { ...sessionMeta(runId, n), ...patch };
|
||||
fs.writeFileSync(path.join(sessionDir(runId, n), 'session.json'), JSON.stringify(m, null, 2) + '\n');
|
||||
@@ -60,12 +78,17 @@ export function writeMeta(runId, n, patch) {
|
||||
|
||||
// the run's state is its latest session's: live while one plays,
|
||||
// else dormant (the review window). At most one live session exists.
|
||||
/** @param {string} runId @returns {?number} */
|
||||
export function liveSession(runId) {
|
||||
return listSessions(runId).find((n) => sessionMeta(runId, n).phase === 'live') ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} status @param {string} message @param {unknown} [detail]
|
||||
* @returns {HttpError}
|
||||
*/
|
||||
const err = (status, message, detail) => {
|
||||
const e = new Error(message);
|
||||
const e = /** @type {HttpError} */ (new Error(message));
|
||||
e.status = status;
|
||||
if (detail) e.detail = detail;
|
||||
return e;
|
||||
@@ -73,6 +96,7 @@ const err = (status, message, detail) => {
|
||||
|
||||
// --- session object ----------------------------------------------------------
|
||||
|
||||
/** @param {string} runId @param {number} n @returns {LiveSession} */
|
||||
function makeSession(runId, n) {
|
||||
return {
|
||||
runId,
|
||||
@@ -82,6 +106,7 @@ function makeSession(runId, n) {
|
||||
lines: [],
|
||||
pendingAsk: null, // { callId, question, calls } -- the whole batch pauses
|
||||
usage: null, // { promptTokens, completionTokens } from the last response
|
||||
/** @param {LogEvent} entry */
|
||||
append(entry) {
|
||||
this.lines.push(entry);
|
||||
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
|
||||
@@ -89,6 +114,7 @@ function makeSession(runId, n) {
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {string} file @returns {LogEvent[]} */
|
||||
function readLogLines(file) {
|
||||
if (!fs.existsSync(file)) {
|
||||
throw err(404, `no session log: ${path.relative(ROOT, file)}`);
|
||||
@@ -105,6 +131,7 @@ function readLogLines(file) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** @param {string} file @param {LogEvent[]} lines */
|
||||
function writeLog(file, lines) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = `${file}.tmp`;
|
||||
@@ -112,6 +139,7 @@ function writeLog(file, lines) {
|
||||
fs.renameSync(tmp, file); // atomic: a crash never leaves a torn log
|
||||
}
|
||||
|
||||
/** @param {string} runId @param {number} n @returns {LiveSession} */
|
||||
export function loadSession(runId, n) {
|
||||
const s = makeSession(runId, n);
|
||||
s.lines = readLogLines(s.file);
|
||||
@@ -120,7 +148,9 @@ export function loadSession(runId, n) {
|
||||
}
|
||||
|
||||
// rebuild the derived state from the log alone
|
||||
/** @param {LiveSession} s */
|
||||
function derive(s) {
|
||||
/** @type {?PendingAsk} */
|
||||
let pending = null;
|
||||
for (const e of s.lines) {
|
||||
if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) {
|
||||
@@ -148,7 +178,7 @@ function derive(s) {
|
||||
&& typeof last.m.content === 'string' && /<\/?variants?>/.test(last.m.content)) {
|
||||
try {
|
||||
const v = parseVariants(last.m.content);
|
||||
s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
||||
if (v) s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
||||
} catch (e) {
|
||||
console.warn(`boot: an unresolved variant turn in session ${s.n} was left as-is: ${e.message}`);
|
||||
}
|
||||
@@ -165,6 +195,7 @@ function derive(s) {
|
||||
// boot resumes a half-finished stop by re-running this over the
|
||||
// on-disk state (the move step reconciles against what already
|
||||
// landed, so it never moves anything twice).
|
||||
/** @param {string} runId @param {number} N */
|
||||
export function stopSession(runId, N) {
|
||||
const dir = sessionDir(runId, N + 1);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
@@ -204,6 +235,7 @@ export function stopSession(runId, N) {
|
||||
}
|
||||
|
||||
// a stop that died in flight leaves its marker; boot finishes it
|
||||
/** @param {string} runId @returns {?{ from: number, dir: number }} */
|
||||
export function findStalledStop(runId) {
|
||||
for (const n of listSessions(runId)) {
|
||||
const p = path.join(sessionDir(runId, n), 'stop.json');
|
||||
@@ -226,6 +258,7 @@ export function findStalledStop(runId) {
|
||||
// conversation: msg, tool, and note events, read as recorded.
|
||||
// Exported for the file editor's save-time check: only clean
|
||||
// openings land.
|
||||
/** @param {LogEvent[]} lines @param {{ authored: boolean }} opts @returns {string[]} */
|
||||
export function lintCarryover(lines, { authored }) {
|
||||
const errors = [];
|
||||
let openings = 0;
|
||||
@@ -233,7 +266,10 @@ export function lintCarryover(lines, { authored }) {
|
||||
const at = `line ${i + 1}`;
|
||||
if (authored) {
|
||||
if (e.t === 'msg') {
|
||||
const m = e.m ?? {};
|
||||
// authored carryovers are prompt-side: anything may be
|
||||
// present that shouldn't be, so m is read permissively and
|
||||
// every wrong thing is named
|
||||
const m = /** @type {import('./shapes.mjs').WireMessage & Record<string, unknown>} */ (e.m ?? {});
|
||||
if (m.role !== 'user' && m.role !== 'assistant') errors.push(`${at}: role must be user (the GM) or assistant (her)`);
|
||||
if (typeof m.content !== 'string' || !m.content.trim()) errors.push(`${at}: content must be a non-empty string`);
|
||||
if (m.tool_calls?.length) errors.push(`${at}: tool calls are runtime artifacts -- the opening never calls tools`);
|
||||
@@ -273,32 +309,37 @@ export function lintCarryover(lines, { authored }) {
|
||||
// freeze, exactly like every bundle file. A continuation carryover is
|
||||
// live prose and NEVER expands -- a literal $word typed in play would
|
||||
// bomb the unresolved-token check, and the words are already real.
|
||||
/** @param {string} runId @param {LogEvent[]} lines @returns {LogEvent[]} */
|
||||
function expandCarryover(runId, lines) {
|
||||
return lines.map((e) => {
|
||||
return /** @type {LogEvent[]} */ (lines.map((e) => {
|
||||
if (e.t === 'msg') return { ...e, m: { ...e.m, content: expandVars(runId, e.m.content) } };
|
||||
if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) };
|
||||
return e;
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
// an unpicked variants event gets its crypto pick at start -- the
|
||||
// same dice the loop rolls on reception; a pick already adjacent
|
||||
// (real history) is final, re-rolls do not exist
|
||||
/** @param {LogEvent[]} lines @returns {LogEvent[]} */
|
||||
function resolvePicks(lines) {
|
||||
/** @type {LogEvent[]} */
|
||||
const out = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const e = lines[i];
|
||||
out.push(e);
|
||||
const next = lines[i + 1];
|
||||
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
|
||||
&& /<\/?variants?>/.test(e.m.content)
|
||||
&& !(lines[i + 1]?.t === 'note' && lines[i + 1].kind === 'pick')) {
|
||||
const v = parseVariants(e.m.content); // lint already validated
|
||||
out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
||||
&& !(next && next.t === 'note' && next.kind === 'pick')) {
|
||||
const v = parseVariants(e.m.content); // lint already validated -- never null past the tag test
|
||||
if (v) out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** @param {string} runId @param {number} n @returns {LogEvent[]} */
|
||||
function readCarryover(runId, n) {
|
||||
const p = carryFile(runId, n);
|
||||
if (!fs.existsSync(p)) return [];
|
||||
@@ -315,6 +356,11 @@ function readCarryover(runId, n) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} runId
|
||||
* @param {{ override?: boolean }} [opts]
|
||||
* @returns {{ session: LiveSession, autoSend: boolean }}
|
||||
*/
|
||||
export function startSession(runId, { override = false } = {}) {
|
||||
requireRun(runId);
|
||||
const n = latestSession(runId);
|
||||
@@ -364,14 +410,16 @@ export function startSession(runId, { override = false } = {}) {
|
||||
// renders from
|
||||
const rr = clerkTry(runId, '--session', String(n), 'render');
|
||||
if (rr.code !== 0) throw err(500, `render failed: ${(rr.err || rr.out).split('\n')[0]}`);
|
||||
/** @type {{ role: 'system', content: string }} */
|
||||
const system = { role: 'system', content: assembleSystem(runId, dir) };
|
||||
const bundle = assembleBundle(runId, dir);
|
||||
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
|
||||
/** @type {LogEvent[]} */
|
||||
const lines = [
|
||||
{ t: 'note', kind: 'session', n },
|
||||
...(opening ? [opening] : []),
|
||||
{ t: 'bundle', m: system, part: 'system' },
|
||||
...bundle.map((m, i) => ({ t: 'bundle', m, part: partNames[i] })),
|
||||
...bundle.map((m, i) => /** @type {LogEvent} */ ({ t: 'bundle', m, part: partNames[i] })),
|
||||
...carry,
|
||||
];
|
||||
// the assembled context must be sound before anything lands:
|
||||
@@ -394,7 +442,7 @@ export function startSession(runId, { override = false } = {}) {
|
||||
// the opening flow: a carryover ending on a GM turn is her cue --
|
||||
// it sends automatically as the first request of the assembled
|
||||
// contwin; otherwise the table waits for the GM's input
|
||||
const lastMsg = [...lines].reverse().find((e) => e.t === 'msg' && !e.reminder);
|
||||
const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null);
|
||||
return { session: s, autoSend: lastMsg?.m?.role === 'user' };
|
||||
}
|
||||
|
||||
@@ -402,9 +450,17 @@ export function startSession(runId, { override = false } = {}) {
|
||||
|
||||
const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g;
|
||||
|
||||
/** The renderer reads only these two of a session -- the start path
|
||||
* validates its assembled context with the same policy before going
|
||||
* live. */
|
||||
/** @typedef {{ lines: LogEvent[], pendingAsk: ?PendingAsk }} SessionView */
|
||||
|
||||
/** @param {SessionView} s @param {number} [keepToolResults] @returns {ViewMessage[]} */
|
||||
export function renderView(s, keepToolResults = 4) {
|
||||
const eff = effectiveContents(s.lines);
|
||||
/** @type {number[]} */
|
||||
const toolIdx = [];
|
||||
/** @type {number[]} */
|
||||
const reminderIdx = [];
|
||||
let lastGmIdx = -1;
|
||||
s.lines.forEach((e, i) => {
|
||||
@@ -414,6 +470,7 @@ export function renderView(s, keepToolResults = 4) {
|
||||
});
|
||||
const keep = new Set(toolIdx.slice(-keepToolResults));
|
||||
const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1;
|
||||
/** @type {ViewMessage[]} */
|
||||
const msgs = [];
|
||||
for (const [i, e] of s.lines.entries()) {
|
||||
if (e.t === 'bundle') {
|
||||
@@ -423,26 +480,26 @@ export function renderView(s, keepToolResults = 4) {
|
||||
// the per-turn reminder: only the newest copy lives in the
|
||||
// context -- superseded ones elide (identical content, freshest
|
||||
// position, exactly like the status/agenda blocks)
|
||||
if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() });
|
||||
if (i === newestReminder) msgs.push({ role: 'system', content: String(e.m.content ?? '').trim() });
|
||||
} else if (e.m.role === 'assistant') {
|
||||
// thinking never goes back; the log keeps it. Variant turns
|
||||
// render their picked variant -- the unpicked rest never reach
|
||||
// a model (the log keeps them)
|
||||
const m = { role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) };
|
||||
const m = /** @type {ViewMessage} */ ({ role: 'assistant', content: eff.has(i) ? eff.get(i) : (e.m.content ?? null) });
|
||||
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
||||
msgs.push(m);
|
||||
} else if (e.conflictOnly) {
|
||||
// transient error traffic: visible while it is the latest word
|
||||
// (the model answers it), elided entirely once the story moves
|
||||
// on -- the log keeps it for provenance
|
||||
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() });
|
||||
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() });
|
||||
} else if (i === lastGmIdx) {
|
||||
// the newest GM turn keeps its blocks as-sent: the current
|
||||
// status and agenda ride it
|
||||
msgs.push({ role: e.m.role, content: e.m.content.trim() });
|
||||
msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() });
|
||||
} else {
|
||||
// older GM turns: status/agenda/conflict blocks elide
|
||||
msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() });
|
||||
msgs.push({ role: e.m.role, content: String(e.m.content ?? '').replace(STRIP_BLOCKS, '').trim() });
|
||||
}
|
||||
} else if (e.t === 'tool') {
|
||||
if (e.ask || keep.has(i)) {
|
||||
@@ -458,6 +515,7 @@ export function renderView(s, keepToolResults = 4) {
|
||||
|
||||
// tool-call pairing is never broken (the endpoint tolerates orphans
|
||||
// silently -- probed 2026-11-12 -- so this one fails quiet unless we check)
|
||||
/** @param {ViewMessage[]} msgs @param {?string|undefined} pendingCallId */
|
||||
function validatePairing(msgs, pendingCallId) {
|
||||
const calls = new Set();
|
||||
const results = new Set();
|
||||
|
||||
Reference in New Issue
Block a user