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.
- The test scripts: `smoke.mjs` expects a CLEAN state/ plus a running
`--mock` server, prints its run ids, and leaves a temp token file
for `restart-check.mjs`; `check-reminder.mjs` takes a run id;
`check-repo.mjs` needs no server. Clean up state/ and the smoke
runs afterwards -- only the real runs stay. The type gate:
`npm.cmd run typecheck` (plain `npx.cmd tsc -p tsconfig.json`)
runs tsc as a no-emit checker over the JSDoc annotations --
dev-only tooling (typescript + @types/node in devDependencies,
node_modules gitignored); the runtime stays zero-dependency
(QUESTIONS #4 amended 2026-11-15). Server core is typed under
strict; the clerk (tool/memory.mjs) and web/ are phases to come --
widen tsconfig include as they land.
for `restart-check.mjs`; `check-reminder.mjs` takes a run id --
one whose NEWEST LOGGED session has GM turns (post-smoke that is
the fork lineage, e.g. the refork id in the token file; the source
run's newest logged session is the near-empty session 4, and
aiming it there fails on 0 reminders -- learned 2026-11-15);
`check-repo.mjs` needs no server. The smoke cannot run twice --
the second run dies on the dirty state (learned 2026-11-15): stop
the server, Remove-Item state/ and runs/, restart, run once. Clean
up state/ and the smoke runs afterwards -- only the real runs
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
@@ -204,16 +223,23 @@ memory the agent owes itself across sessions.
RESOLVED BY PLAN (2026-11-15): the dormant-session rework kills
the autorestart, and during dormancy the latest log IS the
just-closed session; the replay default never needed to move.
- Active work: the entity round, the variant round, and the
dormant-session rework are BUILT (2026-11-15, uncommitted, awaiting
the GM's eye). **The rework is now SMOKE-PROVEN end to end
(2026-11-15, evening): smoke 105/105, restart-check, check-reminder,
check-repo, and a full browser pass, all green; test state cleaned.
The Irene hand-migration is DONE the same sitting (fork proven end
to end, then real her mutated identically, reads green, zero writes
to her log -- see HANDOFF "Where we are"). Next: the op's one-time
first start under multiuser (HANDOFF step 2), then the first real
housekeeping pass (step 3).** Plan of record:
- Active work: the JSDoc typing round is COMPLETE (2026-11-15,
evening) -- all four phases. Phases 1-2 (the server core) are
committed (`f81b188`); phases 3 (the clerk) and 4 (web/, via the
second tsconfig) are done and land with this commit -- typecheck
green on both programs, smoke 110/110, restart-check on a genuine
restart, check-reminder, check-repo, and a full zero-console-error
browser pass over the SPA; test state cleaned. The audit lists of
non-annotation deltas live in HANDOFF ("Where we are"). Working
lessons from the rounds: in checkJs a JSDoc typedef sharing a
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
are"). En-route fix flagged to the GM: the roll retirement had
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
- **The server core is JSDoc-typed, strict, green (2026-11-15,
evening) -- committed.** tsc runs as a
no-emit checker (`npm run typecheck`) over plain `.mjs` with JSDoc
annotations; the shared shapes live in `server/shapes.mjs` (log
events as a tagged union, wire messages, manifests, job state,
the Ctx). Dev tooling only: `typescript` + `@types/node` in
- **The typing round is COMPLETE: all four phases (2026-11-15).**
Phases 1-2 (the server core) are committed (`f81b188`); phases 3
(the clerk) and 4 (web/) are done the same sitting and land with
this commit. tsc runs as a no-emit checker (`npm run typecheck`) over
plain `.mjs` with JSDoc annotations; the shared shapes live 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
zero-dependency (QUESTIONS #4 amended to say so). Verified: the
full diff audited change-by-change (every non-annotation delta is
an impossible-path guard or a behavior-identical wrap), smoke
105/105, restart-check, check-repo, all green. Phases to come are
steps 5 and 6 below.
zero-dependency (QUESTIONS #4 amended to say so).
- The clerk round: every `.get()`/`.all()` cast at the db
boundary, `fail` annotated `@returns {never}` so guard-narrowing
works, tsconfig's include widened to `tool/`. Non-annotation
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`,
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
that should be character), and whether her variants stay same-turn
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)
+1 -1
View File
@@ -3,7 +3,7 @@
"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.",
"scripts": {
"typecheck": "tsc -p tsconfig.json"
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.web.json"
},
"devDependencies": {
"@types/node": "^22.10.0",
+1 -1
View File
@@ -69,7 +69,7 @@ export {};
/** A housekeeping manifest -- the housekeeper's whole write surface. */
/** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */
/** @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 {{ 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
/** @typedef {import('../server/shapes.mjs').Manifest} Manifest */
/** @typedef {import('../server/shapes.mjs').InsertOp} InsertOp */
/** @typedef {import('../server/shapes.mjs').RefOp} RefOp */
/** @typedef {import('../server/shapes.mjs').RewordOp} RewordOp */
/** @typedef {import('../server/shapes.mjs').RunMeta} RunMeta */
/** @typedef {import('../server/shapes.mjs').RunSettings} RunSettings */
/** An entries table row ('cold' is storage, beyond the models' sight). */
/** @typedef {{ id: number, ring: 'a'|'b'|'cold', type: 'place'|'person'|'fact'|'thread', label: string, detail: string, created: string, last_touched: string }} EntryRow */
/** A records table row. */
/** @typedef {{ id: number, kind: string, label: string, detail: string, created: string }} RecordRow */
/** A status table row. */
/** @typedef {{ id: number, descr: string, added: string }} StatusRow */
/** An agenda table row. */
/** @typedef {{ id: number, descr: string, added: string }} AgendaRow */
/** An events table row: the append-only journal, never updated or deleted. */
/** @typedef {{ id: number, session: string, op: string, target: string, reason: string, prior: string }} EventRow */
/** session.json as buildSession1 / the server write it. */
/** @typedef {{ phase?: string, ready?: boolean, [k: string]: unknown }} SessionMeta */
/** One package as `packages` lists it. */
/** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */
/** One run as `runs` lists it (fill is present exactly when initialized). */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */
/** The apply log's record of what a manifest did. */
/** @typedef {{ id: number } & InsertOp} AppliedInsert */
/** @typedef {{ row: EntryRow, reason: string }} AppliedRef */
/** @typedef {{ row: EntryRow, detail: string, reason: string }} AppliedReword */
/** @typedef {{ rid: number, row: EntryRow, reason: string }} AppliedArchive */
/** @typedef {{ insert: AppliedInsert[], touch: AppliedRef[], promote: AppliedRef[], demote: AppliedRef[], reword: AppliedReword[], delete: AppliedRef[], archive: AppliedArchive[] }} AppliedLog */
/** One automatic overflow move (ring a spills to b, ring b to cold). */
/** @typedef {{ id: number, from: string, to: string }} OverflowItem */
import { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
@@ -74,23 +110,28 @@ const STATE_PACKAGES_DIR = path.join(ROOT, 'state', 'packages');
const RUNS_DIR = path.join(ROOT, 'runs');
// dials -- retune freely
/** @type {Record<string, number>} */
const CAPS = { a: 500, b: 3000 };
const AGENDA_CAP = 5; // dial -- retune freely (invariants.md: "intentionally tiny")
const TYPES = ['place', 'person', 'fact', 'thread'];
const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models
/** @param {string} msg @returns {never} */
const fail = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
/** @param {string} p @returns {string} */
const rel = (p) => path.relative(ROOT, p).replaceAll('\\', '/');
// flags: --run <name> beats everything; --gm attributes the op to the GM
const argv = process.argv.slice(2);
const runIdx = argv.indexOf('--run');
/** @type {?string} */
let runOverride = null;
if (runIdx !== -1) {
runOverride = argv[runIdx + 1] ?? null;
argv.splice(runIdx, 2);
}
const sessionIdx = argv.indexOf('--session');
/** @type {?number} */
let sessionOverride = null;
if (sessionIdx !== -1) {
sessionOverride = Number(argv[sessionIdx + 1]);
@@ -108,6 +149,7 @@ for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) arg
const AS_JSON = argv.includes('--json');
for (let i = argv.indexOf('--json'); i !== -1; i = argv.indexOf('--json')) argv.splice(i, 1);
const ownerIdx = argv.indexOf('--owner');
/** @type {?string} */
let ownerOverride = null;
if (ownerIdx !== -1) {
ownerOverride = argv[ownerIdx + 1] ?? null;
@@ -118,14 +160,21 @@ const [cmd, ...args] = argv;
// a run is an instance under runs/, created from a package by `create`;
// state is per-deployment -- a fresh clone has zero runs
const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']);
const RUN = NO_RUN_NEEDED.has(cmd) ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd) && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
const RUN = NO_RUN_NEEDED.has(cmd ?? '') ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd ?? '') && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
fail('no run specified -- use --run <id> (see: runs); runs are created with: create <package> <pc-name>');
}
// per-run paths: set once from --run, and re-pointed by create (which
// builds a run dir before any view is written)
let RUN_ROOT, DB_PATH, CANON_DIR, LOG_DIR, DUMPS_DIR, SETTINGS_PATH, SESS;
/** @type {string} */ let RUN_ROOT;
/** @type {string} */ let DB_PATH;
/** @type {string} */ let CANON_DIR;
/** @type {string} */ let LOG_DIR;
/** @type {string} */ let DUMPS_DIR;
/** @type {string} */ let SETTINGS_PATH;
/** @type {number} */ let SESS;
/** @param {string} dir */
function setRunRoot(dir) {
RUN_ROOT = dir;
SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json');
@@ -141,6 +190,7 @@ function setRunRoot(dir) {
// for audit, writes only where the phase allows (the freeze ruling:
// prompts, rings, and carryover are editable during dormancy, frozen
// from the moment a session goes live).
/** @param {string} [runDir] @returns {number[]} */
function listSessions(runDir = RUN_ROOT) {
const dir = path.join(runDir, 'sessions');
if (!fs.existsSync(dir)) return [];
@@ -149,6 +199,7 @@ function listSessions(runDir = RUN_ROOT) {
.map((d) => Number(d.name)).sort((a, b) => a - b);
}
/** @param {number} n @param {string} [runDir] @returns {SessionMeta} */
const sessionMeta = (n, runDir = RUN_ROOT) => {
try {
return JSON.parse(fs.readFileSync(path.join(runDir, 'sessions', String(n), 'session.json'), 'utf8'));
@@ -157,6 +208,7 @@ const sessionMeta = (n, runDir = RUN_ROOT) => {
}
};
/** @param {?number} want @returns {number} */
function resolveSession(want) {
const ns = listSessions();
if (!ns.length) fail('this run has no sessions -- create builds session one');
@@ -169,6 +221,7 @@ function resolveSession(want) {
return live.length ? live[0] : ns[ns.length - 1];
}
/** @param {number} n */
function setSessionRoot(n) {
SESS = n;
const d = path.join(RUN_ROOT, 'sessions', String(n));
@@ -185,6 +238,7 @@ if (RUN != null && cmd !== 'init') setSessionRoot(resolveSession(sessionOverride
// dangerous, finished is frozen); the status and agenda are runtime
// channels (live) and the dormancy edit surface; apply targets the
// dormant session's rings -- the housekeeping write.
/** @type {Record<string, string[]>} */
const PHASE_RULES = {
insert: ['dormant'], delete: ['dormant'], revive: ['dormant'], unarchive: ['dormant'],
apply: ['dormant'],
@@ -192,6 +246,7 @@ const PHASE_RULES = {
'status-apply': ['live'], 'agenda-apply': ['live'],
file: ['dormant', 'live'], amend: ['dormant', 'live'], discard: ['dormant', 'live'],
};
/** @param {string} verb */
function enforcePhase(verb) {
const allowed = PHASE_RULES[verb];
if (!allowed) return;
@@ -225,6 +280,7 @@ GM ratifies notable inventions afterward.)
Freeform notes:
`;
/** @returns {boolean} */
function recordsEnabled() {
try {
return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true;
@@ -233,6 +289,7 @@ function recordsEnabled() {
}
}
/** @returns {DatabaseSync} */
function openDb() {
if (!fs.existsSync(DB_PATH)) {
fail(`no database at ${rel(DB_PATH)} -- run: node tool/memory.mjs init`);
@@ -251,16 +308,17 @@ function openDb() {
// the old CHECK would reject the new op values mid-flight, and the
// positional copy absorbs the column rename. (Mirrors db/schema.sql;
// old dumps carry their own old schema and self-migrate through here.)
/** @param {DatabaseSync} db */
function migrateStatusNames(db) {
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status-add', 'status-drop', 'status-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => r.name);
const tables = /** @type {{ name: string }[]} */ (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all()).map((r) => r.name);
if (tables.includes('paper') && !tables.includes('status')) {
db.exec('ALTER TABLE paper RENAME TO status');
if (!QUIET) console.log(`(migrated: table paper -> status -- ${rel(DB_PATH)})`);
}
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
const row = /** @type {?{ sql: string }} */ (db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get());
if (!row) return;
const staleOps = db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get().n > 0;
const staleOps = Number(db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get()?.n ?? 0) > 0;
if (!staleOps && row.sql.includes("'status-add'")) return;
db.exec('BEGIN');
try {
@@ -296,18 +354,22 @@ function migrateStatusNames(db) {
if (!QUIET) console.log(`(migrated: events journal to the current names -- ${rel(DB_PATH)})`);
}
/** @param {unknown} s @returns {?number} */
const parseId = (s) => {
const m = /^e(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null;
};
/** @param {unknown} s @returns {string} */
const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
/** @param {unknown} s @returns {?number} */
const parseRid = (s) => {
const m = /^r(\d+)$/.exec(String(s ?? '').trim());
return m ? Number(m[1]) : null;
};
/** @param {DatabaseSync} db @param {string} win @param {string} op @param {string} target @param {string} reason @param {string} [prior] */
const journal = (db, win, op, target, reason, prior = '') =>
db.prepare('INSERT INTO events (session, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
.run(win, op, target, norm(reason), prior);
@@ -316,10 +378,11 @@ const journal = (db, win, op, target, reason, prior = '') =>
// hand-edit them (regenerate with render). The do-not-edit warning lives
// here rather than in the output: prose files carry no comments, purpose
// text lives in code or README.
/** @param {DatabaseSync} db @param {string} ring @returns {{ file: string, count: number }} */
function renderRing(db, ring) {
const rows = db.prepare(
const rows = /** @type {EntryRow[]} */ (db.prepare(
'SELECT * FROM entries WHERE ring = ? ORDER BY last_touched DESC, id DESC'
).all(ring);
).all(ring));
const title = ring === 'a' ? 'what matters' : 'what stuck anyway';
const lines = [
`# Ring ${ring.toUpperCase()} -- ${title}`,
@@ -336,8 +399,9 @@ function renderRing(db, ring) {
return { file, count: rows.length };
}
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderStatus(db) {
const rows = db.prepare('SELECT * FROM status ORDER BY id').all();
const rows = /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all());
const lines = [
'# Status',
'',
@@ -355,6 +419,7 @@ function renderStatus(db) {
// the agenda view: the queue, top (newest) first, numbered as the wire
// renders it -- what the model cites, what the GM reads
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderAgenda(db) {
const items = agendaList(db);
const lines = [
@@ -372,6 +437,7 @@ function renderAgenda(db) {
return { file, count: items.length };
}
/** @param {DatabaseSync} db */
function renderAll(db) {
// --json means stdout carries JSON only; the view paths are human garnish
const talk = !QUIET && !AS_JSON;
@@ -387,8 +453,10 @@ function renderAll(db) {
// canonical serialization: id-ordered, one row per line, restorable SQL.
// this is the committed truth; the binary db is a local cache.
/** @param {DatabaseSync} db @returns {string} */
function dumpDb(db) {
fs.mkdirSync(DUMPS_DIR, { recursive: true });
/** @param {unknown} s @returns {string} */
const q = (s) => `'${String(s ?? '').replace(/'/g, "''")}'`;
const L = [
'-- canonical dump of db/memory.db -- GENERATED by tool/memory.mjs; do not edit.',
@@ -396,19 +464,19 @@ function dumpDb(db) {
fs.readFileSync(SCHEMA_PATH, 'utf8').trim(),
'BEGIN TRANSACTION;',
];
for (const r of db.prepare('SELECT * FROM entries ORDER BY id').all()) {
for (const r of /** @type {EntryRow[]} */ (db.prepare('SELECT * FROM entries ORDER BY id').all())) {
L.push(`INSERT INTO entries VALUES (${r.id},${q(r.ring)},${q(r.type)},${q(r.label)},${q(r.detail)},${q(r.created)},${q(r.last_touched)});`);
}
for (const r of db.prepare('SELECT * FROM records ORDER BY id').all()) {
for (const r of /** @type {RecordRow[]} */ (db.prepare('SELECT * FROM records ORDER BY id').all())) {
L.push(`INSERT INTO records VALUES (${r.id},${q(r.kind)},${q(r.label)},${q(r.detail)},${q(r.created)});`);
}
for (const r of db.prepare('SELECT * FROM status ORDER BY id').all()) {
for (const r of /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all())) {
L.push(`INSERT INTO status VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM agenda ORDER BY id').all()) {
for (const r of /** @type {AgendaRow[]} */ (db.prepare('SELECT * FROM agenda ORDER BY id').all())) {
L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) {
for (const r of /** @type {EventRow[]} */ (db.prepare('SELECT * FROM events ORDER BY id').all())) {
L.push(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
}
L.push('COMMIT;', '');
@@ -420,6 +488,7 @@ function dumpDb(db) {
// stamps are mechanical (real, internal, never rendered): they drive
// the LRU -- overflow, view order, "what's sinking". Story time lives
// in the prose of the entries, never in a column.
/** @param {DatabaseSync} db @param {{ ring: string, type: string, label: string, detail: string, win: string, reason: string }} e @returns {number} */
function insertEntry(db, { ring, type, label, detail, win, reason }) {
const now = today();
const res = db.prepare(
@@ -432,19 +501,23 @@ function insertEntry(db, { ring, type, label, detail, win, reason }) {
// --- validation helpers (used by apply) -------------------------------------
/** @param {DatabaseSync} db */
function makeValidator(db) {
const errors = [];
const seen = new Map();
/** @type {string[]} */ const errors = [];
/** @type {Map<number, string>} */ const seen = new Map();
/** @param {unknown} v @param {string} name */
const need = (v, name) => { if (typeof v !== 'string' || !v.trim()) errors.push(`${name} is required`); };
/** @template T @param {T[]|undefined} v @param {string} name @returns {T[]} */
const asArray = (v, name) => {
if (v === undefined || v === null) return [];
if (!Array.isArray(v)) { errors.push(`${name} must be an array`); return []; }
return v;
};
/** @param {string} op @param {RefOp} e @param {?string} expectRing @returns {?EntryRow} */
const ref = (op, e, expectRing) => {
const id = parseId(e.id);
if (id == null) { errors.push(`${op}: id must look like e12`); return null; }
const row = db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) { errors.push(`${op}: e${id} does not exist`); return null; }
if (row.ring === 'cold') { errors.push(`${op}: e${id} is in cold storage -- the models can't see it`); return null; }
if (expectRing && row.ring !== expectRing) {
@@ -460,8 +533,10 @@ function makeValidator(db) {
// --- apply ------------------------------------------------------------------
/** @param {Manifest} mf @param {AppliedLog} applied @param {OverflowItem[]} overflow @returns {string} */
function renderLog(mf, applied, overflow) {
const L = [`# ${mf.session}`, '', mf.summary, ''];
/** @template T @param {string} title @param {T[]} rows @param {(r: T) => string} fmt */
const section = (title, rows, fmt) => {
if (!rows.length) return;
L.push(`## ${title}`, '');
@@ -482,9 +557,10 @@ function renderLog(mf, applied, overflow) {
return L.join('\n');
}
/** @param {string} manifestPath */
function cmdApply(manifestPath) {
const db = openDb();
let mf;
/** @type {Manifest} */ let mf;
try {
mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (e) {
@@ -536,7 +612,7 @@ function cmdApply(manifestPath) {
});
del.forEach((e) => ref('delete', e, null));
arch.forEach((e) => ref('archive', e, null));
for (const [name, arr] of [['inventions', inventions], ['open_questions', questions]]) {
for (const [name, arr] of /** @type {[string, string[]][]} */ ([['inventions', inventions], ['open_questions', questions]])) {
arr.forEach((s, i) => { if (typeof s !== 'string' || !s.trim()) errors.push(`${name}[${i}] must be a non-empty string`); });
}
@@ -545,9 +621,11 @@ function cmdApply(manifestPath) {
for (const e of errors) console.error(` - ${e}`);
process.exit(1);
}
// validation demands a session slug, so a null logFile is unreachable
if (!logFile) fail('unreachable: manifest without a session');
const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
const overflow = [];
/** @type {AppliedLog} */ const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
/** @type {OverflowItem[]} */ const overflow = [];
db.exec('BEGIN');
try {
@@ -558,34 +636,36 @@ function cmdApply(manifestPath) {
});
applied.insert.push({ id, ...e });
}
/** @param {number} id */
const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(today(), id);
const fetch = (id) => db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
/** @param {number} id @returns {EntryRow} */
const fetch = (id) => /** @type {EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
for (const e of touch) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
touchDate(id);
journal(db, mf.session, 'touch', `e${id}`, e.reason);
applied.touch.push({ row: fetch(id), reason: e.reason });
}
for (const e of promote) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'promote', `e${id}`, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason });
}
for (const e of demote) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.session, 'demote', `e${id}`, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason });
}
for (const e of reword) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), today(), id);
journal(db, mf.session, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
}
for (const e of arch) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
const row = fetch(id);
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(row.type, row.label, row.detail, row.created);
@@ -595,7 +675,7 @@ function cmdApply(manifestPath) {
applied.archive.push({ rid, row, reason: e.reason });
}
for (const e of del) {
const id = parseId(e.id);
const id = /** @type {number} */ (parseId(e.id));
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
journal(db, mf.session, 'delete', `e${id}`, e.reason);
applied.delete.push({ row: fetch(id), reason: e.reason });
@@ -603,9 +683,9 @@ function cmdApply(manifestPath) {
// overflow: A spills to B first, then B spills to cold -- exact, by count
for (const ring of RINGS) {
const rows = db.prepare(
const rows = /** @type {{ id: number }[]} */ (db.prepare(
'SELECT id FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC'
).all(ring);
).all(ring));
const extra = rows.length - CAPS[ring];
for (let i = 0; i < extra; i++) {
const victim = rows[i];
@@ -664,6 +744,7 @@ function cmdInit() {
// stubs, the phase marker. The caller (create or init) owns the
// bundle copies; ready is true from birth -- session one's rings are
// its own (memory.json applied), no housekeeping ever precedes it.
/** @param {string} runDir @returns {{ db: DatabaseSync, dir: string }} */
function buildSession1(runDir) {
const s1 = path.join(runDir, 'sessions', '1');
for (const d of ['bundle', 'db', 'canon', 'dumps', 'log']) {
@@ -709,15 +790,17 @@ const PACKAGE_LAYOUT = {
};
// resolve a package name against both roots; the repo wins a collision
/** @param {?string} name @returns {?string} */
function packageDir(name) {
if (!/^[a-z0-9-]+$/.test(name ?? '')) return null;
if (fs.existsSync(path.join(PACKAGES_DIR, name))) return path.join(PACKAGES_DIR, name);
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, name))) return path.join(STATE_PACKAGES_DIR, name);
if (fs.existsSync(path.join(PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(PACKAGES_DIR, /** @type {string} */ (name));
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name)))) return path.join(STATE_PACKAGES_DIR, /** @type {string} */ (name));
return null;
}
// the package meta of a user package (owner, created); system packages
// have none -- their origin is the repo itself
/** @param {string} dir @returns {?{ owner?: ?string, created?: string }} */
function readPackageMeta(dir) {
try {
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
@@ -726,14 +809,16 @@ function readPackageMeta(dir) {
}
}
/** @param {string} name @param {string} dir @param {'system'|'user'} origin @returns {PackageListed} */
function packageEntry(name, dir, origin) {
// exists AND non-empty: an emptied placeholder is not a playable
// package, and the listing must not call it complete (boutique,
// emptied 2026-11-15, taught this)
/** @param {string} f @returns {boolean} */
const has = (f) => {
try { return fs.statSync(path.join(dir, f)).size > 0; } catch { return false; }
};
let settings = {};
/** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')); } catch {}
const meta = origin === 'user' ? readPackageMeta(dir) : null;
return {
@@ -749,7 +834,8 @@ function packageEntry(name, dir, origin) {
}
function cmdPackages() {
const list = [];
/** @type {PackageListed[]} */ const list = [];
/** @param {string} root @param {'system'|'user'} origin */
const scan = (root, origin) => {
if (!fs.existsSync(root)) return;
for (const d of fs.readdirSync(root, { withFileTypes: true })) {
@@ -771,12 +857,15 @@ function cmdPackages() {
// rename and nothing for a name to collide with. The names that
// matter -- the package display name and the pc's name -- live in the
// run's settings copy and drive the display ("La Caramba / Rell").
/** @param {string} runDir @returns {RunSettings} */
const readRunSettings = (runDir) => {
try { return JSON.parse(fs.readFileSync(path.join(runDir, 'settings.json'), 'utf8')); } catch { return {}; }
};
/** @param {string} pkg @param {RunSettings} settings @returns {string} */
const runDisplay = (pkg, settings) =>
settings.pc ? `${settings.name ?? pkg} / ${settings.pc}` : (settings.name ?? pkg);
/** @returns {string} */
function anonId() {
for (;;) {
const id = randomBytes(4).toString('hex'); // 8 hex chars
@@ -784,6 +873,7 @@ function anonId() {
}
}
/** @param {?string} pkgName @param {?string} pc @param {?string} [displayName] @param {?string} [model] */
function cmdCreate(pkgName, pc, displayName, model) {
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
fail('usage: create <package> <pc-name> ["package display name"] ["model"]');
@@ -796,7 +886,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
const rd = path.join(RUNS_DIR, d.name);
let meta = null;
/** @type {?RunMeta} */ let meta = null;
try { meta = JSON.parse(fs.readFileSync(path.join(rd, 'run.json'), 'utf8')); } catch { continue; }
if (meta?.package !== pkgName) continue;
const st = readRunSettings(rd);
@@ -831,7 +921,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
settings.pc = pc;
settings.name = displayName?.trim() || settings.name || pkgName;
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
const meta = { package: pkgName, created: today() };
/** @type {RunMeta} */ const meta = { package: pkgName, created: today() };
if (model) meta.models = { player: model };
if (ownerOverride) meta.owner = ownerOverride;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
@@ -859,7 +949,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs -- create one: create <package> <pc-name>)'); return; }
const list = [];
/** @type {RunListed[]} */ const list = [];
let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
@@ -867,10 +957,10 @@ function cmdRuns() {
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
found++;
let pkg = '?';
let models = null;
let owner = null;
let created = null;
let forked = null;
/** @type {?{ player?: ?string, housekeeper?: ?string }} */ let models = null;
/** @type {?string} */ let owner = null;
/** @type {?string} */ let created = null;
/** @type {?number} */ let forked = null;
try {
const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8'));
pkg = meta.package ?? '?';
@@ -889,20 +979,22 @@ function cmdRuns() {
const phase = active == null ? null : sessionMeta(active, runDir).phase ?? null;
const dbPath = active == null ? null : path.join(runDir, 'sessions', String(active), 'db', 'memory.db');
const ready = active == null ? null : sessionMeta(active, runDir).ready ?? null;
if (active == null || !fs.existsSync(dbPath)) { list.push({ ...base, sessions: ns.length, phase, ready, initialized: false }); continue; }
if (active == null || dbPath == null || !fs.existsSync(dbPath)) { list.push({ ...base, sessions: ns.length, phase, ready, initialized: false }); continue; }
const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
/** @param {string} ring @returns {number} */
const n = (ring) => Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
list.push({ ...base, sessions: ns.length, phase, ready, initialized: true, fill: { a: n('a'), b: n('b'), cold: n('cold') } });
}
if (AS_JSON) { console.log(JSON.stringify(list)); return; }
for (const x of list) {
if (!x.initialized) { console.log(`${x.id} [${x.package}]: ${x.display} (not initialized)`); continue; }
if (!x.initialized || !x.fill) { console.log(`${x.id} [${x.package}]: ${x.display} (not initialized)`); continue; }
console.log(`${x.id} [${x.package}]: ${x.display} -- a ${x.fill.a}/${CAPS.a} \u00b7 b ${x.fill.b}/${CAPS.b} \u00b7 cold ${x.fill.cold}`);
}
if (!found) console.log('(no runs -- create one: create <package> <pc-name>)');
}
/** @returns {string} */
function today() { return new Date().toISOString().slice(0, 10); }
// save a DRAFT's craft as a new user package: the same files create
@@ -912,6 +1004,7 @@ function today() { return new Date().toISOString().slice(0, 10); }
// is fork's job. The saved package carries no pc (the next create asks
// for one); the display name is the save's one decision. The id is
// anonymous hex, like a run's: no facts, nothing to rename.
/** @param {?string} displayName */
function cmdSavePackage(displayName) {
const name = String(displayName ?? '').trim();
if (!name) fail('usage: save-package "display name" (run required via --run)');
@@ -919,7 +1012,7 @@ function cmdSavePackage(displayName) {
if (ns.length > 1 || sessionMeta(ns[0] ?? 0).phase !== 'dormant') {
fail('save-package is a draft act -- this run has played; fork it to branch the story');
}
let id;
/** @type {string} */ let id;
for (;;) {
id = randomBytes(4).toString('hex');
if (!fs.existsSync(path.join(STATE_PACKAGES_DIR, id)) && !fs.existsSync(path.join(PACKAGES_DIR, id))) break;
@@ -939,7 +1032,7 @@ function cmdSavePackage(displayName) {
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
}
const settingsPath = path.join(dst, 'settings.json');
let settings = {};
/** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {}
settings.name = name;
delete settings.pc; // per-run identity never rides a package
@@ -954,13 +1047,14 @@ function cmdSavePackage(displayName) {
console.log(`saved package '${id}' -- ${name}: ${rel(dst)}`);
}
/** @param {string} ring @param {string} type @param {string} label @param {?string} [detail] */
function gmOp(ring, type, label, detail) {
const db = openDb();
if (!RINGS.includes(ring) || !TYPES.includes(type)) {
fail(`usage: insert <a|b> <${TYPES.join('|')}> "Label" "detail"`);
}
db.exec('BEGIN');
let id;
/** @type {number} */ let id;
try {
id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' });
db.exec('COMMIT');
@@ -973,28 +1067,30 @@ function gmOp(ring, type, label, detail) {
dumpDb(db);
}
/** @param {string} idStr @param {?string} [reason] */
function cmdDelete(idStr, reason) {
const db = openDb();
const id = parseId(idStr);
const row = id && db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = id && /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) fail(`no such entry: ${idStr}`);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(/** @type {number} */ (id));
journal(db, 'gm', 'delete', `e${id}`, reason ?? 'GM edit');
console.log(`[e${id}] **${row.label}** -> cold storage`);
renderAll(db);
dumpDb(db);
}
/** @param {string} idStr @param {?string} [ring] */
function cmdRevive(idStr, ring = 'b') {
const db = openDb();
const id = parseId(idStr);
const row = id && db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
const row = id && /** @type {?EntryRow} */ (db.prepare('SELECT * FROM entries WHERE id = ?').get(id));
if (!row) fail(`no such entry: ${idStr}`);
if (row.ring !== 'cold') fail(`[e${id}] is not in cold storage (ring ${row.ring})`);
if (!RINGS.includes(ring)) fail(`target ring must be a|b`);
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(ring, id);
if (!RINGS.includes(ring ?? '')) fail(`target ring must be a|b`);
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(/** @type {string} */ (ring), /** @type {number} */ (id));
journal(db, 'gm', 'revive', `e${id}`, 'GM revive');
console.log(`[e${id}] **${row.label}** revived -> ring ${ring.toUpperCase()}`);
console.log(`[e${id}] **${row.label}** revived -> ring ${/** @type {string} */ (ring).toUpperCase()}`);
renderAll(db);
dumpDb(db);
}
@@ -1003,6 +1099,7 @@ function cmdDump() {
console.log(rel(dumpDb(openDb())));
}
/** @param {boolean} force */
function cmdRestore(force = false) {
const dumpFile = path.join(DUMPS_DIR, 'memory.sql');
if (!fs.existsSync(dumpFile)) fail(`no dump at ${rel(dumpFile)} -- nothing to restore from`);
@@ -1023,6 +1120,7 @@ function cmdRestore(force = false) {
renderAll(db);
}
/** @param {?string} kind @param {?string} label @param {?string} [detail] @param {?string} [reason] */
function cmdFile(kind, label, detail, reason) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to file (see the run\'s settings.json)');
@@ -1035,14 +1133,15 @@ function cmdFile(kind, label, detail, reason) {
dumpDb(db);
}
/** @param {string} ridStr @param {?string} detail */
function cmdAmend(ridStr, detail) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
if (!detail?.trim()) fail('usage: amend <rid> "new detail"');
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), rid);
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), /** @type {number} */ (rid));
// saga rule: the journal keeps the prior detail, so turn surgery can
// compensate mechanically
journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended', row.detail);
@@ -1050,13 +1149,14 @@ function cmdAmend(ridStr, detail) {
dumpDb(db);
}
/** @param {string} ridStr @param {?string} [reason] */
function cmdDiscard(ridStr, reason) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records');
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
db.prepare('DELETE FROM records WHERE id = ?').run(/** @type {number} */ (rid));
// saga rule: the whole discarded row is journaled -- a compensation
// can re-file it exactly (id included, so rid references stay valid)
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded',
@@ -1073,10 +1173,12 @@ function cmdDiscard(ridStr, reason) {
// The GM overrides out-of-band with status-set. Descriptions never contain
// commas: both the delta lists and the <status> block are comma-separated.
const statusList = (db) => db.prepare('SELECT descr FROM status ORDER BY id').all().map((r) => r.descr);
/** @param {DatabaseSync} db @returns {string[]} */
const statusList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM status ORDER BY id').all()).map((r) => r.descr);
// split a list of descriptions, tolerating newlines and list bullets --
// covers the delta tags and a <status> block body alike
/** @param {unknown} s @returns {string[]} */
const splitDescrs = (s) =>
String(s ?? '').split('\n').flatMap((line) =>
line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean);
@@ -1085,13 +1187,14 @@ function cmdStatus() {
console.log(JSON.stringify(statusList(openDb())));
}
/** @param {string} text */
function cmdStatusApply(text) {
const db = openDb();
const lost = [];
const gained = [];
for (const m of String(text ?? '').matchAll(/<lost>([\s\S]*?)<\/lost>/g)) lost.push(...splitDescrs(m[1]));
for (const m of String(text ?? '').matchAll(/<gained>([\s\S]*?)<\/gained>/g)) gained.push(...splitDescrs(m[1]));
const applied = { lost: [], gained: [], conflicts: [] };
/** @type {{ lost: string[], gained: string[], conflicts: string[] }} */ const applied = { lost: [], gained: [], conflicts: [] };
if (!lost.length && !gained.length) {
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
return;
@@ -1100,7 +1203,7 @@ function cmdStatusApply(text) {
db.exec('BEGIN');
try {
for (const item of lost) {
const row = db.prepare('SELECT * FROM status WHERE descr = ?').get(item);
const row = /** @type {?StatusRow} */ (db.prepare('SELECT * FROM status WHERE descr = ?').get(item));
if (row) {
db.prepare('DELETE FROM status WHERE id = ?').run(row.id);
journal(db, win, 'status-drop', `p${row.id}`, 'delta', row.descr);
@@ -1128,6 +1231,7 @@ function cmdStatusApply(text) {
// whole-status replace (GM override); the journal keeps
// the full prior status so turn surgery can compensate mechanically
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {string[]} */
function setStatus(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = statusList(db);
@@ -1146,6 +1250,7 @@ function setStatus(db, items, reason, win) {
return clean;
}
/** @param {string[]} items */
function cmdStatusSet(items) {
const db = openDb();
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc');
@@ -1164,21 +1269,23 @@ function cmdStatusSet(items) {
// 0-based indexes against the agenda as last rendered, adds are
// comma-separated. The GM overrides whole-list with agenda-set.
const agendaList = (db) => db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all().map((r) => r.descr);
/** @param {DatabaseSync} db @returns {string[]} */
const agendaList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all()).map((r) => r.descr);
function cmdAgenda() {
console.log(JSON.stringify(agendaList(openDb())));
}
/** @param {string} text */
function cmdAgendaApply(text) {
const db = openDb();
const added = [];
const dropped = [];
const evicted = [];
const conflicts = [];
const adds = [];
/** @type {string[]} */ const added = [];
/** @type {string[]} */ const dropped = [];
/** @type {string[]} */ const evicted = [];
/** @type {string[]} */ const conflicts = [];
/** @type {string[]} */ const adds = [];
for (const m of String(text ?? '').matchAll(/<add>([\s\S]*?)<\/add>/g)) adds.push(...splitDescrs(m[1]));
const drops = [];
/** @type {string[]} */ const drops = [];
for (const m of String(text ?? '').matchAll(/<drop>([\s\S]*?)<\/drop>/g)) {
drops.push(...String(m[1]).split(/[\n,]/).map((x) => x.trim()).filter(Boolean));
}
@@ -1193,7 +1300,7 @@ function cmdAgendaApply(text) {
// -> next block. Indexes resolve against the same snapshot, so a
// multi-drop never shifts under itself.
const snapshot = agendaList(db);
const kill = [];
/** @type {number[]} */ const kill = [];
for (const d of drops) {
if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; }
const i = Number(d);
@@ -1205,7 +1312,7 @@ function cmdAgendaApply(text) {
}
for (const i of [...new Set(kill)].sort((a, b) => b - a)) {
const descr = snapshot[i];
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr);
const row = /** @type {{ id: number }} */ (db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr));
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr);
dropped.push(descr);
@@ -1225,7 +1332,7 @@ function cmdAgendaApply(text) {
// overflow: the bottom sinks off the list -- by design, not an error
const over = agendaList(db);
for (let i = over.length - 1; i >= AGENDA_CAP; i--) {
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]);
const row = /** @type {{ id: number }} */ (db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]));
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)');
evicted.push(over[i]);
@@ -1242,6 +1349,7 @@ function cmdAgendaApply(text) {
// whole-list replace (GM override); the journal keeps the prior queue
// so turn surgery can compensate mechanically (the saga rule)
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {string[]} */
function setAgenda(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = agendaList(db);
@@ -1260,6 +1368,7 @@ function setAgenda(db, items, reason, win) {
return clean;
}
/** @param {string[]} items */
function cmdAgendaSet(items) {
const db = openDb();
const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc');
@@ -1268,38 +1377,41 @@ function cmdAgendaSet(items) {
dumpDb(db);
}
/** @param {string[]} options */
function cmdPick(options) {
if (options.length < 2) fail('usage: pick "option one" "option two" [...]');
const choice = options[Math.floor(Math.random() * options.length)];
console.log(`picked: ${choice}`);
}
/** @param {string[]} terms */
function cmdSearch(terms) {
const db = openDb();
if (!recordsEnabled()) fail('this character keeps no records -- nothing to consult');
if (!terms.length) fail('usage: search <terms...>');
const conds = terms.map(() => "(label || ' ' || detail) LIKE ?").join(' AND ');
const params = terms.map((t) => `%${t}%`);
const rows = db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params);
const rows = /** @type {RecordRow[]} */ (db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params));
if (!rows.length) { console.log('(no records match)'); return; }
for (const r of rows) console.log(`[r${r.id}] [${r.kind}] **${r.label}**${r.detail ? ` -- ${r.detail}` : ''}`);
const total = db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params).n;
const total = Number(db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params)?.n ?? 0);
if (total > rows.length) console.log(`...${total - rows.length} more omitted -- narrow the query`);
}
/** @param {string} ridStr @param {?string} [ring] */
function cmdUnarchive(ridStr, ring = 'b') {
const db = openDb();
const rid = parseRid(ridStr);
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
const row = rid && /** @type {?RecordRow} */ (db.prepare('SELECT * FROM records WHERE id = ?').get(rid));
if (!row) fail(`no such record: ${ridStr}`);
if (!RINGS.includes(ring)) fail('target ring must be a|b');
if (!RINGS.includes(ring ?? '')) fail('target ring must be a|b');
const type = TYPES.includes(row.kind) ? row.kind : 'fact';
const res = db.prepare('INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)')
.run(ring, type, row.label, row.detail, row.created, today());
.run(/** @type {string} */ (ring), type, row.label, row.detail, row.created, today());
const eid = Number(res.lastInsertRowid);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
db.prepare('DELETE FROM records WHERE id = ?').run(/** @type {number} */ (rid));
journal(db, 'gm', 'unarchive', `e${eid}`, 'GM unarchive');
console.log(`[r${rid}] **${row.label}** -> ring ${ring.toUpperCase()} as [e${eid}]`);
console.log(`[r${rid}] **${row.label}** -> ring ${/** @type {string} */ (ring).toUpperCase()} as [e${eid}]`);
renderAll(db);
dumpDb(db);
}
@@ -1307,41 +1419,42 @@ function cmdUnarchive(ridStr, ring = 'b') {
function cmdReport() {
const db = openDb();
if (AS_JSON) {
/** @type {{ run: ?string, records: number, recordsEnabled: boolean, status: string[], agenda: string[], events: number, rings: Record<string, number>, sinking: Record<string, { id: number, last_touched: string, label: string }[]> }} */
const out = {
run: RUN,
records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n,
records: Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0),
recordsEnabled: recordsEnabled(),
status: statusList(db),
agenda: agendaList(db),
events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n,
events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0),
rings: {},
sinking: {},
};
for (const ring of ['a', 'b', 'cold']) {
out.rings[ring] = db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
out.rings[ring] = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
if (ring !== 'cold') {
out.sinking[ring] = db.prepare(
out.sinking[ring] = /** @type {{ id: number, last_touched: string, label: string }[]} */ (db.prepare(
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
).all(ring);
).all(ring));
}
}
console.log(JSON.stringify(out));
return;
}
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
const nr = Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0);
console.log(`records: ${nr}`);
const status = statusList(db);
console.log(`status: ${status.length ? '' : '(a blank sheet)'}`);
for (const d of status) console.log(` - ${d}`);
for (const ring of ['a', 'b', 'cold']) {
const n = db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
const n = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
const cap = CAPS[ring] ?? 'none';
console.log(`ring ${ring}: ${n} / ${cap}`);
if (ring !== 'cold') {
const old = db.prepare(
const old = /** @type {{ id: number, last_touched: string, label: string }[]} */ (db.prepare(
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
).all(ring);
).all(ring));
for (const r of old) console.log(` sinking: [e${r.id}] ${r.last_touched} **${r.label}**`);
}
}
@@ -1351,7 +1464,7 @@ function cmdReport() {
// the freeze ruling rides the dispatch: a mutating verb touches only
// the phases its rules allow (see PHASE_RULES)
if (RUN != null && PHASE_RULES[cmd]) enforcePhase(cmd);
if (RUN != null && PHASE_RULES[cmd ?? '']) enforcePhase(cmd ?? '');
switch (cmd) {
case 'packages': cmdPackages(); break;
+1 -1
View File
@@ -11,5 +11,5 @@
"lib": ["ES2022"],
"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
// instead; destructive confirms are two-click armed (widgets.mjs).
/** @typedef {import('../server/shapes.mjs').User} User */
import { $ } from './dom.mjs';
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// -- the lifecycle story is a roadmap extension point
/** @param {?User} [me] */
export function setWho(me) {
$('who').textContent = me ? `${me.name}${me.superuser ? ' \u00b7 op' : ''}` : '';
$('who').title = me?.id ?? '';
}
/** @param {string} text */
export function setSessionInfo(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) {
const fill = $('context-fill');
const label = $('context-label');
@@ -34,18 +41,20 @@ export function renderMeter(detail) {
label.textContent = c.contwin ? `${pct}% -- close & housekeep past 85%` : '';
}
/** @param {boolean} on @param {string} [text] */
export function setBusy(on, text = 'her turn...') {
$('busy').hidden = !on; // model calls take their time -- say so
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') {
const b = $('banner');
b.textContent = text;
b.className = kind;
b.hidden = false;
clearTimeout(bannerTimer);
clearTimeout(bannerTimer ?? undefined);
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;
// 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 { state } from './state.mjs';
import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
/** @returns {string} */
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 clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
/** @param {string} path @param {ApiOpts} [opts] @returns {Promise<any>} */
export async function api(path, opts = {}) {
const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`;
@@ -29,7 +36,7 @@ export async function api(path, opts = {}) {
});
const data = await res.json().catch(() => ({}));
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.status = res.status;
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.
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) {
const e = document.createElement(tag);
if (cls) e.className = cls;
+2 -1
View File
@@ -8,9 +8,10 @@
import { $ } from './dom.mjs';
const log = [];
/** @type {string[]} */ const log = [];
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) {
log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
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 { 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 = {};
/** @param {Record<string, ViewDef>} map */
export function registerViews(map) { Object.assign(views, map); }
/** @param {string} p */
export function navigate(p) {
history.pushState({}, '', p);
render();
@@ -22,11 +29,14 @@ export function navigate(p) {
window.addEventListener('popstate', () => render());
/** @returns {Promise<void>} */
export async function render() {
const seq = ++state.seq;
hideBanner();
const p = location.pathname;
/** @type {?string} */
let name = null;
/** @type {?string} */
let arg = null;
let m;
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-]+)$/))) { name = 'play'; arg = m[1]; }
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
await show(name, arg, seq);
}
/** @param {string} name @param {?string} arg @param {number} seq @returns {Promise<void>} */
async function show(name, arg, seq) {
const prev = state.view;
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.
// render() clears the banner first -- set it after the navigate.
/** @param {string} id @param {string} from */
export function runGone(id, from) {
navigate('/');
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
// 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 = {
view: null, // the active view name ('claim' | 'home' | ...)
seq: 0,
+13 -2
View File
@@ -8,9 +8,15 @@
// delta tags on player turns are machinery, not prose -- they render
// 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';
// splits text into spans: *italics* = narration, **bold** = emphasis
/** @param {HTMLElement} target @param {string} text */
function renderSpans(target, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) {
@@ -34,6 +40,7 @@ function renderSpans(target, text) {
// the riding blocks (status/conflict/agenda) out of GM prose; the
// delta tags on player turns always render as chips. Exported for
// 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 }) {
let body = String(text ?? '');
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
// opening event (her opening status) renders as machinery, mirroring
// the wire policy: it is set once, never re-sent.
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void }} [opts] */
export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript');
t.textContent = '';
const bundleParts = [];
/** @type {BundleEvent[]} */ const bundleParts = [];
const flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
@@ -158,7 +166,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
// the turn reminder: the transcript mirrors the live-context
// policy -- one collapsed card for the newest copy, superseded
// 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) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder -- rides every GM turn'));
@@ -190,6 +198,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
flushBundle();
t.scrollTop = t.scrollHeight;
/** @param {?string} content @param {string} who */
function gmTurn(content, who) {
const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who));
@@ -199,6 +208,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
if (conflict) onConflict?.(conflict);
t.appendChild(d);
}
/** @param {MsgEvent} e */
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
@@ -210,6 +220,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
}
t.appendChild(d);
}
/** @param {NoteEvent} e */
function renderNote(e) {
let text = null;
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 { navigate } from './router.mjs';
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
$('claim-code').value = '';
$('claim-name').value = '';
/** @type {HTMLInputElement} */ ($('claim-code')).value = '';
/** @type {HTMLInputElement} */ ($('claim-name')).value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? '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';
$('claim-code').focus();
/** @type {HTMLInputElement} */ ($('claim-code')).focus();
}
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
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);
state.me = r.user;
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 { 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) {
const runs = await api('/runs');
/** @type {RunCard[]} */ const runs = await api('/runs');
if (seq !== state.seq) return;
const list = $('run-list');
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'));
}
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');
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta -- chrome, never model-facing
@@ -31,15 +34,18 @@ export async function enter(arg, seq) {
await renderAdmin(seq);
}
/** @param {RunCard} r @param {boolean} mine @returns {string} */
const ownershipTag = (r, mine) =>
(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"
/** @param {number} t @returns {string} */
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
/** @param {RunCard} r @returns {string} */
function runStateText(r) {
if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`;
if (r.phase === 'dormant') {
@@ -48,6 +54,7 @@ function runStateText(r) {
}
return 'no sessions';
}
/** @param {RunCard} r @returns {string} */
function runStateClass(r) {
if (r.pendingAsk) return 'attention';
if (r.phase === 'live') return 'ok';
@@ -56,10 +63,12 @@ function runStateClass(r) {
return '';
}
/** @param {number} seq @returns {Promise<void>} */
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
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')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
+11 -8
View File
@@ -9,8 +9,9 @@ import { state } from './state.mjs';
import { banner } from './chrome.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) {
$('package-pick').hidden = false;
$('create-form').hidden = true;
@@ -29,25 +30,27 @@ export async function enter(arg, seq) {
}
}
/** @param {{ display: string, name: string }} p */
async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start -- ${p.display}`;
$('create-name').value = p.display;
$('create-pc').value = '';
$('create-pc').placeholder = 'rolling a name...';
$('create-pc').focus();
/** @type {HTMLInputElement} */ ($('create-name')).value = p.display;
const pcInp = /** @type {HTMLInputElement} */ ($('create-pc'));
pcInp.value = '';
pcInp.placeholder = 'rolling a name...';
pcInp.focus();
const roll = await api('/names').catch(() => null);
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-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('create-name').value.trim();
const pc = $('create-pc').value.trim();
const name = /** @type {HTMLInputElement} */ ($('create-name')).value.trim();
const pc = /** @type {HTMLInputElement} */ ($('create-pc')).value.trim();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
+57 -34
View File
@@ -3,6 +3,13 @@
// instances), the GM notepad, housekeeping (close session, the
// 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 { api } from './client.mjs';
import { state } from './state.mjs';
@@ -49,23 +56,26 @@ const models = modelsBox('models-pane', { title: 'models' });
export function leave() {
saveNotes();
stopPoll();
$('ask-modal').close();
/** @type {HTMLDialogElement} */ ($('ask-modal')).close();
}
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters play with a run id
statusPane.reset();
agendaPane.reset();
$('conflict').hidden = true;
await saveNotes(); // flush the pad for the previous run before switching
state.runId = id;
notesDirty = false;
$('gm-notes').value = '';
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = '';
$('notes-state').textContent = '';
await refreshPlay(id, seq);
}
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function refreshPlay(id, seq) {
let detail;
/** @type {RunDetail} */ let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
@@ -73,7 +83,7 @@ async function refreshPlay(id, seq) {
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
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 (mine) return navigate(`/runs/${id}/setup`);
// 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.
statusPane.setEditable(mine);
agendaPane.setEditable(mine);
$('gm-notes').readOnly = !mine;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = !mine;
if (detail.phase === 'live') {
// the table: the live session's projection -- thinking never
// crosses the wire, variant turns carry only the picked one (the
// 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;
renderTranscript(session.entries, { onConflict: showConflict });
} else if (detail.phase === 'dormant') {
// the review window: the carryover is the preview of the next
// 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;
$('transcript').textContent = '';
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-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false) || !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'
: '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
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
/** @type {HTMLDialogElement} */ ($('ask-modal')).showModal();
/** @type {HTMLInputElement} */ ($('ask-answer')).focus();
} else {
$('ask-modal').close();
/** @type {HTMLDialogElement} */ ($('ask-modal')).close();
}
// housekeeping state
const hk = await api(`/runs/${id}/housekeeping`);
/** @type {JobState} */ const hk = await api(`/runs/${id}/housekeeping`);
if (seq !== state.seq) return;
renderHk(hk);
@@ -159,6 +169,7 @@ async function refreshPlay(id, seq) {
// the dormant bar: the review window's banner over the carryover
// preview, with the one button that leaves it
/** @param {RunDetail} detail @param {?CarryoverResponse} carry @returns {HTMLElement} */
function dormantBar(detail, carry) {
const bar = el('div', 'beat');
const ending = carry?.ends === 'gm'
@@ -171,6 +182,7 @@ function dormantBar(detail, carry) {
return bar;
}
/** @param {string} text */
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
@@ -183,26 +195,28 @@ function showConflict(text) {
// flushed when leaving the play view or switching runs. gm.md never
// reaches any model -- this is the GM's own notes.
let notesTimer = null;
/** @type {?ReturnType<typeof setTimeout>} */ let notesTimer = null;
let notesDirty = false;
/** @param {string} id @param {number} seq @returns {Promise<void>} */
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;
$('gm-notes').value = notes.content;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = notes.content;
}
function notesInput() {
notesDirty = true;
$('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer);
clearTimeout(notesTimer ?? undefined);
notesTimer = setTimeout(saveNotes, 1000);
}
/** @returns {Promise<void>} */
async function saveNotes() {
clearTimeout(notesTimer);
clearTimeout(notesTimer ?? undefined);
if (!notesDirty || !state.runId) return;
const content = $('gm-notes').value;
const content = /** @type {HTMLTextAreaElement} */ ($('gm-notes')).value;
try {
// keepalive: the flush must survive leaving the page entirely
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
// turn, the server sends it automatically as her cue.
/** @returns {Promise<void>} */
async function startRun() {
const override = $('hk-override').checked;
const override = /** @type {HTMLInputElement} */ ($('hk-override')).checked;
hideBanner();
setBusy(true, 'starting...');
try {
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');
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
@@ -237,12 +252,14 @@ async function startRun() {
render();
}
/** @param {string} stateText @param {?string} [cls] */
function setHk(stateText, cls) {
const h = $('hk-state');
h.textContent = stateText;
h.className = cls ?? '';
}
/** @param {JobState} hk */
function renderHk(hk) {
if (hk.state === 'running') {
setHk(hk.phase === 'rerun' ? 're-running housekeeping...' : 'stopping & housekeeping...', '');
@@ -262,39 +279,42 @@ function renderHk(hk) {
}
}
/** @param {boolean} ok */
function setInput(ok) {
$('gm-input').disabled = !ok;
$('gm-send').disabled = !ok;
/** @type {HTMLInputElement} */ ($('gm-input')).disabled = !ok;
/** @type {HTMLButtonElement} */ ($('gm-send')).disabled = !ok;
}
// --- actions -----------------------------------------------------------
/** @returns {Promise<void>} */
async function sendTurn() {
const line = $('gm-input').value.trim();
const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim();
if (!line || !state.runId) return;
$('gm-input').value = '';
/** @type {HTMLInputElement} */ ($('gm-input')).value = '';
setInput(false);
setBusy(true);
try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
} catch (e) {
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);
render();
}
/** @returns {Promise<void>} */
async function sendAnswer() {
const answer = $('ask-answer').value.trim();
const answer = /** @type {HTMLInputElement} */ ($('ask-answer')).value.trim();
if (!answer || !state.runId) return;
$('ask-answer').value = '';
/** @type {HTMLInputElement} */ ($('ask-answer')).value = '';
setBusy(true);
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) {
banner(e.message);
$('ask-answer').value = answer;
/** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
}
setBusy(false);
render();
@@ -302,6 +322,7 @@ async function sendAnswer() {
// fork: a copy of this run under you -- any run, anyone's, including
// yours. Lands you in the fork.
/** @returns {Promise<void>} */
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking...');
@@ -318,6 +339,7 @@ async function forkRun() {
// dry-run: the housekeeper reads the session log, the manifest lands
// in the pane -- nothing applied, the session stays open
/** @returns {Promise<void>} */
async function replayHousekeeping() {
setBusy(true, 'the housekeeper reads...');
try {
@@ -325,8 +347,8 @@ async function replayHousekeeping() {
$('hk-replay-content').textContent = r.parsed
? JSON.stringify(r.manifest, null, 2)
: `${r.reason}\n\nraw output: ${r.file}`;
$('hk-replay-log').hidden = false;
$('hk-replay-log').open = true;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).open = true;
} catch (e) {
banner(e.message);
}
@@ -335,7 +357,7 @@ async function replayHousekeeping() {
// --- housekeeping poll + log -------------------------------------------
let poll = null;
/** @type {?ReturnType<typeof setInterval>} */ let poll = null;
function startPoll() {
stopPoll();
@@ -350,12 +372,13 @@ function stopPoll() {
poll = null;
}
/** @returns {Promise<void>} */
async function loadLog() {
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').hidden = false;
$('hk-log').open = true;
/** @type {HTMLDetailsElement} */ ($('hk-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-log')).open = true;
} catch {
$('hk-log').hidden = true;
}
+47 -30
View File
@@ -5,6 +5,10 @@
// it) or start (the dormant session goes live; a carryover ending on
// 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 { api } from './client.mjs';
import { state } from './state.mjs';
@@ -32,19 +36,23 @@ const EDIT_LIST = [
];
// the editor's working set -- module-local, reset on every enter
let files = null; // { name: { content, exists } }
let drafts = {}; // unsaved edits by file name
let currentFile = null;
let fileSpecs = {};
let repoPrompts = {};
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
/** @type {?string} */ let currentFile = null;
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
/** @type {Record<string, string>} */ let repoPrompts = {};
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) {
if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id;
drafts = {};
currentFile = null;
let detail, filesResp, prompts;
/** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts;
try {
[detail, filesResp, prompts] = await Promise.all([
api(`/runs/${id}`),
@@ -57,7 +65,7 @@ export async function enter(id, seq) {
}
if (seq !== state.seq) return;
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;
repoPrompts = {
@@ -69,7 +77,7 @@ export async function enter(id, seq) {
$('setup-state').textContent = detail.draft
? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts`
: `${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}`;
// draft-only affordances: deletion and save-as-package (a package is
// 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
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 */ }
const varsList = $('setup-vars-list');
varsList.textContent = '';
@@ -86,7 +94,7 @@ export async function enter(id, seq) {
$('setup-vars-state').textContent = '';
for (const tok of vars) {
const row = el('label', 'field', `$${tok}`);
const inp = el('input');
const inp = /** @type {HTMLInputElement} */ (el('input'));
inp.dataset.token = tok;
inp.value = currentVars[tok] ?? '';
row.appendChild(inp);
@@ -120,13 +128,14 @@ export async function enter(id, seq) {
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
}
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or the session's own, the carryover included -- it
// expands at start like every authored surface) becomes a fillable
// input in setup
/** @param {PromptsResponse} prompts @param {Record<string, { content?: string }>} files @returns {string[]} */
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
@@ -141,12 +150,14 @@ function scanVars(prompts, files) {
return [...found].sort();
}
/** @returns {Record<string, string>} */
function collectVars() {
const vars = {};
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim();
/** @type {Record<string, string>} */ const vars = {};
for (const inp of /** @type {NodeListOf<HTMLInputElement>} */ ($('setup-vars-list').querySelectorAll('input'))) vars[/** @type {string} */ (inp.dataset.token)] = inp.value.trim();
return vars;
}
/** @returns {Promise<void>} */
async function saveVars() {
const vars = collectVars();
if (!Object.keys(vars).length) return;
@@ -154,6 +165,7 @@ async function saveVars() {
$('setup-vars-state').textContent = 'saved';
}
/** @param {string} f */
function selectFile(f) {
const prev = currentFile;
if (prev === f) return;
@@ -163,8 +175,8 @@ function selectFile(f) {
const content = spec.source === 'repo'
? (repoPrompts[f] ?? '')
: (drafts[f] ?? spec.content ?? '');
$('setup-edit').value = content;
$('setup-edit').disabled = spec.mode !== 'rw';
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).value = content;
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
renderHighlight();
@@ -177,9 +189,9 @@ function selectFile(f) {
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const ta = $('setup-edit');
const ta = /** @type {HTMLTextAreaElement} */ ($('setup-edit'));
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
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
@@ -188,9 +200,10 @@ function renderHighlight() {
hl.scrollLeft = ta.scrollLeft;
}
/** @param {string} f */
function stashDraft(f) {
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; }
drafts[f] = v;
markNav();
@@ -199,23 +212,24 @@ function stashDraft(f) {
function markNav() {
const items = $('setup-files').children;
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;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// 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);
}
}
/** @returns {Promise<void>} */
async function saveFile() {
const f = currentFile;
if (!f) return;
$('setup-save').disabled = true;
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = true;
try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } });
files[f].content = $('setup-edit').value;
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value } });
files[f].content = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
files[f].exists = true;
delete drafts[f];
$('setup-edit-state').textContent = 'saved';
@@ -224,11 +238,12 @@ async function saveFile() {
banner(e.message);
$('setup-edit-state').textContent = 'not saved';
}
$('setup-save').disabled = false;
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = false;
}
/** @returns {Promise<void>} */
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 })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { 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
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
/** @returns {Promise<void>} */
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');
$('savepkg-btn').disabled = true;
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true;
$('savepkg-state').textContent = 'saving...';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved -- ${r.package.id}`;
$('savepkg-name').value = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = false;
}
/** @returns {Promise<void>} */
async function startRun() {
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 backstop, not the first line of defense
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 { 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) {
if (id == null) return; // unreachable: the router only enters the story with a run id
storyRun = id;
let detail;
/** @type {RunDetail} */ let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
@@ -28,7 +33,7 @@ export async function enter(id, seq) {
}
if (seq !== state.seq) return;
$('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 (!story) return banner('the story could not be read');
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
// 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 }) {
let timer = null;
/** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
btn.addEventListener('click', async () => {
if (timer === null) {
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
// the editor open, nothing was changed. setEditable(false) is the
// 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 }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
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');
editor.hidden = true;
const area = el('textarea');
const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = rows;
area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions');
@@ -54,7 +58,7 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
editor.appendChild(actions);
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
let items = [];
/** @type {string[]} */ let items = [];
let mayEdit = 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
// /models call every render would hammer the endpoint for a list
// that rarely changes
let cachedModels = null;
/** @type {?string[]} */ let cachedModels = null;
/** @returns {Promise<string[]>} */
export async function modelList() {
if (!cachedModels) cachedModels = await api('/models').catch(() => []);
if (!cachedModels) cachedModels = /** @type {string[]} */ (await api('/models').catch(() => []));
return cachedModels;
}
// A select's "" value means "deployment default"; a current override
// missing from the listing stays selectable, so a stale pick never
// silently rewrites itself.
/** @param {HTMLSelectElement} sel @param {?string} current @param {string[]} list @param {?string} [def] */
function fillSelect(sel, current, list, def) {
sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => {
const o = el('option', null, label);
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
@@ -127,12 +134,13 @@ function fillSelect(sel, current, list, def) {
// the models box: player/housekeeper selects + save, posting the
// 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 }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = el('select');
const houseSel = el('select');
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
@@ -158,6 +166,7 @@ export function modelsBox(mount, { title }) {
}
});
return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {string[]} list */
fill(models, defaults, list) {
fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);