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
+46 -20
View File
@@ -91,16 +91,35 @@ memory the agent owes itself across sessions.
launch from the new path. launch from the new path.
- The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running - The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running
`--mock` server, prints its run ids, and leaves a temp token file `--mock` server, prints its run ids, and leaves a temp token file
for `restart-check.mjs`; `check-reminder.mjs` takes a run id; for `restart-check.mjs`; `check-reminder.mjs` takes a run id --
`check-repo.mjs` needs no server. Clean up state/ and the smoke one whose NEWEST LOGGED session has GM turns (post-smoke that is
runs afterwards -- only the real runs stay. The type gate: the fork lineage, e.g. the refork id in the token file; the source
`npm.cmd run typecheck` (plain `npx.cmd tsc -p tsconfig.json`) run's newest logged session is the near-empty session 4, and
runs tsc as a no-emit checker over the JSDoc annotations -- aiming it there fails on 0 reminders -- learned 2026-11-15);
dev-only tooling (typescript + @types/node in devDependencies, `check-repo.mjs` needs no server. The smoke cannot run twice --
node_modules gitignored); the runtime stays zero-dependency the second run dies on the dirty state (learned 2026-11-15): stop
(QUESTIONS #4 amended 2026-11-15). Server core is typed under the server, Remove-Item state/ and runs/, restart, run once. Clean
strict; the clerk (tool/memory.mjs) and web/ are phases to come -- up state/ and the smoke runs afterwards -- only the real runs
widen tsconfig include as they land. stay. The type gate: `npm.cmd run typecheck` runs TWO no-emit
tsc passes over the JSDoc annotations -- `tsconfig.json` (server
+ tool, node types) and `tsconfig.web.json` (web/, DOM libs; node
types ride along because server/shapes.mjs's Provider typedef
pulls provider.mjs into the web program). Dev-only tooling
(typescript + @types/node in devDependencies, node_modules
gitignored); the runtime stays zero-dependency (QUESTIONS #4
amended 2026-11-15). All four phases are typed under strict:
server core, the clerk, and web/. Typing lessons (2026-11-15,
the round): assigning an any (api()/JSON.parse result) to a
`?T` variable does NOT strip the null -- declare the variable
plain `T` and let definite assignment carry the try/catch (the
catch returns); under the web program's DOM+node merge the
browser timers resolve to node's overloads, so annotate them
`?ReturnType<typeof setTimeout>` and `clearTimeout(x ??
undefined)`.
- A fresh git worktree has neither server.json (gitignored) nor
node_modules: copy server.json in from the main repo before the
mock server starts (it exits without one), and run npm.cmd
install before typecheck (2026-11-15, this worktree).
## State pointers ## State pointers
@@ -204,16 +223,23 @@ memory the agent owes itself across sessions.
RESOLVED BY PLAN (2026-11-15): the dormant-session rework kills RESOLVED BY PLAN (2026-11-15): the dormant-session rework kills
the autorestart, and during dormancy the latest log IS the the autorestart, and during dormancy the latest log IS the
just-closed session; the replay default never needed to move. just-closed session; the replay default never needed to move.
- Active work: the entity round, the variant round, and the - Active work: the JSDoc typing round is COMPLETE (2026-11-15,
dormant-session rework are BUILT (2026-11-15, uncommitted, awaiting evening) -- all four phases. Phases 1-2 (the server core) are
the GM's eye). **The rework is now SMOKE-PROVEN end to end committed (`f81b188`); phases 3 (the clerk) and 4 (web/, via the
(2026-11-15, evening): smoke 105/105, restart-check, check-reminder, second tsconfig) are done and land with this commit -- typecheck
check-repo, and a full browser pass, all green; test state cleaned. green on both programs, smoke 110/110, restart-check on a genuine
The Irene hand-migration is DONE the same sitting (fork proven end restart, check-reminder, check-repo, and a full zero-console-error
to end, then real her mutated identically, reads green, zero writes browser pass over the SPA; test state cleaned. The audit lists of
to her log -- see HANDOFF "Where we are"). Next: the op's one-time non-annotation deltas live in HANDOFF ("Where we are"). Working
first start under multiuser (HANDOFF step 2), then the first real lessons from the rounds: in checkJs a JSDoc typedef sharing a
housekeeping pass (step 3).** Plan of record: name with a runtime import conflicts (TS2440) -- the import
already carries the type, just use the imported name in
annotations; the any/null and DOM-timer lessons live in the type
gate bullet above. The earlier rounds (entity, variant,
dormant-session rework, Irene hand-migration) are all committed
and live in the git log; the next operational steps remain the
op's one-time first start under multiuser (HANDOFF step 1), then
the first real housekeeping pass (step 2). Plan of record:
HANDOFF ("The dormant-session rework"); status: HANDOFF ("Where we HANDOFF ("The dormant-session rework"); status: HANDOFF ("Where we
are"). En-route fix flagged to the GM: the roll retirement had are"). En-route fix flagged to the GM: the roll retirement had
missed bundle.mjs's tool list; missed bundle.mjs's tool list;
+48 -19
View File
@@ -9,18 +9,55 @@ file is the "where did we leave off" map.
## Where we are ## Where we are
- **The server core is JSDoc-typed, strict, green (2026-11-15, - **The typing round is COMPLETE: all four phases (2026-11-15).**
evening) -- committed.** tsc runs as a Phases 1-2 (the server core) are committed (`f81b188`); phases 3
no-emit checker (`npm run typecheck`) over plain `.mjs` with JSDoc (the clerk) and 4 (web/) are done the same sitting and land with
annotations; the shared shapes live in `server/shapes.mjs` (log this commit. tsc runs as a no-emit checker (`npm run typecheck`) over
events as a tagged union, wire messages, manifests, job state, plain `.mjs` with JSDoc annotations; the shared shapes live in
the Ctx). Dev tooling only: `typescript` + `@types/node` in `server/shapes.mjs` (log events as a tagged union, wire messages,
manifests, job state, the Ctx), the db row shapes live local to
their owners (the clerk's five tables typed in tool/memory.mjs's
header, like users.mjs's rows), and the SPA's response envelopes
live in `web/shapes.mjs` with the server's shared shapes (User,
LogEvent, JobState) imported from server/shapes.mjs at their use
sites. Dev tooling only: `typescript` + `@types/node` in
devDependencies, `node_modules/` gitignored -- the runtime stays devDependencies, `node_modules/` gitignored -- the runtime stays
zero-dependency (QUESTIONS #4 amended to say so). Verified: the zero-dependency (QUESTIONS #4 amended to say so).
full diff audited change-by-change (every non-annotation delta is - The clerk round: every `.get()`/`.all()` cast at the db
an impossible-path guard or a behavior-identical wrap), smoke boundary, `fail` annotated `@returns {never}` so guard-narrowing
105/105, restart-check, check-repo, all green. Phases to come are works, tsconfig's include widened to `tool/`. Non-annotation
steps 5 and 6 below. deltas, all of them: Number() wraps around COUNT(*) reads, two
impossible-path guards (apply's session, the runs-list fill),
`?? ''` where a possibly undefined cmd indexes the phase rules /
run-less set, and the RewordOp shape fix (reason required -- the
validator demands it; no server code constructs reword ops).
- The web round: a SECOND tsconfig (`tsconfig.web.json`) -- DOM
libs in their own program, keeping the server program free of
DOM/node global collisions; the typecheck script runs both.
`node` types ride along in the web config because
server/shapes.mjs's Provider typedef pulls provider.mjs into
the web program. `$`/`el` typed at the DOM boundary
(HTMLElement; typed-element casts at input/dialog/select use
sites), timers as `?ReturnType<typeof setTimeout>`. The full
diff audited; the non-annotation deltas, all of them: the
transcript's reminder-find gains `x.t === 'msg' &&` (reminder
lives only on msg events), `clearTimeout(x ?? undefined)` on
the three null-initialized timers (null and undefined are both
no-ops), `!!()`-wraps on the two `mine` booleans (null vs
false, used only truthily), five impossible-path guards (the
router's named-view, the play/setup/story enter run-ids,
setup's signed-in owner check, saveDirty's currentFile), the
setup `files` local initialized `{}` instead of null (never
read before enter), and view-new caching the create-pc lookup
in one local (same element, same accesses).
- Verified, both rounds: typecheck green (both programs), smoke
110/110, restart-check on a genuine restart, check-reminder
(aimed at the fork lineage -- the source run's newest logged
session is the near-empty session 4), check-repo, and a full
browser pass over the SPA (claim, home + admin, play incl. a
live turn + pane edits, story, the setup editor incl. dirty
markers + draft stash, new-run incl. the name roll) with zero
console errors; test state cleaned.
- **Everything is built, proven, and committed (through `d737e47`, - **Everything is built, proven, and committed (through `d737e47`,
2026-11-15).** The full scope, each round mock-proven end to end 2026-11-15).** The full scope, each round mock-proven end to end
@@ -89,14 +126,6 @@ file is the "where did we leave off" map.
candidates), coin-flip personality (choices offloaded to chance candidates), coin-flip personality (choices offloaded to chance
that should be character), and whether her variants stay same-turn that should be character), and whether her variants stay same-turn
alternatives rather than sequences. alternatives rather than sequences.
5. **Typing phase 3: the clerk** (`tool/memory.mjs`, the big one).
The db row shapes (entries, records, status, agenda, the events
journal), the CLI dispatch, the manifest validator -- typed at the
db boundary per the same doctrine, then widen tsconfig's include
to `tool/`.
6. **Typing phase 4: web/** -- DOM types for the SPA modules
(`"lib": ["DOM"]` or a second tsconfig), the same shared shapes
imported from server/shapes.mjs where the wire surfaces appear.
## Not yet exercised (expect first-use friction) ## Not yet exercised (expect first-use friction)
+1 -1
View File
@@ -3,7 +3,7 @@
"private": true, "private": true,
"description": "Long-form, freeform, text-based roleplay where the model plays one character and the human plays everything else. Runtime: plain node, zero dependencies -- this file exists for dev tooling only.", "description": "Long-form, freeform, text-based roleplay where the model plays one character and the human plays everything else. Runtime: plain node, zero dependencies -- this file exists for dev tooling only.",
"scripts": { "scripts": {
"typecheck": "tsc -p tsconfig.json" "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.web.json"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.10.0", "@types/node": "^22.10.0",
+1 -1
View File
@@ -69,7 +69,7 @@ export {};
/** A housekeeping manifest -- the housekeeper's whole write surface. */ /** A housekeeping manifest -- the housekeeper's whole write surface. */
/** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */ /** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */
/** @typedef {{ id: string, reason: string }} RefOp */ /** @typedef {{ id: string, reason: string }} RefOp */
/** @typedef {{ id: string, detail: string, reason?: string }} RewordOp */ /** @typedef {{ id: string, detail: string, reason: string }} RewordOp */
/** @typedef {{ type: string, label: string, detail: string }} RecordOp */ /** @typedef {{ type: string, label: string, detail: string }} RecordOp */
/** @typedef {{ session: string, summary: string, insert?: InsertOp[], touch?: RefOp[], promote?: RefOp[], demote?: RefOp[], reword?: RewordOp[], delete?: RefOp[], archive?: RefOp[], record?: RecordOp[], inventions?: string[], open_questions?: string[] }} Manifest */ /** @typedef {{ session: string, summary: string, insert?: InsertOp[], touch?: RefOp[], promote?: RefOp[], demote?: RefOp[], reword?: RewordOp[], delete?: RefOp[], archive?: RefOp[], record?: RecordOp[], inventions?: string[], open_questions?: string[] }} Manifest */
+200 -87
View File
@@ -61,6 +61,42 @@
// //
// report counts, caps, the status, what's sinking // 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 { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto'; import { randomBytes } from 'node:crypto';
import fs from 'node:fs'; 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'); const RUNS_DIR = path.join(ROOT, 'runs');
// dials -- retune freely // dials -- retune freely
/** @type {Record<string, number>} */
const CAPS = { a: 500, b: 3000 }; const CAPS = { a: 500, b: 3000 };
const AGENDA_CAP = 5; // dial -- retune freely (invariants.md: "intentionally tiny") const AGENDA_CAP = 5; // dial -- retune freely (invariants.md: "intentionally tiny")
const TYPES = ['place', 'person', 'fact', 'thread']; const TYPES = ['place', 'person', 'fact', 'thread'];
const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models 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); }; const fail = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
/** @param {string} p @returns {string} */
const rel = (p) => path.relative(ROOT, p).replaceAll('\\', '/'); const rel = (p) => path.relative(ROOT, p).replaceAll('\\', '/');
// flags: --run <name> beats everything; --gm attributes the op to the GM // flags: --run <name> beats everything; --gm attributes the op to the GM
const argv = process.argv.slice(2); const argv = process.argv.slice(2);
const runIdx = argv.indexOf('--run'); const runIdx = argv.indexOf('--run');
/** @type {?string} */
let runOverride = null; let runOverride = null;
if (runIdx !== -1) { if (runIdx !== -1) {
runOverride = argv[runIdx + 1] ?? null; runOverride = argv[runIdx + 1] ?? null;
argv.splice(runIdx, 2); argv.splice(runIdx, 2);
} }
const sessionIdx = argv.indexOf('--session'); const sessionIdx = argv.indexOf('--session');
/** @type {?number} */
let sessionOverride = null; let sessionOverride = null;
if (sessionIdx !== -1) { if (sessionIdx !== -1) {
sessionOverride = Number(argv[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'); const AS_JSON = argv.includes('--json');
for (let i = argv.indexOf('--json'); i !== -1; i = argv.indexOf('--json')) argv.splice(i, 1); for (let i = argv.indexOf('--json'); i !== -1; i = argv.indexOf('--json')) argv.splice(i, 1);
const ownerIdx = argv.indexOf('--owner'); const ownerIdx = argv.indexOf('--owner');
/** @type {?string} */
let ownerOverride = null; let ownerOverride = null;
if (ownerIdx !== -1) { if (ownerIdx !== -1) {
ownerOverride = argv[ownerIdx + 1] ?? null; 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`; // a run is an instance under runs/, created from a package by `create`;
// state is per-deployment -- a fresh clone has zero runs // state is per-deployment -- a fresh clone has zero runs
const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']); const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']);
const RUN = NO_RUN_NEEDED.has(cmd) ? null : runOverride; const RUN = NO_RUN_NEEDED.has(cmd ?? '') ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd) && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) { 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>'); 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 // per-run paths: set once from --run, and re-pointed by create (which
// builds a run dir before any view is written) // 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) { function setRunRoot(dir) {
RUN_ROOT = dir; RUN_ROOT = dir;
SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json'); 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: // for audit, writes only where the phase allows (the freeze ruling:
// prompts, rings, and carryover are editable during dormancy, frozen // prompts, rings, and carryover are editable during dormancy, frozen
// from the moment a session goes live). // from the moment a session goes live).
/** @param {string} [runDir] @returns {number[]} */
function listSessions(runDir = RUN_ROOT) { function listSessions(runDir = RUN_ROOT) {
const dir = path.join(runDir, 'sessions'); const dir = path.join(runDir, 'sessions');
if (!fs.existsSync(dir)) return []; if (!fs.existsSync(dir)) return [];
@@ -149,6 +199,7 @@ function listSessions(runDir = RUN_ROOT) {
.map((d) => Number(d.name)).sort((a, b) => a - b); .map((d) => Number(d.name)).sort((a, b) => a - b);
} }
/** @param {number} n @param {string} [runDir] @returns {SessionMeta} */
const sessionMeta = (n, runDir = RUN_ROOT) => { const sessionMeta = (n, runDir = RUN_ROOT) => {
try { try {
return JSON.parse(fs.readFileSync(path.join(runDir, 'sessions', String(n), 'session.json'), 'utf8')); 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) { function resolveSession(want) {
const ns = listSessions(); const ns = listSessions();
if (!ns.length) fail('this run has no sessions -- create builds session one'); 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]; return live.length ? live[0] : ns[ns.length - 1];
} }
/** @param {number} n */
function setSessionRoot(n) { function setSessionRoot(n) {
SESS = n; SESS = n;
const d = path.join(RUN_ROOT, 'sessions', String(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 // dangerous, finished is frozen); the status and agenda are runtime
// channels (live) and the dormancy edit surface; apply targets the // channels (live) and the dormancy edit surface; apply targets the
// dormant session's rings -- the housekeeping write. // dormant session's rings -- the housekeeping write.
/** @type {Record<string, string[]>} */
const PHASE_RULES = { const PHASE_RULES = {
insert: ['dormant'], delete: ['dormant'], revive: ['dormant'], unarchive: ['dormant'], insert: ['dormant'], delete: ['dormant'], revive: ['dormant'], unarchive: ['dormant'],
apply: ['dormant'], apply: ['dormant'],
@@ -192,6 +246,7 @@ const PHASE_RULES = {
'status-apply': ['live'], 'agenda-apply': ['live'], 'status-apply': ['live'], 'agenda-apply': ['live'],
file: ['dormant', 'live'], amend: ['dormant', 'live'], discard: ['dormant', 'live'], file: ['dormant', 'live'], amend: ['dormant', 'live'], discard: ['dormant', 'live'],
}; };
/** @param {string} verb */
function enforcePhase(verb) { function enforcePhase(verb) {
const allowed = PHASE_RULES[verb]; const allowed = PHASE_RULES[verb];
if (!allowed) return; if (!allowed) return;
@@ -225,6 +280,7 @@ GM ratifies notable inventions afterward.)
Freeform notes: Freeform notes:
`; `;
/** @returns {boolean} */
function recordsEnabled() { function recordsEnabled() {
try { try {
return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true; return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true;
@@ -233,6 +289,7 @@ function recordsEnabled() {
} }
} }
/** @returns {DatabaseSync} */
function openDb() { function openDb() {
if (!fs.existsSync(DB_PATH)) { if (!fs.existsSync(DB_PATH)) {
fail(`no database at ${rel(DB_PATH)} -- run: node tool/memory.mjs init`); 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 // the old CHECK would reject the new op values mid-flight, and the
// positional copy absorbs the column rename. (Mirrors db/schema.sql; // positional copy absorbs the column rename. (Mirrors db/schema.sql;
// old dumps carry their own old schema and self-migrate through here.) // old dumps carry their own old schema and self-migrate through here.)
/** @param {DatabaseSync} db */
function migrateStatusNames(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 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')) { if (tables.includes('paper') && !tables.includes('status')) {
db.exec('ALTER TABLE paper RENAME TO status'); db.exec('ALTER TABLE paper RENAME TO status');
if (!QUIET) console.log(`(migrated: table paper -> status -- ${rel(DB_PATH)})`); 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; 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; if (!staleOps && row.sql.includes("'status-add'")) return;
db.exec('BEGIN'); db.exec('BEGIN');
try { try {
@@ -296,18 +354,22 @@ function migrateStatusNames(db) {
if (!QUIET) console.log(`(migrated: events journal to the current names -- ${rel(DB_PATH)})`); if (!QUIET) console.log(`(migrated: events journal to the current names -- ${rel(DB_PATH)})`);
} }
/** @param {unknown} s @returns {?number} */
const parseId = (s) => { const parseId = (s) => {
const m = /^e(\d+)$/.exec(String(s ?? '').trim()); const m = /^e(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null; return m ? Number(m[1]) : null;
}; };
/** @param {unknown} s @returns {string} */
const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim(); const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
/** @param {unknown} s @returns {?number} */
const parseRid = (s) => { const parseRid = (s) => {
const m = /^r(\d+)$/.exec(String(s ?? '').trim()); const m = /^r(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null; 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 = '') => const journal = (db, win, op, target, reason, prior = '') =>
db.prepare('INSERT INTO events (session, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)') db.prepare('INSERT INTO events (session, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
.run(win, op, target, norm(reason), prior); .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 // hand-edit them (regenerate with render). The do-not-edit warning lives
// here rather than in the output: prose files carry no comments, purpose // here rather than in the output: prose files carry no comments, purpose
// text lives in code or README. // text lives in code or README.
/** @param {DatabaseSync} db @param {string} ring @returns {{ file: string, count: number }} */
function renderRing(db, ring) { 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' '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 title = ring === 'a' ? 'what matters' : 'what stuck anyway';
const lines = [ const lines = [
`# Ring ${ring.toUpperCase()} -- ${title}`, `# Ring ${ring.toUpperCase()} -- ${title}`,
@@ -336,8 +399,9 @@ function renderRing(db, ring) {
return { file, count: rows.length }; return { file, count: rows.length };
} }
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderStatus(db) { 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 = [ const lines = [
'# Status', '# Status',
'', '',
@@ -355,6 +419,7 @@ function renderStatus(db) {
// the agenda view: the queue, top (newest) first, numbered as the wire // the agenda view: the queue, top (newest) first, numbered as the wire
// renders it -- what the model cites, what the GM reads // renders it -- what the model cites, what the GM reads
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderAgenda(db) { function renderAgenda(db) {
const items = agendaList(db); const items = agendaList(db);
const lines = [ const lines = [
@@ -372,6 +437,7 @@ function renderAgenda(db) {
return { file, count: items.length }; return { file, count: items.length };
} }
/** @param {DatabaseSync} db */
function renderAll(db) { function renderAll(db) {
// --json means stdout carries JSON only; the view paths are human garnish // --json means stdout carries JSON only; the view paths are human garnish
const talk = !QUIET && !AS_JSON; const talk = !QUIET && !AS_JSON;
@@ -387,8 +453,10 @@ function renderAll(db) {
// canonical serialization: id-ordered, one row per line, restorable SQL. // canonical serialization: id-ordered, one row per line, restorable SQL.
// this is the committed truth; the binary db is a local cache. // this is the committed truth; the binary db is a local cache.
/** @param {DatabaseSync} db @returns {string} */
function dumpDb(db) { function dumpDb(db) {
fs.mkdirSync(DUMPS_DIR, { recursive: true }); fs.mkdirSync(DUMPS_DIR, { recursive: true });
/** @param {unknown} s @returns {string} */
const q = (s) => `'${String(s ?? '').replace(/'/g, "''")}'`; const q = (s) => `'${String(s ?? '').replace(/'/g, "''")}'`;
const L = [ const L = [
'-- canonical dump of db/memory.db -- GENERATED by tool/memory.mjs; do not edit.', '-- 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(), fs.readFileSync(SCHEMA_PATH, 'utf8').trim(),
'BEGIN TRANSACTION;', '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)});`); 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)});`); 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)});`); 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)});`); 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(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
} }
L.push('COMMIT;', ''); L.push('COMMIT;', '');
@@ -420,6 +488,7 @@ function dumpDb(db) {
// stamps are mechanical (real, internal, never rendered): they drive // stamps are mechanical (real, internal, never rendered): they drive
// the LRU -- overflow, view order, "what's sinking". Story time lives // the LRU -- overflow, view order, "what's sinking". Story time lives
// in the prose of the entries, never in a column. // 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 }) { function insertEntry(db, { ring, type, label, detail, win, reason }) {
const now = today(); const now = today();
const res = db.prepare( const res = db.prepare(
@@ -432,19 +501,23 @@ function insertEntry(db, { ring, type, label, detail, win, reason }) {
// --- validation helpers (used by apply) ------------------------------------- // --- validation helpers (used by apply) -------------------------------------
/** @param {DatabaseSync} db */
function makeValidator(db) { function makeValidator(db) {
const errors = []; /** @type {string[]} */ const errors = [];
const seen = new Map(); /** @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`); }; 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) => { const asArray = (v, name) => {
if (v === undefined || v === null) return []; if (v === undefined || v === null) return [];
if (!Array.isArray(v)) { errors.push(`${name} must be an array`); return []; } if (!Array.isArray(v)) { errors.push(`${name} must be an array`); return []; }
return v; return v;
}; };
/** @param {string} op @param {RefOp} e @param {?string} expectRing @returns {?EntryRow} */
const ref = (op, e, expectRing) => { const ref = (op, e, expectRing) => {
const id = parseId(e.id); const id = parseId(e.id);
if (id == null) { errors.push(`${op}: id must look like e12`); return null; } 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) { 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 (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) { if (expectRing && row.ring !== expectRing) {
@@ -460,8 +533,10 @@ function makeValidator(db) {
// --- apply ------------------------------------------------------------------ // --- apply ------------------------------------------------------------------
/** @param {Manifest} mf @param {AppliedLog} applied @param {OverflowItem[]} overflow @returns {string} */
function renderLog(mf, applied, overflow) { function renderLog(mf, applied, overflow) {
const L = [`# ${mf.session}`, '', mf.summary, '']; const L = [`# ${mf.session}`, '', mf.summary, ''];
/** @template T @param {string} title @param {T[]} rows @param {(r: T) => string} fmt */
const section = (title, rows, fmt) => { const section = (title, rows, fmt) => {
if (!rows.length) return; if (!rows.length) return;
L.push(`## ${title}`, ''); L.push(`## ${title}`, '');
@@ -482,9 +557,10 @@ function renderLog(mf, applied, overflow) {
return L.join('\n'); return L.join('\n');
} }
/** @param {string} manifestPath */
function cmdApply(manifestPath) { function cmdApply(manifestPath) {
const db = openDb(); const db = openDb();
let mf; /** @type {Manifest} */ let mf;
try { try {
mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (e) { } catch (e) {
@@ -536,7 +612,7 @@ function cmdApply(manifestPath) {
}); });
del.forEach((e) => ref('delete', e, null)); del.forEach((e) => ref('delete', e, null));
arch.forEach((e) => ref('archive', 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`); }); 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}`); for (const e of errors) console.error(` - ${e}`);
process.exit(1); 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: [] }; /** @type {AppliedLog} */ const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
const overflow = []; /** @type {OverflowItem[]} */ const overflow = [];
db.exec('BEGIN'); db.exec('BEGIN');
try { try {
@@ -558,34 +636,36 @@ function cmdApply(manifestPath) {
}); });
applied.insert.push({ id, ...e }); applied.insert.push({ id, ...e });
} }
/** @param {number} id */
const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(today(), 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) { for (const e of touch) {
const id = parseId(e.id); const id = /** @type {number} */ (parseId(e.id));
touchDate(id); touchDate(id);
journal(db, mf.session, 'touch', `e${id}`, e.reason); journal(db, mf.session, 'touch', `e${id}`, e.reason);
applied.touch.push({ row: fetch(id), reason: e.reason }); applied.touch.push({ row: fetch(id), reason: e.reason });
} }
for (const e of promote) { 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); db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'promote', `e${id}`, e.reason); journal(db, mf.session, 'promote', `e${id}`, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason }); applied.promote.push({ row: fetch(id), reason: e.reason });
} }
for (const e of demote) { 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); db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'demote', `e${id}`, e.reason); journal(db, mf.session, 'demote', `e${id}`, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason }); applied.demote.push({ row: fetch(id), reason: e.reason });
} }
for (const e of reword) { 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); 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); journal(db, mf.session, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason }); applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
} }
for (const e of arch) { for (const e of arch) {
const id = parseId(e.id); const id = /** @type {number} */ (parseId(e.id));
const row = fetch(id); const row = fetch(id);
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)') const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(row.type, row.label, row.detail, row.created); .run(row.type, row.label, row.detail, row.created);
@@ -595,7 +675,7 @@ function cmdApply(manifestPath) {
applied.archive.push({ rid, row, reason: e.reason }); applied.archive.push({ rid, row, reason: e.reason });
} }
for (const e of del) { 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); db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
journal(db, mf.session, 'delete', `e${id}`, e.reason); journal(db, mf.session, 'delete', `e${id}`, e.reason);
applied.delete.push({ row: fetch(id), reason: 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 // overflow: A spills to B first, then B spills to cold -- exact, by count
for (const ring of RINGS) { 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' 'SELECT id FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC'
).all(ring); ).all(ring));
const extra = rows.length - CAPS[ring]; const extra = rows.length - CAPS[ring];
for (let i = 0; i < extra; i++) { for (let i = 0; i < extra; i++) {
const victim = rows[i]; const victim = rows[i];
@@ -664,6 +744,7 @@ function cmdInit() {
// stubs, the phase marker. The caller (create or init) owns the // stubs, the phase marker. The caller (create or init) owns the
// bundle copies; ready is true from birth -- session one's rings are // bundle copies; ready is true from birth -- session one's rings are
// its own (memory.json applied), no housekeeping ever precedes it. // its own (memory.json applied), no housekeeping ever precedes it.
/** @param {string} runDir @returns {{ db: DatabaseSync, dir: string }} */
function buildSession1(runDir) { function buildSession1(runDir) {
const s1 = path.join(runDir, 'sessions', '1'); const s1 = path.join(runDir, 'sessions', '1');
for (const d of ['bundle', 'db', 'canon', 'dumps', 'log']) { 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 // resolve a package name against both roots; the repo wins a collision
/** @param {?string} name @returns {?string} */
function packageDir(name) { function packageDir(name) {
if (!/^[a-z0-9-]+$/.test(name ?? '')) return null; 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(PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(PACKAGES_DIR, /** @type {string} */ (name));
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, name))) return path.join(STATE_PACKAGES_DIR, name); if (fs.existsSync(path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name));
return null; return null;
} }
// the package meta of a user package (owner, created); system packages // the package meta of a user package (owner, created); system packages
// have none -- their origin is the repo itself // have none -- their origin is the repo itself
/** @param {string} dir @returns {?{ owner?: ?string, created?: string }} */
function readPackageMeta(dir) { function readPackageMeta(dir) {
try { try {
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')); 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) { function packageEntry(name, dir, origin) {
// exists AND non-empty: an emptied placeholder is not a playable // exists AND non-empty: an emptied placeholder is not a playable
// package, and the listing must not call it complete (boutique, // package, and the listing must not call it complete (boutique,
// emptied 2026-11-15, taught this) // emptied 2026-11-15, taught this)
/** @param {string} f @returns {boolean} */
const has = (f) => { const has = (f) => {
try { return fs.statSync(path.join(dir, f)).size > 0; } catch { return false; } 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 {} try { settings = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')); } catch {}
const meta = origin === 'user' ? readPackageMeta(dir) : null; const meta = origin === 'user' ? readPackageMeta(dir) : null;
return { return {
@@ -749,7 +834,8 @@ function packageEntry(name, dir, origin) {
} }
function cmdPackages() { function cmdPackages() {
const list = []; /** @type {PackageListed[]} */ const list = [];
/** @param {string} root @param {'system'|'user'} origin */
const scan = (root, origin) => { const scan = (root, origin) => {
if (!fs.existsSync(root)) return; if (!fs.existsSync(root)) return;
for (const d of fs.readdirSync(root, { withFileTypes: true })) { 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 // 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 // matter -- the package display name and the pc's name -- live in the
// run's settings copy and drive the display ("La Caramba / Rell"). // run's settings copy and drive the display ("La Caramba / Rell").
/** @param {string} runDir @returns {RunSettings} */
const readRunSettings = (runDir) => { const readRunSettings = (runDir) => {
try { return JSON.parse(fs.readFileSync(path.join(runDir, 'settings.json'), 'utf8')); } catch { return {}; } 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) => const runDisplay = (pkg, settings) =>
settings.pc ? `${settings.name ?? pkg} / ${settings.pc}` : (settings.name ?? pkg); settings.pc ? `${settings.name ?? pkg} / ${settings.pc}` : (settings.name ?? pkg);
/** @returns {string} */
function anonId() { function anonId() {
for (;;) { for (;;) {
const id = randomBytes(4).toString('hex'); // 8 hex chars 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) { function cmdCreate(pkgName, pc, displayName, model) {
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) { if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
fail('usage: create <package> <pc-name> ["package display name"] ["model"]'); 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 })) { for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
const rd = path.join(RUNS_DIR, d.name); 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; } try { meta = JSON.parse(fs.readFileSync(path.join(rd, 'run.json'), 'utf8')); } catch { continue; }
if (meta?.package !== pkgName) continue; if (meta?.package !== pkgName) continue;
const st = readRunSettings(rd); const st = readRunSettings(rd);
@@ -831,7 +921,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
settings.pc = pc; settings.pc = pc;
settings.name = displayName?.trim() || settings.name || pkgName; settings.name = displayName?.trim() || settings.name || pkgName;
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n'); 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 (model) meta.models = { player: model };
if (ownerOverride) meta.owner = ownerOverride; if (ownerOverride) meta.owner = ownerOverride;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n'); 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() { function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs -- create one: create <package> <pc-name>)'); return; } 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; let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) { for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run 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 if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
found++; found++;
let pkg = '?'; let pkg = '?';
let models = null; /** @type {?{ player?: ?string, housekeeper?: ?string }} */ let models = null;
let owner = null; /** @type {?string} */ let owner = null;
let created = null; /** @type {?string} */ let created = null;
let forked = null; /** @type {?number} */ let forked = null;
try { try {
const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8')); const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8'));
pkg = meta.package ?? '?'; pkg = meta.package ?? '?';
@@ -889,20 +979,22 @@ function cmdRuns() {
const phase = active == null ? null : sessionMeta(active, runDir).phase ?? null; 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 dbPath = active == null ? null : path.join(runDir, 'sessions', String(active), 'db', 'memory.db');
const ready = active == null ? null : sessionMeta(active, runDir).ready ?? null; 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); const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8')); 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') } }); 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; } if (AS_JSON) { console.log(JSON.stringify(list)); return; }
for (const x of list) { 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}`); 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>)'); if (!found) console.log('(no runs -- create one: create <package> <pc-name>)');
} }
/** @returns {string} */
function today() { return new Date().toISOString().slice(0, 10); } function today() { return new Date().toISOString().slice(0, 10); }
// save a DRAFT's craft as a new user package: the same files create // 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 // 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 // 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. // anonymous hex, like a run's: no facts, nothing to rename.
/** @param {?string} displayName */
function cmdSavePackage(displayName) { function cmdSavePackage(displayName) {
const name = String(displayName ?? '').trim(); const name = String(displayName ?? '').trim();
if (!name) fail('usage: save-package "display name" (run required via --run)'); 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') { 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'); fail('save-package is a draft act -- this run has played; fork it to branch the story');
} }
let id; /** @type {string} */ let id;
for (;;) { for (;;) {
id = randomBytes(4).toString('hex'); id = randomBytes(4).toString('hex');
if (!fs.existsSync(path.join(STATE_PACKAGES_DIR, id)) && !fs.existsSync(path.join(PACKAGES_DIR, id))) break; 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)); if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
} }
const settingsPath = path.join(dst, 'settings.json'); const settingsPath = path.join(dst, 'settings.json');
let settings = {}; /** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {} try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {}
settings.name = name; settings.name = name;
delete settings.pc; // per-run identity never rides a package 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)}`); 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) { function gmOp(ring, type, label, detail) {
const db = openDb(); const db = openDb();
if (!RINGS.includes(ring) || !TYPES.includes(type)) { if (!RINGS.includes(ring) || !TYPES.includes(type)) {
fail(`usage: insert <a|b> <${TYPES.join('|')}> "Label" "detail"`); fail(`usage: insert <a|b> <${TYPES.join('|')}> "Label" "detail"`);
} }
db.exec('BEGIN'); db.exec('BEGIN');
let id; /** @type {number} */ let id;
try { try {
id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' }); id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' });
db.exec('COMMIT'); db.exec('COMMIT');
@@ -973,28 +1067,30 @@ function gmOp(ring, type, label, detail) {
dumpDb(db); dumpDb(db);
} }
/** @param {string} idStr @param {?string} [reason] */
function cmdDelete(idStr, reason) { function cmdDelete(idStr, reason) {
const db = openDb(); const db = openDb();
const id = parseId(idStr); 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) 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'); journal(db, 'gm', 'delete', `e${id}`, reason ?? 'GM edit');
console.log(`[e${id}] **${row.label}** -> cold storage`); console.log(`[e${id}] **${row.label}** -> cold storage`);
renderAll(db); renderAll(db);
dumpDb(db); dumpDb(db);
} }
/** @param {string} idStr @param {?string} [ring] */
function cmdRevive(idStr, ring = 'b') { function cmdRevive(idStr, ring = 'b') {
const db = openDb(); const db = openDb();
const id = parseId(idStr); 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) fail(`no such entry: ${idStr}`);
if (row.ring !== 'cold') fail(`[e${id}] is not in cold storage (ring ${row.ring})`); 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`); if (!RINGS.includes(ring ?? '')) fail(`target ring must be a|b`);
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(ring, id); db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(/** @type {string} */ (ring), /** @type {number} */ (id));
journal(db, 'gm', 'revive', `e${id}`, 'GM revive'); 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); renderAll(db);
dumpDb(db); dumpDb(db);
} }
@@ -1003,6 +1099,7 @@ function cmdDump() {
console.log(rel(dumpDb(openDb()))); console.log(rel(dumpDb(openDb())));
} }
/** @param {boolean} force */
function cmdRestore(force = false) { function cmdRestore(force = false) {
const dumpFile = path.join(DUMPS_DIR, 'memory.sql'); const dumpFile = path.join(DUMPS_DIR, 'memory.sql');
if (!fs.existsSync(dumpFile)) fail(`no dump at ${rel(dumpFile)} -- nothing to restore from`); if (!fs.existsSync(dumpFile)) fail(`no dump at ${rel(dumpFile)} -- nothing to restore from`);
@@ -1023,6 +1120,7 @@ function cmdRestore(force = false) {
renderAll(db); renderAll(db);
} }
/** @param {?string} kind @param {?string} label @param {?string} [detail] @param {?string} [reason] */
function cmdFile(kind, label, detail, reason) { function cmdFile(kind, label, detail, reason) {
const db = openDb(); const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to file (see the run\'s settings.json)'); 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); dumpDb(db);
} }
/** @param {string} ridStr @param {?string} detail */
function cmdAmend(ridStr, detail) { function cmdAmend(ridStr, detail) {
const db = openDb(); const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records'); if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr); 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 (!row) fail(`no such record: ${ridStr}`);
if (!detail?.trim()) fail('usage: amend <rid> "new detail"'); 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 // saga rule: the journal keeps the prior detail, so turn surgery can
// compensate mechanically // compensate mechanically
journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended', row.detail); journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended', row.detail);
@@ -1050,13 +1149,14 @@ function cmdAmend(ridStr, detail) {
dumpDb(db); dumpDb(db);
} }
/** @param {string} ridStr @param {?string} [reason] */
function cmdDiscard(ridStr, reason) { function cmdDiscard(ridStr, reason) {
const db = openDb(); const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records'); if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr); 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 (!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 // saga rule: the whole discarded row is journaled -- a compensation
// can re-file it exactly (id included, so rid references stay valid) // can re-file it exactly (id included, so rid references stay valid)
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded', 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 // The GM overrides out-of-band with status-set. Descriptions never contain
// commas: both the delta lists and the <status> block are comma-separated. // 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 -- // split a list of descriptions, tolerating newlines and list bullets --
// covers the delta tags and a <status> block body alike // covers the delta tags and a <status> block body alike
/** @param {unknown} s @returns {string[]} */
const splitDescrs = (s) => const splitDescrs = (s) =>
String(s ?? '').split('\n').flatMap((line) => String(s ?? '').split('\n').flatMap((line) =>
line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean); line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean);
@@ -1085,13 +1187,14 @@ function cmdStatus() {
console.log(JSON.stringify(statusList(openDb()))); console.log(JSON.stringify(statusList(openDb())));
} }
/** @param {string} text */
function cmdStatusApply(text) { function cmdStatusApply(text) {
const db = openDb(); const db = openDb();
const lost = []; const lost = [];
const gained = []; 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(/<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])); 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) { if (!lost.length && !gained.length) {
console.log(JSON.stringify({ ...applied, status: statusList(db) })); console.log(JSON.stringify({ ...applied, status: statusList(db) }));
return; return;
@@ -1100,7 +1203,7 @@ function cmdStatusApply(text) {
db.exec('BEGIN'); db.exec('BEGIN');
try { try {
for (const item of lost) { 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) { if (row) {
db.prepare('DELETE FROM status WHERE id = ?').run(row.id); db.prepare('DELETE FROM status WHERE id = ?').run(row.id);
journal(db, win, 'status-drop', `p${row.id}`, 'delta', row.descr); 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 // whole-status replace (GM override); the journal keeps
// the full prior status so turn surgery can compensate mechanically // 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) { function setStatus(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean); const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = statusList(db); const prior = statusList(db);
@@ -1146,6 +1250,7 @@ function setStatus(db, items, reason, win) {
return clean; return clean;
} }
/** @param {string[]} items */
function cmdStatusSet(items) { function cmdStatusSet(items) {
const db = openDb(); const db = openDb();
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc'); 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 // 0-based indexes against the agenda as last rendered, adds are
// comma-separated. The GM overrides whole-list with agenda-set. // 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() { function cmdAgenda() {
console.log(JSON.stringify(agendaList(openDb()))); console.log(JSON.stringify(agendaList(openDb())));
} }
/** @param {string} text */
function cmdAgendaApply(text) { function cmdAgendaApply(text) {
const db = openDb(); const db = openDb();
const added = []; /** @type {string[]} */ const added = [];
const dropped = []; /** @type {string[]} */ const dropped = [];
const evicted = []; /** @type {string[]} */ const evicted = [];
const conflicts = []; /** @type {string[]} */ const conflicts = [];
const adds = []; /** @type {string[]} */ const adds = [];
for (const m of String(text ?? '').matchAll(/<add>([\s\S]*?)<\/add>/g)) adds.push(...splitDescrs(m[1])); 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)) { 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)); 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 // -> next block. Indexes resolve against the same snapshot, so a
// multi-drop never shifts under itself. // multi-drop never shifts under itself.
const snapshot = agendaList(db); const snapshot = agendaList(db);
const kill = []; /** @type {number[]} */ const kill = [];
for (const d of drops) { for (const d of drops) {
if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; } if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; }
const i = Number(d); const i = Number(d);
@@ -1205,7 +1312,7 @@ function cmdAgendaApply(text) {
} }
for (const i of [...new Set(kill)].sort((a, b) => b - a)) { for (const i of [...new Set(kill)].sort((a, b) => b - a)) {
const descr = snapshot[i]; 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); db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr); journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr);
dropped.push(descr); dropped.push(descr);
@@ -1225,7 +1332,7 @@ function cmdAgendaApply(text) {
// overflow: the bottom sinks off the list -- by design, not an error // overflow: the bottom sinks off the list -- by design, not an error
const over = agendaList(db); const over = agendaList(db);
for (let i = over.length - 1; i >= AGENDA_CAP; i--) { 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); db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)'); journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)');
evicted.push(over[i]); evicted.push(over[i]);
@@ -1242,6 +1349,7 @@ function cmdAgendaApply(text) {
// whole-list replace (GM override); the journal keeps the prior queue // whole-list replace (GM override); the journal keeps the prior queue
// so turn surgery can compensate mechanically (the saga rule) // 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) { function setAgenda(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean); const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = agendaList(db); const prior = agendaList(db);
@@ -1260,6 +1368,7 @@ function setAgenda(db, items, reason, win) {
return clean; return clean;
} }
/** @param {string[]} items */
function cmdAgendaSet(items) { function cmdAgendaSet(items) {
const db = openDb(); const db = openDb();
const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc'); const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc');
@@ -1268,38 +1377,41 @@ function cmdAgendaSet(items) {
dumpDb(db); dumpDb(db);
} }
/** @param {string[]} options */
function cmdPick(options) { function cmdPick(options) {
if (options.length < 2) fail('usage: pick "option one" "option two" [...]'); if (options.length < 2) fail('usage: pick "option one" "option two" [...]');
const choice = options[Math.floor(Math.random() * options.length)]; const choice = options[Math.floor(Math.random() * options.length)];
console.log(`picked: ${choice}`); console.log(`picked: ${choice}`);
} }
/** @param {string[]} terms */
function cmdSearch(terms) { function cmdSearch(terms) {
const db = openDb(); const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to consult'); if (!recordsEnabled()) fail('this character keeps no records -- nothing to consult');
if (!terms.length) fail('usage: search <terms...>'); if (!terms.length) fail('usage: search <terms...>');
const conds = terms.map(() => "(label || ' ' || detail) LIKE ?").join(' AND '); const conds = terms.map(() => "(label || ' ' || detail) LIKE ?").join(' AND ');
const params = terms.map((t) => `%${t}%`); 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; } 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}` : ''}`); 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`); 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') { function cmdUnarchive(ridStr, ring = 'b') {
const db = openDb(); const db = openDb();
const rid = parseRid(ridStr); 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 (!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 type = TYPES.includes(row.kind) ? row.kind : 'fact';
const res = db.prepare('INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)') 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); 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'); 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); renderAll(db);
dumpDb(db); dumpDb(db);
} }
@@ -1307,41 +1419,42 @@ function cmdUnarchive(ridStr, ring = 'b') {
function cmdReport() { function cmdReport() {
const db = openDb(); const db = openDb();
if (AS_JSON) { 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 = { const out = {
run: RUN, 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(), recordsEnabled: recordsEnabled(),
status: statusList(db), status: statusList(db),
agenda: agendaList(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: {}, rings: {},
sinking: {}, sinking: {},
}; };
for (const ring of ['a', 'b', 'cold']) { 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') { 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' '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)); console.log(JSON.stringify(out));
return; return;
} }
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`); 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}`); console.log(`records: ${nr}`);
const status = statusList(db); const status = statusList(db);
console.log(`status: ${status.length ? '' : '(a blank sheet)'}`); console.log(`status: ${status.length ? '' : '(a blank sheet)'}`);
for (const d of status) console.log(` - ${d}`); for (const d of status) console.log(` - ${d}`);
for (const ring of ['a', 'b', 'cold']) { 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'; const cap = CAPS[ring] ?? 'none';
console.log(`ring ${ring}: ${n} / ${cap}`); console.log(`ring ${ring}: ${n} / ${cap}`);
if (ring !== 'cold') { 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' '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}**`); 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 freeze ruling rides the dispatch: a mutating verb touches only
// the phases its rules allow (see PHASE_RULES) // 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) { switch (cmd) {
case 'packages': cmdPackages(); break; case 'packages': cmdPackages(); break;
+1 -1
View File
@@ -11,5 +11,5 @@
"lib": ["ES2022"], "lib": ["ES2022"],
"types": ["node"] "types": ["node"]
}, },
"include": ["server/**/*.mjs"] "include": ["server/**/*.mjs", "tool/**/*.mjs"]
} }
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true,
"useUnknownInCatchVariables": false,
"target": "ES2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["node"]
},
"include": ["web/**/*.mjs"]
}
+11 -2
View File
@@ -5,20 +5,27 @@
// embedded browser pane. Errors and notices land in the banner // embedded browser pane. Errors and notices land in the banner
// instead; destructive confirms are two-click armed (widgets.mjs). // instead; destructive confirms are two-click armed (widgets.mjs).
/** @typedef {import('../server/shapes.mjs').User} User */
import { $ } from './dom.mjs'; import { $ } from './dom.mjs';
// identity chrome: who is signed in. Signing in is permanent and // identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out // per-browser (the token lives in localStorage); there is no sign-out
// -- the lifecycle story is a roadmap extension point // -- the lifecycle story is a roadmap extension point
/** @param {?User} [me] */
export function setWho(me) { export function setWho(me) {
$('who').textContent = me ? `${me.name}${me.superuser ? ' \u00b7 op' : ''}` : ''; $('who').textContent = me ? `${me.name}${me.superuser ? ' \u00b7 op' : ''}` : '';
$('who').title = me?.id ?? ''; $('who').title = me?.id ?? '';
} }
/** @param {string} text */
export function setSessionInfo(text) { export function setSessionInfo(text) {
$('session-info').textContent = text; $('session-info').textContent = text;
} }
/** The run detail (GET /runs/:id) carries the meter's numbers; null
* is the router's "no run addressed" reset.
* @param {?{ context?: ?{ used?: ?number, pct?: ?number, contwin?: ?boolean } }} [detail] */
export function renderMeter(detail) { export function renderMeter(detail) {
const fill = $('context-fill'); const fill = $('context-fill');
const label = $('context-label'); const label = $('context-label');
@@ -34,18 +41,20 @@ export function renderMeter(detail) {
label.textContent = c.contwin ? `${pct}% -- close & housekeep past 85%` : ''; label.textContent = c.contwin ? `${pct}% -- close & housekeep past 85%` : '';
} }
/** @param {boolean} on @param {string} [text] */
export function setBusy(on, text = 'her turn...') { export function setBusy(on, text = 'her turn...') {
$('busy').hidden = !on; // model calls take their time -- say so $('busy').hidden = !on; // model calls take their time -- say so
if (on) $('busy').textContent = text; if (on) $('busy').textContent = text;
} }
let bannerTimer = null; /** @type {?ReturnType<typeof setTimeout>} */ let bannerTimer = null;
/** @param {string} text @param {string} [kind] */
export function banner(text, kind = 'error') { export function banner(text, kind = 'error') {
const b = $('banner'); const b = $('banner');
b.textContent = text; b.textContent = text;
b.className = kind; b.className = kind;
b.hidden = false; b.hidden = false;
clearTimeout(bannerTimer); clearTimeout(bannerTimer ?? undefined);
bannerTimer = setTimeout(() => { b.hidden = true; }, 10000); bannerTimer = setTimeout(() => { b.hidden = true; }, 10000);
} }
+8 -1
View File
@@ -4,16 +4,23 @@
// rejected token ends the session -- drop it and show the claim view; // rejected token ends the session -- drop it and show the claim view;
// every path leads there until a fresh one is claimed. // every path leads there until a fresh one is claimed.
/** @typedef {import('../server/shapes.mjs').HttpError} HttpError */
/** One api() call: method + body + the keepalive flag. */
/** @typedef {{ method?: string, body?: unknown, keepalive?: boolean }} ApiOpts */
import { logEvent } from './log.mjs'; import { logEvent } from './log.mjs';
import { state } from './state.mjs'; import { state } from './state.mjs';
import { render } from './router.mjs'; import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token'; const TOKEN_KEY = 'rp-token';
/** @returns {string} */
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } }; export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
/** @param {string} t */
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked -- the session just won't persist */ } }; export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked -- the session just won't persist */ } };
export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } }; export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
/** @param {string} path @param {ApiOpts} [opts] @returns {Promise<any>} */
export async function api(path, opts = {}) { export async function api(path, opts = {}) {
const started = performance.now(); const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`; const label = `${opts.method ?? 'GET'} ${path}`;
@@ -29,7 +36,7 @@ export async function api(path, opts = {}) {
}); });
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
if (!res.ok) { if (!res.ok) {
const e = new Error(data.error ?? `${res.status}`); const e = /** @type {HttpError} */ (new Error(data.error ?? `${res.status}`));
e.detail = data.detail; e.detail = data.detail;
e.status = res.status; e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms -- ${e.message}`); logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms -- ${e.message}`);
+5 -2
View File
@@ -1,8 +1,11 @@
// web/dom.mjs -- the two DOM helpers everything else builds on. // web/dom.mjs -- the two DOM helpers everything else builds on.
export const $ = (id) => document.getElementById(id); /** The id is static in index.html; a miss is a runtime crash by
* design (fail loud, never render a half-view). @param {string} id @returns {HTMLElement} */
export const $ = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
// one element, class and text in the common shape /** One element, class and text in the common shape.
* @param {string} tag @param {?string} [cls] @param {?string} [text] @returns {HTMLElement} */
export function el(tag, cls, text) { export function el(tag, cls, text) {
const e = document.createElement(tag); const e = document.createElement(tag);
if (cls) e.className = cls; if (cls) e.className = cls;
+2 -1
View File
@@ -8,9 +8,10 @@
import { $ } from './dom.mjs'; import { $ } from './dom.mjs';
const log = []; /** @type {string[]} */ const log = [];
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt -- start empty */ } try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt -- start empty */ }
/** @param {string} kind @param {string} text */
export function logEvent(kind, text) { export function logEvent(kind, text) {
log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`); log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
if (log.length > 300) log.splice(0, log.length - 300); if (log.length > 300) log.splice(0, log.length - 300);
+13
View File
@@ -12,9 +12,16 @@ import { state } from './state.mjs';
import { banner, hideBanner, renderMeter, setWho, setSessionInfo } from './chrome.mjs'; import { banner, hideBanner, renderMeter, setWho, setSessionInfo } from './chrome.mjs';
import { logEvent } from './log.mjs'; import { logEvent } from './log.mjs';
/** One registered view: its pane element id, its enter (arg = the
* path-captured run id), and its optional leave. */
/** @typedef {{ el: string, enter: (arg: ?string, seq: number) => void|Promise<void>, leave?: () => void }} ViewDef */
/** @type {Record<string, ViewDef>} */
const views = {}; const views = {};
/** @param {Record<string, ViewDef>} map */
export function registerViews(map) { Object.assign(views, map); } export function registerViews(map) { Object.assign(views, map); }
/** @param {string} p */
export function navigate(p) { export function navigate(p) {
history.pushState({}, '', p); history.pushState({}, '', p);
render(); render();
@@ -22,11 +29,14 @@ export function navigate(p) {
window.addEventListener('popstate', () => render()); window.addEventListener('popstate', () => render());
/** @returns {Promise<void>} */
export async function render() { export async function render() {
const seq = ++state.seq; const seq = ++state.seq;
hideBanner(); hideBanner();
const p = location.pathname; const p = location.pathname;
/** @type {?string} */
let name = null; let name = null;
/** @type {?string} */
let arg = null; let arg = null;
let m; let m;
if (p === '/') name = 'home'; if (p === '/') name = 'home';
@@ -35,10 +45,12 @@ export async function render() {
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; } else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; } else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
else return navigate('/'); else return navigate('/');
if (!name) return; // unreachable: the routing always names a view or navigates home
if (!state.me) name = 'claim'; // signed out: every path leads to the claim if (!state.me) name = 'claim'; // signed out: every path leads to the claim
await show(name, arg, seq); await show(name, arg, seq);
} }
/** @param {string} name @param {?string} arg @param {number} seq @returns {Promise<void>} */
async function show(name, arg, seq) { async function show(name, arg, seq) {
const prev = state.view; const prev = state.view;
if (prev && prev !== name && views[prev].leave) views[prev].leave(); if (prev && prev !== name && views[prev].leave) views[prev].leave();
@@ -53,6 +65,7 @@ async function show(name, arg, seq) {
// a run that vanished under us (deleted, 404): leave loudly for home. // a run that vanished under us (deleted, 404): leave loudly for home.
// render() clears the banner first -- set it after the navigate. // render() clears the banner first -- set it after the navigate.
/** @param {string} id @param {string} from */
export function runGone(id, from) { export function runGone(id, from) {
navigate('/'); navigate('/');
banner(`run ${id} is gone -- deleted?`); banner(`run ${id} is gone -- deleted?`);
+43
View File
@@ -0,0 +1,43 @@
// web/shapes.mjs -- the SPA's wire shapes: the REST responses the
// views consume. No runtime code: like server/shapes.mjs, this module
// exists so the tsc checker (JSDoc mode, no emit) and the humans
// reading the code agree on the load-bearing shapes. The server's own
// shared shapes (User, LogEvent, JobState, RunMeta) are imported from
// ../server/shapes.mjs at their use sites -- the API response
// envelopes live here because main.mjs's handlers build them as
// untyped literals; the smoke owns their behavioral truth.
export {};
/** One run card as GET /runs serves it (the clerk's listing,
* enriched by the server with the live-session state). fill is
* present exactly when the run is initialized. */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
/** GET /runs/:id -- the run detail: identity, the phase bookkeeping,
* her two blocks, the fill, the context meter's numbers. */
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, modelDefaults: { player?: ?string, housekeeper?: ?string } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
/** GET /runs/:id/table -- the live session's projection (thinking
* never crosses the wire, variant turns carry only the picked one). */
/** @typedef {{ run: string, session: number, entries: import('../server/shapes.mjs').LogEvent[], pendingAsk: ?string }} TableResponse */
/** GET /runs/:id/carryover -- the dormant session's opening material,
* projected like the table; ends decides the opening flow. */
/** @typedef {{ run: string, session: number, ready: boolean, entries: import('../server/shapes.mjs').LogEvent[], ends: ?('gm'|'player') }} CarryoverResponse */
/** GET /runs/:id/story -- the whole deliverable, read-only: every
* non-dropped literature turn, across all sessions in order. */
/** @typedef {{ run: string, sessions: { session: number, turns: { who: string, text: string }[] }[] }} StoryResponse */
/** GET /api/runs/:id/files -- the editor surface: a fixed whitelist,
* each file with its phase-truth mode. */
/** @typedef {{ session: number, phase: ?string, files: Record<string, { mode: string, exists: boolean, content?: string }> }} FilesResponse */
/** GET /api/prompts -- the repo-fed prompts, read-only context. */
/** @typedef {{ system: ?string, invariants: ?string, reminder: ?string }} PromptsResponse */
/** GET /api/runs/:id/notes -- the GM's notepad. */
/** @typedef {{ content: string }} NotesResponse */
/** GET /api/runs/:id/housekeeping/log -- the latest apply log. */
/** @typedef {{ content: string }} HousekeepingLogResponse */
+3
View File
@@ -6,6 +6,9 @@
// play both write here; saves address it). Everything else is // play both write here; saves address it). Everything else is
// module-local to the view or widget that owns it. // module-local to the view or widget that owns it.
/** @typedef {import('../server/shapes.mjs').User} User */
/** @type {{ view: ?string, seq: number, me: ?User, runId: ?string }} */
export const state = { export const state = {
view: null, // the active view name ('claim' | 'home' | ...) view: null, // the active view name ('claim' | 'home' | ...)
seq: 0, seq: 0,
+13 -2
View File
@@ -8,9 +8,15 @@
// delta tags on player turns are machinery, not prose -- they render // delta tags on player turns are machinery, not prose -- they render
// as chips and pane state, mirroring the live-context policy. // as chips and pane state, mirroring the live-context policy.
/** @typedef {import('../server/shapes.mjs').LogEvent} LogEvent */
/** @typedef {import('../server/shapes.mjs').BundleEvent} BundleEvent */
/** @typedef {import('../server/shapes.mjs').MsgEvent} MsgEvent */
/** @typedef {import('../server/shapes.mjs').NoteEvent} NoteEvent */
import { $, el } from './dom.mjs'; import { $, el } from './dom.mjs';
// splits text into spans: *italics* = narration, **bold** = emphasis // splits text into spans: *italics* = narration, **bold** = emphasis
/** @param {HTMLElement} target @param {string} text */
function renderSpans(target, text) { function renderSpans(target, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g); const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) { for (const p of parts) {
@@ -34,6 +40,7 @@ function renderSpans(target, text) {
// the riding blocks (status/conflict/agenda) out of GM prose; the // the riding blocks (status/conflict/agenda) out of GM prose; the
// delta tags on player turns always render as chips. Exported for // delta tags on player turns always render as chips. Exported for
// the story view, which renders the same registers. // the story view, which renders the same registers.
/** @param {HTMLElement} target @param {?string} text @param {{ extract?: boolean }} opts @returns {{ status: ?string, conflict: ?string, agenda: ?string }} */
export function renderContent(target, text, { extract }) { export function renderContent(target, text, { extract }) {
let body = String(text ?? ''); let body = String(text ?? '');
let status = null; let status = null;
@@ -128,10 +135,11 @@ export function renderContent(target, text, { extract }) {
// turn -- the play view owns where it lands (the status pane). The // turn -- the play view owns where it lands (the status pane). The
// opening event (her opening status) renders as machinery, mirroring // opening event (her opening status) renders as machinery, mirroring
// the wire policy: it is set once, never re-sent. // the wire policy: it is set once, never re-sent.
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void }} [opts] */
export function renderTranscript(entries, { onConflict } = {}) { export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript'); const t = $('transcript');
t.textContent = ''; t.textContent = '';
const bundleParts = []; /** @type {BundleEvent[]} */ const bundleParts = [];
const flushBundle = () => { const flushBundle = () => {
if (!bundleParts.length) return; if (!bundleParts.length) return;
const d = el('details', 'bundle'); const d = el('details', 'bundle');
@@ -158,7 +166,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
// the turn reminder: the transcript mirrors the live-context // the turn reminder: the transcript mirrors the live-context
// policy -- one collapsed card for the newest copy, superseded // policy -- one collapsed card for the newest copy, superseded
// ones elide (the log keeps every as-sent chunk) // ones elide (the log keeps every as-sent chunk)
const newest = [...entries].reverse().find((x) => x.reminder); const newest = [...entries].reverse().find((x) => x.t === 'msg' && x.reminder);
if (e === newest) { if (e === newest) {
const d = el('details', 'bundle'); const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder -- rides every GM turn')); d.appendChild(el('summary', null, 'turn reminder -- rides every GM turn'));
@@ -190,6 +198,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
flushBundle(); flushBundle();
t.scrollTop = t.scrollHeight; t.scrollTop = t.scrollHeight;
/** @param {?string} content @param {string} who */
function gmTurn(content, who) { function gmTurn(content, who) {
const d = el('div', 'turn gm'); const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who)); d.appendChild(el('div', 'who', who));
@@ -199,6 +208,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
if (conflict) onConflict?.(conflict); if (conflict) onConflict?.(conflict);
t.appendChild(d); t.appendChild(d);
} }
/** @param {MsgEvent} e */
function playerTurn(e) { function playerTurn(e) {
const d = el('div', 'turn player'); const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player')); d.appendChild(el('div', 'who', 'player'));
@@ -210,6 +220,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
} }
t.appendChild(d); t.appendChild(d);
} }
/** @param {NoteEvent} e */
function renderNote(e) { function renderNote(e) {
let text = null; let text = null;
if (e.kind === 'session') text = `session ${e.n} opened`; if (e.kind === 'session') text = `session ${e.n} opened`;
+5 -4
View File
@@ -9,22 +9,23 @@ import { banner } from './chrome.mjs';
import { logEvent } from './log.mjs'; import { logEvent } from './log.mjs';
import { navigate } from './router.mjs'; import { navigate } from './router.mjs';
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) { export async function enter(arg, seq) {
$('claim-code').value = ''; /** @type {HTMLInputElement} */ ($('claim-code')).value = '';
$('claim-name').value = ''; /** @type {HTMLInputElement} */ ($('claim-name')).value = '';
let fresh = false; let fresh = false;
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ } try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return; if (seq !== state.seq) return;
$('claim-hint').textContent = fresh $('claim-hint').textContent = fresh
? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server' ? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator'; : 'a single-use invite code, from the operator';
$('claim-code').focus(); /** @type {HTMLInputElement} */ ($('claim-code')).focus();
} }
$('claim-form').addEventListener('submit', async (e) => { $('claim-form').addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
const r = await api('/claim', { method: 'POST', body: { code: $('claim-code').value.trim(), name: $('claim-name').value.trim() } }); const r = await api('/claim', { method: 'POST', body: { code: /** @type {HTMLInputElement} */ ($('claim-code')).value.trim(), name: /** @type {HTMLInputElement} */ ($('claim-name')).value.trim() } });
setToken(r.token); setToken(r.token);
state.me = r.user; state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`); logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
+11 -2
View File
@@ -8,8 +8,11 @@ import { banner } from './chrome.mjs';
import { navigate, render } from './router.mjs'; import { navigate, render } from './router.mjs';
import { armedButton } from './widgets.mjs'; import { armedButton } from './widgets.mjs';
/** @typedef {import('./shapes.mjs').RunCard} RunCard */
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) { export async function enter(arg, seq) {
const runs = await api('/runs'); /** @type {RunCard[]} */ const runs = await api('/runs');
if (seq !== state.seq) return; if (seq !== state.seq) return;
const list = $('run-list'); const list = $('run-list');
list.textContent = ''; list.textContent = '';
@@ -17,7 +20,7 @@ export async function enter(arg, seq) {
list.appendChild(el('div', 'hint', 'no runs yet -- start one from a package')); list.appendChild(el('div', 'hint', 'no runs yet -- start one from a package'));
} }
for (const r of runs) { for (const r of runs) {
const mine = state.me && r.owner === state.me.id; const mine = !!(state.me && r.owner === state.me.id);
const card = el('button', 'card run-card'); const card = el('button', 'card run-card');
// the name carries the content facts plus the ownership garnish; // the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta -- chrome, never model-facing // started-or-forked rides the meta -- chrome, never model-facing
@@ -31,15 +34,18 @@ export async function enter(arg, seq) {
await renderAdmin(seq); await renderAdmin(seq);
} }
/** @param {RunCard} r @param {boolean} mine @returns {string} */
const ownershipTag = (r, mine) => const ownershipTag = (r, mine) =>
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`); (mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC" // all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
/** @param {number} t @returns {string} */
function fmtUnix(t) { function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString(); const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`; return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
} }
/** @param {RunCard} r @returns {string} */
function runStateText(r) { function runStateText(r) {
if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`; if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`;
if (r.phase === 'dormant') { if (r.phase === 'dormant') {
@@ -48,6 +54,7 @@ function runStateText(r) {
} }
return 'no sessions'; return 'no sessions';
} }
/** @param {RunCard} r @returns {string} */
function runStateClass(r) { function runStateClass(r) {
if (r.pendingAsk) return 'attention'; if (r.pendingAsk) return 'attention';
if (r.phase === 'live') return 'ok'; if (r.phase === 'live') return 'ok';
@@ -56,10 +63,12 @@ function runStateClass(r) {
return ''; return '';
} }
/** @param {number} seq @returns {Promise<void>} */
async function renderAdmin(seq) { async function renderAdmin(seq) {
const box = $('admin'); const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; } if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false; box.hidden = false;
/** @type {[{ invites: { id: number, kind: string, created_at: string, state: string }[] }, { users: import('../server/shapes.mjs').User[] }]} */
const [inv, us] = await Promise.all([api('/invites'), api('/users')]); const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return; if (seq !== state.seq) return;
const invList = $('invite-list'); const invList = $('invite-list');
+11 -8
View File
@@ -9,8 +9,9 @@ import { state } from './state.mjs';
import { banner } from './chrome.mjs'; import { banner } from './chrome.mjs';
import { navigate } from './router.mjs'; import { navigate } from './router.mjs';
let pkg = null; // the picked package -- the view owns it /** @type {?{ display: string, name: string }} */ let pkg = null; // the picked package -- the view owns it
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) { export async function enter(arg, seq) {
$('package-pick').hidden = false; $('package-pick').hidden = false;
$('create-form').hidden = true; $('create-form').hidden = true;
@@ -29,25 +30,27 @@ export async function enter(arg, seq) {
} }
} }
/** @param {{ display: string, name: string }} p */
async function pickPackage(p) { async function pickPackage(p) {
pkg = p; pkg = p;
$('package-pick').hidden = true; $('package-pick').hidden = true;
$('create-form').hidden = false; $('create-form').hidden = false;
$('create-title').textContent = `start -- ${p.display}`; $('create-title').textContent = `start -- ${p.display}`;
$('create-name').value = p.display; /** @type {HTMLInputElement} */ ($('create-name')).value = p.display;
$('create-pc').value = ''; const pcInp = /** @type {HTMLInputElement} */ ($('create-pc'));
$('create-pc').placeholder = 'rolling a name...'; pcInp.value = '';
$('create-pc').focus(); pcInp.placeholder = 'rolling a name...';
pcInp.focus();
const roll = await api('/names').catch(() => null); const roll = await api('/names').catch(() => null);
if (state.view !== 'new' || $('create-form').hidden) return; if (state.view !== 'new' || $('create-form').hidden) return;
if ($('create-pc').value === '' && roll?.name) $('create-pc').value = roll.name; if (pcInp.value === '' && roll?.name) pcInp.value = roll.name;
} }
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; }); $('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => { $('create-form').addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const name = $('create-name').value.trim(); const name = /** @type {HTMLInputElement} */ ($('create-name')).value.trim();
const pc = $('create-pc').value.trim(); const pc = /** @type {HTMLInputElement} */ ($('create-pc')).value.trim();
if (!name) return banner('the package needs a display name'); if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name'); if (!pc) return banner('the main character needs a name');
try { try {
+57 -34
View File
@@ -3,6 +3,13 @@
// instances), the GM notepad, housekeeping (close session, the // instances), the GM notepad, housekeeping (close session, the
// dry-run replay), fork, and the input line. // dry-run replay), fork, and the input line.
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').TableResponse} TableResponse */
/** @typedef {import('./shapes.mjs').CarryoverResponse} CarryoverResponse */
/** @typedef {import('./shapes.mjs').NotesResponse} NotesResponse */
/** @typedef {import('./shapes.mjs').HousekeepingLogResponse} HousekeepingLogResponse */
/** @typedef {import('../server/shapes.mjs').JobState} JobState */
import { $, el } from './dom.mjs'; import { $, el } from './dom.mjs';
import { api } from './client.mjs'; import { api } from './client.mjs';
import { state } from './state.mjs'; import { state } from './state.mjs';
@@ -49,23 +56,26 @@ const models = modelsBox('models-pane', { title: 'models' });
export function leave() { export function leave() {
saveNotes(); saveNotes();
stopPoll(); stopPoll();
$('ask-modal').close(); /** @type {HTMLDialogElement} */ ($('ask-modal')).close();
} }
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) { export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters play with a run id
statusPane.reset(); statusPane.reset();
agendaPane.reset(); agendaPane.reset();
$('conflict').hidden = true; $('conflict').hidden = true;
await saveNotes(); // flush the pad for the previous run before switching await saveNotes(); // flush the pad for the previous run before switching
state.runId = id; state.runId = id;
notesDirty = false; notesDirty = false;
$('gm-notes').value = ''; /** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = '';
$('notes-state').textContent = ''; $('notes-state').textContent = '';
await refreshPlay(id, seq); await refreshPlay(id, seq);
} }
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function refreshPlay(id, seq) { async function refreshPlay(id, seq) {
let detail; /** @type {RunDetail} */ let detail;
try { try {
detail = await api(`/runs/${id}`); detail = await api(`/runs/${id}`);
} catch (e) { } catch (e) {
@@ -73,7 +83,7 @@ async function refreshPlay(id, seq) {
return banner(`could not reach the server: ${e.message}`); // stay put -- transient return banner(`could not reach the server: ${e.message}`); // stay put -- transient
} }
if (seq !== state.seq) return; if (seq !== state.seq) return;
const mine = state.me && detail.run.owner === state.me.id; const mine = !!(state.me && detail.run.owner === state.me.id);
if (detail.draft) { if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`); if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence // someone else's unstarted run: nothing to read but its existence
@@ -96,19 +106,19 @@ async function refreshPlay(id, seq) {
// way in. Ownerless runs are spectators for everyone alike. // way in. Ownerless runs are spectators for everyone alike.
statusPane.setEditable(mine); statusPane.setEditable(mine);
agendaPane.setEditable(mine); agendaPane.setEditable(mine);
$('gm-notes').readOnly = !mine; /** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = !mine;
if (detail.phase === 'live') { if (detail.phase === 'live') {
// the table: the live session's projection -- thinking never // the table: the live session's projection -- thinking never
// crosses the wire, variant turns carry only the picked one (the // crosses the wire, variant turns carry only the picked one (the
// raw /session is the audit surface, one fetch away) // raw /session is the audit surface, one fetch away)
const session = await api(`/runs/${id}/table`); /** @type {TableResponse} */ const session = await api(`/runs/${id}/table`);
if (seq !== state.seq) return; if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict }); renderTranscript(session.entries, { onConflict: showConflict });
} else if (detail.phase === 'dormant') { } else if (detail.phase === 'dormant') {
// the review window: the carryover is the preview of the next // the review window: the carryover is the preview of the next
// contwin's opening, rendered exactly as the table will hold it // contwin's opening, rendered exactly as the table will hold it
const carry = await api(`/runs/${id}/carryover`).catch(() => null); /** @type {?CarryoverResponse} */ const carry = await api(`/runs/${id}/carryover`).catch(() => null);
if (seq !== state.seq) return; if (seq !== state.seq) return;
$('transcript').textContent = ''; $('transcript').textContent = '';
if (carry && carry.entries.length) renderTranscript(carry.entries, {}); if (carry && carry.entries.length) renderTranscript(carry.entries, {});
@@ -126,7 +136,7 @@ async function refreshPlay(id, seq) {
$('hk-replay').hidden = !((detail.phase === 'live') || (detail.phase === 'dormant' && detail.sessions >= 2)) || !mine; $('hk-replay').hidden = !((detail.phase === 'live') || (detail.phase === 'dormant' && detail.sessions >= 2)) || !mine;
$('hk-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false) || !mine; $('hk-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false) || !mine;
setInput(detail.phase === 'live' && !detail.pendingAsk && mine); setInput(detail.phase === 'live' && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine /** @type {HTMLInputElement} */ ($('gm-input')).placeholder = mine
? 'GM line -- Enter sends, Shift+Enter newlines' ? 'GM line -- Enter sends, Shift+Enter newlines'
: 'spectating -- fork this run to continue it as yours'; : 'spectating -- fork this run to continue it as yours';
@@ -142,14 +152,14 @@ async function refreshPlay(id, seq) {
// to answer; a spectator follows the thread in the transcript // to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) { if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk; $('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal(); /** @type {HTMLDialogElement} */ ($('ask-modal')).showModal();
$('ask-answer').focus(); /** @type {HTMLInputElement} */ ($('ask-answer')).focus();
} else { } else {
$('ask-modal').close(); /** @type {HTMLDialogElement} */ ($('ask-modal')).close();
} }
// housekeeping state // housekeeping state
const hk = await api(`/runs/${id}/housekeeping`); /** @type {JobState} */ const hk = await api(`/runs/${id}/housekeeping`);
if (seq !== state.seq) return; if (seq !== state.seq) return;
renderHk(hk); renderHk(hk);
@@ -159,6 +169,7 @@ async function refreshPlay(id, seq) {
// the dormant bar: the review window's banner over the carryover // the dormant bar: the review window's banner over the carryover
// preview, with the one button that leaves it // preview, with the one button that leaves it
/** @param {RunDetail} detail @param {?CarryoverResponse} carry @returns {HTMLElement} */
function dormantBar(detail, carry) { function dormantBar(detail, carry) {
const bar = el('div', 'beat'); const bar = el('div', 'beat');
const ending = carry?.ends === 'gm' const ending = carry?.ends === 'gm'
@@ -171,6 +182,7 @@ function dormantBar(detail, carry) {
return bar; return bar;
} }
/** @param {string} text */
function showConflict(text) { function showConflict(text) {
const c = $('conflict'); const c = $('conflict');
c.textContent = `conflict: ${text}`; c.textContent = `conflict: ${text}`;
@@ -183,26 +195,28 @@ function showConflict(text) {
// flushed when leaving the play view or switching runs. gm.md never // flushed when leaving the play view or switching runs. gm.md never
// reaches any model -- this is the GM's own notes. // reaches any model -- this is the GM's own notes.
let notesTimer = null; /** @type {?ReturnType<typeof setTimeout>} */ let notesTimer = null;
let notesDirty = false; let notesDirty = false;
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function loadNotes(id, seq) { async function loadNotes(id, seq) {
const notes = await api(`/runs/${id}/notes`).catch(() => null); /** @type {?NotesResponse} */ const notes = await api(`/runs/${id}/notes`).catch(() => null);
if (!notes || seq !== state.seq || notesDirty) return; if (!notes || seq !== state.seq || notesDirty) return;
$('gm-notes').value = notes.content; /** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = notes.content;
} }
function notesInput() { function notesInput() {
notesDirty = true; notesDirty = true;
$('notes-state').textContent = 'unsaved'; $('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer); clearTimeout(notesTimer ?? undefined);
notesTimer = setTimeout(saveNotes, 1000); notesTimer = setTimeout(saveNotes, 1000);
} }
/** @returns {Promise<void>} */
async function saveNotes() { async function saveNotes() {
clearTimeout(notesTimer); clearTimeout(notesTimer ?? undefined);
if (!notesDirty || !state.runId) return; if (!notesDirty || !state.runId) return;
const content = $('gm-notes').value; const content = /** @type {HTMLTextAreaElement} */ ($('gm-notes')).value;
try { try {
// keepalive: the flush must survive leaving the page entirely // keepalive: the flush must survive leaving the page entirely
await api(`/runs/${state.runId}/notes`, { method: 'PUT', body: { content }, keepalive: true }); await api(`/runs/${state.runId}/notes`, { method: 'PUT', body: { content }, keepalive: true });
@@ -216,13 +230,14 @@ async function saveNotes() {
// start: the dormant session goes live. If the carryover ends on a GM // start: the dormant session goes live. If the carryover ends on a GM
// turn, the server sends it automatically as her cue. // turn, the server sends it automatically as her cue.
/** @returns {Promise<void>} */
async function startRun() { async function startRun() {
const override = $('hk-override').checked; const override = /** @type {HTMLInputElement} */ ($('hk-override')).checked;
hideBanner(); hideBanner();
setBusy(true, 'starting...'); setBusy(true, 'starting...');
try { try {
const r = await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } }); const r = await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
$('hk-override').checked = false; /** @type {HTMLInputElement} */ ($('hk-override')).checked = false;
if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue'); if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue');
} catch (e) { } catch (e) {
if (e.status === 409 && e.detail?.hint) { if (e.status === 409 && e.detail?.hint) {
@@ -237,12 +252,14 @@ async function startRun() {
render(); render();
} }
/** @param {string} stateText @param {?string} [cls] */
function setHk(stateText, cls) { function setHk(stateText, cls) {
const h = $('hk-state'); const h = $('hk-state');
h.textContent = stateText; h.textContent = stateText;
h.className = cls ?? ''; h.className = cls ?? '';
} }
/** @param {JobState} hk */
function renderHk(hk) { function renderHk(hk) {
if (hk.state === 'running') { if (hk.state === 'running') {
setHk(hk.phase === 'rerun' ? 're-running housekeeping...' : 'stopping & housekeeping...', ''); setHk(hk.phase === 'rerun' ? 're-running housekeeping...' : 'stopping & housekeeping...', '');
@@ -262,39 +279,42 @@ function renderHk(hk) {
} }
} }
/** @param {boolean} ok */
function setInput(ok) { function setInput(ok) {
$('gm-input').disabled = !ok; /** @type {HTMLInputElement} */ ($('gm-input')).disabled = !ok;
$('gm-send').disabled = !ok; /** @type {HTMLButtonElement} */ ($('gm-send')).disabled = !ok;
} }
// --- actions ----------------------------------------------------------- // --- actions -----------------------------------------------------------
/** @returns {Promise<void>} */
async function sendTurn() { async function sendTurn() {
const line = $('gm-input').value.trim(); const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim();
if (!line || !state.runId) return; if (!line || !state.runId) return;
$('gm-input').value = ''; /** @type {HTMLInputElement} */ ($('gm-input')).value = '';
setInput(false); setInput(false);
setBusy(true); setBusy(true);
try { try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } }); await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
} catch (e) { } catch (e) {
banner(e.message); banner(e.message);
$('gm-input').value = line; // a failed send must not eat the line /** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
} }
setBusy(false); setBusy(false);
render(); render();
} }
/** @returns {Promise<void>} */
async function sendAnswer() { async function sendAnswer() {
const answer = $('ask-answer').value.trim(); const answer = /** @type {HTMLInputElement} */ ($('ask-answer')).value.trim();
if (!answer || !state.runId) return; if (!answer || !state.runId) return;
$('ask-answer').value = ''; /** @type {HTMLInputElement} */ ($('ask-answer')).value = '';
setBusy(true); setBusy(true);
try { try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } }); await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) { } catch (e) {
banner(e.message); banner(e.message);
$('ask-answer').value = answer; /** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
} }
setBusy(false); setBusy(false);
render(); render();
@@ -302,6 +322,7 @@ async function sendAnswer() {
// fork: a copy of this run under you -- any run, anyone's, including // fork: a copy of this run under you -- any run, anyone's, including
// yours. Lands you in the fork. // yours. Lands you in the fork.
/** @returns {Promise<void>} */
async function forkRun() { async function forkRun() {
if (!state.runId) return; if (!state.runId) return;
setBusy(true, 'forking...'); setBusy(true, 'forking...');
@@ -318,6 +339,7 @@ async function forkRun() {
// dry-run: the housekeeper reads the session log, the manifest lands // dry-run: the housekeeper reads the session log, the manifest lands
// in the pane -- nothing applied, the session stays open // in the pane -- nothing applied, the session stays open
/** @returns {Promise<void>} */
async function replayHousekeeping() { async function replayHousekeeping() {
setBusy(true, 'the housekeeper reads...'); setBusy(true, 'the housekeeper reads...');
try { try {
@@ -325,8 +347,8 @@ async function replayHousekeeping() {
$('hk-replay-content').textContent = r.parsed $('hk-replay-content').textContent = r.parsed
? JSON.stringify(r.manifest, null, 2) ? JSON.stringify(r.manifest, null, 2)
: `${r.reason}\n\nraw output: ${r.file}`; : `${r.reason}\n\nraw output: ${r.file}`;
$('hk-replay-log').hidden = false; /** @type {HTMLDetailsElement} */ ($('hk-replay-log')).hidden = false;
$('hk-replay-log').open = true; /** @type {HTMLDetailsElement} */ ($('hk-replay-log')).open = true;
} catch (e) { } catch (e) {
banner(e.message); banner(e.message);
} }
@@ -335,7 +357,7 @@ async function replayHousekeeping() {
// --- housekeeping poll + log ------------------------------------------- // --- housekeeping poll + log -------------------------------------------
let poll = null; /** @type {?ReturnType<typeof setInterval>} */ let poll = null;
function startPoll() { function startPoll() {
stopPoll(); stopPoll();
@@ -350,12 +372,13 @@ function stopPoll() {
poll = null; poll = null;
} }
/** @returns {Promise<void>} */
async function loadLog() { async function loadLog() {
try { try {
const log = await api(`/runs/${state.runId}/housekeeping/log`); /** @type {HousekeepingLogResponse} */ const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content; $('hk-log-content').textContent = log.content;
$('hk-log').hidden = false; /** @type {HTMLDetailsElement} */ ($('hk-log')).hidden = false;
$('hk-log').open = true; /** @type {HTMLDetailsElement} */ ($('hk-log')).open = true;
} catch { } catch {
$('hk-log').hidden = true; $('hk-log').hidden = true;
} }
+47 -30
View File
@@ -5,6 +5,10 @@
// it) or start (the dormant session goes live; a carryover ending on // it) or start (the dormant session goes live; a carryover ending on
// a GM turn sends automatically as her cue). // a GM turn sends automatically as her cue).
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').FilesResponse} FilesResponse */
/** @typedef {import('./shapes.mjs').PromptsResponse} PromptsResponse */
import { $, el } from './dom.mjs'; import { $, el } from './dom.mjs';
import { api } from './client.mjs'; import { api } from './client.mjs';
import { state } from './state.mjs'; import { state } from './state.mjs';
@@ -32,19 +36,23 @@ const EDIT_LIST = [
]; ];
// the editor's working set -- module-local, reset on every enter // the editor's working set -- module-local, reset on every enter
let files = null; // { name: { content, exists } } /** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
let drafts = {}; // unsaved edits by file name /** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
let currentFile = null; /** @type {?string} */ let currentFile = null;
let fileSpecs = {}; /** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
let repoPrompts = {}; /** @type {Record<string, string>} */ let repoPrompts = {};
const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' }); const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' });
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) { export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id; state.runId = id;
drafts = {}; drafts = {};
currentFile = null; currentFile = null;
let detail, filesResp, prompts; /** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts;
try { try {
[detail, filesResp, prompts] = await Promise.all([ [detail, filesResp, prompts] = await Promise.all([
api(`/runs/${id}`), api(`/runs/${id}`),
@@ -57,7 +65,7 @@ export async function enter(id, seq) {
} }
if (seq !== state.seq) return; if (seq !== state.seq) return;
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only -- fork to edit if (!state.me || detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only -- fork to edit (the router guarantees signed-in)
files = filesResp.files; files = filesResp.files;
repoPrompts = { repoPrompts = {
@@ -69,7 +77,7 @@ export async function enter(id, seq) {
$('setup-state').textContent = detail.draft $('setup-state').textContent = detail.draft
? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts` ? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts`
: `${detail.run.package} \u00b7 ${id} -- session ${detail.sessions} dormant, the review window`; : `${detail.run.package} \u00b7 ${id} -- session ${detail.sessions} dormant, the review window`;
$('setup-start').disabled = false; /** @type {HTMLButtonElement} */ ($('setup-start')).disabled = false;
$('setup-start').textContent = `start session ${detail.sessions}`; $('setup-start').textContent = `start session ${detail.sessions}`;
// draft-only affordances: deletion and save-as-package (a package is // draft-only affordances: deletion and save-as-package (a package is
// a starting point, never a snapshot) // a starting point, never a snapshot)
@@ -78,7 +86,7 @@ export async function enter(id, seq) {
// prompt vars: the $TOKENS the prompts declare, filled per run // prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, files); const vars = scanVars(prompts, files);
let currentVars = {}; /** @type {Record<string, string>} */ let currentVars = {};
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ } try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ }
const varsList = $('setup-vars-list'); const varsList = $('setup-vars-list');
varsList.textContent = ''; varsList.textContent = '';
@@ -86,7 +94,7 @@ export async function enter(id, seq) {
$('setup-vars-state').textContent = ''; $('setup-vars-state').textContent = '';
for (const tok of vars) { for (const tok of vars) {
const row = el('label', 'field', `$${tok}`); const row = el('label', 'field', `$${tok}`);
const inp = el('input'); const inp = /** @type {HTMLInputElement} */ (el('input'));
inp.dataset.token = tok; inp.dataset.token = tok;
inp.value = currentVars[tok] ?? ''; inp.value = currentVars[tok] ?? '';
row.appendChild(inp); row.appendChild(inp);
@@ -120,13 +128,14 @@ export async function enter(id, seq) {
} }
selectFile('system.md'); // how the model is prompted, first thing selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = ''; $('savepkg-state').textContent = '';
$('savepkg-name').value = ''; /** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} }
// the prompts declare their own inputs: every $TOKEN in any prompt // the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or the session's own, the carryover included -- it // file (repo-fed or the session's own, the carryover included -- it
// expands at start like every authored surface) becomes a fillable // expands at start like every authored surface) becomes a fillable
// input in setup // input in setup
/** @param {PromptsResponse} prompts @param {Record<string, { content?: string }>} files @returns {string[]} */
function scanVars(prompts, files) { function scanVars(prompts, files) {
const texts = [ const texts = [
prompts.system, prompts.invariants, prompts.reminder, prompts.system, prompts.invariants, prompts.reminder,
@@ -141,12 +150,14 @@ function scanVars(prompts, files) {
return [...found].sort(); return [...found].sort();
} }
/** @returns {Record<string, string>} */
function collectVars() { function collectVars() {
const vars = {}; /** @type {Record<string, string>} */ const vars = {};
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim(); for (const inp of /** @type {NodeListOf<HTMLInputElement>} */ ($('setup-vars-list').querySelectorAll('input'))) vars[/** @type {string} */ (inp.dataset.token)] = inp.value.trim();
return vars; return vars;
} }
/** @returns {Promise<void>} */
async function saveVars() { async function saveVars() {
const vars = collectVars(); const vars = collectVars();
if (!Object.keys(vars).length) return; if (!Object.keys(vars).length) return;
@@ -154,6 +165,7 @@ async function saveVars() {
$('setup-vars-state').textContent = 'saved'; $('setup-vars-state').textContent = 'saved';
} }
/** @param {string} f */
function selectFile(f) { function selectFile(f) {
const prev = currentFile; const prev = currentFile;
if (prev === f) return; if (prev === f) return;
@@ -163,8 +175,8 @@ function selectFile(f) {
const content = spec.source === 'repo' const content = spec.source === 'repo'
? (repoPrompts[f] ?? '') ? (repoPrompts[f] ?? '')
: (drafts[f] ?? spec.content ?? ''); : (drafts[f] ?? spec.content ?? '');
$('setup-edit').value = content; /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value = content;
$('setup-edit').disabled = spec.mode !== 'rw'; /** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw'; $('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only'; $('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
renderHighlight(); renderHighlight();
@@ -177,9 +189,9 @@ function selectFile(f) {
const SIGIL_RE = /@(PC|Package)\b/g; const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g; const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() { function renderHighlight() {
const ta = $('setup-edit'); const ta = /** @type {HTMLTextAreaElement} */ ($('setup-edit'));
const hl = $('edit-hl'); const hl = $('edit-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c])); const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
hl.innerHTML = esc hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>') .replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>') .replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
@@ -188,9 +200,10 @@ function renderHighlight() {
hl.scrollLeft = ta.scrollLeft; hl.scrollLeft = ta.scrollLeft;
} }
/** @param {string} f */
function stashDraft(f) { function stashDraft(f) {
if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
const v = $('setup-edit').value; const v = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; } if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v; drafts[f] = v;
markNav(); markNav();
@@ -199,23 +212,24 @@ function stashDraft(f) {
function markNav() { function markNav() {
const items = $('setup-files').children; const items = $('setup-files').children;
for (const item of items) { for (const item of items) {
const name = item.querySelector('.file-name').textContent.replace(' (new)', ''); const name = (/** @type {HTMLElement} */ (item.querySelector('.file-name'))).textContent.replace(' (new)', '');
const dirty = drafts[name] !== undefined; const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty); item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the // the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15) // rendered text must match the source (house rule, 2026-11-15)
item.querySelector('.file-dirty').textContent = dirty ? '*' : ''; (/** @type {HTMLElement} */ (item.querySelector('.file-dirty'))).textContent = dirty ? '*' : '';
item.classList.toggle('current', name === currentFile); item.classList.toggle('current', name === currentFile);
} }
} }
/** @returns {Promise<void>} */
async function saveFile() { async function saveFile() {
const f = currentFile; const f = currentFile;
if (!f) return; if (!f) return;
$('setup-save').disabled = true; /** @type {HTMLButtonElement} */ ($('setup-save')).disabled = true;
try { try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } }); await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value } });
files[f].content = $('setup-edit').value; files[f].content = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
files[f].exists = true; files[f].exists = true;
delete drafts[f]; delete drafts[f];
$('setup-edit-state').textContent = 'saved'; $('setup-edit-state').textContent = 'saved';
@@ -224,11 +238,12 @@ async function saveFile() {
banner(e.message); banner(e.message);
$('setup-edit-state').textContent = 'not saved'; $('setup-edit-state').textContent = 'not saved';
} }
$('setup-save').disabled = false; /** @type {HTMLButtonElement} */ ($('setup-save')).disabled = false;
} }
/** @returns {Promise<void>} */
async function saveDirty() { async function saveDirty() {
stashDraft(currentFile); if (currentFile != null) stashDraft(currentFile); // unreachable guard: enter always selects a file first
for (const [f, content] of Object.entries({ ...drafts })) { for (const [f, content] of Object.entries({ ...drafts })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } }); await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
files[f].content = content; files[f].content = content;
@@ -241,26 +256,28 @@ async function saveDirty() {
// save the run's craft as a new user package -- published to every user // save the run's craft as a new user package -- published to every user
// of the deployment, gm.md included. Saves what the run has saved: // of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision. // drafts flush first. The display name is the save's one decision.
/** @returns {Promise<void>} */
async function saveAsPackage() { async function saveAsPackage() {
const name = $('savepkg-name').value.trim(); const name = /** @type {HTMLInputElement} */ ($('savepkg-name')).value.trim();
if (!name) return banner('the package needs a display name'); if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true; /** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true;
$('savepkg-state').textContent = 'saving...'; $('savepkg-state').textContent = 'saving...';
try { try {
await saveDirty(); await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } }); const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved -- ${r.package.id}`; $('savepkg-state').textContent = `saved -- ${r.package.id}`;
$('savepkg-name').value = ''; /** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} catch (e) { } catch (e) {
banner(e.message); banner(e.message);
$('savepkg-state').textContent = 'not saved'; $('savepkg-state').textContent = 'not saved';
} }
$('savepkg-btn').disabled = false; /** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = false;
} }
/** @returns {Promise<void>} */
async function startRun() { async function startRun() {
const id = state.runId; const id = state.runId;
const btn = $('setup-start'); const btn = /** @type {HTMLButtonElement} */ ($('setup-start'));
// the prompts' own inputs must be filled -- the guard at start is // the prompts' own inputs must be filled -- the guard at start is
// the backstop, not the first line of defense // the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) { for (const [tok, v] of Object.entries(collectVars())) {
+8 -3
View File
@@ -15,11 +15,16 @@ import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs'; import { navigate, runGone } from './router.mjs';
import { renderContent } from './transcript.mjs'; import { renderContent } from './transcript.mjs';
let storyRun = null; /** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').StoryResponse} StoryResponse */
/** @type {?string} */ let storyRun = null;
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) { export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters the story with a run id
storyRun = id; storyRun = id;
let detail; /** @type {RunDetail} */ let detail;
try { try {
detail = await api(`/runs/${id}`); detail = await api(`/runs/${id}`);
} catch (e) { } catch (e) {
@@ -28,7 +33,7 @@ export async function enter(id, seq) {
} }
if (seq !== state.seq) return; if (seq !== state.seq) return;
$('story-title').textContent = `${detail.display} -- the story`; $('story-title').textContent = `${detail.display} -- the story`;
const story = await api(`/runs/${id}/story`).catch(() => null); /** @type {?StoryResponse} */ const story = await api(`/runs/${id}/story`).catch(() => null);
if (seq !== state.seq) return; if (seq !== state.seq) return;
if (!story) return banner('the story could not be read'); if (!story) return banner('the story could not be read');
const box = $('story'); const box = $('story');
+18 -9
View File
@@ -16,8 +16,9 @@ import { render } from './router.mjs';
// two-click confirm -- the second click within 5s fires; anything // two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state. // else disarms. Each button owns its own arm state.
/** @param {HTMLElement} btn @param {{ label: string, confirm: string, fire: () => Promise<void> }} opts */
export function armedButton(btn, { label, confirm, fire }) { export function armedButton(btn, { label, confirm, fire }) {
let timer = null; /** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
btn.addEventListener('click', async () => { btn.addEventListener('click', async () => {
if (timer === null) { if (timer === null) {
btn.textContent = confirm; btn.textContent = confirm;
@@ -35,14 +36,17 @@ export function armedButton(btn, { label, confirm, fire }) {
// resolves on success and throws on failure -- a failed save keeps // resolves on success and throws on failure -- a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the // the editor open, nothing was changed. setEditable(false) is the
// spectator state: no edit button, an open editor cancels. // spectator state: no edit button, an open editor cancels.
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[], save: (items: string[]) => Promise<unknown> }} PaneOpts */
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[] }} Pane */
/** @param {PaneOpts} opts @returns {Pane} */
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) { export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
const sec = typeof section === 'string' ? $(section) : section; const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body; const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit'); const editBtn = el('button', null, 'edit');
sec.querySelector('.pane-head').appendChild(editBtn); (/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn);
const editor = el('div', 'pane-editor'); const editor = el('div', 'pane-editor');
editor.hidden = true; editor.hidden = true;
const area = el('textarea'); const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = rows; area.rows = rows;
area.placeholder = placeholder; area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions'); const actions = el('div', 'pane-editor-actions');
@@ -54,7 +58,7 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
editor.appendChild(actions); editor.appendChild(actions);
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane) bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
let items = []; /** @type {string[]} */ let items = [];
let mayEdit = false; let mayEdit = false;
let open = false; let open = false;
@@ -102,19 +106,22 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
// the upstream model listing, fetched once per session -- a live // the upstream model listing, fetched once per session -- a live
// /models call every render would hammer the endpoint for a list // /models call every render would hammer the endpoint for a list
// that rarely changes // that rarely changes
let cachedModels = null; /** @type {?string[]} */ let cachedModels = null;
/** @returns {Promise<string[]>} */
export async function modelList() { export async function modelList() {
if (!cachedModels) cachedModels = await api('/models').catch(() => []); if (!cachedModels) cachedModels = /** @type {string[]} */ (await api('/models').catch(() => []));
return cachedModels; return cachedModels;
} }
// A select's "" value means "deployment default"; a current override // A select's "" value means "deployment default"; a current override
// missing from the listing stays selectable, so a stale pick never // missing from the listing stays selectable, so a stale pick never
// silently rewrites itself. // silently rewrites itself.
/** @param {HTMLSelectElement} sel @param {?string} current @param {string[]} list @param {?string} [def] */
function fillSelect(sel, current, list, def) { function fillSelect(sel, current, list, def) {
sel.textContent = ''; sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => { const mk = (v, label) => {
const o = el('option', null, label); const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v; o.value = v;
sel.appendChild(o); sel.appendChild(o);
}; };
@@ -127,12 +134,13 @@ function fillSelect(sel, current, list, def) {
// the models box: player/housekeeper selects + save, posting the // the models box: player/housekeeper selects + save, posting the
// per-run overrides. The mount keeps its id -- the CSS panels it. // per-run overrides. The mount keeps its id -- the CSS panels it.
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
export function modelsBox(mount, { title }) { export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount; const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = ''; root.textContent = '';
root.appendChild(el('h2', null, title)); root.appendChild(el('h2', null, title));
const playerSel = el('select'); const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = el('select'); const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player '); const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel); pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper '); const hField = el('label', 'field', 'housekeeper ');
@@ -158,6 +166,7 @@ export function modelsBox(mount, { title }) {
} }
}); });
return { return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {string[]} list */
fill(models, defaults, list) { fill(models, defaults, list) {
fillSelect(playerSel, models?.player ?? null, list, defaults?.player); fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper); fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);