audit: canonical dump as committed truth; db demoted to gitignored cache; restore

This commit is contained in:
2026-11-11 17:58:39 +00:00
parent e0b384f858
commit 1dcdc917d2
6 changed files with 115 additions and 11 deletions
+57 -4
View File
@@ -13,6 +13,9 @@
// 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
// 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 <id> "reason"'); break;
case 'revive': (args.length >= 1) ? cmdRevive(args[0], args[1]) : fail('usage: revive <id> [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 <init|render|apply|insert|delete|revive|status>');
console.error('usage: node tool/memory.mjs <init|render|apply|insert|delete|revive|dump|restore|status>');
process.exit(1);
}