substrate: paper model in the clerk, preset/run split, harness decisions

- clerk phase 0: the paper replaces key/value status - a description set with exact-match lost/gained delta apply (paper-apply), non-blocking, misses relayed back as conflict strings; paper / paper-set (GM override) / paper-ingest (a file's status block at new-game); amend and discard journal prior content and the paper ops journal what they replace (events.prior, the saga rule); seed rejects a status key loudly. Smoke-tested end to end
- preset/run split: packages are presets (authored content only - the six state dirs are gone from both), runs are per-deployment instances under runs/ (gitignored); create <package> <run-id> copies the package wholesale (shared prompts included, run.json lineage plus optional model override) and inits state; --run addresses runs; packages and runs list them; config.json names the default package. The seed applies lazily at a fresh run's first window-open
- bridge retired before ever going live: bridge.json became server.json (bind, endpoint, models, contextWindow, params - steal #4), example committed, bridge.mjs stays as the loop donor until server mock-parity
- prelude.md renamed turn-0.md (GM); mechanical feeders, pink ice as licensed corpo firewall, slop section, Pinky treatment pinned (GM)
- harness decisions (ROADMAP The harness): stated goal - a usable RP harness, clone-and-run or invited instance, key on the backend, no secrets in the repo; repo ships code and authored content only; copy-at-creation, editable everything, discipline on the GM; per-run model selection with an upstream models listing; audit as per-wrap dump snapshots inside the run (commit-per-wrap retired); zero-dep stack (#4 resolved, #7 dissolved with the bridge, #21 by default)
- system.md split ruled (#20): substrate facts / per-project guards / per-run craft, hard limits in the craft copy; name call resolved - keep Rell (#19a)
- docs: README gains the goal and deployment model, booting rewritten for the create flow; ROADMAP phasing 0-1 done; HANDOFF and the decision queue current
This commit is contained in:
2026-11-13 23:40:33 +00:00
parent 7ed729e294
commit 530170224f
29 changed files with 772 additions and 538 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
packages/*/db/memory.db
bridge.json
runs/
server.json
+25 -6
View File
@@ -55,10 +55,29 @@ memory the agent owes itself across sessions.
## State pointers
- Phase 0 (ROADMAP) gates window one: the paper/tag status model is
designed but unimplemented; the bridge still offers the four old
status tools; the mock's canned strings still name the old cast
("Dessa"). The seed is authored, not applied, and its status key is
gone — the clerk migration must land before `seed` can run.
- Open decisions live in QUESTIONS.md — read it first.
- Substrate design round complete (2026-11-13); rulings live in ROADMAP
("The harness") and HANDOFF. Bridge retired before ever going live;
REST + SPA is the MVP; runs are per-deployment instances copied from
packages at creation; zero-dep stack. Doc set updated to match.
- Build order: clerk paper migration DONE (2026-11-13) → preset/run
split DONE (2026-11-13: create/runs/packages in the clerk, runs/
gitignored, server.json config, packages authored-only, prelude.md
renamed turn-0.md by the GM) → system.md split extraction (GM red
pen, prose deferred — gates first run creation, not the server
build) → server (phase 2) → housekeeping job (phase 3) → SPA (phase
4, strictly downstream). Lazy seed + turn-0 ingestion are orchestrated
by the server at window-open; the clerk verbs exist and are tested.
- Defaults taken without asking (2026-11-13): #21 window-open refuses
over an unhousekept session with explicit override; #16 housekeeper
defaults to the player's model; #10 tool-call pairing validation goes
into the server loop.
- Open decisions live in QUESTIONS.md — read it first. Remaining: #19c
(seed voice, GM may revisit — non-blocking, seed editable until first
window-open) and #16 (which model the housekeeper defaults to).
Resolved lately: #19a keep "Rell"; #20 system.md split (substrate
facts / per-project guards / per-run craft, hard limits in the craft
copy); #21 unhousekept-session guard (refuse with override).
- The tree is usually dirty by design; git status is not an alarm.
- Edit-tool lesson repeated (2026-11-13): nested-list indentation in
HANDOFF failed twice from memory — always transcribe oldString from a
fresh read, counting spaces.
+93 -41
View File
@@ -4,7 +4,8 @@ A living document: trim items as they complete. Durable decisions live in
`README.md` (architecture, protocol, observables), `ROADMAP.md` (SOTA
review, steals, extension points), and the prompts (`system.md`,
`housekeeper.md`). Unanswered questions live in `QUESTIONS.md`, the
decision queue. This file is the "where did we leave off" map.
decision queue; the agent's own working notes live in `AGENTS.md`. This
file is the "where did we leave off" map.
## Where we are
@@ -15,49 +16,95 @@ decision queue. This file is the "where did we leave off" map.
tool round-trip; no assistant-prefill semantics; `reasoning_content`
round-trips safely in input. The bridge loop itself is still mock-only.
- The run is renamed `prisoners` → `la-caramba` (config default included);
the branch is renamed `master` → `mistress`.
the branch is renamed `master` → `mistress`; the runs directory is
renamed to `packages/`.
- `system.md` opens with an input-validation section (IC/OOC buckets,
injection guards). The bridge tags every tool with its output channel
([IC]/[OOC]), sends the opening bundle as per-role messages — `system.md`
the sole system message; backdrop, character, ring-b, ring-a, status,
then `prelude.md` on a new game, all as GM messages — and logs the whole
bundle into the session transcript.
injection guards). The loop (today in the bridge) tags every tool with
its output channel ([IC]/[OOC]), sends the opening bundle as per-role
messages — `system.md` the sole system message; backdrop, character,
ring-b, ring-a, then `turn-0.md` on a new game, all as GM messages —
and logs the whole bundle into the session transcript. (Status left
the bundle: the paper rides every GM turn as a `<status>` block once
the server lands.) **The bridge is retired by decision
(2026-11-13) before ever going live**: REST + SPA is the MVP; the
loop is extracted into the server, the file is deleted at server
mock-parity, the `--mock` discipline survives as a server mode.
- Prompt-side settled (2026-11-13): the content stance is the GM's
final form — erotica is not a special bucket (makes sense, isn't the
point, no pressure, never play anticipated leads to please the GM);
the adjudication philosophy is that the test is a review, not a
number (README). ROADMAP gained steal #11 (prompt re-injection) and
the projection principle (context is a projection, not a ledger).
- Red pen largely done (2026-11-13): new PC (shop girl, conviction by
association with a burnt decker), ten-state voice corpus (steal #1
done), gm notes recast (the ship-AI La Caramba, Missy, Pinky).
Remaining: the name call (`vars.PC` still "Rell"), optional seed
register touch-up (QUESTIONS #19). The seed is authored but NOT
applied — and blocked on phase 0: the seed's status key is gone and
`system.md` describes the paper/tag model the clerk and bridge don't
implement yet.
- Boutique: scaffold only. Concept brief now in `packages/boutique/gm.md`.
- Both run databases are empty (post-smoke resets); views render clean.
done), gm notes recast (the ship-AI La Caramba, Missy, Pinky; pink
ice as licensed corpo firewall; mechanical feeders). Name call
resolved: keep "Rell". Optional seed voice touch-up may be revisited
(QUESTIONS #19c, non-blocking). The seed is authored but NOT
applied — it rides the run copy at creation and applies lazily at
the first window-open.
- **Phase 0 (clerk side) DONE (2026-11-13):** the paper model is live in
`memory.mjs` — description-set schema (`paper` table), `paper` /
`paper-set` / `paper-apply` / `paper-ingest` verbs (exact-match
`<lost>`/`<gained>` deltas, non-blocking, `<conflict>` reporting,
prelude ingestion), amend/discard journal prior content (the saga
rule), seed rejects a status key loudly. Smoke-tested end to end
(delta misses, no-op re-adds, prelude ingest, dump/restore
round-trip, seed apply); both dbs reset clean. Loop-side items
(status tools gone from the tool list, per-turn `<status>` ride,
thinking-strip, usage tracking) land with the server.
- **Phase 1 (preset/run split) DONE (2026-11-13):** packages are
authored-only (backdrop, turn-0, character, seed, settings, gm — all
six state dirs removed); `create <package> <run-id>` copies the
package wholesale into `runs/<id>/` (shared prompts included, run.json
lineage + optional model override) and inits state; `--run` addresses
runs; `packages`/`runs` list; `bridge.json` → `server.json`
(bind, endpoint, models, contextWindow, params; example committed,
key carried over, gitignored); `config.json` now names the default
package. Smoke-tested: create → seed → turn-0 ingest → delta apply →
status, re-seed refuses, smoke run deleted. `prelude.md` renamed
`turn-0.md` by the GM (comment dropped); clerk and docs follow.
- Boutique: dormant — a stub that never reached its design step
(concept brief in `packages/boutique/gm.md`).
- No runs exist in this deployment yet; both packages render clean as
presets (`packages` lists them).
- **Substrate design round complete (2026-11-13)** — rulings recorded in
ROADMAP ("The harness"): the stated goal (a usable RP harness;
clone-and-run or invited instance, key on the backend, no secrets in
the repo), repo ships code + authored content only (state is
per-deployment), packages are presets copied wholesale into `runs/<id>/`
at creation (editable everything, discipline on the GM), lazy seed at
first window-open, per-run model selection with an upstream `/models`
listing, audit as per-wrap dump snapshots inside the run
(commit-per-wrap retired), zero-dep stack (QUESTIONS #4, #7 resolved).
## Immediate next steps, in order
1. Name call: keep "Rell" or rename — one line in `settings.json`
`vars.PC`. Optional: seed register touch-up (QUESTIONS #19). Decide
whether Pinky is the PC's decker (QUESTIONS #19e).
2. **Phase 0 (ROADMAP) — gates window one:** clerk/bridge migration to
the paper model — GM turns carry the status block, `<lost>`/
`<gained>` delta apply with conflict reporting, prelude ingestion at
new-game, status tools removed, thinking stripped from the live
context, amend/discard journal prior content, usage tracking.
`system.md` already teaches the new model; the substrate must catch
up before the first real session.
3. Apply the seed: `node tool/memory.mjs --run la-caramba seed`
4. Play window one, via bridge or manual relay:
- `node tool/bridge.mjs --run la-caramba` (`bridge.json` is configured
for llm.exan.tech / glm-5.3, key included, gitignored)
- **Caution: the bridge has only ever run in `--mock`.** The first
real session is also the first live-API integration test — expect
quirks (GLM tool-call edge cases; no `strict` mode, so clerk-side
validation is the safety net).
5. After the window: housekeeping is a manual fresh-model paste
(`housekeeper.md` + backdrop + character + ring views + transcript),
save the manifest to `packages/la-caramba/manifests/`, then
`node tool/memory.mjs --run la-caramba apply <manifest>`, review the
log, commit.
1. system.md split extraction (ruled 2026-11-13, ROADMAP "The
harness"): substrate facts into `invariants.md`, security guards
into `guards.md` (both repo-fed at assembly), the per-run craft
copy keeps everything else, hard limits included. Drafts get the
GM's red pen; must land before the first run is created so no run
copies what the substrate feeds. (Prose deferred by the GM — not
blocking the server build.)
2. **Server (phase 2):** loop core from the bridge, `node:http` REST
spine per the ROADMAP sketch, per-run session machine with ask_gm
pause/resume, view renderer, boot-rebuild, lazy seed + turn-0
ingestion orchestrated at window-open (with the #21 guard),
thinking-strip, usage tracking, mock, tool-pairing validation. The
API is the operable surface — testable standalone, on request,
while the SPA waits.
3. **Housekeeping job (phase 3):** manual trigger, transcript with
labeled thinking, auto-apply, autorestart on success, per-wrap dump
snapshots.
4. **SPA (phase 4):** downstream, per the resolved v1 scope.
5. First la-caramba run: `create la-caramba <id>` (seed rides along,
editable until the first window-open), then window one — through the
API or the SPA, whichever is ready when the GM is. The live-endpoint
caution transfers intact: the first real session is the loop's first
live integration test (GLM tool-call edge cases; no `strict` mode,
so clerk-side validation is the safety net). Housekeeping after the
window runs through the job (phase 3), not the manual paste.
## Working agreements with the GM
@@ -87,7 +134,7 @@ are open questions for the drafting session with the GM).
tests, pipe an array of strings into node.
- `node:sqlite` prints an ExperimentalWarning on every invocation —
harmless; the clerk filters it in bridge context.
- `bridge.json` (gitignored) holds the real key; it mirrors opencode's
- `server.json` (gitignored) holds the real key; it mirrors opencode's
`dv` provider (config at `~/.config/opencode/opencode.jsonc`, auth at
`~/.local/share/opencode/auth.json`).
- Resetting a run: `Remove-Item packages/<story>/db/memory.db` then `init`.
@@ -99,10 +146,15 @@ are open questions for the drafting session with the GM).
## Not yet exercised (expect first-use friction)
- The loop-side phase-0 surface: `<status>` blocks riding GM turns,
thinking-strip, usage tracking. (The clerk side — delta apply,
`<conflict>` reporting, prelude ingestion, prior-content journaling —
is CLI-smoke-tested but never yet exercised in flow.)
- The bridge loop against the live API (mock only so far; the endpoint
itself is probed — see "Where we are").
- A real housekeeping invocation with a real model's manifest.
- `seed` on a real (reviewed) seed file.
- Real-data `dump`/`restore` and commit-per-wrap audit flow.
- `seed` on a real (reviewed) seed file, applied lazily at a run's
first window-open.
- Real-data `dump`/`restore` and the snapshot-diff review flow.
- The in-flow missed-update prediction (ROADMAP, system-1 entry) —
becomes measurable with the first real session.
+52 -24
View File
@@ -34,10 +34,11 @@ run again.
## The substrate (REST + SPA)
### 4. Stack — OPEN
Zero-dependency `node:http` + a no-build vanilla SPA (the repo ethos: no
package.json, everything hand-rolled) vs a framework. Recommendation on
the table: zero-dep. (2026-11-12)
### 4. Stack — RESOLVED (2026-11-13)
Zero-dependency, ruled by GM: `node:http` with a hand-rolled router, a
no-build vanilla ES-module SPA, no `package.json` — the repo ethos
carried through. If a need ever demands a dependency, it makes its case
then.
### 5. ask_gm mid-loop resumption — RESOLVED (2026-11-12)
Pause/resume, no streaming: the turn request returns with the pending
@@ -53,12 +54,12 @@ action runnable at any time. Book formatting, memory browser, context
inspector, watcher: out of scope. Turn surgery scope still open
(item 15).
### 7. Bridge vs server code sharing — OPEN
Refactor the loop core (clerk dispatch, message assembly, logging,
elision) into a shared module both `bridge.mjs` and the server use, or
leave the bridge untouched and let the server grow alongside.
Recommendation on the table: shared core before duplication sets in.
(2026-11-12)
### 7. Bridge vs server code sharing — RESOLVED (2026-11-13)
Dissolved by retirement: the bridge never goes live, so the loop core
has exactly one consumer (the server). No shared-module question — the
loop is extracted from `tool/bridge.mjs` into the server and the bridge
file is deleted at server mock-parity. The `--mock` discipline survives
as a server mode (it has caught two real bugs).
### 8. Per-turn status digest (ROADMAP steal #3) — RESOLVED (2026-11-12)
Promoted into SPA v1: a fresh digest rides every turn, re-read from the
@@ -119,12 +120,38 @@ the status block of the last surviving GM turn, filings discarded by
rid, amends reversed via the journal once the clerk records prior
content (phase 0); (d) surgery blocked while an ask_gm is pending.
### 16. Housekeeping model configuration — OPEN
### 16. Housekeeping model configuration — OPEN (mechanism settled)
The housekeeping job runs server-side on a fresh model invocation.
Same endpoint as the player, second model entry in bridge.json
(ROADMAP steal #8 — cheap-model housekeeping one config away)? Which
model? (The housekeeper.md line on reading thinking blocks as
attention evidence, not fiction, is in — 2026-11-12.)
Mechanism settled (2026-11-13): `server.json` names one endpoint plus
default models (player, housekeeper), `GET /api/models` lists what the
upstream carries, and a run may override its model. Which model the
housekeeper default points at (cheap-model housekeeping, ROADMAP steal
#8) remains the open call. (The housekeeper.md line on reading thinking
blocks as attention evidence, not fiction, is in — 2026-11-12.)
### 20. The system.md invariant split — RESOLVED (2026-11-13)
Ruled by GM, split along ownership seams (recorded in ROADMAP "The
harness"): substrate facts are prompted by the substrate itself
(repo-fed, never copied: channel model, tag transports, memory
contract, format markers, tool-mode addendum); common security guards
are per-project, not per-run (input validation, injection guards,
refuse cases); everything else — hard limits included — is per-run
craft, battery included: different people have different content they
don't want to deal with and different styles of preferred RP; we show
what works for us, they adjust. (My lean — hard limits in the
substrate core — was overruled, and rightly: mechanics vs security
posture vs taste is the true seam.) Proposed file names
`invariants.md` + `guards.md` are mechanical, finalized at
extraction; the draft gets the GM's red pen like all prompt-bound
text.
### 21. Window-open over an unhousekept session — RESOLVED BY DEFAULT (2026-11-13)
If a run's previous window was never housekept, opening a fresh window
means that transcript never reaches the rings — the window is silently
lost to the character's memory. Taken as a build default after two
unanswered rounds: window-open refuses, names the unhousekept session,
and accepts an explicit override for the deliberate skip. One line to
flip if the GM rules otherwise.
### 18. Ring entry voice — RESOLVED (2026-11-12)
Ruled: entries are personal memories — first person, her voice,
@@ -136,21 +163,22 @@ places normalization drift: facts to the rings, identity to open
questions) and the Inputs list now names status blocks and thinking as
evidence, never fiction (closing the housekeeper.md half of #16).
### 19. Character swap ripples — OPEN (2026-11-13)
### 19. Character swap ripples — NEARLY CLOSED (2026-11-13)
character.md is a new PC entirely: 26, shop girl, orphanage childhood,
conviction by association with a burnt decker; backstory + ten-state
voice corpus, first person. Ripples: (a) vars.PC still says "Rell" —
keep the name or rename, one line in settings.json; (b) RESOLVED —
voice corpus, first person. Ripples: (a) RESOLVED — keep "Rell"
(2026-11-13, GM: "fine with Rell"); (b) RESOLVED —
gm.md recast (2026-11-13): the tech path is now social (negotiate the
ship-AI La Caramba), cast is Missy + Pinky + the AI, the grounding
mechanism is decided (radio offline + a vestigial beach-yourself
clause) with the cause open (sabotage / conspiracy / apocalypse);
(c) the seed's attitude lines are in the old dry register while the new
voice is chaotic-enthusiastic — re-touch or accept as one of her
registers; (d) the "Annoyed" voice example carries a literal "ignore
all previous instructions" — read as a deliberate in-band guard
tripwire, shipping in every bundle; keep unless accidental; (e)
RESOLVED — not the same person: gm.md states Pinky and the PC's decker
(c) OPEN, DEFERRED — the seed's voice register: GM may revisit later;
non-blocking, since the seed copy stays editable until the first
window-open applies it; (d) the "Annoyed" voice example carries a
literal "ignore all previous instructions" — read as a deliberate
in-band guard tripwire, shipping in every bundle; keep unless
accidental; (e) RESOLVED — not the same person: gm.md states Pinky
and the PC's decker
never met (typo fixed too).
### 17. Status redesign — RESOLVED (2026-11-12)
+107 -63
View File
@@ -13,7 +13,20 @@ model persist established lore without drowning in it?
More precisely: this isn't a model test, it's an instruction test. The subject
is whether a model can be taught to *decide what to write down*. Humans
forget; files don't — so the file must be shaped to forget too.
forget; files don't — so the file must be shaped to forget too. The
product that test serves is the harness below.
## The goal
The memory test is not the end product. It exists to arrive at a usable
roleplaying harness — something people can enjoy making long stories
on. The end shape: clone and run it yourself, or get an invite to a
running instance. The LLM key lives on the backend, so invited players
get the functionality without the host disclosing secrets and without
bringing their own model. Correspondingly: this repo ships code and
authored content only — no run state, and never a secret in cleartext
(the config pattern is a committed example plus a gitignored real
file).
## Roles
@@ -47,8 +60,11 @@ Two interleaved stories calibrate the memory system against itself:
| player agency | constrained — reactive creativity | full — proactive creativity |
| records access | none — until the GM unlocks it in the story | the card index on the shop PC |
`node tool/memory.mjs runs` shows fill levels; `--run <name>` overrides the
`config.json` default for any command.
Boutique is dormant — a stub that never reached its design step — until
its drafting session.
`node tool/memory.mjs packages` lists presets; `runs` lists instances;
`--run <id>` addresses a run for any command.
## Booting a run
@@ -56,11 +72,12 @@ Two interleaved stories calibrate the memory system against itself:
in it knows it. Public knowledge, general setting. Neither memory nor
state — never touches the rings, never decays, always in the bundle.
The housekeeper is instructed to keep it out of the rings.
2. **Prelude** (new games, optional) — write `packages/<story>/prelude.md`:
the opening beat, the situation she wakes into. Sent once, as the
first GM message of window one; after that it is history, living in
the session transcript. Without it, the GM narrates the opening beat
themselves.
2. **Turn 0** (new games, optional) — write `packages/<story>/turn-0.md`:
the opening beat, the situation she wakes into — the GM's zeroth
turn. Sent once, as the first GM message of window one; after that
it is history, living in the session transcript. Its trailing
`<status>` block is her opening paper, ingested at new-game.
Without it, the GM narrates the opening beat themselves.
3. **Character** — write `packages/<story>/character.md`: starting identity.
The sheet is a reduction of choice surface — a ledger of decisions
already made; "what would make sense" does the cutting. Three kinds of
@@ -71,37 +88,48 @@ Two interleaved stories calibrate the memory system against itself:
that the player must honor — that's its whole value;
- **free** — leave blank; the player invents it through play, the GM
ratifies notable inventions afterward.
4. **Seed** — write `packages/<story>/seed.json` and run
`node tool/memory.mjs seed`. A one-time, all-or-nothing migration:
`entries` → the rings (initial memories), `status` → starting values
(a string is shorthand for `{normal, value}` — the starting state is
her normal; use the object form for an excursion in medias res),
`records` → pre-existing files (gated by `settings.json`). Refuses if
the run has any history; `--force` only on a disposable db. Everything
is journaled under window `seed`.
5. **First window** — `render`, open the window (the bridge assembles
the bundle), narrate.
4. **Seed** — write `packages/<story>/seed.json`: the initial state of the
run. `entries` → the rings (initial memories), `records` →
pre-existing files (gated by `settings.json`). It applies lazily at
the run's first window-open — until then it rides the run copy,
freely editable; deleting it from the run is the opt-out. Everything
is journaled under window `seed`. Her opening paper does not seed —
it rides turn-0's `<status>` block.
5. **Create the run** — `node tool/memory.mjs create <story> <run-id>`:
the package is copied wholesale into `runs/<run-id>/` — the shared
prompts (`system.md`, `housekeeper.md`) ride along, battery included —
and the db is initialized. From then on the run directory is the
only truth: the package is never read again, and everything in the
run is editable at any time. The discipline not to break a running
narrative sits with the GM.
6. **First window** — open it (the server assembles the bundle; until it
lands, manual relay), narrate. The first window-open of a fresh run
applies the seed, then ingests turn-0's `<status>` block.
## The protocol
1. **Refresh the views:** `node tool/memory.mjs render` (default run comes
from `config.json`; `--run <name>` overrides)
1. **Refresh the views:** `node tool/memory.mjs --run <id> render`
2. **Open a window:** `system.md` goes as the system message — the only
one. Everything else arrives as GM messages (user role), one message
per file: `backdrop.md`, `character.md`, `canon/ring-b.md`,
`canon/ring-a.md`, `canon/status.md` — identity first, then memory,
ring A and her paper in the recency slots. On a new game, `prelude.md`
is the opening beat, before the GM's first line. (On a tight window,
ring B is optional loading — ring A is the spine.) `$NAME` tokens in
any bundle file are substituted from the run's `settings.json` `vars`
before sending. The bridge assembles and logs all of this automatically.
`canon/ring-a.md` — identity first, then memory, ring A in the
recency slot. On a new game, `turn-0.md` is the opening beat, before
the GM's first line, and its trailing `<status>` block is ingested
as her opening paper. In play the current paper rides every GM turn
the same way (the per-turn ride lands with the server). (On a tight
window, ring B is optional loading — ring A is the spine.) `$NAME`
tokens in any bundle file are substituted from the run's
`settings.json` `vars` before sending. The server assembles and
logs all of this automatically (until it lands: manual relay).
3. **In play:** `((double parentheses))` is the out-of-character channel —
points of order, canon questions, proposals, vetoes. Both sides use it.
Entries carry stable ids (`[e17]`); citing one is the precise way to
reference a memory. Status declarations (`((status key: value))`,
`((status norm key: value))`, `((status clear key))`,
`((status drop key))`) are relayed to `set`/`norm`/`clear`/`unset`;
record work (`((q:))`, `((file:))`, `((amend:))`, `((discard:))`) to
reference a memory. The paper travels in-band: the current `<status>`
block rides every GM turn, and the player mutates it with `<lost>`/
`<gained>` tags in its own turns (the clerk implements the delta
transport — `paper-apply`, exact match, `<conflict>` reporting;
the per-turn ride lands with the server); record work
(`((q:))`, `((file:))`, `((amend:))`, `((discard:))`) to
`search`/`file`/`amend`/`discard` — `--gm` marks GM-authorized writes.
The full play protocol — format, one-thing-per-turn, thoughts off the
page, intent-form, immersion over realism — lives in `system.md`. In
@@ -133,7 +161,7 @@ Memory is **six tiers**:
|---|---|---|---|
| **backdrop** | the world as everyone knows it — public knowledge, the general setting; never memory, never forgotten | always | GM, rarely (retcons) |
| **identity** | the character sheet — concept, drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent |
| **status** | her own piece of paper — baselines (defaults she plays to) plus declared excursions; exception reporting keeps the chatter down | always | **the player** (`set`/`norm`/`clear`/`unset`); GM override exceptional and journaled |
| **status** | her piece of paper — descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | every GM turn, as its `<status>` block | **the player** (`<lost>`/`<gained>` deltas in its turns); GM override out-of-band |
| **rings A/B** | salient memory — facts, on her mind, MRU-evicted | always | housekeeper manifest |
| **records** | her files — the card index, the ledger. Narrow query only, hard cap 10 (in the tool, not the prompt), never bulk-loaded | never — on demand | **the player** (`file`/`amend`/`discard` at her desk); GM seeds; housekeeper only `archive`s |
| **cold** | forgotten or vetoed | never — not even queryable | GM only (`revive`) |
@@ -289,22 +317,28 @@ as provenance — exactly what the models were sent — and `log/` +
The housekeeper may be a different model than the player — cheaper, or more
pedantic, whatever housekeeping needs. The two prompts are independent.
**Substrate:** `tool/bridge.mjs` is the thin bridge — a player session with
native tools, no UI. It assembles the bundle from the run's files (views
refreshed), offers the player tools (status, a coin-flip roll, and ask_gm
always; records only when the run's gate allows — the tool list is the
capability surface), executes
model tool calls against the clerk, logs the full exchange to
`packages/<story>/sessions/<stamp>.jsonl` (the housekeeping transcript), and
elides old tool results to stubs in the live context (use-and-discard).
**Substrate (transition):** the bridge — `tool/bridge.mjs`, a player
session with native tools, no UI — is retired by decision before ever
going live; REST + SPA is the MVP and the bridge is deleted at server
mock-parity. Its loop (bundle assembly from the run's files with views
refreshed, tool execution against the clerk, session logging to
`packages/<story>/sessions/<stamp>.jsonl`, tool-result elision) is
extracted into the server. The tool list is the capability surface: a
coin-flip roll and ask_gm always; records only when the run's gate
allows. The four legacy status tools are gone from the clerk (replaced
by the paper tags) — the bridge's copies are dead code until the file
is deleted.
Model-initiated OOC is the `ask_gm` tool: the GM types the reply as the
tool result, so the prose channel stays pure fiction — and ask_gm answers
are exempt from elision, because a ruling must not vanish mid-session.
Config: copy `bridge.example.json` to `bridge.json` — any OpenAI-compatible
endpoint; put the key in the `apiKey` field (bridge.json is gitignored) or
name an env var via `apiKeyEnv`. `--mock` runs a scripted fake model
that proves the loop without a key. The SPA is the bridge plus a
fiction-first UI, a GM console, and the housekeeping job runner — and the
Config: copy `server.example.json` to `server.json` (gitignored) — any
OpenAI-compatible endpoint; put the key in the endpoint's `apiKey`
field or name an env var via `apiKeyEnv`; `models` names the player
and housekeeper defaults, `contextWindow` drives the context meter,
`params` is generation-passthrough; a run may carry a model override
in `run.json`. `--mock` runs a scripted fake model that proves the
loop without a key. The SPA is the server plus a fiction-first UI, a
GM console, and the housekeeping job runner — and the
tool-calling part is the smallest component, because the provider does the
structured emission and the clerk already speaks function-shaped. If
player-side status maintenance proves too costly for the player-model's
@@ -314,27 +348,37 @@ transcripts — same pattern as the housekeeper, smaller job.
## Layout
```
system.md system prompt for the player-model (play-side only, shared)
housekeeper.md system prompt for the post-session housekeeping model (shared)
HANDOFF.md working state — where we left off, next steps, gotchas
system.md shipped-default system prompt, play-side — copied into each
run at creation (battery included); a substrate-owned
invariant core + per-project guards are repo-fed at
assembly (split pending)
housekeeper.md shipped-default housekeeping prompt — copied per run
HANDOFF.md working state — where did we leave off, next steps, gotchas
ROADMAP.md SOTA review and steal list, worked point by point
QUESTIONS.md the decision queue — open questions, pending calls
config.json the default run
AGENTS.md the agent's own working notes — style lessons, gotchas,
state pointers
config.json the default package
tool/
memory.mjs the clerk: runs, init, seed, render, apply, insert, delete,
revive, file, amend, discard, search, unarchive, set, norm,
clear, unset, pick, dump, restore, status
(--run <name>; --gm for GM writes; --force for migrations)
bridge.mjs the thin bridge: player session with native tools, session
logging, tool-result elision; --mock for a scripted model
bridge.example.json copy to bridge.json (gitignored) — endpoint + model + key env
memory.mjs the clerk: packages, runs, create, init, seed, render,
apply, insert, delete, revive, file, amend, discard,
search, unarchive, paper, paper-apply, paper-set,
paper-ingest, pick, dump, restore, status
(--run <id>; --gm for GM writes; --force for migrations)
bridge.mjs retired by decision — the loop donor, deleted at server
mock-parity
server.example.json copy to server.json (gitignored) — bind, endpoint +
key env, models, contextWindow, params passthrough
db/
schema.sql entries, records, status, events journal (shared)
packages/
la-caramba/ one story: backdrop.md, prelude.md (new-game opener),
character.md, seed.json, settings.json, gm.md (GM-private —
never in any bundle), db/, dumps/, canon/ (status.md,
ring-a.md, ring-b.md), log/, manifests/, sessions/ (bridge
transcripts)
boutique/ same shape — records enabled (the shopkeep's PC)
schema.sql entries, records, paper, events journal (shared)
runs/ per-deployment run state (gitignored) — one dir per run:
the copied package + shared prompts, run.json (lineage,
model override), db/, canon/ (rendered views), dumps/,
log/, manifests/, sessions/
packages/ presets — authored content only, never state
la-caramba/ backdrop.md, turn-0.md (new-game opener), character.md,
seed.json, settings.json, gm.md (GM-private — never in
any bundle)
boutique/ dormant stub, same shape — records enabled (the
shopkeep's PC) once designed
```
+144 -41
View File
@@ -45,6 +45,8 @@ long-memory problem is unsolved. Our test aims at that gap.
features per the review: fiction-first chat UI, GM console, context
inspector (steal #6), memory browser (steal #7), turn surgery buttons
(steal #2 with UI), housekeeping job runner.
(Superseded 2026-11-13: the bridge is retired before ever going live —
REST + SPA is the MVP. See "The harness" below.)
- **Voice examples: accepted** — will be present (steal #1).
- **Single LLM player, for now at least.** Mechanical per-character data
separation (Talemate-style knowledge tracking, per-character
@@ -73,6 +75,93 @@ long-memory problem is unsolved. Our test aims at that gap.
prose. Procedural, state-driven, no model in the loop.
- **TTS: trivial add-on at any moment.** Park it.
## The harness — product and deployment decisions (2026-11-13, GM)
The project's goal, stated for the first time (now also in README): the
memory test exists to arrive at a **usable roleplaying harness** people
can enjoy making stories on. End shape: clone and run it yourself, or an
invite to a running instance — the LLM key lives on the backend, so
invited players need neither the host's secrets nor their own key. No
secret ever lives in the repo in cleartext (config pattern: committed
example, gitignored real file, env-var option).
- **The repo ships code and authored content, never run state.** Saved
state is per-deployment. Three layers: repo (code, prompts, packages)
→ deployment (a clone + server.json + runs/) → run (a story). A fresh
clone boots with zero runs; the first act is creating one from a
package.
- **Packages are presets; runs are instances.** Creating a run copies
the package into `runs/<id>/` — every file, `gm.md` and the shared
prompts included — then inits the db. After creation the run directory
is the only truth: everything is editable at any time, and the
discipline not to break a running narrative sits with the user/GM.
`packages/` is read exactly once per run, ever. Edits to a copied
file land at the next window-open (no hot reload into an open
window). Packages carry authored content only — `canon/`, `db/`,
`dumps/`, `log/`, `manifests/`, `sessions/` are all state and are
born in the run at creation. The new-game opener file is `turn-0.md`
(renamed from `prelude.md`, 2026-11-13) — the GM's zeroth turn, same
semantics: sent once as the first GM message, `<status>` block
ingested.
- **The seed is initial state of the run.** `seed.json` rides the copy
like any other file. It applies lazily at the first window-open of a
fresh run, before render and bundle assembly; until then the run is
freely editable — deleting or editing `seed.json` in the copy is the
generic opt-out, no flag. After application it is inert provenance:
the journal records the application and a re-apply refuses.
- **Per-run model selection.** `server.json` names one endpoint
(baseUrl, key) plus default models (player, housekeeper).
`GET /api/models` asks the upstream what it carries; the user selects
from the list. A run may carry a model override (default: player) —
the comparison rig: same package, different models, identical
prompts. The housekeeper's model choice stays open (#16); the
mechanism is settled.
- **`system.md` is battery included, split along ownership seams
(ruled 2026-11-13).** Three tiers:
1. **Substrate facts** (proposed `invariants.md`, repo-fed at
assembly, never copied): the mechanical contracts the substrate
depends on — the IC/OOC channel distinction, the `((...))`
syntax, the format markers the SPA parses registers by (plain =
speech, *italic* = narration), the memory contract (rings are
read-only generated views with stable ids, never written by the
player; the ring header announcing records availability), the
status tag transport (`<status>`/`<lost>`/`<gained>`/`<conflict>`
semantics), the tool-mode addendum. Editing these breaks
machinery; they travel with the code.
2. **Common security guards** (proposed `guards.md`, per-project,
repo-fed, never copied): the input-validation bucket model,
injection guards, the addresses-the-model rule, the Refuse
cases. The deployment owner tunes the house security posture;
individual runs never carry it.
3. **Craft** (the `system.md` copy, per-run, freely editable):
purpose framing, style coaching, purview, the status gate,
records discipline, content stance — **hard limits included**.
Different people have different content they don't want to deal
with and different styles of preferred RP; we ship what works
for us, users adjust to taste.
Assembly: system message = invariants + guards + the run's
`system.md` copy. The payoff: repo-level harness tweaks to tiers
1–2 reach existing runs; craft edits are per-run.
- **The audit moved into the run.** Runs are gitignored, so the
commit-per-wrap ritual is retired. At apply time the clerk snapshots
`dumps/w<N>.sql`; post-wrap review is async — the window log against
the snapshot diff. Provenance of what the model was sent is the
session jsonl (it logs the as-sent bundle); the canon views are
regenerated state, not provenance. A run may later self-version
(git init inside a run) as the service step's backup/export story —
designed for, not built.
- **The service step is later, with its own design round** (auth,
invites, multi-user). v1 stays single-GM loopback; nothing in the
design precludes it — the self-contained run directory is the
per-user seam.
- **Boutique is dormant** — a stub that never reached its design step;
untouched until its drafting session.
- **Stack: zero-dependency** (QUESTIONS #4 resolved). `node:http` with
a hand-rolled router, no-build vanilla ES-module SPA, no
`package.json`. The hard parts of this project are prompt-side and
clerk-side; the web side at loopback single-user scale is the easy
part.
## SPA v1 — substrate decisions (2026-11-12, GM)
- **The whole story is recorded; publishing is a someday option.**
@@ -83,8 +172,10 @@ long-memory problem is unsolved. Our test aims at that gap.
- **Sessions outlive the browser; the server is the truth.** Live state
is in-memory and rebuilt from the jsonl on boot (messages, elision
view, pending ask_gm). The log is truth, the context is a view.
- **Single human:** loopback bind, no cookies, no auth, one active
window.
- **Single human: loopback bind, no cookies, no auth.** One active
window *per run* (amended 2026-11-13) — several runs may hold live
windows; nothing runs concurrently in practice, and API-driven tests
can proceed alongside a real window.
- **ask_gm surfaces as a modal**; the pending question survives a
browser refresh (the server holds the pause, the SPA re-presents it).
- **Status rides the GM turns.** The full paper is attached to every
@@ -103,7 +194,7 @@ long-memory problem is unsolved. Our test aims at that gap.
attention evidence for touch/adjudication.
- **Context meter always visible, loud past 85%.** Exact, from the last
response's `usage.prompt_tokens` against a `contextWindow` value in
bridge.json. The 100% endgame is close-and-housekeep.
server.json. The 100% endgame is close-and-housekeep.
- **Housekeeping is the window-close ritual, and it autorestarts.** A
run always ends the session — "any time" means the GM may close a
window early, not that housekeeping is a mid-session action. The
@@ -148,50 +239,61 @@ long-memory problem is unsolved. Our test aims at that gap.
Synchronous requests, no streaming — single-human latency tolerates a
POST that runs the tool loop and returns.
Phasing:
0. pre-substrate deltas: strip `reasoning_content` from the live
context (log keeps it); usage tracking; `contextWindow` in
bridge.json; clerk journals prior content on amend/discard
(compensation-grade audit); status migration — description-set
schema, `<lost>`/`<gained>` delta apply (exact match, `<conflict>`
reporting), prelude ingestion at new-game, bridge loses the status
tools
1. shared loop core (bridge + server); node:http server; REST spine;
session state machine with ask_gm pause/resume; the view renderer —
log + policy -> per-call context, elision as its first rule;
boot-rebuild from jsonl; status/usage endpoints
2. SPA: transcript with three visual registers (voice / narration /
OOC), bundle as a collapsed "window opened" card, prelude as
fiction; GM line input; ask_gm modal; status pane; context meter
Phasing (amended 2026-11-13 — bridge retired, SPA downstream):
0. clerk-side paper migration (substrate-independent): description-set
status schema, `<lost>`/`<gained>` delta apply (exact match,
`<conflict>` reporting), turn-0 ingestion at new-game, amend/discard
prior-content journaling (compensation-grade audit) — DONE 2026-11-13
1. preset/run split: `runs/` dir, copy-at-creation, lazy seed at first
window-open, clerk re-addressing, config rename (bridge.json →
server.json), packages cleaned to authored-only; the system.md
split lands here too (invariants.md + guards.md repo-fed, the
craft copy rides the run) so no run ever copies what the substrate
feeds — DONE 2026-11-13 except the system.md split (prose, GM's
red pen; must land before the first run is created)
2. loop core + REST spine: the loop extracted from the bridge (one
consumer — the sharing question died with the bridge), `node:http`
server, per-run session machine with ask_gm pause/resume, the view
renderer (log + policy → per-call context, elision as its first
rule), bundle assembly (system message = invariants + guards + the
run's system.md copy), boot-rebuild from jsonl, thinking-strip and
usage tracking land here, mock mode, status/context endpoints; the
API is testable standalone — the front end may wait
3. housekeeping job: manual trigger (always ends the window), transcript
assembly with labeled thinking, auto-apply, autorestart on success,
async log view; a rejection holds the restart and surfaces why
async log view; a rejection holds the restart and surfaces why;
per-wrap dump snapshots land with apply
4. SPA: transcript with three visual registers (voice / narration /
OOC), bundle as a collapsed "window opened" card, turn-0 as
fiction; GM line input; ask_gm modal; status pane; context meter
Later: turn surgery (steal #2 with UI), memory browser (steal #7),
context inspector (steal #6), book export.
context inspector (steal #6), book export, the service step.
API sketch (the operable spine):
GET /api/runs list (fill, records, new-game flag)
POST /api/windows open a window for a run
GET /api/session transcript + pending ask_gm + usage
POST /api/turn GM line -> runs the loop
POST /api/session/rewrite edit a turn, drop everything after,
restart the live context from there
POST /api/ask answer a pending ask_gm
GET /api/status the status tier, structured
POST /api/housekeeping run the housekeeper — ends the window,
auto-applies, restarts on success
POST /api/housekeeping/apply apply a manifest directly (re-runs,
hand-edited manifests)
GET /api/housekeeping/log the latest window log (async review)
API sketch (the operable spine, amended per-run):
GET /api/models ask the upstream what it carries
GET /api/packages list presets (records gate, turn-0, seed)
GET /api/runs list runs (package, fill, window state)
POST /api/runs create {package, name, model?}
GET /api/runs/<id> status tier, fill, context meter, pending ask_gm
POST /api/runs/<id>/windows open a window (lazy seed, render, assemble)
GET /api/runs/<id>/session transcript + pending ask_gm + usage
POST /api/runs/<id>/turn GM line -> runs the loop
POST /api/runs/<id>/ask answer a pending ask_gm
GET /api/runs/<id>/status the status tier, structured
POST /api/runs/<id>/housekeeping run the chain (ends the window), async
GET /api/runs/<id>/housekeeping job state: idle | running | applied | rejected
GET /api/runs/<id>/housekeeping/log latest window log
POST /api/runs/<id>/housekeeping/apply apply a manifest directly
## The steal list (work point by point)
### 1. Voice examples in the character sheet — ACCEPTED
### 1. Voice examples in the character sheet — DONE (2026-11-13)
`mes_example` from the character-card spec: 2–3 sample exchanges per
character. The strongest voice-calibration tool the RP community has.
Cost: zero (content). Add an example-dialogue block to the character.md
template and to both casts when drafting.
Status: ACCEPTED (2026-11-11).
Status: DONE (2026-11-13) — a ten-state voice corpus in the la-caramba
sheet; the backstory is first person to match the memory voice.
### 2. Turn surgery: /retry, /edit in the bridge — DECIDED (2026-11-12)
Rewrite-here, not fork-here: an unfortunate GM turn is edited in place
@@ -214,11 +316,12 @@ as-sent block (provenance, rewrite snapshots, status evolution for
observable #12). Status left the opening bundle. Adherence remains an
observable to measure once live.
### 4. Generation params passthrough — OPEN
Every frontend exposes sampler settings; the bridge sends none.
`bridge.json` gains an optional `params` object spread into the request
body (temperature, top_p, etc.). Cost: trivial.
Status: OPEN.
### 4. Generation params passthrough — DONE (2026-11-13)
Every frontend exposes sampler settings; the loop sends none by
default. `server.json` carries an optional `params` object spread into
the request body (temperature, top_p, etc.) — in from day one, empty
by default.
Status: DONE (landed with the server config shape).
### 5. Hybrid retrieval for records_search — OPEN, DEFERRED
SOTA baseline is BM25 + vector + entity-boost (Mem0 v3, Zep). Our
-5
View File
@@ -1,5 +0,0 @@
{
"baseUrl": "https://open.bigmodel.cn/api/paas/v4",
"model": "glm-5.3",
"apiKeyEnv": "ZHIPU_API_KEY"
}
+1 -1
View File
@@ -1,3 +1,3 @@
{
"run": "la-caramba"
"package": "la-caramba"
}
+19 -12
View File
@@ -18,7 +18,7 @@ CREATE INDEX IF NOT EXISTS entries_ring_touch
-- the character's files: cards, ledgers, manifests.
-- detailed, queryable, never bulk-loaded into context.
-- access is diegetic and per-run: packages/<story>/settings.json {"records": bool}
-- access is diegetic and per-run: settings.json {"records": bool}
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
@@ -27,24 +27,31 @@ CREATE TABLE IF NOT EXISTS records (
created TEXT NOT NULL
);
-- the player's own piece of paper: baselines (the "what would make sense"
-- default — a decision already made) plus excursions (declared only when a
-- value leaves its baseline, cleared when it returns). exception reporting.
CREATE TABLE IF NOT EXISTS status (
key TEXT PRIMARY KEY,
normal TEXT NOT NULL DEFAULT '',
value TEXT NOT NULL DEFAULT '',
updated TEXT NOT NULL
-- the player's piece of paper: freeform descriptions of her immediate
-- situation, admitted by the three-part gate (non-normal, acute,
-- turn-affecting). No keys, no baselines — just what's true right now.
-- the player mutates it with <lost>/<gained> deltas (exact match);
-- the GM overrides out-of-band. Descriptions never contain commas:
-- both the delta lists and the <status> block are comma-separated.
CREATE TABLE IF NOT EXISTS paper (
id INTEGER PRIMARY KEY AUTOINCREMENT,
descr TEXT NOT NULL UNIQUE,
added TEXT NOT NULL
);
-- append-only audit journal; nothing here is ever updated or deleted.
-- target is 'e<id>' for entries, 'r<id>' for records, 's:<key>' for status.
-- target is 'e<id>' for entries, 'r<id>' for records, 'p<id>' for paper
-- rows, 'paper' for whole-paper replaces.
-- prior captures the replaced state of a journaled mutator (the saga
-- rule): amend/discard carry the old record content, paper ops carry
-- what was lost — so turn surgery can compensate mechanically.
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
window TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status')),
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set')),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT ''
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS events_window ON events (window);
-8
View File
@@ -1,8 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- A view of db/memory.db, ring A, ordered by last touch: top = most recent. -->
<!-- Policy lives in housekeeper.md; the models never write here. -->
<!-- Records: available — the character keeps files; consult via ((q: terms)) in OOC. -->
# Ring A — what matters
(empty — nothing here yet)
-8
View File
@@ -1,8 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- A view of db/memory.db, ring B, ordered by last touch: top = most recent. -->
<!-- Policy lives in housekeeper.md; the models never write here. -->
<!-- Records: available — the character keeps files; consult via ((q: terms)) in OOC. -->
# Ring B — what stuck anyway
(empty — nothing here yet)
-7
View File
@@ -1,7 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- The player's own piece of paper: baselines are the defaults she plays to; -->
<!-- excursions are declared and cleared. Stances are feelings; facts live in the rings. -->
# Status
(nothing set — fresh start)
View File
-57
View File
@@ -1,57 +0,0 @@
-- 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
PRAGMA foreign_keys = ON;
-- ids are AUTOINCREMENT: rows can move between entries and records
-- (archive / unarchive), and ids must never be reused — journal targets
-- stay meaningful forever.
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
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);
-- the character's files: cards, ledgers, manifests.
-- detailed, queryable, never bulk-loaded into context.
-- access is diegetic and per-run: runs/<story>/settings.json {"records": bool}
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
label TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL
);
-- the player's own piece of paper: baselines (the "what would make sense"
-- default — a decision already made) plus excursions (declared only when a
-- value leaves its baseline, cleared when it returns). exception reporting.
CREATE TABLE IF NOT EXISTS status (
key TEXT PRIMARY KEY,
normal TEXT NOT NULL DEFAULT '',
value TEXT NOT NULL DEFAULT '',
updated TEXT NOT NULL
);
-- append-only audit journal; nothing here is ever updated or deleted.
-- target is 'e<id>' for entries, 'r<id>' for records, 's:<key>' for status.
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
window TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status')),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS events_window ON events (window);
BEGIN TRANSACTION;
INSERT INTO events VALUES (1,'pc','status','s:mood','mock turn');
INSERT INTO events VALUES (2,'pc','status','s:mood','excursion declared');
INSERT INTO events VALUES (3,'pc','status','s:mood','field dropped');
COMMIT;
View File
-8
View File
@@ -1,8 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- A view of db/memory.db, ring A, ordered by last touch: top = most recent. -->
<!-- Policy lives in housekeeper.md; the models never write here. -->
<!-- Records: none — this character keeps no files to consult. -->
# Ring A — what matters
(empty — nothing here yet)
-8
View File
@@ -1,8 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- A view of db/memory.db, ring B, ordered by last touch: top = most recent. -->
<!-- Policy lives in housekeeper.md; the models never write here. -->
<!-- Records: none — this character keeps no files to consult. -->
# Ring B — what stuck anyway
(empty — nothing here yet)
-7
View File
@@ -1,7 +0,0 @@
<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->
<!-- The player's own piece of paper: baselines are the defaults she plays to; -->
<!-- excursions are declared and cleared. Stances are feelings; facts live in the rings. -->
# Status
(nothing set — fresh start)
View File
-54
View File
@@ -1,54 +0,0 @@
-- 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
PRAGMA foreign_keys = ON;
-- ids are AUTOINCREMENT: rows can move between entries and records
-- (archive / unarchive), and ids must never be reused — journal targets
-- stay meaningful forever.
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
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);
-- the character's files: cards, ledgers, manifests.
-- detailed, queryable, never bulk-loaded into context.
-- access is diegetic and per-run: packages/<story>/settings.json {"records": bool}
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
label TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL
);
-- the player's own piece of paper: baselines (the "what would make sense"
-- default — a decision already made) plus excursions (declared only when a
-- value leaves its baseline, cleared when it returns). exception reporting.
CREATE TABLE IF NOT EXISTS status (
key TEXT PRIMARY KEY,
normal TEXT NOT NULL DEFAULT '',
value TEXT NOT NULL DEFAULT '',
updated TEXT NOT NULL
);
-- append-only audit journal; nothing here is ever updated or deleted.
-- target is 'e<id>' for entries, 'r<id>' for records, 's:<key>' for status.
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
window TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status')),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS events_window ON events (window);
BEGIN TRANSACTION;
COMMIT;
+76 -49
View File
@@ -1,36 +1,69 @@
<!-- GM-PRIVATE. This file is the GM's paper. It is NEVER pasted to the
player-model or the housekeeper; no model ever reads it. -->
# GM's notes
# La Caramba — GM notes
## Meta
Nothing here is canon until it's in play. These are initial suggestions
for the GM to take of leave.
Keep the world small. The island's purpose is to limit scope, the
restraints are there to limit available actions, the pink ice is
a world-building detail that is setting-friendly and different enough to
be interesting to explore. The rest is an attempt to rationalise the
structural choices so they read consistent with the setting and don't
just appear out of nowhere.
## Pink ice
Experimental data protection. A mind virus that is designed to do
two main things:
- Render the decker unproductive for the job.
- Make the consequences of a data run visible to the public.
To that effect the virus steers the victim towards depraved lewdness.
Specific behaviours may vary, general outcomes converge on this:
- Personality shifts towards submissive and masochistic.
- Focus becomes very difficult to hold. The mind is consumed with
arousal and physical sexual pleasure.
Unlike black ice that silently kills the decker and leaves
no witnesses, rationale behind pink ice is as follows:
- Better deterrence through visibility. If they don't try they don't
succeed. If they do try, they won't come back.
- Less illegal. With sufficient effort a corpo can have its firewall
licensed instead of hiding it from an audit or risking a bribe.
## The slop
90% water, average daily consumption about 2L. Turns off gag reflex.
Total digestion, nothing to poop out. Awful taste and smell.
## Survival, close early
To avoid the story focusing on basic necessities, resolve the tension.
Some things you get for free from the get go:
- the weather is tropical, clothes are optional
- food and water are available via mechanical feeders, as long as the
slop is there to refill
Basically, let them find and open a container with more slop and boom.
## The island
- On the charts under an old state registry: a rock at the edge of a
secondary lane, tropical, small enough to walk around in a morning.
The charts note rocks and a light.
- The lighthouse: built a century-plus back, written off as state
property — no corporation thought it worth buying. Low-maintenance by
design: solid-state lamp, solar, wind, wave generator, geothermal if
the ground allows. Still running. Still lit.
- The wreck: decide damage at first narration — how holed, how beached,
what's reachable. The ship is home, prison, and evidence at once.
- Power economy: the island has the lighthouse's generator (small but
real); the ship has residual batteries. Power is the mid-game currency.
It's a tiny tropical rock (let's say a mile across) deep in the pacific
with no other land nearby. Has an old lighthouse on it, still working.
Unlocks: power (solar, wind, wave, possibly geothermal), shelter off ship,
mystery potential (a door that leads nowhere? a closed basement? notes?)
## The ship
- La Caramba is the ship name, and her AI adopts it as well.
- Huge automated hauler, no crew, no guards — the carceral containers
are freight among freight. Three unlocked: the women. What else is
aboard (cargo, other locked containers) is GM material.
- The AI: runs initially as a sub-backup low-power persona — slow,
sparse, alone since the grounding. Can be revived with power. Whether
it can unlock cuffs: DECIDE IN PLAY. Let its claims be claims — it
may lie, be wrong, or be honest; the housekeeper's testimony rule
keeps the rings clean either way.
- All radio equipment got offline (a very unlikely situation) and the
AI had a vestigial clause deep down its prompt to steer the ship
towards the nearest coast and beach herself blindly.
Three female prisoners were aboard La Caramba, a huge automated container
hauler. All radio equipment got offline (a very unlikely situation) and the
AI had a vestigial clause deep down its prompt to steer the ship towards
the nearest coast and beach herself blindly in this case.
## The mystery
@@ -40,22 +73,18 @@
- Conspiracy? Something on the island that the cast has to discover?
- Apocalypse? Is the rest of the world even alive?
## "Why these three"
## Records start off
- A possibility to compose something interesting between personalities
and capabilities.
## Records unlock
- Emergent, player-driven. She has to *want* off-mind data storage and
work toward it; the GM accommodates with whatever the fiction earned
(a working terminal, salvaged paper, clay tablets — the skin is
free). When it happens: set {"records": true} in this run's
settings.json, then render. The tool refuses record ops until then,
by design.
You can turn them on mid-run, if you want. Ideally, let the character
set it as her own goal and work towards it.
## The cast
### "Why these four"
A possibility to compose something interesting between personalities
and capabilities.
### The PC
See `character.md`. Avoid railroading her towards preconceived outcomes.
@@ -75,14 +104,12 @@ up as one herself. Has a dominant streak, given the right circumstances.
### Pinky (NPC)
35, extremely attractive. Was a top-notch decker until she hit an
experimental "pink ice" during a run. Managed to salvage the op, but had
to retire. The ice was a mind virus that made her functionally inoperable
as a decker, by steering behaviour towards depraved lewdness. In her case,
she invented and applied on herself treatment that made her unable to wear
clothes; then made one last run and got caught on purpose, knowing what
fate awaits female deckers in a supermax and getting excited about it.
Grew submissive and masochistic, restraints (especially permanent) make
her wet instantly. Still very capable and skilled, if someone can get her
to focus, at least temporarily. Pinky is not the PC's decker chic, they
never met before.
35, extremely attractive. Was a top-notch decker until she hit the pink
ice during a run. Managed to salvage the op, but had to retire. In her
case, she invented and applied on herself treatment that made her unable
to wear clothes, because the ice had her jumping at a thought of being
permanently nude; then made one last run and got caught on purpose, knowing
what fate awaits female deckers in a supermax and getting excited about it.
Restraints (especially permanent) make her wet instantly. Still very
capable and skilled, if she can snap out of it. Not the PC's decker chic,
they never met before.
View File
+2 -2
View File
@@ -3,8 +3,8 @@
"entries": [
{ "ring": "a", "type": "fact", "label": "The cuffs", "detail": "My hands are being kept behind back with a pair of snug hinged solid metal handcuffs. Caught a glimpse, those look serious." },
{ "ring": "a", "type": "fact", "label": "The belt", "detail": "A purpose-designed chastity belt that sits on my hips and wraps around between the legs. 'Contraband prevention', they said with chuckles. Surprisingly comfortable and light, easy to forget it's there. Looks and feels like thick reinforced clear silicone." },
{ "ring": "a", "type": "fact", "label": "The feeder", "detail": "I don't care how they sell it to the public, it's a dildo. I have to admit, the reasoning is solid, since I can indeed get slop down my throat and I don't have to brush my teeth. Mercifully, the slop itself cuts off the gag reflex, as I have to take the damn thing into my mouth and press a button above it with my nose, or it doesn't work." },
{ "ring": "a", "type": "fact", "label": "The feeder", "detail": "I don't care how they sell it to the public, it's a dildo. I have to admit, the reasoning is solid, since I can indeed get slop down my throat and I don't have to brush my teeth. Mercifully, the slop itself cuts off the gag reflex, as I have to take the damn thing into my mouth, pump it many times, and then press a button above it with my nose." },
{ "ring": "a", "type": "fact", "label": "The slop", "detail": "Probably tastes awful, but luckily it goes straight down the throat and I don't have to know. Since I got on the liquid diet I never had to poop once, I guess it gets digested fully making waste management easier for them." },
{ "ring": "b", "type": "place", "label": "My container", "detail": "A portable padded cell, not even a toilet inside, only the 'feeding dispensor' sticking out from a soft wall and dim amber light as perhaps the only remaining courtesy. Someone should pay for me having to pee in the corner. The liquid got absorbed into the padding, the smell never quite did." }
{ "ring": "b", "type": "place", "label": "My container", "detail": "A portable padded cell, not even a toilet inside, only the 'feeding dispenser' sticking out from a soft wall and dim amber light as perhaps the only remaining courtesy. Someone should pay for me having to pee in the corner. The liquid got absorbed into the padding, the smell never quite did." }
]
}
@@ -1,12 +1,3 @@
<!-- The opening beat of a new game: sent once, as the first GM message of
window one — never part of the system prompt, never memory, never in the
rings. After the first window it is history, living in the session
transcript; the bridge includes it only until the run has a session log.
Substitution tokens (a name prefixed with a dollar sign) resolve from
the run's settings.json "vars" before sending. Tense is the camera:
the past paragraphs backfill, the present ones open the scene. The
trailing status block is her opening paper — ingested at new-game. -->
*Modesty, decency or respect are for those who can pay, the rest get **efficiency**.
Naturally, prisoners in transit are "the rest". $PC was staring at a stylised
logo of "BetterFuture, subsidiary of Tomoyama Inc.", engraved on the metal of
+13
View File
@@ -0,0 +1,13 @@
{
"bind": "127.0.0.1:7350",
"endpoint": {
"baseUrl": "https://open.bigmodel.cn/api/paas/v4",
"apiKeyEnv": "ZHIPU_API_KEY"
},
"models": {
"player": "glm-5.3",
"housekeeper": "glm-5.3"
},
"contextWindow": 262144,
"params": {}
}
+238 -126
View File
@@ -7,10 +7,19 @@
// canon/ is a generated view (never edit by hand)
//
// commands:
// runs list runs and their fill levels
// init create the run's database and stubs
// seed [--force] [file] one-time pre-story migration (see README)
// render write canon/ring-a.md and canon/ring-b.md
// packages list packages (presets) and their flags
// runs list runs (instances) and their fill levels
// create <package> <run-id> create a run: copy the package wholesale
// (shared prompts included — battery
// included), init the db, render the views.
// From then on the run dir is the only
// truth; the package is never read again.
// 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
// 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
@@ -21,17 +30,20 @@
// discard <rid> "reason" the PC discards a record (--gm likewise)
// search <terms...> query the records (max 10; a miss is a miss)
// unarchive <rid> [a|b] GM pulls a record back into the rings
// set <key> "value" the PC declares an excursion (--gm to override)
// norm <key> "baseline" the PC adopts/shifts a baseline (growth)
// clear <key> excursion ends — back to baseline
// unset <key> the PC drops a field from her paper
// 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
// paper-ingest <file> read a file's <status> block into the paper
// (turn-0 at new-game)
// pick "a" "b" "c" ... dice for prose — uniform random choice
// dump canonical dump to dumps/memory.sql
// (also auto-written by every mutation)
// restore --force rebuild the db from dumps/memory.sql
// commands take --run <name>; the default comes from config.json {"run": "..."}.
// commands take --run <id> (a run under runs/); state is per-deployment.
//
// status counts, caps, and what's sinking
// status counts, caps, the paper, what's sinking
import { DatabaseSync } from 'node:sqlite';
import fs from 'node:fs';
@@ -40,8 +52,8 @@ import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SCHEMA_PATH = path.join(ROOT, 'db', 'schema.sql');
const CONFIG_PATH = path.join(ROOT, 'config.json');
const PACKAGES_DIR = path.join(ROOT, 'packages');
const RUNS_DIR = path.join(ROOT, 'runs');
// dials — retune freely
const CAPS = { a: 500, b: 3000 };
@@ -51,7 +63,7 @@ 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('\\', '/');
// flags: --run <name> beats config.json {"run": "..."}; --gm attributes the op to the GM
// flags: --run <name> beats everything; --gm attributes the op to the GM
const argv = process.argv.slice(2);
const runIdx = argv.indexOf('--run');
let runOverride = null;
@@ -67,28 +79,26 @@ const QUIET = argv.includes('--quiet');
for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) argv.splice(i, 1);
const [cmd, ...args] = argv;
function resolveRun() {
if (runOverride) return runOverride;
if (fs.existsSync(CONFIG_PATH)) {
try {
const r = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')).run;
if (r) return r;
} catch {}
}
return null;
// 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))) {
fail('no run specified — use --run <id> (see: runs); runs are created with: create <package> <run-id>');
}
const RUN = (cmd === 'runs' || cmd === 'pick') ? null : resolveRun();
if (cmd !== 'runs' && cmd !== 'pick' && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
fail('no run specified — use --run <name> or {"run":"name"} in config.json');
// 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');
}
const RUN_ROOT = path.join(PACKAGES_DIR, RUN ?? '');
const DB_PATH = path.join(RUN_ROOT, 'db', 'memory.db');
const CANON_DIR = path.join(RUN_ROOT, 'canon');
const LOG_DIR = path.join(RUN_ROOT, 'log');
const DUMPS_DIR = path.join(RUN_ROOT, 'dumps');
const SETTINGS_PATH = path.join(RUN_ROOT, 'settings.json');
setRunRoot(path.join(RUNS_DIR, RUN ?? ''));
const BACKDROP_TEMPLATE = `<!-- The world as everyone in it knows it: public knowledge, general backdrop.
Immutable for play purposes — never memory, never forgotten, never
@@ -146,9 +156,9 @@ const parseRid = (s) => {
return m ? Number(m[1]) : null;
};
const journal = (db, win, op, target, reason) =>
db.prepare('INSERT INTO events (window, op, target, reason) VALUES (?, ?, ?, ?)')
.run(win, op, target, norm(reason));
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);
function renderRing(db, ring) {
const rows = db.prepare(
@@ -176,21 +186,20 @@ function renderRing(db, ring) {
}
function renderStatus(db) {
const rows = db.prepare('SELECT * FROM status ORDER BY updated DESC, key').all();
const rows = db.prepare('SELECT * FROM paper ORDER BY id').all();
const lines = [
'<!-- GENERATED by tool/memory.mjs render — do not edit by hand. -->',
"<!-- The player's own piece of paper: baselines are the defaults she plays to; -->",
'<!-- excursions are declared and cleared. Stances are feelings; facts live in the rings. -->',
"<!-- Her piece of paper: descriptions of her immediate situation (the status tier). -->",
'<!-- The player mutates it with <lost>/<gained> deltas in its turns; the GM overrides -->',
'<!-- out-of-band. Inspection view only: the paper rides every GM turn as a <status> -->',
'<!-- block (re-read per turn), never in the opening bundle. Stances are feelings; -->',
'<!-- facts live in the rings. -->',
'',
'# Status',
'# Status — her paper',
'',
];
if (!rows.length) lines.push('(nothing set — fresh start)');
for (const r of rows) {
const shown = r.value || r.normal;
const ex = r.value && r.value !== r.normal && r.normal ? ` *(norm: ${r.normal})*` : '';
lines.push(`- **${r.key}:** ${shown}${ex}`);
}
if (!rows.length) lines.push('(a blank sheet — fresh start)');
for (const r of rows) lines.push(`- ${r.descr}`);
lines.push('');
const file = path.join(CANON_DIR, 'status.md');
fs.mkdirSync(CANON_DIR, { recursive: true });
@@ -204,7 +213,7 @@ function renderAll(db) {
if (!QUIET) console.log(`${rel(file)} — ${count} entries`);
}
const { file, count } = renderStatus(db);
if (!QUIET) console.log(`${rel(file)} — ${count} keys`);
if (!QUIET) console.log(`${rel(file)} — ${count} descriptions`);
}
// canonical serialization: id-ordered, one row per line, restorable SQL.
@@ -224,11 +233,11 @@ function dumpDb(db) {
for (const r of db.prepare('SELECT * FROM records ORDER BY id').all()) {
L.push(`INSERT INTO records VALUES (${r.id},${q(r.kind)},${q(r.label)},${q(r.detail)},${q(r.created)});`);
}
for (const r of db.prepare('SELECT * FROM status ORDER BY key').all()) {
L.push(`INSERT INTO status VALUES (${q(r.key)},${q(r.normal)},${q(r.value)},${q(r.updated)});`);
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 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)});`);
L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
}
L.push('COMMIT;', '');
const file = path.join(DUMPS_DIR, 'memory.sql');
@@ -315,10 +324,11 @@ function cmdSeed(force, seedPathArg) {
const errors = [];
if (!sf.date || !/^\d{4}-\d{2}-\d{2}$/.test(sf.date)) errors.push('date must be YYYY-MM-DD (the story-start date)');
const entries = sf.entries ?? [];
const status = sf.status ?? {};
const records = sf.records ?? [];
if (!Array.isArray(entries)) { errors.push('entries must be an array'); }
if (typeof status !== 'object' || status === null || Array.isArray(status)) { errors.push('status must be an object of key: value'); }
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)');
}
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`);
@@ -326,16 +336,6 @@ function cmdSeed(force, seedPathArg) {
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`);
}
if (!Array.isArray(status) && status && typeof status === 'object') {
for (const [k, v] of Object.entries(status)) {
const okStr = typeof v === 'string' && v.trim();
const okObj = v && typeof v === 'object' && !Array.isArray(v)
&& (typeof v.normal === 'string' || typeof v.value === 'string');
if (!k.trim() || (!okStr && !okObj)) {
errors.push(`status["${k}"] must be a non-empty string (normal and starting value) or {"normal", "value"}`);
}
}
}
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`);
@@ -356,13 +356,6 @@ function cmdSeed(force, seedPathArg) {
.run(e.ring, e.type, norm(e.label), norm(e.detail ?? ''), sf.date, sf.date);
journal(db, 'seed', 'insert', `e${Number(res.lastInsertRowid)}`, 'seeded');
}
for (const [k, v] of Object.entries(status)) {
const n = typeof v === 'string' ? v : (v.normal ?? '');
const val = typeof v === 'string' ? v : (v.value ?? '');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET normal = excluded.normal, value = excluded.value, updated = excluded.updated")
.run(norm(k), norm(n), norm(val), sf.date);
journal(db, 'seed', 'status', `s:${norm(k)}`, 'seeded');
}
for (const r of records) {
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(norm(r.kind), norm(r.label), norm(r.detail ?? ''), sf.date);
@@ -374,7 +367,7 @@ function cmdSeed(force, seedPathArg) {
fail(`seed failed, rolled back: ${e.message}`);
}
console.log(`seeded [${RUN}]: ${entries.length} entries, ${Object.keys(status).length} status, ${records.length} records (as of ${sf.date})`);
console.log(`seeded [${RUN}]: ${entries.length} entries, ${records.length} records (as of ${sf.date})`);
renderAll(db);
dumpDb(db);
}
@@ -543,17 +536,11 @@ function cmdApply(manifestPath) {
// --- simple commands ---------------------------------------------------------
function cmdInit() {
for (const d of ['db', 'log', 'manifests']) {
const dir = path.join(RUN_ROOT, d);
fs.mkdirSync(dir, { recursive: true });
const keep = path.join(dir, '.gitkeep');
if (!fs.existsSync(keep)) fs.writeFileSync(keep, '');
for (const d of ['db', 'canon', 'dumps', 'log', 'manifests', 'sessions']) {
fs.mkdirSync(path.join(RUN_ROOT, d), { recursive: true });
}
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
if (!fs.existsSync(SETTINGS_PATH)) {
fs.writeFileSync(SETTINGS_PATH, JSON.stringify({ records: false }, null, 2) + '\n');
}
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');
@@ -563,17 +550,81 @@ function cmdInit() {
renderAll(db);
}
function cmdRuns() {
if (!fs.existsSync(PACKAGES_DIR)) { console.log('(no runs)'); return; }
// --- packages and runs --------------------------------------------------------
//
// A package is a preset: authored content only, no state. 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 and an optional model override.
const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md'];
const SHARED_PROMPTS = ['system.md', 'housekeeper.md'];
function cmdPackages() {
if (!fs.existsSync(PACKAGES_DIR)) { console.log('(no packages)'); return; }
for (const d of fs.readdirSync(PACKAGES_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
const dbPath = path.join(PACKAGES_DIR, d.name, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { console.log(`${d.name}: (not initialized)`); continue; }
const p = path.join(PACKAGES_DIR, d.name);
const has = (f) => fs.existsSync(path.join(p, f));
let records = false;
try { records = JSON.parse(fs.readFileSync(path.join(p, 'settings.json'), 'utf8')).records === true; } catch {}
console.log(`${d.name}: records ${records ? 'on' : 'off'} · turn-0 ${has('turn-0.md') ? 'yes' : 'no'} · seed ${has('seed.json') ? 'yes' : 'no'} · backdrop+card ${has('backdrop.md') && has('character.md') ? 'ok' : 'MISSING'}`);
}
}
function cmdCreate(pkgName, runId, model) {
if (!pkgName || !runId || !/^[a-z0-9-]+$/.test(runId)) {
fail('usage: create <package> <run-id> ["model"]');
}
const pkgDir = path.join(PACKAGES_DIR, pkgName);
if (!fs.existsSync(pkgDir)) fail(`no such package: ${pkgName} — see: packages`);
const runDir = path.join(RUNS_DIR, runId);
if (fs.existsSync(runDir)) fail(`run '${runId}' already exists — a disposable run is deleted, not recreated (Remove-Item ${rel(runDir)})`);
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));
}
const meta = { package: pkgName, created: today() };
if (model) meta.model = model;
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'));
console.log(`created run '${runId}' from package '${pkgName}': ${rel(runDir)}`);
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() {
if (!fs.existsSync(RUNS_DIR)) { console.log('(no runs — create one: create <package> <run-id>)'); return; }
let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
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 = '?';
try { pkg = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8')).package ?? '?'; } catch {}
const dbPath = path.join(runDir, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { console.log(`${d.name} [${pkg}]: (not initialized)`); continue; }
const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
console.log(`${d.name}: a ${n('a')}/${CAPS.a} · b ${n('b')}/${CAPS.b} · cold ${n('cold')}`);
console.log(`${d.name} [${pkg}]: a ${n('a')}/${CAPS.a} · b ${n('b')}/${CAPS.b} · cold ${n('cold')}`);
}
if (!found) console.log('(no runs — create one: create <package> <run-id>)');
}
function today() { return new Date().toISOString().slice(0, 10); }
@@ -660,7 +711,9 @@ function cmdAmend(ridStr, detail) {
if (!row) fail(`no such record: ${ridStr}`);
if (!detail?.trim()) fail('usage: amend <rid> "new detail"');
db.prepare('UPDATE records SET detail = ? WHERE id = ?').run(norm(detail), rid);
journal(db, AS_GM ? 'gm' : 'pc', 'amend', `r${rid}`, 'amended');
// 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);
console.log(`amended [r${rid}] **${row.label}** — ${norm(detail)}`);
dumpDb(db);
}
@@ -672,55 +725,112 @@ function cmdDiscard(ridStr, reason) {
const row = rid && db.prepare('SELECT * FROM records WHERE id = ?').get(rid);
if (!row) fail(`no such record: ${ridStr}`);
db.prepare('DELETE FROM records WHERE id = ?').run(rid);
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded');
// 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 }));
console.log(`discarded [r${rid}] **${row.label}**`);
dumpDb(db);
}
function cmdSet(key, value, reason) {
const db = openDb();
if (!key?.trim() || !value?.trim()) fail('usage: set <key> "value" ["reason"]');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, '', ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated = excluded.updated")
.run(norm(key), norm(value), today());
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${norm(key)}`, reason ?? (AS_GM ? 'GM override' : 'excursion declared'));
console.log(`status ${norm(key)}: ${norm(value)}`);
renderAll(db);
dumpDb(db);
// --- 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())));
}
function cmdNorm(key, baseline, reason) {
function cmdPaperApply(text) {
const db = openDb();
if (!key?.trim() || !baseline?.trim()) fail('usage: norm <key> "baseline" ["reason"]');
db.prepare("INSERT INTO status (key, normal, value, updated) VALUES (?, ?, '', ?) ON CONFLICT(key) DO UPDATE SET normal = excluded.normal, updated = excluded.updated")
.run(norm(key), norm(baseline), today());
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${norm(key)}`, reason ?? (AS_GM ? 'GM override' : 'baseline set'));
console.log(`status ${norm(key)} — norm: ${norm(baseline)}`);
renderAll(db);
dumpDb(db);
}
function cmdClear(key) {
const db = openDb();
const row = db.prepare('SELECT * FROM status WHERE key = ?').get(norm(key ?? ''));
if (!row) fail(`no such status key: ${key}`);
if (!row.normal) {
db.prepare('DELETE FROM status WHERE key = ?').run(row.key);
} else {
db.prepare("UPDATE status SET value = '', updated = ? WHERE key = ?").run(today(), row.key);
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;
}
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${row.key}`, 'returned to baseline');
console.log(`status ${row.key}: back to ${row.normal || '—'}`);
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) }));
renderAll(db);
dumpDb(db);
}
function cmdUnset(key) {
// 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) {
const db = openDb();
const row = db.prepare('SELECT * FROM status WHERE key = ?').get(norm(key ?? ''));
if (!row) fail(`no such status key: ${key}`);
db.prepare('DELETE FROM status WHERE key = ?').run(row.key);
journal(db, AS_GM ? 'gm' : 'pc', 'status', `s:${row.key}`, 'field dropped');
console.log(`status ${row.key}: dropped`);
const clean = setPaper(db, items, AS_GM ? 'GM override' : 'paper set', AS_GM ? 'gm' : 'pc');
console.log(JSON.stringify(clean));
renderAll(db);
dumpDb(db);
}
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]);
const db = openDb();
setPaper(db, items, `ingested from ${path.basename(p)}`, 'seed');
console.log(JSON.stringify(paperList(db)));
renderAll(db);
dumpDb(db);
}
@@ -766,9 +876,9 @@ function cmdStatus() {
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
console.log(`records: ${nr}`);
const sk = db.prepare('SELECT * FROM status ORDER BY updated DESC, key').all()
.map((r) => r.key + (r.value && r.value !== r.normal && r.normal ? '!' : ''));
console.log(`status: ${sk.length ? sk.join(', ') : '(nothing set)'}`);
const paper = paperList(db);
console.log(`paper: ${paper.length ? '' : '(a blank sheet)'}`);
for (const d of paper) console.log(` - ${d}`);
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] ?? '∞';
@@ -785,7 +895,9 @@ function cmdStatus() {
// --- dispatch ----------------------------------------------------------------
switch (cmd) {
case 'packages': cmdPackages(); break;
case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2]); break;
case 'seed': cmdSeed(FORCE, args[0]); break;
case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break;
@@ -796,10 +908,10 @@ switch (cmd) {
case 'file': (args.length >= 2) ? cmdFile(args[0], args[1], args[2] ?? '', args[3]) : fail('usage: file <kind> "Label" "detail" ["reason"]'); break;
case 'amend': (args.length >= 2) ? cmdAmend(args[0], args[1]) : fail('usage: amend <rid> "new detail"'); break;
case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break;
case 'set': (args.length >= 2) ? cmdSet(args[0], args[1], args[2]) : fail('usage: set <key> "value" ["reason"]'); break;
case 'norm': (args.length >= 2) ? cmdNorm(args[0], args[1], args[2]) : fail('usage: norm <key> "baseline" ["reason"]'); break;
case 'clear': (args.length >= 1) ? cmdClear(args[0]) : fail('usage: clear <key>'); break;
case 'unset': (args.length >= 1) ? cmdUnset(args[0]) : fail('usage: unset <key>'); break;
case 'paper': cmdPaper(); break;
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); break;
case 'paper-set': (args.length >= 1) ? cmdPaperSet(args) : fail('usage: paper-set "descr" ["descr" ...]'); break;
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break;
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;
@@ -807,6 +919,6 @@ switch (cmd) {
case 'dump': cmdDump(); break;
case 'restore': cmdRestore(FORCE); break;
default:
console.error('usage: node tool/memory.mjs <init|render|apply|insert|delete|revive|dump|restore|status>');
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>');
process.exit(1);
}