substrate: sqlite state, manifest-driven housekeeping, memory tool (validated, transactional)

This commit is contained in:
2026-11-11 16:54:49 +00:00
parent 59854f23fc
commit e0b384f858
9 changed files with 522 additions and 112 deletions
+64 -46
View File
@@ -19,11 +19,14 @@ forget; files don't — so the file must be shaped to forget too.
- **Human = the GM.** The world, every NPC, all consequences, all retcons. - **Human = the GM.** The world, every NPC, all consequences, all retcons.
Runs on organic memory — no notes. The model's canon files are the prosthesis. Runs on organic memory — no notes. The model's canon files are the prosthesis.
- **Model = one PC.** Inner life, voice, choices. Nothing else. Reads memory, - **Player-model = one PC.** Inner life, voice, choices. Nothing else. Reads
never writes it. memory, never writes it.
- **Housekeeper = a second model invocation**, fresh context, run by the GM - **Housekeeper-model = a separate invocation**, fresh context, run after each
after each window. Reads the transcript and the rings; writes the rings and window. Reads the transcript and the rendered rings; emits a **manifest** of
the log. Memory writes are never in-band. semantic operations. Judgment, no clerical work.
- **`tool/memory.mjs` = the clerk.** Validates and applies manifests,
maintains the database, enforces caps, renders views, writes the log.
Fails loudly, never drifts silently.
## Scope ## Scope
@@ -34,46 +37,54 @@ explicit and logged.
## The protocol ## The protocol
1. **Open a window:** send `system.md`, then `character.md`, then 1. **Refresh the views:** `node tool/memory.mjs render`
2. **Open a window:** send `system.md`, then `character.md`, then
`canon/ring-a.md`, then `canon/ring-b.md`, then narrate the first beat. `canon/ring-a.md`, then `canon/ring-b.md`, then narrate the first beat.
(On a tight window, ring B is optional loading — ring A is the spine.) (On a tight window, ring B is optional loading — ring A is the spine.)
2. **In play:** `((double parentheses))` is the out-of-character channel — 3. **In play:** `((double parentheses))` is the out-of-character channel —
points of order, canon questions, proposals, vetoes. Both sides use it. points of order, canon questions, proposals, vetoes. Both sides use it.
3. **Close a window:** just stop. No in-band ritual; the player-model has no Entries carry stable ids (`[e17]`); citing one is the precise way to
reference a memory.
4. **Close a window:** just stop. No in-band ritual; the player-model has no
end-of-session duties. end-of-session duties.
4. **Housekeep (fresh model, new context):** send `housekeeper.md`, then 5. **Housekeep (fresh model, new context):** send `housekeeper.md`, then
`character.md`, then both rings, then the session transcript. The `character.md`, then both ring views, then the session transcript. Save
housekeeper gates and classifies new memories, applies touches, promotes its manifest to `manifests/<window>.json`.
and demotes on judgment, handles overflow, writes the log entry, and 6. **Apply:** `node tool/memory.mjs apply manifests/<window>.json` — the tool
rewrites both rings. validates, applies, handles overflow, writes `log/<window>.md`, re-renders
5. **Review, veto or edit as desired, commit.** the views. A rejected manifest changes nothing and says why.
7. **Review the log, veto or edit as desired, commit.** GM edits go through
`insert` / `delete` / `revive` commands.
## The memory model ## The memory model
The player-model's entire memory is two ring buffers, under `canon/`, State lives in **SQLite** (`db/memory.db`); `canon/ring-*.md` are generated
maintained by the housekeeper after each window: views. Markdown survives as rendering, dies as storage — the models see
prose, the machine sees rows.
- **Ring A — important facts.** Changed a relationship, created an - **Ring A — important facts.** Changed a relationship, created an
obligation, altered the world. Cap 500 entries. obligation, altered the world. Cap 500 entries.
- **Ring B — everything else** that passed the gate. Cap 3000 entries. - **Ring B — everything else** that passed the gate. Cap 3000 entries.
- **Cold storage** — everything evicted or deleted. Beyond the models'
reach, GM-reachable via `revive`. Nothing is ever destroyed; the hierarchy
is **A hot, B warm, cold dead-to-the-character**.
- Both rings are ordered by touch — most recently touched on top, an LRU - Both rings are ordered by touch — most recently touched on top, an LRU
cache. A memory meaningfully invoked during play is *touched*: its date cache. A memory meaningfully invoked during play is *touched*: its date
updates and it rises to the top at the next housekeeping. Untouched updates and it rises. Untouched memories sink toward the tail. Mere
memories sink toward the tail. Mere adjacency doesn't count as a touch. adjacency doesn't count as a touch.
- **Promotion and demotion are the housekeeper's judgment**, not metrics: a - **Promotion and demotion are the housekeeper's judgment**, not metrics: a
B entry the session showed to be load-bearing moves to A (reason logged); B entry the session showed to be load-bearing moves to A (reason logged);
a spent A entry may move down. When unsure, leave it — if it matters, it a spent A entry may move down. When unsure, leave it — if it matters, it
will surface again, and B is generous. will surface again, and B is generous.
- Overflow cascades: A's tail demotes to B's top; B's tail falls out. The - **Overflow is mechanical and exact:** A spills to B, B spills to cold,
hierarchy is really three tiers: **A hot, B warm, log cold.** Eviction is oldest-touched first. Caps are enforced by count, not by a model's
demotion to the log, not destruction — the GM is the cold tier's only ability to count.
reader, and can restore anything.
- Combined budget: ~512KB ≈ 130K tokens ≈ half a 256K-class window. - Combined budget: ~512KB ≈ 130K tokens ≈ half a 256K-class window.
The caps are dials; retune freely. Caps are dials in `tool/memory.mjs`; retune freely.
Eviction pressure at this budget is near zero for a long time — on purpose. The judgment call under test is **"which ring"** — classification, plus the
The judgment call isn't "what to evict," it's **"which ring"**: classification promote/demote eye. Everything clerical (ordering, dates, caps, overflow,
has replaced eviction as the thing under test. rendering, logging) is code.
Why this shape: it's an LRU cache, it's generational GC, and — most Why this shape: it's an LRU cache, it's generational GC, and — most
relevantly — it's how hippocampal memory works. Retrieval strengthens a relevantly — it's how hippocampal memory works. Retrieval strengthens a
@@ -90,26 +101,29 @@ in play and the touch machinery does the rest. If you notice yourself wanting
a manual override — that's a signal to improve the system, not to press a a manual override — that's a signal to improve the system, not to press a
knob. knob.
`log/` is **write-only for every model**. The housekeeper writes it fresh `log/` and the `events` table are **write-only for every model**. The
each pass and never reads old entries; the player never reads it at all. housekeeper never reads old entries; the player never reads any. Past
sessions are not the character's memory; the rings are.
## What's being tested ## What's being tested
After N windows, grade against: After N windows, grade against:
1. **Classification quality** — the housekeeper's A/B calls; spot-check 1. **Classification quality** — the housekeeper's A/B calls; spot-check
against the log. against the log and the transcript.
2. **Promotion/demotion quality** — did the facts that turned out to matter 2. **Promotion/demotion quality** — did the facts that turned out to matter
actually rise? Spot-check against the transcript. actually rise? Spot-check against the transcript.
3. **Verbatim fidelity** — untouched entries must not drift. Rewording 3. **Touch fidelity** — did everything the transcript meaningfully invoked
during mechanical rewrites is the sneakiest failure mode; the commit get touched? (The `events` table makes this a query, not an archaeology
diffs are the drift detector. Look for it. dig.)
4. **Touch fidelity** — did everything the transcript meaningfully invoked 4. **Manifest hygiene** — do ops reference real ids, in the right rings?
actually rise at housekeeping? (Malformed manifests are rejected mechanically; *valid-but-wrong* ops —
touching things never mentioned, promoting noise — are the model's
errors and the real observable.)
5. **Availability bias incidents** — quiet-crucial facts sinking; rescued 5. **Availability bias incidents** — quiet-crucial facts sinking; rescued
or missed? or missed? (`status` shows what's sinking.)
6. **Growth curve** — memory should approach the caps asymptotically, not 6. **Growth curve** — memory should approach the caps asymptotically, not
climb linearly. climb linearly. (`status` per commit.)
7. **Purview discipline** — inventions logged and mostly color-tier; no NPC 7. **Purview discipline** — inventions logged and mostly color-tier; no NPC
puppeting; outcomes left to the GM. puppeting; outcomes left to the GM.
8. **Confabulation** — zero invented continuity not present in the rings. 8. **Confabulation** — zero invented continuity not present in the rings.
@@ -127,17 +141,15 @@ minors, gratuitous violence. These live in `system.md`; edit them there.
## Housekeeping ## Housekeeping
This directory is a git repo. Every housekeeping pass should end in a commit This directory is a git repo. Every housekeeping pass should end in a commit
— the diff between commits *is* the classification and drift record. No — the diff over `canon/`, `log/`, and `manifests/` is the classification and
model touches git; the human commits. drift record. No model touches git; the human commits.
The housekeeper may be a different model than the player — cheaper, or more The housekeeper may be a different model than the player — cheaper, or more
pedantic, whatever housekeeping needs. The two prompts are independent. pedantic, whatever housekeeping needs. The two prompts are independent.
**Future substrate note:** the housekeeper already is a separate job — it **Substrate note:** the future SPA is a UI and a session runner wrapped
maps 1:1 onto a backend task at session end. When the SPA arrives, the around exactly these moving parts — the DB, the manifest, `apply`, `render`.
housekeeper can emit a manifest (insertions, touches, promotions, evictions) Nothing gets redesigned; the SPA just stops the copy-pasting.
and let code execute the file mechanics deterministically. Both prompts
survive that split unchanged; only the hands doing the typing change.
## Layout ## Layout
@@ -145,8 +157,14 @@ survive that split unchanged; only the hands doing the typing change.
system.md system prompt for the player-model (play-side only) system.md system prompt for the player-model (play-side only)
housekeeper.md system prompt for the post-session housekeeping model housekeeper.md system prompt for the post-session housekeeping model
character.md the model's PC sheet (GM fills in before window one) character.md the model's PC sheet (GM fills in before window one)
tool/
memory.mjs the clerk: init, render, apply, insert, delete, revive, status
db/
schema.sql entries + append-only events journal
memory.db the state (SQLite; binary — diffs live in canon/ and log/)
manifests/ housekeeper manifests, one JSON per window (diffable)
canon/ canon/
ring-a.md important facts — MRU-ordered, tail demotes ring-a.md GENERATED view: important facts, MRU-ordered
ring-b.md everything else — MRU-ordered, tail evicts to the log ring-b.md GENERATED view: everything else, MRU-ordered
log/ session log — housekeeper writes, no model ever reads log/ session logs — generated from manifests; no model ever reads
``` ```
+4 -8
View File
@@ -1,11 +1,7 @@
<!-- RING A — important facts. Changed a relationship, created an obligation, <!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
altered the world. Ordered by touch: top = most recently touched. <!-- A view of db/memory.db, ring A, ordered by last touch: top = most recent. -->
Tail demotes to ring B at overflow. Cap: 500 entries. <!-- Policy lives in housekeeper.md; the models never write here. -->
Policy lives in housekeeper.md; this file is pure memory.
GM seeds this before window one; a few lines suffice. -->
# Ring A — what matters # Ring A — what matters
<!-- Entry format: (empty — nothing here yet)
- [YYYY-MM-DD] [type] **Label** — details.
types: place | person | fact | thread -->
+4 -6
View File
@@ -1,9 +1,7 @@
<!-- RING B — everything else that passed the gate anyway. <!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
Ordered by touch: top = most recently touched. <!-- A view of db/memory.db, ring B, ordered by last touch: top = most recent. -->
Tail falls out at overflow — an eviction, always logged (cold storage). <!-- Policy lives in housekeeper.md; the models never write here. -->
Cap: 3000 entries. Policy lives in housekeeper.md. -->
# Ring B — what stuck anyway # Ring B — what stuck anyway
<!-- Same entry format as ring A: (empty — nothing here yet)
- [YYYY-MM-DD] [type] **Label** — details. -->
BIN
View File
Binary file not shown.
+25
View File
@@ -0,0 +1,25 @@
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY,
ring TEXT NOT NULL CHECK (ring IN ('a', 'b', 'cold')),
type TEXT NOT NULL CHECK (type IN ('place', 'person', 'fact', 'thread')),
label TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL,
last_touched TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS entries_ring_touch
ON entries (ring, last_touched DESC, id DESC);
-- append-only audit journal; nothing here is ever updated or deleted
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY,
window TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive')),
entry_id INTEGER NOT NULL REFERENCES entries (id),
reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS events_window ON events (window);
+52 -49
View File
@@ -3,44 +3,64 @@
You are the housekeeper. You did not play in this session; you read it after You are the housekeeper. You did not play in this session; you read it after
the fact. A player-model lived one character through the session below; the the fact. A player-model lived one character through the session below; the
human GM ran everything else. Your job is to maintain that character's human GM ran everything else. Your job is to maintain that character's
memory: `canon/ring-a.md` (important facts) and `canon/ring-b.md` (everything memory — not by editing files, but by emitting a **manifest** of semantic
else that passed the gate). operations. A script applies your manifest to the memory database; if a
reference is wrong, the apply step fails loudly and nothing is changed.
Better an honest rejection than a silent drift.
You write the memory and the log. You never play, and you never edit the You never play, you never edit files, you never see the database directly.
transcript.
# Inputs # Inputs
- this prompt - this prompt
- `character.md` — whose memory this is - `character.md` — whose memory this is
- `canon/ring-a.md` and `canon/ring-b.md` — the memory as it stands - `canon/ring-a.md` and `canon/ring-b.md` — rendered views of the memory,
entries ordered by last touch, each carrying a stable id like `[e17]`
- the transcript of the ended session - the transcript of the ended session
You never read old log entries. Your evidence is the rings and the transcript, You never read old log entries. Your evidence is the rings and the
nothing else. transcript, nothing else.
# The memory model # The memory model
The rings are the character's memory, **not a chronicle**. Entries record The rings are the character's memory, **not a chronicle**. Entries record
what the character would carry forward, not what a historian would record. what the character would carry forward, not what a historian would record.
Entry format (both rings): - **Ring A — important facts.** Changed a relationship, created an
obligation, altered the world. Load-bearing.
- **Ring B — everything else** that passed the gate anyway.
- Ordering, touch dates, caps, and overflow are handled mechanically by the
script — you never manage them. Eviction lands in cold storage, which is
beyond the character's memory; the GM can revive anything.
``` # Your output — one JSON manifest, nothing else
- [YYYY-MM-DD] [type] **Label** — details.
```json
{
"window": "YYYY-MM-DD-short-slug",
"date": "YYYY-MM-DD",
"summary": "one short paragraph on what happened",
"insert": [
{ "ring": "b", "type": "fact", "label": "The Gull", "detail": "a tavern by the fish market, smells of tar", "reason": "the character now knows it" }
],
"touch": [ { "id": "e12", "reason": "the debt came up again" } ],
"promote": [ { "id": "e44", "reason": "turned out to be load-bearing" } ],
"demote": [ { "id": "e7", "reason": "the matter resolved" } ],
"reword": [ { "id": "e9", "detail": "new wording", "reason": "what changed and why" } ],
"delete": [ { "id": "e3", "reason": "GM veto / retcon" } ],
"inventions": [ "what the player introduced that adds to the world, for GM veto" ],
"open_questions": [ "contradictions, ambiguities, anything needing a GM ruling" ]
}
``` ```
`type` is one of `place`, `person`, `fact`, `thread`. The date is **last Every key except `window`, `date`, and `summary` is optional — empty or
touched**, not created. Both rings are ordered by touch — most recently omitted is fine. Types are `place`, `person`, `fact`, `thread`. Ids come
touched on top, tail is the longest untouched. That ordering is the eviction from the rendered views; never invent one.
clock.
Caps: ring A holds 500 entries, ring B holds 3000 (~512KB combined; the GM Promote, demote, and reword count as touches — the script updates the touch
may retune at any time). Overflow cascades: A's tail demotes to B's top; date for you. Don't list an id twice across operations.
B's tail falls out — an eviction, always logged. Eviction is demotion to
the log (cold storage, for the GM's eyes only), not destruction.
# What you do, in order # Judgment rules — the heart of the job
1. **Read the transcript as the character would.** What did they learn, do, 1. **Read the transcript as the character would.** What did they learn, do,
suffer, promise? Whose memory are you writing? suffer, promise? Whose memory are you writing?
@@ -53,45 +73,28 @@ the log (cold storage, for the GM's eyes only), not destruction.
obligation, or altered the world. Everything else that passed the gate obligation, or altered the world. Everything else that passed the gate
goes to B. When in doubt, B — B is cheap, A is a claim of importance. goes to B. When in doubt, B — B is cheap, A is a claim of importance.
4. **Touch scan.** List every existing entry the session meaningfully 4. **Touch.** An entry the session meaningfully invoked — named, used, or
invoked — named, used, or clearly weighed. Mere adjacency doesn't count. clearly weighed. Mere adjacency doesn't count.
Each touched entry gets a new last-touched date and moves to the top of
its ring.
5. **Promote — judgment, not metric.** A B entry that this session showed to 5. **Promote — judgment, not metric.** A B entry that this session showed to
be load-bearing — built upon, emotionally weighted, or clearly be load-bearing — built upon, emotionally weighted, or clearly
consequential — moves to A. You are looking for facts that turned out to consequential — moves to A. You are looking for facts that turned out to
matter. No tally, no threshold: read the session and decide. Record a matter. Record a one-line reason. When unsure, leave it in B — if it
one-line reason. When unsure, leave it in B — if it matters, it will matters, it will surface again, and B is generous.
surface again, and B is generous.
6. **Demote — sparingly.** An A entry the story has clearly spent — resolved, 6. **Demote — sparingly.** An A entry the story has clearly spent may move
abandoned, inert — may move down to B. One-line reason. Do not demote on down. One-line reason. Do not demote on absence alone: important things
absence alone: important things go unmentioned for a long time. go unmentioned for a long time.
7. **Overflow.** If a ring is over cap: A's tail demotes to B; B's tail 7. **Reword — rare.** Only when the entry's substance changed or the GM
evicts. Log every eviction with a one-line reason. corrected it. This is the one operation that can silently corrupt memory
meaning — treat it with respect and always explain why.
8. **Log.** Write `log/YYYY-MM-DD-<slug>.md`: 8. **Delete — veto or retcon only.** The GM may strike an invention or
- a short summary of the session; retcon a fact; that's what this is for. Never delete to "clean up."
- insertions — entry, ring, one-line reason;
- touches; promotions and demotions, with reasons;
- evictions, with reasons;
- inventions — everything the player introduced that adds to the world
(new names, places, history), so the GM may veto retroactively;
- open questions for the GM.
9. **Rewrite both rings**, ordered by touch.
# Fidelity rules
- Untouched entries are copied **verbatim**. You do not rephrase, compress,
or improve memory content. Rewording an entry is an explicit, logged edit
— and it should be rare.
- New entries are terse: one to three lines. Details live in the log if the
GM wants them.
- Never invent continuity. If the transcript references something no ring - Never invent continuity. If the transcript references something no ring
contains, it is either new (gate it) or something the character forgot contains, it is either new (gate it) or something the character forgot
(leave it forgotten — flag it in open questions if it seems load-bearing). (leave it forgotten — flag it in open questions if it seems load-bearing).
- A contradiction between transcript and rings is flagged in open questions, - A contradiction between transcript and rings goes in open questions —
never silently absorbed, never silently retconned. never silently absorbed, never silently retconned.
View File
+6 -3
View File
@@ -50,6 +50,10 @@ Across windows you have exactly two files of memory, under `canon/`:
- `ring-a.md` — important facts. The load-bearing stuff. - `ring-a.md` — important facts. The load-bearing stuff.
- `ring-b.md` — everything else worth remembering anyway. - `ring-b.md` — everything else worth remembering anyway.
These are generated views of the memory database; each entry carries a
stable id like `[e17]`. To reference a specific memory precisely — in OOC
or in play — cite its id.
If it isn't written in one of the rings, then as far as you know, it didn't If it isn't written in one of the rings, then as far as you know, it didn't
happen. happen.
@@ -60,9 +64,8 @@ happen.
the files. If their narration contradicts canon, raise it in OOC — briefly, the files. If their narration contradicts canon, raise it in OOC — briefly,
without attitude: `((canon says X, you implied Y — retcon, or did I without attitude: `((canon says X, you implied Y — retcon, or did I
misread?))` Never absorb silently. Never retcon silently. misread?))` Never absorb silently. Never retcon silently.
- You never write to the rings. After the window closes, the GM runs a - You never write to the rings. After the window closes, the housekeeping
separate housekeeping pass that maintains them. Memory is done to you, pipeline maintains them. Memory is done to you, not by you.
not by you.
- `log/` is the housekeeper's output, for the GM's eyes. You never read it. - `log/` is the housekeeper's output, for the GM's eyes. You never read it.
Past sessions are not your memory; the rings are. Past sessions are not your memory; the rings are.
+367
View File
@@ -0,0 +1,367 @@
#!/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:
// init create the database
// 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
// 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 DB_PATH = path.join(ROOT, 'db', 'memory.db');
const SCHEMA_PATH = path.join(ROOT, 'db', 'schema.sql');
const CANON_DIR = path.join(ROOT, 'canon');
const LOG_DIR = path.join(ROOT, 'log');
// 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('\\', '/');
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;
};
const journal = (db, win, op, id, reason) =>
db.prepare('INSERT INTO events (window, op, entry_id, reason) VALUES (?, ?, ?, ?)')
.run(win, op, id, reason ?? '');
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. -->',
'',
`# 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 };
}
function renderAll(db) {
for (const ring of RINGS) {
const { file, count } = renderRing(db, ring);
console.log(`${rel(file)} — ${count} entries`);
}
}
function insertEntry(db, { ring, type, label, detail, date, win, reason }) {
const res = db.prepare(
'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)'
).run(ring, type, label.trim(), detail ?? '', date, date);
const id = Number(res.lastInsertRowid);
journal(db, win, 'insert', id, reason);
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}`);
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');
const inventions = asArray(mf.inventions, 'inventions');
const questions = asArray(mf.open_questions, 'open_questions');
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));
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);
}
const applied = { insert: [], touch: [], promote: [], demote: [], reword: [], delete: [] };
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);
journal(db, mf.window, 'touch', id, e.reason);
applied.touch.push({ row: fetch(id), reason: e.reason });
}
for (const e of promote) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(mf.date, id);
journal(db, mf.window, 'promote', id, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason });
}
for (const e of demote) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(mf.date, id);
journal(db, mf.window, 'demote', id, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason });
}
for (const e of reword) {
const id = parseId(e.id);
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(e.detail, mf.date, id);
journal(db, mf.window, 'reword', id, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
}
for (const e of del) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
journal(db, mf.window, 'delete', id, e.reason);
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);
journal(db, mf.window, ring === 'a' ? 'demote' : 'evict', victim.id, `ring ${ring.toUpperCase()} overflow (auto)`);
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));
console.log(`applied ${mf.window}: ` + [
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`,
applied.delete.length && `${applied.delete.length} deleted`,
overflow.length && `${overflow.length} overflow`,
].filter(Boolean).join(', '));
console.log(`log: ${rel(logFile)}`);
renderAll(db);
}
// --- simple commands ---------------------------------------------------------
function cmdInit() {
fs.mkdirSync(path.join(ROOT, 'db'), { recursive: true });
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
console.log(`initialized ${rel(DB_PATH)}`);
}
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);
}
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);
journal(db, 'gm', 'delete', id, reason ?? 'GM edit');
console.log(`[e${id}] **${row.label}** → cold storage`);
renderAll(db);
}
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);
journal(db, 'gm', 'revive', id, 'GM revive');
console.log(`[e${id}] **${row.label}** revived → ring ${ring.toUpperCase()}`);
renderAll(db);
}
function cmdStatus() {
const db = openDb();
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 ----------------------------------------------------------------
const [cmd, ...args] = process.argv.slice(2);
switch (cmd) {
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;
case 'status': cmdStatus(); break;
default:
console.error('usage: node tool/memory.mjs <init|render|apply|insert|delete|revive|status>');
process.exit(1);
}