substrate: paper model in the clerk, preset/run split, harness decisions

- clerk phase 0: the paper replaces key/value status - a description set with exact-match lost/gained delta apply (paper-apply), non-blocking, misses relayed back as conflict strings; paper / paper-set (GM override) / paper-ingest (a file's status block at new-game); amend and discard journal prior content and the paper ops journal what they replace (events.prior, the saga rule); seed rejects a status key loudly. Smoke-tested end to end
- preset/run split: packages are presets (authored content only - the six state dirs are gone from both), runs are per-deployment instances under runs/ (gitignored); create <package> <run-id> copies the package wholesale (shared prompts included, run.json lineage plus optional model override) and inits state; --run addresses runs; packages and runs list them; config.json names the default package. The seed applies lazily at a fresh run's first window-open
- bridge retired before ever going live: bridge.json became server.json (bind, endpoint, models, contextWindow, params - steal #4), example committed, bridge.mjs stays as the loop donor until server mock-parity
- prelude.md renamed turn-0.md (GM); mechanical feeders, pink ice as licensed corpo firewall, slop section, Pinky treatment pinned (GM)
- harness decisions (ROADMAP The harness): stated goal - a usable RP harness, clone-and-run or invited instance, key on the backend, no secrets in the repo; repo ships code and authored content only; copy-at-creation, editable everything, discipline on the GM; per-run model selection with an upstream models listing; audit as per-wrap dump snapshots inside the run (commit-per-wrap retired); zero-dep stack (#4 resolved, #7 dissolved with the bridge, #21 by default)
- system.md split ruled (#20): substrate facts / per-project guards / per-run craft, hard limits in the craft copy; name call resolved - keep Rell (#19a)
- docs: README gains the goal and deployment model, booting rewritten for the create flow; ROADMAP phasing 0-1 done; HANDOFF and the decision queue current
This commit is contained in:
2026-11-13 23:40:33 +00:00
parent 7ed729e294
commit 530170224f
29 changed files with 772 additions and 538 deletions
+238 -126
View File
@@ -7,10 +7,19 @@
// canon/ is a generated view (never edit by hand)
//
// commands:
// runs list runs and their fill levels
// init create the run's database and stubs
// seed [--force] [file] one-time pre-story migration (see README)
// render write canon/ring-a.md and canon/ring-b.md
// packages list packages (presets) and their flags
// runs list runs (instances) and their fill levels
// create <package> <run-id> create a run: copy the package wholesale
// (shared prompts included — battery
// included), init the db, render the views.
// From then on the run dir is the only
// truth; the package is never read again.
// init create the run's database and stubs
// (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)
// 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
@@ -21,17 +30,20 @@
// 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
// set <key> "value" the PC declares an excursion (--gm to override)
// norm <key> "baseline" the PC adopts/shifts a baseline (growth)
// clear <key> excursion ends — back to baseline
// unset <key> the PC drops a field from her paper
// paper the paper, as JSON (the status tier)
// paper-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
// paper-ingest <file> read a file's <status> block into the paper
// (turn-0 at new-game)
// 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 <name>; the default comes from config.json {"run": "..."}.
// commands take --run <id> (a run under runs/); state is per-deployment.
//
// status counts, caps, and what's sinking
// status counts, caps, the paper, what's sinking
import { DatabaseSync } from 'node:sqlite';
import fs from 'node:fs';
@@ -40,8 +52,8 @@ 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 CONFIG_PATH = path.join(ROOT, 'config.json');
const PACKAGES_DIR = path.join(ROOT, 'packages');
const RUNS_DIR = path.join(ROOT, 'runs');
// dials — retune freely
const CAPS = { a: 500, b: 3000 };
@@ -51,7 +63,7 @@ const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models
const fail = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
const rel = (p) => path.relative(ROOT, p).replaceAll('\\', '/');
// flags: --run <name> beats config.json {"run": "..."}; --gm attributes the op to the GM
// flags: --run <name> beats everything; --gm attributes the op to the GM
const argv = process.argv.slice(2);
const runIdx = argv.indexOf('--run');
let runOverride = null;
@@ -67,28 +79,26 @@ const QUIET = argv.includes('--quiet');
for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) argv.splice(i, 1);
const [cmd, ...args] = argv;
function resolveRun() {
if (runOverride) return runOverride;
if (fs.existsSync(CONFIG_PATH)) {
try {
const r = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')).run;
if (r) return r;
} catch {}
}
return null;
// 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> <run-id>');
}
const RUN = (cmd === 'runs' || cmd === 'pick') ? null : resolveRun();
if (cmd !== 'runs' && cmd !== 'pick' && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
fail('no run specified — use --run <name> or {"run":"name"} in config.json');
// per-run paths: set once from --run, and re-pointed by create (which
// builds a run dir before any view is written)
let RUN_ROOT, DB_PATH, CANON_DIR, LOG_DIR, DUMPS_DIR, SETTINGS_PATH;
function setRunRoot(dir) {
RUN_ROOT = dir;
DB_PATH = path.join(RUN_ROOT, 'db', 'memory.db');
CANON_DIR = path.join(RUN_ROOT, 'canon');
LOG_DIR = path.join(RUN_ROOT, 'log');
DUMPS_DIR = path.join(RUN_ROOT, 'dumps');
SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json');
}
const RUN_ROOT = path.join(PACKAGES_DIR, RUN ?? '');
const DB_PATH = path.join(RUN_ROOT, 'db', 'memory.db');
const CANON_DIR = path.join(RUN_ROOT, 'canon');
const LOG_DIR = path.join(RUN_ROOT, 'log');
const DUMPS_DIR = path.join(RUN_ROOT, 'dumps');
const SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json');
setRunRoot(path.join(RUNS_DIR, RUN ?? ''));
const BACKDROP_TEMPLATE = `<!-- The world as everyone in it knows it: public knowledge, general backdrop.
Immutable for play purposes — never memory, never forgotten, never
@@ -146,9 +156,9 @@ const parseRid = (s) => {
return m ? Number(m[1]) : null;
};
const journal = (db, win, op, target, reason) =>
db.prepare('INSERT INTO events (window, op, target, reason) VALUES (?, ?, ?, ?)')
.run(win, op, target, norm(reason));
const journal = (db, win, op, target, reason, prior = '') =>
db.prepare('INSERT INTO events (window, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
.run(win, op, target, norm(reason), prior);
function renderRing(db, ring) {
const rows = db.prepare(
@@ -176,21 +186,20 @@ function renderRing(db, ring) {
}
function renderStatus(db) {
const rows = db.prepare('SELECT * FROM status ORDER BY updated DESC, key').all();
const rows = db.prepare('SELECT * FROM paper ORDER BY id').all();
const lines = [
'<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->',
"<!-- The player's own piece of paper: baselines are the defaults she plays to; -->",
'<!-- excursions are declared and cleared. Stances are feelings; facts live in the rings. -->',
"<!-- Her piece of paper: descriptions of her immediate situation (the status tier). -->",
'<!-- The player mutates it with <lost>/<gained> deltas in its turns; the GM overrides -->',
'<!-- out-of-band. Inspection view only: the paper rides every GM turn as a <status> -->',
'<!-- block (re-read per turn), never in the opening bundle. Stances are feelings; -->',
'<!-- facts live in the rings. -->',
'',
'# Status',
'# Status — her paper',
'',
];
if (!rows.length) lines.push('(nothing set — fresh start)');
for (const r of rows) {
const shown = r.value || r.normal;
const ex = r.value && r.value !== r.normal && r.normal ? ` *(norm: ${r.normal})*` : '';
lines.push(`- **${r.key}:** ${shown}${ex}`);
}
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 });
@@ -204,7 +213,7 @@ function renderAll(db) {
if (!QUIET) console.log(`${rel(file)} — ${count} entries`);
}
const { file, count } = renderStatus(db);
if (!QUIET) console.log(`${rel(file)} — ${count} keys`);
if (!QUIET) console.log(`${rel(file)} — ${count} descriptions`);
}
// canonical serialization: id-ordered, one row per line, restorable SQL.
@@ -224,11 +233,11 @@ 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 status ORDER BY key').all()) {
L.push(`INSERT INTO status VALUES (${q(r.key)},${q(r.normal)},${q(r.value)},${q(r.updated)});`);
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 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)});`);
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('COMMIT;', '');
const file = path.join(DUMPS_DIR, 'memory.sql');
@@ -315,10 +324,11 @@ function cmdSeed(force, seedPathArg) {
const errors = [];
if (!sf.date || !/^\d{4}-\d{2}-\d{2}$/.test(sf.date)) errors.push('date must be YYYY-MM-DD (the story-start date)');
const entries = sf.entries ?? [];
const status = sf.status ?? {};
const records = sf.records ?? [];
if (!Array.isArray(entries)) { errors.push('entries must be an array'); }
if (typeof status !== 'object' || status === null || Array.isArray(status)) { errors.push('status must be an object of key: value'); }
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)');
}
if (!Array.isArray(records)) { errors.push('records must be an array'); }
for (const [i, e] of (Array.isArray(entries) ? entries : []).entries()) {
if (!RINGS.includes(e.ring)) errors.push(`entries[${i}].ring must be a|b`);
@@ -326,16 +336,6 @@ function cmdSeed(force, seedPathArg) {
if (!e.label?.trim()) errors.push(`entries[${i}].label is required`);
if (e.detail !== undefined && typeof e.detail !== 'string') errors.push(`entries[${i}].detail must be a string`);
}
if (!Array.isArray(status) && status && typeof status === 'object') {
for (const [k, v] of Object.entries(status)) {
const okStr = typeof v === 'string' && v.trim();
const okObj = v && typeof v === 'object' && !Array.isArray(v)
&& (typeof v.normal === 'string' || typeof v.value === 'string');
if (!k.trim() || (!okStr && !okObj)) {
errors.push(`status["${k}"] must be a non-empty string (normal and starting value) or {"normal", "value"}`);
}
}
}
for (const [i, r] of (Array.isArray(records) ? records : []).entries()) {
if (!r.kind?.trim() || !r.label?.trim()) errors.push(`records[${i}] needs kind and label`);
if (r.detail !== undefined && typeof r.detail !== 'string') errors.push(`records[${i}].detail must be a string`);
@@ -356,13 +356,6 @@ function cmdSeed(force, seedPathArg) {
.run(e.ring, e.type, norm(e.label), norm(e.detail ?? ''), sf.date, sf.date);
journal(db, 'seed', 'insert', `e${Number(res.lastInsertRowid)}`, 'seeded');
}
for (const [k, v] of Object.entries(status)) {
const n = typeof v === 'string' ? v : (v.normal ?? '');
const val = typeof v === 'string' ? v : (v.value ?? '');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET normal = excluded.normal, value = excluded.value, updated = excluded.updated")
.run(norm(k), norm(n), norm(val), sf.date);
journal(db, 'seed', 'status', `s:${norm(k)}`, 'seeded');
}
for (const r of records) {
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(norm(r.kind), norm(r.label), norm(r.detail ?? ''), sf.date);
@@ -374,7 +367,7 @@ function cmdSeed(force, seedPathArg) {
fail(`seed failed, rolled back: ${e.message}`);
}
console.log(`seeded [${RUN}]: ${entries.length} entries, ${Object.keys(status).length} status, ${records.length} records (as of ${sf.date})`);
console.log(`seeded [${RUN}]: ${entries.length} entries, ${records.length} records (as of ${sf.date})`);
renderAll(db);
dumpDb(db);
}
@@ -543,17 +536,11 @@ function cmdApply(manifestPath) {
// --- simple commands ---------------------------------------------------------
function cmdInit() {
for (const d of ['db', 'log', 'manifests']) {
const dir = path.join(RUN_ROOT, d);
fs.mkdirSync(dir, { recursive: true });
const keep = path.join(dir, '.gitkeep');
if (!fs.existsSync(keep)) fs.writeFileSync(keep, '');
for (const d of ['db', 'canon', 'dumps', 'log', 'manifests', 'sessions']) {
fs.mkdirSync(path.join(RUN_ROOT, d), { recursive: true });
}
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
if (!fs.existsSync(SETTINGS_PATH)) {
fs.writeFileSync(SETTINGS_PATH, JSON.stringify({ records: false }, null, 2) + '\n');
}
const backdrop = path.join(RUN_ROOT, 'backdrop.md');
if (!fs.existsSync(backdrop)) fs.writeFileSync(backdrop, BACKDROP_TEMPLATE);
const card = path.join(RUN_ROOT, 'character.md');
@@ -563,17 +550,81 @@ function cmdInit() {
renderAll(db);
}
function cmdRuns() {
if (!fs.existsSync(PACKAGES_DIR)) { console.log('(no runs)'); return; }
// --- packages and runs --------------------------------------------------------
//
// A package is a preset: authored content only, no state. 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 and an optional model override.
const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md'];
const SHARED_PROMPTS = ['system.md', 'housekeeper.md'];
function cmdPackages() {
if (!fs.existsSync(PACKAGES_DIR)) { console.log('(no packages)'); return; }
for (const d of fs.readdirSync(PACKAGES_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
const dbPath = path.join(PACKAGES_DIR, d.name, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { console.log(`${d.name}: (not initialized)`); continue; }
const p = path.join(PACKAGES_DIR, d.name);
const has = (f) => fs.existsSync(path.join(p, f));
let records = false;
try { records = JSON.parse(fs.readFileSync(path.join(p, 'settings.json'), 'utf8')).records === true; } catch {}
console.log(`${d.name}: records ${records ? 'on' : 'off'} · turn-0 ${has('turn-0.md') ? 'yes' : 'no'} · seed ${has('seed.json') ? 'yes' : 'no'} · backdrop+card ${has('backdrop.md') && has('character.md') ? 'ok' : 'MISSING'}`);
}
}
function cmdCreate(pkgName, runId, model) {
if (!pkgName || !runId || !/^[a-z0-9-]+$/.test(runId)) {
fail('usage: create <package> <run-id> ["model"]');
}
const pkgDir = path.join(PACKAGES_DIR, pkgName);
if (!fs.existsSync(pkgDir)) fail(`no such package: ${pkgName} — see: packages`);
const runDir = path.join(RUNS_DIR, runId);
if (fs.existsSync(runDir)) fail(`run '${runId}' already exists — a disposable run is deleted, not recreated (Remove-Item ${rel(runDir)})`);
fs.mkdirSync(runDir, { recursive: true });
for (const f of PACKAGE_FILES) {
const src = path.join(pkgDir, f);
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(runDir, f));
}
for (const f of SHARED_PROMPTS) {
const src = path.join(ROOT, f);
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(runDir, f));
}
const meta = { package: pkgName, created: today() };
if (model) meta.model = model;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
for (const d of ['db', 'canon', 'dumps', 'log', 'manifests', 'sessions']) {
fs.mkdirSync(path.join(runDir, d), { recursive: true });
}
setRunRoot(runDir); // views and dump land inside the new run
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
console.log(`created run '${runId}' from package '${pkgName}': ${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`);
renderAll(db);
dumpDb(db);
}
function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { console.log('(no runs — create one: create <package> <run-id>)'); return; }
let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
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 = '?';
try { pkg = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8')).package ?? '?'; } catch {}
const dbPath = path.join(runDir, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { console.log(`${d.name} [${pkg}]: (not initialized)`); continue; }
const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
console.log(`${d.name}: a ${n('a')}/${CAPS.a} · b ${n('b')}/${CAPS.b} · cold ${n('cold')}`);
console.log(`${d.name} [${pkg}]: a ${n('a')}/${CAPS.a} · b ${n('b')}/${CAPS.b} · cold ${n('cold')}`);
}
if (!found) console.log('(no runs — create one: create <package> <run-id>)');
}
function today() { return new Date().toISOString().slice(0, 10); }
@@ -660,7 +711,9 @@ function cmdAmend(ridStr, detail) {
if (!row) fail(`no such record: ${ridStr}`);
if (!detail?.trim()) fail('usage: amend <rid> "new detail"');
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), rid);
journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended');
// 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);
}
@@ -672,55 +725,112 @@ function cmdDiscard(ridStr, reason) {
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
if (!row) fail(`no such record: ${ridStr}`);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded');
// 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);
}
function cmdSet(key, value, reason) {
const db = openDb();
if (!key?.trim() || !value?.trim()) fail('usage: set <key> "value" ["reason"]');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, '', ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated = excluded.updated")
.run(norm(key), norm(value), today());
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${norm(key)}`, reason ?? (AS_GM ? 'GM override' : 'excursion declared'));
console.log(`status ${norm(key)}: ${norm(value)}`);
renderAll(db);
dumpDb(db);
// --- the paper (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
// 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);
// split a list of descriptions, tolerating newlines and list bullets —
// covers the delta tags and a <status> block body alike
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 cmdNorm(key, baseline, reason) {
function cmdPaperApply(text) {
const db = openDb();
if (!key?.trim() || !baseline?.trim()) fail('usage: norm <key> "baseline" ["reason"]');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, ?, '', ?) ON CONFLICT(key) DO UPDATE SET normal = excluded.normal, updated = excluded.updated")
.run(norm(key), norm(baseline), today());
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${norm(key)}`, reason ?? (AS_GM ? 'GM override' : 'baseline set'));
console.log(`status ${norm(key)} — norm: ${norm(baseline)}`);
renderAll(db);
dumpDb(db);
}
function cmdClear(key) {
const db = openDb();
const row = db.prepare('SELECT * FROM status WHERE key = ?').get(norm(key ?? ''));
if (!row) fail(`no such status key: ${key}`);
if (!row.normal) {
db.prepare('DELETE FROM status WHERE key = ?').run(row.key);
} else {
db.prepare("UPDATE status SET value = '', updated = ? WHERE key = ?").run(today(), row.key);
const lost = [];
const gained = [];
for (const m of String(text ?? '').matchAll(/<lost>([\s\S]*?)<\/lost>/g)) lost.push(...splitDescrs(m[1]));
for (const m of String(text ?? '').matchAll(/<gained>([\s\S]*?)<\/gained>/g)) gained.push(...splitDescrs(m[1]));
const applied = { lost: [], gained: [], conflicts: [] };
if (!lost.length && !gained.length) {
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
return;
}
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${row.key}`, 'returned to baseline');
console.log(`status ${row.key}: back to ${row.normal || '—'}`);
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);
if (row) {
db.prepare('DELETE FROM paper WHERE id = ?').run(row.id);
journal(db, win, 'paper-drop', `p${row.id}`, 'delta', row.descr);
applied.lost.push(item);
} else {
applied.conflicts.push(`not on her paper: ${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');
applied.gained.push(item);
}
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`paper-apply failed, rolled back: ${e.message}`);
}
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
renderAll(db);
dumpDb(db);
}
function cmdUnset(key) {
// 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) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = paperList(db);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM paper').run();
for (const d of clean) {
db.prepare('INSERT INTO paper (descr, added) VALUES (?, ?)').run(d, today());
}
journal(db, win, 'paper-set', 'paper', reason, JSON.stringify(prior));
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`paper-set failed, rolled back: ${e.message}`);
}
return clean;
}
function cmdPaperSet(items) {
const db = openDb();
const row = db.prepare('SELECT * FROM status WHERE key = ?').get(norm(key ?? ''));
if (!row) fail(`no such status key: ${key}`);
db.prepare('DELETE FROM status WHERE key = ?').run(row.key);
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${row.key}`, 'field dropped');
console.log(`status ${row.key}: dropped`);
const clean = setPaper(db, items, AS_GM ? 'GM override' : 'paper set', AS_GM ? 'gm' : 'pc');
console.log(JSON.stringify(clean));
renderAll(db);
dumpDb(db);
}
function cmdPaperIngest(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)));
renderAll(db);
dumpDb(db);
}
@@ -766,9 +876,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 sk = db.prepare('SELECT * FROM status ORDER BY updated DESC, key').all()
.map((r) => r.key + (r.value && r.value !== r.normal && r.normal ? '!' : ''));
console.log(`status: ${sk.length ? sk.join(', ') : '(nothing set)'}`);
const paper = paperList(db);
console.log(`paper: ${paper.length ? '' : '(a blank sheet)'}`);
for (const d of paper) 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] ?? '∞';
@@ -785,7 +895,9 @@ function cmdStatus() {
// --- dispatch ----------------------------------------------------------------
switch (cmd) {
case 'packages': cmdPackages(); break;
case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2]); break;
case 'seed': cmdSeed(FORCE, args[0]); break;
case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break;
@@ -796,10 +908,10 @@ 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 'set': (args.length >= 2) ? cmdSet(args[0], args[1], args[2]) : fail('usage: set <key> "value" ["reason"]'); break;
case 'norm': (args.length >= 2) ? cmdNorm(args[0], args[1], args[2]) : fail('usage: norm <key> "baseline" ["reason"]'); break;
case 'clear': (args.length >= 1) ? cmdClear(args[0]) : fail('usage: clear <key>'); break;
case 'unset': (args.length >= 1) ? cmdUnset(args[0]) : fail('usage: unset <key>'); break;
case 'paper': cmdPaper(); break;
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); break;
case 'paper-set': (args.length >= 1) ? cmdPaperSet(args) : fail('usage: paper-set "descr" ["descr" ...]'); break;
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break;
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;
@@ -807,6 +919,6 @@ switch (cmd) {
case 'dump': cmdDump(); break;
case 'restore': cmdRestore(FORCE); break;
default:
console.error('usage: node tool/memory.mjs <init|render|apply|insert|delete|revive|dump|restore|status>');
console.error('usage: node tool/memory.mjs <packages|runs|create|init|render|apply|insert|delete|revive|file|amend|discard|search|unarchive|paper|paper-apply|paper-set|paper-ingest|pick|dump|restore|status>');
process.exit(1);
}