agenda: the player's second paper (add/drop deltas, cap-5 recency queue); conflicts self-heal as their own turn; same-verb blocks combine; per-run model selection; substrate-tag syntax rule
This commit is contained in:
+184
-5
@@ -43,6 +43,14 @@
|
||||
// (no descrs = clear it)
|
||||
// paper-ingest <file> read a file's <status> block into the paper
|
||||
// (turn-0 at new-game)
|
||||
// agenda the agenda, as JSON (the intentions tier)
|
||||
// agenda-apply "<turn text>" apply <add>/<drop> deltas from a player
|
||||
// turn; drops are 0-based indexes against
|
||||
// the agenda as last rendered; JSON result
|
||||
// (added / dropped / evicted / conflicts /
|
||||
// agenda)
|
||||
// agenda-set "item" ... GM override: replace the whole agenda
|
||||
// (no items = clear it)
|
||||
// pick "a" "b" "c" ... dice for prose — uniform random choice
|
||||
// dump canonical dump to dumps/memory.sql
|
||||
// (also auto-written by every mutation)
|
||||
@@ -65,6 +73,7 @@ const RUNS_DIR = path.join(ROOT, 'runs');
|
||||
|
||||
// dials — retune freely
|
||||
const CAPS = { a: 500, b: 3000 };
|
||||
const AGENDA_CAP = 5; // dial — retune freely (invariants.md: "intentionally tiny")
|
||||
const TYPES = ['place', 'person', 'fact', 'thread'];
|
||||
const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models
|
||||
|
||||
@@ -154,9 +163,40 @@ function openDb() {
|
||||
}
|
||||
const db = new DatabaseSync(DB_PATH);
|
||||
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
|
||||
migrateEventsCheck(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
// the events CHECK names every legal op; a db opened before the agenda
|
||||
// carries the narrower list and would reject agenda journaling. SQLite
|
||||
// cannot alter a CHECK in place, so this rebuilds events once — the
|
||||
// table is append-only, the copy is exact. (Mirrors db/schema.sql.)
|
||||
function migrateEventsCheck(db) {
|
||||
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
|
||||
if (!row || row.sql.includes('agenda-add')) return;
|
||||
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.exec(`CREATE TABLE events_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
window TEXT NOT NULL,
|
||||
op TEXT NOT NULL CHECK (op IN ${OPS}),
|
||||
target TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
prior TEXT NOT NULL DEFAULT ''
|
||||
)`);
|
||||
db.exec('INSERT INTO events_new SELECT * FROM events');
|
||||
db.exec('DROP TABLE events');
|
||||
db.exec('ALTER TABLE events_new RENAME TO events');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS events_window ON events (window)');
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`events migration failed: ${e.message}`);
|
||||
}
|
||||
if (!QUIET) console.log(`(migrated: events journal widened for the agenda ops — ${rel(DB_PATH)})`);
|
||||
}
|
||||
|
||||
const parseId = (s) => {
|
||||
const m = /^e(\d+)$/.exec(String(s ?? '').trim());
|
||||
return m ? Number(m[1]) : null;
|
||||
@@ -214,6 +254,25 @@ function renderStatus(db) {
|
||||
return { file, count: rows.length };
|
||||
}
|
||||
|
||||
// the agenda view: the queue, top (newest) first, numbered as the wire
|
||||
// renders it — what the model cites, what the GM reads
|
||||
function renderAgenda(db) {
|
||||
const items = agendaList(db);
|
||||
const lines = [
|
||||
'# Agenda — what drives her',
|
||||
'',
|
||||
'The queue is the player\'s — intentions, not facts; facts live in the rings.',
|
||||
'',
|
||||
];
|
||||
if (!items.length) lines.push('(a clear head — nothing queued)');
|
||||
items.forEach((d, i) => lines.push(`- ${i}. ${d}`));
|
||||
lines.push('');
|
||||
const file = path.join(CANON_DIR, 'agenda.md');
|
||||
fs.mkdirSync(CANON_DIR, { recursive: true });
|
||||
fs.writeFileSync(file, lines.join('\n'));
|
||||
return { file, count: items.length };
|
||||
}
|
||||
|
||||
function renderAll(db) {
|
||||
for (const ring of RINGS) {
|
||||
const { file, count } = renderRing(db, ring);
|
||||
@@ -221,6 +280,8 @@ function renderAll(db) {
|
||||
}
|
||||
const { file, count } = renderStatus(db);
|
||||
if (!QUIET) console.log(`${rel(file)} — ${count} descriptions`);
|
||||
const a = renderAgenda(db);
|
||||
if (!QUIET) console.log(`${rel(a.file)} — ${a.count} queued`);
|
||||
}
|
||||
|
||||
// canonical serialization: id-ordered, one row per line, restorable SQL.
|
||||
@@ -243,6 +304,9 @@ function dumpDb(db) {
|
||||
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)});`);
|
||||
}
|
||||
for (const r of db.prepare('SELECT * FROM agenda ORDER BY id').all()) {
|
||||
L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
|
||||
}
|
||||
for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) {
|
||||
L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
|
||||
}
|
||||
@@ -693,7 +757,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
|
||||
settings.name = displayName?.trim() || settings.name || pkgName;
|
||||
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
|
||||
const meta = { package: pkgName, created: today() };
|
||||
if (model) meta.model = model;
|
||||
if (model) meta.models = { player: model };
|
||||
if (ownerOverride) meta.owner = ownerOverride;
|
||||
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
|
||||
|
||||
@@ -720,20 +784,20 @@ function cmdRuns() {
|
||||
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
|
||||
found++;
|
||||
let pkg = '?';
|
||||
let model = null;
|
||||
let models = null;
|
||||
let owner = null;
|
||||
let created = null;
|
||||
let forked = null;
|
||||
try {
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8'));
|
||||
pkg = meta.package ?? '?';
|
||||
model = meta.model ?? null;
|
||||
models = meta.models ?? null;
|
||||
owner = meta.owner ?? null;
|
||||
created = meta.created ?? null;
|
||||
forked = meta.forked ?? null;
|
||||
} catch {}
|
||||
const st = readRunSettings(runDir);
|
||||
const base = { id: d.name, package: pkg, model, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) };
|
||||
const base = { id: d.name, package: pkg, models, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) };
|
||||
const dbPath = path.join(runDir, 'db', 'memory.db');
|
||||
if (!fs.existsSync(dbPath)) { list.push({ ...base, initialized: false }); continue; }
|
||||
const db = new DatabaseSync(dbPath);
|
||||
@@ -993,6 +1057,117 @@ function cmdPaperIngest(filePath) {
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// --- the agenda (intentions tier) ---------------------------------------------
|
||||
//
|
||||
// The hot queue of what drives her: goals she is working towards right
|
||||
// now — intentions, never states (those are the paper's). Fixed cap
|
||||
// (a dial); id order IS queue order — adds land at the top in written
|
||||
// order, overflow evicts the bottom, a recency ring buffer for free.
|
||||
// The player mutates via <add>/<drop> in its own turns: drops are
|
||||
// 0-based indexes against the agenda as last rendered, adds are
|
||||
// comma-separated. The GM overrides whole-list with agenda-set.
|
||||
|
||||
const agendaList = (db) => db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all().map((r) => r.descr);
|
||||
|
||||
function cmdAgenda() {
|
||||
console.log(JSON.stringify(agendaList(openDb())));
|
||||
}
|
||||
|
||||
function cmdAgendaApply(text) {
|
||||
const db = openDb();
|
||||
const added = [];
|
||||
const dropped = [];
|
||||
const evicted = [];
|
||||
const conflicts = [];
|
||||
const adds = [];
|
||||
for (const m of String(text ?? '').matchAll(/<add>([\s\S]*?)<\/add>/g)) adds.push(...splitDescrs(m[1]));
|
||||
const drops = [];
|
||||
for (const m of String(text ?? '').matchAll(/<drop>([\s\S]*?)<\/drop>/g)) {
|
||||
drops.push(...String(m[1]).split(/[\n,]/).map((x) => x.trim()).filter(Boolean));
|
||||
}
|
||||
if (!adds.length && !drops.length) {
|
||||
console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) }));
|
||||
return;
|
||||
}
|
||||
const win = AS_GM ? 'gm' : 'pc';
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
// order of execution (invariants.md): received block -> drop -> add
|
||||
// -> next block. Indexes resolve against the same snapshot, so a
|
||||
// multi-drop never shifts under itself.
|
||||
const snapshot = agendaList(db);
|
||||
const kill = [];
|
||||
for (const d of drops) {
|
||||
if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; }
|
||||
const i = Number(d);
|
||||
if (i >= snapshot.length) {
|
||||
conflicts.push(`agenda has no item at index ${i}${snapshot.length ? '' : ' — it is empty'}`);
|
||||
continue;
|
||||
}
|
||||
kill.push(i);
|
||||
}
|
||||
for (const i of [...new Set(kill)].sort((a, b) => b - a)) {
|
||||
const descr = snapshot[i];
|
||||
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr);
|
||||
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
|
||||
journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr);
|
||||
dropped.push(descr);
|
||||
}
|
||||
// adds land at the top in written order (first item = the top slot):
|
||||
// insert in reverse, id order does the rest. Already queued is a
|
||||
// no-op, not a conflict — reorder is drop-then-add, by design.
|
||||
for (const item of [...new Set(adds)].reverse()) {
|
||||
if (db.prepare('SELECT 1 FROM agenda WHERE descr = ?').get(item)) continue;
|
||||
const res = db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(item, today());
|
||||
journal(db, win, 'agenda-add', `a${Number(res.lastInsertRowid)}`, 'delta');
|
||||
added.push(item);
|
||||
}
|
||||
// overflow: the bottom sinks off the list — by design, not an error
|
||||
const over = agendaList(db);
|
||||
for (let i = over.length - 1; i >= AGENDA_CAP; i--) {
|
||||
const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]);
|
||||
db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id);
|
||||
journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)');
|
||||
evicted.push(over[i]);
|
||||
}
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`agenda-apply failed, rolled back: ${e.message}`);
|
||||
}
|
||||
console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) }));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// whole-list replace (GM override); the journal keeps the prior queue
|
||||
// so turn surgery can compensate mechanically (the saga rule)
|
||||
function setAgenda(db, items, reason, win) {
|
||||
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
||||
const prior = agendaList(db);
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.prepare('DELETE FROM agenda').run();
|
||||
for (const d of [...clean].reverse()) { // first item = the top of the queue
|
||||
db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(d, today());
|
||||
}
|
||||
journal(db, win, 'agenda-set', 'agenda', reason, JSON.stringify(prior));
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`agenda-set failed, rolled back: ${e.message}`);
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
function cmdAgendaSet(items) {
|
||||
const db = openDb();
|
||||
const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc');
|
||||
console.log(JSON.stringify(clean));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
function cmdPick(options) {
|
||||
if (options.length < 2) fail('usage: pick "option one" "option two" [...]');
|
||||
const choice = options[Math.floor(Math.random() * options.length)];
|
||||
@@ -1037,6 +1212,7 @@ function cmdStatus() {
|
||||
records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n,
|
||||
recordsEnabled: recordsEnabled(),
|
||||
paper: paperList(db),
|
||||
agenda: agendaList(db),
|
||||
events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n,
|
||||
rings: {},
|
||||
sinking: {},
|
||||
@@ -1092,6 +1268,9 @@ switch (cmd) {
|
||||
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); break;
|
||||
case 'paper-set': cmdPaperSet(args); break; // no args = clear the paper (a legitimate GM override)
|
||||
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break;
|
||||
case 'agenda': cmdAgenda(); break;
|
||||
case 'agenda-apply': (args.length >= 1) ? cmdAgendaApply(args.join(' ')) : fail('usage: agenda-apply "<turn text>"'); break;
|
||||
case 'agenda-set': cmdAgendaSet(args); break; // no args = clear the agenda
|
||||
case 'pick': cmdPick(args); break;
|
||||
case 'search': cmdSearch(args); break;
|
||||
case 'unarchive': (args.length >= 1) ? cmdUnarchive(args[0], args[1]) : fail('usage: unarchive <rid> [a|b]'); break;
|
||||
@@ -1099,6 +1278,6 @@ switch (cmd) {
|
||||
case 'dump': cmdDump(); break;
|
||||
case 'restore': cmdRestore(FORCE); break;
|
||||
default:
|
||||
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>');
|
||||
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|insert|delete|revive|file|amend|discard|search|unarchive|paper|paper-apply|paper-set|paper-ingest|agenda|agenda-apply|agenda-set|pick|dump|restore|status>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user