2026-11-11 16:54:49 +00:00
#!/usr/bin/env node
// tool/memory.mjs — bookkeeping for the memory rings.
//
// judgment lives in the models (player + housekeeper)
// mechanics live here (this file)
// state lives in db/memory.db
// canon/ is a generated view (never edit by hand)
//
// commands:
2026-11-11 18:25:09 +00:00
// runs list runs and their fill levels
// init create the run's database
2026-11-11 16:54:49 +00:00
// render write canon/ring-a.md and canon/ring-b.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
// revive <id> [a|b] GM pulls an entry back from cold storage
2026-11-11 18:44:58 +00:00
// file <kind> "Label" "detail" the PC files a record at her desk
// (records-enabled runs; --gm to seed as GM)
// amend <rid> "new detail" the PC amends a record (--gm for GM fixes)
// discard <rid> "reason" the PC discards a record (--gm likewise)
2026-11-11 18:30:29 +00:00
// search <terms...> query the records (max 10; a miss is a miss)
// unarchive <rid> [a|b] GM pulls a record back into the rings
2026-11-11 18:44:58 +00:00
// set <key> "value" the PC updates her status (--gm to override)
// unset <key> the PC clears a status key
2026-11-11 17:58:39 +00:00
// dump canonical dump to dumps/memory.sql
// (also auto-written by every mutation)
// restore [--force] rebuild the db from dumps/memory.sql
2026-11-11 18:25:09 +00:00
// commands take --run <name>; the default comes from config.json {"run": "..."}.
//
2026-11-11 16:54:49 +00:00
// status counts, caps, and what's sinking
import { DatabaseSync } from 'node:sqlite' ;
import fs from 'node:fs' ;
import path from 'node:path' ;
import { fileURLToPath } from 'node:url' ;
const ROOT = path . resolve ( path . dirname ( fileURLToPath ( import . meta . url )), '..' );
const SCHEMA_PATH = path . join ( ROOT , 'db' , 'schema.sql' );
2026-11-11 18:25:09 +00:00
const CONFIG_PATH = path . join ( ROOT , 'config.json' );
const RUNS_DIR = path . join ( ROOT , 'runs' );
2026-11-11 16:54:49 +00:00
// dials — retune freely
const CAPS = { a : 500 , b : 3000 };
const TYPES = [ 'place' , 'person' , 'fact' , 'thread' ];
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 ( '\\' , '/' );
2026-11-11 18:44:58 +00:00
// flags: --run <name> beats config.json {"run": "..."}; --gm attributes the op to the GM
2026-11-11 18:25:09 +00:00
const argv = process . argv . slice ( 2 );
const runIdx = argv . indexOf ( '--run' );
let runOverride = null ;
if ( runIdx !== - 1 ) {
runOverride = argv [ runIdx + 1 ] ?? null ;
argv . splice ( runIdx , 2 );
}
2026-11-11 18:44:58 +00:00
const AS_GM = argv . includes ( '--gm' );
for ( let i = argv . indexOf ( '--gm' ); i !== - 1 ; i = argv . indexOf ( '--gm' )) argv . splice ( i , 1 );
2026-11-11 18:25:09 +00:00
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 ;
}
const RUN = cmd === 'runs' ? null : resolveRun ();
if ( cmd !== 'runs' && ( ! RUN || ! /^[a-z0-9-]+$/ . test ( RUN ))) {
fail ( 'no run specified — use --run <name> or {"run":"name"} in config.json' );
}
const RUN_ROOT = path . join ( RUNS_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' );
2026-11-11 18:30:29 +00:00
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 ;
}
}
2026-11-11 18:25:09 +00:00
2026-11-11 16:54:49 +00:00
function openDb () {
if ( ! fs . existsSync ( DB_PATH )) {
fail ( `no database at ${ rel ( DB_PATH ) } — run: node tool/memory.mjs init` );
}
const db = new DatabaseSync ( DB_PATH );
db . exec ( fs . readFileSync ( SCHEMA_PATH , 'utf8' ));
return db ;
}
const parseId = ( s ) => {
const m = /^e(\d+)$/ . exec ( String ( s ?? '' ). trim ());
return m ? Number ( m [ 1 ]) : null ;
};
2026-11-11 17:58:39 +00:00
const norm = ( s ) => String ( s ?? '' ). replace ( /\s+/g , ' ' ). trim ();
2026-11-11 18:30:29 +00:00
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 ));
2026-11-11 16:54:49 +00:00
function renderRing ( db , ring ) {
const rows = db . prepare (
'SELECT * FROM entries WHERE ring = ? ORDER BY last_touched DESC, id DESC'
). all ( ring );
const title = ring === 'a' ? 'what matters' : 'what stuck anyway' ;
const lines = [
'<!-- 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. -->' ,
2026-11-11 18:30:29 +00:00
`<!-- Records: ${ recordsEnabled () ? 'available — the character keeps files; consult via ((q: terms)) in OOC' : 'none — this character keeps no files to consult' } . -->` ,
2026-11-11 16:54:49 +00:00
'' ,
`# Ring ${ ring . toUpperCase () } — ${ title } ` ,
'' ,
];
if ( rows . length === 0 ) lines . push ( '(empty — nothing here yet)' );
for ( const r of rows ) {
lines . push ( `- [e ${ r . id } ] [ ${ r . last_touched } ] [ ${ r . type } ] ** ${ r . label } ** ${ r . detail ? ` — ${ r . detail } ` : '.' } ` );
}
lines . push ( '' );
const file = path . join ( CANON_DIR , `ring- ${ ring } .md` );
fs . mkdirSync ( CANON_DIR , { recursive : true });
fs . writeFileSync ( file , lines . join ( '\n' ));
return { file , count : rows . length };
}
2026-11-11 18:44:58 +00:00
function renderStatus ( db ) {
const rows = db . prepare ( 'SELECT * FROM status ORDER BY updated DESC, key' ). all ();
const lines = [
'<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->' ,
"<!-- The player's own current state, maintained via ((status key: value)) in OOC. -->" ,
'<!-- Stances are feelings; facts live in the rings. GM overrides are rare and journaled. -->' ,
'' ,
'# Status' ,
'' ,
];
if ( ! rows . length ) lines . push ( '(nothing set — fresh start)' );
for ( const r of rows ) lines . push ( `- ** ${ r . key } :** ${ r . value } ` );
lines . push ( '' );
const file = path . join ( CANON_DIR , 'status.md' );
fs . mkdirSync ( CANON_DIR , { recursive : true });
fs . writeFileSync ( file , lines . join ( '\n' ));
return { file , count : rows . length };
}
2026-11-11 16:54:49 +00:00
function renderAll ( db ) {
for ( const ring of RINGS ) {
const { file , count } = renderRing ( db , ring );
console . log ( ` ${ rel ( file ) } — ${ count } entries` );
}
2026-11-11 18:44:58 +00:00
const { file , count } = renderStatus ( db );
console . log ( ` ${ rel ( file ) } — ${ count } keys` );
2026-11-11 16:54:49 +00:00
}
2026-11-11 17:58:39 +00:00
// 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 ) } );` );
}
2026-11-11 18:30:29 +00:00
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 ) } );` );
}
2026-11-11 18:44:58 +00:00
for ( const r of db . prepare ( 'SELECT * FROM status ORDER BY key' ). all ()) {
L . push ( `INSERT INTO status VALUES ( ${ q ( r . key ) } , ${ q ( r . value ) } , ${ q ( r . updated ) } );` );
}
2026-11-11 17:58:39 +00:00
for ( const r of db . prepare ( 'SELECT * FROM events ORDER BY id' ). all ()) {
2026-11-11 18:30:29 +00:00
L . push ( `INSERT INTO events VALUES ( ${ r . id } , ${ q ( r . window ) } , ${ q ( r . op ) } , ${ q ( r . target ) } , ${ q ( r . reason ) } );` );
2026-11-11 17:58:39 +00:00
}
L . push ( 'COMMIT;' , '' );
const file = path . join ( DUMPS_DIR , 'memory.sql' );
fs . writeFileSync ( file , L . join ( '\n' ));
return file ;
}
2026-11-11 16:54:49 +00:00
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 (?, ?, ?, ?, ?, ?)'
2026-11-11 17:58:39 +00:00
). run ( ring , type , norm ( label ), norm ( detail ), date , date );
2026-11-11 16:54:49 +00:00
const id = Number ( res . lastInsertRowid );
2026-11-11 18:30:29 +00:00
journal ( db , win , 'insert' , `e ${ id } ` , reason );
2026-11-11 16:54:49 +00:00
return id ;
}
// --- validation helpers (used by apply) -------------------------------------
function makeValidator ( db ) {
const errors = [];
const seen = new Map ();
const need = ( v , name ) => { if ( typeof v !== 'string' || ! v . trim ()) errors . push ( ` ${ name } is required` ); };
const asArray = ( v , name ) => {
if ( v === undefined || v === null ) return [];
if ( ! Array . isArray ( v )) { errors . push ( ` ${ name } must be an array` ); return []; }
return v ;
};
const ref = ( op , e , expectRing ) => {
const id = parseId ( e . id );
if ( id == null ) { errors . push ( ` ${ op } : id must look like e12` ); return null ; }
const row = db . prepare ( 'SELECT * FROM entries WHERE id = ?' ). get ( id );
if ( ! row ) { errors . push ( ` ${ op } : e ${ id } does not exist` ); return null ; }
if ( row . ring === 'cold' ) { errors . push ( ` ${ op } : e ${ id } is in cold storage — the models can't see it` ); return null ; }
if ( expectRing && row . ring !== expectRing ) {
errors . push ( ` ${ op } : e ${ id } is in ring ${ row . ring } , expected ${ expectRing } ` );
}
if ( seen . has ( id )) errors . push ( `e ${ id } appears in more than one operation ( ${ seen . get ( id ) } and ${ op } )` );
else seen . set ( id , op );
need ( e . reason , ` ${ op } (e ${ id } ): reason` );
return row ;
};
return { errors , need , asArray , ref };
}
// --- apply ------------------------------------------------------------------
function renderLog ( mf , applied , overflow ) {
const L = [ `# ${ mf . window } ` , '' , mf . summary , '' ];
const section = ( title , rows , fmt ) => {
if ( ! rows . length ) return ;
L . push ( `## ${ title } ` , '' );
for ( const r of rows ) L . push ( `- ${ fmt ( r ) } ` );
L . push ( '' );
};
section ( 'Insertions' , applied . insert ,
( e ) => `[e ${ e . id } ] → ring ${ e . ring . toUpperCase () } · ${ e . type } · ** ${ e . label } ** ${ e . detail ? ` — ${ e . detail } ` : '' } — ${ e . reason } ` );
section ( 'Touches' , applied . touch , ( t ) => `[e ${ t . row . id } ] ** ${ t . row . label } ** — ${ t . reason } ` );
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 } ` );
2026-11-11 18:30:29 +00:00
section ( 'Archived (rings → records)' , applied . archive , ( a ) => `[r ${ a . rid } ] [ ${ a . row . type } ] ** ${ a . row . label } ** ← [e ${ a . row . id } ] — ${ a . reason } ` );
2026-11-11 16:54:49 +00:00
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 ));
section ( 'Open questions' , mf . open_questions ?? [], ( s ) => String ( s ));
return L . join ( '\n' );
}
function cmdApply ( manifestPath ) {
const db = openDb ();
let mf ;
try {
mf = JSON . parse ( fs . readFileSync ( manifestPath , 'utf8' ));
} catch ( e ) {
fail ( `cannot read manifest ${ manifestPath } : ${ e . message } ` );
}
const { errors , need , asArray , ref } = makeValidator ( db );
need ( mf . window , 'window' );
need ( mf . date , 'date' );
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 . date === 'string' && ! /^\d{4}-\d{2}-\d{2}$/ . test ( mf . date )) {
errors . push ( 'date must be YYYY-MM-DD' );
}
const logFile = mf . window ? path . join ( LOG_DIR , ` ${ mf . window } .md` ) : null ;
if ( logFile && fs . existsSync ( logFile )) {
errors . push ( ` ${ rel ( logFile ) } already exists — delete it first if this is a re-run` );
}
const ins = asArray ( mf . insert , 'insert' );
const touch = asArray ( mf . touch , 'touch' );
const promote = asArray ( mf . promote , 'promote' );
const demote = asArray ( mf . demote , 'demote' );
const reword = asArray ( mf . reword , 'reword' );
const del = asArray ( mf . delete , 'delete' );
2026-11-11 18:30:29 +00:00
const rec = asArray ( mf . record , 'record' );
const arch = asArray ( mf . archive , 'archive' );
2026-11-11 16:54:49 +00:00
const inventions = asArray ( mf . inventions , 'inventions' );
const questions = asArray ( mf . open_questions , 'open_questions' );
2026-11-11 18:44:58 +00:00
if ( arch . length && ! recordsEnabled ()) {
errors . push ( 'this character keeps no records — archive ops are unavailable (see the run\'s settings.json)' );
}
if ( rec . length ) {
errors . push ( 'filing is not yours — record ops belong to the player at her desk (or the GM CLI); housekeeping is rings-only' );
2026-11-11 18:30:29 +00:00
}
2026-11-11 16:54:49 +00:00
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 ( '|' ) } ` );
need ( e . label , `insert[ ${ i } ].label` );
if ( e . detail !== undefined && typeof e . detail !== 'string' ) errors . push ( `insert[ ${ i } ].detail must be a string` );
need ( e . reason , `insert[ ${ i } ].reason` );
}
touch . forEach (( e ) => ref ( 'touch' , e , null ));
promote . forEach (( e ) => ref ( 'promote' , e , 'b' ));
demote . forEach (( e ) => ref ( 'demote' , e , 'a' ));
reword . forEach (( e ) => {
const row = ref ( 'reword' , e , null );
if ( row && ! String ( e . detail ?? '' ). trim ()) errors . push ( `reword (e ${ row . id } ): detail is required` );
});
del . forEach (( e ) => ref ( 'delete' , e , null ));
2026-11-11 18:30:29 +00:00
arch . forEach (( e ) => ref ( 'archive' , e , null ));
2026-11-11 16:54:49 +00:00
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` ); });
}
if ( errors . length ) {
console . error ( 'manifest rejected — nothing was applied:' );
for ( const e of errors ) console . error ( ` - ${ e } ` );
process . exit ( 1 );
}
2026-11-11 18:44:58 +00:00
const applied = { insert : [], touch : [], promote : [], demote : [], reword : [], delete : [], archive : [] };
2026-11-11 16:54:49 +00:00
const overflow = [];
db . exec ( 'BEGIN' );
try {
for ( const e of ins ) {
const id = insertEntry ( db , {
ring : e . ring , type : e . type , label : e . label , detail : e . detail ?? '' ,
date : mf . date , win : mf . window , reason : e . reason ,
});
applied . insert . push ({ id , ... e });
}
const touchDate = ( id ) => db . prepare ( 'UPDATE entries SET last_touched = ? WHERE id = ?' ). run ( mf . date , id );
const fetch = ( id ) => db . prepare ( 'SELECT * FROM entries WHERE id = ?' ). get ( id );
for ( const e of touch ) {
const id = parseId ( e . id );
touchDate ( id );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , 'touch' , `e ${ id } ` , e . reason );
2026-11-11 16:54:49 +00:00
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 );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , 'promote' , `e ${ id } ` , e . reason );
2026-11-11 16:54:49 +00:00
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 );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , 'demote' , `e ${ id } ` , e . reason );
2026-11-11 16:54:49 +00:00
applied . demote . push ({ row : fetch ( id ), reason : e . reason });
}
for ( const e of reword ) {
const id = parseId ( e . id );
2026-11-11 17:58:39 +00:00
db . prepare ( 'UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?' ). run ( norm ( e . detail ), mf . date , id );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , 'reword' , `e ${ id } ` , e . reason );
2026-11-11 16:54:49 +00:00
applied . reword . push ({ row : fetch ( id ), detail : e . detail , reason : e . reason });
}
2026-11-11 18:30:29 +00:00
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 });
}
2026-11-11 16:54:49 +00:00
for ( const e of del ) {
const id = parseId ( e . id );
db . prepare ( "UPDATE entries SET ring = 'cold' WHERE id = ?" ). run ( id );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , 'delete' , `e ${ id } ` , e . reason );
2026-11-11 16:54:49 +00:00
applied . delete . push ({ row : fetch ( id ), reason : e . reason });
}
// overflow: A spills to B first, then B spills to cold — exact, by count
for ( const ring of RINGS ) {
const rows = db . prepare (
'SELECT id FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC'
). all ( ring );
const extra = rows . length - CAPS [ ring ];
for ( let i = 0 ; i < extra ; i ++ ) {
const victim = rows [ i ];
const dest = ring === 'a' ? 'b' : 'cold' ;
db . prepare ( 'UPDATE entries SET ring = ? WHERE id = ?' ). run ( dest , victim . id );
2026-11-11 18:30:29 +00:00
journal ( db , mf . window , ring === 'a' ? 'demote' : 'evict' , `e ${ victim . id } ` , `ring ${ ring . toUpperCase () } overflow (auto)` );
2026-11-11 16:54:49 +00:00
overflow . push ({ id : victim . id , from : ring , to : dest });
}
}
db . exec ( 'COMMIT' );
} catch ( e ) {
db . exec ( 'ROLLBACK' );
fail ( `transaction failed, rolled back: ${ e . message } ` );
}
fs . mkdirSync ( LOG_DIR , { recursive : true });
fs . writeFileSync ( logFile , renderLog ( mf , applied , overflow ));
2026-11-11 18:25:09 +00:00
console . log ( `applied [ ${ RUN } ] ${ mf . window } : ` + [
2026-11-11 16:54:49 +00:00
applied . insert . length && ` ${ applied . insert . length } inserted` ,
applied . touch . length && ` ${ applied . touch . length } touched` ,
applied . promote . length && ` ${ applied . promote . length } promoted` ,
applied . demote . length && ` ${ applied . demote . length } demoted` ,
applied . reword . length && ` ${ applied . reword . length } reworded` ,
2026-11-11 18:30:29 +00:00
applied . archive . length && ` ${ applied . archive . length } archived` ,
2026-11-11 16:54:49 +00:00
applied . delete . length && ` ${ applied . delete . length } deleted` ,
overflow . length && ` ${ overflow . length } overflow` ,
]. filter ( Boolean ). join ( ', ' ));
console . log ( `log: ${ rel ( logFile ) } ` );
renderAll ( db );
2026-11-11 17:58:39 +00:00
console . log ( `dump: ${ rel ( dumpDb ( db )) } ` );
2026-11-11 16:54:49 +00:00
}
// --- simple commands ---------------------------------------------------------
function cmdInit () {
2026-11-11 18:25:09 +00:00
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 , '' );
}
2026-11-11 16:54:49 +00:00
const db = new DatabaseSync ( DB_PATH );
db . exec ( fs . readFileSync ( SCHEMA_PATH , 'utf8' ));
2026-11-11 18:30:29 +00:00
if ( ! fs . existsSync ( SETTINGS_PATH )) {
fs . writeFileSync ( SETTINGS_PATH , JSON . stringify ({ records : false }, null , 2 ) + '\n' );
}
2026-11-11 18:25:09 +00:00
console . log ( `initialized run ' ${ RUN } ': ${ rel ( DB_PATH ) } ` );
dumpDb ( db );
renderAll ( db );
}
function cmdRuns () {
if ( ! fs . existsSync ( RUNS_DIR )) { console . log ( '(no runs)' ); return ; }
for ( const d of fs . readdirSync ( RUNS_DIR , { withFileTypes : true })) {
if ( ! d . isDirectory ()) continue ;
const dbPath = path . join ( RUNS_DIR , d . name , 'db' , 'memory.db' );
if ( ! fs . existsSync ( dbPath )) { console . log ( ` ${ d . name } : (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' ) } ` );
}
2026-11-11 16:54:49 +00:00
}
function today () { return new Date (). toISOString (). slice ( 0 , 10 ); }
function gmOp ( ring , type , label , detail ) {
const db = openDb ();
if ( ! RINGS . includes ( ring ) || ! TYPES . includes ( type )) {
fail ( `usage: insert <a|b> < ${ TYPES . join ( '|' ) } > "Label" "detail"` );
}
db . exec ( 'BEGIN' );
let id ;
try {
id = insertEntry ( db , { ring , type , label , detail : detail ?? '' , date : today (), win : 'gm' , reason : 'GM edit' });
db . exec ( 'COMMIT' );
} catch ( e ) {
db . exec ( 'ROLLBACK' );
fail ( e . message );
}
console . log ( `inserted [e ${ id } ] → ring ${ ring . toUpperCase () } ` );
renderAll ( db );
2026-11-11 17:58:39 +00:00
dumpDb ( db );
2026-11-11 16:54:49 +00:00
}
function cmdDelete ( idStr , reason ) {
const db = openDb ();
const id = parseId ( idStr );
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 );
2026-11-11 18:30:29 +00:00
journal ( db , 'gm' , 'delete' , `e ${ id } ` , reason ?? 'GM edit' );
2026-11-11 16:54:49 +00:00
console . log ( `[e ${ id } ] ** ${ row . label } ** → cold storage` );
renderAll ( db );
2026-11-11 17:58:39 +00:00
dumpDb ( db );
2026-11-11 16:54:49 +00:00
}
function cmdRevive ( idStr , ring = 'b' ) {
const db = openDb ();
const id = parseId ( idStr );
const row = id && db . prepare ( 'SELECT * FROM entries WHERE id = ?' ). get ( id );
if ( ! row ) fail ( `no such entry: ${ idStr } ` );
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 );
2026-11-11 18:30:29 +00:00
journal ( db , 'gm' , 'revive' , `e ${ id } ` , 'GM revive' );
2026-11-11 16:54:49 +00:00
console . log ( `[e ${ id } ] ** ${ row . label } ** revived → ring ${ ring . toUpperCase () } ` );
renderAll ( db );
2026-11-11 17:58:39 +00:00
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 );
2026-11-11 16:54:49 +00:00
}
2026-11-11 18:44:58 +00:00
function cmdFile ( kind , label , detail , reason ) {
2026-11-11 18:30:29 +00:00
const db = openDb ();
if ( ! recordsEnabled ()) fail ( 'this character keeps no records — nothing to file (see the run\'s settings.json)' );
2026-11-11 18:44:58 +00:00
if ( ! kind ? . trim () || ! label ? . trim ()) fail ( 'usage: file <kind> "Label" "detail"' );
2026-11-11 18:30:29 +00:00
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 );
2026-11-11 18:44:58 +00:00
journal ( db , AS_GM ? 'gm' : 'pc' , 'record' , `r ${ rid } ` , reason ?? ( AS_GM ? 'GM seed' : 'player filing' ));
2026-11-11 18:30:29 +00:00
console . log ( `filed [r ${ rid } ] [ ${ norm ( kind ) } ] ** ${ norm ( label ) } **` );
dumpDb ( db );
}
2026-11-11 18:44:58 +00:00
function cmdAmend ( ridStr , detail ) {
const db = openDb ();
if ( ! recordsEnabled ()) fail ( 'this character keeps no records' );
const rid = parseRid ( ridStr );
const row = rid && db . prepare ( 'SELECT * FROM records WHERE id = ?' ). get ( rid );
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' );
console . log ( `amended [r ${ rid } ] ** ${ row . label } ** — ${ norm ( detail ) } ` );
dumpDb ( db );
}
function cmdDiscard ( ridStr , reason ) {
const db = openDb ();
if ( ! recordsEnabled ()) fail ( 'this character keeps no records' );
const rid = parseRid ( ridStr );
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' );
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, 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' : 'player declaration' ));
console . log ( `status ${ norm ( key ) } : ${ norm ( value ) } ` );
renderAll ( db );
dumpDb ( db );
}
function cmdUnset ( key ) {
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 } ` , 'cleared' );
console . log ( `status ${ row . key } : cleared` );
renderAll ( db );
dumpDb ( db );
}
2026-11-11 18:30:29 +00:00
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 );
}
2026-11-11 16:54:49 +00:00
function cmdStatus () {
const db = openDb ();
2026-11-11 18:30:29 +00:00
console . log ( `run: ${ RUN }${ recordsEnabled () ? '' : ' (no records)' } ` );
const nr = db . prepare ( 'SELECT COUNT(*) AS n FROM records' ). get (). n ;
console . log ( `records: ${ nr } ` );
2026-11-11 18:44:58 +00:00
const sk = db . prepare ( 'SELECT key FROM status ORDER BY updated DESC, key' ). all (). map (( r ) => r . key );
console . log ( `status: ${ sk . length ? sk . join ( ', ' ) : '(nothing set)' } ` );
2026-11-11 16:54:49 +00:00
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 ] ?? '∞' ;
console . log ( `ring ${ ring } : ${ n } / ${ cap } ` );
if ( ring !== 'cold' ) {
const old = db . prepare (
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
). all ( ring );
for ( const r of old ) console . log ( ` sinking: [e ${ r . id } ] ${ r . last_touched } ** ${ r . label } **` );
}
}
}
// --- dispatch ----------------------------------------------------------------
switch ( cmd ) {
2026-11-11 18:25:09 +00:00
case 'runs' : cmdRuns (); break ;
2026-11-11 16:54:49 +00:00
case 'init' : cmdInit (); break ;
case 'render' : renderAll ( openDb ()); break ;
case 'apply' : args [ 0 ] ? cmdApply ( args [ 0 ]) : fail ( 'usage: apply <manifest.json>' ); break ;
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 ;
2026-11-11 18:44:58 +00:00
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 'unset' : ( args . length >= 1 ) ? cmdUnset ( args [ 0 ]) : fail ( 'usage: unset <key>' ); break ;
2026-11-11 18:30:29 +00:00
case 'search' : cmdSearch ( args ); break ;
case 'unarchive' : ( args . length >= 1 ) ? cmdUnarchive ( args [ 0 ], args [ 1 ]) : fail ( 'usage: unarchive <rid> [a|b]' ); break ;
2026-11-11 16:54:49 +00:00
case 'status' : cmdStatus (); break ;
2026-11-11 17:58:39 +00:00
case 'dump' : cmdDump (); break ;
case 'restore' : cmdRestore ( args [ 0 ] === '--force' ); break ;
2026-11-11 16:54:49 +00:00
default :
2026-11-11 17:58:39 +00:00
console . error ( 'usage: node tool/memory.mjs <init|render|apply|insert|delete|revive|dump|restore|status>' );
2026-11-11 16:54:49 +00:00
process . exit ( 1 );
}