spa modules and terminology: app.mjs split into flat es modules (router lifecycle, shared widgets, views own their state), mock smoke in test/; DICTIONARY.md rules the terms, four renames swept clean through the machinery - paper->status (run summary command is report now), window->session, wrap->housekeeping, context window->contwin; no dual-accepts by ruling, old data migrates once in the clerk (restore self-heals old dumps)
This commit is contained in:
+122
-92
@@ -23,7 +23,7 @@
|
||||
// (the low-level primitive under create)
|
||||
// seed [--force] [file] one-time pre-story migration; applies
|
||||
// lazily at a fresh run's first
|
||||
// window-open (the server calls it)
|
||||
// session-open (the server calls it)
|
||||
// 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
|
||||
@@ -35,13 +35,13 @@
|
||||
// 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
|
||||
// paper the paper, as JSON (the status tier)
|
||||
// paper-apply "<turn text>" apply <lost>/<gained> deltas from a player
|
||||
// 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 / paper)
|
||||
// paper-set "descr" ... GM override: replace the whole paper
|
||||
// (lost / gained / conflicts / status)
|
||||
// status-set "descr" ... GM override: replace the whole status
|
||||
// (no descrs = clear it)
|
||||
// paper-ingest <file> read a file's <status> block into the paper
|
||||
// status-ingest <file> read a file's <status> block into her status
|
||||
// (turn-0 at new-game)
|
||||
// agenda the agenda, as JSON (the intentions tier)
|
||||
// agenda-apply "<turn text>" apply <add>/<drop> deltas from a player
|
||||
@@ -57,7 +57,7 @@
|
||||
// restore --force rebuild the db from dumps/memory.sql
|
||||
// commands take --run <id> (a run under runs/); state is per-deployment.
|
||||
//
|
||||
// status counts, caps, the paper, what's sinking
|
||||
// status counts, caps, the status, what's sinking
|
||||
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
@@ -135,7 +135,7 @@ touches the rings and is always in the bundle.)
|
||||
|
||||
const CARD_TEMPLATE = `# <name>
|
||||
|
||||
(Fill this in before window one. Five lines is plenty; freeform beats
|
||||
(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.)
|
||||
|
||||
@@ -162,39 +162,62 @@ function openDb() {
|
||||
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'));
|
||||
migrateEventsCheck(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
// the events CHECK names every legal op; a db opened before the agenda
|
||||
// carries the narrower list and would reject agenda journaling. SQLite
|
||||
// cannot alter a CHECK in place, so this rebuilds events once — the
|
||||
// table is append-only, the copy is exact. (Mirrors db/schema.sql.)
|
||||
function migrateEventsCheck(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.)
|
||||
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);
|
||||
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();
|
||||
if (!row || row.sql.includes('agenda-add')) return;
|
||||
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
|
||||
if (!row) return;
|
||||
const staleOps = db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get().n > 0;
|
||||
if (!staleOps && row.sql.includes("'status-add'")) return;
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.exec(`CREATE TABLE events_new (
|
||||
db.exec(`CREATE TABLE events_mig (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
window TEXT NOT NULL,
|
||||
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_new SELECT * FROM events');
|
||||
db.exec('DROP TABLE events');
|
||||
db.exec('ALTER TABLE events_new RENAME TO events');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS events_window ON events (window)');
|
||||
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 migration failed: ${e.message}`);
|
||||
fail(`events rename migration failed: ${e.message}`);
|
||||
}
|
||||
if (!QUIET) console.log(`(migrated: events journal widened for the agenda ops — ${rel(DB_PATH)})`);
|
||||
if (!QUIET) console.log(`(migrated: events journal to the current names — ${rel(DB_PATH)})`);
|
||||
}
|
||||
|
||||
const parseId = (s) => {
|
||||
@@ -210,7 +233,7 @@ const parseRid = (s) => {
|
||||
};
|
||||
|
||||
const journal = (db, win, op, target, reason, prior = '') =>
|
||||
db.prepare('INSERT INTO events (window, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
|
||||
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
|
||||
@@ -238,11 +261,11 @@ function renderRing(db, ring) {
|
||||
}
|
||||
|
||||
function renderStatus(db) {
|
||||
const rows = db.prepare('SELECT * FROM paper ORDER BY id').all();
|
||||
const rows = db.prepare('SELECT * FROM status ORDER BY id').all();
|
||||
const lines = [
|
||||
'# Status — her paper',
|
||||
'# Status',
|
||||
'',
|
||||
'The paper is the player\'s — stances and feelings; facts live in the rings.',
|
||||
'The status is the player\'s — stances and feelings; facts live in the rings.',
|
||||
'',
|
||||
];
|
||||
if (!rows.length) lines.push('(a blank sheet — fresh start)');
|
||||
@@ -301,14 +324,14 @@ function dumpDb(db) {
|
||||
for (const r of 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 paper ORDER BY id').all()) {
|
||||
L.push(`INSERT INTO paper VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
|
||||
for (const r of 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()) {
|
||||
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()) {
|
||||
L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
|
||||
L.push(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
|
||||
}
|
||||
L.push('COMMIT;', '');
|
||||
const file = path.join(DUMPS_DIR, 'memory.sql');
|
||||
@@ -360,7 +383,7 @@ function makeValidator(db) {
|
||||
// --- apply ------------------------------------------------------------------
|
||||
|
||||
function renderLog(mf, applied, overflow) {
|
||||
const L = [`# ${mf.window}`, '', mf.summary, ''];
|
||||
const L = [`# ${mf.session}`, '', mf.summary, ''];
|
||||
const section = (title, rows, fmt) => {
|
||||
if (!rows.length) return;
|
||||
L.push(`## ${title}`, '');
|
||||
@@ -401,7 +424,7 @@ function cmdSeed(force, seedPathArg) {
|
||||
const records = sf.records ?? [];
|
||||
if (!Array.isArray(entries)) { errors.push('entries must be an array'); }
|
||||
if (sf.status !== undefined) {
|
||||
errors.push('status no longer seeds — the initial paper rides turn-0\'s <status> block, ingested at new-game (paper-ingest)');
|
||||
errors.push('status no longer seeds — the initial status rides turn-0\'s <status> block, ingested at new-game (status-ingest)');
|
||||
}
|
||||
if (!Array.isArray(records)) { errors.push('records must be an array'); }
|
||||
for (const [i, e] of (Array.isArray(entries) ? entries : []).entries()) {
|
||||
@@ -457,12 +480,12 @@ function cmdApply(manifestPath) {
|
||||
}
|
||||
|
||||
const { errors, need, asArray, ref } = makeValidator(db);
|
||||
need(mf.window, 'window');
|
||||
need(mf.session, 'session');
|
||||
need(mf.summary, 'summary');
|
||||
if (typeof mf.window === 'string' && !/^[a-z0-9-]+$/i.test(mf.window)) {
|
||||
errors.push('window must be a short slug (letters, digits, dashes)');
|
||||
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.window ? path.join(LOG_DIR, `${mf.window}.md`) : null;
|
||||
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`);
|
||||
}
|
||||
@@ -519,7 +542,7 @@ function cmdApply(manifestPath) {
|
||||
for (const e of ins) {
|
||||
const id = insertEntry(db, {
|
||||
ring: e.ring, type: e.type, label: e.label, detail: e.detail ?? '',
|
||||
win: mf.window, reason: e.reason,
|
||||
win: mf.session, reason: e.reason,
|
||||
});
|
||||
applied.insert.push({ id, ...e });
|
||||
}
|
||||
@@ -528,25 +551,25 @@ function cmdApply(manifestPath) {
|
||||
for (const e of touch) {
|
||||
const id = parseId(e.id);
|
||||
touchDate(id);
|
||||
journal(db, mf.window, 'touch', `e${id}`, e.reason);
|
||||
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);
|
||||
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
|
||||
journal(db, mf.window, 'promote', `e${id}`, e.reason);
|
||||
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);
|
||||
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
|
||||
journal(db, mf.window, 'demote', `e${id}`, e.reason);
|
||||
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);
|
||||
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), today(), id);
|
||||
journal(db, mf.window, 'reword', `e${id}`, e.reason);
|
||||
journal(db, mf.session, 'reword', `e${id}`, e.reason);
|
||||
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
|
||||
}
|
||||
for (const e of arch) {
|
||||
@@ -556,13 +579,13 @@ function cmdApply(manifestPath) {
|
||||
.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.window, 'archive', `r${rid}`, e.reason);
|
||||
journal(db, mf.session, 'archive', `r${rid}`, e.reason);
|
||||
applied.archive.push({ rid, row, reason: e.reason });
|
||||
}
|
||||
for (const e of del) {
|
||||
const id = parseId(e.id);
|
||||
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
|
||||
journal(db, mf.window, 'delete', `e${id}`, e.reason);
|
||||
journal(db, mf.session, 'delete', `e${id}`, e.reason);
|
||||
applied.delete.push({ row: fetch(id), reason: e.reason });
|
||||
}
|
||||
|
||||
@@ -576,7 +599,7 @@ function cmdApply(manifestPath) {
|
||||
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.window, ring === 'a' ? 'demote' : 'evict', `e${victim.id}`, `ring ${ring.toUpperCase()} overflow (auto)`);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -590,12 +613,12 @@ function cmdApply(manifestPath) {
|
||||
fs.mkdirSync(LOG_DIR, { recursive: true });
|
||||
fs.writeFileSync(logFile, renderLog(mf, applied, overflow));
|
||||
const dumpFile = dumpDb(db);
|
||||
// per-wrap snapshot: the committed-truth successor now that runs are
|
||||
// gitignored — diffing consecutive snapshots reconstructs the window's
|
||||
// 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.window}.sql`);
|
||||
const snapshot = path.join(DUMPS_DIR, `${mf.session}.sql`);
|
||||
fs.copyFileSync(dumpFile, snapshot);
|
||||
console.log(`applied [${RUN}] ${mf.window}: ` + [
|
||||
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`,
|
||||
@@ -641,7 +664,7 @@ function cmdInit() {
|
||||
const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md'];
|
||||
// battery included, copied per run and then the run's to edit: the craft
|
||||
// tier. housekeeper.md is substrate-internal like invariants.md —
|
||||
// repo-fed at wrap time, never copied, never user-exposed; system.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 SHARED_PROMPTS = ['handbook.md'];
|
||||
@@ -769,7 +792,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
|
||||
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
|
||||
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(` seed rides the copy (${fs.existsSync(path.join(runDir, 'seed.json')) ? 'present' : 'absent'}), editable until the first window-open applies it`);
|
||||
console.log(` seed rides the copy (${fs.existsSync(path.join(runDir, 'seed.json')) ? 'present' : 'absent'}), editable until the first session-open applies it`);
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
@@ -909,6 +932,13 @@ function cmdRestore(force = false) {
|
||||
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);
|
||||
}
|
||||
@@ -955,15 +985,15 @@ function cmdDiscard(ridStr, reason) {
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// --- the paper (status tier) -------------------------------------------------
|
||||
// --- 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 paper-set. Descriptions never contain
|
||||
// The GM overrides out-of-band with status-set. Descriptions never contain
|
||||
// commas: both the delta lists and the <status> block are comma-separated.
|
||||
|
||||
const paperList = (db) => db.prepare('SELECT descr FROM paper ORDER BY id').all().map((r) => r.descr);
|
||||
const statusList = (db) => 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
|
||||
@@ -971,11 +1001,11 @@ const splitDescrs = (s) =>
|
||||
String(s ?? '').split('\n').flatMap((line) =>
|
||||
line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean);
|
||||
|
||||
function cmdPaper() {
|
||||
console.log(JSON.stringify(paperList(openDb())));
|
||||
function cmdStatus() {
|
||||
console.log(JSON.stringify(statusList(openDb())));
|
||||
}
|
||||
|
||||
function cmdPaperApply(text) {
|
||||
function cmdStatusApply(text) {
|
||||
const db = openDb();
|
||||
const lost = [];
|
||||
const gained = [];
|
||||
@@ -983,76 +1013,76 @@ function cmdPaperApply(text) {
|
||||
for (const m of String(text ?? '').matchAll(/<gained>([\s\S]*?)<\/gained>/g)) gained.push(...splitDescrs(m[1]));
|
||||
const applied = { lost: [], gained: [], conflicts: [] };
|
||||
if (!lost.length && !gained.length) {
|
||||
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
|
||||
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 = db.prepare('SELECT * FROM paper WHERE descr = ?').get(item);
|
||||
const row = db.prepare('SELECT * FROM status WHERE descr = ?').get(item);
|
||||
if (row) {
|
||||
db.prepare('DELETE FROM paper WHERE id = ?').run(row.id);
|
||||
journal(db, win, 'paper-drop', `p${row.id}`, 'delta', row.descr);
|
||||
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 on her paper: ${item}`);
|
||||
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 paper WHERE descr = ?').get(item)) continue;
|
||||
const res = db.prepare('INSERT INTO paper (descr, added) VALUES (?, ?)').run(item, today());
|
||||
journal(db, win, 'paper-add', `p${Number(res.lastInsertRowid)}`, 'delta');
|
||||
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(`paper-apply failed, rolled back: ${e.message}`);
|
||||
fail(`status-apply failed, rolled back: ${e.message}`);
|
||||
}
|
||||
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
|
||||
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// whole-paper replace (GM override, turn-0 ingestion); the journal keeps
|
||||
// the full prior paper so turn surgery can compensate mechanically
|
||||
function setPaper(db, items, reason, win) {
|
||||
// whole-status replace (GM override, turn-0 ingestion); the journal keeps
|
||||
// the full prior status so turn surgery can compensate mechanically
|
||||
function setStatus(db, items, reason, win) {
|
||||
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
||||
const prior = paperList(db);
|
||||
const prior = statusList(db);
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.prepare('DELETE FROM paper').run();
|
||||
db.prepare('DELETE FROM status').run();
|
||||
for (const d of clean) {
|
||||
db.prepare('INSERT INTO paper (descr, added) VALUES (?, ?)').run(d, today());
|
||||
db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(d, today());
|
||||
}
|
||||
journal(db, win, 'paper-set', 'paper', reason, JSON.stringify(prior));
|
||||
journal(db, win, 'status-set', 'p', reason, JSON.stringify(prior));
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`paper-set failed, rolled back: ${e.message}`);
|
||||
fail(`status-set failed, rolled back: ${e.message}`);
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
function cmdPaperSet(items) {
|
||||
function cmdStatusSet(items) {
|
||||
const db = openDb();
|
||||
const clean = setPaper(db, items, AS_GM ? 'GM override' : 'paper set', AS_GM ? 'gm' : 'pc');
|
||||
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc');
|
||||
console.log(JSON.stringify(clean));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
function cmdPaperIngest(filePath) {
|
||||
function cmdStatusIngest(filePath) {
|
||||
const p = path.resolve(filePath ?? '');
|
||||
if (!fs.existsSync(p)) fail(`no such file: ${filePath}`);
|
||||
const blocks = [...fs.readFileSync(p, 'utf8').matchAll(/<status>([\s\S]*?)<\/status>/g)];
|
||||
if (!blocks.length) fail(`no <status> block in ${filePath}`);
|
||||
const items = splitDescrs(blocks[blocks.length - 1][1]);
|
||||
const db = openDb();
|
||||
setPaper(db, items, `ingested from ${path.basename(p)}`, 'seed');
|
||||
console.log(JSON.stringify(paperList(db)));
|
||||
setStatus(db, items, `ingested from ${path.basename(p)}`, 'seed');
|
||||
console.log(JSON.stringify(statusList(db)));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
@@ -1060,7 +1090,7 @@ function cmdPaperIngest(filePath) {
|
||||
// --- the agenda (intentions tier) ---------------------------------------------
|
||||
//
|
||||
// The hot queue of what drives her: goals she is working towards right
|
||||
// now — intentions, never states (those are the paper's). Fixed cap
|
||||
// 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
|
||||
@@ -1204,14 +1234,14 @@ function cmdUnarchive(ridStr, ring = 'b') {
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
function cmdStatus() {
|
||||
function cmdReport() {
|
||||
const db = openDb();
|
||||
if (AS_JSON) {
|
||||
const out = {
|
||||
run: RUN,
|
||||
records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n,
|
||||
recordsEnabled: recordsEnabled(),
|
||||
paper: paperList(db),
|
||||
status: statusList(db),
|
||||
agenda: agendaList(db),
|
||||
events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n,
|
||||
rings: {},
|
||||
@@ -1231,9 +1261,9 @@ function cmdStatus() {
|
||||
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
|
||||
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
|
||||
console.log(`records: ${nr}`);
|
||||
const paper = paperList(db);
|
||||
console.log(`paper: ${paper.length ? '' : '(a blank sheet)'}`);
|
||||
for (const d of paper) console.log(` - ${d}`);
|
||||
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 cap = CAPS[ring] ?? '∞';
|
||||
@@ -1264,20 +1294,20 @@ switch (cmd) {
|
||||
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 'paper': cmdPaper(); break;
|
||||
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); break;
|
||||
case 'paper-set': cmdPaperSet(args); break; // no args = clear the paper (a legitimate GM override)
|
||||
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); 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 'status-ingest': (args.length === 1) ? cmdStatusIngest(args[0]) : fail('usage: status-ingest <file>'); break;
|
||||
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 'status': cmdStatus(); 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|paper|paper-apply|paper-set|paper-ingest|agenda|agenda-apply|agenda-set|pick|dump|restore|status>');
|
||||
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|status-ingest|agenda|agenda-apply|agenda-set|pick|dump|restore|report>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user