gm surface: home flow, run identity, full-assembly editor, notepad, wrap replay; sigils and dateless rings

This commit is contained in:
2026-11-14 09:04:13 +00:00
parent ba72d2ed1f
commit 9f85adc3c6
20 changed files with 2014 additions and 433 deletions
+53 -8
View File
@@ -57,7 +57,13 @@ memory the agent owes itself across sessions.
- The edit tool matches bytes, and the console renders dashes - The edit tool matches bytes, and the console renders dashes
unreliably. When an edit fails on text that "looks right," dump char unreliably. When an edit fails on text that "looks right," dump char
codes via PowerShell before retrying; or transcribe from a fresh codes via PowerShell before retrying; or transcribe from a fresh
read, never from memory. read, never from memory. **The three-space trap (bitten 2026-11-13
and 2026-11-14):** the read tool prefixes each line with `N: `, so
continuation-line indentation LOOKS one space deeper than it is —
eyeballing a " the package" was really " the package". Never
count indentation from the rendered display: dump the exact line
with `node -e` + JSON.stringify and transcribe from that when an
edit keeps failing on text that reads right.
- `node:sqlite` prints an ExperimentalWarning on every clerk call — - `node:sqlite` prints an ExperimentalWarning on every clerk call —
harmless, filtered in bridge context. harmless, filtered in bridge context.
- Session logs, dumps, and views are generated; never hand-edit them. - Session logs, dumps, and views are generated; never hand-edit them.
@@ -94,18 +100,57 @@ memory the agent owes itself across sessions.
of their input once while a test confirm hung on my dialog-tool of their input once while a test confirm hung on my dialog-tool
fumbling). In-page UI only: the banner for notices, two-click arm fumbling). In-page UI only: the banner for notices, two-click arm
for confirms. for confirms.
- Browser-tool gotchas (2026-11-14, UI testing): evaluate takes a raw
expression, not an arrow function (an arrow returns the function
uninvoked — its .value serializes to {} and silently corrupts
whatever you build from it); wait's text matches RENDERED text, so
CSS text-transform breaks literal waits (wait for "HER PAPER", not
"her paper"); clickable divs are invisible to the a11y tree and the
keyboard — clickable things are buttons.
- Gotcha (2026-11-14, rewind aftermath): a session rewind erases my - Gotcha (2026-11-14, rewind aftermath): a session rewind erases my
memory of tool calls but NOT their effects — the server, files, and memory of tool calls but NOT their effects — the server, files, and
databases keep them. After any rewind, external state is the truth: databases keep them. After any rewind, external state is the truth:
re-read it, and never assume authorship of found content (I once re-read it, and never assume authorship of found content (I once
credited the GM with a GM-turn that pre-rewind me had written). credited the GM with a GM-turn that pre-rewind me had written).
- Open tails: none on the prompt side — housekeeper aligned to the - Open tails (handoff, 2026-11-14): **housekeeper.md review is the
invariants paper boundary (2026-11-14), assembly order confirmed next creative step** — the GM's dry-run verdict was "works, but not
(system → invariants → the run's handbook, one system message). as expected; I never saw the prompt"; iterate with the replay
- Dates principle (2026-11-14): dates in seeds/manifests/rings are button (nothing applied). **Status discipline**: the paper has
STORY dates; real dates never surface to the player (canon: taken up thread-tracking; the GM wants the admission-gate section
la-caramba is 2069). The seed was fixed to 2069-11-18 (day is the in invariants.md tightened. **Verbosity**: completions lengthened
GM's call). 103 -> 668 chars across window one; the GM is thinking about it.
The first real wrap (Irene's window) is the memory test's start.
- Active work: NONE — the GM surface rework is complete and
live-proven; the first real story is being played. Working lessons
from the build: the newest GM turn must keep its <status>/<conflict>
blocks (that ride is the paper's only channel from window two on);
any new path that reads a run file for sending goes through
expandVars (turn0() initially didn't); the transcript must surface
failed window-open notes (ingest), not print success unconditionally;
after changing a default, re-run the primary path (the start button
broke for the GM because post-redesign tests never pressed it).
- Postulates (GM, 2026-11-14): female PCs only (names are gendered;
QUESTIONS #2 closed by it). Boutique is dormant AND defunct — fine
broken until its design round; do not fix or design it unprompted.
- Identity model (2026-11-14): @PC/@Package are identity sigils
(settings pc/name); $TOKENs are prompt-declared template vars
(setup inputs -> settings vars). Run ids are anonymous hex —
display is always "Package / PC". Any new prompt-side file reader
goes through expandVars.
- Exposure rule (GM, 2026-11-14): everything that enters the bundle
is inspectable read-only in the SPA (system.md, invariants.md, the
assembled system message in the bundle card); anything that prompts
an internal agent (housekeeper.md) is never exposed. Don't hide
bundle parts, don't surface agent prompts.
- Dates principle (revised 2026-11-14, GM): **no model-facing surface
renders a date** — ring views, search results, everything the
player-model sees. Memory doesn't timestamp; when something happened
lives in the entry prose. Internal stamps (created/last_touched) are
real, mechanical (LRU/overflow/sinking), never rendered; GM-facing
CLI keeps them. The manifest and seed carry no date keys at all —
the housekeeper's date duty is gone (it couldn't ask, and the touch
stamp was rewriting story time). Supersedes the story-date ruling
below.
- Watch: the "never open with world narration" rule was cut as - Watch: the "never open with world narration" rule was cut as
superfluous by the GM — reinstate only if testing shows drift. superfluous by the GM — reinstate only if testing shows drift.
- Defaults taken without asking (2026-11-13): #21 window-open refuses - Defaults taken without asking (2026-11-13): #21 window-open refuses
+60 -74
View File
@@ -9,6 +9,43 @@ file is the "where did we leave off" map.
## Where we are ## Where we are
- **The GM surface rework is complete and live-proven (2026-11-14).**
Home lists runs by display name with live state; new run walks a
package picker into a naming form (package display name + a
dictionary-rolled, per-package-unique pc name, names-female.txt);
setup is a full-assembly editor (system.md/invariants.md read-only
first, then the editable craft in bundle order — handbook, backdrop,
character, seed, turn-0 — then read-only config; sigil/var
highlighting; $TOKENs declared by the prompts surface as inputs and
gate start; drafts two-click deletable); start opens the window and
sends turn-0 as the first GM turn. Play carries: the GM notepad
(gm.md — auto-saved, never model-facing), the paper as a compact
comma block with a GM edit button (paper-set, journaled),
housekeeping with a dry-run replay button, diagnostics on both
sides of the wire (server request log + a sessionStorage event log
behind the header's "log" button), busy indicators, and hardened
failure modes (no throw-to-home — only a real 404 leaves, loudly;
failed sends restore the line). Identity: @PC/@Package are identity
sigils (settings pc/name — a distinct class from $TOKENs, which the
prompts declare and setup collects); run ids are anonymous hex;
display is "La Caramba / Rell". Postulates: female PCs only;
boutique dormant AND defunct. Exposure rule: bundle parts are
inspectable read-only; agent prompts (housekeeper.md, repo-fed at
wrap, never copied) are never exposed.
- **Dates left the rings (GM, 2026-11-14).** No model-facing surface
renders a date — the old rendered date was the touch stamp
(referencing a memory rewrote its "when"), and records search
leaked real dates too. Manifest and seed carry no date keys; stamps
are internal and mechanical (LRU, overflow, "what's sinking" —
GM-facing only). Story time lives in prose. Live-proven: the real
housekeeper produced a clean dateless manifest first try.
- **The first real story is live: "La Caramba / Irene"** (run
4f261452, gitignored state). Window one open, 44+ exchanges at ~23K
prompt tokens — 9% of the window; the economy holds because
thinking never goes back, old status rides strip, and the bundle
floor is ~4.2K tokens. The GM ran the wrap dry-run on it: works
mechanically, output not yet as expected — housekeeper.md review
pending (the GM has not read the prompt yet).
- **The MVP substrate is complete (2026-11-14): all four phases built, - **The MVP substrate is complete (2026-11-14): all four phases built,
mock-proven, and live-proven.** Clerk (paper model, presets/runs), mock-proven, and live-proven.** Clerk (paper model, presets/runs),
server (REST spine, session machine, view renderer), housekeeping server (REST spine, session machine, view renderer), housekeeping
@@ -16,17 +53,13 @@ file is the "where did we leave off" map.
bridge is deleted. Two real housekeeping wraps ran clean (both bridge is deleted. Two real housekeeping wraps ran clean (both
manifests sound: correct ring-B classification, first-person voice, manifests sound: correct ring-B classification, first-person voice,
precise touches); a full session was driven through the UI end to precise touches); a full session was driven through the UI end to
end. All test runs are deleted; **no runs exist; the server is end. **The server is stopped** (state as of this commit). Start it:
stopped**. Start it: `node server/main.mjs [--mock]`, SPA at `node server/main.mjs [--mock]`, SPA at
http://127.0.0.1:7350/ (see AGENTS gotchas: check port 7350 first; http://127.0.0.1:7350/ (see AGENTS gotchas: check port 7350 first;
POST from PowerShell via Invoke-RestMethod). POST from PowerShell via Invoke-RestMethod).
- Nothing has been *played* yet — every session so far was a test.
The story starts with the next session: `create la-caramba <id>`,
window one, for real.
- Live endpoint proven in-flow (glm-5.3 via llm.exan.tech, 13 models - Live endpoint proven in-flow (glm-5.3 via llm.exan.tech, 13 models
carried on /models): right-format turns in her voice first try, carried on /models): right-format turns in her voice first try,
paper transport both directions, usage/context meter live, paper transport both directions, usage/context meter live.
story-dated wraps.
- **Prompt split in force (GM's cut, 2026-11-14):** `system.md` = - **Prompt split in force (GM's cut, 2026-11-14):** `system.md` =
opening + guards (glossary, purpose, input validation — repo-fed, opening + guards (glossary, purpose, input validation — repo-fed,
per-project); `invariants.md` = substrate (syntax markers, tools, per-project); `invariants.md` = substrate (syntax markers, tools,
@@ -70,7 +103,7 @@ file is the "where did we leave off" map.
thinking-strip, usage tracking) land with the server. thinking-strip, usage tracking) land with the server.
- **Phase 1 (preset/run split) DONE (2026-11-13):** packages are - **Phase 1 (preset/run split) DONE (2026-11-13):** packages are
authored-only (backdrop, turn-0, character, seed, settings, gm — all authored-only (backdrop, turn-0, character, seed, settings, gm — all
six state dirs removed); `create <package> <run-id>` copies the six state dirs removed); `create <package> <pc-name>` copies the
package wholesale into `runs/<id>/` (shared prompts included, run.json package wholesale into `runs/<id>/` (shared prompts included, run.json
lineage + optional model override) and inits state; `--run` addresses lineage + optional model override) and inits state; `--run` addresses
runs; `packages`/`runs` list; `bridge.json` → `server.json` runs; `packages`/`runs` list; `bridge.json` → `server.json`
@@ -95,72 +128,25 @@ file is the "where did we leave off" map.
## Immediate next steps, in order ## Immediate next steps, in order
1. **Prompt split DONE (2026-11-14, GM's cut).** system.md = opening + 1. **The first real wrap — the memory test begins.** Close-and-
guards (glossary, purpose, input validation — repo-fed, per-project); housekeep the Irene window when the GM is ready; review the
invariants.md = substrate (syntax, tools, memory, records, the manifest and the window log against the dump diff (the audit
paper + its gate — repo-fed, travels with the code); handbook.md = surface). Everything from the story so far (the shipwreck, Molly,
craft copy (shape of play, purview, time skips, stance, hard limits the island) lives only in context and on the paper until this
— copied per run). The clerk's create copies handbook.md + lands.
housekeeper.md only. Assembly confirmed: one system message, 2. **Housekeeper prompt review (GM-led).** The GM's dry-run verdict:
system.md → invariants.md → the run's handbook.md, then the bundle works mechanically, output not as expected, and the prompt itself
as GM messages. Housekeeper aligned to the invariants paper is unseen so far. Iterate: read housekeeper.md, tweak, replay —
boundary (acute states on the paper; relational shifts recorded as the dry-run button re-runs the wrap over the session log with
the facts behind them). Watch item: "never open a scene with world nothing applied.
narration" was cut as superfluous (GM, 2026-11-14) — reinstate if 3. **Status discipline (GM wants the section tightened).** The paper
narrative-discipline drift shows in testing. has taken up thread-tracking ("planning to talk to Pinky" is a
2. **Server (phase 2) DONE (2026-11-14, mock-proven).** `server/` — thread, not an acute state); the admission-gate copy in
zero-dep node:http REST spine per the ROADMAP sketch; per-run invariants.md's paper section wants tightening.
session machine with ask_gm pause/resume (whole batch waits, so 4. **Keep playing.** Observables #12 (does the paper stay small and
pairing stays sound); view renderer (thinking-strip, tool-result match the transcripts) and #14 (one thing per turn vs lengthening
elision with ask answers exempt, old status/conflict blocks turns — completions grew 103 to 668 chars across window one) are
stripped); boot-rebuild from the typed jsonl; lazy seed + turn-0 live now.
ingestion at window-open (with the #21 refuse-with-override guard);
usage tracking + context meter; tool-pairing validation; `--mock`
scripted model. Smoke: create → open → roll → ask pause → answer →
paper deltas → restart → rebuild → live turn. The clerk gained
`--json` (packages/runs/status). **tool/bridge.mjs deleted at
mock-parity.** **Live API proven same day (run `live-smoke`):** the
upstream /models listing works (13 models carried), the assembled
prompt produces right-format turns in her voice, paper deltas
applied both turns, usage/context meter live (~4.6K prompt tokens,
2% of window). Not yet exercised live: ask_gm in flow (the model
just made its choices — by design), the conflict-carry path,
records tools (la-caramba has none), housekeeping (phase 3).
3. **Housekeeping job (phase 3) DONE (2026-11-14, mock + live).**
`server/housekeeping.mjs`: trigger ends the window and runs the
chain async (transcript with labeled thinking -> housekeeper on a
fresh context with run state injected -> manifest saved (raw output
too, if unparseable) -> clerk apply (validates, writes the window
log, snapshots `dumps/<window>.sql`) -> `state.json`
`lastHousekeptSession` -> autorestart). Rejection holds the restart
and surfaces why; `POST .../housekeeping/apply` is the recovery
path (hand-edited manifests, also the manual-relay close). The
first real wrap ran on `live-smoke`: window
`2026-11-18-beach-arrival`, two ring-B inserts, two correct
touches, clean voice — the manifest and log are in the run dir for
review.
4. **SPA (phase 4) DONE (2026-11-14).** `web/` — index.html, style.css,
app.mjs; no build step, vanilla ES modules, served by the server
from `/`. Transcript renders the three registers by the ruled
markers (plain speech, *italics* narration incl. multi-line blocks,
single-paren OOC with lone-paren skip), the bundle as a collapsed
card with turn-0 as the opening GM turn, paper tags as chips,
status/conflict extracted to the pane, machinery muted. Run
selector + new-run form, window-open (with the #21 override
confirm), GM line input (Enter sends), ask modal (re-presents on
refresh via detail.pendingAsk), status pane, context meter (hot
past 85%), housekeeping button with confirm → 3s poll → log
display → autorestart. Found and fixed in testing: `.mjs` MIME
(module scripts enforce it), multi-line narration parsing. One
prompt fix: housekeeper.md now teaches story dates (the second
real wrap dated itself with the wall clock otherwise).
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 ## Working agreements with the GM
+15 -12
View File
@@ -13,13 +13,11 @@ generic name ("*Alice starts searching her pockets*"), decoupling the
example from the PC. A rename touches `settings.json` `vars.PC` and the example from the PC. A rename touches `settings.json` `vars.PC` and the
sheet H1 only. sheet H1 only.
### 2. Pronouns are hardcoded she/her in the shared files — OPEN ### 2. Pronouns are hardcoded she/her in the shared files — RESOLVED BY POSTULATE (2026-11-14)
`system.md` is shared by both runs and says "her paper", "she never Names are inherently gendered, so the harness postulates female PCs
expects them to", throughout; so do the prelude and the status views. only (README Scope); she/her throughout the shared files is correct
Fine while every PC is a woman; the boutique shopkeeper may not be. by that postulate. Male or otherwise PCs reopen this — the line to
Options: per-run pronoun vars in `settings.json`, or neutral phrasing in revisit is named in the README.
the shared files. Decide before boutique drafting at the latest.
(2026-11-12)
### 3. The system-prompt disclosure example — RESOLVED (2026-11-12) ### 3. The system-prompt disclosure example — RESOLVED (2026-11-12)
GM wrote the addressee rule into system.md: OOC input addressing the GM wrote the addressee rule into system.md: OOC input addressing the
@@ -86,14 +84,19 @@ Logged with the assistant message, never displayed. Keep the
fiction-first surface clean, or expose reasoning in a SPA debug pane? fiction-first surface clean, or expose reasoning in a SPA debug pane?
(2026-11-12) (2026-11-12)
### 12. seed.json date is 2026-11-18 — RESOLVED (2026-11-14) ### 12. seed.json date is 2026-11-18 — RESOLVED, then SUPERSEDED (2026-11-14)
The date was a real-world date; real dates look alien when exposed to The date was a real-world date; real dates look alien when exposed to
the player, and the canon (turn-0) establishes la-caramba takes place the player, and the canon (turn-0) establishes la-caramba takes place
in 2069. Principle: dates in seeds and manifests are story dates, and in 2069. Principle: dates in seeds and manifests are story dates, and
real dates never surface to the player. The seed now carries a 2069 real dates never surface to the player. The seed was fixed to a 2069
story date (proposed 2069-11-18 — the actual day is the GM's canon story date; the housekeeper followed the story dates it saw in the
call); the housekeeper follows the story dates it sees in the rings rings. **Superseded later the same day (GM):** dates left the rings
(its first real manifest was story-dated). entirely — the rendered date was the touch stamp (referencing a
memory rewrote its "when"), the housekeeper's date duty was a silent
failure surface it couldn't ask about, and the model had no story-now
to anchor dates against anyway. No model-facing surface renders a
date now; the seed and manifest carry no date keys; story time lives
in prose. See README (memory model) and AGENTS.
### 13. Time conventions — RESOLVED (2026-11-12) ### 13. Time conventions — RESOLVED (2026-11-12)
Settled and written into system.md: speech takes any tense naturally Settled and written into system.md: speech takes any tense naturally
+73 -28
View File
@@ -50,6 +50,11 @@ no handbook, no stats. Anything goes if it makes sense and makes the story
better. Retcons are allowed but discouraged; when they happen they are better. Retcons are allowed but discouraged; when they happen they are
explicit and logged. explicit and logged.
The harness currently supports **female PCs only** — names are inherently
gendered and the shared prompts say "she" throughout; the postulate is
cheaper than a gender system no customer has asked for yet. When a male
or otherwise PC ever needs support, this is the line to revisit.
## Runs ## Runs
Two interleaved stories calibrate the memory system against itself: Two interleaved stories calibrate the memory system against itself:
@@ -62,14 +67,20 @@ Two interleaved stories calibrate the memory system against itself:
| player agency | constrained — reactive creativity | full — proactive creativity | | 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 | | records access | none — until the GM unlocks it in the story | the card index on the shop PC |
Boutique is dormant — a stub that never reached its design step — until Boutique is dormant and defunct — a stub that never reached its design
its drafting session. step — broken is fine until its drafting session gives it design and
proper content.
`node tool/memory.mjs packages` lists presets; `runs` lists instances; `node tool/memory.mjs packages` lists presets; `runs` lists instances;
`--run <id>` addresses a run for any command. `--run <id>` addresses a run for any command.
## Booting a run ## Booting a run
Through the CLI below, or through the SPA: home → new run → pick a
package → edit the copied prompts (project prompts inspectable
read-only alongside) → **start** — which creates the run, opens the
window, and sends turn-0 as the first GM turn in one action.
1. **Backdrop** — write `packages/<story>/backdrop.md`: the world as everyone 1. **Backdrop** — write `packages/<story>/backdrop.md`: the world as everyone
in it knows it. Public knowledge, general setting. Neither memory nor in it knows it. Public knowledge, general setting. Neither memory nor
state — never touches the rings, never decays, always in the bundle. state — never touches the rings, never decays, always in the bundle.
@@ -97,10 +108,15 @@ its drafting session.
freely editable; deleting it from the run is the opt-out. Everything freely editable; deleting it from the run is the opt-out. Everything
is journaled under window `seed`. Her opening paper does not seed — is journaled under window `seed`. Her opening paper does not seed —
it rides turn-0's `<status>` block. it rides turn-0's `<status>` block.
5. **Create the run** — `node tool/memory.mjs create <story> <run-id>`: 5. **Create the run** — `node tool/memory.mjs create <story> <pc-name>`:
the package is copied wholesale into `runs/<run-id>/` — the craft the package is copied wholesale into `runs/<id>/` — the craft
prompts (`handbook.md`, `housekeeper.md`) ride along, battery prompt (`handbook.md`) rides along, battery
included — and the db is initialized. From then on the run directory is the included — and the db is initialized. The run id is anonymous (it
carries no facts, so there is nothing to rename); the pc's name
and the package's display name land in the run's `settings.json`
and drive what everything shows: "La Caramba / Rell". Different
runs of the same package need different pc names. From then on
the run directory is the
only truth: the package is never read again, and everything in 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 run is editable at any time. The discipline not to break a running
narrative sits with the GM. narrative sits with the GM.
@@ -118,14 +134,24 @@ its drafting session.
else arrives as GM messages (user role), one message else arrives as GM messages (user role), one message
per file: `backdrop.md`, `character.md`, `canon/ring-b.md`, per file: `backdrop.md`, `character.md`, `canon/ring-b.md`,
`canon/ring-a.md` — identity first, then memory, ring A in the `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 recency slot. On a new game, `turn-0.md` is the opening beat: its
the GM's first line, and its trailing `<status>` block is ingested trailing `<status>` block is ingested as her opening paper at
as her opening paper. In play the current paper rides every GM turn window-open, and the beat itself is sent as the first GM turn when
play starts — a separate message through the turn path, not part of
the bundle. In play the current paper rides every GM turn
the same way (the per-turn ride lands with the server). (On a tight 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` window, ring B is optional loading — ring A is the spine.)
tokens in any bundle file are substituted from the run's Substitution has two classes: `@PC` (her name) and `@Package` (the
`settings.json` `vars` before sending. The server assembles and display name) are identity sigils resolved from the run's
logs all of this automatically (until it lands: manual relay). `settings.json` `pc`/`name`; `$TOKEN`s are template vars declared
by the prompts themselves — every `$TOKEN` found in any prompt
surfaces as an input in the SPA's setup, and the run's `vars`
holds the answers (a package may ship defaults). Unresolved
sigils-of-ours and vars fail loudly before anything is sent; any
other `@`-word is the author's own text — `@` syntax is not owned
here — and passes through untouched. The server
assembles and logs all of this automatically (until it lands:
manual relay).
3. **In play:** a line opening with `(` is the out-of-character channel — 3. **In play:** a line opening with `(` is the out-of-character channel —
points of order, canon questions, proposals, vetoes; both sides use points of order, canon questions, proposals, vetoes; both sides use
it, closing paren optional. Entries carry stable ids (`[e17]`); it, closing paren optional. Entries carry stable ids (`[e17]`);
@@ -143,7 +169,9 @@ its drafting session.
tool; the GM's own OOC stays `(...)` in their turns. tool; the GM's own OOC stays `(...)` in their turns.
4. **Close a window:** just stop. No in-band ritual; the player-model has no 4. **Close a window:** just stop. No in-band ritual; the player-model has no
end-of-session duties. end-of-session duties.
5. **Housekeep (fresh model, new context):** send `housekeeper.md`, then 5. **Housekeep (fresh model, new context):** send `housekeeper.md`
(the repo-fed housekeeping prompt — substrate-internal, never
copied into a run), then
the run's `backdrop.md` and `character.md`, then both ring views, then the run's `backdrop.md` and `character.md`, then both ring views, then
the session transcript — pasted, or the latest the session transcript — pasted, or the latest
`runs/<id>/sessions/*.jsonl` when playing through the server (the `runs/<id>/sessions/*.jsonl` when playing through the server (the
@@ -201,9 +229,15 @@ mechanical — `LIMIT 10` in the tool, not a polite request in the prompt.
reach, GM-reachable via `revive`. Nothing is ever destroyed; the hierarchy reach, GM-reachable via `revive`. Nothing is ever destroyed; the hierarchy
is **A hot, B warm, cold dead-to-the-character**. is **A hot, B warm, cold dead-to-the-character**.
- Both rings are ordered by touch — most recently touched on top, an LRU - Both rings are ordered by touch — most recently touched on top, an LRU
cache. A memory meaningfully invoked during play is *touched*: its date cache. A memory meaningfully invoked during play is *touched*: it
updates and it rises. Untouched memories sink toward the tail. Mere rises. Untouched memories sink toward the tail. Mere
adjacency doesn't count as a touch. adjacency doesn't count as a touch.
- **Entries carry no dates.** Memory doesn't timestamp — when something
happened lives in the prose ("the morning after the storm"), which is
the only chronology the views ever had anyway, since they order by
touch. Internal stamps exist and stay mechanical (LRU, overflow,
"what's sinking") but never render; no model-facing surface shows a
date.
- **Promotion and demotion are the housekeeper's judgment**, not metrics: a - **Promotion and demotion are the housekeeper's judgment**, not metrics: a
B entry the session showed to be load-bearing moves to A (reason logged); B entry the session showed to be load-bearing moves to A (reason logged);
a spent A entry may move down. When unsure, leave it — if it matters, it a spent A entry may move down. When unsure, leave it — if it matters, it
@@ -215,7 +249,7 @@ mechanical — `LIMIT 10` in the tool, not a polite request in the prompt.
Caps are dials in `tool/memory.mjs`; retune freely. Caps are dials in `tool/memory.mjs`; retune freely.
The judgment call under test is **"which ring"** — classification, plus the The judgment call under test is **"which ring"** — classification, plus the
promote/demote eye. Everything clerical (ordering, dates, caps, overflow, promote/demote eye. Everything clerical (ordering, caps, overflow,
rendering, logging) is code. rendering, logging) is code.
Why this shape: it's an LRU cache, it's generational GC, and — most Why this shape: it's an LRU cache, it's generational GC, and — most
@@ -364,13 +398,19 @@ invariants.md the substrate tier — the mechanical contracts (syntax
handbook.md the craft tier, shipped default — copied into each handbook.md the craft tier, shipped default — copied into each
run at creation, editable to taste (shape of play, run at creation, editable to taste (shape of play,
purview, time skips, content stance, hard limits) purview, time skips, content stance, hard limits)
housekeeper.md shipped-default housekeeping prompt — copied per run housekeeper.md the wrap prompt — repo-fed at wrap, never copied
into a run, never user-facing: it prompts the
internal housekeeper agent, never the bundle
(system.md and invariants.md are bundle parts and
are inspectable read-only in the SPA)
HANDOFF.md working state — where did we leave off, next steps, gotchas HANDOFF.md working state — where did we leave off, next steps, gotchas
ROADMAP.md SOTA review and steal list, worked point by point ROADMAP.md SOTA review and steal list, worked point by point
QUESTIONS.md the decision queue — open questions, pending calls QUESTIONS.md the decision queue — open questions, pending calls
AGENTS.md the agent's own working notes — style lessons, gotchas, AGENTS.md the agent's own working notes — style lessons, gotchas,
state pointers state pointers
config.json the default package config.json the default package
names-female.txt the name dictionary — one name per line; the new-run
form rolls an unused one for the main character
tool/ tool/
memory.mjs the clerk: packages, runs, create, init, seed, render, memory.mjs the clerk: packages, runs, create, init, seed, render,
apply, insert, delete, revive, file, amend, discard, apply, insert, delete, revive, file, amend, discard,
@@ -385,7 +425,7 @@ server/ the substrate: a zero-dependency node:http service
open windows from the session logs on start open windows from the session logs on start
provider.mjs the endpoint client (chat completions, models listing) provider.mjs the endpoint client (chat completions, models listing)
bundle.mjs run context: prompt assembly (the trio system message, bundle.mjs run context: prompt assembly (the trio system message,
the GM-message bundle, $NAME vars), the tool manifest the GM-message bundle, @ sigils + $ vars), the tool manifest
and its clerk dispatch and its clerk dispatch
session.mjs window lifecycle (open guards, lazy seed + turn-0 session.mjs window lifecycle (open guards, lazy seed + turn-0
ingestion), the append-only typed jsonl, the view ingestion), the append-only typed jsonl, the view
@@ -397,24 +437,29 @@ server/ the substrate: a zero-dependency node:http service
with labeled thinking, run-state injection, the with labeled thinking, run-state injection, the
housekeeper call, manifest save, apply, autorestart; housekeeper call, manifest save, apply, autorestart;
rejections hold and surface why rejections hold and surface why
web/ the SPA — no build, vanilla ES modules, served at / web/ the SPA — no build, vanilla ES modules, path-routed
index.html the layout: transcript, status pane, context meter, index.html the shell: home (runs), new (packages), setup (editor),
GM input, ask modal play (transcript, status pane, context meter, GM input,
app.mjs the client: register parsing (speech / narration / ask modal) — the server serves it for any extensionless
OOC), bundle cards, turns, housekeeping polling path
app.mjs the client: routing, the setup editor, register parsing
(speech / narration / OOC), bundle cards, turns,
housekeeping polling
style.css dark, quiet, fiction-first style.css dark, quiet, fiction-first
server.example.json copy to server.json (gitignored) — bind, endpoint + server.example.json copy to server.json (gitignored) — bind, endpoint +
key env, models, contextWindow, params passthrough key env, models, contextWindow, params passthrough
db/ db/
schema.sql entries, records, paper, events journal (shared) schema.sql entries, records, paper, events journal (shared)
runs/ per-deployment run state (gitignored) — one dir per run: runs/ per-deployment run state (gitignored) — one anonymous
the copied package, the craft prompts (handbook.md, id per run (carries no facts): the copied package,
housekeeper.md), run.json (lineage, the craft prompt (handbook.md),
run.json (lineage,
model override), db/, canon/ (rendered views), dumps/, model override), db/, canon/ (rendered views), dumps/,
log/, manifests/, sessions/ log/, manifests/, sessions/
packages/ presets — authored content only, never state packages/ presets — authored content only, never state
la-caramba/ backdrop.md, turn-0.md (new-game opener), character.md, la-caramba/ backdrop.md, turn-0.md (new-game opener), character.md,
seed.json, settings.json, gm.md (GM-private — never in seed.json, settings.json, gm.md (the GM's notepad —
seeded per run, always editable in the SPA, never in
any bundle) any bundle)
boutique/ dormant stub, same shape — records enabled (the boutique/ dormant stub, same shape — records enabled (the
shopkeep's PC) once designed shopkeep's PC) once designed
+22 -4
View File
@@ -147,6 +147,13 @@ example, gitignored real file, env-var option).
substrate reach existing runs; craft edits are per-run. The GM's cut substrate reach existing runs; craft edits are per-run. The GM's cut
also resolved the OOC syntax conflict (system.md no longer teaches also resolved the OOC syntax conflict (system.md no longer teaches
`((double parens))`). `((double parens))`).
Amendment (GM, 2026-11-14): `housekeeper.md` is repo-fed at wrap,
never copied into a run, never user-exposed. The seam is not
machinery vs taste but the exposure rule: everything that enters
the bundle is inspectable read-only (`system.md`, `invariants.md`
included — the user should understand how the model is prompted);
`housekeeper.md` never enters the bundle — it prompts the separate
internal housekeeper agent.
- **The audit moved into the run.** Runs are gitignored, so the - **The audit moved into the run.** Runs are gitignored, so the
commit-per-wrap ritual is retired. At apply time the clerk snapshots 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 `dumps/w<N>.sql`; post-wrap review is async — the window log against
@@ -300,16 +307,27 @@ context inspector (steal #6), book export, the service step.
API sketch (the operable spine, amended per-run): API sketch (the operable spine, amended per-run):
GET /api/models ask the upstream what it carries GET /api/models ask the upstream what it carries
GET /api/packages list presets (records gate, turn-0, seed) GET /api/packages list presets (display name, pc default, records gate, turn-0, seed)
GET /api/runs list runs (package, fill, window state) GET /api/prompts the repo-fed prompts (system, invariants) — read-only
POST /api/runs create {package, name, model?} GET /api/names roll an unused dictionary name for a new main character
GET /api/runs/<id> status tier, fill, context meter, pending ask_gm GET /api/runs list runs (display "La Caramba / Rell", fill, open window, draft/housekept state)
POST /api/runs create {package, pc, name?, model?} — anonymous id, pc unique per package
GET /api/runs/<id> status tier, fill, context meter, pending ask_gm, draft, display
GET /api/runs/<id>/files run file contents — craft rw, config ro, whitelisted
PUT /api/runs/<id>/files/<file> edit a run file (whitelist, JSON validated)
POST /api/runs/<id>/vars fill the $TOKENs the prompts declare (saved to settings vars)
POST /api/runs/<id>/windows open a window (lazy seed, render, assemble) POST /api/runs/<id>/windows open a window (lazy seed, render, assemble)
POST /api/runs/<id>/turn0 send turn-0 as the first GM turn (fresh window)
GET /api/runs/<id>/notes the GM's notepad (gm.md) — never sent to any model
PUT /api/runs/<id>/notes update the notepad
GET /api/runs/<id>/session transcript + pending ask_gm + usage GET /api/runs/<id>/session transcript + pending ask_gm + usage
POST /api/runs/<id>/turn GM line -> runs the loop POST /api/runs/<id>/turn GM line -> runs the loop
POST /api/runs/<id>/ask answer a pending ask_gm POST /api/runs/<id>/ask answer a pending ask_gm
GET /api/runs/<id>/status the status tier, structured GET /api/runs/<id>/status the status tier, structured
POST /api/runs/<id>/paper GM override: replace the whole paper (empty = clear)
DELETE /api/runs/<id> delete a draft (no sessions); played runs refuse — by hand
POST /api/runs/<id>/housekeeping run the chain (ends the window), async POST /api/runs/<id>/housekeeping run the chain (ends the window), async
POST /api/runs/<id>/housekeeping/replay dry-run the housekeeper over a session log — nothing applied
GET /api/runs/<id>/housekeeping job state: idle | running | applied | rejected GET /api/runs/<id>/housekeeping job state: idle | running | applied | rejected
GET /api/runs/<id>/housekeeping/log latest window log GET /api/runs/<id>/housekeeping/log latest window log
POST /api/runs/<id>/housekeeping/apply apply a manifest directly POST /api/runs/<id>/housekeeping/apply apply a manifest directly
+8 -9
View File
@@ -46,8 +46,7 @@ detail carries the memory.
```json ```json
{ {
"window": "YYYY-MM-DD-short-slug", "window": "short-slug",
"date": "YYYY-MM-DD",
"summary": "one short paragraph on what happened", "summary": "one short paragraph on what happened",
"insert": [ "insert": [
{ "ring": "b", "type": "fact", "label": "The Gull", "detail": "I know the place — by the fish market, smells of tar", "reason": "the character now knows it" } { "ring": "b", "type": "fact", "label": "The Gull", "detail": "I know the place — by the fish market, smells of tar", "reason": "the character now knows it" }
@@ -63,18 +62,18 @@ detail carries the memory.
} }
``` ```
Every key except `window`, `date`, and `summary` is optional — empty or Every key except `window` and `summary` is optional — empty or
omitted is fine. Types are `place`, `person`, `fact`, `thread`. Ids come omitted is fine. Types are `place`, `person`, `fact`, `thread`. Ids come
from the rendered views; never invent one. `date` is a **story date**: from the rendered views; never invent one. When something happened —
follow the calendar already established in the ring views and the before, after, how long ago — belongs in the *detail prose* in the
transcript — never the real-world clock, whose dates must never reach character's voice ("the morning after the storm"), never in a field of
the player. Housekeeping is **rings-only**: its own. Housekeeping is **rings-only**:
`archive` is valid when the run provides records (the invocation tells `archive` is valid when the run provides records (the invocation tells
you), but `record` is not yours at all — filing happens at the player's you), but `record` is not yours at all — filing happens at the player's
desk, and the tool rejects it. desk, and the tool rejects it.
Promote, demote, and reword count as touches — the script updates the touch Promote, demote, and reword count as touches — the script handles the
date for you. Don't list an id twice across operations. mechanics for you. Don't list an id twice across operations.
# Judgment rules — the heart of the job # Judgment rules — the heart of the job
+366
View File
@@ -0,0 +1,366 @@
Ada
Adele
Adrienne
Agnes
Aiko
Alba
Alice
Alina
Alma
Amanda
Amber
Amelia
Ana
Anouk
April
Astrid
Athena
Aubrey
Aurora
Ava
Bailey
Beatrice
Bella
Betty
Bianca
Bonnie
Brenda
Briar
Brielle
Bronwyn
Caitlin
Camille
Carla
Carmen
Carol
Cassandra
Catalina
Catherine
Cecily
Celeste
Charlotte
Chelsea
Chloe
Clara
Claire
Clara
Clementine
Colleen
Cora
Cordelia
Cynthia
Dahlia
Daisy
Dana
Daphne
Daria
Deborah
Delia
Delphine
Denise
Dinah
Dominique
Donna
Dora
Doris
Dorothy
Drew
Edith
Eileen
Elaine
Eleanor
Elena
Eliane
Elisa
Elise
Ella
Ellen
Elsa
Ember
Emilia
Emily
Emma
Erin
Esther
Etal
Eugenia
Eva
Evelyn
Evie
Fatima
Faye
Fiona
Flora
Frances
Freya
Gail
Gemma
Georgina
Gina
Giselle
Gloria
Grace
Greta
Gwen
Gwendolyn
Hana
Hannah
Harriet
Harlow
Hazel
Heather
Hedy
Heidi
Helen
Helena
Heloise
Hermione
Hilda
Holly
Hope
Ida
Ignacia
Ilsa
Imogen
Ingrid
Irene
Iris
Isabel
Ivy
Ivy
Izzy
Jacinta
Jade
Jamie
Jane
Janet
Janice
Jasmine
Jenna
Jennifer
Jess
Jessica
Jill
Joan
Jocelyn
Jolene
Joni
Jordan
Josephine
Joy
Judith
Julia
June
Juno
Kara
Karen
Karin
Kate
Katherine
Kayleigh
Keira
Kelly
Kendra
Kerry
Kim
Kira
Kirsten
Kitty
Kristen
Kyla
Lacey
Lana
Lara
Laura
Lauren
Leah
Leigh
Lena
Leonie
Lesley
Lila
Lillian
Lily
Linda
Lise
Liv
Lois
Lola
Lorelei
Lorna
Lottie
Louise
Lucia
Lucille
Lucy
Luna
Lydia
Lynn
Mabel
Mackenzie
Madeline
Mae
Maggie
Maisie
Mallory
Mara
Marceline
Margaret
Margot
Maria
Marianne
Marina
Marion
Marjorie
Marlene
Martha
Mary
Matilda
Maud
Maureen
May
Mei
Melanie
Melissa
Meredith
Mia
Michelle
Mila
Mildred
Millie
Mina
Mira
Miriam
Molly
Mona
Mona
Monica
Morgan
Muriel
Myra
Nadia
Nancy
Naomi
Natalia
Natalie
Nell
Nena
Nia
Nichole
Nikita
Nina
Nora
Noreen
Norma
Octavia
Odette
Olga
Olivia
Olive
Opal
Ophelia
Oriana
Paige
Pamela
Patricia
Paula
Pauline
Pearl
Peggy
Penelope
Petra
Philipa
Phoebe
Phyllis
Polly
Poppy
Priya
Quinn
Rachel
Reagan
Rebecca
Regina
Renee
Rhoda
Rita
Roberta
Rosalind
Rosalyn
Rose
Rosemary
Roxanne
Ruby
Ruth
Rylee
Sadie
Sally
Samantha
Sandra
Sarah
Sasha
Savannah
Selma
Serena
Shannon
Sharon
Sheila
Shirley
Sienna
Silvia
Simone
Sofia
Sonia
Sophie
Stella
Sue
Susanna
Sybil
Sylvia
Tabitha
Tamara
Tamsin
Tanya
Tara
Teresa
Tess
Thelma
Theodora
Theresa
Tilda
Tiffany
Tina
Toni
Tracy
Trixie
Ursula
Valentina
Valerie
Vanessa
Vera
Verna
Veronica
Vicky
Viola
Violet
Virgie
Vita
Vivian
Wanda
Wendy
Whitney
Willa
Willow
Wilma
Winifred
Wynne
Xena
Ximena
Yasmin
Yolanda
Yvette
Yvonne
Zadie
Zelda
Zena
Zoe
Zora
+1 -1
View File
@@ -6,7 +6,7 @@ with memories voice. Voice examples are given for dialogue.
## Backstory ## Backstory
My name is $PC, I'm 26, and nothing about me feels particularly remarkable. My name is @PC, I'm 26, and nothing about me feels particularly remarkable.
Growing up in an orphanage doesn't give one a running start at life, but at Growing up in an orphanage doesn't give one a running start at life, but at
the very least I managed not to get hooked on numeth or camwhore for income. the very least I managed not to get hooked on numeth or camwhore for income.
I never had any fondness for commodified sex (and good luck finding it in I never had any fondness for commodified sex (and good luck finding it in
-1
View File
@@ -1,5 +1,4 @@
{ {
"date": "2069-11-18",
"entries": [ "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 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 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." },
+2 -1
View File
@@ -1,4 +1,5 @@
{ {
"records": false, "records": false,
"vars": { "PC": "Rell" } "name": "La Caramba",
"pc": "Rell"
} }
+1 -1
View File
@@ -1,5 +1,5 @@
*Modesty, decency or respect are for those who can pay, the rest get **efficiency**. *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 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 logo of "BetterFuture, subsidiary of Tomoyama Inc.", engraved on the metal of
the feeding device, not convinced she is hungry enough yet to use it, when the the feeding device, not convinced she is hungry enough yet to use it, when the
massive THONK made her padded container jump a little. After long seconds of massive THONK made her padded container jump a little. After long seconds of
+36 -8
View File
@@ -5,8 +5,8 @@
// The bundle rides as GM messages (user role), one per file: backdrop, // The bundle rides as GM messages (user role), one per file: backdrop,
// character, ring-b, ring-a — identity first, then memory, ring A in // character, ring-b, ring-a — identity first, then memory, ring A in
// the recency slot; turn-0 opens a fresh run before the GM's first // the recency slot; turn-0 opens a fresh run before the GM's first
// line. $NAME tokens resolve from the run's settings.json "vars" and // line. Substitution resolves before sending — the model never sees a
// fail loudly when unresolved — the model never sees a raw $NAME. // raw sigil.
// //
// The tool list is the capability surface: roll and ask_gm always, // The tool list is the capability surface: roll and ask_gm always,
// records verbs only when the run's settings allow. // records verbs only when the run's settings allow.
@@ -43,13 +43,33 @@ export function readSettings(runId) {
} }
} }
// Substitution has two classes. @ sigils are identity — @PC (the
// character's name, settings "pc") and @Package (the display name,
// settings "name") — first-class, never user-fillable; these two are
// ours, and an unresolved one fails loudly. Any other @-word is the
// author's own text — @ syntax is not owned here, users may find
// other uses for it — and passes through untouched. $TOKENS are
// template vars, declared by the prompts themselves: any $TOKEN found
// in a prompt surfaces as an input in setup, and the run's settings
// "vars" holds the answers (a package may ship defaults); an
// unresolved $TOKEN fails loudly — the model never sees a raw var.
function expandVars(runId, s) { function expandVars(runId, s) {
const vars = readSettings(runId).vars ?? {}; const settings = readSettings(runId);
let out = String(s ?? ''); let out = String(s ?? '');
for (const [k, v] of Object.entries(vars)) out = out.replaceAll(`$${k}`, String(v)); const sigils = { PC: settings.pc, Package: settings.name };
out = out.replace(/@(PC|Package)\b/g, (full, name) => {
const v = sigils[name];
if (v == null || !String(v).trim()) {
const err = new Error(`unresolved @${name} — it must be set in the run's settings.json`);
err.status = 500;
throw err;
}
return String(v);
});
for (const [k, v] of Object.entries(settings.vars ?? {})) out = out.replaceAll(`$${k}`, String(v));
const unresolved = [...new Set([...out.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)].map((m) => `$${m[1]}`))]; const unresolved = [...new Set([...out.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)].map((m) => `$${m[1]}`))];
if (unresolved.length) { if (unresolved.length) {
const err = new Error(`unresolved token(s): ${unresolved.join(', ')} — declare them in the run's settings.json "vars"`); const err = new Error(`unresolved token(s): ${unresolved.join(', ')} — fill them in setup; they save to the run's settings.json "vars"`);
err.status = 500; err.status = 500;
throw err; throw err;
} }
@@ -57,6 +77,14 @@ function expandVars(runId, s) {
} }
export { expandVars }; export { expandVars };
// "La Caramba / Rell" — the run's display name; the anonymous id
// never surfaces as a name
export function runDisplay(runId) {
const s = readSettings(runId);
const pkg = runMeta(runId)?.package ?? '?';
return s.pc ? `${s.name ?? pkg} / ${s.pc}` : (s.name ?? pkg);
}
const read = (p) => { const read = (p) => {
if (!fs.existsSync(p)) { if (!fs.existsSync(p)) {
const err = new Error(`missing bundle file: ${path.relative(ROOT, p)}`); const err = new Error(`missing bundle file: ${path.relative(ROOT, p)}`);
@@ -74,8 +102,9 @@ export function assembleSystem(runId) {
return expandVars(runId, [system, invariants, handbook].join('\n\n')); return expandVars(runId, [system, invariants, handbook].join('\n\n'));
} }
// the bundle: GM messages, one per file. turn-0 only on a fresh run. // the bundle: GM messages, one per file. turn-0 never rides it — the
export function assembleBundle(runId, fresh) { // opening beat is a GM turn (sent on start), not context.
export function assembleBundle(runId) {
const d = runDir(runId); const d = runDir(runId);
const files = [ const files = [
{ role: 'user', path: path.join(d, 'backdrop.md') }, { role: 'user', path: path.join(d, 'backdrop.md') },
@@ -83,7 +112,6 @@ export function assembleBundle(runId, fresh) {
{ role: 'user', path: path.join(d, 'canon', 'ring-b.md') }, { role: 'user', path: path.join(d, 'canon', 'ring-b.md') },
{ role: 'user', path: path.join(d, 'canon', 'ring-a.md') }, { role: 'user', path: path.join(d, 'canon', 'ring-a.md') },
]; ];
if (fresh) files.push({ role: 'user', path: path.join(d, 'turn-0.md') });
return files.map((f) => ({ role: f.role, content: expandVars(runId, read(f.path)) })); return files.map((f) => ({ role: f.role, content: expandVars(runId, read(f.path)) }));
} }
+4 -6
View File
@@ -30,10 +30,7 @@ const readRun = (runId, f) => fs.readFileSync(path.join(runDir(runId), f), 'utf8
export function renderTranscript(lines) { export function renderTranscript(lines) {
const L = []; const L = [];
for (const e of lines) { for (const e of lines) {
if (e.t === 'bundle') { if (e.t === 'bundle') continue; // context, not exchange — provided as separate inputs
if (e.part === 'turn-0') L.push('[GM: opening beat]', e.m.content, '');
continue;
}
if (e.t === 'msg') { if (e.t === 'msg') {
if (e.m.role === 'user') { if (e.m.role === 'user') {
L.push('[GM]', e.m.content, ''); L.push('[GM]', e.m.content, '');
@@ -70,7 +67,7 @@ export function buildMessages(runId, lines, stamp) {
? 'available — this character keeps files; the archive op is valid' ? 'available — this character keeps files; the archive op is valid'
: 'none — this character keeps no files; the archive op is invalid'}. The ended session is ${stamp}.`; : 'none — this character keeps no files; the archive op is invalid'}. The ended session is ${stamp}.`;
return [ return [
{ role: 'system', content: expandVars(runId, readRun(runId, 'housekeeper.md')) }, { role: 'system', content: expandVars(runId, fs.readFileSync(path.join(ROOT, 'housekeeper.md'), 'utf8').trim()) }, // substrate-internal, repo-fed
{ role: 'user', content: runState }, { role: 'user', content: runState },
{ role: 'user', content: expandVars(runId, readRun(runId, 'character.md')) }, { role: 'user', content: expandVars(runId, readRun(runId, 'character.md')) },
{ role: 'user', content: expandVars(runId, readRun(runId, 'backdrop.md')) }, { role: 'user', content: expandVars(runId, readRun(runId, 'backdrop.md')) },
@@ -145,6 +142,7 @@ async function callHousekeeper(ctx, runId, messages) {
const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {}); const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {});
return data.choices[0].message.content ?? ''; return data.choices[0].message.content ?? '';
} }
export { callHousekeeper };
// apply -> mark housekept -> autorestart. Shared by the chain and the // apply -> mark housekept -> autorestart. Shared by the chain and the
// manual apply endpoint (hand-edited manifests). // manual apply endpoint (hand-edited manifests).
@@ -186,7 +184,6 @@ export function latestLog(runId) {
function mockManifest(stamp) { function mockManifest(stamp) {
return JSON.stringify({ return JSON.stringify({
window: stamp.toLowerCase(), window: stamp.toLowerCase(),
date: new Date().toISOString().slice(0, 10),
summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.', summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.',
touch: [{ id: 'e1', reason: 'the cuffs shaped every move she made' }], touch: [{ id: 'e1', reason: 'the cuffs shaped every move she made' }],
insert: [{ insert: [{
@@ -196,3 +193,4 @@ function mockManifest(stamp) {
}], }],
}); });
} }
export { mockManifest };
+23 -1
View File
@@ -7,8 +7,10 @@
// before every GM turn and rides it as a <status> block; the player's // before every GM turn and rides it as a <status> block; the player's
// <lost>/<gained> deltas apply after its final message, and any // <lost>/<gained> deltas apply after its final message, and any
// conflicts ride the next GM turn as a <conflict> block. // conflicts ride the next GM turn as a <conflict> block.
import fs from 'node:fs';
import path from 'node:path';
import { clerkJson } from './clerk.mjs'; import { clerkJson } from './clerk.mjs';
import { toolList, runTool, readSettings } from './bundle.mjs'; import { toolList, runTool, readSettings, runDir, expandVars } from './bundle.mjs';
import { renderView } from './session.mjs'; import { renderView } from './session.mjs';
export class HttpError extends Error { export class HttpError extends Error {
@@ -38,6 +40,26 @@ export async function gmTurn(ctx, runId, line) {
return runLoop(ctx, runId); return runLoop(ctx, runId);
} }
// the opening beat: turn-0 sent as the first GM turn, separate from
// the bundle (start = open window, then this). Its trailing <status>
// block was ingested as her opening paper at window-open — stripped
// here, since the normal ride carries the current paper on every GM
// turn, the beat included.
export async function turn0(ctx, runId) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
if (!s.fresh) throw new HttpError(409, 'turn-0 opens a fresh run only');
if (s.lines.some((e) => e.t === 'msg' && e.m.role === 'user')) {
throw new HttpError(409, 'a GM line already exists — the opening beat was sent, or the GM spoke first');
}
const file = path.join(runDir(runId), 'turn-0.md');
if (!fs.existsSync(file)) throw new HttpError(404, 'this run has no turn-0.md — narrate the opening yourself (POST /turn)');
let text = expandVars(runId, fs.readFileSync(file, 'utf8')); // $NAME tokens resolve like every bundle file
const sm = text.match(/<status>[\s\S]*?<\/status>/);
if (sm) text = text.replace(sm[0], '');
return gmTurn(ctx, runId, text.trim());
}
export async function answerAsk(ctx, runId, answer) { export async function answerAsk(ctx, runId, answer) {
const s = needSession(ctx, runId); const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question'); if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
+216 -13
View File
@@ -1,10 +1,9 @@
// server/main.mjs — entry + REST spine. // server/main.mjs — entry + REST spine.
// //
// Loopback, single-human, synchronous JSON. The SPA (later) and curl // Loopback, single-human, synchronous JSON. The SPA and curl are both
// are both just clients. Boot-rebuild: every run whose latest session // just clients. Boot-rebuild: every run whose latest session was not
// was not housekept gets its open window back from the jsonl — the log // housekept gets its open window back from the jsonl — the log is the
// is the truth, the context is a view. Housekeeping endpoints answer // truth, the context is a view.
// 501 until phase 3 lands the job.
// //
// usage: node server/main.mjs [--mock] // usage: node server/main.mjs [--mock]
import fs from 'node:fs'; import fs from 'node:fs';
@@ -16,7 +15,7 @@ import { clerkRaw, clerkRawJson, clerkJson } from './clerk.mjs';
import * as bundle from './bundle.mjs'; import * as bundle from './bundle.mjs';
import * as session from './session.mjs'; import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs'; import * as housekeeping from './housekeeping.mjs';
import { gmTurn, answerAsk, HttpError } from './loop.mjs'; import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock'); const MOCK = process.argv.includes('--mock');
@@ -103,7 +102,12 @@ function serveStatic(pathname, res) {
if (!rel) rel = 'index.html'; if (!rel) rel = 'index.html';
const file = path.resolve(WEB_DIR, rel); const file = path.resolve(WEB_DIR, rel);
if (!file.startsWith(WEB_DIR + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { if (!file.startsWith(WEB_DIR + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
send(res, 404, { error: `no such file: ${rel}` }); // SPA fallback: client-side routes are extensionless paths —
// serve the shell; anything that looks like a file stays a 404
if (path.extname(rel)) { send(res, 404, { error: `no such file: ${rel}` }); return; }
const shell = fs.readFileSync(path.join(WEB_DIR, 'index.html'));
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': shell.length });
res.end(shell);
return; return;
} }
const data = fs.readFileSync(file); const data = fs.readFileSync(file);
@@ -113,21 +117,63 @@ function serveStatic(pathname, res) {
// --- routes ------------------------------------------------------------------- // --- routes -------------------------------------------------------------------
route('GET', '/api', async () => ({ service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size })); route('GET', '/api', async () => ({
service: 'rp-test', mock: MOCK, openWindows: ctx.sessions.size,
// the live window inventory — debugging state divergence at a glance
windows: [...ctx.sessions.entries()].map(([id, s]) => ({ run: id, stamp: s.stamp, fresh: s.fresh, pendingAsk: !!s.pendingAsk })),
}));
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models())); route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
route('GET', '/api/packages', async () => clerkRawJson('packages')); route('GET', '/api/packages', async () => clerkRawJson('packages'));
route('GET', '/api/runs', async () => clerkRawJson('runs'));
// the repo-fed prompts, read-only: per-project opening + guards and
// substrate invariants — never copied into a run, so the editor shows
// them as context, not as something to edit
route('GET', '/api/prompts', async () => ({
system: fs.readFileSync(path.join(ROOT, 'system.md'), 'utf8').trim(),
invariants: fs.readFileSync(path.join(ROOT, 'invariants.md'), 'utf8').trim(),
}));
// the clerk's list, enriched with what the server already knows: the
// open window, the pending ask, and the housekeeping bookkeeping. A
// run with no sessions is a draft — created, never started.
route('GET', '/api/runs', async () => {
const runs = clerkRawJson('runs');
for (const r of runs) {
const s = ctx.sessions.get(r.id);
r.open = !!s;
r.window = s?.stamp ?? null;
r.fresh = s?.fresh ?? false;
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
r.lastHousekept = session.lastHousekept(r.id);
}
return runs;
});
// create: the pc's name is required (unique per package); the
// package display name defaults to the package's own. The id is
// anonymous, generated by the clerk.
route('POST', '/api/runs', async ({ body }) => { route('POST', '/api/runs', async ({ body }) => {
const name = String(body.name ?? '').trim();
const pkg = String(body.package ?? '').trim(); const pkg = String(body.package ?? '').trim();
if (!/^[a-z0-9-]+$/.test(name)) throw new HttpError(400, 'name must be a slug (lowercase letters, digits, dashes)'); const pc = String(body.pc ?? '').trim();
if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages'); if (!/^[a-z0-9-]+$/.test(pkg)) throw new HttpError(400, 'package must be a slug — see GET /api/packages');
const r = clerkRaw('create', pkg, name, ...(body.model ? [String(body.model)] : [])); if (!pc) throw new HttpError(400, 'pc is required — the main character\'s name, distinct per package');
const name = body.name === undefined ? undefined : String(body.name);
const r = clerkRaw('--json', 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed'); if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
return { run: bundle.runMeta(name), dir: `runs/${name}` }; const run = JSON.parse(r.out);
return { run, dir: `runs/${run.id}` };
});
// a name to play as: rolled from the dictionary, unused by any run
route('GET', '/api/names', async () => {
const all = fs.readFileSync(path.join(ROOT, 'names-female.txt'), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean);
const used = new Set(clerkRawJson('runs').flatMap((r) => (r.pc ? [String(r.pc).toLowerCase()] : [])));
const free = all.filter((n) => !used.has(n.toLowerCase()));
const pool = free.length ? free : all; // a fully-used dictionary still suggests
return { name: pool[Math.floor(Math.random() * pool.length)] };
}); });
route('GET', '/api/runs/:id', async ({ params }) => { route('GET', '/api/runs/:id', async ({ params }) => {
@@ -138,7 +184,10 @@ route('GET', '/api/runs/:id', async ({ params }) => {
const meta = bundle.runMeta(id); const meta = bundle.runMeta(id);
return { return {
run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null }, run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null },
display: bundle.runDisplay(id),
open: !!s, open: !!s,
draft: session.latestSession(id) === null,
lastSession: session.latestSession(id),
window: s?.stamp ?? null, window: s?.stamp ?? null,
fresh: s?.fresh ?? false, fresh: s?.fresh ?? false,
paper: st.paper, paper: st.paper,
@@ -155,6 +204,96 @@ route('GET', '/api/runs/:id', async ({ params }) => {
}; };
}); });
// --- run files: the editor's surface ------------------------------------------
//
// A fixed whitelist, not a path API: state dirs are the clerk's
// alone. Craft files are writable; housekeeper.md is substrate-
// internal (repo-fed at wrap, never copied, not exposed here) and
// gm.md lives only in the notepad endpoints (the play-view pad);
// config is read-only (vars and lineage are easy to break blind).
// JSON writes are validated before landing.
const RUN_FILES = {
'backdrop.md': 'rw',
'character.md': 'rw',
'turn-0.md': 'rw',
'seed.json': 'rw',
'handbook.md': 'rw',
'settings.json': 'ro',
'run.json': 'ro',
};
route('GET', '/api/runs/:id/files', async ({ params }) => {
const dir = bundle.requireRun(params.id);
const files = {};
for (const [f, mode] of Object.entries(RUN_FILES)) {
const p = path.join(dir, f);
files[f] = fs.existsSync(p)
? { mode, exists: true, content: fs.readFileSync(p, 'utf8') }
: { mode, exists: false };
}
return { files };
});
route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
const dir = bundle.requireRun(params.id);
const f = params.path;
const mode = RUN_FILES[f];
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
if (mode !== 'rw') throw new HttpError(403, `${f} is read-only`);
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
if (f.endsWith('.json')) {
try { JSON.parse(body.content); } catch { throw new HttpError(400, `${f} rejected: not valid JSON`); }
}
fs.writeFileSync(path.join(dir, f), body.content);
return { ok: true, file: f, bytes: Buffer.byteLength(body.content) };
});
// prompt vars: the inputs the prompts themselves declare ($TOKENS
// found in any prompt file). Values live in the run's settings vars.
route('POST', '/api/runs/:id/vars', async ({ params, body }) => {
const dir = bundle.requireRun(params.id);
const vars = body.vars;
if (typeof vars !== 'object' || vars === null || Array.isArray(vars)) throw new HttpError(400, 'vars (an object of token -> value) is required');
for (const [k, v] of Object.entries(vars)) {
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(k)) throw new HttpError(400, `bad var name: ${JSON.stringify(k)}`);
if (typeof v !== 'string') throw new HttpError(400, `var ${k} must be a string`);
}
const settings = bundle.readSettings(params.id);
settings.vars = { ...(settings.vars ?? {}), ...vars };
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
return { ok: true, vars: settings.vars };
});
// the GM's notepad: the run's gm.md — always editable in the SPA,
// never in any bundle, never sent to any model (no assembly path
// reads it). Seeded from the package at creation, the GM's to keep.
route('GET', '/api/runs/:id/notes', async ({ params }) => {
const dir = bundle.requireRun(params.id);
const file = path.join(dir, 'gm.md');
return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' };
});
route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
const dir = bundle.requireRun(params.id);
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
return { ok: true };
});
// delete a DRAFT: a run with no sessions holds nothing but its copy,
// so the directory is the whole run and removal is complete. A played
// run is a story — deleting one is a deliberate act that stays by
// hand (Remove-Item runs/<id>), not a button.
route('DELETE', '/api/runs/:id', async ({ params }) => {
const dir = bundle.requireRun(params.id);
if (session.latestSession(params.id) !== null) {
throw new HttpError(409, `this run has been played — its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${path.join('runs', params.id)}`);
}
fs.rmSync(dir, { recursive: true, force: true });
return { ok: true, deleted: params.id };
});
route('POST', '/api/runs/:id/windows', async ({ params, body }) => { route('POST', '/api/runs/:id/windows', async ({ params, body }) => {
const id = params.id; const id = params.id;
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`); if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
@@ -185,6 +324,10 @@ route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
return { ok: true, ...(await gmTurn(ctx, params.id, line)) }; return { ok: true, ...(await gmTurn(ctx, params.id, line)) };
}); });
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
route('POST', '/api/runs/:id/turn0', async ({ params }) => ({ ok: true, ...(await turn0(ctx, params.id)) }));
route('POST', '/api/runs/:id/ask', async ({ params, body }) => { route('POST', '/api/runs/:id/ask', async ({ params, body }) => {
const answer = String(body.answer ?? '').trim(); const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required'); if (!answer) throw new HttpError(400, 'answer is required');
@@ -197,12 +340,64 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null }; return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null };
}); });
// the GM's out-of-band paper override: whole-paper replace via the
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// item is a 400, not a silent corruption later.
route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
const id = params.id;
bundle.requireRun(id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
for (const it of items) {
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
}
const paper = clerkJson(id, '--gm', 'paper-set', ...items);
return { ok: true, paper };
});
route('POST', '/api/runs/:id/housekeeping', async ({ params }) => { route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
// ends the window and kicks the async chain; poll GET for the outcome // ends the window and kicks the async chain; poll GET for the outcome
const job = housekeeping.trigger(ctx, params.id); const job = housekeeping.trigger(ctx, params.id);
return { state: job.state, session: job.session }; return { state: job.state, session: job.session };
}); });
// dry-run the housekeeper over a session log: the same transcript
// assembly the real wrap uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no window ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
const id = params.id;
bundle.requireRun(id);
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
let lines;
try {
lines = session.loadSession(id, stamp).lines;
} catch {
throw new HttpError(404, `no such session: ${stamp}`);
}
if (!lines.some((e) => e.t === 'msg')) throw new HttpError(409, 'that session has no exchange to review');
const dir = path.join(bundle.runDir(id), 'manifests');
fs.mkdirSync(dir, { recursive: true });
const text = ctx.mock
? housekeeping.mockManifest(stamp)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp));
let mf;
try {
mf = housekeeping.parseManifest(text);
} catch (e) {
const raw = path.join(dir, `${stamp}.replay.raw.md`);
fs.writeFileSync(raw, String(text));
return { ok: true, parsed: false, session: stamp, file: `manifests/${stamp}.replay.raw.md`, reason: e.message };
}
const file = path.join(dir, `${stamp}.replay.json`);
fs.writeFileSync(file, JSON.stringify(mf, null, 2) + '\n');
return { ok: true, parsed: true, session: stamp, file: `manifests/${stamp}.replay.json`, manifest: mf };
});
route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id)); route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id));
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id)); route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
@@ -233,8 +428,16 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
// --- dispatch ------------------------------------------------------------------- // --- dispatch -------------------------------------------------------------------
const server = http.createServer(async (req, res) => { const server = http.createServer(async (req, res) => {
const started = Date.now();
try { try {
const url = new URL(req.url, 'http://localhost'); const url = new URL(req.url, 'http://localhost');
// the request log: one line per API call — reconstruct any session
// from the console output after the fact
res.on('finish', () => {
if (url.pathname.startsWith('/api')) {
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
}
});
if (!url.pathname.startsWith('/api')) { if (!url.pathname.startsWith('/api')) {
if (req.method !== 'GET') throw new HttpError(405, 'static files are GET-only'); if (req.method !== 'GET') throw new HttpError(405, 'static files are GET-only');
serveStatic(url.pathname, res); serveStatic(url.pathname, res);
+21 -7
View File
@@ -101,8 +101,10 @@ export function openWindow(runId, override = false) {
} }
const system = { role: 'system', content: assembleSystem(runId) }; const system = { role: 'system', content: assembleSystem(runId) };
const bundle = assembleBundle(runId, fresh); const bundle = assembleBundle(runId);
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a', ...(fresh ? ['turn-0'] : [])]; // turn-0 is not a bundle part: the opening beat is sent as the
// first GM turn (POST /api/runs/<id>/turn0) when play starts
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
const s = makeSession(runId, stamp()); const s = makeSession(runId, stamp());
s.fresh = fresh; s.fresh = fresh;
fs.mkdirSync(sessionsDir(runId), { recursive: true }); fs.mkdirSync(sessionsDir(runId), { recursive: true });
@@ -131,6 +133,10 @@ export function loadSession(runId, st) {
} }
} }
derive(s); derive(s);
// fresh survives a restart: this window is the run's first iff no
// earlier session log exists (derive() can't know — it sees one log)
const files = fs.readdirSync(sessionsDir(runId)).filter((f) => f.endsWith('.jsonl')).sort();
s.fresh = files.length === 1 && files[0] === `${st}.jsonl`;
return s; return s;
} }
@@ -164,10 +170,14 @@ const STRIP_BLOCKS = /\n?<(status|conflict)>[\s\S]*?<\/\1>\n?/g;
export function renderView(s, keepToolResults = 4) { export function renderView(s, keepToolResults = 4) {
const toolIdx = []; const toolIdx = [];
s.lines.forEach((e, i) => { if (e.t === 'tool') toolIdx.push(i); }); let lastGmIdx = -1;
s.lines.forEach((e, i) => {
if (e.t === 'tool') toolIdx.push(i);
if (e.t === 'msg' && e.m.role === 'user') lastGmIdx = i;
});
const keep = new Set(toolIdx.slice(-keepToolResults)); const keep = new Set(toolIdx.slice(-keepToolResults));
const msgs = []; const msgs = [];
for (const e of s.lines) { for (const [i, e] of s.lines.entries()) {
if (e.t === 'bundle') { if (e.t === 'bundle') {
msgs.push({ role: e.m.role, content: e.m.content }); msgs.push({ role: e.m.role, content: e.m.content });
} else if (e.t === 'msg') { } else if (e.t === 'msg') {
@@ -176,13 +186,17 @@ export function renderView(s, keepToolResults = 4) {
const m = { role: 'assistant', content: e.m.content ?? null }; const m = { role: 'assistant', content: e.m.content ?? null };
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls; if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
msgs.push(m); msgs.push(m);
} else if (i === lastGmIdx) {
// the newest GM turn keeps its blocks as-sent: the current
// paper rides it, and a pending conflict rides it — the
// model must see both
msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else { } else {
// GM-side: old status/conflict blocks elide — the current // older GM turns: status/conflict blocks elide
// paper rides the newest GM turn
msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() }); msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() });
} }
} else if (e.t === 'tool') { } else if (e.t === 'tool') {
if (e.ask || keep.has(s.lines.indexOf(e))) { if (e.ask || keep.has(i)) {
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: e.m.content }); msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: e.m.content });
} else { } else {
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: '[elided: earlier tool result]' }); msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: '[elided: earlier tool result]' });
+92 -42
View File
@@ -9,9 +9,11 @@
// commands: // commands:
// packages list packages (presets) and their flags // packages list packages (presets) and their flags
// runs list runs (instances) and their fill levels // runs list runs (instances) and their fill levels
// create <package> <run-id> create a run: copy the package wholesale // create <package> <pc-name> create a run: copy the package wholesale
// (shared prompts included — battery // (shared prompts included — battery
// included), init the db, render the views. // included), give it an anonymous id and
// the pc's name (distinct per package),
// init the db, render the views.
// From then on the run dir is the only // From then on the run dir is the only
// truth; the package is never read again. // truth; the package is never read again.
// init create the run's database and stubs // init create the run's database and stubs
@@ -35,6 +37,7 @@
// turn; exact match, non-blocking; JSON result // turn; exact match, non-blocking; JSON result
// (lost / gained / conflicts / paper) // (lost / gained / conflicts / paper)
// paper-set "descr" ... GM override: replace the whole paper // paper-set "descr" ... GM override: replace the whole paper
// (no descrs = clear it)
// paper-ingest <file> read a file's <status> block into the paper // paper-ingest <file> read a file's <status> block into the paper
// (turn-0 at new-game) // (turn-0 at new-game)
// pick "a" "b" "c" ... dice for prose — uniform random choice // pick "a" "b" "c" ... dice for prose — uniform random choice
@@ -46,6 +49,7 @@
// status counts, caps, the paper, what's sinking // status counts, caps, the paper, what's sinking
import { DatabaseSync } from 'node:sqlite'; import { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
@@ -86,7 +90,7 @@ const [cmd, ...args] = argv;
const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']); const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']);
const RUN = NO_RUN_NEEDED.has(cmd) ? null : runOverride; const RUN = NO_RUN_NEEDED.has(cmd) ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd) && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) { 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>'); fail('no run specified — use --run <id> (see: runs); runs are created with: create <package> <pc-name>');
} }
// per-run paths: set once from --run, and re-pointed by create (which // per-run paths: set once from --run, and re-pointed by create (which
@@ -174,7 +178,7 @@ function renderRing(db, ring) {
]; ];
if (rows.length === 0) lines.push('(empty — nothing here yet)'); if (rows.length === 0) lines.push('(empty — nothing here yet)');
for (const r of rows) { for (const r of rows) {
lines.push(`- [e${r.id}] [${r.last_touched}] [${r.type}] **${r.label}**${r.detail ? ` — ${r.detail}` : '.'}`); lines.push(`- [e${r.id}] [${r.type}] **${r.label}**${r.detail ? ` — ${r.detail}` : '.'}`);
} }
lines.push(''); lines.push('');
const file = path.join(CANON_DIR, `ring-${ring}.md`); const file = path.join(CANON_DIR, `ring-${ring}.md`);
@@ -238,10 +242,14 @@ function dumpDb(db) {
return file; return file;
} }
function insertEntry(db, { ring, type, label, detail, date, win, reason }) { // stamps are mechanical (real, internal, never rendered): they drive
// the LRU — overflow, view order, "what's sinking". Story time lives
// in the prose of the entries, never in a column.
function insertEntry(db, { ring, type, label, detail, win, reason }) {
const now = today();
const res = db.prepare( const res = db.prepare(
'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)' 'INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)'
).run(ring, type, norm(label), norm(detail), date, date); ).run(ring, type, norm(label), norm(detail), now, now);
const id = Number(res.lastInsertRowid); const id = Number(res.lastInsertRowid);
journal(db, win, 'insert', `e${id}`, reason); journal(db, win, 'insert', `e${id}`, reason);
return id; return id;
@@ -315,7 +323,6 @@ function cmdSeed(force, seedPathArg) {
} }
const errors = []; 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 entries = sf.entries ?? [];
const records = sf.records ?? []; const records = sf.records ?? [];
if (!Array.isArray(entries)) { errors.push('entries must be an array'); } if (!Array.isArray(entries)) { errors.push('entries must be an array'); }
@@ -344,14 +351,15 @@ function cmdSeed(force, seedPathArg) {
db.exec('BEGIN'); db.exec('BEGIN');
try { try {
const now = today();
for (const e of entries) { for (const e of entries) {
const res = db.prepare('INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)') const res = db.prepare('INSERT INTO entries (ring, type, label, detail, created, last_touched) VALUES (?, ?, ?, ?, ?, ?)')
.run(e.ring, e.type, norm(e.label), norm(e.detail ?? ''), sf.date, sf.date); .run(e.ring, e.type, norm(e.label), norm(e.detail ?? ''), now, now);
journal(db, 'seed', 'insert', `e${Number(res.lastInsertRowid)}`, 'seeded'); journal(db, 'seed', 'insert', `e${Number(res.lastInsertRowid)}`, 'seeded');
} }
for (const r of records) { for (const r of records) {
const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)') const res = db.prepare('INSERT INTO records (kind, label, detail, created) VALUES (?, ?, ?, ?)')
.run(norm(r.kind), norm(r.label), norm(r.detail ?? ''), sf.date); .run(norm(r.kind), norm(r.label), norm(r.detail ?? ''), now);
journal(db, 'seed', 'record', `r${Number(res.lastInsertRowid)}`, 'seeded'); journal(db, 'seed', 'record', `r${Number(res.lastInsertRowid)}`, 'seeded');
} }
db.exec('COMMIT'); db.exec('COMMIT');
@@ -360,7 +368,7 @@ function cmdSeed(force, seedPathArg) {
fail(`seed failed, rolled back: ${e.message}`); fail(`seed failed, rolled back: ${e.message}`);
} }
console.log(`seeded [${RUN}]: ${entries.length} entries, ${records.length} records (as of ${sf.date})`); console.log(`seeded [${RUN}]: ${entries.length} entries, ${records.length} records`);
renderAll(db); renderAll(db);
dumpDb(db); dumpDb(db);
} }
@@ -376,14 +384,10 @@ function cmdApply(manifestPath) {
const { errors, need, asArray, ref } = makeValidator(db); const { errors, need, asArray, ref } = makeValidator(db);
need(mf.window, 'window'); need(mf.window, 'window');
need(mf.date, 'date');
need(mf.summary, 'summary'); need(mf.summary, 'summary');
if (typeof mf.window === 'string' && !/^[a-z0-9-]+$/i.test(mf.window)) { if (typeof mf.window === 'string' && !/^[a-z0-9-]+$/i.test(mf.window)) {
errors.push('window must be a short slug (letters, digits, dashes)'); errors.push('window must be a short slug (letters, digits, dashes)');
} }
if (typeof mf.date === 'string' && !/^\d{4}-\d{2}-\d{2}$/.test(mf.date)) {
errors.push('date must be YYYY-MM-DD');
}
const logFile = mf.window ? path.join(LOG_DIR, `${mf.window}.md`) : null; const logFile = mf.window ? path.join(LOG_DIR, `${mf.window}.md`) : null;
if (logFile && fs.existsSync(logFile)) { if (logFile && fs.existsSync(logFile)) {
errors.push(`${rel(logFile)} already exists — delete it first if this is a re-run`); errors.push(`${rel(logFile)} already exists — delete it first if this is a re-run`);
@@ -441,11 +445,11 @@ function cmdApply(manifestPath) {
for (const e of ins) { for (const e of ins) {
const id = insertEntry(db, { const id = insertEntry(db, {
ring: e.ring, type: e.type, label: e.label, detail: e.detail ?? '', ring: e.ring, type: e.type, label: e.label, detail: e.detail ?? '',
date: mf.date, win: mf.window, reason: e.reason, win: mf.window, reason: e.reason,
}); });
applied.insert.push({ id, ...e }); applied.insert.push({ id, ...e });
} }
const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(mf.date, id); const touchDate = (id) => db.prepare('UPDATE entries SET last_touched = ? WHERE id = ?').run(today(), id);
const fetch = (id) => db.prepare('SELECT * FROM entries WHERE id = ?').get(id); const fetch = (id) => db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
for (const e of touch) { for (const e of touch) {
const id = parseId(e.id); const id = parseId(e.id);
@@ -455,19 +459,19 @@ function cmdApply(manifestPath) {
} }
for (const e of promote) { for (const e of promote) {
const id = parseId(e.id); const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(mf.date, id); db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.window, 'promote', `e${id}`, e.reason); journal(db, mf.window, 'promote', `e${id}`, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason }); applied.promote.push({ row: fetch(id), reason: e.reason });
} }
for (const e of demote) { for (const e of demote) {
const id = parseId(e.id); const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(mf.date, id); db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.window, 'demote', `e${id}`, e.reason); journal(db, mf.window, 'demote', `e${id}`, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason }); applied.demote.push({ row: fetch(id), reason: e.reason });
} }
for (const e of reword) { for (const e of reword) {
const id = parseId(e.id); const id = parseId(e.id);
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), mf.date, id); db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), today(), id);
journal(db, mf.window, 'reword', `e${id}`, e.reason); journal(db, mf.window, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason }); applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
} }
@@ -559,9 +563,11 @@ function cmdInit() {
const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md']; const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md'];
// battery included, copied per run and then the run's to edit: the craft // battery included, copied per run and then the run's to edit: the craft
// tier and the housekeeping prompt. system.md and invariants.md are // tier. housekeeper.md is substrate-internal like invariants.md —
// repo-fed at assembly (opening+guards, substrate facts) — never copied // repo-fed at wrap time, never copied, never user-exposed; system.md
const SHARED_PROMPTS = ['handbook.md', 'housekeeper.md']; // and invariants.md are likewise repo-fed at assembly (opening+guards,
// substrate facts)
const SHARED_PROMPTS = ['handbook.md'];
function cmdPackages() { function cmdPackages() {
if (!fs.existsSync(PACKAGES_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no packages)'); return; } if (!fs.existsSync(PACKAGES_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no packages)'); return; }
@@ -570,29 +576,64 @@ function cmdPackages() {
if (!d.isDirectory()) continue; if (!d.isDirectory()) continue;
const p = path.join(PACKAGES_DIR, d.name); const p = path.join(PACKAGES_DIR, d.name);
const has = (f) => fs.existsSync(path.join(p, f)); const has = (f) => fs.existsSync(path.join(p, f));
let records = false; let settings = {};
try { records = JSON.parse(fs.readFileSync(path.join(p, 'settings.json'), 'utf8')).records === true; } catch {} try { settings = JSON.parse(fs.readFileSync(path.join(p, 'settings.json'), 'utf8')); } catch {}
list.push({ list.push({
name: d.name, records, name: d.name,
display: settings.name ?? d.name,
pc: settings.pc ?? null,
records: settings.records === true,
turn0: has('turn-0.md'), seed: has('seed.json'), turn0: has('turn-0.md'), seed: has('seed.json'),
complete: has('backdrop.md') && has('character.md'), complete: has('backdrop.md') && has('character.md'),
}); });
} }
if (AS_JSON) { console.log(JSON.stringify(list)); return; } if (AS_JSON) { console.log(JSON.stringify(list)); return; }
for (const x of list) { for (const x of list) {
console.log(`${x.name}: records ${x.records ? 'on' : 'off'} · turn-0 ${x.turn0 ? 'yes' : 'no'} · seed ${x.seed ? 'yes' : 'no'} · backdrop+card ${x.complete ? 'ok' : 'MISSING'}`); console.log(`${x.name}: ${x.display} — records ${x.records ? 'on' : 'off'} · turn-0 ${x.turn0 ? 'yes' : 'no'} · seed ${x.seed ? 'yes' : 'no'} · backdrop+card ${x.complete ? 'ok' : 'MISSING'}`);
} }
} }
function cmdCreate(pkgName, runId, model) { // run ids are anonymous: they carry no facts, so there is nothing to
if (!pkgName || !runId || !/^[a-z0-9-]+$/.test(runId)) { // rename and nothing for a name to collide with. The names that
fail('usage: create <package> <run-id> ["model"]'); // matter — the package display name and the pc's name — live in the
// run's settings copy and drive the display ("La Caramba / Rell").
const readRunSettings = (runDir) => {
try { return JSON.parse(fs.readFileSync(path.join(runDir, 'settings.json'), 'utf8')); } catch { return {}; }
};
const runDisplay = (pkg, settings) =>
settings.pc ? `${settings.name ?? pkg} / ${settings.pc}` : (settings.name ?? pkg);
function anonId() {
for (;;) {
const id = randomBytes(4).toString('hex'); // 8 hex chars
if (!fs.existsSync(path.join(RUNS_DIR, id))) return id;
}
}
function cmdCreate(pkgName, pc, displayName, model) {
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
fail('usage: create <package> <pc-name> ["package display name"] ["model"]');
} }
const pkgDir = path.join(PACKAGES_DIR, pkgName); const pkgDir = path.join(PACKAGES_DIR, pkgName);
if (!fs.existsSync(pkgDir)) fail(`no such package: ${pkgName} — see: packages`); if (!fs.existsSync(pkgDir)) fail(`no such package: ${pkgName} — see: packages`);
const runDir = path.join(RUNS_DIR, runId); pc = String(pc).trim();
if (fs.existsSync(runDir)) fail(`run '${runId}' already exists — a disposable run is deleted, not recreated (Remove-Item ${rel(runDir)})`); // different runs of the same package require different pc names
if (fs.existsSync(RUNS_DIR)) {
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
const rd = path.join(RUNS_DIR, d.name);
let meta = null;
try { meta = JSON.parse(fs.readFileSync(path.join(rd, 'run.json'), 'utf8')); } catch { continue; }
if (meta?.package !== pkgName) continue;
const st = readRunSettings(rd);
if (String(st.pc ?? '').toLowerCase() === pc.toLowerCase()) {
fail(`a run of '${pkgName}' named '${pc}' already exists: ${d.name}`);
}
}
}
const runId = anonId();
const runDir = path.join(RUNS_DIR, runId);
fs.mkdirSync(runDir, { recursive: true }); fs.mkdirSync(runDir, { recursive: true });
for (const f of PACKAGE_FILES) { for (const f of PACKAGE_FILES) {
const src = path.join(pkgDir, f); const src = path.join(pkgDir, f);
@@ -602,6 +643,12 @@ function cmdCreate(pkgName, runId, model) {
const src = path.join(ROOT, f); const src = path.join(ROOT, f);
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(runDir, f)); if (fs.existsSync(src)) fs.copyFileSync(src, path.join(runDir, f));
} }
// first-class identity lands in the settings copy: the pc name is
// this run's own; the display name defaults to the package's
const settings = readRunSettings(runDir);
settings.pc = pc;
settings.name = displayName?.trim() || settings.name || pkgName;
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
const meta = { package: pkgName, created: today() }; const meta = { package: pkgName, created: today() };
if (model) meta.model = model; if (model) meta.model = model;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n'); fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
@@ -612,14 +659,15 @@ function cmdCreate(pkgName, runId, model) {
setRunRoot(runDir); // views and dump land inside the new run setRunRoot(runDir); // views and dump land inside the new run
const db = new DatabaseSync(DB_PATH); const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8')); db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
console.log(`created run '${runId}' from package '${pkgName}': ${rel(runDir)}`); if (AS_JSON) { console.log(JSON.stringify({ id: runId, package: pkgName, name: settings.name, pc })); return; }
console.log(`created run '${runId}' — ${runDisplay(pkgName, settings)}: ${rel(runDir)}`);
console.log(` seed rides the copy (${fs.existsSync(path.join(runDir, 'seed.json')) ? 'present' : 'absent'}), editable until the first window-open applies it`); 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); renderAll(db);
dumpDb(db); dumpDb(db);
} }
function cmdRuns() { function cmdRuns() {
if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs — create one: create <package> <run-id>)'); return; } if (!fs.existsSync(RUNS_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no runs — create one: create <package> <pc-name>)'); return; }
const list = []; const list = [];
let found = 0; let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) { for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
@@ -634,19 +682,21 @@ function cmdRuns() {
pkg = meta.package ?? '?'; pkg = meta.package ?? '?';
model = meta.model ?? null; model = meta.model ?? null;
} catch {} } catch {}
const st = readRunSettings(runDir);
const base = { id: d.name, package: pkg, model, pc: st.pc ?? null, display: runDisplay(pkg, st) };
const dbPath = path.join(runDir, 'db', 'memory.db'); const dbPath = path.join(runDir, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { list.push({ id: d.name, package: pkg, model, initialized: false }); continue; } if (!fs.existsSync(dbPath)) { list.push({ ...base, initialized: false }); continue; }
const db = new DatabaseSync(dbPath); const db = new DatabaseSync(dbPath);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8')); db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n; const n = (ring) => db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
list.push({ id: d.name, package: pkg, model, initialized: true, fill: { a: n('a'), b: n('b'), cold: n('cold') } }); list.push({ ...base, initialized: true, fill: { a: n('a'), b: n('b'), cold: n('cold') } });
} }
if (AS_JSON) { console.log(JSON.stringify(list)); return; } if (AS_JSON) { console.log(JSON.stringify(list)); return; }
for (const x of list) { for (const x of list) {
if (!x.initialized) { console.log(`${x.id} [${x.package}]: (not initialized)`); continue; } if (!x.initialized) { console.log(`${x.id} [${x.package}]: ${x.display} (not initialized)`); continue; }
console.log(`${x.id} [${x.package}]: a ${x.fill.a}/${CAPS.a} · b ${x.fill.b}/${CAPS.b} · cold ${x.fill.cold}`); console.log(`${x.id} [${x.package}]: ${x.display} — a ${x.fill.a}/${CAPS.a} · b ${x.fill.b}/${CAPS.b} · cold ${x.fill.cold}`);
} }
if (!found) console.log('(no runs — create one: create <package> <run-id>)'); if (!found) console.log('(no runs — create one: create <package> <pc-name>)');
} }
function today() { return new Date().toISOString().slice(0, 10); } function today() { return new Date().toISOString().slice(0, 10); }
@@ -659,7 +709,7 @@ function gmOp(ring, type, label, detail) {
db.exec('BEGIN'); db.exec('BEGIN');
let id; let id;
try { try {
id = insertEntry(db, { ring, type, label, detail: detail ?? '', date: today(), win: 'gm', reason: 'GM edit' }); id = insertEntry(db, { ring, type, label, detail: detail ?? '', win: 'gm', reason: 'GM edit' });
db.exec('COMMIT'); db.exec('COMMIT');
} catch (e) { } catch (e) {
db.exec('ROLLBACK'); db.exec('ROLLBACK');
@@ -871,7 +921,7 @@ function cmdSearch(terms) {
const params = terms.map((t) => `%${t}%`); const params = terms.map((t) => `%${t}%`);
const rows = db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params); const rows = db.prepare(`SELECT * FROM records WHERE ${conds} ORDER BY id LIMIT 10`).all(...params);
if (!rows.length) { console.log('(no records match)'); return; } if (!rows.length) { console.log('(no records match)'); return; }
for (const r of rows) console.log(`[r${r.id}] [${r.kind}] **${r.label}**${r.detail ? ` — ${r.detail}` : ''} (${r.created})`); for (const r of rows) console.log(`[r${r.id}] [${r.kind}] **${r.label}**${r.detail ? ` — ${r.detail}` : ''}`);
const total = db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params).n; const total = db.prepare(`SELECT COUNT(*) AS n FROM records WHERE ${conds}`).get(...params).n;
if (total > rows.length) console.log(`…${total - rows.length} more omitted — narrow the query`); if (total > rows.length) console.log(`…${total - rows.length} more omitted — narrow the query`);
} }
@@ -940,7 +990,7 @@ function cmdStatus() {
switch (cmd) { switch (cmd) {
case 'packages': cmdPackages(); break; case 'packages': cmdPackages(); break;
case 'runs': cmdRuns(); break; case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2]); break; case 'create': cmdCreate(args[0], args[1], args[2], args[3]); break;
case 'seed': cmdSeed(FORCE, args[0]); break; case 'seed': cmdSeed(FORCE, args[0]); break;
case 'init': cmdInit(); break; case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break; case 'render': renderAll(openDb()); break;
@@ -953,7 +1003,7 @@ switch (cmd) {
case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break; case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break;
case 'paper': cmdPaper(); break; case 'paper': cmdPaper(); break;
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); 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-set': cmdPaperSet(args); break; // no args = clear the paper (a legitimate GM override)
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break; case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break;
case 'pick': cmdPick(args); break; case 'pick': cmdPick(args); break;
case 'search': cmdSearch(args); break; case 'search': cmdSearch(args); break;
+721 -164
View File
File diff suppressed because it is too large Load Diff
+83 -13
View File
@@ -8,48 +8,118 @@
</head> </head>
<body> <body>
<header> <header>
<select id="run-select" title="run"></select> <a id="home-link" href="/">rp-test</a>
<details id="new-run">
<summary>new run</summary>
<form id="new-run-form">
<select id="new-run-package"></select>
<input id="new-run-name" placeholder="run id (slug)" autocomplete="off">
<button type="submit">create</button>
</form>
</details>
<div id="window-info"></div> <div id="window-info"></div>
<div id="context-meter" title="context usage of the last call"> <div id="context-meter" title="context usage of the last call">
<div id="context-bar"><div id="context-fill"></div></div> <div id="context-bar"><div id="context-fill"></div></div>
<span id="context-label"></span> <span id="context-label"></span>
</div> </div>
<button id="diag-btn" title="diagnostics log">log</button>
</header> </header>
<main> <main>
<section id="transcript" aria-live="polite"></section> <section id="view-home" hidden>
<h1>runs</h1>
<div id="run-list"></div>
<button id="new-run-btn" class="primary">new run</button>
</section>
<section id="view-new" hidden>
<h1>new run</h1>
<div id="package-pick">
<p class="hint">a run is a copy of the package — everything stays editable until the window opens</p>
<div id="package-list"></div>
</div>
<form id="create-form" hidden>
<h2 id="create-title"></h2>
<label class="field">package name <input id="create-name" autocomplete="off"></label>
<label class="field">main character name <input id="create-pc" autocomplete="off"></label>
<div class="form-actions">
<button type="button" id="create-back">back</button>
<button type="submit" class="primary">create</button>
</div>
</form>
</section>
<section id="view-setup" hidden>
<div class="setup-head">
<h1 id="setup-title"></h1>
<span id="setup-state"></span>
<button id="setup-delete">delete draft</button>
<button id="setup-start" class="primary">start</button>
</div>
<div id="setup-vars" hidden>
<h2>prompt variables — declared by the prompts, filled per run</h2>
<div id="setup-vars-list"></div>
<div class="form-actions">
<button id="setup-vars-save">save variables</button>
<span id="setup-vars-state"></span>
</div>
</div>
<div class="setup-body">
<nav id="setup-files"></nav>
<div id="setup-editor">
<div id="edit-stack">
<pre id="edit-hl" aria-hidden="true"></pre>
<textarea id="setup-edit" spellcheck="false"></textarea>
</div>
<div id="setup-edit-bar">
<button id="setup-save">save</button>
<span id="setup-edit-state"></span>
</div>
</div>
</div>
</section>
<section id="view-play" hidden>
<div id="transcript" aria-live="polite"></div>
</section>
</main> </main>
<aside> <aside id="play-aside">
<section id="status-pane"> <section id="status-pane">
<div class="pane-head">
<h2>her paper</h2> <h2>her paper</h2>
<ul id="paper"></ul> <button id="paper-edit">edit</button>
</div>
<div id="paper"></div>
<div id="paper-editor" hidden>
<textarea id="paper-edit-area" rows="5" placeholder="one description per line — empty clears the paper"></textarea>
<div class="pane-editor-actions">
<button id="paper-save">save</button>
<button id="paper-cancel">cancel</button>
</div>
</div>
<div id="conflict" hidden></div> <div id="conflict" hidden></div>
</section> </section>
<section id="notes-pane">
<div class="pane-head">
<h2>gm notes</h2>
<span id="notes-state"></span>
</div>
<textarea id="gm-notes" placeholder="yours alone — never sent to the model"></textarea>
</section>
<section id="housekeeping"> <section id="housekeeping">
<h2>housekeeping</h2> <h2>housekeeping</h2>
<div id="hk-state"></div> <div id="hk-state"></div>
<button id="hk-run" hidden>close window &amp; housekeep</button> <button id="hk-run" hidden>close window &amp; housekeep</button>
<label id="hk-override-wrap"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label> <label id="hk-override-wrap"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
<button id="window-open" hidden>open window</button> <button id="window-open" hidden>open window</button>
<button id="hk-replay" hidden title="run the housekeeper over the session log — nothing applied">dry-run the wrap</button>
<details id="hk-log" hidden><summary>window log</summary><pre id="hk-log-content"></pre></details> <details id="hk-log" hidden><summary>window log</summary><pre id="hk-log-content"></pre></details>
<details id="hk-replay-log" hidden><summary>replay manifest</summary><pre id="hk-replay-content"></pre></details>
</section> </section>
</aside> </aside>
<footer> <footer>
<div id="banner" hidden></div>
<textarea id="gm-input" rows="2" placeholder="GM line — Enter sends, Shift+Enter newlines" disabled></textarea> <textarea id="gm-input" rows="2" placeholder="GM line — Enter sends, Shift+Enter newlines" disabled></textarea>
<span id="busy" hidden>her turn…</span>
<button id="gm-send" disabled>send</button> <button id="gm-send" disabled>send</button>
</footer> </footer>
<div id="banner" hidden></div>
<pre id="diag" hidden></pre>
<dialog id="ask-modal"> <dialog id="ask-modal">
<h2>the player asks</h2> <h2>the player asks</h2>
<p id="ask-question"></p> <p id="ask-question"></p>
+202 -25
View File
@@ -1,6 +1,7 @@
/* rp-test SPA — dark, quiet, fiction-first. Three registers: speech is /* rp-test SPA — dark, quiet, fiction-first. Three registers: speech is
plain, narration is italic (rendered dimmer), OOC is boxed. Machinery plain, narration is italic (rendered dimmer), OOC is boxed. Machinery
(tools, notes, deltas) stays small and muted. */ (tools, notes, deltas) stays small and muted. Home / setup views are
workbenches: cards, a file editor, read-only context. */
:root { :root {
--bg: #16161a; --bg: #16161a;
@@ -25,11 +26,19 @@ html, body {
body { body {
display: grid; display: grid;
grid-template:
"header" auto
"main" 1fr
"footer" auto / 1fr;
height: 100vh;
}
/* play keeps the two-column transcript + aside layout */
body.play {
grid-template: grid-template:
"header header" auto "header header" auto
"main aside" 1fr "main aside" 1fr
"footer footer" auto / 1fr 300px; "footer footer" auto / 1fr 300px;
height: 100vh;
} }
/* --- header --- */ /* --- header --- */
@@ -44,6 +53,35 @@ header {
border-bottom: 1px solid var(--line); border-bottom: 1px solid var(--line);
} }
#home-link { color: var(--accent); text-decoration: none; font-weight: 600; letter-spacing: 0.04em; }
#home-link:hover { text-decoration: underline; }
#window-info { color: var(--dim); font-size: 13px; margin-left: auto; white-space: nowrap; }
#context-meter { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--dim); visibility: hidden; }
body.play #context-meter { visibility: visible; }
#context-bar { width: 90px; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
#context-fill { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; }
#context-fill.hot { background: var(--danger); }
#diag-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#diag {
position: fixed;
right: 14px;
top: 46px;
width: min(620px, 85vw);
max-height: 45vh;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 6px;
padding: 10px 12px;
font: 11px/1.5 ui-monospace, Consolas, monospace;
color: var(--dim);
white-space: pre-wrap;
z-index: 20;
}
select, input, textarea, button { select, input, textarea, button {
background: var(--bg); background: var(--bg);
color: var(--text); color: var(--text);
@@ -56,21 +94,130 @@ select, input, textarea, button {
button { cursor: pointer; } button { cursor: pointer; }
button:hover { border-color: var(--accent); } button:hover { border-color: var(--accent); }
button:disabled { opacity: 0.4; cursor: default; } button:disabled { opacity: 0.4; cursor: default; }
button.primary { border-color: var(--accent); color: var(--accent); }
#new-run summary { cursor: pointer; color: var(--dim); } /* --- main / views --- */
#new-run form { display: flex; gap: 6px; margin-top: 6px; }
#window-info { color: var(--dim); font-size: 13px; margin-left: auto; white-space: nowrap; }
#context-meter { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--dim); }
#context-bar { width: 90px; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
#context-fill { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; }
#context-fill.hot { background: var(--danger); }
/* --- transcript --- */
main { grid-area: main; overflow-y: auto; padding: 18px 22px; } main { grid-area: main; overflow-y: auto; padding: 18px 22px; }
h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); font-weight: normal; margin: 4px 0 14px; }
.hint { color: var(--dim); font-size: 13px; font-style: italic; }
/* cards: runs on home, packages on /new — real buttons, left-aligned */
.card {
display: block;
width: 100%;
max-width: 560px;
text-align: left;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel);
padding: 10px 14px;
margin-bottom: 10px;
cursor: pointer;
}
.card:hover { border-color: var(--accent); }
.card.busy { opacity: 0.5; cursor: wait; }
.card-name { display: block; font-weight: 600; letter-spacing: 0.02em; }
.card-meta { display: block; color: var(--dim); font-size: 13px; margin-top: 2px; }
.card-state { display: block; font-size: 12px; margin-top: 6px; color: var(--dim); }
.card-state.draft { color: var(--accent); }
.card-state.ok { color: var(--ok); }
.card-state.attention { color: var(--danger); }
#new-run-btn { margin-top: 8px; }
/* the naming form (new run) and the vars box (setup) */
#create-form { max-width: 560px; }
#create-form h2 { font-size: 15px; margin: 0 0 14px; color: var(--text); font-weight: 600; }
.field { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; color: var(--dim); font-size: 13px; }
.field input { flex: 1; }
.form-actions { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
#setup-vars {
max-width: 560px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel);
padding: 10px 14px;
margin-bottom: 14px;
}
#setup-vars h2 {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
}
#setup-vars-state { color: var(--dim); font-size: 12px; }
/* --- setup: the editor --- */
.setup-head {
display: flex;
align-items: baseline;
gap: 14px;
margin-bottom: 14px;
}
.setup-head h1 { margin: 0; }
#setup-state { color: var(--dim); font-size: 13px; flex: 1; }
#setup-delete { font-size: 12px; color: var(--danger); }
.setup-body {
display: grid;
grid-template-columns: 190px 1fr;
gap: 14px;
height: calc(100vh - 130px);
}
#setup-files { overflow-y: auto; }
.file-item {
display: flex;
justify-content: space-between;
width: 100%;
text-align: left;
padding: 6px 10px;
border: 1px solid transparent;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
color: var(--text);
}
.file-item:hover { border-color: var(--line); }
.file-item.current { border-color: var(--accent); }
.file-item.absent { color: var(--dim); font-style: italic; }
.file-item.ro { color: var(--dim); }
.file-item.dirty .file-dirty::after { content: "*"; color: var(--accent); }
#setup-editor { display: flex; flex-direction: column; min-width: 0; }
#edit-stack { position: relative; flex: 1; min-height: 0; }
/* the highlight overlay: a pre behind a transparent-text textarea,
identical metrics, scroll-synced — sigils and vars light up in place */
#edit-hl, #setup-edit {
position: absolute;
inset: 0;
margin: 0;
padding: 5px 8px;
font: 13px/1.5 ui-monospace, Consolas, monospace;
white-space: pre-wrap;
overflow-wrap: break-word;
border: 1px solid var(--line);
border-radius: 4px;
}
#edit-hl { pointer-events: none; overflow: hidden; color: var(--text); border-color: transparent; }
#setup-edit {
background: transparent;
color: transparent;
caret-color: var(--text);
resize: none;
overflow-y: auto;
}
#setup-edit::selection { background: rgba(201, 162, 109, 0.3); }
.tok-sigil { color: var(--accent); }
.tok-var { color: var(--ok); }
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
#setup-edit-state { color: var(--dim); font-size: 12px; }
/* --- transcript (play) --- */
.turn { margin: 0 0 20px; max-width: 760px; } .turn { margin: 0 0 20px; max-width: 760px; }
.turn .who { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; } .turn .who { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; }
.turn.gm .who { color: var(--accent); } .turn.gm .who { color: var(--accent); }
@@ -88,7 +235,6 @@ main { grid-area: main; overflow-y: auto; padding: 18px 22px; }
} }
.chip.lost { text-decoration: line-through; } .chip.lost { text-decoration: line-through; }
.chip.gained { color: var(--ok); border-color: var(--ok); } .chip.gained { color: var(--ok); border-color: var(--ok); }
.chip.machinery { font-size: 11px; }
.machinery { .machinery {
margin: 6px 0; font-size: 12px; color: var(--dim); margin: 6px 0; font-size: 12px; color: var(--dim);
@@ -96,7 +242,17 @@ main { grid-area: main; overflow-y: auto; padding: 18px 22px; }
} }
.machinery .head { color: var(--text); } .machinery .head { color: var(--text); }
/* the bundle: a collapsed card, per part */ /* the opening beat, when the window opened but the beat never sent */
.beat {
display: flex; align-items: center; gap: 14px;
border: 1px solid var(--accent); border-radius: 6px;
padding: 8px 12px; margin: 0 0 16px; max-width: 760px;
font-size: 13px; color: var(--dim);
}
.beat button { margin-left: auto; }
/* the bundle: a collapsed card, per part — the system message is
inspectable like the rest, read-only */
details.bundle { details.bundle {
margin: 14px 0; border: 1px solid var(--line); border-radius: 6px; margin: 14px 0; border: 1px solid var(--line); border-radius: 6px;
background: var(--panel); font-size: 13px; color: var(--dim); background: var(--panel); font-size: 13px; color: var(--dim);
@@ -106,32 +262,51 @@ details.bundle pre { margin: 0; padding: 0 12px 10px; white-space: pre-wrap; fon
.error-line { color: var(--danger); } .error-line { color: var(--danger); }
/* --- aside --- */ /* --- aside (play) --- */
aside { #play-aside {
grid-area: aside; grid-area: aside;
border-left: 1px solid var(--line); border-left: 1px solid var(--line);
background: var(--panel); background: var(--panel);
padding: 14px; padding: 14px;
overflow-y: auto; overflow-y: auto;
font-size: 13px; font-size: 13px;
display: none;
} }
body.play #play-aside { display: block; }
aside h2 { #play-aside h2 {
margin: 4px 0 8px; font-size: 11px; letter-spacing: 0.14em; margin: 4px 0 8px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal; text-transform: uppercase; color: var(--dim); font-weight: normal;
} }
#paper { list-style: none; margin: 0; padding: 0; } .pane-head { display: flex; align-items: baseline; gap: 8px; }
#paper li { padding: 3px 0; border-bottom: 1px dashed var(--line); } .pane-head h2 { flex: 1; margin: 4px 0 8px; }
#paper li::before { content: "— "; color: var(--dim); } .pane-head button { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#paper li.empty { color: var(--dim); font-style: italic; }
#paper { margin: 0; line-height: 1.5; }
#paper.empty { color: var(--dim); font-style: italic; }
#paper-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
.pane-editor-actions { display: flex; gap: 6px; margin-top: 6px; }
.pane-editor-actions button { font-size: 12px; padding: 2px 12px; }
#conflict { #conflict {
margin-top: 10px; padding: 8px; border: 1px solid var(--danger); margin-top: 10px; padding: 8px; border: 1px solid var(--danger);
border-radius: 4px; color: var(--danger); font-size: 12px; border-radius: 4px; color: var(--danger); font-size: 12px;
} }
/* the GM's notepad: always on screen during play, auto-saved */
#notes-pane { margin-top: 22px; }
#notes-state { color: var(--dim); font-size: 11px; }
#gm-notes {
width: 100%;
min-height: 150px;
resize: vertical;
font-size: 13px;
line-height: 1.5;
}
#housekeeping { margin-top: 22px; } #housekeeping { margin-top: 22px; }
#hk-state { color: var(--dim); margin-bottom: 8px; white-space: pre-wrap; } #hk-state { color: var(--dim); margin-bottom: 8px; white-space: pre-wrap; }
#hk-state.rejected { color: var(--danger); } #hk-state.rejected { color: var(--danger); }
@@ -141,21 +316,23 @@ aside h2 {
#housekeeping button { width: 100%; margin-top: 6px; } #housekeeping button { width: 100%; margin-top: 6px; }
#hk-override-wrap { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; } #hk-override-wrap { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; }
/* --- footer --- */ /* --- footer (play) --- */
footer { footer {
grid-area: footer; grid-area: footer;
display: flex; gap: 8px; padding: 10px 14px; display: flex; gap: 8px; padding: 10px 14px;
background: var(--panel); border-top: 1px solid var(--line); background: var(--panel); border-top: 1px solid var(--line);
position: relative; display: none;
} }
body.play footer { display: flex; }
#gm-input { flex: 1; resize: none; } #gm-input { flex: 1; resize: none; }
#gm-send { padding: 5px 18px; } #gm-send { padding: 5px 18px; }
#busy { color: var(--dim); font-size: 12px; font-style: italic; white-space: nowrap; align-self: center; }
/* in-page banner — replaces JS alert()/confirm() (they block the /* in-page banner — replaces JS alert()/confirm() (they block the
embedded pane); errors and notices land here instead */ embedded pane); errors and notices land here instead */
#banner { #banner {
position: absolute; left: 50%; top: -6px; transform: translate(-50%, -100%); position: fixed; left: 50%; top: 12px; transform: translateX(-50%);
max-width: 70%; padding: 8px 14px; border-radius: 6px; max-width: 70%; padding: 8px 14px; border-radius: 6px;
background: var(--panel); border: 1px solid var(--danger); background: var(--panel); border: 1px solid var(--danger);
color: var(--danger); font-size: 13px; white-space: pre-wrap; z-index: 10; color: var(--danger); font-size: 13px; white-space: pre-wrap; z-index: 10;