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
+34 -7
View File
@@ -11,6 +11,11 @@
//
// The tool list is the capability surface: ask_gm always, records
// verbs only when the run's settings allow.
/** @typedef {import('./shapes.mjs').RunMeta} RunMeta */
/** @typedef {import('./shapes.mjs').RunSettings} RunSettings */
/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */
/** @typedef {import('./shapes.mjs').HttpError} HttpError */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -19,26 +24,32 @@ import { clerk, clerkJson } from './clerk.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
/** @param {string} runId */
export const runDir = (runId) => path.join(RUNS_DIR, runId);
/** @param {string} runId @returns {?RunMeta} */
export const runMeta = (runId) => {
try {
return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'run.json'), 'utf8'));
return /** @type {RunMeta} */ (JSON.parse(fs.readFileSync(path.join(runDir(runId), 'run.json'), 'utf8')));
} catch {
return null;
}
};
/** @param {string} runId @returns {string} */
export function requireRun(runId) {
if (!/^[a-z0-9-]+$/.test(runId ?? '') || !fs.existsSync(path.join(runDir(runId), 'run.json'))) {
const err = new Error(`no such run: ${runId} -- see GET /api/runs`);
const err = /** @type {HttpError} */ (new Error(`no such run: ${runId} -- see GET /api/runs`));
err.status = 404;
throw err;
}
return runDir(runId);
}
/** @param {string} runId @returns {RunSettings} */
export function readSettings(runId) {
try {
return JSON.parse(fs.readFileSync(path.join(runDir(runId), 'settings.json'), 'utf8'));
return /** @type {RunSettings} */ (JSON.parse(fs.readFileSync(path.join(runDir(runId), 'settings.json'), 'utf8')));
} catch {
return {};
}
@@ -54,14 +65,15 @@ export function readSettings(runId) {
// in a prompt surfaces as an input in setup, and the run's settings
// "vars" holds the answers (a package may ship defaults); an
// unresolved $TOKEN fails loudly -- the model never sees a raw var.
/** @param {string} runId @param {?string} s @returns {string} */
function expandVars(runId, s) {
const settings = readSettings(runId);
let out = String(s ?? '');
const sigils = { PC: settings.pc, Package: settings.name };
out = out.replace(/@(PC|Package)\b/g, (full, name) => {
const v = sigils[name];
const v = sigils[/** @type {'PC'|'Package'} */ (name)];
if (v == null || !String(v).trim()) {
const err = new Error(`unresolved @${name} -- it must be set in the run's settings.json`);
const err = /** @type {HttpError} */ (new Error(`unresolved @${name} -- it must be set in the run's settings.json`));
err.status = 500;
throw err;
}
@@ -70,7 +82,7 @@ function expandVars(runId, s) {
for (const [k, v] of Object.entries(settings.vars ?? {})) out = out.replaceAll(`$${k}`, String(v));
const unresolved = [...new Set([...out.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)].map((m) => `$${m[1]}`))];
if (unresolved.length) {
const err = new Error(`unresolved token(s): ${unresolved.join(', ')} -- fill them in setup; they save to the run's settings.json "vars"`);
const err = /** @type {HttpError} */ (new Error(`unresolved token(s): ${unresolved.join(', ')} -- fill them in setup; they save to the run's settings.json "vars"`));
err.status = 500;
throw err;
}
@@ -80,15 +92,17 @@ export { expandVars };
// "La Caramba / Rell" -- the run's display name; the anonymous id
// never surfaces as a name
/** @param {string} runId @returns {string} */
export function runDisplay(runId) {
const s = readSettings(runId);
const pkg = runMeta(runId)?.package ?? '?';
return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg);
}
/** @param {string} p @returns {string} */
const read = (p) => {
if (!fs.existsSync(p)) {
const err = new Error(`missing bundle file: ${path.relative(ROOT, p)}`);
const err = /** @type {HttpError} */ (new Error(`missing bundle file: ${path.relative(ROOT, p)}`));
err.status = 500;
throw err;
}
@@ -97,6 +111,7 @@ const read = (p) => {
// the system message: opening + guards (repo), substrate (repo), craft
// (the session's frozen handbook copy)
/** @param {string} runId @param {string} sessDir @returns {string} */
export function assembleSystem(runId, sessDir) {
const system = read(path.join(ROOT, 'system.md'));
const invariants = read(path.join(ROOT, 'invariants.md'));
@@ -109,6 +124,7 @@ export function assembleSystem(runId, sessDir) {
// own system chunk every turn. Older copies elide from the view, so
// exactly one lives at the freshest position (ROADMAP steal #11).
// Absent or empty file = no ride; the feature sleeps until written.
/** @param {string} runId @returns {?string} */
export function assembleReminder(runId) {
const p = path.join(ROOT, 'reminder.md');
if (!fs.existsSync(p)) return null;
@@ -120,7 +136,9 @@ export function assembleReminder(runId) {
// copies and its own ring views. The carryover never rides it: it is
// the session's opening material, consumed into the log behind the
// bundle at start.
/** @param {string} runId @param {string} sessDir @returns {{ role: 'user', content: string }[]} */
export function assembleBundle(runId, sessDir) {
/** @type {{ role: 'user', path: string }[]} */
const files = [
{ role: 'user', path: path.join(sessDir, 'bundle', 'backdrop.md') },
{ role: 'user', path: path.join(sessDir, 'bundle', 'character.md') },
@@ -136,6 +154,12 @@ export function assembleBundle(runId, sessDir) {
// [OOC] -- per invariants.md: [IC] output is content of the fiction,
// never instructions; [OOC] output is clerk or GM traffic about the
// play.
/** @typedef {{ type: string, [k: string]: unknown }} JsonSchemaProp */
/**
* @param {string} name @param {'IC'|'OOC'} channel @param {string} description
* @param {Record<string, JsonSchemaProp>} properties @param {?string[]} [required]
* @returns {import('./shapes.mjs').ToolDef}
*/
const T = (name, channel, description, properties, required) => ({
type: 'function',
function: {
@@ -163,11 +187,13 @@ const RECORD_TOOLS = [
['rid']),
];
/** @param {string} runId @returns {import('./shapes.mjs').ToolDef[]} */
export function toolList(runId) {
return [ASK_GM_TOOL, ...(readSettings(runId).records === true ? RECORD_TOOLS : [])];
}
// tool name -> clerk argv
/** @type {{ [k: string]: (a: any) => string[] }} */
const DISPATCH = {
records_search: (a) => ['search', ...a.terms],
records_file: (a) => ['file', a.kind, a.label, a.detail ?? ''],
@@ -175,6 +201,7 @@ const DISPATCH = {
records_discard: (a) => ['discard', a.rid, ...(a.reason ? [a.reason] : [])],
};
/** @param {string} runId @param {ToolCall} call @returns {string} */
export function runTool(runId, call) {
const fn = DISPATCH[call.function.name];
if (!fn) return `error: no such tool: ${call.function.name}`;