jsdoc typing round, phases 3-4: the clerk (tool/memory.mjs) and the SPA (web/) typed under strict -- row shapes local to their owners (the clerk's five tables in its header; the SPA's response envelopes in the new web/shapes.mjs, the server's shared shapes imported at their use sites: User, LogEvent, JobState, HttpError); the db boundary cast at every .get()/.all(), fail as @returns {never} so guard-narrowing works; web via a second tsconfig (tsconfig.web.json: DOM libs in their own program, node types riding along because shapes.mjs's Provider typedef pulls provider.mjs in), npm run typecheck runs both; every non-annotation delta audited onto a small intended list (COUNT(*) Number() wraps, impossible-path guards, ?? ''/?? undefined null-absorbers, the RewordOp reason fix -- the validator demands it, the reminder-find naming its tag); smoke 110/110 + restart + reminder + repo checks + a zero-console-error browser pass green; the typing round is complete

This commit is contained in:
2026-11-15 19:57:07 +00:00
parent f81b188ce1
commit 8d4a6b91df
22 changed files with 567 additions and 227 deletions
+200 -87
View File
@@ -61,6 +61,42 @@
//
// report counts, caps, the status, what's sinking
/** @typedef {import('../server/shapes.mjs').Manifest} Manifest */
/** @typedef {import('../server/shapes.mjs').InsertOp} InsertOp */
/** @typedef {import('../server/shapes.mjs').RefOp} RefOp */
/** @typedef {import('../server/shapes.mjs').RewordOp} RewordOp */
/** @typedef {import('../server/shapes.mjs').RunMeta} RunMeta */
/** @typedef {import('../server/shapes.mjs').RunSettings} RunSettings */
/** An entries table row ('cold' is storage, beyond the models' sight). */
/** @typedef {{ id: number, ring: 'a'|'b'|'cold', type: 'place'|'person'|'fact'|'thread', label: string, detail: string, created: string, last_touched: string }} EntryRow */
/** A records table row. */
/** @typedef {{ id: number, kind: string, label: string, detail: string, created: string }} RecordRow */
/** A status table row. */
/** @typedef {{ id: number, descr: string, added: string }} StatusRow */
/** An agenda table row. */
/** @typedef {{ id: number, descr: string, added: string }} AgendaRow */
/** An events table row: the append-only journal, never updated or deleted. */
/** @typedef {{ id: number, session: string, op: string, target: string, reason: string, prior: string }} EventRow */
/** session.json as buildSession1 / the server write it. */
/** @typedef {{ phase?: string, ready?: boolean, [k: string]: unknown }} SessionMeta */
/** One package as `packages` lists it. */
/** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */
/** One run as `runs` lists it (fill is present exactly when initialized). */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */
/** The apply log's record of what a manifest did. */
/** @typedef {{ id: number } & InsertOp} AppliedInsert */
/** @typedef {{ row: EntryRow, reason: string }} AppliedRef */
/** @typedef {{ row: EntryRow, detail: string, reason: string }} AppliedReword */
/** @typedef {{ rid: number, row: EntryRow, reason: string }} AppliedArchive */
/** @typedef {{ insert: AppliedInsert[], touch: AppliedRef[], promote: AppliedRef[], demote: AppliedRef[], reword: AppliedReword[], delete: AppliedRef[], archive: AppliedArchive[] }} AppliedLog */
/** One automatic overflow move (ring a spills to b, ring b to cold). */
/** @typedef {{ id: number, from: string, to: string }} OverflowItem */
import { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
@@ -74,23 +110,28 @@ const STATE_PACKAGES_DIR = path.join(ROOT, 'state', 'packages');
const RUNS_DIR = path.join(ROOT, 'runs');
// dials -- retune freely
/** @type {Record<string, number>} */
const CAPS = { a: 500, b: 3000 };
const AGENDA_CAP = 5; // dial -- retune freely (invariants.md: "intentionally tiny")
const TYPES = ['place', 'person', 'fact', 'thread'];
const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models
/** @param {string} msg @returns {never} */
const fail = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
/** @param {string} p @returns {string} */
const rel = (p) => path.relative(ROOT, p).replaceAll('\\', '/');
// flags: --run <name> beats everything; --gm attributes the op to the GM
const argv = process.argv.slice(2);
const runIdx = argv.indexOf('--run');
/** @type {?string} */
let runOverride = null;
if (runIdx !== -1) {
runOverride = argv[runIdx + 1] ?? null;
argv.splice(runIdx, 2);
}
const sessionIdx = argv.indexOf('--session');
/** @type {?number} */
let sessionOverride = null;
if (sessionIdx !== -1) {
sessionOverride = Number(argv[sessionIdx + 1]);
@@ -108,6 +149,7 @@ for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) arg
const AS_JSON = argv.includes('--json');
for (let i = argv.indexOf('--json'); i !== -1; i = argv.indexOf('--json')) argv.splice(i, 1);
const ownerIdx = argv.indexOf('--owner');
/** @type {?string} */
let ownerOverride = null;
if (ownerIdx !== -1) {
ownerOverride = argv[ownerIdx + 1] ?? null;
@@ -118,14 +160,21 @@ const [cmd, ...args] = argv;
// a run is an instance under runs/, created from a package by `create`;
// state is per-deployment -- a fresh clone has zero runs
const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']);
const RUN = NO_RUN_NEEDED.has(cmd) ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd) && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
const RUN = NO_RUN_NEEDED.has(cmd ?? '') ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd ?? '') && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
fail('no run specified -- use --run <id> (see: runs); runs are created with: create <package> <pc-name>');
}
// per-run paths: set once from --run, and re-pointed by create (which
// builds a run dir before any view is written)
let RUN_ROOT, DB_PATH, CANON_DIR, LOG_DIR, DUMPS_DIR, SETTINGS_PATH, SESS;
/** @type {string} */ let RUN_ROOT;
/** @type {string} */ let DB_PATH;
/** @type {string} */ let CANON_DIR;
/** @type {string} */ let LOG_DIR;
/** @type {string} */ let DUMPS_DIR;
/** @type {string} */ let SETTINGS_PATH;
/** @type {number} */ let SESS;
/** @param {string} dir */
function setRunRoot(dir) {
RUN_ROOT = dir;
SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json');
@@ -141,6 +190,7 @@ function setRunRoot(dir) {
// for audit, writes only where the phase allows (the freeze ruling:
// prompts, rings, and carryover are editable during dormancy, frozen
// from the moment a session goes live).
/** @param {string} [runDir] @returns {number[]} */
function listSessions(runDir = RUN_ROOT) {
const dir = path.join(runDir, 'sessions');
if (!fs.existsSync(dir)) return [];
@@ -149,6 +199,7 @@ function listSessions(runDir = RUN_ROOT) {
.map((d) => Number(d.name)).sort((a, b) => a - b);
}
/** @param {number} n @param {string} [runDir] @returns {SessionMeta} */
const sessionMeta = (n, runDir = RUN_ROOT) => {
try {
return JSON.parse(fs.readFileSync(path.join(runDir, 'sessions', String(n), 'session.json'), 'utf8'));
@@ -157,6 +208,7 @@ const sessionMeta = (n, runDir = RUN_ROOT) => {
}
};
/** @param {?number} want @returns {number} */
function resolveSession(want) {
const ns = listSessions();
if (!ns.length) fail('this run has no sessions -- create builds session one');
@@ -169,6 +221,7 @@ function resolveSession(want) {
return live.length ? live[0] : ns[ns.length - 1];
}
/** @param {number} n */
function setSessionRoot(n) {
SESS = n;
const d = path.join(RUN_ROOT, 'sessions', String(n));
@@ -185,6 +238,7 @@ if (RUN != null && cmd !== 'init') setSessionRoot(resolveSession(sessionOverride
// dangerous, finished is frozen); the status and agenda are runtime
// channels (live) and the dormancy edit surface; apply targets the
// dormant session's rings -- the housekeeping write.
/** @type {Record<string, string[]>} */
const PHASE_RULES = {
insert: ['dormant'], delete: ['dormant'], revive: ['dormant'], unarchive: ['dormant'],
apply: ['dormant'],
@@ -192,6 +246,7 @@ const PHASE_RULES = {
'status-apply': ['live'], 'agenda-apply': ['live'],
file: ['dormant', 'live'], amend: ['dormant', 'live'], discard: ['dormant', 'live'],
};
/** @param {string} verb */
function enforcePhase(verb) {
const allowed = PHASE_RULES[verb];
if (!allowed) return;
@@ -225,6 +280,7 @@ GM ratifies notable inventions afterward.)
Freeform notes:
`;
/** @returns {boolean} */
function recordsEnabled() {
try {
return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true;
@@ -233,6 +289,7 @@ function recordsEnabled() {
}
}
/** @returns {DatabaseSync} */
function openDb() {
if (!fs.existsSync(DB_PATH)) {
fail(`no database at ${rel(DB_PATH)} -- run: node tool/memory.mjs init`);
@@ -251,16 +308,17 @@ function openDb() {
// the old CHECK would reject the new op values mid-flight, and the
// positional copy absorbs the column rename. (Mirrors db/schema.sql;
// old dumps carry their own old schema and self-migrate through here.)
/** @param {DatabaseSync} db */
function migrateStatusNames(db) {
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status-add', 'status-drop', 'status-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => r.name);
const tables = /** @type {{ name: string }[]} */ (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()).map((r) => r.name);
if (tables.includes('paper') && !tables.includes('status')) {
db.exec('ALTER TABLE paper RENAME TO status');
if (!QUIET) console.log(`(migrated: table paper -> status -- ${rel(DB_PATH)})`);
}
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
const row = /** @type {?{ sql: string }} */ (db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get());
if (!row) return;
const staleOps = db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get().n > 0;
const staleOps = Number(db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get()?.n ?? 0) > 0;
if (!staleOps && row.sql.includes("'status-add'")) return;
db.exec('BEGIN');
try {
@@ -296,18 +354,22 @@ function migrateStatusNames(db) {
if (!QUIET) console.log(`(migrated: events journal to the current names -- ${rel(DB_PATH)})`);
}
/** @param {unknown} s @returns {?number} */
const parseId = (s) => {
const m = /^e(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null;
};
/** @param {unknown} s @returns {string} */
const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
/** @param {unknown} s @returns {?number} */
const parseRid = (s) => {
const m = /^r(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null;
};
/** @param {DatabaseSync} db @param {string} win @param {string} op @param {string} target @param {string} reason @param {string} [prior] */
const journal = (db, win, op, target, reason, prior = '') =>
db.prepare('INSERT INTO events (session, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
.run(win, op, target, norm(reason), prior);
@@ -316,10 +378,11 @@ const journal = (db, win, op, target, reason, prior = '') =>
// hand-edit them (regenerate with render). The do-not-edit warning lives
// here rather than in the output: prose files carry no comments, purpose
// text lives in code or README.
/** @param {DatabaseSync} db @param {string} ring @returns {{ file: string, count: number }} */
function renderRing(db, ring) {
const rows = db.prepare(
const rows = /** @type {EntryRow[]} */ (db.prepare(
'SELECT * FROM entries WHERE ring = ? ORDER BY last_touched DESC, id DESC'
).all(ring);
).all(ring));
const title = ring === 'a' ? 'what matters' : 'what stuck anyway';
const lines = [
`# Ring ${ring.toUpperCase()} -- ${title}`,
@@ -336,8 +399,9 @@ function renderRing(db, ring) {
return { file, count: rows.length };
}
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderStatus(db) {
const rows = db.prepare('SELECT * FROM status ORDER BY id').all();
const rows = /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all());
const lines = [
'# Status',
'',
@@ -355,6 +419,7 @@ function renderStatus(db) {
// the agenda view: the queue, top (newest) first, numbered as the wire
// renders it -- what the model cites, what the GM reads
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderAgenda(db) {
const items = agendaList(db);
const lines = [
@@ -372,6 +437,7 @@ function renderAgenda(db) {
return { file, count: items.length };
}
/** @param {DatabaseSync} db */
function renderAll(db) {
// --json means stdout carries JSON only; the view paths are human garnish
const talk = !QUIET && !AS_JSON;
@@ -387,8 +453,10 @@ function renderAll(db) {
// canonical serialization: id-ordered, one row per line, restorable SQL.
// this is the committed truth; the binary db is a local cache.
/** @param {DatabaseSync} db @returns {string} */
function dumpDb(db) {
fs.mkdirSync(DUMPS_DIR, { recursive: true });
/** @param {unknown} s @returns {string} */
const q = (s) => `'${String(s ?? '').replace(/'/g, "''")}'`;
const L = [
'-- canonical dump of db/memory.db -- GENERATED by tool/memory.mjs; do not edit.',
@@ -396,19 +464,19 @@ function dumpDb(db) {
fs.readFileSync(SCHEMA_PATH, 'utf8').trim(),
'BEGIN TRANSACTION;',
];
for (const r of db.prepare('SELECT * FROM entries ORDER BY id').all()) {
for (const r of /** @type {EntryRow[]} */ (db.prepare('SELECT * FROM entries ORDER BY id').all())) {
L.push(`INSERT INTO entries VALUES (${r.id},${q(r.ring)},${q(r.type)},${q(r.label)},${q(r.detail)},${q(r.created)},${q(r.last_touched)});`);
}
for (const r of db.prepare('SELECT * FROM records ORDER BY id').all()) {
for (const r of /** @type {RecordRow[]} */ (db.prepare('SELECT * FROM records ORDER BY id').all())) {
L.push(`INSERT INTO records VALUES (${r.id},${q(r.kind)},${q(r.label)},${q(r.detail)},${q(r.created)});`);
}
for (const r of db.prepare('SELECT * FROM status ORDER BY id').all()) {
for (const r of /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all())) {
L.push(`INSERT INTO status VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM agenda ORDER BY id').all()) {
for (const r of /** @type {AgendaRow[]} */ (db.prepare('SELECT * FROM agenda ORDER BY id').all())) {
L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) {
for (const r of /** @type {EventRow[]} */ (db.prepare('SELECT * FROM events ORDER BY id').all())) {
L.push(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
}
L.push('COMMIT;', '');
@@ -420,6 +488,7 @@ function dumpDb(db) {
// stamps are mechanical (real, internal, never rendered): they drive
// the LRU -- overflow, view order, "what's sinking". Story time lives
// in the prose of the entries, never in a column.
/** @param {DatabaseSync} db @param {{ ring: string, type: string, label: string, detail: string, win: string, reason: string }} e @returns {number} */
function insertEntry(db, { ring, type, label, detail, win, reason }) {
const now = today();
const res = db.prepare(
@@ -432,19 +501,23 @@ function insertEntry(db, { ring, type, label, detail, win, reason }) {
// --- validation helpers (used by apply) -------------------------------------
/** @param {DatabaseSync} db */
function makeValidator(db) {
const errors = [];
const seen = new Map();
/** @type {string[]} */ const errors = [];
/** @type {Map<number, string>} */ const seen = new Map();
/** @param {unknown} v @param {string} name */
const need = (v, name) => { if (typeof v !== 'string' || !v.trim()) errors.push(`${name} is required`); };
/** @template T @param {T[]|undefined} v @param {string} name @returns {T[]} */
const asArray = (v, name) => {
if (v === undefined || v === null) return [];
if (!Array.isArray(v)) { errors.push(`${name} must be an array`); return []; }
return v;
};
/** @param {string} op @param {RefOp} e @param {?string} expectRing @returns {?EntryRow} */
const ref = (op, e, expectRing) => {
const id = parseId(e.id);
if (id == null) { errors.push(`${op}: id must look like e12`); return null; }
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) { errors.push(`${op}: e${id} does not exist`); return null; }
if (row.ring === 'cold') { errors.push(`${op}: e${id} is in cold storage -- the models can't see it`); return null; }
if (expectRing && row.ring !== expectRing) {
@@ -460,8 +533,10 @@ function makeValidator(db) {
// --- apply ------------------------------------------------------------------
/** @param {Manifest} mf @param {AppliedLog} applied @param {OverflowItem[]} overflow @returns {string} */
function renderLog(mf, applied, overflow) {
const L = [`# ${mf.session}`, '', mf.summary, ''];
/** @template T @param {string} title @param {T[]} rows @param {(r: T) => string} fmt */
const section = (title, rows, fmt) => {
if (!rows.length) return;
L.push(`## ${title}`, '');
@@ -482,9 +557,10 @@ function renderLog(mf, applied, overflow) {
return L.join('\n');
}
/** @param {string} manifestPath */
function cmdApply(manifestPath) {
const db = openDb();
let mf;
/** @type {Manifest} */ let mf;
try {
mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (e) {
@@ -536,7 +612,7 @@ function cmdApply(manifestPath) {
});
del.forEach((e) => ref('delete', e, null));
arch.forEach((e) => ref('archive', e, null));
for (const [name, arr] of [['inventions', inventions], ['open_questions', questions]]) {
for (const [name, arr] of /** @type {[string, string[]][]} */ ([['inventions', inventions], ['open_questions', questions]])) {
arr.forEach((s, i) => { if (typeof s !== 'string' || !s.trim()) errors.push(`${name}[${i}] must be a non-empty string`); });
}
@@ -545,9 +621,11 @@ function cmdApply(manifestPath) {
for (const e of errors) console.error(` - ${e}`);
process.exit(1);
}
// validation demands a session slug, so a null logFile is unreachable
if (!logFile) fail('unreachable: manifest without a session');
const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
const overflow = [];
/** @type {AppliedLog} */ const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
/** @type {OverflowItem[]} */ const overflow = [];
db.exec('BEGIN');
try {
@@ -558,34 +636,36 @@ function cmdApply(manifestPath) {
});
applied.insert.push({ id, ...e });
}
/** @param {number} id */
const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(today(), id);
const fetch = (id) => db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
/** @param {number} id @returns {EntryRow} */
const fetch = (id) => /** @type {EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
for (const e of touch) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
touchDate(id);
journal(db, mf.session, 'touch', `e${id}`, e.reason);
applied.touch.push({ row: fetch(id), reason: e.reason });
}
for (const e of promote) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'promote', `e${id}`, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason });
}
for (const e of demote) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'demote', `e${id}`, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason });
}
for (const e of reword) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), today(), id);
journal(db, mf.session, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
}
for (const e of arch) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
const row = fetch(id);
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(row.type, row.label, row.detail, row.created);
@@ -595,7 +675,7 @@ function cmdApply(manifestPath) {
applied.archive.push({ rid, row, reason: e.reason });
}
for (const e of del) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
journal(db, mf.session, 'delete', `e${id}`, e.reason);
applied.delete.push({ row: fetch(id), reason: e.reason });
@@ -603,9 +683,9 @@ function cmdApply(manifestPath) {
// overflow: A spills to B first, then B spills to cold -- exact, by count
for (const ring of RINGS) {
const rows = db.prepare(
const rows = /** @type {{ id: number }[]} */ (db.prepare(
'SELECT id FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC'
).all(ring);
).all(ring));
const extra = rows.length - CAPS[ring];
for (let i = 0; i < extra; i++) {
const victim = rows[i];
@@ -664,6 +744,7 @@ function cmdInit() {
// stubs, the phase marker. The caller (create or init) owns the
// bundle copies; ready is true from birth -- session one's rings are
// its own (memory.json applied), no housekeeping ever precedes it.
/** @param {string} runDir @returns {{ db: DatabaseSync, dir: string }} */
function buildSession1(runDir) {
const s1 = path.join(runDir, 'sessions', '1');
for (const d of ['bundle', 'db', 'canon', 'dumps', 'log']) {
@@ -709,15 +790,17 @@ const PACKAGE_LAYOUT = {
};
// resolve a package name against both roots; the repo wins a collision
/** @param {?string} name @returns {?string} */
function packageDir(name) {
if (!/^[a-z0-9-]+$/.test(name ?? '')) return null;
if (fs.existsSync(path.join(PACKAGES_DIR, name))) return path.join(PACKAGES_DIR, name);
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, name))) return path.join(STATE_PACKAGES_DIR, name);
if (fs.existsSync(path.join(PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(PACKAGES_DIR, /** @type {string} */ (name));
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name));
return null;
}
// the package meta of a user package (owner, created); system packages
// have none -- their origin is the repo itself
/** @param {string} dir @returns {?{ owner?: ?string, created?: string }} */
function readPackageMeta(dir) {
try {
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
@@ -726,14 +809,16 @@ function readPackageMeta(dir) {
}
}
/** @param {string} name @param {string} dir @param {'system'|'user'} origin @returns {PackageListed} */
function packageEntry(name, dir, origin) {
// exists AND non-empty: an emptied placeholder is not a playable
// package, and the listing must not call it complete (boutique,
// emptied 2026-11-15, taught this)
/** @param {string} f @returns {boolean} */
const has = (f) => {
try { return fs.statSync(path.join(dir, f)).size > 0; } catch { return false; }
};
let settings = {};
/** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')); } catch {}
const meta = origin === 'user' ? readPackageMeta(dir) : null;
return {
@@ -749,7 +834,8 @@ function packageEntry(name, dir, origin) {
}
function cmdPackages() {
const list = [];
/** @type {PackageListed[]} */ const list = [];
/** @param {string} root @param {'system'|'user'} origin */
const scan = (root, origin) => {
if (!fs.existsSync(root)) return;
for (const d of fs.readdirSync(root, { withFileTypes: true })) {
@@ -771,12 +857,15 @@ function cmdPackages() {
// rename and nothing for a name to collide with. The names that
// matter -- the package display name and the pc's name -- live in the
// run's settings copy and drive the display ("La Caramba / Rell").
/** @param {string} runDir @returns {RunSettings} */
const readRunSettings = (runDir) => {
try { return JSON.parse(fs.readFileSync(path.join(runDir, 'settings.json'), 'utf8')); } catch { return {}; }
};
/** @param {string} pkg @param {RunSettings} settings @returns {string} */
const runDisplay = (pkg, settings) =>
settings.pc ? `${settings.name ?? pkg} / ${settings.pc}` : (settings.name ?? pkg);
/** @returns {string} */
function anonId() {
for (;;) {
const id = randomBytes(4).toString('hex'); // 8 hex chars
@@ -784,6 +873,7 @@ function anonId() {
}
}
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] @param {?string} [model] */
function cmdCreate(pkgName, pc, displayName, model) {
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
fail('usage: create <package> <pc-name> ["package display name"] ["model"]');
@@ -796,7 +886,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
const rd = path.join(RUNS_DIR, d.name);
let meta = null;
/** @type {?RunMeta} */ let meta = null;
try { meta = JSON.parse(fs.readFileSync(path.join(rd, 'run.json'), 'utf8')); } catch { continue; }
if (meta?.package !== pkgName) continue;
const st = readRunSettings(rd);
@@ -831,7 +921,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
settings.pc = pc;
settings.name = displayName?.trim() || settings.name || pkgName;
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
const meta = { package: pkgName, created: today() };
/** @type {RunMeta} */ const meta = { package: pkgName, created: today() };
if (model) meta.models = { player: model };
if (ownerOverride) meta.owner = ownerOverride;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
@@ -859,7 +949,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs -- create one: create <package> <pc-name>)'); return; }
const list = [];
/** @type {RunListed[]} */ const list = [];
let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
@@ -867,10 +957,10 @@ function cmdRuns() {
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
found++;
let pkg = '?';
let models = null;
let owner = null;
let created = null;
let forked = null;
/** @type {?{ player?: ?string, housekeeper?: ?string }} */ let models = null;
/** @type {?string} */ let owner = null;
/** @type {?string} */ let created = null;
/** @type {?number} */ let forked = null;
try {
const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8'));
pkg = meta.package ?? '?';
@@ -889,20 +979,22 @@ function cmdRuns() {
const phase = active == null ? null : sessionMeta(active, runDir).phase ?? null;
const dbPath = active == null ? null : path.join(runDir, 'sessions', String(active), 'db', 'memory.db');
const ready = active == null ? null : sessionMeta(active, runDir).ready ?? null;
if (active == null || !fs.existsSync(dbPath)) { list.push({ ...base, sessions: ns.length, phase, ready, initialized: false }); continue; }
if (active == null || dbPath == null || !fs.existsSync(dbPath)) { list.push({ ...base, sessions: ns.length, phase, ready, initialized: false }); continue; }
const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
/** @param {string} ring @returns {number} */
const n = (ring) => Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
list.push({ ...base, sessions: ns.length, phase, ready, initialized: true, fill: { a: n('a'), b: n('b'), cold: n('cold') } });
}
if (AS_JSON) { console.log(JSON.stringify(list)); return; }
for (const x of list) {
if (!x.initialized) { console.log(`${x.id} [${x.package}]: ${x.display} (not initialized)`); continue; }
if (!x.initialized || !x.fill) { console.log(`${x.id} [${x.package}]: ${x.display} (not initialized)`); continue; }
console.log(`${x.id} [${x.package}]: ${x.display} -- a ${x.fill.a}/${CAPS.a} \u00b7 b ${x.fill.b}/${CAPS.b} \u00b7 cold ${x.fill.cold}`);
}
if (!found) console.log('(no runs -- create one: create <package> <pc-name>)');
}
/** @returns {string} */
function today() { return new Date().toISOString().slice(0, 10); }
// save a DRAFT's craft as a new user package: the same files create
@@ -912,6 +1004,7 @@ function today() { return new Date().toISOString().slice(0, 10); }
// is fork's job. The saved package carries no pc (the next create asks
// for one); the display name is the save's one decision. The id is
// anonymous hex, like a run's: no facts, nothing to rename.
/** @param {?string} displayName */
function cmdSavePackage(displayName) {
const name = String(displayName ?? '').trim();
if (!name) fail('usage: save-package "display name" (run required via --run)');
@@ -919,7 +1012,7 @@ function cmdSavePackage(displayName) {
if (ns.length > 1 || sessionMeta(ns[0] ?? 0).phase !== 'dormant') {
fail('save-package is a draft act -- this run has played; fork it to branch the story');
}
let id;
/** @type {string} */ let id;
for (;;) {
id = randomBytes(4).toString('hex');
if (!fs.existsSync(path.join(STATE_PACKAGES_DIR, id)) && !fs.existsSync(path.join(PACKAGES_DIR, id))) break;
@@ -939,7 +1032,7 @@ function cmdSavePackage(displayName) {
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
}
const settingsPath = path.join(dst, 'settings.json');
let settings = {};
/** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {}
settings.name = name;
delete settings.pc; // per-run identity never rides a package
@@ -954,13 +1047,14 @@ function cmdSavePackage(displayName) {
console.log(`saved package '${id}' -- ${name}: ${rel(dst)}`);
}
/** @param {string} ring @param {string} type @param {string} label @param {?string} [detail] */
function gmOp(ring, type, label, detail) {
const db = openDb();
if (!RINGS.includes(ring) || !TYPES.includes(type)) {
fail(`usage: insert <a|b> <${TYPES.join('|')}> "Label" "detail"`);
}
db.exec('BEGIN');
let id;
/** @type {number} */ let id;
try {
id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' });
db.exec('COMMIT');
@@ -973,28 +1067,30 @@ function gmOp(ring, type, label, detail) {
dumpDb(db);
}
/** @param {string} idStr @param {?string} [reason] */
function cmdDelete(idStr, reason) {
const db = openDb();
const id = parseId(idStr);
const row = id && db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = id && /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) fail(`no such entry: ${idStr}`);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(/** @type {number} */ (id));
journal(db, 'gm', 'delete', `e${id}`, reason ?? 'GM edit');
console.log(`[e${id}] **${row.label}** -> cold storage`);
renderAll(db);
dumpDb(db);
}
/** @param {string} idStr @param {?string} [ring] */
function cmdRevive(idStr, ring = 'b') {
const db = openDb();
const id = parseId(idStr);
const row = id && db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = id && /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) fail(`no such entry: ${idStr}`);
if (row.ring !== 'cold') fail(`[e${id}] is not in cold storage (ring ${row.ring})`);
if (!RINGS.includes(ring)) fail(`target ring must be a|b`);
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(ring, id);
if (!RINGS.includes(ring ?? '')) fail(`target ring must be a|b`);
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(/** @type {string} */ (ring), /** @type {number} */ (id));
journal(db, 'gm', 'revive', `e${id}`, 'GM revive');
console.log(`[e${id}] **${row.label}** revived -> ring ${ring.toUpperCase()}`);
console.log(`[e${id}] **${row.label}** revived -> ring ${/** @type {string} */ (ring).toUpperCase()}`);
renderAll(db);
dumpDb(db);
}
@@ -1003,6 +1099,7 @@ function cmdDump() {
console.log(rel(dumpDb(openDb())));
}
/** @param {boolean} force */
function cmdRestore(force = false) {
const dumpFile = path.join(DUMPS_DIR, 'memory.sql');
if (!fs.existsSync(dumpFile)) fail(`no dump at ${rel(dumpFile)} -- nothing to restore from`);
@@ -1023,6 +1120,7 @@ function cmdRestore(force = false) {
renderAll(db);
}
/** @param {?string} kind @param {?string} label @param {?string} [detail] @param {?string} [reason] */
function cmdFile(kind, label, detail, reason) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to file (see the run\'s settings.json)');
@@ -1035,14 +1133,15 @@ function cmdFile(kind, label, detail, reason) {
dumpDb(db);
}
/** @param {string} ridStr @param {?string} detail */
function cmdAmend(ridStr, detail) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
if (!detail?.trim()) fail('usage: amend <rid> "new detail"');
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), rid);
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), /** @type {number} */ (rid));
// saga rule: the journal keeps the prior detail, so turn surgery can
// compensate mechanically
journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended', row.detail);
@@ -1050,13 +1149,14 @@ function cmdAmend(ridStr, detail) {
dumpDb(db);
}
/** @param {string} ridStr @param {?string} [reason] */
function cmdDiscard(ridStr, reason) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
db.prepare('DELETE FROM records WHERE id = ?').run(/** @type {number} */ (rid));
// saga rule: the whole discarded row is journaled -- a compensation
// can re-file it exactly (id included, so rid references stay valid)
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded',
@@ -1073,10 +1173,12 @@ function cmdDiscard(ridStr, reason) {
// The GM overrides out-of-band with status-set. Descriptions never contain
// commas: both the delta lists and the <status> block are comma-separated.
const statusList = (db) => db.prepare('SELECT descr FROM status ORDER BY id').all().map((r) => r.descr);
/** @param {DatabaseSync} db @returns {string[]} */
const statusList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM status ORDER BY id').all()).map((r) => r.descr);
// split a list of descriptions, tolerating newlines and list bullets --
// covers the delta tags and a <status> block body alike
/** @param {unknown} s @returns {string[]} */
const splitDescrs = (s) =>
String(s ?? '').split('\n').flatMap((line) =>
line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean);
@@ -1085,13 +1187,14 @@ function cmdStatus() {
console.log(JSON.stringify(statusList(openDb())));
}
/** @param {string} text */
function cmdStatusApply(text) {
const db = openDb();
const lost = [];
const gained = [];
for (const m of String(text ?? '').matchAll(/<lost>([\s\S]*?)<\/lost>/g)) lost.push(...splitDescrs(m[1]));
for (const m of String(text ?? '').matchAll(/<gained>([\s\S]*?)<\/gained>/g)) gained.push(...splitDescrs(m[1]));
const applied = { lost: [], gained: [], conflicts: [] };
/** @type {{ lost: string[], gained: string[], conflicts: string[] }} */ const applied = { lost: [], gained: [], conflicts: [] };
if (!lost.length && !gained.length) {
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
return;
@@ -1100,7 +1203,7 @@ function cmdStatusApply(text) {
db.exec('BEGIN');
try {
for (const item of lost) {
const row = db.prepare('SELECT * FROM status WHERE descr = ?').get(item);
const row = /** @type {?StatusRow} */ (db.prepare('SELECT * FROM status WHERE descr = ?').get(item));
if (row) {
db.prepare('DELETE FROM status WHERE id = ?').run(row.id);
journal(db, win, 'status-drop', `p${row.id}`, 'delta', row.descr);
@@ -1128,6 +1231,7 @@ function cmdStatusApply(text) {
// whole-status replace (GM override); the journal keeps
// the full prior status so turn surgery can compensate mechanically
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {string[]} */
function setStatus(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = statusList(db);
@@ -1146,6 +1250,7 @@ function setStatus(db, items, reason, win) {
return clean;
}
/** @param {string[]} items */
function cmdStatusSet(items) {
const db = openDb();
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc');
@@ -1164,21 +1269,23 @@ function cmdStatusSet(items) {
// 0-based indexes against the agenda as last rendered, adds are
// comma-separated. The GM overrides whole-list with agenda-set.
const agendaList = (db) => db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all().map((r) => r.descr);
/** @param {DatabaseSync} db @returns {string[]} */
const agendaList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all()).map((r) => r.descr);
function cmdAgenda() {
console.log(JSON.stringify(agendaList(openDb())));
}
/** @param {string} text */
function cmdAgendaApply(text) {
const db = openDb();
const added = [];
const dropped = [];
const evicted = [];
const conflicts = [];
const adds = [];
/** @type {string[]} */ const added = [];
/** @type {string[]} */ const dropped = [];
/** @type {string[]} */ const evicted = [];
/** @type {string[]} */ const conflicts = [];
/** @type {string[]} */ const adds = [];
for (const m of String(text ?? '').matchAll(/<add>([\s\S]*?)<\/add>/g)) adds.push(...splitDescrs(m[1]));
const drops = [];
/** @type {string[]} */ const drops = [];
for (const m of String(text ?? '').matchAll(/<drop>([\s\S]*?)<\/drop>/g)) {
drops.push(...String(m[1]).split(/[\n,]/).map((x) => x.trim()).filter(Boolean));
}
@@ -1193,7 +1300,7 @@ function cmdAgendaApply(text) {
// -> next block. Indexes resolve against the same snapshot, so a
// multi-drop never shifts under itself.
const snapshot = agendaList(db);
const kill = [];
/** @type {number[]} */ const kill = [];
for (const d of drops) {
if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; }
const i = Number(d);
@@ -1205,7 +1312,7 @@ function cmdAgendaApply(text) {
}
for (const i of [...new Set(kill)].sort((a, b) => b - a)) {
const descr = snapshot[i];
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr);
const row = /** @type {{ id: number }} */ (db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr));
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr);
dropped.push(descr);
@@ -1225,7 +1332,7 @@ function cmdAgendaApply(text) {
// overflow: the bottom sinks off the list -- by design, not an error
const over = agendaList(db);
for (let i = over.length - 1; i >= AGENDA_CAP; i--) {
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]);
const row = /** @type {{ id: number }} */ (db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]));
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)');
evicted.push(over[i]);
@@ -1242,6 +1349,7 @@ function cmdAgendaApply(text) {
// whole-list replace (GM override); the journal keeps the prior queue
// so turn surgery can compensate mechanically (the saga rule)
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {string[]} */
function setAgenda(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = agendaList(db);
@@ -1260,6 +1368,7 @@ function setAgenda(db, items, reason, win) {
return clean;
}
/** @param {string[]} items */
function cmdAgendaSet(items) {
const db = openDb();
const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc');
@@ -1268,38 +1377,41 @@ function cmdAgendaSet(items) {
dumpDb(db);
}
/** @param {string[]} options */
function cmdPick(options) {
if (options.length < 2) fail('usage: pick "option one" "option two" [...]');
const choice = options[Math.floor(Math.random() * options.length)];
console.log(`picked: ${choice}`);
}
/** @param {string[]} terms */
function cmdSearch(terms) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to consult');
if (!terms.length) fail('usage: search <terms...>');
const conds = terms.map(() => "(label || ' ' || detail) LIKE ?").join(' AND ');
const params = terms.map((t) => `%${t}%`);
const rows = db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params);
const rows = /** @type {RecordRow[]} */ (db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params));
if (!rows.length) { console.log('(no records match)'); return; }
for (const r of rows) console.log(`[r${r.id}] [${r.kind}] **${r.label}**${r.detail ? ` -- ${r.detail}` : ''}`);
const total = db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params).n;
const total = Number(db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params)?.n ?? 0);
if (total > rows.length) console.log(`...${total - rows.length} more omitted -- narrow the query`);
}
/** @param {string} ridStr @param {?string} [ring] */
function cmdUnarchive(ridStr, ring = 'b') {
const db = openDb();
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
if (!RINGS.includes(ring)) fail('target ring must be a|b');
if (!RINGS.includes(ring ?? '')) fail('target ring must be a|b');
const type = TYPES.includes(row.kind) ? row.kind : 'fact';
const res = db.prepare('INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)')
.run(ring, type, row.label, row.detail, row.created, today());
.run(/** @type {string} */ (ring), type, row.label, row.detail, row.created, today());
const eid = Number(res.lastInsertRowid);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
db.prepare('DELETE FROM records WHERE id = ?').run(/** @type {number} */ (rid));
journal(db, 'gm', 'unarchive', `e${eid}`, 'GM unarchive');
console.log(`[r${rid}] **${row.label}** -> ring ${ring.toUpperCase()} as [e${eid}]`);
console.log(`[r${rid}] **${row.label}** -> ring ${/** @type {string} */ (ring).toUpperCase()} as [e${eid}]`);
renderAll(db);
dumpDb(db);
}
@@ -1307,41 +1419,42 @@ function cmdUnarchive(ridStr, ring = 'b') {
function cmdReport() {
const db = openDb();
if (AS_JSON) {
/** @type {{ run: ?string, records: number, recordsEnabled: boolean, status: string[], agenda: string[], events: number, rings: Record<string, number>, sinking: Record<string, { id: number, last_touched: string, label: string }[]> }} */
const out = {
run: RUN,
records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n,
records: Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0),
recordsEnabled: recordsEnabled(),
status: statusList(db),
agenda: agendaList(db),
events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n,
events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0),
rings: {},
sinking: {},
};
for (const ring of ['a', 'b', 'cold']) {
out.rings[ring] = db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
out.rings[ring] = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
if (ring !== 'cold') {
out.sinking[ring] = db.prepare(
out.sinking[ring] = /** @type {{ id: number, last_touched: string, label: string }[]} */ (db.prepare(
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
).all(ring);
).all(ring));
}
}
console.log(JSON.stringify(out));
return;
}
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
const nr = Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0);
console.log(`records: ${nr}`);
const status = statusList(db);
console.log(`status: ${status.length ? '' : '(a blank sheet)'}`);
for (const d of status) console.log(` - ${d}`);
for (const ring of ['a', 'b', 'cold']) {
const n = db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
const n = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
const cap = CAPS[ring] ?? 'none';
console.log(`ring ${ring}: ${n} / ${cap}`);
if (ring !== 'cold') {
const old = db.prepare(
const old = /** @type {{ id: number, last_touched: string, label: string }[]} */ (db.prepare(
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
).all(ring);
).all(ring));
for (const r of old) console.log(` sinking: [e${r.id}] ${r.last_touched} **${r.label}**`);
}
}
@@ -1351,7 +1464,7 @@ function cmdReport() {
// the freeze ruling rides the dispatch: a mutating verb touches only
// the phases its rules allow (see PHASE_RULES)
if (RUN != null && PHASE_RULES[cmd]) enforcePhase(cmd);
if (RUN != null && PHASE_RULES[cmd ?? '']) enforcePhase(cmd ?? '');
switch (cmd) {
case 'packages': cmdPackages(); break;