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-13 23:40:33 +00:00
// packages list packages (presets) and their flags
// runs list runs (instances) and their fill levels
2026-11-14 09:04:13 +00:00
// create <package> <pc-name> create a run: copy the package wholesale
2026-11-13 23:40:33 +00:00
// (shared prompts included — battery
2026-11-14 09:04:13 +00:00
// included), give it an anonymous id and
// the pc's name (distinct per package),
// init the db, render the views.
2026-11-13 23:40:33 +00:00
// From then on the run dir is the only
// truth; the package is never read again.
2026-11-14 20:01:15 +00:00
// save-package "display name" save this run's craft as a new user
// package (state/packages/, published to
// all; pc never rides; --owner stamps)
2026-11-13 23:40:33 +00:00
// 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
2026-11-11 16:54:49 +00:00
// 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-13 23:40:33 +00:00
// 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
2026-11-14 09:04:13 +00:00
// (no descrs = clear it)
2026-11-13 23:40:33 +00:00
// paper-ingest <file> read a file's <status> block into the paper
// (turn-0 at new-game)
2026-11-11 19:02:11 +00:00
// pick "a" "b" "c" ... dice for prose — uniform random choice
2026-11-11 17:58:39 +00:00
// dump canonical dump to dumps/memory.sql
// (also auto-written by every mutation)
2026-11-11 18:52:04 +00:00
// restore --force rebuild the db from dumps/memory.sql
2026-11-13 23:40:33 +00:00
// commands take --run <id> (a run under runs/); state is per-deployment.
2026-11-11 18:25:09 +00:00
//
2026-11-13 23:40:33 +00:00
// status counts, caps, the paper, what's sinking
2026-11-11 16:54:49 +00:00
import { DatabaseSync } from 'node:sqlite' ;
2026-11-14 09:04:13 +00:00
import { randomBytes } from 'node:crypto' ;
2026-11-11 16:54:49 +00:00
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-13 05:16:31 +00:00
const PACKAGES_DIR = path . join ( ROOT , 'packages' );
2026-11-14 20:01:15 +00:00
const STATE_PACKAGES_DIR = path . join ( ROOT , 'state' , 'packages' );
2026-11-13 23:40:33 +00:00
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-13 23:40:33 +00:00
// flags: --run <name> beats everything; --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:52:04 +00:00
const FORCE = argv . includes ( '--force' );
for ( let i = argv . indexOf ( '--force' ); i !== - 1 ; i = argv . indexOf ( '--force' )) argv . splice ( i , 1 );
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 21:14:50 +00:00
const QUIET = argv . includes ( '--quiet' );
for ( let i = argv . indexOf ( '--quiet' ); i !== - 1 ; i = argv . indexOf ( '--quiet' )) argv . splice ( i , 1 );
2026-11-14 03:15:53 +00:00
const AS_JSON = argv . includes ( '--json' );
for ( let i = argv . indexOf ( '--json' ); i !== - 1 ; i = argv . indexOf ( '--json' )) argv . splice ( i , 1 );
2026-11-14 20:01:15 +00:00
const ownerIdx = argv . indexOf ( '--owner' );
let ownerOverride = null ;
if ( ownerIdx !== - 1 ) {
ownerOverride = argv [ ownerIdx + 1 ] ?? null ;
argv . splice ( ownerIdx , 2 );
}
2026-11-11 18:25:09 +00:00
const [ cmd , ... args ] = argv ;
2026-11-13 23:40:33 +00:00
// 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 ))) {
2026-11-14 09:04:13 +00:00
fail ( 'no run specified — use --run <id> (see: runs); runs are created with: create <package> <pc-name>' );
2026-11-11 18:25:09 +00:00
}
2026-11-13 23:40:33 +00:00
// 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' );
2026-11-11 18:25:09 +00:00
}
2026-11-13 23:40:33 +00:00
setRunRoot ( path . join ( RUNS_DIR , RUN ?? '' ));
2026-11-11 18:30:29 +00:00
2026-11-14 03:15:53 +00:00
const BACKDROP_TEMPLATE = `# Backdrop
2026-11-11 18:52:04 +00:00
(One to three paragraphs: what any inhabitant of this world knows — the
place, the era, how things work here. Common knowledge, not what any
2026-11-14 03:15:53 +00:00
particular character learned. Never memory, never forgotten: it never
touches the rings and is always in the bundle.)
2026-11-11 18:52:04 +00:00
` ;
const CARD_TEMPLATE = `# <name>
2026-11-14 03:15:53 +00:00
(Fill this in before window one. Five lines is plenty; freeform beats
complete. Blank fields are the player's to invent through play — the
GM ratifies notable inventions afterward.)
2026-11-11 18:52:04 +00:00
- **Concept:** one line
- **Drives:** what they want, generally
- **Edges:** what they're good at
- **Flaws:** what gets in their way
- **Voice:** how they talk — register, tics, what they'd never say
- **Doesn't know:** (optional) what's plausibly outside their world
Freeform notes:
` ;
2026-11-11 18:30:29 +00:00
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 ;
};
2026-11-13 23:40:33 +00:00
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 );
2026-11-11 16:54:49 +00:00
2026-11-14 03:15:53 +00:00
// generated views: the ring and status files are machine-written — never
// hand-edit them (regenerate with render). The do-not-edit warning lives
// here rather than in the output: prose files carry no comments, purpose
// text lives in code or README.
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 = [
`# Ring ${ ring . toUpperCase () } — ${ title } ` ,
'' ,
];
if ( rows . length === 0 ) lines . push ( '(empty — nothing here yet)' );
for ( const r of rows ) {
2026-11-14 09:04:13 +00:00
lines . push ( `- [e ${ r . id } ] [ ${ r . type } ] ** ${ r . label } ** ${ r . detail ? ` — ${ r . detail } ` : '.' } ` );
2026-11-11 16:54:49 +00:00
}
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 ) {
2026-11-13 23:40:33 +00:00
const rows = db . prepare ( 'SELECT * FROM paper ORDER BY id' ). all ();
2026-11-11 18:44:58 +00:00
const lines = [
2026-11-13 23:40:33 +00:00
'# Status — her paper' ,
2026-11-11 18:44:58 +00:00
'' ,
2026-11-14 03:15:53 +00:00
'The paper is the player\'s — stances and feelings; facts live in the rings.' ,
'' ,
2026-11-11 18:44:58 +00:00
];
2026-11-13 23:40:33 +00:00
if ( ! rows . length ) lines . push ( '(a blank sheet — fresh start)' );
for ( const r of rows ) lines . push ( `- ${ r . descr } ` );
2026-11-11 18:44:58 +00:00
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 );
2026-11-11 21:14:50 +00:00
if ( ! QUIET ) console . log ( ` ${ rel ( file ) } — ${ count } entries` );
2026-11-11 16:54:49 +00:00
}
2026-11-11 18:44:58 +00:00
const { file , count } = renderStatus ( db );
2026-11-13 23:40:33 +00:00
if ( ! QUIET ) console . log ( ` ${ rel ( file ) } — ${ count } descriptions` );
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-13 23:40:33 +00:00
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 ) } );` );
2026-11-11 18:44:58 +00:00
}
2026-11-11 17:58:39 +00:00
for ( const r of db . prepare ( 'SELECT * FROM events ORDER BY id' ). all ()) {
2026-11-13 23:40:33 +00:00
L . push ( `INSERT INTO events VALUES ( ${ r . id } , ${ q ( r . window ) } , ${ q ( r . op ) } , ${ q ( r . target ) } , ${ q ( r . reason ) } , ${ q ( r . prior ) } );` );
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-14 09:04:13 +00:00
// stamps are mechanical (real, internal, never rendered): they drive
// the LRU — overflow, view order, "what's sinking". Story time lives
// in the prose of the entries, never in a column.
function insertEntry ( db , { ring , type , label , detail , win , reason }) {
const now = today ();
2026-11-11 16:54:49 +00:00
const res = db . prepare (
'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)'
2026-11-14 09:04:13 +00:00
). run ( ring , type , norm ( label ), norm ( detail ), now , now );
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' );
}
2026-11-11 18:52:04 +00:00
function cmdSeed ( force , seedPathArg ) {
const db = openDb ();
const seedPath = seedPathArg ? path . resolve ( seedPathArg ) : path . join ( RUN_ROOT , 'seed.json' );
if ( ! fs . existsSync ( seedPath )) fail ( `no seed file at ${ rel ( seedPath ) } — write one (see README: Booting a run)` );
const prior = db . prepare ( 'SELECT COUNT(*) AS n FROM events' ). get (). n ;
if ( prior > 0 && ! force ) {
fail ( 'this run already has history — seed is a pre-story migration (--force only on a disposable db)' );
}
let sf ;
try {
sf = JSON . parse ( fs . readFileSync ( seedPath , 'utf8' ));
} catch ( e ) {
fail ( `cannot read seed ${ seedPath } : ${ e . message } ` );
}
const errors = [];
const entries = sf . entries ?? [];
const records = sf . records ?? [];
if ( ! Array . isArray ( entries )) { errors . push ( 'entries must be an array' ); }
2026-11-13 23:40:33 +00:00
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)' );
}
2026-11-11 18:52:04 +00:00
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` );
if ( ! TYPES . includes ( e . type )) errors . push ( `entries[ ${ i } ].type must be ${ TYPES . join ( '|' ) } ` );
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` );
}
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` );
}
if ( Array . isArray ( records ) && records . length && ! recordsEnabled ()) {
errors . push ( 'this character keeps no records — records in seed violate the gate (see the run\'s settings.json)' );
}
if ( errors . length ) {
console . error ( 'seed rejected — nothing was applied:' );
for ( const e of errors ) console . error ( ` - ${ e } ` );
process . exit ( 1 );
}
db . exec ( 'BEGIN' );
try {
2026-11-14 09:04:13 +00:00
const now = today ();
2026-11-11 18:52:04 +00:00
for ( const e of entries ) {
const res = db . prepare ( 'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)' )
2026-11-14 09:04:13 +00:00
. run ( e . ring , e . type , norm ( e . label ), norm ( e . detail ?? '' ), now , now );
2026-11-11 18:52:04 +00:00
journal ( db , 'seed' , 'insert' , `e ${ Number ( res . lastInsertRowid ) } ` , 'seeded' );
}
for ( const r of records ) {
const res = db . prepare ( 'INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)' )
2026-11-14 09:04:13 +00:00
. run ( norm ( r . kind ), norm ( r . label ), norm ( r . detail ?? '' ), now );
2026-11-11 18:52:04 +00:00
journal ( db , 'seed' , 'record' , `r ${ Number ( res . lastInsertRowid ) } ` , 'seeded' );
}
db . exec ( 'COMMIT' );
} catch ( e ) {
db . exec ( 'ROLLBACK' );
fail ( `seed failed, rolled back: ${ e . message } ` );
}
2026-11-14 09:04:13 +00:00
console . log ( `seeded [ ${ RUN } ]: ${ entries . length } entries, ${ records . length } records` );
2026-11-11 18:52:04 +00:00
renderAll ( db );
dumpDb ( db );
}
2026-11-11 16:54:49 +00:00
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 . 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)' );
}
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 ?? '' ,
2026-11-14 09:04:13 +00:00
win : mf . window , reason : e . reason ,
2026-11-11 16:54:49 +00:00
});
applied . insert . push ({ id , ... e });
}
2026-11-14 09:04:13 +00:00
const touchDate = ( id ) => db . prepare ( 'UPDATE entries SET last_touched = ? WHERE id = ?' ). run ( today (), id );
2026-11-11 16:54:49 +00:00
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 );
2026-11-14 09:04:13 +00:00
db . prepare ( "UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?" ). run ( today (), 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 );
2026-11-14 09:04:13 +00:00
db . prepare ( "UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?" ). run ( today (), 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-14 09:04:13 +00:00
db . prepare ( 'UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?' ). run ( norm ( e . detail ), today (), 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-14 03:15:53 +00:00
const dumpFile = dumpDb ( db );
// per-wrap snapshot: the committed-truth successor now that runs are
// gitignored — diffing consecutive snapshots reconstructs the window's
// operations for async review
const snapshot = path . join ( DUMPS_DIR , ` ${ mf . window } .sql` );
fs . copyFileSync ( dumpFile , snapshot );
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-14 03:15:53 +00:00
console . log ( `dump: ${ rel ( dumpFile ) } | snapshot: ${ rel ( snapshot ) } ` );
2026-11-11 16:54:49 +00:00
}
// --- simple commands ---------------------------------------------------------
function cmdInit () {
2026-11-13 23:40:33 +00:00
for ( const d of [ 'db' , 'canon' , 'dumps' , 'log' , 'manifests' , 'sessions' ]) {
fs . mkdirSync ( path . join ( RUN_ROOT , d ), { recursive : true });
2026-11-11 18:25:09 +00:00
}
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:52:04 +00:00
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' );
if ( ! fs . existsSync ( card )) fs . writeFileSync ( card , CARD_TEMPLATE );
2026-11-11 18:25:09 +00:00
console . log ( `initialized run ' ${ RUN } ': ${ rel ( DB_PATH ) } ` );
dumpDb ( db );
renderAll ( db );
}
2026-11-13 23:40:33 +00:00
// --- packages and runs --------------------------------------------------------
//
2026-11-14 20:01:15 +00:00
// A package is a preset: authored content only, no state. Packages
// come from two roots: system (repo, authored, read-only) and user
// (state/packages, saved from a run, published to everyone). 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, the owner
// (multiuser), and an optional model override.
2026-11-13 23:40:33 +00:00
const PACKAGE_FILES = [ 'backdrop.md' , 'turn-0.md' , 'character.md' , 'seed.json' , 'settings.json' , 'gm.md' ];
2026-11-14 03:15:53 +00:00
// battery included, copied per run and then the run's to edit: the craft
2026-11-14 09:04:13 +00:00
// tier. housekeeper.md is substrate-internal like invariants.md —
// repo-fed at wrap time, never copied, never user-exposed; system.md
// and invariants.md are likewise repo-fed at assembly (opening+guards,
// substrate facts)
const SHARED_PROMPTS = [ 'handbook.md' ];
2026-11-13 23:40:33 +00:00
2026-11-14 20:01:15 +00:00
// resolve a package name against both roots; the repo wins a collision
function packageDir ( name ) {
if ( ! /^[a-z0-9-]+$/ . test ( name ?? '' )) return null ;
if ( fs . existsSync ( path . join ( PACKAGES_DIR , name ))) return path . join ( PACKAGES_DIR , name );
if ( fs . existsSync ( path . join ( STATE_PACKAGES_DIR , name ))) return path . join ( STATE_PACKAGES_DIR , name );
return null ;
}
// the package meta of a user package (owner, created); system packages
// have none — their origin is the repo itself
function readPackageMeta ( dir ) {
try {
return JSON . parse ( fs . readFileSync ( path . join ( dir , 'package.json' ), 'utf8' ));
} catch {
return null ;
}
}
function packageEntry ( name , dir , origin ) {
const has = ( f ) => fs . existsSync ( path . join ( dir , f ));
let settings = {};
try { settings = JSON . parse ( fs . readFileSync ( path . join ( dir , 'settings.json' ), 'utf8' )); } catch {}
const meta = origin === 'user' ? readPackageMeta ( dir ) : null ;
return {
name ,
origin ,
...( origin === 'user' ? { owner : meta ? . owner ?? null } : {}),
display : settings . name ?? name ,
pc : settings . pc ?? null ,
records : settings . records === true ,
turn0 : has ( 'turn-0.md' ), seed : has ( 'seed.json' ),
complete : has ( 'backdrop.md' ) && has ( 'character.md' ),
};
}
2026-11-13 23:40:33 +00:00
function cmdPackages () {
2026-11-14 03:15:53 +00:00
const list = [];
2026-11-14 20:01:15 +00:00
const scan = ( root , origin ) => {
if ( ! fs . existsSync ( root )) return ;
for ( const d of fs . readdirSync ( root , { withFileTypes : true })) {
if ( ! d . isDirectory ()) continue ;
list . push ( packageEntry ( d . name , path . join ( root , d . name ), origin ));
}
};
scan ( PACKAGES_DIR , 'system' );
scan ( STATE_PACKAGES_DIR , 'user' );
list . sort (( a , b ) => a . name . localeCompare ( b . name ));
2026-11-14 03:15:53 +00:00
if ( AS_JSON ) { console . log ( JSON . stringify ( list )); return ; }
2026-11-14 20:01:15 +00:00
if ( ! list . length ) { console . log ( '(no packages)' ); return ; }
2026-11-14 03:15:53 +00:00
for ( const x of list ) {
2026-11-14 20:01:15 +00:00
console . log ( ` ${ x . name } : ${ x . display } [ ${ x . origin } ] — records ${ x . records ? 'on' : 'off' } · turn-0 ${ x . turn0 ? 'yes' : 'no' } · seed ${ x . seed ? 'yes' : 'no' } · backdrop+card ${ x . complete ? 'ok' : 'MISSING' } ` );
2026-11-14 09:04:13 +00:00
}
}
// run ids are anonymous: they carry no facts, so there is nothing to
// rename and nothing for a name to collide with. The names that
// matter — the package display name and the pc's name — live in the
// run's settings copy and drive the display ("La Caramba / Rell").
const readRunSettings = ( runDir ) => {
try { return JSON . parse ( fs . readFileSync ( path . join ( runDir , 'settings.json' ), 'utf8' )); } catch { return {}; }
};
const runDisplay = ( pkg , settings ) =>
settings . pc ? ` ${ settings . name ?? pkg } / ${ settings . pc } ` : ( settings . name ?? pkg );
function anonId () {
for (;;) {
const id = randomBytes ( 4 ). toString ( 'hex' ); // 8 hex chars
if ( ! fs . existsSync ( path . join ( RUNS_DIR , id ))) return id ;
2026-11-13 23:40:33 +00:00
}
}
2026-11-14 09:04:13 +00:00
function cmdCreate ( pkgName , pc , displayName , model ) {
if ( ! pkgName || ! /^[a-z0-9-]+$/ . test ( pkgName ) || ! pc || ! String ( pc ). trim ()) {
fail ( 'usage: create <package> <pc-name> ["package display name"] ["model"]' );
2026-11-13 23:40:33 +00:00
}
2026-11-14 20:01:15 +00:00
const pkgDir = packageDir ( pkgName );
if ( ! pkgDir ) fail ( `no such package: ${ pkgName } — see: packages` );
2026-11-14 09:04:13 +00:00
pc = String ( pc ). trim ();
// different runs of the same package require different pc names
if ( fs . existsSync ( RUNS_DIR )) {
for ( const d of fs . readdirSync ( RUNS_DIR , { withFileTypes : true })) {
2026-11-14 20:01:15 +00:00
if ( ! d . isDirectory () || d . name . startsWith ( '.' )) continue ; // .staging-* is never a run
2026-11-14 09:04:13 +00:00
const rd = path . join ( RUNS_DIR , d . name );
let meta = null ;
try { meta = JSON . parse ( fs . readFileSync ( path . join ( rd , 'run.json' ), 'utf8' )); } catch { continue ; }
if ( meta ? . package !== pkgName ) continue ;
const st = readRunSettings ( rd );
if ( String ( st . pc ?? '' ). toLowerCase () === pc . toLowerCase ()) {
fail ( `a run of ' ${ pkgName } ' named ' ${ pc } ' already exists: ${ d . name } ` );
}
}
}
2026-11-13 23:40:33 +00:00
2026-11-14 09:04:13 +00:00
const runId = anonId ();
const runDir = path . join ( RUNS_DIR , runId );
2026-11-13 23:40:33 +00:00
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 ));
}
2026-11-14 09:04:13 +00:00
// first-class identity lands in the settings copy: the pc name is
// this run's own; the display name defaults to the package's
const settings = readRunSettings ( runDir );
settings . pc = pc ;
settings . name = displayName ? . trim () || settings . name || pkgName ;
fs . writeFileSync ( path . join ( runDir , 'settings.json' ), JSON . stringify ( settings , null , 2 ) + '\n' );
2026-11-13 23:40:33 +00:00
const meta = { package : pkgName , created : today () };
if ( model ) meta . model = model ;
2026-11-14 20:01:15 +00:00
if ( ownerOverride ) meta . owner = ownerOverride ;
2026-11-13 23:40:33 +00:00
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' ));
2026-11-14 09:04:13 +00:00
if ( AS_JSON ) { console . log ( JSON . stringify ({ id : runId , package : pkgName , name : settings . name , pc })); return ; }
console . log ( `created run ' ${ runId } ' — ${ runDisplay ( pkgName , settings ) } : ${ rel ( runDir ) } ` );
2026-11-13 23:40:33 +00:00
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 () {
2026-11-14 09:04:13 +00:00
if ( ! fs . existsSync ( RUNS_DIR )) { if ( AS_JSON ) console . log ( '[]' ); else console . log ( '(no runs — create one: create <package> <pc-name>)' ); return ; }
2026-11-14 03:15:53 +00:00
const list = [];
2026-11-13 23:40:33 +00:00
let found = 0 ;
for ( const d of fs . readdirSync ( RUNS_DIR , { withFileTypes : true })) {
2026-11-14 20:01:15 +00:00
if ( ! d . isDirectory () || d . name . startsWith ( '.' )) continue ; // .staging-* is never a run
2026-11-13 23:40:33 +00:00
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 = '?' ;
2026-11-14 03:15:53 +00:00
let model = null ;
2026-11-14 20:01:15 +00:00
let owner = null ;
let created = null ;
let forked = null ;
2026-11-14 03:15:53 +00:00
try {
const meta = JSON . parse ( fs . readFileSync ( path . join ( runDir , 'run.json' ), 'utf8' ));
pkg = meta . package ?? '?' ;
model = meta . model ?? null ;
2026-11-14 20:01:15 +00:00
owner = meta . owner ?? null ;
created = meta . created ?? null ;
forked = meta . forked ?? null ;
2026-11-14 03:15:53 +00:00
} catch {}
2026-11-14 09:04:13 +00:00
const st = readRunSettings ( runDir );
2026-11-14 20:01:15 +00:00
const base = { id : d . name , package : pkg , model , owner , created , forked , pc : st . pc ?? null , display : runDisplay ( pkg , st ) };
2026-11-13 23:40:33 +00:00
const dbPath = path . join ( runDir , 'db' , 'memory.db' );
2026-11-14 09:04:13 +00:00
if ( ! fs . existsSync ( dbPath )) { list . push ({ ... base , initialized : false }); continue ; }
2026-11-11 18:25:09 +00:00
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 ;
2026-11-14 09:04:13 +00:00
list . push ({ ... base , initialized : true , fill : { a : n ( 'a' ), b : n ( 'b' ), cold : n ( 'cold' ) } });
2026-11-14 03:15:53 +00:00
}
if ( AS_JSON ) { console . log ( JSON . stringify ( list )); return ; }
for ( const x of list ) {
2026-11-14 09:04:13 +00:00
if ( ! x . initialized ) { console . log ( ` ${ x . id } [ ${ x . package } ]: ${ x . display } (not initialized)` ); continue ; }
console . log ( ` ${ x . id } [ ${ x . package } ]: ${ x . display } — a ${ x . fill . a } / ${ CAPS . a } · b ${ x . fill . b } / ${ CAPS . b } · cold ${ x . fill . cold } ` );
2026-11-11 18:25:09 +00:00
}
2026-11-14 09:04:13 +00:00
if ( ! found ) console . log ( '(no runs — create one: create <package> <pc-name>)' );
2026-11-11 16:54:49 +00:00
}
function today () { return new Date (). toISOString (). slice ( 0 , 10 ); }
2026-11-14 20:01:15 +00:00
// save the run's craft as a new user package: the same files create
// copies (plus handbook), published to every user of the deployment —
// gm.md included, because saving is the act of publishing. The saved
// package carries no pc (the next create asks for one); the display
// name is the save's one decision. The id is anonymous hex, like a
// run's: no facts, nothing to rename.
function cmdSavePackage ( displayName ) {
const name = String ( displayName ?? '' ). trim ();
if ( ! name ) fail ( 'usage: save-package "display name" (run required via --run)' );
let id ;
for (;;) {
id = randomBytes ( 4 ). toString ( 'hex' );
if ( ! fs . existsSync ( path . join ( STATE_PACKAGES_DIR , id )) && ! fs . existsSync ( path . join ( PACKAGES_DIR , id ))) break ;
}
const dst = path . join ( STATE_PACKAGES_DIR , id );
fs . mkdirSync ( dst , { recursive : true });
for ( const f of [... PACKAGE_FILES , ... SHARED_PROMPTS ]) {
const src = path . join ( RUN_ROOT , f );
if ( fs . existsSync ( src )) fs . copyFileSync ( src , path . join ( dst , f ));
}
const settingsPath = path . join ( dst , 'settings.json' );
let settings = {};
try { settings = JSON . parse ( fs . readFileSync ( settingsPath , 'utf8' )); } catch {}
settings . name = name ;
delete settings . pc ; // per-run identity never rides a package
fs . writeFileSync ( settingsPath , JSON . stringify ( settings , null , 2 ) + '\n' );
fs . writeFileSync ( path . join ( dst , 'package.json' ), JSON . stringify ({
owner : ownerOverride , created : today (),
}, null , 2 ) + '\n' );
if ( AS_JSON ) {
console . log ( JSON . stringify ({ id , name , origin : 'user' , owner : ownerOverride }));
return ;
}
console . log ( `saved package ' ${ id } ' — ${ name } : ${ rel ( dst ) } ` );
}
2026-11-11 16:54:49 +00:00
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 {
2026-11-14 09:04:13 +00:00
id = insertEntry ( db , { ring , type , label , detail : detail ?? '' , win : 'gm' , reason : 'GM edit' });
2026-11-11 16:54:49 +00:00
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 );
2026-11-13 23:40:33 +00:00
// 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 );
2026-11-11 18:44:58 +00:00
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 );
2026-11-13 23:40:33 +00:00
// 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 }));
2026-11-11 18:44:58 +00:00
console . log ( `discarded [r ${ rid } ] ** ${ row . label } **` );
dumpDb ( db );
}
2026-11-13 23:40:33 +00:00
// --- 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 ())));
2026-11-11 18:44:58 +00:00
}
2026-11-13 23:40:33 +00:00
function cmdPaperApply ( text ) {
2026-11-11 19:02:11 +00:00
const db = openDb ();
2026-11-13 23:40:33 +00:00
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 ;
}
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 ) }));
2026-11-11 19:02:11 +00:00
renderAll ( db );
dumpDb ( db );
}
2026-11-13 23:40:33 +00:00
// 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 ) {
2026-11-11 19:02:11 +00:00
const db = openDb ();
2026-11-13 23:40:33 +00:00
const clean = setPaper ( db , items , AS_GM ? 'GM override' : 'paper set' , AS_GM ? 'gm' : 'pc' );
console . log ( JSON . stringify ( clean ));
2026-11-11 19:02:11 +00:00
renderAll ( db );
dumpDb ( db );
}
2026-11-13 23:40:33 +00:00
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 ]);
2026-11-11 18:44:58 +00:00
const db = openDb ();
2026-11-13 23:40:33 +00:00
setPaper ( db , items , `ingested from ${ path . basename ( p ) } ` , 'seed' );
console . log ( JSON . stringify ( paperList ( db )));
2026-11-11 18:44:58 +00:00
renderAll ( db );
dumpDb ( db );
}
2026-11-11 19:02:11 +00:00
function cmdPick ( options ) {
if ( options . length < 2 ) fail ( 'usage: pick "option one" "option two" [...]' );
const choice = options [ Math . floor ( Math . random () * options . length )];
console . log ( `picked: ${ choice } ` );
}
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 ; }
2026-11-14 09:04:13 +00:00
for ( const r of rows ) console . log ( `[r ${ r . id } ] [ ${ r . kind } ] ** ${ r . label } ** ${ r . detail ? ` — ${ r . detail } ` : '' } ` );
2026-11-11 18:30:29 +00:00
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-14 03:15:53 +00:00
if ( AS_JSON ) {
const out = {
run : RUN ,
records : db . prepare ( 'SELECT COUNT(*) AS n FROM records' ). get (). n ,
recordsEnabled : recordsEnabled (),
paper : paperList ( db ),
events : db . prepare ( 'SELECT COUNT(*) AS n FROM events' ). get (). n ,
rings : {},
sinking : {},
};
for ( const ring of [ 'a' , 'b' , 'cold' ]) {
out . rings [ ring ] = db . prepare ( 'SELECT COUNT(*) AS n FROM entries WHERE ring = ?' ). get ( ring ). n ;
if ( ring !== 'cold' ) {
out . sinking [ ring ] = db . prepare (
'SELECT id, last_touched, label FROM entries WHERE ring = ? ORDER BY last_touched ASC, id ASC LIMIT 5'
). all ( ring );
}
}
console . log ( JSON . stringify ( out ));
return ;
}
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-13 23:40:33 +00:00
const paper = paperList ( db );
console . log ( `paper: ${ paper . length ? '' : '(a blank sheet)' } ` );
for ( const d of paper ) console . log ( ` - ${ d } ` );
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-13 23:40:33 +00:00
case 'packages' : cmdPackages (); break ;
2026-11-11 18:25:09 +00:00
case 'runs' : cmdRuns (); break ;
2026-11-14 09:04:13 +00:00
case 'create' : cmdCreate ( args [ 0 ], args [ 1 ], args [ 2 ], args [ 3 ]); break ;
2026-11-14 20:01:15 +00:00
case 'save-package' : cmdSavePackage ( args [ 0 ]); break ;
2026-11-11 18:52:04 +00:00
case 'seed' : cmdSeed ( FORCE , args [ 0 ]); 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 ;
2026-11-13 23:40:33 +00:00
case 'paper' : cmdPaper (); break ;
case 'paper-apply' : ( args . length >= 1 ) ? cmdPaperApply ( args . join ( ' ' )) : fail ( 'usage: paper-apply "<turn text>"' ); break ;
2026-11-14 09:04:13 +00:00
case 'paper-set' : cmdPaperSet ( args ); break ; // no args = clear the paper (a legitimate GM override)
2026-11-13 23:40:33 +00:00
case 'paper-ingest' : ( args . length === 1 ) ? cmdPaperIngest ( args [ 0 ]) : fail ( 'usage: paper-ingest <file>' ); break ;
2026-11-11 19:02:11 +00:00
case 'pick' : cmdPick ( args ); 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 ;
2026-11-11 18:52:04 +00:00
case 'restore' : cmdRestore ( FORCE ); break ;
2026-11-11 16:54:49 +00:00
default :
2026-11-13 23:40:33 +00:00
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>' );
2026-11-11 16:54:49 +00:00
process . exit ( 1 );
}