records: queryable file tier, diegetic per-run gate, narrow search with hard cap

This commit is contained in:
2026-11-11 18:30:29 +00:00
parent 57e8718ffa
commit b77a0de527
13 changed files with 277 additions and 49 deletions
+120 -15
View File
@@ -14,6 +14,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
// record <kind> "Label" "detail" GM files a record (if records are enabled)
// search <terms...> query the records (max 10; a miss is a miss)
// unarchive <rid> [a|b] GM pulls a record back into the rings
// dump canonical dump to dumps/memory.sql
// (also auto-written by every mutation)
// restore [--force] rebuild the db from dumps/memory.sql
@@ -70,6 +73,15 @@ 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');
function recordsEnabled() {
try {
return JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8')).records === true;
} catch {
return false;
}
}
function openDb() {
if (!fs.existsSync(DB_PATH)) {
@@ -87,9 +99,14 @@ const parseId = (s) => {
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, norm(reason));
const parseRid = (s) => {
const m = /^r(\d+)$/.exec(String(s ?? '').trim());
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));
function renderRing(db, ring) {
const rows = db.prepare(
@@ -100,6 +117,7 @@ function renderRing(db, ring) {
'<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->',
`<!-- A view of db/memory.db, ring ${ring.toUpperCase()}, ordered by last touch: top = most recent. -->`,
'<!-- Policy lives in housekeeper.md; the models never write here. -->',
`<!-- Records: ${recordsEnabled() ? 'available — the character keeps files; consult via ((q: terms)) in OOC' : 'none — this character keeps no files to consult'}. -->`,
'',
`# Ring ${ring.toUpperCase()} — ${title}`,
'',
@@ -136,8 +154,11 @@ function dumpDb(db) {
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 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 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(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)});`);
}
L.push('COMMIT;', '');
const file = path.join(DUMPS_DIR, 'memory.sql');
@@ -150,7 +171,7 @@ function insertEntry(db, { ring, type, label, detail, date, win, reason }) {
'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)'
).run(ring, type, norm(label), norm(detail), date, date);
const id = Number(res.lastInsertRowid);
journal(db, win, 'insert', id, reason);
journal(db, win, 'insert', `e${id}`, reason);
return id;
}
@@ -198,6 +219,8 @@ function renderLog(mf, applied, overflow) {
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('Records (filed)', applied.record, (r) => `[r${r.rid}] [${r.kind}] **${r.label}**${r.detail ? ` — ${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));
@@ -235,9 +258,15 @@ function cmdApply(manifestPath) {
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 ((rec.length || arch.length) && !recordsEnabled()) {
errors.push('this character keeps no records — record/archive ops are unavailable (see the run\'s settings.json)');
}
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('|')}`);
@@ -253,6 +282,13 @@ function cmdApply(manifestPath) {
if (row && !String(e.detail ?? '').trim()) errors.push(`reword (e${row.id}): detail is required`);
});
del.forEach((e) => ref('delete', e, null));
for (const [i, e] of rec.entries()) {
need(e.kind, `record[${i}].kind`);
need(e.label, `record[${i}].label`);
if (e.detail !== undefined && typeof e.detail !== 'string') errors.push(`record[${i}].detail must be a string`);
need(e.reason, `record[${i}].reason`);
}
arch.forEach((e) => ref('archive', e, null));
for (const [name, arr] of [['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`); });
}
@@ -263,7 +299,7 @@ function cmdApply(manifestPath) {
process.exit(1);
}
const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [] };
const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [], record: [], archive: [] };
const overflow = [];
db.exec('BEGIN');
@@ -280,31 +316,48 @@ function cmdApply(manifestPath) {
for (const e of touch) {
const id = parseId(e.id);
touchDate(id);
journal(db, mf.window, 'touch', id, e.reason);
journal(db, mf.window, '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(mf.date, id);
journal(db, mf.window, 'promote', id, e.reason);
journal(db, mf.window, '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(mf.date, id);
journal(db, mf.window, 'demote', id, e.reason);
journal(db, mf.window, '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), mf.date, id);
journal(db, mf.window, 'reword', id, e.reason);
journal(db, mf.window, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
}
for (const e of rec) {
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(norm(e.kind), norm(e.label), norm(e.detail ?? ''), mf.date);
const rid = Number(res.lastInsertRowid);
journal(db, mf.window, 'record', `r${rid}`, e.reason);
applied.record.push({ rid, ...e });
}
for (const e of arch) {
const id = 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.window, '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', id, e.reason);
journal(db, mf.window, 'delete', `e${id}`, e.reason);
applied.delete.push({ row: fetch(id), reason: e.reason });
}
@@ -318,7 +371,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', victim.id, `ring ${ring.toUpperCase()} overflow (auto)`);
journal(db, mf.window, ring === 'a' ? 'demote' : 'evict', `e${victim.id}`, `ring ${ring.toUpperCase()} overflow (auto)`);
overflow.push({ id: victim.id, from: ring, to: dest });
}
}
@@ -337,6 +390,8 @@ function cmdApply(manifestPath) {
applied.promote.length && `${applied.promote.length} promoted`,
applied.demote.length && `${applied.demote.length} demoted`,
applied.reword.length && `${applied.reword.length} reworded`,
applied.record.length && `${applied.record.length} filed`,
applied.archive.length && `${applied.archive.length} archived`,
applied.delete.length && `${applied.delete.length} deleted`,
overflow.length && `${overflow.length} overflow`,
].filter(Boolean).join(', '));
@@ -356,6 +411,9 @@ function cmdInit() {
}
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');
}
console.log(`initialized run '${RUN}': ${rel(DB_PATH)}`);
dumpDb(db);
renderAll(db);
@@ -401,7 +459,7 @@ function cmdDelete(idStr, reason) {
const row = id && 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(id);
journal(db, 'gm', 'delete', id, reason ?? 'GM edit');
journal(db, 'gm', 'delete', `e${id}`, reason ?? 'GM edit');
console.log(`[e${id}] **${row.label}** → cold storage`);
renderAll(db);
dumpDb(db);
@@ -415,7 +473,7 @@ function cmdRevive(idStr, ring = 'b') {
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(ring, id);
journal(db, 'gm', 'revive', id, 'GM revive');
journal(db, 'gm', 'revive', `e${id}`, 'GM revive');
console.log(`[e${id}] **${row.label}** revived → ring ${ring.toUpperCase()}`);
renderAll(db);
dumpDb(db);
@@ -438,9 +496,53 @@ function cmdRestore(force = false) {
renderAll(db);
}
function cmdRecord(kind, label, detail) {
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: record <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, 'gm', 'record', `r${rid}`, 'GM edit');
console.log(`filed [r${rid}] [${norm(kind)}] **${norm(label)}**`);
dumpDb(db);
}
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 = 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}` : ''} (${r.created})`);
const total = db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params).n;
if (total > rows.length) console.log(`…${total - rows.length} more omitted — narrow the query`);
}
function cmdUnarchive(ridStr, ring = 'b') {
const db = openDb();
const rid = parseRid(ridStr);
const row = rid && 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(ring, type, row.label, row.detail, row.created, today());
const eid = Number(res.lastInsertRowid);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
journal(db, 'gm', 'unarchive', `e${eid}`, 'GM unarchive');
console.log(`[r${rid}] **${row.label}** → ring ${ring.toUpperCase()} as [e${eid}]`);
renderAll(db);
dumpDb(db);
}
function cmdStatus() {
const db = openDb();
console.log(`run: ${RUN}`);
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
console.log(`records: ${nr}`);
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] ?? '∞';
@@ -464,6 +566,9 @@ switch (cmd) {
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 'record': (args.length >= 2) ? cmdRecord(args[0], args[1], args[2] ?? '') : fail('usage: record <kind> "Label" "detail"'); 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 'dump': cmdDump(); break;
case 'restore': cmdRestore(args[0] === '--force'); break;