diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b67125c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +db/memory.db diff --git a/README.md b/README.md index c171b92..8433e32 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,8 @@ forget; files don't — so the file must be shaped to forget too. window. Reads the transcript and the rendered rings; emits a **manifest** of semantic operations. Judgment, no clerical work. - **`tool/memory.mjs` = the clerk.** Validates and applies manifests, - maintains the database, enforces caps, renders views, writes the log. - Fails loudly, never drifts silently. + maintains the database, enforces caps, renders views, writes the log, + dumps canonical state. Fails loudly, never drifts silently. ## Scope @@ -140,9 +140,26 @@ minors, gratuitous violence. These live in `system.md`; edit them there. ## Housekeeping -This directory is a git repo. Every housekeeping pass should end in a commit -— the diff over `canon/`, `log/`, and `manifests/` is the classification and -drift record. No model touches git; the human commits. +This directory is a git repo. Every housekeeping pass should end in a commit. +The **primary audit surface is `dumps/memory.sql`** — the canonical dump: +id-ordered, one row per line, auto-written by every mutation. Because the +ordering is by id, diffs are position-stable — a touch is one changed line, +a promotion is one changed line, an eviction is one changed line. Diffing +two consecutive dumps reconstructs exactly the operations that were applied, +including overflow and everything in cold storage. + +Cross-check it against the window's log: the log is what the housekeeper +*declared*, the dump-diff is what *actually happened*. Any disagreement is +either a tool bug or a hand edit — and hand edits have a contract: all +mutations go through the tool, so the dump never drifts. (If you ever poke +the db with a sqlite browser, run `dump` afterwards and confess in the +commit message.) + +The dump is restorable SQL and the **committed truth**; the binary +`db/memory.db` is a gitignored local cache — fresh clone: +`node tool/memory.mjs restore`. The `canon/` views stay committed as +provenance — exactly what the models were sent — and `log/` + `manifests/` +remain the human-readable record. The housekeeper may be a different model than the player — cheaper, or more pedantic, whatever housekeeping needs. The two prompts are independent. @@ -161,7 +178,10 @@ tool/ memory.mjs the clerk: init, render, apply, insert, delete, revive, status db/ schema.sql entries + append-only events journal - memory.db the state (SQLite; binary — diffs live in canon/ and log/) + memory.db the state (gitignored local cache — rebuilt via restore) +dumps/ + memory.sql canonical dump (GENERATED): id-ordered, restorable SQL — + the committed truth and primary diff/audit surface manifests/ housekeeper manifests, one JSON per window (diffable) canon/ ring-a.md GENERATED view: important facts, MRU-ordered diff --git a/canon/ring-a.md b/canon/ring-a.md index 489084c..98685ff 100644 --- a/canon/ring-a.md +++ b/canon/ring-a.md @@ -4,4 +4,5 @@ # Ring A — what matters -(empty — nothing here yet) +- [e2] [2026-11-12] [place] **The Gull** — a tavern by the fish market, smells of tar +- [e1] [2026-11-12] [person] **Marta** — harbormaster; owes the PC silence; warm but transactional diff --git a/db/memory.db b/db/memory.db deleted file mode 100644 index 2c1fe3e..0000000 Binary files a/db/memory.db and /dev/null differ diff --git a/dumps/memory.sql b/dumps/memory.sql new file mode 100644 index 0000000..bd42346 --- /dev/null +++ b/dumps/memory.sql @@ -0,0 +1,29 @@ +-- 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 +PRAGMA foreign_keys = ON; + +CREATE TABLE IF NOT EXISTS entries ( + id INTEGER PRIMARY KEY, + ring TEXT NOT NULL CHECK (ring IN ('a', 'b', 'cold')), + type TEXT NOT NULL CHECK (type IN ('place', 'person', 'fact', 'thread')), + label TEXT NOT NULL, + detail TEXT NOT NULL DEFAULT '', + created TEXT NOT NULL, + last_touched TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS entries_ring_touch + ON entries (ring, last_touched DESC, id DESC); + +-- append-only audit journal; nothing here is ever updated or deleted +CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY, + window TEXT NOT NULL, + op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive')), + entry_id INTEGER NOT NULL REFERENCES entries (id), + reason TEXT NOT NULL DEFAULT '' +); + +CREATE INDEX IF NOT EXISTS events_window ON events (window); +BEGIN TRANSACTION; +COMMIT; diff --git a/tool/memory.mjs b/tool/memory.mjs index 06860fe..7fb77e3 100644 --- a/tool/memory.mjs +++ b/tool/memory.mjs @@ -13,6 +13,9 @@ // insert "Label" "detail" GM-authoritative insert // delete "reason" GM-authoritative removal to cold storage // revive [a|b] GM pulls an entry back from cold storage +// dump canonical dump to dumps/memory.sql +// (also auto-written by every mutation) +// restore [--force] rebuild the db from dumps/memory.sql // status counts, caps, and what's sinking import { DatabaseSync } from 'node:sqlite'; @@ -25,6 +28,7 @@ const DB_PATH = path.join(ROOT, 'db', 'memory.db'); const SCHEMA_PATH = path.join(ROOT, 'db', 'schema.sql'); const CANON_DIR = path.join(ROOT, 'canon'); const LOG_DIR = path.join(ROOT, 'log'); +const DUMPS_DIR = path.join(ROOT, 'dumps'); // dials — retune freely const CAPS = { a: 500, b: 3000 }; @@ -48,9 +52,11 @@ const parseId = (s) => { return m ? Number(m[1]) : null; }; +const norm = (s) => String(s ?? '').replace(/\s+/g, ' ').trim(); + const journal = (db, win, op, id, reason) => db.prepare('INSERT INTO events (window, op, entry_id, reason) VALUES (?, ?, ?, ?)') - .run(win, op, id, reason ?? ''); + .run(win, op, id, norm(reason)); function renderRing(db, ring) { const rows = db.prepare( @@ -83,10 +89,33 @@ function renderAll(db) { } } +// canonical serialization: id-ordered, one row per line, restorable SQL. +// this is the committed truth; the binary db is a local cache. +function dumpDb(db) { + fs.mkdirSync(DUMPS_DIR, { recursive: true }); + 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 db.prepare('SELECT * FROM entries ORDER BY id').all()) { + L.push(`INSERT INTO entries VALUES (${r.id},${q(r.ring)},${q(r.type)},${q(r.label)},${q(r.detail)},${q(r.created)},${q(r.last_touched)});`); + } + for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) { + L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${r.entry_id},${q(r.reason)});`); + } + L.push('COMMIT;', ''); + const file = path.join(DUMPS_DIR, 'memory.sql'); + fs.writeFileSync(file, L.join('\n')); + return file; +} + function insertEntry(db, { ring, type, label, detail, date, win, reason }) { const res = db.prepare( 'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)' - ).run(ring, type, label.trim(), detail ?? '', date, date); + ).run(ring, type, norm(label), norm(detail), date, date); const id = Number(res.lastInsertRowid); journal(db, win, 'insert', id, reason); return id; @@ -235,7 +264,7 @@ function cmdApply(manifestPath) { } for (const e of reword) { const id = parseId(e.id); - db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(e.detail, mf.date, id); + db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), mf.date, id); journal(db, mf.window, 'reword', id, e.reason); applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason }); } @@ -280,6 +309,7 @@ function cmdApply(manifestPath) { ].filter(Boolean).join(', ')); console.log(`log: ${rel(logFile)}`); renderAll(db); + console.log(`dump: ${rel(dumpDb(db))}`); } // --- simple commands --------------------------------------------------------- @@ -289,6 +319,7 @@ function cmdInit() { const db = new DatabaseSync(DB_PATH); db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8')); console.log(`initialized ${rel(DB_PATH)}`); + console.log(`dump: ${rel(dumpDb(db))}`); } function today() { return new Date().toISOString().slice(0, 10); } @@ -309,6 +340,7 @@ function gmOp(ring, type, label, detail) { } console.log(`inserted [e${id}] → ring ${ring.toUpperCase()}`); renderAll(db); + dumpDb(db); } function cmdDelete(idStr, reason) { @@ -320,6 +352,7 @@ function cmdDelete(idStr, reason) { journal(db, 'gm', 'delete', id, reason ?? 'GM edit'); console.log(`[e${id}] **${row.label}** → cold storage`); renderAll(db); + dumpDb(db); } function cmdRevive(idStr, ring = 'b') { @@ -333,6 +366,24 @@ function cmdRevive(idStr, ring = 'b') { journal(db, 'gm', 'revive', id, 'GM revive'); console.log(`[e${id}] **${row.label}** revived → ring ${ring.toUpperCase()}`); renderAll(db); + dumpDb(db); +} + +function cmdDump() { + console.log(rel(dumpDb(openDb()))); +} + +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')); + console.log(`restored ${rel(DB_PATH)} from ${rel(dumpFile)}`); + renderAll(db); } function cmdStatus() { @@ -361,7 +412,9 @@ switch (cmd) { case 'delete': (args.length >= 1) ? cmdDelete(args[0], args[1]) : fail('usage: delete "reason"'); break; case 'revive': (args.length >= 1) ? cmdRevive(args[0], args[1]) : fail('usage: revive [a|b]'); break; case 'status': cmdStatus(); break; + case 'dump': cmdDump(); break; + case 'restore': cmdRestore(args[0] === '--force'); break; default: - console.error('usage: node tool/memory.mjs '); + console.error('usage: node tool/memory.mjs '); process.exit(1); }