Files
tiny-worlds/tool/memory.mjs
T

1499 lines
70 KiB
JavaScript

#!/usr/bin/env node
// tool/memory.mjs -- bookkeeping for the memory rings.
//
// judgment lives in the models (player + housekeeper)
// mechanics live here (this file)
// state lives in db/memory.db
// canon/ is a generated view (never edit by hand)
//
// commands:
// packages list packages (presets) and their flags
// runs list runs (instances) and their fill levels
// create <package> <pc-name> create a run: copy the package wholesale
// (shared prompts included -- battery
// included), give it an anonymous id and
// the pc's name (distinct per package),
// build dormant session one (bundle, db,
// carryover; memory.json applies through
// the standard apply path). From then on
// the run dir is the only truth; the
// package is never read again.
// save-package "display name" save a DRAFT's craft as a new user
// package (state/packages/, published to
// all; pc never rides; --owner stamps)
// init build session one of a fresh run
// (the low-level primitive under create)
// render write canon/ring-a.md, ring-b.md, status.md
// apply <manifest.json> apply a housekeeper manifest (validated, transactional)
// insert <ring> <type> "Label" "detail" GM-authoritative insert
// delete <id> "reason" GM-authoritative removal to cold storage
// revive <id> [a|b] GM pulls an entry back from cold storage
// file <kind> "Label" "detail" the PC files a record at her desk
// (records-enabled runs; --gm to file
// ahead of play)
// amend <rid> "new detail" the PC amends a record (--gm for GM fixes)
// discard <rid> "reason" the PC discards a record (--gm likewise)
// search <terms...> query the records (max 10; a miss is a miss)
// unarchive <rid> [a|b] GM pulls a record back into the rings
// status her status, as JSON (the status tier)
// status-apply "<turn text>" apply <lost>/<gained> deltas from a player
// turn; exact match, non-blocking; JSON result
// (lost / gained / conflicts / status)
// status-set "descr" ... GM override: replace the whole status
// (no descrs = clear it)
// agenda the agenda, as JSON (the intentions tier)
// agenda-apply "<turn text>" apply <add>/<drop> deltas from a player
// turn; drops are 0-based indexes against
// the agenda as last rendered; JSON result
// (added / dropped / evicted / conflicts /
// agenda)
// agenda-set "item" ... GM override: replace the whole agenda
// (no items = clear it)
// pick "a" "b" "c" ... dice for prose -- uniform random choice
// dump canonical dump to dumps/memory.sql
// (also auto-written by every mutation)
// restore --force rebuild the db from dumps/memory.sql
// commands take --run <id> (a run under runs/) and --session <n> (a
// specific session; the default is the ACTIVE session -- the live one
// while a session plays, else the latest, the dormant one during the
// review window). State is per-deployment and per-session: every
// session owns its db, canon views, dumps, and housekeeping logs.
//
// 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';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SCHEMA_PATH = path.join(ROOT, 'db', 'schema.sql');
const PACKAGES_DIR = path.join(ROOT, 'packages');
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]);
if (!Number.isInteger(sessionOverride) || sessionOverride < 1) {
fail('--session <n> -- a session number, 1-based');
}
argv.splice(sessionIdx, 2);
}
const FORCE = argv.includes('--force');
for (let i = argv.indexOf('--force'); i !== -1; i = argv.indexOf('--force')) argv.splice(i, 1);
const AS_GM = argv.includes('--gm');
for (let i = argv.indexOf('--gm'); i !== -1; i = argv.indexOf('--gm')) argv.splice(i, 1);
const QUIET = argv.includes('--quiet');
for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) argv.splice(i, 1);
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;
argv.splice(ownerIdx, 2);
}
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))) {
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)
/** @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');
}
// --- session addressing -------------------------------------------------------
//
// Every session owns its state under sessions/<n>/: the db, the canon
// views, the dumps, the housekeeping logs, the carryover. Commands
// address the ACTIVE session by default -- the live one while a
// session plays, else the latest (the dormant one during the review
// window). An explicit --session <n> addresses any session: reads
// 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 [];
return fs.readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isDirectory() && /^\d+$/.test(d.name))
.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'));
} catch {
return {};
}
};
/** @param {?number} want @returns {number} */
function resolveSession(want) {
const ns = listSessions();
if (!ns.length) fail('this run has no sessions -- create builds session one');
if (want != null) {
if (!ns.includes(want)) fail(`no such session: ${want} (this run has ${ns.join(', ')})`);
return want;
}
const live = ns.filter((x) => sessionMeta(x).phase === 'live');
if (live.length > 1) fail(`sessions ${live.join(' and ')} are both live -- corrupt state, fix by hand`);
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));
DB_PATH = path.join(d, 'db', 'memory.db');
CANON_DIR = path.join(d, 'canon');
LOG_DIR = path.join(d, 'log');
DUMPS_DIR = path.join(d, 'dumps');
}
setRunRoot(path.join(RUNS_DIR, RUN ?? ''));
if (RUN != null && cmd !== 'init') setSessionRoot(resolveSession(sessionOverride));
// the freeze ruling, enforced: which phases each mutating verb may
// touch. Ring edits are the dormancy window (live is unnecessary and
// 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'],
'status-set': ['dormant', 'live'], 'agenda-set': ['dormant', 'live'],
'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;
const phase = sessionMeta(SESS).phase ?? 'unmarked';
if (!allowed.includes(phase)) {
fail(`${verb} refused: session ${SESS} is ${phase} -- ${verb} is allowed while ${allowed.join(' / ')} (the freeze ruling)`);
}
}
const BACKDROP_TEMPLATE = `# Backdrop
(One to three paragraphs: what any inhabitant of this world knows -- the
place, the era, how things work here. Common knowledge, not what any
particular character learned. Never memory, never forgotten: it never
touches the rings and is always in the bundle.)
`;
const CARD_TEMPLATE = `# <name>
(Fill this in before session one. Five lines is plenty; freeform beats
complete. Blank fields are the player's to invent through play -- the
GM ratifies notable inventions afterward.)
- **Concept:** one line
- **Drives:** what they want, generally
- **Edges:** what they're good at
- **Flaws:** what gets in their way
- **Voice:** how they talk -- register, tics, what they'd never say
- **Doesn't know:** (optional) what's plausibly outside their world
Freeform notes:
`;
/** @returns {boolean} */
function recordsEnabled() {
try {
return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true;
} catch {
return false;
}
}
/** @returns {DatabaseSync} */
function openDb() {
if (!fs.existsSync(DB_PATH)) {
fail(`no database at ${rel(DB_PATH)} -- run: node tool/memory.mjs init`);
}
const db = new DatabaseSync(DB_PATH);
migrateStatusNames(db); // before the schema exec: renames must land before CREATE IF NOT EXISTS
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
return db;
}
// One normalizer brings any events table to the current schema
// (2026-11-14, GM: no legacy hauling -- renames are clean, old data
// migrates once): the column `window` -> `session`, the journal op
// values `paper-*` -> `status-*`, and the CHECK widened to the full
// op list. The rebuild copies through a check-free intermediate --
// 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 = /** @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 = /** @type {?{ sql: string }} */ (db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get());
if (!row) return;
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 {
db.exec(`CREATE TABLE events_mig (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session TEXT NOT NULL,
op TEXT NOT NULL,
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
)`);
db.exec('INSERT INTO events_mig SELECT * FROM events');
db.exec("UPDATE events_mig SET op = 'status-add' WHERE op = 'paper-add'");
db.exec("UPDATE events_mig SET op = 'status-drop' WHERE op = 'paper-drop'");
db.exec("UPDATE events_mig SET op = 'status-set' WHERE op = 'paper-set'");
db.exec('DROP TABLE events');
db.exec(`CREATE TABLE events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ${OPS}),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
)`);
db.exec('INSERT INTO events SELECT * FROM events_mig');
db.exec('DROP TABLE events_mig');
db.exec('CREATE INDEX IF NOT EXISTS events_session ON events (session)');
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`events rename migration failed: ${e.message}`);
}
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);
// generated views: the ring and status files are machine-written -- never
// 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 = /** @type {EntryRow[]} */ (db.prepare(
'SELECT * FROM entries WHERE ring = ? ORDER BY last_touched DESC, id DESC'
).all(ring));
const title = ring === 'a' ? 'what matters' : 'what stuck anyway';
const lines = [
`# Ring ${ring.toUpperCase()} -- ${title}`,
'',
];
if (rows.length === 0) lines.push('(empty -- nothing here yet)');
for (const r of rows) {
lines.push(`- [e${r.id}] [${r.type}] **${r.label}**${r.detail ? ` -- ${r.detail}` : '.'}`);
}
lines.push('');
const file = path.join(CANON_DIR, `ring-${ring}.md`);
fs.mkdirSync(CANON_DIR, { recursive: true });
fs.writeFileSync(file, lines.join('\n'));
return { file, count: rows.length };
}
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
function renderStatus(db) {
const rows = /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all());
const lines = [
'# Status',
'',
'The status is the player\'s -- stances and feelings; facts live in the rings.',
'',
];
if (!rows.length) lines.push('(a blank sheet -- fresh start)');
for (const r of rows) lines.push(`- ${r.descr}`);
lines.push('');
const file = path.join(CANON_DIR, 'status.md');
fs.mkdirSync(CANON_DIR, { recursive: true });
fs.writeFileSync(file, lines.join('\n'));
return { file, count: rows.length };
}
// 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 = [
'# Agenda -- what drives her',
'',
'The queue is the player\'s -- intentions, not facts; facts live in the rings.',
'',
];
if (!items.length) lines.push('(a clear head -- nothing queued)');
items.forEach((d, i) => lines.push(`- ${i}. ${d}`));
lines.push('');
const file = path.join(CANON_DIR, 'agenda.md');
fs.mkdirSync(CANON_DIR, { recursive: true });
fs.writeFileSync(file, lines.join('\n'));
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;
for (const ring of RINGS) {
const { file, count } = renderRing(db, ring);
if (talk) console.log(`${rel(file)} -- ${count} entries`);
}
const { file, count } = renderStatus(db);
if (talk) console.log(`${rel(file)} -- ${count} descriptions`);
const a = renderAgenda(db);
if (talk) console.log(`${rel(a.file)} -- ${a.count} queued`);
}
// 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.',
'-- one row per line; entries and events ordered by id; restore with: restore',
fs.readFileSync(SCHEMA_PATH, 'utf8').trim(),
'BEGIN TRANSACTION;',
];
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 /** @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 /** @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 /** @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 /** @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;', '');
const file = path.join(DUMPS_DIR, 'memory.sql');
fs.writeFileSync(file, L.join('\n'));
return file;
}
// 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(
'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)'
).run(ring, type, norm(label), norm(detail), now, now);
const id = Number(res.lastInsertRowid);
journal(db, win, 'insert', `e${id}`, reason);
return id;
}
// --- validation helpers (used by apply) -------------------------------------
/** @param {DatabaseSync} db */
function makeValidator(db) {
/** @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 = /** @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) {
errors.push(`${op}: e${id} is in ring ${row.ring}, expected ${expectRing}`);
}
if (seen.has(id)) errors.push(`e${id} appears in more than one operation (${seen.get(id)} and ${op})`);
else seen.set(id, op);
need(e.reason, `${op} (e${id}): reason`);
return row;
};
return { errors, need, asArray, ref };
}
// --- 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}`, '');
for (const r of rows) L.push(`- ${fmt(r)}`);
L.push('');
};
section('Insertions', applied.insert,
(e) => `[e${e.id}] -> ring ${e.ring.toUpperCase()} \u00b7 ${e.type} \u00b7 **${e.label}**${e.detail ? ` -- ${e.detail}` : ''} -- ${e.reason}`);
section('Touches', applied.touch, (t) => `[e${t.row.id}] **${t.row.label}** -- ${t.reason}`);
section('Promotions', applied.promote, (p) => `[e${p.row.id}] **${p.row.label}** -> ring A -- ${p.reason}`);
section('Demotions', applied.demote, (d) => `[e${d.row.id}] **${d.row.label}** -> ring B -- ${d.reason}`);
section('Rewords', applied.reword, (r) => `[e${r.row.id}] **${r.row.label}** -- now: ${r.detail} -- ${r.reason}`);
section('Archived (rings -> records)', applied.archive, (a) => `[r${a.rid}] [${a.row.type}] **${a.row.label}** <- [e${a.row.id}] -- ${a.reason}`);
section('Deletions (to cold storage)', applied.delete, (d) => `[e${d.row.id}] **${d.row.label}** -- ${d.reason}`);
section('Overflow (auto)', overflow, (o) => `[e${o.id}] ring ${o.from.toUpperCase()} -> ${o.to === 'cold' ? 'cold storage' : 'ring ' + o.to.toUpperCase()}`);
section('Inventions', mf.inventions ?? [], (s) => String(s));
section('Open questions', mf.open_questions ?? [], (s) => String(s));
return L.join('\n');
}
/** @param {string} manifestPath */
function cmdApply(manifestPath) {
const db = openDb();
/** @type {Manifest} */ let mf;
try {
mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (e) {
fail(`cannot read manifest ${manifestPath}: ${e.message}`);
}
const { errors, need, asArray, ref } = makeValidator(db);
need(mf.session, 'session');
need(mf.summary, 'summary');
if (typeof mf.session === 'string' && !/^[a-z0-9-]+$/i.test(mf.session)) {
errors.push('session must be a short slug (letters, digits, dashes)');
}
const logFile = mf.session ? path.join(LOG_DIR, `${mf.session}.md`) : null;
if (logFile && fs.existsSync(logFile)) {
errors.push(`${rel(logFile)} already exists -- delete it first if this is a re-run`);
}
const ins = asArray(mf.insert, 'insert');
const touch = asArray(mf.touch, 'touch');
const promote = asArray(mf.promote, 'promote');
const demote = asArray(mf.demote, 'demote');
const reword = asArray(mf.reword, 'reword');
const del = asArray(mf.delete, 'delete');
const rec = asArray(mf.record, 'record');
const arch = asArray(mf.archive, 'archive');
const inventions = asArray(mf.inventions, 'inventions');
const questions = asArray(mf.open_questions, 'open_questions');
if (arch.length && !recordsEnabled()) {
errors.push('this character keeps no records -- archive ops are unavailable (see the run\'s settings.json)');
}
if (rec.length) {
errors.push('filing is not yours -- record ops belong to the player at her desk (or the GM CLI); housekeeping is rings-only');
}
for (const [i, e] of ins.entries()) {
if (!RINGS.includes(e.ring)) errors.push(`insert[${i}].ring must be a|b`);
if (!TYPES.includes(e.type)) errors.push(`insert[${i}].type must be ${TYPES.join('|')}`);
need(e.label, `insert[${i}].label`);
if (e.detail !== undefined && typeof e.detail !== 'string') errors.push(`insert[${i}].detail must be a string`);
need(e.reason, `insert[${i}].reason`);
}
touch.forEach((e) => ref('touch', e, null));
promote.forEach((e) => ref('promote', e, 'b'));
demote.forEach((e) => ref('demote', e, 'a'));
reword.forEach((e) => {
const row = ref('reword', e, null);
if (row && !String(e.detail ?? '').trim()) errors.push(`reword (e${row.id}): detail is required`);
});
del.forEach((e) => ref('delete', e, null));
arch.forEach((e) => ref('archive', e, null));
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`); });
}
if (errors.length) {
console.error('manifest rejected -- nothing was applied:');
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');
/** @type {AppliedLog} */ const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], archive: [] };
/** @type {OverflowItem[]} */ const overflow = [];
db.exec('BEGIN');
try {
for (const e of ins) {
const id = insertEntry(db, {
ring: e.ring, type: e.type, label: e.label, detail: e.detail ?? '',
win: mf.session, reason: e.reason,
});
applied.insert.push({ id, ...e });
}
/** @param {number} id */
const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(today(), 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 = /** @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 = /** @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 = /** @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 = /** @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 = /** @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);
const rid = Number(res.lastInsertRowid);
db.prepare('DELETE FROM entries WHERE id = ?').run(id);
journal(db, mf.session, 'archive', `r${rid}`, e.reason);
applied.archive.push({ rid, row, reason: e.reason });
}
for (const e of del) {
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 });
}
// overflow: A spills to B first, then B spills to cold -- exact, by count
for (const ring of RINGS) {
const rows = /** @type {{ id: number }[]} */ (db.prepare(
'SELECT id FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC'
).all(ring));
const extra = rows.length - CAPS[ring];
for (let i = 0; i < extra; i++) {
const victim = rows[i];
const dest = ring === 'a' ? 'b' : 'cold';
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(dest, victim.id);
journal(db, mf.session, ring === 'a' ? 'demote' : 'evict', `e${victim.id}`, `ring ${ring.toUpperCase()} overflow (auto)`);
overflow.push({ id: victim.id, from: ring, to: dest });
}
}
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`transaction failed, rolled back: ${e.message}`);
}
fs.mkdirSync(LOG_DIR, { recursive: true });
fs.writeFileSync(logFile, renderLog(mf, applied, overflow));
const dumpFile = dumpDb(db);
// per-pass snapshot: the committed-truth successor now that runs are
// gitignored -- diffing consecutive snapshots reconstructs the session's
// operations for async review
const snapshot = path.join(DUMPS_DIR, `${mf.session}.sql`);
fs.copyFileSync(dumpFile, snapshot);
if (!AS_JSON) {
console.log(`applied [${RUN}] ${mf.session}: ` + [
applied.insert.length && `${applied.insert.length} inserted`,
applied.touch.length && `${applied.touch.length} touched`,
applied.promote.length && `${applied.promote.length} promoted`,
applied.demote.length && `${applied.demote.length} demoted`,
applied.reword.length && `${applied.reword.length} reworded`,
applied.archive.length && `${applied.archive.length} archived`,
applied.delete.length && `${applied.delete.length} deleted`,
overflow.length && `${overflow.length} overflow`,
].filter(Boolean).join(', '));
console.log(`log: ${rel(logFile)}`);
renderAll(db);
console.log(`dump: ${rel(dumpFile)} \u00b7 snapshot: ${rel(snapshot)}`);
} else {
renderAll(db);
}
}
// --- simple commands ---------------------------------------------------------
function cmdInit() {
if (listSessions().length) fail('this run already has sessions -- init builds session one of a fresh run');
const { db, dir } = buildSession1(RUN_ROOT);
setSessionRoot(1);
console.log(`initialized run '${RUN}': session one at ${rel(dir)}`);
dumpDb(db);
renderAll(db);
}
// build dormant session one of a run: the dirs, the db, the craft
// 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']) {
fs.mkdirSync(path.join(s1, d), { recursive: true });
}
const backdrop = path.join(s1, 'bundle', 'backdrop.md');
if (!fs.existsSync(backdrop)) fs.writeFileSync(backdrop, BACKDROP_TEMPLATE);
const card = path.join(s1, 'bundle', 'character.md');
if (!fs.existsSync(card)) fs.writeFileSync(card, CARD_TEMPLATE);
fs.writeFileSync(path.join(s1, 'session.json'), JSON.stringify({ phase: 'dormant', ready: true }, null, 2) + '\n');
const db = new DatabaseSync(path.join(s1, 'db', 'memory.db'));
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
return { db, dir: s1 };
}
// --- packages and runs --------------------------------------------------------
//
// A package is a preset: authored content only, no state. Packages
// come from two roots: system (repo, authored, read-only) and user
// (state/packages, saved from a run, published to everyone). A run is
// an instance: the package copied wholesale (the shared prompts
// included -- battery included, editable per run), plus all state.
// Creation is the one time a package is ever read; afterwards the run
// dir is the only truth. run.json records the lineage, the owner
// (multiuser), and an optional model override.
// where each package file lands in a new run: the craft is session
// one's bundle (session-specific from birth); identity (settings) and
// the notepad (gm.md) are the run's; the session-0 artifacts (her
// starting memories, her opening) are session one's own. handbook.md
// is repo craft, copied per run like the rest of the bundle.
// housekeeper.md is substrate-internal like invariants.md -- repo-fed
// at housekeeping time, never copied, never user-exposed; system.md
// and invariants.md are likewise repo-fed at assembly (opening+guards,
// substrate facts)
const PACKAGE_LAYOUT = {
'backdrop.md': 'bundle',
'character.md': 'bundle',
'memory.json': '',
'carryover.jsonl': '',
'settings.json': 'root',
'gm.md': 'root',
};
// 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, /** @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'));
} catch {
return null;
}
}
/** @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; }
};
/** @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 {
name,
origin,
...(origin === 'user' ? { owner: meta?.owner ?? null } : {}),
display: settings.name ?? name,
pc: settings.pc ?? null,
records: settings.records === true,
carryover: has('carryover.jsonl'), memory: has('memory.json'),
complete: has('backdrop.md') && has('character.md'),
};
}
function cmdPackages() {
/** @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 })) {
if (!d.isDirectory()) continue;
list.push(packageEntry(d.name, path.join(root, d.name), origin));
}
};
scan(PACKAGES_DIR, 'system');
scan(STATE_PACKAGES_DIR, 'user');
list.sort((a, b) => a.name.localeCompare(b.name));
if (AS_JSON) { console.log(JSON.stringify(list)); return; }
if (!list.length) { console.log('(no packages)'); return; }
for (const x of list) {
console.log(`${x.name}: ${x.display} [${x.origin}] -- records ${x.records ? 'on' : 'off'} \u00b7 carryover ${x.carryover ? 'yes' : 'no'} \u00b7 memory ${x.memory ? 'yes' : 'no'} \u00b7 backdrop+card ${x.complete ? 'ok' : 'MISSING'}`);
}
}
// run ids are anonymous: they carry no facts, so there is nothing to
// 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
if (!fs.existsSync(path.join(RUNS_DIR, id))) return id;
}
}
/** @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"]');
}
const pkgDir = packageDir(pkgName);
if (!pkgDir) fail(`no such package: ${pkgName} -- see: packages`);
pc = String(pc).trim();
// different runs of the same package require different pc names
if (fs.existsSync(RUNS_DIR)) {
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);
/** @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);
if (String(st.pc ?? '').toLowerCase() === pc.toLowerCase()) {
fail(`a run of '${pkgName}' named '${pc}' already exists: ${d.name}`);
}
}
}
const runId = anonId();
const runDir = path.join(RUNS_DIR, runId);
fs.mkdirSync(runDir, { recursive: true });
// the package copy lands where it lives from now on: the craft is
// session one's bundle, identity and the notepad are the run's, the
// session-0 artifacts are session one's own
const s1 = path.join(runDir, 'sessions', '1');
for (const [f, dest] of Object.entries(PACKAGE_LAYOUT)) {
const src = path.join(pkgDir, f);
if (!fs.existsSync(src)) continue;
const dst = dest === 'root' ? path.join(runDir, f) : path.join(s1, dest, f);
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.copyFileSync(src, dst);
}
const hb = path.join(ROOT, 'handbook.md');
if (fs.existsSync(hb)) {
fs.mkdirSync(path.join(s1, 'bundle'), { recursive: true });
fs.copyFileSync(hb, path.join(s1, 'bundle', 'handbook.md'));
}
// first-class identity lands in the settings copy: the pc name is
// this run's own; the display name defaults to the package's
const settings = readRunSettings(runDir);
settings.pc = pc;
settings.name = displayName?.trim() || settings.name || pkgName;
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
/** @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');
fs.mkdirSync(path.join(runDir, 'manifests'), { recursive: true });
setRunRoot(runDir); // views and dumps land inside the new run
buildSession1(runDir);
setSessionRoot(1);
// session-0's housekeeping: memory.json is a manifest -- the mock
// output of the session that never existed -- applied through the
// same path a real pass takes. An absent file is empty rings,
// listed honestly.
const mem = path.join(s1, 'memory.json');
if (fs.existsSync(mem)) {
cmdApply(mem);
} else {
const db = openDb();
renderAll(db);
dumpDb(db);
}
if (AS_JSON) { console.log(JSON.stringify({ id: runId, package: pkgName, name: settings.name, pc })); return; }
console.log(`created run '${runId}' -- ${runDisplay(pkgName, settings)}: ${rel(runDir)}`);
console.log(` session one is dormant \u00b7 memory ${fs.existsSync(mem) ? 'applied' : 'absent'} \u00b7 start it from setup`);
}
function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs -- create one: create <package> <pc-name>)'); return; }
/** @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
const runDir = path.join(RUNS_DIR, d.name);
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
found++;
let pkg = '?';
/** @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 ?? '?';
models = meta.models ?? null;
owner = meta.owner ?? null;
created = meta.created ?? null;
forked = meta.forked ?? null;
} catch {}
const st = readRunSettings(runDir);
const base = { id: d.name, package: pkg, models, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) };
// the fill reads the ACTIVE session's db (the live one, else the
// latest -- the dormant one during the review window)
const ns = listSessions(runDir);
const liveN = ns.find((x) => sessionMeta(x, runDir).phase === 'live');
const active = ns.length ? (liveN ?? ns[ns.length - 1]) : null;
const phase = active == null ? null : sessionMeta(active, runDir).phase ?? null;
const dbPath = active == null ? null : path.join(runDir, 'sessions', String(active), 'db', 'memory.db');
const ready = active == null ? null : sessionMeta(active, runDir).ready ?? null;
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'));
/** @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 || !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
// copies, published to every user of the deployment -- gm.md included,
// because saving is the act of publishing. Draft-only by ruling: a
// package is a starting point, never a snapshot -- continue-this-story
// 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)');
const ns = listSessions();
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');
}
/** @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;
}
const dst = path.join(STATE_PACKAGES_DIR, id);
fs.mkdirSync(dst, { recursive: true });
const s1 = path.join(RUN_ROOT, 'sessions', '1');
for (const [f, src] of [
['handbook.md', path.join(s1, 'bundle', 'handbook.md')],
['backdrop.md', path.join(s1, 'bundle', 'backdrop.md')],
['character.md', path.join(s1, 'bundle', 'character.md')],
['memory.json', path.join(s1, 'memory.json')],
['carryover.jsonl', path.join(s1, 'carryover.jsonl')],
['settings.json', path.join(RUN_ROOT, 'settings.json')],
['gm.md', path.join(RUN_ROOT, 'gm.md')],
]) {
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
}
const settingsPath = path.join(dst, 'settings.json');
/** @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
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
fs.writeFileSync(path.join(dst, 'package.json'), JSON.stringify({
owner: ownerOverride, created: today(),
}, null, 2) + '\n');
if (AS_JSON) {
console.log(JSON.stringify({ id, name, origin: 'user', owner: ownerOverride }));
return;
}
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');
/** @type {number} */ let id;
try {
id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' });
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(e.message);
}
console.log(`inserted [e${id}] -> ring ${ring.toUpperCase()}`);
renderAll(db);
dumpDb(db);
}
/** @param {string} idStr @param {?string} [reason] */
function cmdDelete(idStr, reason) {
const db = openDb();
const id = parseId(idStr);
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(/** @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 && /** @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(/** @type {string} */ (ring), /** @type {number} */ (id));
journal(db, 'gm', 'revive', `e${id}`, 'GM revive');
console.log(`[e${id}] **${row.label}** revived -> ring ${/** @type {string} */ (ring).toUpperCase()}`);
renderAll(db);
dumpDb(db);
}
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`);
if (fs.existsSync(DB_PATH) && !force) {
fail(`db already exists -- run with --force to overwrite it from the dump`);
}
if (fs.existsSync(DB_PATH)) fs.rmSync(DB_PATH);
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(dumpFile, 'utf8'));
// an old dump embeds its own old schema -- normalize before rendering:
// the renames first (the schema exec's CREATE IF NOT EXISTS would
// collide with a table awaiting rename), then the schema (creates
// tables the dump predates, e.g. agenda). Old dumps self-heal
// through the same path as openDb.
migrateStatusNames(db);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
console.log(`restored ${rel(DB_PATH)} from ${rel(dumpFile)}`);
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)');
if (!kind?.trim() || !label?.trim()) fail('usage: file <kind> "Label" "detail"');
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(norm(kind), norm(label), norm(detail ?? ''), today());
const rid = Number(res.lastInsertRowid);
journal(db, AS_GM ? 'gm' : 'pc', 'record', `r${rid}`, reason ?? (AS_GM ? 'GM filed ahead of play' : 'player filing'));
console.log(`filed [r${rid}] [${norm(kind)}] **${norm(label)}**`);
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 && /** @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), /** @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);
console.log(`amended [r${rid}] **${row.label}** -- ${norm(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 && /** @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(/** @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',
JSON.stringify({ id: row.id, kind: row.kind, label: row.label, detail: row.detail, created: row.created }));
console.log(`discarded [r${rid}] **${row.label}**`);
dumpDb(db);
}
// --- her status (the status tier) -------------------------------------------------
//
// Freeform descriptions, no keys, no baselines. The player mutates via
// <lost>/<gained> deltas in its own turns -- exact match, non-blocking,
// misses relayed back to the model as a <conflict> block by the caller.
// The GM overrides out-of-band with status-set. Descriptions never contain
// commas: both the delta lists and the <status> block are comma-separated.
/** @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);
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]));
/** @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;
}
const win = AS_GM ? 'gm' : 'pc';
db.exec('BEGIN');
try {
for (const item of lost) {
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);
applied.lost.push(item);
} else {
applied.conflicts.push(`not in her status: ${item}`);
}
}
for (const item of gained) {
// already listed is a no-op, not a conflict
if (db.prepare('SELECT 1 FROM status WHERE descr = ?').get(item)) continue;
const res = db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(item, today());
journal(db, win, 'status-add', `p${Number(res.lastInsertRowid)}`, 'delta');
applied.gained.push(item);
}
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`status-apply failed, rolled back: ${e.message}`);
}
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
renderAll(db);
dumpDb(db);
}
// 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);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM status').run();
for (const d of clean) {
db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(d, today());
}
journal(db, win, 'status-set', 'p', reason, JSON.stringify(prior));
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`status-set failed, rolled back: ${e.message}`);
}
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');
console.log(JSON.stringify(clean));
renderAll(db);
dumpDb(db);
}
// --- the agenda (intentions tier) ---------------------------------------------
//
// The hot queue of what drives her: goals she is working towards right
// now -- intentions, never states (those are the status's). Fixed cap
// (a dial); id order IS queue order -- adds land at the top in written
// order, overflow evicts the bottom, a recency ring buffer for free.
// The player mutates via <add>/<drop> in its own turns: drops are
// 0-based indexes against the agenda as last rendered, adds are
// comma-separated. The GM overrides whole-list with agenda-set.
/** @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();
/** @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]));
/** @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));
}
if (!adds.length && !drops.length) {
console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) }));
return;
}
const win = AS_GM ? 'gm' : 'pc';
db.exec('BEGIN');
try {
// order of execution (invariants.md): received block -> drop -> add
// -> next block. Indexes resolve against the same snapshot, so a
// multi-drop never shifts under itself.
const snapshot = agendaList(db);
/** @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);
if (i >= snapshot.length) {
conflicts.push(`agenda has no item at index ${i}${snapshot.length ? '' : ' -- it is empty'}`);
continue;
}
kill.push(i);
}
for (const i of [...new Set(kill)].sort((a, b) => b - a)) {
const descr = snapshot[i];
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);
}
// adds land at the top in written order (first item = the top slot):
// insert in reverse, id order does the rest. Already queued is a
// no-op, not a conflict -- reorder is drop-then-add, by design.
// The report keeps written order (the reverse loop is storage mechanics).
const fresh = [];
for (const item of [...new Set(adds)].reverse()) {
if (db.prepare('SELECT 1 FROM agenda WHERE descr = ?').get(item)) continue;
const res = db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(item, today());
journal(db, win, 'agenda-add', `a${Number(res.lastInsertRowid)}`, 'delta');
fresh.push(item);
}
added.push(...fresh.reverse());
// 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 = /** @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]);
}
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`agenda-apply failed, rolled back: ${e.message}`);
}
console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) }));
renderAll(db);
dumpDb(db);
}
// 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);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM agenda').run();
for (const d of [...clean].reverse()) { // first item = the top of the queue
db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(d, today());
}
journal(db, win, 'agenda-set', 'agenda', reason, JSON.stringify(prior));
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`agenda-set failed, rolled back: ${e.message}`);
}
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');
console.log(JSON.stringify(clean));
renderAll(db);
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 = /** @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 = 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 && /** @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');
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(/** @type {string} */ (ring), type, row.label, row.detail, row.created, today());
const eid = Number(res.lastInsertRowid);
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 ${/** @type {string} */ (ring).toUpperCase()} as [e${eid}]`);
renderAll(db);
dumpDb(db);
}
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: Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0),
recordsEnabled: recordsEnabled(),
status: statusList(db),
agenda: agendaList(db),
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] = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
if (ring !== 'cold') {
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));
}
}
console.log(JSON.stringify(out));
return;
}
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
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 = 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 = /** @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));
for (const r of old) console.log(` sinking: [e${r.id}] ${r.last_touched} **${r.label}**`);
}
}
}
// --- dispatch ----------------------------------------------------------------
// 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 ?? '');
switch (cmd) {
case 'packages': cmdPackages(); break;
case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2], args[3]); break;
case 'save-package': cmdSavePackage(args[0]); break;
case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break;
case 'apply': args[0] ? cmdApply(args[0]) : fail('usage: apply <manifest.json>'); break;
case 'insert': (args.length >= 3) ? gmOp(args[0], args[1], args[2], args[3] ?? '') : fail('usage: insert <a|b> <type> "Label" "detail"'); break;
case 'delete': (args.length >= 1) ? cmdDelete(args[0], args[1]) : fail('usage: delete <id> "reason"'); break;
case 'revive': (args.length >= 1) ? cmdRevive(args[0], args[1]) : fail('usage: revive <id> [a|b]'); break;
case 'file': (args.length >= 2) ? cmdFile(args[0], args[1], args[2] ?? '', args[3]) : fail('usage: file <kind> "Label" "detail" ["reason"]'); break;
case 'amend': (args.length >= 2) ? cmdAmend(args[0], args[1]) : fail('usage: amend <rid> "new detail"'); break;
case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break;
case 'status': cmdStatus(); break;
case 'status-apply': (args.length >= 1) ? cmdStatusApply(args.join(' ')) : fail('usage: status-apply "<turn text>"'); break;
case 'status-set': cmdStatusSet(args); break; // no args = clear the status (a legitimate GM override)
case 'agenda': cmdAgenda(); break;
case 'agenda-apply': (args.length >= 1) ? cmdAgendaApply(args.join(' ')) : fail('usage: agenda-apply "<turn text>"'); break;
case 'agenda-set': cmdAgendaSet(args); break; // no args = clear the agenda
case 'pick': cmdPick(args); break;
case 'search': cmdSearch(args); break;
case 'unarchive': (args.length >= 1) ? cmdUnarchive(args[0], args[1]) : fail('usage: unarchive <rid> [a|b]'); break;
case 'report': cmdReport(); break;
case 'dump': cmdDump(); break;
case 'restore': cmdRestore(FORCE); break;
default:
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|insert|delete|revive|file|amend|discard|search|unarchive|status|status-apply|status-set|agenda|agenda-apply|agenda-set|pick|dump|restore|report>');
process.exit(1);
}