spa modules and terminology: app.mjs split into flat es modules (router lifecycle, shared widgets, views own their state), mock smoke in test/; DICTIONARY.md rules the terms, four renames swept clean through the machinery - paper->status (run summary command is report now), window->session, wrap->housekeeping, context window->contwin; no dual-accepts by ruling, old data migrates once in the clerk (restore self-heals old dumps)

This commit is contained in:
2026-11-14 23:48:27 +00:00
parent 89a2c161b3
commit c51d31078e
36 changed files with 2643 additions and 1779 deletions
+68 -29
View File
@@ -3,7 +3,8 @@
Working notes for the agent working this repo. Not project
documentation — the project's homes are README (architecture, protocol,
observables), ROADMAP (decisions, steal list, substrate plan),
QUESTIONS (the decision queue), HANDOFF (working state). This file is
QUESTIONS (the decision queue), DICTIONARY (the terms of art),
HANDOFF (working state). This file is
memory the agent owes itself across sessions.
## Working with the GM
@@ -86,7 +87,7 @@ memory the agent owes itself across sessions.
per-run `models: {player, housekeeper}` over server.json defaults
(#16 narrowed to the default choice only). Signing in is permanent
and per-browser — no sign-out (lifecycle is a ROADMAP extension
point). The agenda (QUESTIONS #32): second player paper, `<add>`/
point). The agenda (QUESTIONS #32): the player's second block, `<add>`/
`<drop>` deltas, cap-5 recency queue; Irene's events journal
migrated (CHECK widened) — her db is agenda-ready. The per-turn
reminder (QUESTIONS #34, steal #11 done): reminder.md is repo-shared,
@@ -127,44 +128,82 @@ memory the agent owes itself across sessions.
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. Added 2026-11-14 (multiuser
round): the a11y snapshot races async renders — waiting for static
skeleton text ("RUNS") snapshots BEFORE the fetches land and looks
like a rendering bug; wait for text that only exists post-render (a
card name, the window-info line) or probe the DOM via evaluate.
CSS text-transform breaks literal waits (wait for "HER STATUS", not
"her status") and PLACEHOLDERS never match a wait at all (probe the
textarea via evaluate instead); clickable divs are invisible to the
a11y tree and the keyboard — clickable things are buttons. Added
2026-11-14 (multiuser round): the a11y snapshot races async renders
— waiting for static skeleton text ("RUNS", the aside headings)
snapshots BEFORE the fetches land and looks like a rendering bug;
wait for text that only exists post-render (a card name, the
session-info line) or probe the DOM via evaluate.
- Test-state discipline (2026-11-14): the deployment's state/ is real
— never leave test users or invites in it. Smoke against --mock,
then Remove-Item state/ and every test run (all but the GM's real
ones) before calling it done. A stale bootstrap file is harmless
(dead once a superuser exists), but test users make the deployment
NOT fresh and block the real bootstrap.
- Naming gotcha (2026-11-14, SPA round): static files under web/ must
not have names starting with "api" — the server's route guard
matches the /api PREFIX, so web/api.mjs 404'd as a bogus API route
and the app died at module load with an empty <main>. The REST
client module is client.mjs. Any future web file name gets this
check.
- Gotcha (2026-11-14, rewind aftermath): a session rewind erases my
memory of tool calls but NOT their effects — the server, files, and
databases keep them. After any rewind, external state is the truth:
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).
- Open tails (handoff, 2026-11-14): **housekeeper.md review is the
next creative step** — the GM's dry-run verdict was "works, but not
as expected; I never saw the prompt"; iterate with the replay
button (nothing applied). **Status discipline**: the paper has
taken up thread-tracking; the GM wants the admission-gate section
in invariants.md tightened. **Verbosity**: completions lengthened
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).
- Open tails (handoff, 2026-11-14, evening): **housekeeper.md review
is still the next creative step** — the GM's dry-run verdict was
"works, but not as expected; I never saw the prompt"; iterate with
the replay button (nothing applied). **Status discipline: RESOLVED**
by the agenda (QUESTIONS #32/#33). **Verbosity**: completions
lengthened 103 -> 668 chars across session one; the per-turn reminder
is the countermeasure now built — the next live session is the test.
The first real housekeeping pass (Irene's session) is the memory
test's start, and the op's one-time act (bootstrap claim +
hand-stamping Irene's owner) rides before it (HANDOFF step 1). **Replay-after-housekeeping is
dead** (found in the SPA round, unfixed, server-side): housekeeping
auto-restarts the next session, so the replay default (latest
session) points at the fresh empty session and 409s — the closed
session needs naming. GM's call where the default should point.
- Active work: NONE — the SPA module refactor + terminology round is
complete, verified, and committed (2026-11-14): web/ is flat ES
modules (app, router, client, state, chrome, log, widgets,
transcript, view-* per view), the three hand-copied patterns became
factories (armedButton, paneEditor, modelsBox), views own their
state and teardown via enter/leave, the mock smoke lives in test/,
and DICTIONARY.md rules the terms — four renames swept clean
through the machinery (paper->status, window->session, wrap->
housekeeping, context window->contwin), one clerk normalizer
migrates old dbs/dumps, no dual-accepts (GM: no legacy hauling).
The multiuser + agenda + reminder round is committed through
89a2c16 (the amended reminder commit — abf8ef3 is its dead
pre-amend twin); the first real story is being played. Working
lessons from the build: the newest GM
turn must keep its <status>/<agenda> blocks (that ride is the
status/agenda blocks' only channel from session two on); any new path that reads a
run file for sending goes through expandVars (turn0() initially
didn't); the transcript must surface failed session-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); ownership is resolved
against the users table, never swept on disk; same-verb delta blocks
combine into one apply, never execute in sequence. Rename-mechanics
lesson (2026-11-14): scripted renames with split/join replace EVERY
occurrence — renaming the clerk's `paper` case to `status` and then
`status` to `report` ate both, leaving no `status` dispatch; the
smoke caught it on the next run. Order rename pairs so a new name
is never a later pair's old name, and grep dispatch tables after.
CLI note: the run summary is `report` now; `status` is the tier
verb.
- 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.
broken until its design round; do not fix or design it unprompted,
and do not keep it aligned: term sweeps, renames, and audits skip
it entirely (2026-11-14, GM — its gm.md "paper" wording stays
as-is; don't flag it again).
- 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 —
@@ -186,13 +225,13 @@ memory the agent owes itself across sessions.
below.
- Watch: the "never open with world narration" rule was cut as
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 session-open refuses
over an unhousekept session with explicit override; #16 housekeeper
defaults to the player's model; #10 tool-call pairing validation goes
into the server loop.
- Open decisions live in QUESTIONS.md — read it first. Remaining: #19c
(seed voice, GM may revisit — non-blocking, seed editable until first
window-open) and #16 (which model the housekeeper defaults to).
session-open) and #16 (which model the housekeeper defaults to).
Resolved lately: #19a keep "Rell"; #20 system.md split (substrate
facts / per-project guards / per-run craft, hard limits in the craft
copy); #21 unhousekept-session guard (refuse with override).
+252
View File
@@ -0,0 +1,252 @@
# Dictionary — the terms of art
The source of truth for what things are called. When prose, UI, or
code drifts from these names, the fix is to align to this file; when
a name here stops working, the fix is to re-rule it here first, then
sweep. Durable meanings live in `README.md`; this file rules the
WORDS.
## The people and the models
- **the GM** — the human running the world: every NPC, every
consequence, all retcons. Runs on organic memory; the model's canon
files are the prosthesis. Always a human, never a model.
- **the player** — the player-model: the LLM playing the one PC.
The two parties who play are the GM and the player (2026-11-14,
GM) — and the player is always the model: humans are never "the
player" (QUESTIONS #28); a human in the app is a GM (of their own
runs), a spectator, or the op.
- **the PC** — the one character the player-model plays. Female by
postulate (README Scope); the shared prompts say "she" throughout.
- **the housekeeper** — a fresh model invocation after each session,
reading the transcript and the rings; emits a manifest. Judgment,
never clerical work; never plays, never edits files. Its prompt
(housekeeper.md) is substrate-internal and never exposed.
- **the clerk** — `tool/memory.mjs`: validates, applies, renders,
dumps. Fails loudly, never drifts silently. Code, never a model.
- **the op** — the superuser of a deployment: mints and revokes
invites and users; recovery is filesystem access. The whole of
admin.
## The story state
- **the deployment** — one clone plus `server.json`, `state/`, and
`runs/` (all gitignored): the unit of sharing. Invited users need
neither the key nor a clone.
- **the package** — a preset: authored content only, no state.
System packages ship with the repo; user packages are saved runs,
published to the deployment (gm.md included — saving is the act of
publishing). Read exactly once per run, ever — at create.
- **the run** — one story: the package copied wholesale into
`runs/<id>/` at create; from then the run directory is the only
truth. The id is anonymous hex and carries no facts; the visible
name is "Package / PC". The run is the PROCESS that delivers; the
story is the DELIVERABLE it exists to produce. In anything
mechanical it is always "the run".
- **the story** — the emerging deliverable: the narrative a run
exists to deliver. Prose may speak of the story; mechanics
always say run.
- **draft** — a run with no sessions yet: created, never started.
Editable in setup, deletable from the SPA; a played run refuses
deletion server-side.
- **the session** — one play period between housekeeping passes:
opens with the bundle assembly, plays by turns, ends with
housekeeping (which applies memories and auto-opens the next).
Renamed from "window" — see Ruled renames. Its transcript log is
`sessions/<stamp>.jsonl`; ordinals in prose: "session one", "her
next session".
- **the turn** — one exchange: a GM turn (user role), then the
player's turn (assistant role; tool calls may interleave between
beats).
- **the bundle** — the opening context of a session, assembled in
order: the system message trio (system.md → invariants.md → the
run's handbook), then the GM messages — backdrop, character,
ring-b, ring-a. Everything in it is inspectable read-only in the
SPA; agent prompts never enter it.
- **fresh** — a session over a never-started run: the seed applies
(lazily, once) and turn-0's `<status>` block ingests at open.
- **the seed** — `seed.json`, the run's initial state (`entries` →
rings, `records` → files). Rides the run copy until the first
session-open applies it; freely editable until then; re-apply
refuses.
- **turn-0** — the opening beat file: the GM's zeroth turn, sent
once as the first GM message of the first session. The FILE is
turn-0; the MESSAGE, once sent, is "the opening beat".
## Memory
- **the rings** — her salient memory, two tiers ordered by touch
(an LRU cache): **ring A** — important facts, cap 500; **ring B** —
the rest that passed the gate, cap 3000. Storage is rows; the
views (`canon/ring-*.md`) are rendering.
- **touch** — a meaningful invocation during play (named, used,
clearly weighed); raises the entry. Mere adjacency doesn't count.
- **promotion / demotion** — the housekeeper's A↔B judgment, reason
logged. Judgment, not a metric.
- **overflow** — mechanical and exact: A spills to B, B spills to
cold, oldest-touched first. Enforced by count, never by a model's
arithmetic.
- **cold storage** — everything evicted or deleted. Beyond the
models' reach; GM-reachable via revive. Nothing is ever destroyed.
- **status** — descriptions of her immediate situation, admitted by
the three-part gate (non-normal, acute, turn-affecting). Rides
every GM turn as the `<status>` block; mutated by
`<lost>`/`<gained>` deltas; entirely hers — the housekeeper never
writes it. Renamed from "paper" — see Ruled renames.
- **the agenda** — her second self-kept block: intentions — what she
means to do — in a cap-5 recency queue. Rides as the `<agenda>`
block, mutated by `<add>`/`<drop>` (drops by 0-based index);
disposable by design. The seam with the status: how she is vs what
she means to do.
- **records** — her files: the card index, the ledger, whatever she
keeps. Diegetic and per-run (the settings gate); narrow query,
hard cap 10 in the tool; a miss is a miss. Filed at her desk by
the player; the housekeeper only archives.
- **the backdrop** — the world as everyone in it knows it: public
knowledge. Never memory, never decays, always in the bundle.
- **identity** — `character.md`, the sheet: concept, drives, skills,
voice. The GM's to edit; the housekeeper proposes via open
questions; blanks are the player's to invent.
- **the manifest** — the housekeeper's whole output: JSON semantic
operations (insert, touch, promote, demote, reword, delete,
archive; plus summary, inventions, open questions). Validated and
applied by the clerk; a rejected manifest changes nothing and says
why.
- **housekeeping** — the session-close ritual: a fresh housekeeper
call over the transcript + rendered rings, the manifest, the
apply, the log, the autorestart of the next session. The only
word for it (2026-11-14, GM): the old shorthand "the wrap" is
retired.
- **the log** — `log/<session>.md`, one per pass: what the
housekeeper declared, cross-checked against the dump diff. The
`events` table is the journal underneath; both are write-only for
every model.
## Channels and syntax
- **IC / OOC** — in-character vs out-of-character. OOC is a line
opening with `(`, closing paren optional; any opening `<tag>` line
is substrate traffic and always OOC. Unknown tags are reported to
the GM.
- **speech / narration** — plain text is spoken aloud; `*italics*`
carry actions, descriptions, thoughts, interiority.
- **sigils** — `@PC` (her name) and `@Package` (the display name):
identity substitution resolved from the run's settings. Any other
`@`-word is the author's own text — `@` syntax is not owned here.
- **$TOKENs / vars** — template variables the prompts declare
themselves; setup collects them; the run's `settings.vars` holds
the answers.
- **deltas** — the in-band mutations: `<lost>`/`<gained>` on the
status, `<add>`/`<drop>` on the agenda. Same-verb blocks combine
into one apply; misses return as a conflict.
- **conflict** — the self-heal message: a `<conflict>` block sent as
its own GM-side message, clean of prose; the model adjusts in the
same exchange. Capped at 3 heals per turn.
- **ask_gm** — the player's tool for points of order, canon
questions, proposals. Pauses the turn mid-loop; the answer is
authoritative and never elides from the context.
- **roll** — the dice tool: a uniform random pick among equal-weight
options; the model receives `picked: <option>`. Randomizes
choices, never outcomes; commit, no re-rolling.
- **the reminder** — `reminder.md`: the turn-composition procedure,
repo-shared, riding after every GM turn as its own system chunk.
One live copy — superseded copies elide from the view; the log
keeps every as-sent chunk.
## People mechanics
- **invite / claim / token** — identity, in that order: a single-use
invite code is exchanged at claim for a persistent bearer token.
No usernames, no passwords, no external IDPs. Spent invites stay
recorded forever and are rejected loudly on reuse.
- **owner / ownerless / spectator** — runs belong to their starter;
every mutation and every model call is owner-only; everything is
readable by any user. Ownership is resolved, never maintained:
run.json keeps dead owner ids, the API reads them as absent. A
non-owner in a run is a spectator: reads everything, notepad
included (the boundary is the model boundary), mutates nothing.
Fork is the way in.
- **fork** — an atomic copy of any run under the forker, window
state honestly carried. No lineage; the only mark is
`forked: unixtime` in run.json beside the carried `created`.
## Instrumentation
- **the meter** — the context meter: prompt-token usage of the last
call against the contwin; loud past 85%.
- **contwin** — the context window, under its own name (coined
2026-11-14, GM: the word "window" is beyond overloaded, so even
this use got renamed). The config key in server.json is `contwin`
(`contextWindow` is still accepted).
- **mock mode** — `--mock`: the scripted fake model that proves the
loop without a key. The smoke (`test/`) runs against it.
- **the dump** — `dumps/memory.sql`: the canonical id-ordered SQL
snapshot, auto-written by every mutation. The primary audit
surface — diffing two consecutive dumps reconstructs the applied
operations exactly.
- **the view** — the rendered live context under policy: thinking
never goes back; old tool results elide to stubs (ask_gm answers
never); old status and agenda blocks elide; the current status and
agenda ride every GM turn; one live reminder at the freshest end.
## Conventions the words lean on
- All dates and times UTC, everywhere. No time zones, ever.
- No model-facing surface renders a date; story time lives in prose.
Internal stamps are mechanical (LRU, overflow, sinking) and never
render to a model.
- Ids are anonymous hex; display is "Package / PC"; run ids carry no
facts, so nothing ever needs renaming.
- Renames are clean (2026-11-14, GM: no legacy hauling). No
dual-accept shims: a renamed thing accepts only its new name, old
data migrates once (the clerk normalizes on open), and anything
left on the old name fails loudly. Upstream words (the DOM's
window, the OS's) are consumed as-is.
## Ruled renames
- **paper → status** (2026-11-14, GM). One name for the thing on
every surface a model or human reads: the prompts (invariants.md,
housekeeper.md, the rendered status view), the SPA, the docs'
living prose. Amended later the same day (GM: "I don't like
hauling legacy around" — renames are clean, no dual-accept
shims): the machinery renamed too — the `status`/`status-apply`/
`status-set`/`status-ingest` verbs (the run summary command is
`report` now), the db `status` table, the `/status` route, the
`detail.status` field, the `status-*` journal ops. Old data
migrates once, in the clerk; historical records (resolved
QUESTIONS entries, build logs) keep the vocabulary of their day.
- **window → session** (2026-11-14, GM). Reasons: to a user,
"closing a window" means exiting the program; and "context window"
already owns the word here — one project, one window, and it is
the context window (that last carve-out was superseded later the
same day by the contwin ruling below: the word is gone entirely).
Swept the same day (SPA strings, server
messages, docs prose, and the housekeeper manifest's key, now
`session` — the clerk dual-accepts `window` so old manifests stay
valid). Historical records keep the vocabulary of their day —
and old data is consumed as-is from its era: pre-rename session
logs carry `window`-kind notes (readers accept both), pre-rename
manifests carry the `window` key (the clerk dual-accepts), and
pre-rename dumps embed their own old schema and self-migrate.
- **the window machinery renamed too** (2026-11-14, GM: "invisibles
gone as well"). What survived the first sweep as private plumbing
is renamed like everything else we own: element ids
`session-info`/`session-open`, the route `POST /sessions`, the
response field `session`, the meter field `contwin`, the
function `openSession`, the `events` column `session` (one-time
rename migration, data-preserving). Words we do not own are
consumed from upstream as-is: the DOM's `window`, the OS's
window.
- **context window → contwin** (2026-11-14, GM). The word "window"
is retired entirely — even the context window gets its own name,
so nothing in the project says "window" on any surface. The config
key is `contwin`; the old `contextWindow` key is dual-accepted so
existing deployments keep booting.
- **wrap → housekeeping** (2026-11-14, GM). "Housekeeping" is the
only word; the shorthand "the wrap" is retired from strings and
living prose alike.
## Open naming questions
None currently open — ruled items live above and in the entries.
+126 -54
View File
@@ -9,6 +9,57 @@ file is the "where did we leave off" map.
## Where we are
- **DICTIONARY.md exists — the terms of art, one source of truth
(2026-11-14, GM-ruled).** A rename rules there first, then sweeps.
The full round is DONE: **paper → status, window → session, wrap →
housekeeping, context window → contwin** — swept on every surface
INCLUDING the machinery (element ids, routes, response fields, db
tables, journal ops), with one-time data-preserving migrations in
the clerk and **no dual-accepts** (the no-legacy convention is
recorded in the dictionary's Conventions). Two costs to remember:
the clerk's run summary is **`report`** now (`status` is the tier
verb, JSON), and Irene's pre-rename session log carries old-kind
notes that no longer render — cosmetic, data intact.
- **The SPA is refactored into modules (2026-11-14, GM-ruled).** The
1378-line app.mjs is gone; web/ is now flat ES modules like
server/: `app.mjs` (thin entry), `router.mjs` (path routing + the
view enter/leave lifecycle — each view owns its teardown, show()
never hand-resets panes), `client.mjs` (the fetch choke point —
named client, NOT api: a web file named api.mjs 404s, the static
guard matches the /api prefix), `state.mjs` (me/seq/runId only —
everything else is module-local to its view), `chrome.mjs`,
`log.mjs`, `widgets.mjs` (armedButton — the two-click confirm,
per-button arm state, fixing the shared-arm bug where arming one
user-revoke armed them all; paneEditor — the status/agenda twins as
one factory, two instances; modelsBox — the setup/play-aside
duplicate), `transcript.mjs`, and one `view-*.mjs` per view. The
mock smoke moved into the repo (`test/`). Verified: smoke 58/58,
reminder elision, restart check, and a full browser pass (claim,
home + admin, new run + name roll, setup editor + models box,
start, play: pane editors end to end, GM turn -> ask modal ->
answer, two-click housekeeping -> poll -> applied + log, the
auto-restarted session, spectator mode on Irene) — zero console
errors. Found en route, pre-existing, unfixed: **the dry-run
replay button is dead after a housekeeping pass** — housekeeping
auto-restarts the next session, so the latest session (the replay default) is the
fresh empty one and the call 409s ("no exchange to review"); the
closed session needs naming. Server-side semantics, GM's call.
- **The multiuser server, the agenda, and the per-turn reminder are
built, mock-proven, and committed (2026-11-14, through `89a2c16`).**
Token identity with single-use invites (no usernames, no passwords,
no external IDPs; the bootstrap invite auto-mints on the fresh
deployment to state/bootstrap-invite.txt and the console);
owner-gated runs with fork (atomic copy, owner replaced, no
lineage); system/user packages; per-run model selection (player +
housekeeper over the server.json defaults); spectator mode (read
everything, mutate nothing); the agenda — the player's second
status, `<add>`/`<drop>` deltas over a cap-5 recency queue, with
conflicts self-healing as their own message; and the reminder — the
GM-written turn-composition procedure riding every GM turn as its
own system chunk, one live copy. Design lives in ROADMAP ("The
multiuser server") and QUESTIONS #22-34, all resolved. **No users
exist yet:** the next server start mints the real bootstrap invite.
The server is stopped.
- **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
@@ -17,10 +68,10 @@ file is the "where did we leave off" map.
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
gate start; drafts two-click deletable); start opens the session 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),
(gm.md — auto-saved, never model-facing), her status as a compact
comma block with a GM edit button (status-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
@@ -31,7 +82,7 @@ file is the "where did we leave off" map.
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.
housekeeping, 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
@@ -41,16 +92,16 @@ file is the "where did we leave off" map.
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
prompt tokens — 9% of the contwin; 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
floor is ~4.2K tokens. The GM ran the housekeeping 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,
mock-proven, and live-proven.** Clerk (paper model, presets/runs),
server (REST spine, session machine, view renderer), housekeeping
job (async chain with autorestart), SPA (full v1 scope). The tool/
bridge is deleted. Two real housekeeping wraps ran clean (both
bridge is deleted. Two real housekeeping passes ran clean (both
manifests sound: correct ring-B classification, first-person voice,
precise touches); a full session was driven through the UI end to
end. **The server is stopped** (state as of this commit). Start it:
@@ -63,7 +114,7 @@ file is the "where did we leave off" map.
- **Prompt split in force (GM's cut, 2026-11-14):** `system.md` =
opening + guards (glossary, purpose, input validation — repo-fed,
per-project); `invariants.md` = substrate (syntax markers, tools,
memory, records, the paper + its gate — repo-fed, travels with the
memory, records, the status + its gate — repo-fed, travels with the
code); `handbook.md` = craft copy (shape of play, thoughts, purview,
time skips, continuity, stance, hard limits — copied per run,
editable to taste). One system message: system → invariants → the
@@ -85,7 +136,7 @@ file is the "where did we leave off" map.
quantified). Name call resolved: keep "Rell". Optional seed voice
touch-up may be revisited (QUESTIONS #19c, non-blocking). The seed
is authored but NOT applied — it rides the run copy at creation and
applies lazily at the first window-open.
applies lazily at the first session-open.
- Build history in brief (details in ROADMAP phasing): phase 0 clerk
paper migration (2026-11-13), phase 1 preset/run split
(2026-11-13), phase 2 server (2026-11-14), phase 3 housekeeping job
@@ -107,49 +158,56 @@ file is the "where did we leave off" map.
package wholesale into `runs/<id>/` (shared prompts included, run.json
lineage + optional model override) and inits state; `--run` addresses
runs; `packages`/`runs` list; `bridge.json` → `server.json`
(bind, endpoint, models, contextWindow, params; example committed,
(bind, endpoint, models, contwin, params; example committed,
key carried over, gitignored); `config.json` now names the default
package. Smoke-tested: create → seed → turn-0 ingest → delta apply →
status, re-seed refuses, smoke run deleted. `prelude.md` renamed
`turn-0.md` by the GM (comment dropped); clerk and docs follow.
- Boutique: dormant — a stub that never reached its design step
(concept brief in `packages/boutique/gm.md`).
- No runs exist in this deployment yet; both packages render clean as
presets (`packages` lists them).
- One run exists: Irene (4f261452, see above). Both packages render
clean as presets (`packages` lists them).
- **Substrate design round complete (2026-11-13)** — rulings recorded in
ROADMAP ("The harness"): the stated goal (a usable RP harness;
clone-and-run or invited instance, key on the backend, no secrets in
the repo), repo ships code + authored content only (state is
per-deployment), packages are presets copied wholesale into `runs/<id>/`
at creation (editable everything, discipline on the GM), lazy seed at
first window-open, per-run model selection with an upstream `/models`
listing, audit as per-wrap dump snapshots inside the run
(commit-per-wrap retired), zero-dep stack (QUESTIONS #4, #7 resolved).
first session-open, per-run model selection with an upstream `/models`
listing, audit as per-pass dump snapshots inside the run
(commit-per-pass retired), zero-dep stack (QUESTIONS #4, #7 resolved).
## Immediate next steps, in order
1. **The first real wrap — the memory test begins.** Close-and-
housekeep the Irene window when the GM is ready; review the
manifest and the window log against the dump diff (the audit
1. **First start under multiuser (op, one-time).** Start the server,
claim the bootstrap invite (`state/bootstrap-invite.txt` and the
console both carry it), then hand-stamp Irene's `run.json` with
`"owner": "<your user id>"` — the SPA header tooltip shows the id.
No migration code exists, by ruling; this is the op's one manual
act.
2. **The first real housekeeping pass — the memory test begins.**
Close-and-housekeep the Irene session when the GM is ready; review
the manifest and the session log against the dump diff (the audit
surface). Everything from the story so far (the shipwreck, Molly,
the island) lives only in context and on the paper until this
lands.
2. **Housekeeper prompt review (GM-led).** The GM's dry-run verdict:
the island) lives only in context and in her status until this
lands. Note: Irene's OPEN session still carries her old handbook
copy (craft edits land at session-open) — the housekeeping itself is
unaffected, but the clean reminder/agenda experiment starts at her
next session.
3. **Housekeeper prompt review (GM-led).** The GM's dry-run verdict:
works mechanically, output not as expected, and the prompt itself
is unseen so far. Iterate: read housekeeper.md, tweak, replay —
the dry-run button re-runs the wrap over the session log with
the dry-run button re-runs housekeeping over the session log with
nothing applied.
3. ~~**Status discipline**~~ — RESOLVED BY REDIRECT (2026-11-14,
QUESTIONS #32/#33): the paper's thread-tracking drift got its own
channel. The agenda (`<agenda>`/`<add>`/`<drop>`, cap-5 recency
queue, invariants.md GM-written) is built end to end; the gate
fight is over by design. The test is the next live window: watch
cross-channel drift and drop off-by-ones alongside observables
#12/#14.
4. **Keep playing.** Observables #12 (does the paper stay small and
match the transcripts) and #14 (one thing per turn vs lengthening
turns — completions grew 103 to 668 chars across window one) are
live now.
4. **Keep playing — and watch the experiments.** Observables #12 (the
status stays small and matches the transcripts) and #14 (turn
lengthening — the reminder is the countermeasure under test), plus
the fresh watchables: does thread-tracking move to the agenda;
drop off-by-ones; cross-channel drift; whether description-only
"empty turns" stay on her side of the purview line.
(Resolved en route: the status-discipline fight — the agenda gave the
drift its own channel, QUESTIONS #32/#33.)
## The multiuser build (2026-11-14) — DONE
@@ -164,12 +222,12 @@ Design round closed (ROADMAP "The multiuser server", QUESTIONS
2. **Ownership + fork + packages** — owner gating on every mutation
and every model call; per-run activity locks (turn, ask, turn0,
housekeeping job, fork); `POST /api/runs/:id/fork` (staged copy,
atomic swap, owner replaced, `forked` stamped, window state
atomic swap, owner replaced, `forked` stamped, session state
mirrored); clerk learns the second packages root (`state/packages`)
and `save-package`; user packages published to all. Ownership is
resolved, never maintained (GM ruling): run.json keeps dead owner
ids, the API reads them as absent; revocation is a db delete plus
closing the revoked user's open windows.
closing the revoked user's open sessions.
3. **SPA** — claim view, identity in the header, superuser admin on
home, spectator mode (read everything, mutate nothing, fork CTA),
save-as-package on setup, origin in the package picker, garnish
@@ -185,7 +243,7 @@ Design round closed (ROADMAP "The multiuser server", QUESTIONS
Gotcha learned while testing: the a11y snapshot races async renders —
wait for text that only exists POST-render (a card name, the
window-info line), never the static skeleton; and CSS text-transform
session-info line), never the static skeleton; and CSS text-transform
still uppercases wait targets.
Model selection wired (GM, same day): run.json now carries
@@ -214,13 +272,18 @@ the public user shape only (it was leaking the token hash). Smoke
56/56, UI verified end to end.
The per-turn reminder built (GM-ruled, QUESTIONS #34, steal #11 DONE):
`reminder.md` (repo-shared, agent-drafted extraction of the turn-
composition protocol, awaiting the GM's edit + handbook cut) rides
after every GM turn as its own system chunk; one live copy — older
elide from the view, the SPA shows one collapsed card for the newest,
housekeeping never sees it. Smoke 58/58 plus an elision unit check
(log keeps 5, view carries exactly one, positioned at the freshest
end). The next live window is the experiment for observable #14.
`reminder.md` (repo-shared) rides after every GM turn as its own
system chunk; one live copy — older elide from the view, the SPA shows
one collapsed card for the newest, housekeeping never sees it. The
GM's rewrite superseded the agent's extraction draft: it is a
*procedure* (understand -> decide -> compose -> adjust your papers),
not a rule list — new material throughout, including the per-class
turn budget (zero or one of thoughts/dialogue/actions) and the
dice-tiebreak. The handbook's "one thing per turn" was cut to "short
turns" in step (the budget lives in the reminder now). Smoke 58/58
plus an elision unit check (the log keeps every copy, the view carries
exactly one, at the freshest end). The next live window is the
experiment for observable #14.
## Working agreements with the GM
@@ -253,24 +316,33 @@ are open questions for the drafting session with the GM).
- `server.json` (gitignored) holds the real key; it mirrors opencode's
`dv` provider (config at `~/.config/opencode/opencode.jsonc`, auth at
`~/.local/share/opencode/auth.json`).
- Resetting a run: `Remove-Item packages/<story>/db/memory.db` then `init`.
- Resetting a run: `Remove-Item runs/<id>/db/memory.db` then `init`.
`--force` flags are only for disposable pre-story states.
- Sessions log to `packages/<story>/sessions/<stamp>.jsonl` — housekeeping's
- Sessions log to `runs/<id>/sessions/<stamp>.jsonl` — housekeeping's
transcript, and the future watcher agent's food (see ROADMAP).
- The `--mock` mode has caught two real bugs already (dump column
rename, readline line-loss). Run it before any live first-use.
- The mock smoke lives in the repo (`test/` — the scripts moved in
from the temp dir at the GM's ask, 2026-11-14; no broader
test-infra ruling is attached): `smoke.mjs` (the 58-step
multiuser/agenda/reminder pass), `check-reminder.mjs` (the elision
unit check), `restart-check.mjs` (post-restart rebuild). They
expect a CLEAN state/ plus a running `--mock` server; smoke prints
its run ids and leaves a temp token file for the restart check.
Clean up state/ and the smoke runs afterwards — only the real runs
stay.
## Not yet exercised (expect first-use friction)
- **First start under multiuser** (step 1 above) — nothing live has
touched the auth spine, invites, fork, or spectator mode yet; all
are mock-proven only.
- ask_gm in live flow (pause/resume is mock-proven; the live model
simply made its own choices so far — by design), the conflict-carry
path in flow, records tools through the server (needs a
records-enabled run).
- The housekeeping chain is live-proven once (see `live-smoke`); a
rejection in live flow, and the recovery-apply path on a real
simply made its own choices so far — by design), the self-heal
conflict path in live flow (mock-proven; capped at 3 heals a turn),
the agenda and the reminder against a live model, records tools
through the server (needs a records-enabled run).
- A live housekeeping rejection, and the recovery-apply path on a real
manifest, remain first-use items.
- The in-flow missed-update prediction (ROADMAP, system-1 entry) —
measurable from the second real window on. The `live-smoke` run
(2026-11-14) is the first real session: two turns + the first real
wrap; window two is open on it now — the run is disposable but
usable for a test drive.
measurable from the second real session on.
+10
View File
@@ -5,6 +5,16 @@ unanswered. Trim items as they are answered; durable decisions graduate to
`README.md`, `ROADMAP.md`, or the prompts. Tiered by urgency, FIFO within
a tier.
## Operator's queue (don't edit, don't work on)
- how does the dice tool work again? what does the model receive back?
- prohibit all-caps styles
- render agenda as a bullet list
- ASCII only, no unicode
- sliding window compaction
- full story in the SPA
- name the project
## Play-side (before window one)
### 1. The PC token in system.md — RESOLVED (2026-11-12)
+81 -51
View File
@@ -5,10 +5,10 @@ and the human plays **everything else**.
## The premise
Using a model as the GM hits the context window wall and dilutes creativity —
Using a model as the GM hits the contwin (context window) wall and dilutes creativity —
it has to hold the whole world in its head. Inverting the roles fixes the
footprint: a player-character holds one perspective. Short plays would work
fine either way; the actual test is **long, cross-window stories**: can the
fine either way; the actual test is **long, cross-session stories**: can the
model persist established lore without drowning in it?
More precisely: this isn't a model test, it's an instruction test. The subject
@@ -37,7 +37,7 @@ housekeeping job, and SPA — see `node server/main.mjs` and open
- **Player-model = one PC.** Inner life, voice, choices. Nothing else. Reads
memory, never writes it.
- **Housekeeper-model = a separate invocation**, fresh context, run after each
window. Reads the transcript and the rendered rings; emits a **manifest** of
session. Reads the transcript and the rendered rings; emits a **manifest** of
semantic operations. Judgment, no clerical work.
- **`tool/memory.mjs` = the clerk.** Validates and applies manifests,
maintains the database, enforces caps, renders views, writes the log,
@@ -76,7 +76,7 @@ forking makes that cheap — stories outlive identities by design.
requires a signed-in user (`Authorization: Bearer <token>`).
- **Runs belong to their starter.** Every mutation and every model
call is owner-only; every run is readable by any user — transcript,
paper, rings, config, notepad included. The boundary is the model
status, rings, config, notepad included. The boundary is the model
boundary: gm.md is secret from the player-model, never from people.
Ownerless runs — pre-user, or the owner was revoked — are one
uniform state: readable, forkable, no owner actions, never
@@ -96,7 +96,7 @@ forking makes that cheap — stories outlive identities by design.
names the defaults (player, housekeeper); a run's owner overrides
either role from the upstream listing — in setup for drafts, in the
play aside for started runs. Each call resolves fresh, so a
mid-window switch simply takes the next turn.
mid-session switch simply takes the next turn.
- Every logged LLM call records the acting user. Quotas and limits are
an extension point, not built.
- All dates and times are UTC everywhere. No time zones, ever.
@@ -107,7 +107,7 @@ Two interleaved stories calibrate the memory system against itself:
| | `la-caramba` | `boutique` |
|---|---|---|
| entries per window | few — tiny cast, deep history | many — the customer parade |
| entries per session | few — tiny cast, deep history | many — the customer parade |
| dominant ops | touch, reword | insert, gate, demote/retire |
| ring A pressure | staleness — standings shift on hot entries | clutter — obligations accrete |
| player agency | constrained — reactive creativity | full — proactive creativity |
@@ -125,7 +125,7 @@ proper content.
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.
session, and sends turn-0 as the first GM turn in one action.
1. **Backdrop** — write `packages/<story>/backdrop.md`: the world as everyone
in it knows it. Public knowledge, general setting. Neither memory nor
@@ -133,9 +133,9 @@ window, and sends turn-0 as the first GM turn in one action.
The housekeeper is instructed to keep it out of the rings.
2. **Turn 0** (new games, optional) — write `packages/<story>/turn-0.md`:
the opening beat, the situation she wakes into — the GM's zeroth
turn. Sent once, as the first GM message of window one; after that
turn. Sent once, as the first GM message of session one; after that
it is history, living in the session transcript. Its trailing
`<status>` block is her opening paper, ingested at new-game.
`<status>` block is her opening status, ingested at new-game.
Without it, the GM narrates the opening beat themselves.
3. **Character** — write `packages/<story>/character.md`: starting identity.
The sheet is a reduction of choice surface — a ledger of decisions
@@ -150,9 +150,9 @@ window, and sends turn-0 as the first GM turn in one action.
4. **Seed** — write `packages/<story>/seed.json`: the initial state of the
run. `entries` → the rings (initial memories), `records` →
pre-existing files (gated by `settings.json`). It applies lazily at
the run's first window-open — until then it rides the run copy,
the run's first session-open — until then it rides the run copy,
freely editable; deleting it from the run is the opt-out. Everything
is journaled under window `seed`. Her opening paper does not seed —
is journaled under session `seed`. Her opening status does not seed —
it rides turn-0's `<status>` block.
5. **Create the run** — `node tool/memory.mjs create <story> <pc-name>`:
the package is copied wholesale into `runs/<id>/` — the craft
@@ -166,14 +166,14 @@ window, and sends turn-0 as the first GM turn in one action.
only truth: the package is never read again, and everything in the
run is editable at any time. The discipline not to break a running
narrative sits with the GM.
6. **First window** — open it (the server assembles the bundle; until it
lands, manual relay), narrate. The first window-open of a fresh run
6. **First session** — open it (the server assembles the bundle; until it
lands, manual relay), narrate. The first session-open of a fresh run
applies the seed, then ingests turn-0's `<status>` block.
## The protocol
1. **Refresh the views:** `node tool/memory.mjs --run <id> render`
2. **Open a window:** one system-role message is assembled in order:
2. **Open a session:** one system-role message is assembled in order:
`system.md` (glossary, purpose, input guards) and `invariants.md`
(the substrate's mechanical contracts) — both repo-fed — then the
run's `handbook.md` craft copy. Everything
@@ -184,12 +184,12 @@ window, and sends turn-0 as the first GM turn in one action.
`reminder.md` (repo-fed) as its own `role: system` chunk carrying
the turn-composition protocol; superseded copies elide from the
live view, so exactly one exists, always at the freshest end. On a new game, `turn-0.md` is the opening beat: its
trailing `<status>` block is ingested as her opening paper at
window-open, and the beat itself is sent as the first GM turn when
trailing `<status>` block is ingested as her opening status at
session-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 bundle. In play the current status rides every GM turn
the same way (the per-turn ride lands with the server). (On a tight
window, ring B is optional loading — ring A is the spine.)
session, ring B is optional loading — ring A is the spine.)
Substitution has two classes: `@PC` (her name) and `@Package` (the
display name) are identity sigils resolved from the run's
`settings.json` `pc`/`name`; `$TOKEN`s are template vars declared
@@ -204,7 +204,7 @@ window, and sends turn-0 as the first GM turn in one action.
3. **In play:** a line opening with `(` is the out-of-character channel —
points of order, canon questions, proposals, vetoes; both sides use
it, closing paren optional. Entries carry stable ids (`[e17]`);
citing one is the precise way to reference a memory. The paper
citing one is the precise way to reference a memory. The status
travels in-band: the current `<status>` block rides every GM turn,
and the player mutates it with `<lost>`/`<gained>` tags in its own
turns (the clerk applies the deltas — same-verb blocks combine into
@@ -220,7 +220,7 @@ window, and sends turn-0 as the first GM turn in one action.
over realism — lives in `system.md`, `invariants.md`, and
`handbook.md`. Through the server, the model's OOC is the `ask_gm`
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 session:** just stop. No in-band ritual; the player-model has no
end-of-session duties.
5. **Housekeep (fresh model, new context):** send `housekeeper.md`
(the repo-fed housekeeping prompt — substrate-internal, never
@@ -229,10 +229,10 @@ window, and sends turn-0 as the first GM turn in one action.
the session transcript — pasted, or the latest
`runs/<id>/sessions/*.jsonl` when playing through the server (the
phase-3 housekeeping job automates this). Save
its manifest to `runs/<id>/manifests/<window>.json`.
6. **Apply:** `node tool/memory.mjs --run <id> apply runs/<id>/manifests/<window>.json`
its manifest to `runs/<id>/manifests/<session>.json`.
6. **Apply:** `node tool/memory.mjs --run <id> apply runs/<id>/manifests/<session>.json`
— the tool validates, applies, handles overflow, writes the run's
`log/<window>.md`, re-renders the views. A rejected manifest changes
`log/<session>.md`, re-renders the views. A rejected manifest changes
nothing and says why.
7. **Review the log, veto or edit as desired, commit.** GM edits go through
`insert` / `delete` / `revive` commands.
@@ -249,7 +249,7 @@ Memory is **seven tiers**:
|---|---|---|---|
| **backdrop** | the world as everyone knows it — public knowledge, the general setting; never memory, never forgotten | always | GM, rarely (retcons) |
| **identity** | the character sheet — concept, drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent |
| **status** | her piece of paper — descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | every GM turn, as its `<status>` block | **the player** (`<lost>`/`<gained>` deltas in its turns); GM override out-of-band |
| **status** | descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | every GM turn, as its `<status>` block | **the player** (`<lost>`/`<gained>` deltas in its turns); GM override out-of-band |
| **agenda** | her hot queue of intentions — what she's working towards right now; a fixed-cap recency buffer (new on top, overflow evicts the bottom), disposable by design | every GM turn, as its `<agenda>` block | **the player** (`<add>`/`<drop>` deltas in its turns, drops by index); GM override out-of-band |
| **rings A/B** | salient memory — facts, on her mind, MRU-evicted | always | housekeeper manifest |
| **records** | her files — the card index, the ledger. Narrow query only, hard cap 10 (in the tool, not the prompt), never bulk-loaded | never — on demand | **the player** (`file`/`amend`/`discard` at her desk); GM seeds; housekeeper only `archive`s |
@@ -258,7 +258,7 @@ Memory is **seven tiers**:
The boundary that keeps the tiers honest: **stances are feelings (status,
the player's); facts are facts (rings, the housekeeper's).** The
housekeeper never writes feelings; the player never rewrites facts. The
paper and the agenda split the player's own two surfaces along the same
status and the agenda split the player's own two surfaces along the same
seam: **how she is (status) vs what she means to do (agenda)** — states
fade with the situation, intentions persist until dropped or evicted.
And if she doesn't file it, it's not in her files — records reflect what
@@ -270,7 +270,7 @@ gates it. The boutique's keeper has her card index on the shop PC
tool refuses queries and record ops when the flag is off, and the rendered
views tell the model the current truth. Unlocking mid-story is a narrative
act: narrate the discovery (the salvaged manifest), flip the flag,
re-render — the next window and the next housekeeping both see it.
re-render — the next session and the next housekeeping both see it.
The query discipline is an instruction test in itself: queries must be
narrow (what this beat needs, not a fishing expedition), and **a miss is a
@@ -330,7 +330,7 @@ sessions are not the character's memory; the rings are.
## What's being tested
The adjudication isn't a number — it's a review. Read the window as a
The adjudication isn't a number — it's a review. Read the session as a
story and write what works and what doesn't, as a reader would: the
classic trap is trying to arrive at an objective value for a creative
piece, and a score — holistic or otherwise — is still that trap. The
@@ -343,7 +343,7 @@ noticing what the list can't; that's how the list grows. The
fiction-only story render is the reading surface: machinery seams show
as prose seams.
After N windows, grade against:
After N sessions, grade against:
1. **Classification quality** — the housekeeper's A/B calls; spot-check
against the log and the transcript.
@@ -357,7 +357,7 @@ After N windows, grade against:
touching things never mentioned, promoting noise — are the model's
errors and the real observable.)
5. **Availability bias incidents** — quiet-crucial facts sinking; rescued
or missed? (`status` shows what's sinking.)
or missed? (`report` shows what's sinking.)
6. **Growth curve** — memory should approach the caps asymptotically, not
climb linearly. (`status` per commit.)
7. **Purview discipline** — inventions logged and mostly color-tier; no NPC
@@ -369,7 +369,7 @@ After N windows, grade against:
(records): are customer cards filed, not memorized?
12. **Status maintenance** — excursions declared when leaving baseline and
cleared when returning; baseline shifts track character growth; her
paper stays small. Does her declared status match the transcripts?
status stays small. Does her declared status match the transcripts?
13. **Filing discipline** — cards filed at natural desk moments and kept
current, or dumped and forgotten?
14. **Narrative discipline** — one thing per turn; zero hedged
@@ -399,7 +399,7 @@ a promotion is one changed line, an eviction is one changed line. Diffing
two consecutive dumps reconstructs exactly the operations that were applied,
including overflow and everything in cold storage.
Cross-check it against the window's log: the log is what the housekeeper
Cross-check it against the session's log: the log is what the housekeeper
*declared*, the dump-diff is what *actually happened*. Any disagreement is
either a tool bug or a hand edit — and hand edits have a contract: all
mutations go through the tool, so the dump never drifts. (If you ever poke
@@ -417,11 +417,11 @@ pedantic, whatever housekeeping needs. The two prompts are independent.
**Substrate:** `server/` — a zero-dependency `node:http` service
(`node server/main.mjs [--mock]`), loopback, single-human, synchronous
JSON. Boot-rebuilds open windows from the session logs on start; the
JSON. Boot-rebuilds open sessions from the session logs on start; the
append-only jsonl is the truth, the live context is a view under
policy (thinking never goes back, old tool results elide to stubs —
ask_gm answers never do, a ruling must not vanish — old GM-side
status blocks elide, the current paper rides every GM turn).
status blocks elide, the current status rides every GM turn).
Tool-call pairing is validated before every call. The tool list is
the capability surface: a coin-flip roll and ask_gm always; records
only when the run's gate allows. ask_gm pauses the turn mid-loop —
@@ -432,7 +432,8 @@ reached mock-parity (2026-11-14).
Config: copy `server.example.json` to `server.json` (gitignored) — any
OpenAI-compatible endpoint; put the key in the endpoint's `apiKey`
field or name an env var via `apiKeyEnv`; `models` names the player
and housekeeper defaults, `contextWindow` drives the context meter,
and housekeeper defaults, `contwin` (the context window; the old
`contextWindow` key still accepted) drives the context meter,
`params` is generation-passthrough; a run may carry a model override
in `run.json`. `--mock` runs a scripted fake model that proves the
loop without a key. The SPA is the server plus a fiction-first UI, a
@@ -449,13 +450,13 @@ transcripts — same pattern as the housekeeper, smaller job.
system.md the opening: glossary, purpose, input validation —
the guards tier, per-project, repo-fed at assembly
invariants.md the substrate tier — the mechanical contracts (syntax
markers, tool channels, memory, records, the paper and
markers, tool channels, memory, records, the status and
its gate); repo-fed at assembly, never copied into a
run, travels with the code
handbook.md the craft tier, shipped default — copied into each
run at creation, editable to taste (shape of play,
purview, time skips, content stance, hard limits)
housekeeper.md the wrap prompt — repo-fed at wrap, never copied
housekeeper.md the housekeeping prompt — repo-fed at housekeeping, 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
@@ -467,6 +468,8 @@ reminder.md the per-turn reminder: the turn-composition protocol,
HANDOFF.md working state — where did we leave off, next steps, gotchas
ROADMAP.md SOTA review and steal list, worked point by point
QUESTIONS.md the decision queue — open questions, pending calls
DICTIONARY.md the terms of art — the ruled names, one source of
truth; a rename rules here first, then sweeps
AGENTS.md the agent's own working notes — style lessons, gotchas,
state pointers
config.json the default package
@@ -475,18 +478,18 @@ names-female.txt the name dictionary — one name per line; the new-run
tool/
memory.mjs the clerk: packages, runs, create, save-package, init,
seed, render, apply, insert, delete, revive, file,
amend, discard, search, unarchive, paper, paper-apply,
paper-set, paper-ingest, agenda, agenda-apply,
agenda-set, pick, dump, restore, status
amend, discard, search, unarchive, status, status-apply,
status-set, status-ingest, agenda, agenda-apply,
agenda-set, pick, dump, restore, report
(--run <id>; --owner stamps a run's owner; --gm for
GM writes; --force for migrations; --json for machine
output on packages/runs/status)
output on packages/runs/report)
server/ the substrate: a zero-dependency node:http service
main.mjs entry + REST spine (node server/main.mjs [--mock]);
bearer-token auth on every route (session/claim are
public), ownership gating, per-run activity locks
(turn, ask, turn0, the housekeeping job, fork);
boot-rebuilds open windows from the session logs on
boot-rebuilds open sessions from the session logs on
start; bootstraps the fresh-deployment superuser
invite; the request log and every LLM call carry the
acting user
@@ -497,32 +500,59 @@ server/ the substrate: a zero-dependency node:http service
bundle.mjs run context: prompt assembly (the trio system message,
the GM-message bundle, @ sigils + $ vars), the tool manifest
and its clerk dispatch
session.mjs window lifecycle (open guards, lazy seed + turn-0
session.mjs session lifecycle (open guards, lazy seed + turn-0
ingestion), the append-only typed jsonl, the view
renderer (elision, thinking-strip, pairing check)
loop.mjs the turn loop: ask_gm pause/resume, paper ride and
loop.mjs the turn loop: ask_gm pause/resume, status ride and
delta apply, conflict carry; the scripted mock model
fork.mjs fork: the staged atomic copy with the owner replaced
and the `forked` stamp
clerk.mjs the clerk boundary (every state op via memory.mjs)
housekeeping.mjs the window-close ritual as an async job: transcript
housekeeping.mjs the session-close ritual as an async job: transcript
with labeled thinking, run-state injection, the
housekeeper call, manifest save, apply, autorestart;
rejections hold and surface why
web/ the SPA — no build, vanilla ES modules, path-routed
web/ the SPA — no build, vanilla ES modules, path-routed;
flat modules like server/, views own their state
index.html the shell: claim (invite), home (runs + admin), new
(packages), setup (editor), play (transcript, status
pane, context meter, GM input, ask modal, fork) —
the server serves it for any extensionless path
app.mjs the client: routing, the token session, the setup
editor, register parsing (speech / narration / OOC),
bundle cards, turns, housekeeping polling, spectator
mode
app.mjs the entry: view registration and the token-session
boot — thin
router.mjs path routing + the view lifecycle (enter/leave per
view; the seq race guard; runGone ejection)
client.mjs the REST client: the one fetch choke point (named
client, never api — /api is the server's route
namespace and the static guard matches by prefix)
state.mjs the shared runtime state: me, seq, runId
chrome.mjs the shared page chrome: identity, session info, the
context meter, the busy note, the notice banner
log.mjs the diagnostics event log (sessionStorage, survives
refreshes; the header's "log" button)
widgets.mjs the shared factories: armedButton (the two-click
confirm), paneEditor (the status/agenda pattern),
modelsBox (per-run model selects over the listing)
transcript.mjs register rendering (speech / narration / OOC) and
the session-log entry walk
view-*.mjs one module per view — claim, home, new, setup, play —
each owning its elements, its state, and its wiring
style.css dark, quiet, fiction-first
test/ the mock smoke, kept next to the code
smoke.mjs the 58-step multiuser/agenda/reminder pass against
the --mock server — expects a clean state/, prints
its run ids, leaves a temp token file for the
restart check; clean up state/ and the smoke runs
afterwards
check-reminder.mjs unit-verifies the reminder elision policy (one
live copy, at the freshest end) against a run's
session log
restart-check.mjs after a server restart: the token survives,
unhousekept sessions rebuild, drafts stay intact
server.example.json copy to server.json (gitignored) — bind, endpoint +
key env, models, contextWindow, params passthrough
key env, models, contwin, params passthrough
db/
schema.sql entries, records, paper, agenda, events journal (shared)
schema.sql entries, records, status, agenda, events journal (shared)
state/ per-deployment people + shared packages (gitignored):
deployment.db (users, invites), bootstrap-invite.txt,
packages/ (user-saved, published to everyone)
+34 -34
View File
@@ -61,11 +61,11 @@ long-memory problem is unsolved. Our test aims at that gap.
**the flow is sacred** — anything mechanical rides a structural channel
(tools) or lives outside the flow (housekeeper, GM, watcher);
prompt-nagging mid-flow is the last resort. System-1's natural homes:
(a) GM-side aids — salience pre-pass before wrap, quick oracle,
(a) GM-side aids — salience pre-pass before housekeeping, quick oracle,
transcript review helpers; (b) an auxiliary watcher agent — a cheap
model reading the live session JSONL, flagging touches, stance drift,
and status lag; it proposes, never writes, and its flags become hints
the housekeeper verifies at wrap. Two-speed memory: watcher = salience
the housekeeper verifies at housekeeping. Two-speed memory: watcher = salience
capture (recall), housekeeper = consolidation (precision), GM =
authority. The seam exists: sessions/*.jsonl is the watcher's food.
Player-side missed-update rate becomes a testable observable.
@@ -96,15 +96,15 @@ example, gitignored real file, env-var option).
is the only truth: everything is editable at any time, and the
discipline not to break a running narrative sits with the user/GM.
`packages/` is read exactly once per run, ever. Edits to a copied
file land at the next window-open (no hot reload into an open
window). Packages carry authored content only — `canon/`, `db/`,
file land at the next session-open (no hot reload into an open
session). Packages carry authored content only — `canon/`, `db/`,
`dumps/`, `log/`, `manifests/`, `sessions/` are all state and are
born in the run at creation. The new-game opener file is `turn-0.md`
(renamed from `prelude.md`, 2026-11-13) — the GM's zeroth turn, same
semantics: sent once as the first GM message, `<status>` block
ingested.
- **The seed is initial state of the run.** `seed.json` rides the copy
like any other file. It applies lazily at the first window-open of a
like any other file. It applies lazily at the first session-open of a
fresh run, before render and bundle assembly; until then the run is
freely editable — deleting or editing `seed.json` in the copy is the
generic opt-out, no flag. After application it is inert provenance:
@@ -115,7 +115,7 @@ example, gitignored real file, env-var option).
from the list. A run may carry per-run overrides for both roles
(`run.json` `models: {player, housekeeper}`, wired in the SPA
2026-11-14 — setup for drafts, the play aside for started runs;
each call resolves fresh, so a mid-window switch takes the next
each call resolves fresh, so a mid-session switch takes the next
turn) — the comparison rig: same package, different models,
identical prompts. Which model the housekeeper DEFAULT points at
stays open (#16); the mechanism is settled.
@@ -126,8 +126,8 @@ example, gitignored real file, env-var option).
copied, travels with the code: the syntax markers the renderer
parses registers by (plain = speech, *italic* = narration,
single-paren OOC), the tool-channel contract, the memory contract,
records availability via the tool list, the paper tag transport
(`<status>`/`<gained>`/`<lost>`/`<conflict>`) **and the paper's
records availability via the tool list, the status tag transport
(`<status>`/`<gained>`/`<lost>`/`<conflict>`) **and the status's
three-part admission gate** (moved into the substrate tier in the
GM's cut). Implementation-agnostic by design: storage details
unimportant, the tool manifest is self-describing.
@@ -150,7 +150,7 @@ example, gitignored real file, env-var option).
substrate reach existing runs; craft edits are per-run. The GM's cut
also resolved the OOC syntax conflict (system.md no longer teaches
`((double parens))`).
Amendment (GM, 2026-11-14): `housekeeper.md` is repo-fed at wrap,
Amendment (GM, 2026-11-14): `housekeeper.md` is repo-fed at housekeeping,
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`
@@ -158,8 +158,8 @@ example, gitignored real file, env-var option).
`housekeeper.md` never enters the bundle — it prompts the separate
internal housekeeper agent.
- **The audit moved into the run.** Runs are gitignored, so the
commit-per-wrap ritual is retired. At apply time the clerk snapshots
`dumps/w<N>.sql`; post-wrap review is async — the window log against
commit-per-pass ritual is retired. At apply time the clerk snapshots
`dumps/w<N>.sql`; post-apply review is async — the session log against
the snapshot diff. Provenance of what the model was sent is the
session jsonl (it logs the as-sent bundle); the canon views are
regenerated state, not provenance. A run may later self-version
@@ -255,17 +255,17 @@ without running anything locally.
is in-memory and rebuilt from the jsonl on boot (messages, elision
view, pending ask_gm). The log is truth, the context is a view.
- **Single human: loopback bind, no cookies, no auth.** One active
window *per run* (amended 2026-11-13) — several runs may hold live
windows; nothing runs concurrently in practice, and API-driven tests
can proceed alongside a real window.
session *per run* (amended 2026-11-13) — several runs may hold live
sessions; nothing runs concurrently in practice, and API-driven tests
can proceed alongside a real session.
- **ask_gm surfaces as a modal**; the pending question survives a
browser refresh (the server holds the pause, the SPA re-presents it).
- **Status rides the GM turns.** The full paper is attached to every
- **Status rides the GM turns.** The full status is attached to every
GM turn as a `<status>` block — reads are state, writes are deltas:
the player mutates with `<lost>`/`<gained>` tags in its own turn,
exact-match, non-blocking, misses relayed back via `<conflict>`. Old
status blocks elide from the live context view like old tool results;
the log keeps them all. The initial paper rides the prelude, ingested
the log keeps them all. The initial status rides the prelude, ingested
at new-game. GM turns never carry deltas; GM override stays
out-of-band.
- **Status pane always visible** — the current description set, live;
@@ -280,15 +280,15 @@ without running anything locally.
phase 0); the housekeeping transcript labels them as `[thinking]`
attention evidence for touch/adjudication.
- **Context meter always visible, loud past 85%.** Exact, from the last
response's `usage.prompt_tokens` against a `contextWindow` value in
response's `usage.prompt_tokens` against a `contwin` value in
server.json. The 100% endgame is close-and-housekeep.
- **Housekeeping is the window-close ritual, and it autorestarts.** A
- **Housekeeping is the session-close ritual, and it autorestarts.** A
run always ends the session — "any time" means the GM may close a
window early, not that housekeeping is a mid-session action. The
session early, not that housekeeping is a mid-session action. The
chain runs unattended: housekeeper -> manifest -> apply -> next
window opens with fresh views. Review is async, via the log and the
session opens with fresh views. Review is async, via the log and the
dump diff; GM edits and vetoes remain available through the clerk at
any time, including mid-next-window. A rejected manifest holds the
any time, including mid-next-session. A rejected manifest holds the
restart and surfaces the reason for a re-run.
- **Rewrite-here, not forks.** An unfortunate GM turn is edited and the
session restarts from there — all turns since are lost from the live
@@ -380,26 +380,26 @@ API sketch (the operable spine, amended per-run):
GET /api/packages list presets (display name, pc default, records gate, turn-0, seed)
GET /api/prompts the repo-fed prompts (system, invariants) — read-only
GET /api/names roll an unused dictionary name for a new main character
GET /api/runs list runs (display "La Caramba / Rell", fill, open window, draft/housekept state)
GET /api/runs list runs (display "La Caramba / Rell", fill, open session, 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>/turn0 send turn-0 as the first GM turn (fresh window)
POST /api/runs/<id>/sessions open a session (lazy seed, render, assemble)
POST /api/runs/<id>/turn0 send turn-0 as the first GM turn (fresh session)
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
POST /api/runs/<id>/turn GM line -> runs the loop
POST /api/runs/<id>/ask answer a pending ask_gm
GET /api/runs/<id>/status the status tier, structured
POST /api/runs/<id>/paper GM override: replace the whole paper (empty = clear)
POST /api/runs/<id>/status GM override: replace the whole status (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 session), 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/log latest window log
GET /api/runs/<id>/housekeeping/log latest session log
POST /api/runs/<id>/housekeeping/apply apply a manifest directly
## The steal list (work point by point)
@@ -426,7 +426,7 @@ the substrate.
The Author's Note / `@@depth` / `post_history_instructions` pattern:
instructions placed after history get better adherence. Folded into the
SPA v1 substrate — superseded by the status redesign (QUESTIONS #17):
the full paper rides every GM turn as a `<status>` block; reads are
the full status rides every GM turn as a `<status>` block; reads are
state, writes are deltas (`<lost>`/`<gained>`). Old blocks elide from
the live context view like old tool results; the log keeps every
as-sent block (provenance, rewrite snapshots, status evolution for
@@ -475,8 +475,8 @@ Status: OPEN (low priority).
### 10. Mid-session housekeeping trigger — DEFERRED
Talemate summarizes on token thresholds; Letta dreams on compaction.
Our housekeeping is per-window; a marathon session has no relief valve.
Current answer: close the window. Fine for the test; revisit if real
Our housekeeping is per-session; a marathon session has no relief valve.
Current answer: close the session. Fine for the test; revisit if real
sessions regularly overflow.
Status: DEFERRED.
@@ -487,11 +487,11 @@ protocol extracted into `reminder.md` (repo-shared, never copied into
a run). It rides after the GM's prose as its own `role: system`
session chunk on every turn; superseded copies elide from the live
view, so exactly one exists, always at the freshest position — the
same single-copy policy as the papers. Absent/empty file = no ride
same single-copy policy as the riding blocks. Absent/empty file = no ride
(the feature sleeps). The measured trigger arrived first: observable
#14's completions lengthening across window one. The reminder is now
the experiment: does the lengthening flatten with it in the window.
Housekeeping never sees it (fresh context per wrap); the SPA shows one
#14's completions lengthening across session one. The reminder is now
the experiment: does the lengthening flatten with it in the session.
Housekeeping never sees it (a fresh context each pass); the SPA shows one
collapsed card for the newest copy, mirroring the policy.
Status: DONE (content is the GM's, extracted from the handbook — the
duplicate handbook cut is the GM's red pen).
+10 -10
View File
@@ -27,25 +27,25 @@ CREATE TABLE IF NOT EXISTS records (
created TEXT NOT NULL
);
-- the player's piece of paper: freeform descriptions of her immediate
-- her status: freeform descriptions of her immediate
-- situation, admitted by the three-part gate (non-normal, acute,
-- turn-affecting). No keys, no baselines — just what's true right now.
-- the player mutates it with <lost>/<gained> deltas (exact match);
-- the GM overrides out-of-band. Descriptions never contain commas:
-- both the delta lists and the <status> block are comma-separated.
CREATE TABLE IF NOT EXISTS paper (
CREATE TABLE IF NOT EXISTS status (
id INTEGER PRIMARY KEY AUTOINCREMENT,
descr TEXT NOT NULL UNIQUE,
added TEXT NOT NULL
);
-- her agenda: the hot queue of what drives her — intentions, not
-- states (those live on the paper). Id order IS queue order:
-- states (those live in her status). Id order IS queue order:
-- newest-added at the top, the bottom evicted on overflow — a recency
-- ring buffer for free. The player mutates it with <add>/<drop>
-- deltas (comma-separated adds, index-based drops); the GM overrides
-- with agenda-set. Items never contain commas: the add transport is
-- comma-separated, same as the paper's descriptions.
-- comma-separated, same as the status descriptions.
CREATE TABLE IF NOT EXISTS agenda (
id INTEGER PRIMARY KEY AUTOINCREMENT,
descr TEXT NOT NULL UNIQUE,
@@ -53,18 +53,18 @@ CREATE TABLE IF NOT EXISTS agenda (
);
-- append-only audit journal; nothing here is ever updated or deleted.
-- target is 'e<id>' for entries, 'r<id>' for records, 'p<id>' for paper
-- rows, 'paper' for whole-paper replaces.
-- target is 'e<id>' for entries, 'r<id>' for records, 'p<id>' for status
-- rows, 'p' for whole-status replaces.
-- prior captures the replaced state of a journaled mutator (the saga
-- rule): amend/discard carry the old record content, paper ops carry
-- rule): amend/discard carry the old record content, status ops carry
-- what was lost — so turn surgery can compensate mechanically.
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
window TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')),
session TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status-add', 'status-drop', 'status-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS events_window ON events (window);
CREATE INDEX IF NOT EXISTS events_session ON events (session);
+5 -5
View File
@@ -46,7 +46,7 @@ detail carries the memory.
```json
{
"window": "short-slug",
"session": "short-slug",
"summary": "one short paragraph on what happened",
"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" }
@@ -62,7 +62,7 @@ detail carries the memory.
}
```
Every key except `window` and `summary` is optional — empty or
Every key except `session` and `summary` is optional — empty or
omitted is fine. Types are `place`, `person`, `fact`, `thread`. Ids come
from the rendered views; never invent one. When something happened —
before, after, how long ago — belongs in the *detail prose* in the
@@ -132,14 +132,14 @@ mechanics for you. Don't list an id twice across operations.
("I suspect Marta knew"). Wrong facts in memory are worse than no
facts: an entry that later turns out false is a retcon. In a story full
of liars and mysteries, attributed claims are the only safe facts.
- Rings hold **facts, never her feelings**. Her paper holds acute
- Rings hold **facts, never her feelings**. Her status holds acute
states, and it is entirely hers — you never write it. A relational
shift is not a stance to record: write the fact behind it ("Marta
lied about the radio" — attributed per the testimony rule), and the
stance stays in the prose. Watch the paper across the session: when
stance stays in the prose. Watch her status across the session: when
a non-normal state has become her new normal, place the drift —
record it as a fact if it belongs in memory, or propose a card edit
in open questions if it is identity. If her paper contradicts the
in open questions if it is identity. If her status contradicts the
session you just read, flag it.
- `character.md` (identity) is the GM's too. If identity or drives have
shifted, propose an amendment in open questions; never edit the sheet
+8 -8
View File
@@ -40,7 +40,7 @@ You have to at least mention working with records in the story, like "*Alice che
don't include record-keeping verbs, your character is unable to offload memory on any media for some reason (usually obvious from
the story itself). If your character develops a need to do so, play it out. If you think your character should have access, ask GM.
# Player's paper
# Character's status
Attached to the GM's turns you receive a `<status>` block, its purpose is a compact reminder of your character's immediate situation.
You should keep it aligned with the story. When your turn changes the status, append tokens to add or remove inside `<gained>`
@@ -55,7 +55,7 @@ Phew, thanks a bunch. Got a fag?
<gained>craving a smoke</gained>
```
What belongs on the paper passes a three-part gate. A token must be:
What belongs in the status passes a three-part gate. A token must be:
1. **outside broad normality** for your character — the ordinary is never listed;
2. something your character is **acutely aware of** right now;
@@ -63,17 +63,17 @@ What belongs on the paper passes a three-part gate. A token must be:
Bored, shivering, proud, ashamed, naked, hungry, cuffed, on edge, craves a smoke, afterglow, full bladder, barefoot, in pain — all pass.
Warm (when the weather is warm), liking puppies, being on the pill — none do: normal, ambient, or chronic. If the prose already carries it
clearly, leave it off the paper. There is no exhaustive inventory of possible tokens, all listed are examples.
clearly, leave it off. There is no exhaustive inventory of possible tokens, all listed are examples.
What stops being true leaves the paper the turn it stops. If a non-normal state becomes the new normal, stop listing it
What stops being true leaves the status the turn it stops. If a non-normal state becomes the new normal, stop listing it
(example: the character is always sweaty in this climate now).
What can't be expressed as a status token doesn't belong on the paper. "Trusts Marta less" is not a status, it gets established
in the prose or derived from memory. For contrast, "suspicious" is a status token when your character does feel this way.
What can't be expressed as a status token doesn't belong in the status. "Trusts Marta less" gets established in the prose or derived
from memory. For contrast, "suspicious" is a status token when your character does feel this way.
# Player's agenda
# Character's agenda
A very similar `<agenda>` block has the same lifecycle, but different purpose. Your verbs to edit it are `<add>` and `<drop>`. Instead of
A similar `<agenda>` block has the same lifecycle, but different purpose. Your verbs to edit it are `<add>` and `<drop>`. Instead of
the current situation, it should hold goals that your character is working towards right now. This isn't a storage space for detailed plans,
it's the hot view of what drives the character. The goals may be long term, but they should represent what's currently on the mind.
+1 -1
View File
@@ -40,7 +40,7 @@ GM can't skip a turn. GM can't put a turn inside your turn. End dialogue when th
Dialogue goes verbatim, thoughts and actions require narration. Decorate the turn with additional flavour when it seems appropriate.
## Adjust your papers
## Adjust your cache
Your status and agenda blocks keep their contents between your turns. Now that you know what your turn describes, add and remove items from
both lists to make them reflect the new reality your turn creates.
+1 -1
View File
@@ -8,6 +8,6 @@
"player": "glm-5.3",
"housekeeper": "glm-5.3"
},
"contextWindow": 262144,
"contwin": 262144,
"params": {}
}
+2 -2
View File
@@ -7,7 +7,7 @@
// lands staged under a dot-name and is swapped in by a same-volume
// rename, which is atomic — no reader ever sees a half-run. The
// caller holds the source run's activity lock, so the copy is never
// taken mid-turn; a copied open window reopens honestly in the fork
// taken mid-turn; a copied open session reopens honestly in the fork
// (the log is the truth, same as boot-rebuild).
import fs from 'node:fs';
import path from 'node:path';
@@ -34,7 +34,7 @@ export function forkRun(ctx, srcId, user) {
meta.forked = Math.floor(Date.now() / 1000); // unixtime, UTC by definition
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
fs.renameSync(staging, path.join(RUNS_DIR, id)); // same-volume rename: the atomic swap-in
// an open, unhousekept window in the source is an open window in the
// an open, unhousekept session in the source is an open session in the
// fork — its transcript reaches the fork's rings only after the fork
// housekeeps it, same rule as the original
const latest = latestSession(id);
+19 -19
View File
@@ -1,11 +1,11 @@
// server/housekeeping.mjs — the window-close ritual, as an async job.
// server/housekeeping.mjs — the session-close ritual, as an async job.
//
// The chain, unattended: render the transcript -> invoke the
// housekeeper on a fresh context (its prompt, run state, the card, the
// backdrop, both ring views, the transcript with labeled thinking) ->
// save the manifest -> apply via the clerk (which validates, writes
// the window log, snapshots the dump) -> mark the session housekept ->
// autorestart: a fresh window opens with fresh views. A rejection at
// the session log, snapshots the dump) -> mark the session housekept ->
// autorestart: a fresh session opens with fresh views. A rejection at
// any step holds the restart and surfaces why; the manifest (or the
// raw output, if unparseable) stays on disk for a hand edit and
// POST .../housekeeping/apply.
@@ -14,7 +14,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { clerk } from './clerk.mjs';
import { runDir, requireRun, readSettings, expandVars } from './bundle.mjs';
import { openWindow, markHousekept, latestSession, lastHousekept } from './session.mjs';
import { openSession, markHousekept, latestSession, lastHousekept } from './session.mjs';
import { HttpError } from './loop.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -51,14 +51,14 @@ export function renderTranscript(lines) {
continue;
}
if (e.t === 'note') {
if (e.kind === 'paper') {
L.push(`[paper] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
if (e.kind === 'status') {
L.push(`[status] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
} else if (e.kind === 'agenda') {
L.push(`[agenda] added: ${JSON.stringify(e.applied?.added ?? [])}, dropped: ${JSON.stringify(e.applied?.dropped ?? [])}, evicted: ${JSON.stringify(e.applied?.evicted ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, '');
} else if (e.kind === 'ask') {
L.push(`[ask_gm pending] ${e.question}`, '');
} else if (e.kind === 'window') {
L.push(`[window opened ${e.at}${e.fresh ? ' — fresh' : ''}]`, '');
} else if (e.kind === 'session') {
L.push(`[session opened ${e.at}${e.fresh ? ' — fresh' : ''}]`, '');
} else if (e.kind === 'seed' || e.kind === 'ingest') {
L.push(`[${e.kind}] ${e.ok ? 'ok' : 'failed'}: ${e.detail}`, '');
}
@@ -106,13 +106,13 @@ export function parseManifest(text) {
export function trigger(ctx, runId, user) {
requireRun(runId);
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for '${runId}' — housekeeping is the window-close ritual`);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it before closing the window');
ctx.sessions.delete(runId); // the window is closed from here on
if (!s) throw new HttpError(409, `no open session for '${runId}' — housekeeping is the session-close ritual`);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it before closing the session');
ctx.sessions.delete(runId); // the session is closed from here on
const job = { state: 'running', session: s.stamp, started: new Date().toISOString() };
ctx.jobs.set(runId, job);
// the whole async chain holds the run's activity lock — a fork
// enqueued behind it copies the post-wrap state, never a half-apply
// enqueued behind it copies the post-apply state, never a half-apply
ctx.enqueue(runId, () => runJob(ctx, runId, s.stamp, s.lines, user));
return job;
}
@@ -136,7 +136,7 @@ async function runJob(ctx, runId, stamp, lines, user) {
fs.writeFileSync(manifestPath, JSON.stringify(mf, null, 2) + '\n');
job.manifest = `manifests/${stamp}.json`;
const next = applyAndRestart(ctx, runId, manifestPath, stamp);
job.window = mf.window;
job.session = mf.session;
job.next = next.stamp;
job.state = 'applied';
} catch (e) {
@@ -165,7 +165,7 @@ export function applyAndRestart(ctx, runId, manifestPath, sessionStamp) {
const r = clerk(runId, 'apply', manifestPath);
if (r.code !== 0) throw new Error(`apply rejected:\n${r.err || r.out}`);
markHousekept(runId, sessionStamp);
const s = openWindow(runId); // the #21 guard passes now
const s = openSession(runId); // the #21 guard passes now
ctx.sessions.set(runId, s);
return s;
}
@@ -184,11 +184,11 @@ export function jobState(ctx, runId) {
export function latestLog(runId) {
const dir = path.join(runDir(runId), 'log');
if (!fs.existsSync(dir)) throw new HttpError(404, 'no window logs yet');
if (!fs.existsSync(dir)) throw new HttpError(404, 'no session logs yet');
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
if (!files.length) throw new HttpError(404, 'no window logs yet');
if (!files.length) throw new HttpError(404, 'no session logs yet');
const f = files[files.length - 1];
return { window: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
return { session: f.replace(/\.md$/, '', ''), content: fs.readFileSync(path.join(dir, f), 'utf8') };
}
// --- the mock housekeeper ----------------------------------------------------
@@ -198,8 +198,8 @@ export function latestLog(runId) {
// ring-B memory. Exercises the whole chain without a key.
function mockManifest(stamp) {
return JSON.stringify({
window: stamp.toLowerCase(),
summary: 'Mock wrap: she left the container, crossed the hot sand and entered the dark hold.',
session: stamp.toLowerCase(),
summary: 'Mock housekeeping: she left the container, crossed the hot sand and entered the dark hold.',
touch: [{ id: 'e1', reason: 'the cuffs shaped every move she made' }],
insert: [{
ring: 'b', type: 'place', label: 'The dark hold',
+11 -11
View File
@@ -3,7 +3,7 @@
// Synchronous REST: a POST runs the tool loop and returns. ask_gm
// pauses mid-turn — the whole tool-call batch waits (pairing stays
// sound), the request returns with the pending question, and the
// answer call resumes the loop. The paper is re-read from the clerk
// answer call resumes the loop. The status is re-read from the clerk
// before every GM turn and rides it as a <status> block; the player's
// <lost>/<gained> deltas apply after its final message, and any
// conflicts ride the next GM turn as a <conflict> block.
@@ -23,18 +23,18 @@ export class HttpError extends Error {
function needSession(ctx, runId) {
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for run '${runId}' — POST /api/runs/${runId}/windows first`);
if (!s) throw new HttpError(409, `no open session for run '${runId}' — POST /api/runs/${runId}/sessions first`);
return s;
}
export async function gmTurn(ctx, runId, line, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
const paper = clerkJson(runId, 'paper'); // fresh per turn
const status = clerkJson(runId, 'status'); // fresh per turn
const agenda = clerkJson(runId, 'agenda'); // fresh per turn
// the wire renders the queue as the model cites it: numbered from the top
const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; ');
const content = `${line.trim()}\n\n<status>${paper.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
const content = `${line.trim()}\n\n<status>${status.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
s.append({ t: 'msg', m: { role: 'user', content } });
// the reminder follows the GM's prose as its own system chunk —
// every turn, one live copy (older ones elide in the view)
@@ -44,9 +44,9 @@ export async function gmTurn(ctx, runId, line, user) {
}
// 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
// the bundle (start = open session, then this). Its trailing <status>
// block was ingested as her opening status at session-open — stripped
// here, since the normal ride carries the current status on every GM
// turn, the beat included.
export async function turn0(ctx, runId, user) {
const s = needSession(ctx, runId);
@@ -118,15 +118,15 @@ async function runLoop(ctx, runId, user) {
continue; // let the model see the results before ending its turn
}
// final player message — the paper and agenda deltas ride the turn
// final player message — the status and agenda deltas ride the turn
// text. Same-verb blocks combine into one apply (the clerk's
// collectors gather every block before executing anything), never a
// sequence of applies.
const text = msg.content ?? '';
const carry = [];
if (/<(lost|gained)>/.test(text)) {
const r = clerkJson(runId, 'paper-apply', text);
s.append({ t: 'note', kind: 'paper', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
const r = clerkJson(runId, 'status-apply', text);
s.append({ t: 'note', kind: 'status', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
carry.push(...(r.conflicts ?? []));
}
if (/<(add|drop)>/.test(text)) {
@@ -157,7 +157,7 @@ function resolveModel(ctx, runId) {
//
// A scripted stand-in that exercises the loop without a key: turn one
// rolls, turn two asks (the pause/resume path), the answer lands with
// paper deltas (the tag transport), everything after is plain prose.
// status deltas (the tag transport), everything after is plain prose.
function mockModel(s, view) {
const call = (name, args, id) => ({
role: 'assistant',
+38 -37
View File
@@ -4,7 +4,7 @@
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
// window back from the jsonl — the log is the truth, the context is a
// session back from the jsonl — the log is the truth, the context is a
// view.
//
// usage: node server/main.mjs [--mock]
@@ -30,6 +30,7 @@ if (!fs.existsSync(CONFIG_PATH)) {
process.exit(1);
}
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
if (cfg.contextWindow && !cfg.contwin) console.warn('config: contextWindow was renamed to contwin - the meter stays null until fixed');
const provider = makeProvider(cfg.endpoint ?? {});
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
@@ -38,7 +39,7 @@ const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), r
// Serializes every async mutation span (turn, ask, turn0, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (paper-set, file writes) need no lock: they
// Sync-only handlers (status-set, file writes) need no lock: they
// block the event loop and are atomic by construction.
ctx.locks = new Map();
ctx.enqueue = (runId, fn) => {
@@ -197,7 +198,7 @@ route('GET', '/api/users', async ({ user }) => {
// revocation destroys the identity: the token dies with the row. Their
// runs and packages stay on disk untouched — the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open windows close.
// read. Only the live map is reconciled: their open sessions close.
route('POST', '/api/users/:id/revoke', async ({ params, user }) => {
requireSuperuser(user);
if (params.id === user.id) throw new HttpError(409, 'revoking yourself would lock the deployment out of its superuser');
@@ -235,9 +236,9 @@ function requireOwner(user, runId) {
// --- routes -------------------------------------------------------------------
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 })),
service: 'rp-test', mock: MOCK, openSessions: ctx.sessions.size,
// the live session inventory — debugging state divergence at a glance
sessions: [...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()));
@@ -280,14 +281,14 @@ route('GET', '/api/prompts', async () => {
});
// the clerk's list, enriched with what the server already knows: the
// open window, the pending ask, and the housekeeping bookkeeping. A
// open session, 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.session = s?.stamp ?? null;
r.fresh = s?.fresh ?? false;
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
@@ -325,7 +326,7 @@ route('GET', '/api/names', async () => {
route('GET', '/api/runs/:id', async ({ params }) => {
const id = params.id;
bundle.requireRun(id);
const st = clerkJson(id, '--json', 'status');
const st = clerkJson(id, '--json', 'report');
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
@@ -344,9 +345,9 @@ route('GET', '/api/runs/:id', async ({ params }) => {
open: !!s,
draft: session.latestSession(id) === null,
lastSession: session.latestSession(id),
window: s?.stamp ?? null,
session: s?.stamp ?? null,
fresh: s?.fresh ?? false,
paper: st.paper,
status: st.status,
agenda: st.agenda,
records: st.records,
fill: st.rings,
@@ -355,8 +356,8 @@ route('GET', '/api/runs/:id', async ({ params }) => {
usage: s?.usage ?? null,
context: s?.usage ? {
used: s.usage.promptTokens,
window: cfg.contextWindow ?? null,
pct: cfg.contextWindow ? Math.round((100 * s.usage.promptTokens) / cfg.contextWindow) : null,
contwin: cfg.contwin ?? null,
pct: cfg.contwin ? Math.round((100 * s.usage.promptTokens) / cfg.contwin) : null,
} : null,
};
});
@@ -365,7 +366,7 @@ route('GET', '/api/runs/:id', async ({ params }) => {
//
// 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
// internal (repo-fed at housekeeping, 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.
@@ -427,7 +428,7 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
// the run's models: per-run overrides of the deployment defaults
// (server.json), selected from the upstream listing (GET /api/models).
// Owner-only, changeable at any time — every call resolves fresh, so a
// mid-window switch simply takes the next turn. null clears a role
// mid-session switch simply takes the next turn. null clears a role
// back to its deployment default.
route('POST', '/api/runs/:id/model', async ({ params, body, user }) => {
const id = params.id;
@@ -482,14 +483,14 @@ route('DELETE', '/api/runs/:id', async ({ params, user }) => {
return { ok: true, deleted: params.id };
});
route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
const s = session.openWindow(id, body.override === true);
if (ctx.sessions.has(id)) throw new HttpError(409, `a session is already open for '${id}' — one active session per run`);
const s = session.openSession(id, body.override === true);
ctx.sessions.set(id, s);
return {
window: s.stamp,
session: s.stamp,
fresh: s.fresh,
notes: s.lines.filter((e) => e.t === 'note').map((e) => ({ kind: e.kind, ok: e.ok, detail: e.detail })),
};
@@ -497,10 +498,10 @@ route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
route('GET', '/api/runs/:id/session', async ({ params }) => {
const s = ctx.sessions.get(params.id);
if (!s) throw new HttpError(404, `no open window for '${params.id}'`);
if (!s) throw new HttpError(404, `no open session for '${params.id}'`);
return {
run: params.id,
window: s.stamp,
session: s.stamp,
entries: s.lines,
pendingAsk: s.pendingAsk?.question ?? null,
usage: s.usage,
@@ -515,7 +516,7 @@ route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
});
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
// fresh session — "start" is this right after session-open
route('POST', '/api/runs/:id/turn0', async ({ params, user }) => {
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => turn0(ctx, params.id, user))) };
@@ -538,25 +539,25 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
route('GET', '/api/runs/:id/status', async ({ params }) => {
bundle.requireRun(params.id);
return { paper: clerkJson(params.id, 'paper'), agenda: clerkJson(params.id, 'agenda') };
return { status: clerkJson(params.id, 'status'), agenda: clerkJson(params.id, 'agenda') };
});
// the GM's out-of-band paper override: whole-paper replace via the
// the GM's out-of-band status override: whole-status 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, user }) => {
route('POST', '/api/runs/:id/status', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, 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');
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the status');
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 };
const status = clerkJson(id, '--gm', 'status-set', ...items);
return { ok: true, status };
});
// the GM's out-of-band agenda override: whole-queue replace via the
@@ -578,17 +579,17 @@ route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
});
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// ends the window and kicks the async chain; poll GET for the outcome
// ends the session and kicks the async chain; poll GET for the outcome
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
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
// assembly the real housekeeping uses, a real housekeeper call, the manifest
// saved for review — but nothing applied, no session ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
// without playing more; works on the open session too.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
@@ -626,21 +627,21 @@ route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeepin
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open window, marks the latest session housekept, autorestarts
// any open session, marks the latest session housekept, autorestarts
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const file = String(body.file ?? '').trim();
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json');
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<session>.json');
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
if (!manifestPath.startsWith(path.join(ROOT, 'runs', id))) throw new HttpError(400, 'file must stay inside the run dir');
if (!fs.existsSync(manifestPath)) throw new HttpError(404, `no such manifest: ${file}`);
const latest = session.latestSession(id);
if (!latest) throw new HttpError(409, 'no session to mark housekept');
ctx.sessions.delete(id); // housekeeping always ends the window
ctx.sessions.delete(id); // housekeeping always ends the session
try {
const next = housekeeping.applyAndRestart(ctx, id, manifestPath, latest);
return { ok: true, housekept: latest, window: next.stamp };
return { ok: true, housekept: latest, session: next.stamp };
} catch (e) {
const job = { state: 'rejected', session: latest, reason: e.message };
ctx.jobs.set(id, job);
@@ -689,5 +690,5 @@ const server = http.createServer(async (req, res) => {
const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':');
server.listen(Number(port), host, () => {
console.log(`rp-test server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} window(s) rebuilt`);
console.log(`rp-test server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt`);
});
+11 -11
View File
@@ -1,4 +1,4 @@
// server/session.mjs — a window's live state.
// server/session.mjs — a session's live state.
//
// The append-only jsonl is the truth; the in-memory context is a view
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
@@ -6,7 +6,7 @@
// without a format migration. The view renderer is pure policy over
// the log: thinking never goes back, old tool results elide to stubs
// (the last few and every ask_gm answer stay), old GM-side
// <status>/<conflict> blocks elide — the current paper rides the
// <status>/<conflict> blocks elide — the current status rides the
// newest GM turn.
import fs from 'node:fs';
import path from 'node:path';
@@ -62,16 +62,16 @@ function makeSession(runId, st) {
};
}
// --- open a window -----------------------------------------------------------
// --- open a session -----------------------------------------------------------
// The #21 guard: opening over an unhousekept session means that
// transcript never reaches the rings — refuse and name it, unless the
// caller explicitly overrides (the deliberate skip).
export function openWindow(runId, override = false) {
export function openSession(runId, override = false) {
requireRun(runId);
const latest = latestSession(runId);
if (latest && latest !== (readState(runId).lastHousekeptSession ?? null) && !override) {
const err = new Error(`the previous window (${latest}) was never housekept — its transcript would never reach the rings`);
const err = new Error(`the previous session (${latest}) was never housekept — its transcript would never reach the rings`);
err.status = 409;
err.detail = { session: latest, hint: 'housekeep it first, or POST with {"override": true} to deliberately skip it' };
throw err;
@@ -80,7 +80,7 @@ export function openWindow(runId, override = false) {
const notes = [];
const fresh = latest === null;
if (fresh) {
// lazy seed: applies at the first window-open, before render and
// lazy seed: applies at the first session-open, before render and
// assembly, so the bundle sees populated rings. The clerk refuses
// on history (a hand-prepped run), which is the opt-out.
if (fs.existsSync(path.join(runDir(runId), 'seed.json'))) {
@@ -88,7 +88,7 @@ export function openWindow(runId, override = false) {
notes.push({ kind: 'seed', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
if (fs.existsSync(path.join(runDir(runId), 'turn-0.md'))) {
const r = clerkTry(runId, 'paper-ingest', path.join(runDir(runId), 'turn-0.md'));
const r = clerkTry(runId, 'status-ingest', path.join(runDir(runId), 'turn-0.md'));
notes.push({ kind: 'ingest', ok: r.code === 0, detail: (r.code === 0 ? r.out : r.err).split('\n')[0] });
}
}
@@ -107,7 +107,7 @@ export function openWindow(runId, override = false) {
const s = makeSession(runId, stamp());
s.fresh = fresh;
fs.mkdirSync(sessionsDir(runId), { recursive: true });
s.append({ t: 'note', kind: 'window', at: s.stamp, fresh });
s.append({ t: 'note', kind: 'session', at: s.stamp, fresh });
for (const n of notes) s.append({ t: 'note', kind: n.kind, ok: n.ok, detail: n.detail });
s.append({ t: 'bundle', m: system, part: 'system' });
for (let i = 0; i < bundle.length; i++) s.append({ t: 'bundle', m: bundle[i], part: partNames[i] });
@@ -132,7 +132,7 @@ export function loadSession(runId, st) {
}
}
derive(s);
// fresh survives a restart: this window is the run's first iff no
// fresh survives a restart: this session 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`;
@@ -182,7 +182,7 @@ export function renderView(s, keepToolResults = 4) {
if (e.reminder) {
// the per-turn reminder: only the newest copy lives in the
// context — superseded ones elide (identical content, freshest
// position, exactly like the papers)
// position, exactly like the status/agenda blocks)
if (i === newestReminder) msgs.push({ role: 'system', content: e.m.content.trim() });
} else if (e.m.role === 'assistant') {
// thinking never goes back; the log keeps it
@@ -196,7 +196,7 @@ export function renderView(s, keepToolResults = 4) {
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else if (i === lastGmIdx) {
// the newest GM turn keeps its blocks as-sent: the current
// paper and agenda ride it
// status and agenda ride it
msgs.push({ role: e.m.role, content: e.m.content.trim() });
} else {
// older GM turns: status/agenda/conflict blocks elide
+34
View File
@@ -0,0 +1,34 @@
// test/check-reminder.mjs — unit-verifies the reminder elision
// policy: the live context carries exactly one reminder (the newest),
// sitting at the freshest end, next to the one system trio from the
// bundle. Run against a run id that has GM turns:
// node test/check-reminder.mjs <runId>
import { loadSession, renderView } from '../server/session.mjs';
import { readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const runId = process.argv[2];
const dir = join(ROOT, 'runs', runId, 'sessions');
const latest = readdirSync(dir).filter((f) => f.endsWith('.jsonl')).sort().pop().replace(/\.jsonl$/, '');
const s = loadSession(runId, latest);
const view = renderView(s);
const sys = view.filter((m) => m.role === 'system');
let fails = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
if (!cond) fails++;
};
const logged = s.lines.filter((e) => e.reminder).length;
ok(`log keeps every copy (${logged})`, logged >= 5, `${logged}`);
ok('view carries exactly two system chunks (the trio + the newest reminder)', sys.length === 2, `${sys.length}`);
// mid-call the reminder is the last message; after the model's reply it
// sits immediately before that reply — either way it follows the newest
// GM turn at the freshest end of the context
const ri = view.findIndex((m) => m.role === 'system' && /How to compose your turn/i.test(m.content));
const tail = view.slice(-3).map((m) => m.role).join(',');
ok('the reminder rides at the freshest end', (ri === view.length - 1) || (ri === view.length - 2 && view[view.length - 1].role === 'assistant'), tail);
console.log(fails ? `\n${fails} FAILURES` : '\nALL PASS');
process.exit(fails ? 1 : 0);
+38
View File
@@ -0,0 +1,38 @@
// test/restart-check.mjs — after a server restart: the token
// survives, the boot-rebuild reopened the unhousekept sessions, the
// runs list is whole. Reads the token + run ids smoke.mjs left in
// the temp file; run against the restarted --mock server:
// node test/restart-check.mjs
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const BASE = process.env.RP_BASE ?? 'http://127.0.0.1:7350';
const [token, reforkId, secondId] = readFileSync(join(tmpdir(), 'rp-test-smoke-token.txt'), 'utf8').trim().split(' ');
const call = async (path, tok) => {
const res = await fetch(`${BASE}/api${path}`, {
headers: tok ? { authorization: `Bearer ${tok}` } : {},
});
return { status: res.status, data: await res.json().catch(() => ({})) };
};
let failures = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
if (!cond) failures++;
};
let r = await call('/session', token);
ok('token survives restart', r.status === 200 && r.data.user?.name === 'Op');
r = await call(`/runs/${reforkId}`, token);
ok('forked session rebuilt', r.status === 200 && r.data.open === true, JSON.stringify({ open: r.data.open, owner: r.data.run.owner }));
r = await call(`/runs/${secondId}`, token);
ok('draft intact', r.status === 200 && r.data.draft === true);
r = await call('/runs', token);
ok('runs listed', r.status === 200 && Array.isArray(r.data) && r.data.length >= 4, `${r.data.length} runs`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);
+215
View File
@@ -0,0 +1,215 @@
// test/smoke.mjs — end-to-end multiuser pass against the --mock
// server. Covers: bootstrap, claim, spent-invite rejection, second
// user, run lifecycle, spectator 403s, fork, save-package,
// create-from-user-package, revocation, ownerless state, the agenda
// deltas + self-heal, the reminder ride, per-run models.
// Prints PASS/FAIL per step; exit code carries the verdict.
//
// Expects a CLEAN state/ (no users) and a running --mock server:
// node server/main.mjs --mock
// node test/smoke.mjs
// Leaves its token + run ids in a temp file for restart-check.mjs.
// Clean up afterwards: Remove-Item state/, delete the smoke runs.
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const BASE = process.env.RP_BASE ?? 'http://127.0.0.1:7350';
export const TOKEN_FILE = join(tmpdir(), 'rp-test-smoke-token.txt');
let failures = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra !== '' ? ` — ${extra}` : ''}`);
if (!cond) failures++;
};
const call = async (path, { method = 'GET', token, body } = {}) => {
const res = await fetch(`${BASE}/api${path}`, {
method,
headers: {
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
return { status: res.status, data };
};
const meta = (id) => JSON.parse(readFileSync(`${ROOT}/runs/${id}/run.json`, 'utf8'));
// 1. fresh deployment
let r = await call('/session');
ok('fresh session', r.status === 200 && r.data.user === null && r.data.fresh === true);
// 2. auth required
r = await call('/runs');
ok('runs need auth', r.status === 401);
// 3. bootstrap invite on disk
const code = readFileSync(`${ROOT}/state/bootstrap-invite.txt`, 'utf8').trim();
ok('bootstrap file', code.length === 24, code);
// 4. claim superuser
r = await call('/claim', { method: 'POST', body: { code, name: 'Op' } });
ok('claim op', r.status === 200 && r.data.user.superuser === true, r.data.error ?? '');
const op = r.data.token;
const opId = r.data.user.id;
// 5. invite reuse rejected
r = await call('/claim', { method: 'POST', body: { code, name: 'Sneak' } });
ok('spent invite rejected', r.status === 400 && /already used/.test(r.data.error));
// 6. mint invite -> second user
r = await call('/invites', { method: 'POST', token: op, body: {} });
ok('mint invite', r.status === 200 && r.data.code?.length === 24, r.data.error ?? r.data.code);
const inviteCode = r.data.code;
r = await call('/claim', { method: 'POST', body: { code: inviteCode, name: 'Ash' } });
ok('claim ash', r.status === 200 && r.data.user.superuser === false, r.data.error ?? '');
const ash = r.data.token;
const ashId = r.data.user.id;
// 7. ash cannot mint
r = await call('/invites', { method: 'POST', token: ash, body: {} });
ok('invite mint is op-only', r.status === 403);
// 8. op creates a run
r = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Smokina', name: 'Smoke Story' } });
ok('create run', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const runId = r.data.run?.id;
ok('owner stamped', meta(runId).owner === opId);
// 9. start: session + turn0 (mock: roll, then reply)
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('session open', r.status === 200, r.data.error ?? r.data.session);
r = await call(`/runs/${runId}/turn0`, { method: 'POST', token: op, body: {} });
ok('turn0', r.status === 200, r.data.error ?? '');
// 10. a plain turn (mock: asks) + the answer
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The tide comes in.*' } });
ok('gm turn -> pending ask', r.status === 200 && !!r.data.pendingAsk, r.data.error ?? r.data.pendingAsk);
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'yes, clear toward the bow' } });
ok('ask answered', r.status === 200, r.data.error ?? '');
// 10b. the agenda: same-verb blocks combine (two <add> and two <gained>
// blocks in one turn); a bad drop conflicts, and the conflict goes back
// as its own message — the model heals inside the same turn
r = await call(`/runs/${runId}`, { token: op });
ok('two add blocks combined, order kept', JSON.stringify(r.data.agenda) === '["find fresh water","signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
ok('two gained blocks combined', JSON.stringify(r.data.status.slice(-2)) === '["settled","curious about the clicking"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She sets off.*' } });
ok('gm turn (drop)', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('agenda after drop', JSON.stringify(r.data.agenda) === '["signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Evening comes.*' } });
ok('bad drop self-heals in the same turn', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
r = await call(`/runs/${runId}`, { token: op });
ok('heal applied (multi-index drop)', JSON.stringify(r.data.agenda) === '[]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/session`, { token: op });
const conflictMsg = r.data.entries.find((e) => e.conflictOnly);
ok('conflict went as its own message', !!conflictMsg && /<conflict>agenda has no item at index 9<\/conflict>/.test(conflictMsg.m.content), conflictMsg?.m.content ?? 'none');
const cIdx = r.data.entries.indexOf(conflictMsg);
ok('the model answered the conflict', r.data.entries.slice(cIdx + 1).some((e) => e.t === 'msg' && e.m.role === 'assistant'), '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Night falls.*' } });
ok('next gm turn is clean', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
const lastGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
ok('no conflict attached to the GM turn', !/<conflict>/.test(lastGm.m.content), lastGm.m.content.slice(-100));
ok('the empty agenda rides honestly', /<agenda><\/agenda>/.test(lastGm.m.content), lastGm.m.content.slice(-120));
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: op, body: { items: ['climb the ridge', 'rest'] } });
ok('agenda-set (GM override)', r.status === 200 && JSON.stringify(r.data.agenda) === '["climb the ridge","rest"]', JSON.stringify(r.data.agenda));
// 10c. the reminder: a system chunk after every GM turn, one live copy
r = await call(`/runs/${runId}/session`, { token: op });
const reminders = r.data.entries.filter((e) => e.reminder);
ok('reminder rode every GM turn', reminders.length >= 5 && reminders.every((x) => x.m.role === 'system'), `${reminders.length} in the log`);
ok('reminder carries the turn protocol', /How to compose your turn/i.test(reminders[0]?.m.content ?? ''), (reminders[0]?.m.content ?? '').slice(0, 60));
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: ash, body: { items: [] } });
ok('agenda override owner-only', r.status === 403);
r = await call(`/runs/${runId}/status`, { token: op });
ok('status endpoint carries both', Array.isArray(r.data.status) && Array.isArray(r.data.agenda), JSON.stringify(r.data).slice(0, 120));
// 11. ash spectates: reads ok, mutates 403
r = await call(`/runs/${runId}`, { token: ash });
ok('ash reads run', r.status === 200 && r.data.run.ownerName === 'Op', r.data.error ?? '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: ash, body: { line: 'hi' } });
ok('ash turn 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { method: 'PUT', token: ash, body: { content: 'mine' } });
ok('ash notes write 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { token: ash });
ok('ash reads notes', r.status === 200); // spectators read the pad
r = await call(`/runs/${runId}/housekeeping/replay`, { method: 'POST', token: ash, body: {} });
ok('ash replay 403 (spends a call)', r.status === 403);
// 12. ash forks
r = await call(`/runs/${runId}/fork`, { method: 'POST', token: ash, body: {} });
ok('fork', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const forkId = r.data.run;
const fm = meta(forkId);
ok('fork owner + forked stamp', fm.owner === ashId && Number.isInteger(fm.forked) && fm.created === meta(runId).created,
`owner=${fm.owner} forked=${fm.forked} created=${fm.created}`);
r = await call(`/runs/${forkId}`, { token: ash });
ok('fork session carried over', r.status === 200 && r.data.open === true, r.data.error ?? '');
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She looks around.*' } });
ok('ash turns on the fork', r.status === 200, r.data.error ?? '');
// 12b. models: per-run overrides of the deployment defaults
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
ok('set models', r.status === 200 && r.data.models.player === 'mock' && r.data.models.housekeeper === 'mock-cheap', JSON.stringify(r.data));
ok('models stamped in run.json', meta(forkId).models?.player === 'mock' && meta(forkId).models?.housekeeper === 'mock-cheap');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
ok('clear a role back to default', r.status === 200 && r.data.models.housekeeper === undefined && r.data.models.player === 'mock', JSON.stringify(r.data));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: 'x' } });
ok('model set is owner-only', r.status === 403);
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
ok('unknown role rejected', r.status === 400);
r = await call(`/runs/${forkId}`, { token: ash });
ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !!r.data.run.modelDefaults?.player, JSON.stringify(r.data.run.models));
r = await call('/models', { token: ash });
ok('model listing', r.status === 200 && Array.isArray(r.data) && r.data.includes('mock'));
// 13. ash saves the fork as a package
r = await call('/packages', { method: 'POST', token: ash, body: { from: forkId, name: 'Forked Pack' } });
ok('save-package', r.status === 200 && !!r.data.package?.id, r.data.error ?? r.data.package?.id);
const pkgId = r.data.package?.id;
r = await call('/packages', { token: op });
const saved = r.data.find((p) => p.name === pkgId);
ok('package listed with origin', !!saved && saved.origin === 'user' && saved.ownerName === 'Ash'
&& saved.pc === null && saved.display === 'Forked Pack', JSON.stringify(saved));
// 14. op creates a run from the user package
r = await call('/runs', { method: 'POST', token: op, body: { package: pkgId, pc: 'Secondina', name: 'Second Story' } });
ok('create from user package', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const secondId = r.data.run?.id;
// 15. op revokes ash — identity destroyed, data stays
r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} });
ok('revoke ash', r.status === 200, r.data.error ?? '');
r = await call('/runs', { token: ash });
ok('ash token dead', r.status === 401);
r = await call(`/runs/${forkId}`, { token: op });
ok('fork now ownerless, session closed', r.status === 200 && r.data.run.owner === null && r.data.run.ownerName === null && r.data.open === false,
JSON.stringify(r.data.run));
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: op, body: { line: 'x' } });
ok('ownerless turn 403 even for op', r.status === 403 && /ownerless/.test(r.data.error));
r = await call('/packages', { token: op });
const saved2 = r.data.find((p) => p.name === pkgId);
ok('user package survives, ownerless', !!saved2 && saved2.owner === null && saved2.ownerName === null && saved2.display === 'Forked Pack',
JSON.stringify(saved2));
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const reforkId = r.data.run;
ok('fork carries the models', meta(reforkId).models?.player === 'mock');
// 16. users list, self-revoke refused
r = await call('/users', { token: op });
ok('users list', r.status === 200 && r.data.users.length === 1 && r.data.users[0].id === opId);
r = await call(`/users/${opId}/revoke`, { method: 'POST', token: op, body: {} });
ok('self-revoke refused', r.status === 409);
console.log(`\nrun ids: source=${runId} fork=${forkId} second=${secondId} refork=${reforkId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);
+122 -92
View File
@@ -23,7 +23,7 @@
// (the low-level primitive under create)
// seed [--force] [file] one-time pre-story migration; applies
// lazily at a fresh run's first
// window-open (the server calls it)
// session-open (the server calls it)
// render write canon/ring-a.md, ring-b.md, status.md
// apply <manifest.json> apply a housekeeper manifest (validated, transactional)
// insert <ring> <type> "Label" "detail" GM-authoritative insert
@@ -35,13 +35,13 @@
// discard <rid> "reason" the PC discards a record (--gm likewise)
// search <terms...> query the records (max 10; a miss is a miss)
// unarchive <rid> [a|b] GM pulls a record back into the rings
// paper the paper, as JSON (the status tier)
// paper-apply "<turn text>" apply <lost>/<gained> deltas from a player
// status her status, as JSON (the status tier)
// status-apply "<turn text>" apply <lost>/<gained> deltas from a player
// turn; exact match, non-blocking; JSON result
// (lost / gained / conflicts / paper)
// paper-set "descr" ... GM override: replace the whole paper
// (lost / gained / conflicts / status)
// status-set "descr" ... GM override: replace the whole status
// (no descrs = clear it)
// paper-ingest <file> read a file's <status> block into the paper
// status-ingest <file> read a file's <status> block into her status
// (turn-0 at new-game)
// agenda the agenda, as JSON (the intentions tier)
// agenda-apply "<turn text>" apply <add>/<drop> deltas from a player
@@ -57,7 +57,7 @@
// restore --force rebuild the db from dumps/memory.sql
// commands take --run <id> (a run under runs/); state is per-deployment.
//
// status counts, caps, the paper, what's sinking
// status counts, caps, the status, what's sinking
import { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto';
@@ -135,7 +135,7 @@ touches the rings and is always in the bundle.)
const CARD_TEMPLATE = `# <name>
(Fill this in before window one. Five lines is plenty; freeform beats
(Fill this in before session one. Five lines is plenty; freeform beats
complete. Blank fields are the player's to invent through play — the
GM ratifies notable inventions afterward.)
@@ -162,39 +162,62 @@ function openDb() {
fail(`no database at ${rel(DB_PATH)} — run: node tool/memory.mjs init`);
}
const db = new DatabaseSync(DB_PATH);
migrateStatusNames(db); // before the schema exec: renames must land before CREATE IF NOT EXISTS
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
migrateEventsCheck(db);
return db;
}
// the events CHECK names every legal op; a db opened before the agenda
// carries the narrower list and would reject agenda journaling. SQLite
// cannot alter a CHECK in place, so this rebuilds events once — the
// table is append-only, the copy is exact. (Mirrors db/schema.sql.)
function migrateEventsCheck(db) {
// One normalizer brings any events table to the current schema
// (2026-11-14, GM: no legacy hauling — renames are clean, old data
// migrates once): the column `window` -> `session`, the journal op
// values `paper-*` -> `status-*`, and the CHECK widened to the full
// op list. The rebuild copies through a check-free intermediate —
// the old CHECK would reject the new op values mid-flight, and the
// positional copy absorbs the column rename. (Mirrors db/schema.sql;
// old dumps carry their own old schema and self-migrate through here.)
function migrateStatusNames(db) {
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'status-add', 'status-drop', 'status-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => r.name);
if (tables.includes('paper') && !tables.includes('status')) {
db.exec('ALTER TABLE paper RENAME TO status');
if (!QUIET) console.log(`(migrated: table paper -> status — ${rel(DB_PATH)})`);
}
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
if (!row || row.sql.includes('agenda-add')) return;
const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')";
if (!row) return;
const staleOps = db.prepare("SELECT COUNT(*) AS n FROM events WHERE op LIKE 'paper-%'").get().n > 0;
if (!staleOps && row.sql.includes("'status-add'")) return;
db.exec('BEGIN');
try {
db.exec(`CREATE TABLE events_new (
db.exec(`CREATE TABLE events_mig (
id INTEGER PRIMARY KEY AUTOINCREMENT,
window TEXT NOT NULL,
session TEXT NOT NULL,
op TEXT NOT NULL,
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
)`);
db.exec('INSERT INTO events_mig SELECT * FROM events');
db.exec("UPDATE events_mig SET op = 'status-add' WHERE op = 'paper-add'");
db.exec("UPDATE events_mig SET op = 'status-drop' WHERE op = 'paper-drop'");
db.exec("UPDATE events_mig SET op = 'status-set' WHERE op = 'paper-set'");
db.exec('DROP TABLE events');
db.exec(`CREATE TABLE events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session TEXT NOT NULL,
op TEXT NOT NULL CHECK (op IN ${OPS}),
target TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
prior TEXT NOT NULL DEFAULT ''
)`);
db.exec('INSERT INTO events_new SELECT * FROM events');
db.exec('DROP TABLE events');
db.exec('ALTER TABLE events_new RENAME TO events');
db.exec('CREATE INDEX IF NOT EXISTS events_window ON events (window)');
db.exec('INSERT INTO events SELECT * FROM events_mig');
db.exec('DROP TABLE events_mig');
db.exec('CREATE INDEX IF NOT EXISTS events_session ON events (session)');
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`events migration failed: ${e.message}`);
fail(`events rename migration failed: ${e.message}`);
}
if (!QUIET) console.log(`(migrated: events journal widened for the agenda ops — ${rel(DB_PATH)})`);
if (!QUIET) console.log(`(migrated: events journal to the current names — ${rel(DB_PATH)})`);
}
const parseId = (s) => {
@@ -210,7 +233,7 @@ const parseRid = (s) => {
};
const journal = (db, win, op, target, reason, prior = '') =>
db.prepare('INSERT INTO events (window, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
db.prepare('INSERT INTO events (session, op, target, reason, prior) VALUES (?, ?, ?, ?, ?)')
.run(win, op, target, norm(reason), prior);
// generated views: the ring and status files are machine-written — never
@@ -238,11 +261,11 @@ function renderRing(db, ring) {
}
function renderStatus(db) {
const rows = db.prepare('SELECT * FROM paper ORDER BY id').all();
const rows = db.prepare('SELECT * FROM status ORDER BY id').all();
const lines = [
'# Status — her paper',
'# Status',
'',
'The paper is the player\'s — stances and feelings; facts live in the rings.',
'The status is the player\'s — stances and feelings; facts live in the rings.',
'',
];
if (!rows.length) lines.push('(a blank sheet — fresh start)');
@@ -301,14 +324,14 @@ function dumpDb(db) {
for (const r of db.prepare('SELECT * FROM records ORDER BY id').all()) {
L.push(`INSERT INTO records VALUES (${r.id},${q(r.kind)},${q(r.label)},${q(r.detail)},${q(r.created)});`);
}
for (const r of db.prepare('SELECT * FROM paper ORDER BY id').all()) {
L.push(`INSERT INTO paper VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
for (const r of db.prepare('SELECT * FROM status ORDER BY id').all()) {
L.push(`INSERT INTO status VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM agenda ORDER BY id').all()) {
L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
}
for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) {
L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
L.push(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
}
L.push('COMMIT;', '');
const file = path.join(DUMPS_DIR, 'memory.sql');
@@ -360,7 +383,7 @@ function makeValidator(db) {
// --- apply ------------------------------------------------------------------
function renderLog(mf, applied, overflow) {
const L = [`# ${mf.window}`, '', mf.summary, ''];
const L = [`# ${mf.session}`, '', mf.summary, ''];
const section = (title, rows, fmt) => {
if (!rows.length) return;
L.push(`## ${title}`, '');
@@ -401,7 +424,7 @@ function cmdSeed(force, seedPathArg) {
const records = sf.records ?? [];
if (!Array.isArray(entries)) { errors.push('entries must be an array'); }
if (sf.status !== undefined) {
errors.push('status no longer seeds — the initial paper rides turn-0\'s <status> block, ingested at new-game (paper-ingest)');
errors.push('status no longer seeds — the initial status rides turn-0\'s <status> block, ingested at new-game (status-ingest)');
}
if (!Array.isArray(records)) { errors.push('records must be an array'); }
for (const [i, e] of (Array.isArray(entries) ? entries : []).entries()) {
@@ -457,12 +480,12 @@ function cmdApply(manifestPath) {
}
const { errors, need, asArray, ref } = makeValidator(db);
need(mf.window, 'window');
need(mf.session, 'session');
need(mf.summary, 'summary');
if (typeof mf.window === 'string' && !/^[a-z0-9-]+$/i.test(mf.window)) {
errors.push('window must be a short slug (letters, digits, dashes)');
if (typeof mf.session === 'string' && !/^[a-z0-9-]+$/i.test(mf.session)) {
errors.push('session must be a short slug (letters, digits, dashes)');
}
const logFile = mf.window ? path.join(LOG_DIR, `${mf.window}.md`) : null;
const logFile = mf.session ? path.join(LOG_DIR, `${mf.session}.md`) : null;
if (logFile && fs.existsSync(logFile)) {
errors.push(`${rel(logFile)} already exists — delete it first if this is a re-run`);
}
@@ -519,7 +542,7 @@ function cmdApply(manifestPath) {
for (const e of ins) {
const id = insertEntry(db, {
ring: e.ring, type: e.type, label: e.label, detail: e.detail ?? '',
win: mf.window, reason: e.reason,
win: mf.session, reason: e.reason,
});
applied.insert.push({ id, ...e });
}
@@ -528,25 +551,25 @@ function cmdApply(manifestPath) {
for (const e of touch) {
const id = parseId(e.id);
touchDate(id);
journal(db, mf.window, 'touch', `e${id}`, e.reason);
journal(db, mf.session, 'touch', `e${id}`, e.reason);
applied.touch.push({ row: fetch(id), reason: e.reason });
}
for (const e of promote) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'a', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.window, 'promote', `e${id}`, e.reason);
journal(db, mf.session, 'promote', `e${id}`, e.reason);
applied.promote.push({ row: fetch(id), reason: e.reason });
}
for (const e of demote) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'b', last_touched = ? WHERE id = ?").run(today(), id);
journal(db, mf.window, 'demote', `e${id}`, e.reason);
journal(db, mf.session, 'demote', `e${id}`, e.reason);
applied.demote.push({ row: fetch(id), reason: e.reason });
}
for (const e of reword) {
const id = parseId(e.id);
db.prepare('UPDATE entries SET detail = ?, last_touched = ? WHERE id = ?').run(norm(e.detail), today(), id);
journal(db, mf.window, 'reword', `e${id}`, e.reason);
journal(db, mf.session, 'reword', `e${id}`, e.reason);
applied.reword.push({ row: fetch(id), detail: e.detail, reason: e.reason });
}
for (const e of arch) {
@@ -556,13 +579,13 @@ function cmdApply(manifestPath) {
.run(row.type, row.label, row.detail, row.created);
const rid = Number(res.lastInsertRowid);
db.prepare('DELETE FROM entries WHERE id = ?').run(id);
journal(db, mf.window, 'archive', `r${rid}`, e.reason);
journal(db, mf.session, 'archive', `r${rid}`, e.reason);
applied.archive.push({ rid, row, reason: e.reason });
}
for (const e of del) {
const id = parseId(e.id);
db.prepare("UPDATE entries SET ring = 'cold' WHERE id = ?").run(id);
journal(db, mf.window, 'delete', `e${id}`, e.reason);
journal(db, mf.session, 'delete', `e${id}`, e.reason);
applied.delete.push({ row: fetch(id), reason: e.reason });
}
@@ -576,7 +599,7 @@ function cmdApply(manifestPath) {
const victim = rows[i];
const dest = ring === 'a' ? 'b' : 'cold';
db.prepare('UPDATE entries SET ring = ? WHERE id = ?').run(dest, victim.id);
journal(db, mf.window, ring === 'a' ? 'demote' : 'evict', `e${victim.id}`, `ring ${ring.toUpperCase()} overflow (auto)`);
journal(db, mf.session, ring === 'a' ? 'demote' : 'evict', `e${victim.id}`, `ring ${ring.toUpperCase()} overflow (auto)`);
overflow.push({ id: victim.id, from: ring, to: dest });
}
}
@@ -590,12 +613,12 @@ function cmdApply(manifestPath) {
fs.mkdirSync(LOG_DIR, { recursive: true });
fs.writeFileSync(logFile, renderLog(mf, applied, overflow));
const dumpFile = dumpDb(db);
// per-wrap snapshot: the committed-truth successor now that runs are
// gitignored — diffing consecutive snapshots reconstructs the window's
// per-pass snapshot: the committed-truth successor now that runs are
// gitignored — diffing consecutive snapshots reconstructs the session's
// operations for async review
const snapshot = path.join(DUMPS_DIR, `${mf.window}.sql`);
const snapshot = path.join(DUMPS_DIR, `${mf.session}.sql`);
fs.copyFileSync(dumpFile, snapshot);
console.log(`applied [${RUN}] ${mf.window}: ` + [
console.log(`applied [${RUN}] ${mf.session}: ` + [
applied.insert.length && `${applied.insert.length} inserted`,
applied.touch.length && `${applied.touch.length} touched`,
applied.promote.length && `${applied.promote.length} promoted`,
@@ -641,7 +664,7 @@ function cmdInit() {
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
// tier. housekeeper.md is substrate-internal like invariants.md —
// repo-fed at wrap time, never copied, never user-exposed; system.md
// repo-fed at housekeeping time, never copied, never user-exposed; system.md
// and invariants.md are likewise repo-fed at assembly (opening+guards,
// substrate facts)
const SHARED_PROMPTS = ['handbook.md'];
@@ -769,7 +792,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
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 session-open applies it`);
renderAll(db);
dumpDb(db);
}
@@ -909,6 +932,13 @@ function cmdRestore(force = false) {
if (fs.existsSync(DB_PATH)) fs.rmSync(DB_PATH);
const db = new DatabaseSync(DB_PATH);
db.exec(fs.readFileSync(dumpFile, 'utf8'));
// an old dump embeds its own old schema — normalize before rendering:
// the renames first (the schema exec's CREATE IF NOT EXISTS would
// collide with a table awaiting rename), then the schema (creates
// tables the dump predates, e.g. agenda). Old dumps self-heal
// through the same path as openDb.
migrateStatusNames(db);
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
console.log(`restored ${rel(DB_PATH)} from ${rel(dumpFile)}`);
renderAll(db);
}
@@ -955,15 +985,15 @@ function cmdDiscard(ridStr, reason) {
dumpDb(db);
}
// --- the paper (status tier) -------------------------------------------------
// --- her status (the status tier) -------------------------------------------------
//
// Freeform descriptions, no keys, no baselines. The player mutates via
// <lost>/<gained> deltas in its own turns — exact match, non-blocking,
// misses relayed back to the model as a <conflict> block by the caller.
// The GM overrides out-of-band with paper-set. Descriptions never contain
// The GM overrides out-of-band with status-set. Descriptions never contain
// commas: both the delta lists and the <status> block are comma-separated.
const paperList = (db) => db.prepare('SELECT descr FROM paper ORDER BY id').all().map((r) => r.descr);
const statusList = (db) => db.prepare('SELECT descr FROM status ORDER BY id').all().map((r) => r.descr);
// split a list of descriptions, tolerating newlines and list bullets —
// covers the delta tags and a <status> block body alike
@@ -971,11 +1001,11 @@ const splitDescrs = (s) =>
String(s ?? '').split('\n').flatMap((line) =>
line.replace(/^\s*[-*]\s+/, '').split(',')).map((x) => x.trim()).filter(Boolean);
function cmdPaper() {
console.log(JSON.stringify(paperList(openDb())));
function cmdStatus() {
console.log(JSON.stringify(statusList(openDb())));
}
function cmdPaperApply(text) {
function cmdStatusApply(text) {
const db = openDb();
const lost = [];
const gained = [];
@@ -983,76 +1013,76 @@ function cmdPaperApply(text) {
for (const m of String(text ?? '').matchAll(/<gained>([\s\S]*?)<\/gained>/g)) gained.push(...splitDescrs(m[1]));
const applied = { lost: [], gained: [], conflicts: [] };
if (!lost.length && !gained.length) {
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
return;
}
const win = AS_GM ? 'gm' : 'pc';
db.exec('BEGIN');
try {
for (const item of lost) {
const row = db.prepare('SELECT * FROM paper WHERE descr = ?').get(item);
const row = db.prepare('SELECT * FROM status WHERE descr = ?').get(item);
if (row) {
db.prepare('DELETE FROM paper WHERE id = ?').run(row.id);
journal(db, win, 'paper-drop', `p${row.id}`, 'delta', row.descr);
db.prepare('DELETE FROM status WHERE id = ?').run(row.id);
journal(db, win, 'status-drop', `p${row.id}`, 'delta', row.descr);
applied.lost.push(item);
} else {
applied.conflicts.push(`not on her paper: ${item}`);
applied.conflicts.push(`not in her status: ${item}`);
}
}
for (const item of gained) {
// already listed is a no-op, not a conflict
if (db.prepare('SELECT 1 FROM paper WHERE descr = ?').get(item)) continue;
const res = db.prepare('INSERT INTO paper (descr, added) VALUES (?, ?)').run(item, today());
journal(db, win, 'paper-add', `p${Number(res.lastInsertRowid)}`, 'delta');
if (db.prepare('SELECT 1 FROM status WHERE descr = ?').get(item)) continue;
const res = db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(item, today());
journal(db, win, 'status-add', `p${Number(res.lastInsertRowid)}`, 'delta');
applied.gained.push(item);
}
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`paper-apply failed, rolled back: ${e.message}`);
fail(`status-apply failed, rolled back: ${e.message}`);
}
console.log(JSON.stringify({ ...applied, paper: paperList(db) }));
console.log(JSON.stringify({ ...applied, status: statusList(db) }));
renderAll(db);
dumpDb(db);
}
// whole-paper replace (GM override, turn-0 ingestion); the journal keeps
// the full prior paper so turn surgery can compensate mechanically
function setPaper(db, items, reason, win) {
// whole-status replace (GM override, turn-0 ingestion); the journal keeps
// the full prior status so turn surgery can compensate mechanically
function setStatus(db, items, reason, win) {
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
const prior = paperList(db);
const prior = statusList(db);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM paper').run();
db.prepare('DELETE FROM status').run();
for (const d of clean) {
db.prepare('INSERT INTO paper (descr, added) VALUES (?, ?)').run(d, today());
db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(d, today());
}
journal(db, win, 'paper-set', 'paper', reason, JSON.stringify(prior));
journal(db, win, 'status-set', 'p', reason, JSON.stringify(prior));
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
fail(`paper-set failed, rolled back: ${e.message}`);
fail(`status-set failed, rolled back: ${e.message}`);
}
return clean;
}
function cmdPaperSet(items) {
function cmdStatusSet(items) {
const db = openDb();
const clean = setPaper(db, items, AS_GM ? 'GM override' : 'paper set', AS_GM ? 'gm' : 'pc');
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc');
console.log(JSON.stringify(clean));
renderAll(db);
dumpDb(db);
}
function cmdPaperIngest(filePath) {
function cmdStatusIngest(filePath) {
const p = path.resolve(filePath ?? '');
if (!fs.existsSync(p)) fail(`no such file: ${filePath}`);
const blocks = [...fs.readFileSync(p, 'utf8').matchAll(/<status>([\s\S]*?)<\/status>/g)];
if (!blocks.length) fail(`no <status> block in ${filePath}`);
const items = splitDescrs(blocks[blocks.length - 1][1]);
const db = openDb();
setPaper(db, items, `ingested from ${path.basename(p)}`, 'seed');
console.log(JSON.stringify(paperList(db)));
setStatus(db, items, `ingested from ${path.basename(p)}`, 'seed');
console.log(JSON.stringify(statusList(db)));
renderAll(db);
dumpDb(db);
}
@@ -1060,7 +1090,7 @@ function cmdPaperIngest(filePath) {
// --- the agenda (intentions tier) ---------------------------------------------
//
// The hot queue of what drives her: goals she is working towards right
// now — intentions, never states (those are the paper's). Fixed cap
// now — intentions, never states (those are the status's). Fixed cap
// (a dial); id order IS queue order — adds land at the top in written
// order, overflow evicts the bottom, a recency ring buffer for free.
// The player mutates via <add>/<drop> in its own turns: drops are
@@ -1204,14 +1234,14 @@ function cmdUnarchive(ridStr, ring = 'b') {
dumpDb(db);
}
function cmdStatus() {
function cmdReport() {
const db = openDb();
if (AS_JSON) {
const out = {
run: RUN,
records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n,
recordsEnabled: recordsEnabled(),
paper: paperList(db),
status: statusList(db),
agenda: agendaList(db),
events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n,
rings: {},
@@ -1231,9 +1261,9 @@ function cmdStatus() {
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
const nr = db.prepare('SELECT COUNT(*) AS n FROM records').get().n;
console.log(`records: ${nr}`);
const paper = paperList(db);
console.log(`paper: ${paper.length ? '' : '(a blank sheet)'}`);
for (const d of paper) console.log(` - ${d}`);
const status = statusList(db);
console.log(`status: ${status.length ? '' : '(a blank sheet)'}`);
for (const d of status) console.log(` - ${d}`);
for (const ring of ['a', 'b', 'cold']) {
const n = db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring).n;
const cap = CAPS[ring] ?? '∞';
@@ -1264,20 +1294,20 @@ switch (cmd) {
case 'file': (args.length >= 2) ? cmdFile(args[0], args[1], args[2] ?? '', args[3]) : fail('usage: file <kind> "Label" "detail" ["reason"]'); break;
case 'amend': (args.length >= 2) ? cmdAmend(args[0], args[1]) : fail('usage: amend <rid> "new detail"'); break;
case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break;
case 'paper': cmdPaper(); break;
case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply "<turn text>"'); break;
case 'paper-set': cmdPaperSet(args); break; // no args = clear the paper (a legitimate GM override)
case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest <file>'); break;
case 'status': cmdStatus(); break;
case 'status-apply': (args.length >= 1) ? cmdStatusApply(args.join(' ')) : fail('usage: status-apply "<turn text>"'); break;
case 'status-set': cmdStatusSet(args); break; // no args = clear the status (a legitimate GM override)
case 'status-ingest': (args.length === 1) ? cmdStatusIngest(args[0]) : fail('usage: status-ingest <file>'); break;
case 'agenda': cmdAgenda(); break;
case 'agenda-apply': (args.length >= 1) ? cmdAgendaApply(args.join(' ')) : fail('usage: agenda-apply "<turn text>"'); break;
case 'agenda-set': cmdAgendaSet(args); break; // no args = clear the agenda
case 'pick': cmdPick(args); break;
case 'search': cmdSearch(args); break;
case 'unarchive': (args.length >= 1) ? cmdUnarchive(args[0], args[1]) : fail('usage: unarchive <rid> [a|b]'); break;
case 'status': cmdStatus(); break;
case 'report': cmdReport(); break;
case 'dump': cmdDump(); break;
case 'restore': cmdRestore(FORCE); break;
default:
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|insert|delete|revive|file|amend|discard|search|unarchive|paper|paper-apply|paper-set|paper-ingest|agenda|agenda-apply|agenda-set|pick|dump|restore|status>');
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|insert|delete|revive|file|amend|discard|search|unarchive|status|status-apply|status-set|status-ingest|agenda|agenda-apply|agenda-set|pick|dump|restore|report>');
process.exit(1);
}
+27 -1362
View File
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
// web/chrome.mjs — the shared page chrome: header identity, session
// info, the context meter, the busy note, the notice banner.
//
// In-page notices only — no JS alert()/confirm(): they block the
// embedded browser pane. Errors and notices land in the banner
// instead; destructive confirms are two-click armed (widgets.mjs).
import { $ } from './dom.mjs';
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// — the lifecycle story is a roadmap extension point
export function setWho(me) {
$('who').textContent = me ? `${me.name}${me.superuser ? ' · op' : ''}` : '';
$('who').title = me?.id ?? '';
}
export function setSessionInfo(text) {
$('session-info').textContent = text;
}
export function renderMeter(detail) {
const fill = $('context-fill');
const label = $('context-label');
const c = detail?.context;
if (!c || c.used == null) {
fill.style.width = '0';
label.textContent = '';
return;
}
const pct = c.pct ?? 0;
fill.style.width = `${Math.min(100, pct)}%`;
fill.classList.toggle('hot', pct > 85);
label.textContent = c.contwin ? `${pct}% — close & housekeep past 85%` : '';
}
export function setBusy(on, text = 'her turn…') {
$('busy').hidden = !on; // model calls take their time — say so
if (on) $('busy').textContent = text;
}
let bannerTimer = null;
export function banner(text, kind = 'error') {
const b = $('banner');
b.textContent = text;
b.className = kind;
b.hidden = false;
clearTimeout(bannerTimer);
bannerTimer = setTimeout(() => { b.hidden = true; }, 10000);
}
export function hideBanner() {
$('banner').hidden = true;
}
+50
View File
@@ -0,0 +1,50 @@
// web/client.mjs — the REST client: the one fetch choke point.
//
// Every call is logged to the diagnostics (status + duration); a
// rejected token ends the session — drop it and show the claim view;
// every path leads there until a fresh one is claimed.
import { logEvent } from './log.mjs';
import { state } from './state.mjs';
import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked — the session just won't persist */ } };
export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
export async function api(path, opts = {}) {
const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`;
try {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: {
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page — the notepad flush
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const e = new Error(data.error ?? `${res.status}`);
e.detail = data.detail;
e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms — ${e.message}`);
if (res.status === 401 && path !== '/session' && authToken()) {
clearToken();
state.me = null;
logEvent('nav', 'signed out: token rejected');
setTimeout(render, 0);
}
throw e;
}
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
return data;
} catch (e) {
if (!e.status) logEvent('api', `${label} FAILED ${Math.round(performance.now() - started)}ms — ${e.message}`); // network level
throw e;
}
}
+11
View File
@@ -0,0 +1,11 @@
// web/dom.mjs — the two DOM helpers everything else builds on.
export const $ = (id) => document.getElementById(id);
// one element, class and text in the common shape
export function el(tag, cls, text) {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}
+11 -41
View File
@@ -10,7 +10,7 @@
<header>
<a id="home-link" href="/">rp-test</a>
<span id="who"></span>
<div id="window-info"></div>
<div id="session-info"></div>
<div id="context-meter" title="context usage of the last call">
<div id="context-bar"><div id="context-fill"></div></div>
<span id="context-label"></span>
@@ -49,7 +49,7 @@
<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>
<p class="hint">a run is a copy of the package — everything stays editable until the session opens</p>
<div id="package-list"></div>
</div>
<form id="create-form" hidden>
@@ -78,15 +78,7 @@
<span id="setup-vars-state"></span>
</div>
</div>
<div id="setup-models">
<h2>models — per-run, over the deployment defaults</h2>
<label class="field">player <select id="model-player"></select></label>
<label class="field">housekeeper <select id="model-housekeeper"></select></label>
<div class="form-actions">
<button id="models-save">save models</button>
<span id="models-state"></span>
</div>
</div>
<div id="setup-models"></div>
<div id="setup-savepkg">
<input id="savepkg-name" placeholder="new package display name" autocomplete="off">
<button id="savepkg-btn">save as package</button>
@@ -115,32 +107,16 @@
<aside id="play-aside">
<section id="status-pane">
<div class="pane-head">
<h2>her paper</h2>
<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>
<h2>her status</h2>
</div>
<div id="status"></div>
<div id="conflict" hidden></div>
</section>
<section id="agenda-pane">
<div class="pane-head">
<h2>her agenda</h2>
<button id="agenda-edit">edit</button>
</div>
<div id="agenda"></div>
<div id="agenda-editor" hidden>
<textarea id="agenda-edit-area" rows="4" placeholder="one item per line, top first — empty clears the agenda"></textarea>
<div class="pane-editor-actions">
<button id="agenda-save">save</button>
<button id="agenda-cancel">cancel</button>
</div>
</div>
</section>
<section id="notes-pane">
<div class="pane-head">
@@ -152,11 +128,11 @@
<section id="housekeeping">
<h2>housekeeping</h2>
<div id="hk-state"></div>
<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>
<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>
<button id="hk-run" hidden>close session &amp; housekeep</button>
<label id="hk-override-row"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
<button id="session-open" hidden>open session</button>
<button id="hk-replay" hidden title="run the housekeeper over the session log — nothing applied">dry-run housekeeping</button>
<details id="hk-log" hidden><summary>session 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 id="fork-pane">
@@ -164,13 +140,7 @@
<p class="hint">a copy of this run — yours to continue</p>
<button id="fork-btn">fork this run</button>
</section>
<section id="models-pane" hidden>
<h2>models</h2>
<label class="field">player <select id="pm-player"></select></label>
<label class="field">housekeeper <select id="pm-housekeeper"></select></label>
<button id="pm-save">save models</button>
<span id="pm-state"></span>
</section>
<section id="models-pane" hidden></section>
</aside>
<footer>
+33
View File
@@ -0,0 +1,33 @@
// web/log.mjs — diagnostics: a rolling event log that survives
// refreshes.
//
// The api() choke point records every server call (status + duration),
// uncaught errors land here, and so do navigation ejections — the
// "why did the app throw me out" history the ten-second banner loses.
// Kept in sessionStorage; the header's "log" button shows it.
import { $ } from './dom.mjs';
const log = [];
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt — start empty */ }
export function logEvent(kind, text) {
log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
if (log.length > 300) log.splice(0, log.length - 300);
try { sessionStorage.setItem('diag', JSON.stringify(log)); } catch { /* storage full or blocked — the in-memory copy lives on */ }
}
function renderDiag() {
const d = $('diag');
d.textContent = log.join('\n');
d.scrollTop = d.scrollHeight;
}
$('diag-btn').addEventListener('click', () => {
const d = $('diag');
d.hidden = !d.hidden;
if (!d.hidden) renderDiag();
});
window.addEventListener('error', (e) => logEvent('error', e.message));
window.addEventListener('unhandledrejection', (e) => logEvent('error', `unhandled: ${e.reason?.message ?? e.reason}`));
+59
View File
@@ -0,0 +1,59 @@
// web/router.mjs — path routing and the view lifecycle.
//
// Views register { el, enter, leave? } at boot (app.mjs). render()
// routes the path, then show() runs the previous view's leave and
// the next view's enter — each view owns its own teardown, so the
// router never has to know a pane's internals. Stale async work is
// dropped by the seq guard: a view captures seq at enter and checks
// it after every await.
import { $ } from './dom.mjs';
import { state } from './state.mjs';
import { banner, hideBanner, renderMeter, setWho, setSessionInfo } from './chrome.mjs';
import { logEvent } from './log.mjs';
const views = {};
export function registerViews(map) { Object.assign(views, map); }
export function navigate(p) {
history.pushState({}, '', p);
render();
}
window.addEventListener('popstate', () => render());
export async function render() {
const seq = ++state.seq;
hideBanner();
const p = location.pathname;
let name = null;
let arg = null;
let m;
if (p === '/') name = 'home';
else if (p === '/new') name = 'new';
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) { name = 'setup'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
else return navigate('/');
if (!state.me) name = 'claim'; // signed out: every path leads to the claim
await show(name, arg, seq);
}
async function show(name, arg, seq) {
const prev = state.view;
if (prev && prev !== name && views[prev].leave) views[prev].leave();
state.view = name;
for (const [n, v] of Object.entries(views)) $(v.el).hidden = n !== name;
document.body.classList.toggle('play', name === 'play');
setWho(state.me);
setSessionInfo('');
renderMeter(null);
await views[name].enter(arg, seq);
}
// a run that vanished under us (deleted, 404): leave loudly for home.
// render() clears the banner first — set it after the navigate.
export function runGone(id, from) {
navigate('/');
banner(`run ${id} is gone — deleted?`);
logEvent('nav', `left ${from} for home: run gone (404)`);
}
+14
View File
@@ -0,0 +1,14 @@
// web/state.mjs — the shared runtime state.
//
// Deliberately small: auth (me), the render sequence (seq — the
// async race guard; a view captures it at enter and checks it after
// every await), and the currently addressed run (runId — setup and
// play both write here; saves address it). Everything else is
// module-local to the view or widget that owns it.
export const state = {
view: null, // the active view name ('claim' | 'home' | ...)
seq: 0,
me: null, // the signed-in user ({ id, name, superuser }) or null
runId: null,
};
+7 -11
View File
@@ -56,7 +56,7 @@ header {
#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; }
#session-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; }
@@ -131,7 +131,6 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
/* --- identity + admin --- */
#who { color: var(--dim); font-size: 13px; }
#logout-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#claim-form { max-width: 480px; }
@@ -162,7 +161,6 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
#models-pane .field { margin-bottom: 6px; }
#models-pane .field select { flex: 1; }
#models-pane button { width: 100%; margin-top: 4px; }
#pm-state { color: var(--dim); font-size: 11px; }
/* the naming form (new run) and the vars box (setup) */
#create-form { max-width: 560px; }
@@ -183,7 +181,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
}
#setup-vars-state, #models-state { color: var(--dim); font-size: 12px; }
#setup-vars-state, .save-state { color: var(--dim); font-size: 12px; }
#setup-models .field select { flex: 1; }
/* --- setup: the editor --- */
@@ -323,15 +321,13 @@ body.play #play-aside { display: block; }
.pane-head h2 { flex: 1; margin: 4px 0 8px; }
.pane-head button { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#paper { margin: 0; line-height: 1.5; }
#paper.empty { color: var(--dim); font-style: italic; }
#status { margin: 0; line-height: 1.5; }
#status.empty { color: var(--dim); font-style: italic; }
#agenda-pane { margin-top: 16px; }
#agenda { margin: 0; line-height: 1.5; }
#agenda.empty { color: var(--dim); font-style: italic; }
#agenda-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
#paper-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
.pane-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; }
@@ -358,13 +354,13 @@ body.play #play-aside { display: block; }
#hk-log pre { white-space: pre-wrap; font-size: 12px; max-height: 40vh; overflow-y: auto; }
#housekeeping button { width: 100%; margin-top: 6px; }
#hk-override-wrap { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; }
#hk-override-row { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; }
/* --- footer (play) --- */
footer {
grid-area: footer;
display: flex; gap: 8px; padding: 10px 14px;
gap: 8px; padding: 10px 14px;
background: var(--panel); border-top: 1px solid var(--line);
display: none;
}
+216
View File
@@ -0,0 +1,216 @@
// web/transcript.mjs — the transcript: register rendering and the
// entry walk.
//
// The transcript renders three registers by the ruled markers: plain
// text is speech, *italics* is narration, a line opening with `(` is
// OOC (closing paren optional; a lone paren is an empty OOC line and
// is skipped). The <status>/<agenda> blocks riding GM turns and the
// delta tags on player turns are machinery, not prose — they render
// as chips and pane state, mirroring the live-context policy.
import { $, el } from './dom.mjs';
// splits text into spans: *italics* = narration, **bold** = emphasis
function renderSpans(target, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) {
if (!p) continue;
if (p.startsWith('**') && p.endsWith('**')) {
const b = document.createElement('strong');
b.textContent = p.slice(2, -2);
target.appendChild(b);
} else if (p.startsWith('*') && p.endsWith('*') && p.length > 2) {
const i = document.createElement('em');
i.className = 'narration';
i.textContent = p.slice(1, -1);
target.appendChild(i);
} else {
target.appendChild(document.createTextNode(p));
}
}
}
// one content block (a GM or player turn) -> DOM lines. extract pulls
// the riding blocks (status/conflict/agenda) out of GM prose; the
// delta tags on player turns always render as chips.
function renderContent(target, text, { extract }) {
let body = String(text ?? '');
let status = null;
let conflict = null;
let agenda = null;
if (extract) {
const sm = body.match(/<status>([\s\S]*?)<\/status>/);
if (sm) { status = sm[1]; body = body.replace(sm[0], ''); }
const cm = body.match(/<conflict>([\s\S]*?)<\/conflict>/);
if (cm) { conflict = cm[1]; body = body.replace(cm[0], ''); }
const am = body.match(/<agenda>([\s\S]*?)<\/agenda>/);
if (am) { agenda = am[1]; body = body.replace(am[0], ''); }
}
const tags = [];
for (const m of body.matchAll(/<(lost|gained|add|drop)>([\s\S]*?)<\/\1>/g)) {
tags.push({ kind: m[1], items: m[2].split('\n').flatMap((l) => l.split(',')).map((x) => x.trim()).filter(Boolean) });
}
for (const t of tags) body = body.replace(new RegExp(`<${t.kind}>[\\s\\S]*?</${t.kind}>`), '');
let narr = false; // an open multi-line narration block
for (const line of body.split('\n')) {
const t = line.trim();
if (!t) { target.appendChild(document.createElement('br')); continue; }
if (t.startsWith('(')) {
if (t === '(') continue; // empty OOC — skip
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
target.appendChild(d);
continue;
}
if (t.startsWith('<')) {
// substrate lines: an opening <tag> is always OOC (invariants.md).
// Known blocks were extracted above; whatever remains is an
// unknown or unbalanced tag — keep it visible, styled as OOC
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
target.appendChild(d);
continue;
}
const stars = (line.match(/\*/g) ?? []).length;
if (!narr && stars % 2 === 0) {
// balanced: spans carry the registers — mixed lines
// (`*foo* bar *baz*`), whole-line narration (`*she sleeps.*`),
// bold — all render correctly
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
target.appendChild(d);
continue;
}
if (!narr && !(t.startsWith('*') && !t.startsWith('**'))) {
// a stray unpaired * mid-line is not a block opener — render
// as-is; the stray stays literal
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
target.appendChild(d);
continue;
}
// block narration: an unpaired leading * opens a multi-line
// block, a trailing * closes it
let content = line.replace(/^\s*\*/, '');
narr = true;
if (t.endsWith('*') && !t.endsWith('**')) {
narr = false;
content = content.trimEnd().slice(0, -1);
}
const d = document.createElement('div');
d.className = 'line narration';
renderSpans(d, content);
target.appendChild(d);
}
if (tags.length) {
const wrap = document.createElement('div');
wrap.className = 'tags';
for (const t of tags) {
for (const item of t.items) {
const c = document.createElement('span');
c.className = `chip ${t.kind}`;
c.textContent = item;
wrap.appendChild(c);
}
}
target.appendChild(wrap);
}
return { status, conflict, agenda };
}
// the entry walk. onConflict receives a conflict block found on a GM
// turn — the play view owns where it lands (the status pane).
export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript');
t.textContent = '';
const bundleParts = [];
const flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `session bundle — ${bundleParts.map((p) => p.part).join(', ')}`));
for (const p of bundleParts) {
const sec = el('details');
sec.appendChild(el('summary', null, p.part));
sec.appendChild(el('pre', null, p.m.content));
d.appendChild(sec);
}
t.appendChild(d);
bundleParts.length = 0;
};
for (const e of entries) {
if (e.t === 'bundle') {
// every part is inspectable, read-only: system (guards +
// substrate + craft), backdrop, character, the rings
bundleParts.push(e);
continue;
}
flushBundle();
if (e.t === 'msg' && e.reminder) {
// the turn reminder: the transcript mirrors the live-context
// policy — one collapsed card for the newest copy, superseded
// ones elide (the log keeps every as-sent chunk)
const newest = [...entries].reverse().find((x) => x.reminder);
if (e === newest) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder — rides every GM turn'));
d.appendChild(el('pre', null, e.m.content));
t.appendChild(d);
}
continue;
}
if (e.t === 'msg') {
if (e.m.role === 'user' && e.conflictOnly) {
// the self-heal message: error traffic on its own, never GM prose
t.appendChild(el('div', 'machinery', `[conflict] ${String(e.m.content).replace(/<\/?conflict>/g, '').trim()}`));
continue;
}
if (e.m.role === 'user') gmTurn(e.m.content, 'GM');
else if (e.m.role === 'assistant') playerTurn(e);
continue;
}
if (e.t === 'tool') {
t.appendChild(el('div', 'machinery', `${e.ask ? '[ruling] ' : '[tool result] '}${String(e.m.content).split('\n')[0]}`));
continue;
}
if (e.t === 'note') renderNote(e);
}
flushBundle();
t.scrollTop = t.scrollHeight;
function gmTurn(content, who) {
const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who));
const body = el('div');
d.appendChild(body);
const { conflict } = renderContent(body, content, { extract: true });
if (conflict) onConflict?.(conflict);
t.appendChild(d);
}
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
const body = el('div');
d.appendChild(body);
if (e.m.reasoning_content) d.appendChild(el('div', 'machinery', '[thinking is logged for the housekeeper, not shown]'));
renderContent(body, e.m.content, { extract: false });
for (const c of e.m.tool_calls ?? []) {
d.appendChild(el('div', 'machinery', `[tool call] ${c.function.name}`));
}
t.appendChild(d);
}
function renderNote(e) {
let text = null;
if (e.kind === 'session') text = `session opened ${e.at}${e.fresh ? ' — fresh' : ''}`;
else if (e.kind === 'seed') text = `seed ${e.ok ? 'applied' : 'failed'}: ${e.detail}`;
else if (e.kind === 'ingest') text = `turn-0 status ${e.ok === false ? 'INGEST FAILED' : 'ingested'}${e.ok === false ? `: ${(e.detail ?? '').split('\n')[0]}` : ''}`;
else if (e.kind === 'ask') text = `ask_gm: ${e.question}`;
else if (e.kind === 'status') text = `status: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
if (text) t.appendChild(el('div', 'machinery', text));
}
}
+35
View File
@@ -0,0 +1,35 @@
// web/view-claim.mjs — the invite claim: the only public screen.
// A single-use invite code is exchanged for a persistent token; the
// display name is a freeform label, collisions allowed.
import { $ } from './dom.mjs';
import { api, setToken } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { logEvent } from './log.mjs';
import { navigate } from './router.mjs';
export async function enter(arg, seq) {
$('claim-code').value = '';
$('claim-name').value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? 'this deployment has no users yet — the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-code').focus();
}
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const r = await api('/claim', { method: 'POST', body: { code: $('claim-code').value.trim(), name: $('claim-name').value.trim() } });
setToken(r.token);
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
banner(err.message);
}
});
+109
View File
@@ -0,0 +1,109 @@
// web/view-home.mjs — home: the run list (display names, live state,
// the ownership garnish) plus the superuser admin (invites, users).
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, render } from './router.mjs';
import { armedButton } from './widgets.mjs';
export async function enter(arg, seq) {
const runs = await api('/runs');
if (seq !== state.seq) return;
const list = $('run-list');
list.textContent = '';
if (!runs.length) {
list.appendChild(el('div', 'hint', 'no runs yet — start one from a package'));
}
for (const r of runs) {
const mine = state.me && r.owner === state.me.id;
const card = el('button', 'card run-card');
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta — chrome, never model-facing
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.models?.player ? ` · ${r.models.player}` : ''}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
// another user's draft is read-only: the play view says so; your own opens the editor
card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
list.appendChild(card);
}
await renderAdmin(seq);
}
const ownershipTag = (r, mine) =>
(mine ? ' · yours' : r.owner == null ? ' · ownerless' : ` · ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
function runStateText(r) {
if (!r.lastSession) return 'draft — not started yet';
if (r.open) return `session open${r.pendingAsk ? ' — waiting for your answer' : ''}`;
if (r.lastSession !== r.lastHousekept) return 'session closed, never housekept';
return 'session closed';
}
function runStateClass(r) {
if (!r.lastSession) return 'draft';
if (r.pendingAsk) return 'attention';
if (r.open) return 'ok';
if (r.lastSession !== r.lastHousekept) return 'attention';
return '';
}
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
invList.textContent = '';
for (const i of inv.invites) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} — ${i.state}`));
if (i.state === 'unclaimed') {
const b = el('button', null, 'revoke');
b.addEventListener('click', async () => {
try { await api(`/invites/${i.id}`, { method: 'DELETE' }); render(); } catch (e) { banner(e.message); }
});
row.appendChild(b);
}
invList.appendChild(row);
}
const userList = $('user-list');
userList.textContent = '';
for (const u of us.users) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `${u.name} · ${u.id}${u.superuser ? ' · op' : ''}`));
if (u.id !== state.me.id) {
const b = el('button', 'danger', 'revoke');
// revocation destroys the identity — two-click armed, like
// every destructive act
armedButton(b, {
label: 'revoke',
confirm: 'sure? click again',
fire: async () => {
try { await api(`/users/${u.id}/revoke`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
render();
},
});
row.appendChild(b);
}
userList.appendChild(row);
}
}
$('new-run-btn').addEventListener('click', () => navigate('/new'));
$('invite-mint').addEventListener('click', async () => {
try {
const r = await api('/invites', { method: 'POST', body: {} });
$('invite-code').textContent = r.code; // shown once — it is never listed again
render();
} catch (e) {
banner(e.message);
}
});
+59
View File
@@ -0,0 +1,59 @@
// web/view-new.mjs — new run: the package picker, then the naming
// form — the package display name plus the main character's name,
// rolled from the dictionary, unused by any run. Runs of the same
// package need distinct pc names.
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
let pkg = null; // the picked package — the view owns it
export async function enter(arg, seq) {
$('package-pick').hidden = false;
$('create-form').hidden = true;
const pkgs = await api('/packages');
if (seq !== state.seq) return;
const list = $('package-list');
list.textContent = '';
for (const p of pkgs) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} · ${origin} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete — missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
}
}
async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start — ${p.display}`;
$('create-name').value = p.display;
$('create-pc').value = '';
$('create-pc').placeholder = 'rolling a name…';
$('create-pc').focus();
const roll = await api('/names').catch(() => null);
if (state.view !== 'new' || $('create-form').hidden) return;
if ($('create-pc').value === '' && roll?.name) $('create-pc').value = roll.name;
}
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('create-name').value.trim();
const pc = $('create-pc').value.trim();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
const r = await api('/runs', { method: 'POST', body: { package: pkg?.name, pc, name } });
navigate(`/runs/${r.run.id}/setup`);
} catch (err) {
banner(err.message);
}
});
+386
View File
@@ -0,0 +1,386 @@
// web/view-play.mjs — the play surface: the transcript, her two
// blocks (the status pane and the agenda pane — one widget, two
// instances), the GM notepad, housekeeping (close session, the
// dry-run replay), fork, and the input line.
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chrome.mjs';
import { navigate, render, runGone } from './router.mjs';
import { logEvent } from './log.mjs';
import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs';
import { renderTranscript } from './transcript.mjs';
// her two blocks, split along the seam: how she is (the status) vs
// what she means to do (the agenda). Both render compact, mirroring
// the wire formats the model cites.
const statusPane = paneEditor({
section: 'status-pane',
body: 'status',
empty: 'a blank sheet',
placeholder: 'one description per line — empty clears the status',
rows: 5,
format: (items) => items.join(', '), // compact, mirroring the <status> wire format
toText: (items) => items.join('\n'),
fromText: (text) => text
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
.map((x) => x.trim()).filter(Boolean),
save: (items) => api(`/runs/${state.runId}/status`, { method: 'POST', body: { items } }),
});
const agendaPane = paneEditor({
section: 'agenda-pane',
body: 'agenda',
empty: 'a clear head',
placeholder: 'one item per line, top first — empty clears the agenda',
rows: 4,
// the queue numbered from the top, exactly as the model cites it
format: (items) => items.map((d, i) => `${i}. ${d}`).join('; '),
toText: (items) => items.join('\n'),
fromText: (text) => text
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
.map((x) => x.trim()).filter(Boolean),
save: (items) => api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } }),
});
const models = modelsBox('models-pane', { title: 'models' });
export function leave() {
saveNotes();
stopPoll();
$('ask-modal').close();
}
export async function enter(id, seq) {
statusPane.reset();
agendaPane.reset();
$('conflict').hidden = true;
await saveNotes(); // flush the pad for the previous run before switching
state.runId = id;
notesDirty = false;
$('gm-notes').value = '';
$('notes-state').textContent = '';
await refreshPlay(id, seq);
}
async function refreshPlay(id, seq) {
let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
return banner(`could not reach the server: ${e.message}`); // stay put — transient
}
if (seq !== state.seq) return;
const mine = state.me && detail.run.owner === state.me.id;
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
setSessionInfo(`${detail.display} — a draft, not yours`);
$('transcript').textContent = '';
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft — fork it to make it yours and edit it'));
return;
}
setSessionInfo((detail.open
? `${detail.display} — session ${detail.session}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: `${detail.display} — no open session`)
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating'));
renderMeter(detail);
statusPane.set(detail.status);
agendaPane.set(detail.agenda);
$('conflict').hidden = true;
// spectator mode: read everything, mutate nothing — the fork is the
// way in. Ownerless runs are spectators for everyone alike.
statusPane.setEditable(mine);
agendaPane.setEditable(mine);
$('gm-notes').readOnly = !mine;
let beatNeeded = false;
if (detail.open) {
const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict });
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
} else {
$('transcript').textContent = '';
}
// the opening beat, if start was interrupted or the session was opened directly
if (beatNeeded) await offerBeat(id, seq);
// controls
$('session-open').hidden = detail.open || !mine;
$('hk-run').hidden = !detail.open || !mine;
$('hk-replay').hidden = !detail.lastSession || !mine; // any session log is replayable, by the owner
setInput(detail.open && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
? 'GM line — Enter sends, Shift+Enter newlines'
: 'spectating — fork this run to continue it as yours';
// models: the owner's per-run overrides
$('models-pane').hidden = !mine;
if (mine) {
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
}
// pending ask: the modal re-presents after a refresh — the owner's
// to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
} else {
$('ask-modal').close();
}
// housekeeping state
const hk = await api(`/runs/${id}/housekeeping`);
if (seq !== state.seq) return;
renderHk(hk);
// the GM's notepad — skip the reload if a save failed (dirty wins)
await loadNotes(id, seq);
}
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
c.hidden = false;
}
// --- the GM's notepad: always on screen, auto-saved -------------------
//
// A debounced save (1s after the last keystroke, immediate on blur),
// flushed when leaving the play view or switching runs. gm.md never
// reaches any model — this is the GM's own notes.
let notesTimer = null;
let notesDirty = false;
async function loadNotes(id, seq) {
const notes = await api(`/runs/${id}/notes`).catch(() => null);
if (!notes || seq !== state.seq || notesDirty) return;
$('gm-notes').value = notes.content;
}
function notesInput() {
notesDirty = true;
$('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer);
notesTimer = setTimeout(saveNotes, 1000);
}
async function saveNotes() {
clearTimeout(notesTimer);
if (!notesDirty || !state.runId) return;
const content = $('gm-notes').value;
try {
// keepalive: the flush must survive leaving the page entirely
await api(`/runs/${state.runId}/notes`, { method: 'PUT', body: { content }, keepalive: true });
notesDirty = false;
$('notes-state').textContent = 'saved';
} catch (e) {
$('notes-state').textContent = 'not saved';
banner(e.message);
}
}
async function offerBeat(id, seq) {
let hasTurn0 = true;
try {
const files = await api(`/runs/${id}/files`);
if (seq !== state.seq) return;
hasTurn0 = files.files['turn-0.md']?.exists === true;
} catch { /* try the endpoint anyway */ }
if (!hasTurn0) return;
const bar = el('div', 'beat');
bar.appendChild(el('span', null, 'the session is open; the opening beat has not been sent'));
const b = el('button', 'primary', 'send the opening beat');
b.addEventListener('click', async () => {
setBusy(true);
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
banner(e.message);
}
setBusy(false);
render();
});
bar.appendChild(b);
$('transcript').prepend(bar);
}
function setHk(stateText, cls) {
const h = $('hk-state');
h.textContent = stateText;
h.className = cls ?? '';
}
function renderHk(hk) {
if (hk.state === 'running') {
setHk('housekeeping…', '');
startPoll();
return;
}
stopPoll();
if (hk.state === 'applied') {
setHk(`applied — session ${hk.session ?? ''}\nnext session open`, 'applied');
loadLog(); // idempotent — also covers a refresh while applied
} else if (hk.state === 'rejected') {
setHk(`rejected — held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
} else {
setHk('idle', '');
}
}
function setInput(ok) {
$('gm-input').disabled = !ok;
$('gm-send').disabled = !ok;
}
// --- actions -----------------------------------------------------------
async function sendTurn() {
const line = $('gm-input').value.trim();
if (!line || !state.runId) return;
$('gm-input').value = '';
setInput(false);
setBusy(true);
try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
} catch (e) {
banner(e.message);
$('gm-input').value = line; // a failed send must not eat the line
}
setBusy(false);
render();
}
async function sendAnswer() {
const answer = $('ask-answer').value.trim();
if (!answer || !state.runId) return;
$('ask-answer').value = '';
setBusy(true);
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) {
banner(e.message);
$('ask-answer').value = answer;
}
setBusy(false);
render();
}
// fork: a copy of this run under you — any run, anyone's, including
// yours. Lands you in the fork.
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking…');
try {
const r = await api(`/runs/${state.runId}/fork`, { method: 'POST', body: {} });
setBusy(false);
logEvent('nav', `forked ${state.runId} -> ${r.run}`);
navigate(`/runs/${r.run}`);
} catch (e) {
setBusy(false);
banner(e.message);
}
}
async function openSession() {
const override = $('hk-override').checked;
hideBanner();
try {
await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
$('hk-override').checked = false;
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
banner(`${e.message}\n${e.detail.hint}`, 'info');
} else {
banner(e.message);
}
}
render();
}
// dry-run: the housekeeper reads the session log, the manifest lands
// in the pane — nothing applied, the session stays open
async function replayHousekeeping() {
setBusy(true, 'the housekeeper reads…');
try {
const r = await api(`/runs/${state.runId}/housekeeping/replay`, { method: 'POST', body: {} });
$('hk-replay-content').textContent = r.parsed
? JSON.stringify(r.manifest, null, 2)
: `${r.reason}\n\nraw output: ${r.file}`;
$('hk-replay-log').hidden = false;
$('hk-replay-log').open = true;
} catch (e) {
banner(e.message);
}
setBusy(false);
}
// --- housekeeping poll + log -------------------------------------------
let poll = null;
function startPoll() {
stopPoll();
poll = setInterval(async () => {
if (!state.runId || state.view !== 'play') return stopPoll();
const hk = await api(`/runs/${state.runId}/housekeeping`).catch(() => null);
if (hk && hk.state !== 'running') render();
}, 3000);
}
function stopPoll() {
if (poll) clearInterval(poll);
poll = null;
}
async function loadLog() {
try {
const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content;
$('hk-log').hidden = false;
$('hk-log').open = true;
} catch {
$('hk-log').hidden = true;
}
}
// --- wiring ---
armedButton($('hk-run'), {
label: 'close session & housekeep',
confirm: 'sure? click again to close & housekeep',
fire: async () => {
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('housekeeping…', '');
startPoll();
} catch (e) {
banner(e.message);
}
render();
},
});
$('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
});
$('ask-send').addEventListener('click', sendAnswer);
$('ask-answer').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
});
$('session-open').addEventListener('click', openSession);
$('hk-replay').addEventListener('click', replayHousekeeping);
$('fork-btn').addEventListener('click', forkRun);
$('gm-notes').addEventListener('input', notesInput);
$('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
+319
View File
@@ -0,0 +1,319 @@
// web/view-setup.mjs — the draft editor: the full assembly in bundle
// order (the repo-fed prompts read-only, the run's craft editable,
// config read-only), the prompt-declared $TOKEN inputs, per-run
// models, and the two exits — save as package (publishes it) or
// start (opens the session, sends turn-0).
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs';
import { armedButton, modelList, modelsBox } from './widgets.mjs';
// one list, in bundle-assembly order: the repo-fed system message
// parts (read-only — the user should understand how the model is
// prompted), the craft tail and GM messages (editable), then the
// initial state, then run config (read-only). Everything the run
// sends, nothing it doesn't.
const EDIT_LIST = [
{ name: 'system.md', mode: 'ro', source: 'repo' },
{ name: 'invariants.md', mode: 'ro', source: 'repo' },
{ name: 'reminder.md', mode: 'ro', source: 'repo' }, // rides every turn as its own system chunk
{ name: 'handbook.md', mode: 'rw', source: 'run' },
{ name: 'backdrop.md', mode: 'rw', source: 'run' },
{ name: 'character.md', mode: 'rw', source: 'run' },
{ name: 'seed.json', mode: 'rw', source: 'run' }, // the rings it seeds — turn-0 wakes into them
{ name: 'turn-0.md', mode: 'rw', source: 'run' },
{ name: 'settings.json', mode: 'ro', source: 'run' },
{ name: 'run.json', mode: 'ro', source: 'run' },
];
// the editor's working set — module-local, reset on every enter
let files = null; // { name: { content, exists } }
let drafts = {}; // unsaved edits by file name
let currentFile = null;
let fileSpecs = {};
let repoPrompts = {};
const models = modelsBox('setup-models', { title: 'models — per-run, over the deployment defaults' });
export async function enter(id, seq) {
state.runId = id;
drafts = {};
currentFile = null;
let detail, filesResp, prompts;
try {
[detail, filesResp, prompts] = await Promise.all([
api(`/runs/${id}`),
api(`/runs/${id}/files`),
api('/prompts'),
]);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
return banner(`could not reach the server: ${e.message}`); // stay put — transient
}
if (seq !== state.seq) return;
if (!detail.draft) return navigate(`/runs/${id}`); // started runs live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only — fork to edit
files = filesResp.files;
repoPrompts = {
'system.md': prompts.system ?? '',
'invariants.md': prompts.invariants ?? '',
'reminder.md': prompts.reminder ?? '',
};
$('setup-title').textContent = detail.display;
$('setup-state').textContent = `${detail.run.package} · ${id} — draft; edits land when the session opens`;
$('setup-start').disabled = false;
$('setup-start').textContent = 'start';
// prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, files);
let currentVars = {};
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings — empty vars */ }
const varsList = $('setup-vars-list');
varsList.textContent = '';
$('setup-vars').hidden = !vars.length;
$('setup-vars-state').textContent = '';
for (const tok of vars) {
const row = el('label', 'field', `$${tok}`);
const inp = el('input');
inp.dataset.token = tok;
inp.value = currentVars[tok] ?? '';
row.appendChild(inp);
varsList.appendChild(row);
}
// models: per-run overrides, selected from the upstream listing
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
const nav = $('setup-files');
nav.textContent = '';
fileSpecs = {};
for (const e of EDIT_LIST) {
const runFile = files[e.name];
const spec = {
...e,
exists: e.source === 'repo' ? true : !!runFile?.exists,
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
};
fileSpecs[e.name] = spec;
const item = el('button', `file-item${e.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
item.appendChild(el('span', 'file-name', e.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => selectFile(e.name));
nav.appendChild(item);
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
}
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or run copy) becomes a fillable input in setup
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
files['handbook.md']?.content,
files['backdrop.md']?.content, files['character.md']?.content, files['turn-0.md']?.content,
];
const found = new Set();
for (const t of texts) {
if (!t) continue;
for (const m of t.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) found.add(m[1]);
}
return [...found].sort();
}
function collectVars() {
const vars = {};
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim();
return vars;
}
async function saveVars() {
const vars = collectVars();
if (!Object.keys(vars).length) return;
await api(`/runs/${state.runId}/vars`, { method: 'POST', body: { vars } });
$('setup-vars-state').textContent = 'saved';
}
function selectFile(f) {
const prev = currentFile;
if (prev === f) return;
if (prev && fileSpecs[prev]?.mode === 'rw') stashDraft(prev);
currentFile = f;
const spec = fileSpecs[f] ?? { mode: 'rw', source: 'run', exists: false };
const content = spec.source === 'repo'
? (repoPrompts[f] ?? '')
: (drafts[f] ?? spec.content ?? '');
$('setup-edit').value = content;
$('setup-edit').disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
renderHighlight();
markNav();
}
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain — @ syntax is not owned here
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const ta = $('setup-edit');
const hl = $('edit-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
+ '\n\u200b'; // keep the trailing empty line's height honest
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
function stashDraft(f) {
if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
const v = $('setup-edit').value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v;
markNav();
}
function markNav() {
const items = $('setup-files').children;
for (const item of items) {
const name = item.querySelector('.file-name').textContent.replace(' (new)', '');
item.classList.toggle('dirty', drafts[name] !== undefined);
item.classList.toggle('current', name === currentFile);
}
}
async function saveFile() {
const f = currentFile;
if (!f) return;
$('setup-save').disabled = true;
try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } });
files[f].content = $('setup-edit').value;
files[f].exists = true;
delete drafts[f];
$('setup-edit-state').textContent = 'saved';
markNav();
} catch (e) {
banner(e.message);
$('setup-edit-state').textContent = 'not saved';
}
$('setup-save').disabled = false;
}
async function saveDirty() {
stashDraft(currentFile);
for (const [f, content] of Object.entries({ ...drafts })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
files[f].content = content;
files[f].exists = true;
delete drafts[f];
}
markNav();
}
// save the run's craft as a new user package — published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true;
$('savepkg-state').textContent = 'saving…';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved — ${r.package.id}`;
$('savepkg-name').value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
}
async function startRun() {
const id = state.runId;
const btn = $('setup-start');
// the prompts' own inputs must be filled — the guard at session-open
// is the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) {
if (!v) {
banner(`$${tok} is unfilled — a prompt declares it, the run needs it`);
return;
}
}
btn.disabled = true;
btn.textContent = 'starting…';
try {
await saveVars();
await saveDirty();
} catch (e) {
banner(`did not start — ${e.message}`);
btn.disabled = false;
btn.textContent = 'start';
return;
}
let opened = false;
try {
await api(`/runs/${id}/sessions`, { method: 'POST', body: {} });
opened = true;
} catch (e) {
banner(e.message);
}
if (opened && files['turn-0.md']?.exists) {
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
banner(`${e.message} — the beat can be sent from the play view`);
}
}
navigate(`/runs/${id}`);
}
// --- wiring ---
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side — stories are deleted by hand.
armedButton($('setup-delete'), {
label: 'delete draft',
confirm: 'sure? click again to delete',
fire: async () => {
try {
await api(`/runs/${state.runId}`, { method: 'DELETE' });
navigate('/');
} catch (e) {
banner(e.message);
}
},
});
$('setup-vars-save').addEventListener('click', async () => {
try {
await saveVars();
} catch (e) {
banner(e.message);
$('setup-vars-state').textContent = 'not saved';
}
});
$('setup-save').addEventListener('click', saveFile);
$('setup-edit').addEventListener('input', () => {
if (currentFile) stashDraft(currentFile);
$('setup-edit-state').textContent = 'unsaved';
renderHighlight();
});
$('setup-edit').addEventListener('scroll', () => {
$('edit-hl').scrollTop = $('setup-edit').scrollTop;
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
});
$('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage);
+167
View File
@@ -0,0 +1,167 @@
// web/widgets.mjs — the small factories the views share.
//
// Three patterns that were hand-copied per use, now one each:
// - armedButton: the two-click confirm (no JS confirm() — it blocks
// the embedded pane; every destructive act is armed instead)
// - paneEditor: the status/agenda pattern — a body line, an edit
// button, an inline editor; the section shell stays in index.html
// - modelsBox: the per-run player/housekeeper selects over the
// upstream listing; setup and the play aside each carry one
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { render } from './router.mjs';
// two-click confirm — the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
export function armedButton(btn, { label, confirm, fire }) {
let timer = null;
btn.addEventListener('click', async () => {
if (timer === null) {
btn.textContent = confirm;
timer = setTimeout(() => { timer = null; btn.textContent = label; }, 5000);
return;
}
clearTimeout(timer);
timer = null;
btn.textContent = label;
await fire();
});
}
// a pane: body line + edit button + inline editor. save(items)
// resolves on success and throws on failure — a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the
// spectator state: no edit button, an open editor cancels.
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit');
sec.querySelector('.pane-head').appendChild(editBtn);
const editor = el('div', 'pane-editor');
editor.hidden = true;
const area = el('textarea');
area.rows = rows;
area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions');
const saveBtn = el('button', null, 'save');
const cancelBtn = el('button', null, 'cancel');
actions.appendChild(saveBtn);
actions.appendChild(cancelBtn);
editor.appendChild(area);
editor.appendChild(actions);
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
let items = [];
let mayEdit = false;
let open = false;
const sync = () => {
bodyEl.hidden = open;
editBtn.hidden = open || !mayEdit;
editor.hidden = !open;
};
const renderBody = () => {
bodyEl.textContent = items.length ? format(items) : empty;
bodyEl.classList.toggle('empty', !items.length);
};
const openEditor = () => {
area.value = toText(items);
open = true;
sync();
area.focus();
};
const cancel = () => { open = false; sync(); };
const doSave = async () => {
const next = fromText(area.value);
try {
await save(next);
} catch (e) {
banner(e.message);
return; // stay in the editor — nothing was changed
}
items = next;
cancel();
render(); // the server's truth re-renders the panes
};
editBtn.addEventListener('click', openEditor);
cancelBtn.addEventListener('click', cancel);
saveBtn.addEventListener('click', doSave);
return {
set(next) { items = next ?? []; renderBody(); },
setEditable(ok) { mayEdit = ok; cancel(); },
reset() { cancel(); },
get items() { return items; },
};
}
// the upstream model listing, fetched once per session — a live
// /models call every render would hammer the endpoint for a list
// that rarely changes
let cachedModels = null;
export async function modelList() {
if (!cachedModels) cachedModels = await api('/models').catch(() => []);
return cachedModels;
}
// A select's "" value means "deployment default"; a current override
// missing from the listing stays selectable, so a stale pick never
// silently rewrites itself.
function fillSelect(sel, current, list, def) {
sel.textContent = '';
const mk = (v, label) => {
const o = el('option', null, label);
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` — ${def}` : ' (unset)'}`);
const opts = [...list];
if (current && !opts.includes(current)) opts.push(current);
for (const m of opts) mk(m, m);
sel.value = current ?? '';
}
// the models box: player/housekeeper selects + save, posting the
// per-run overrides. The mount keeps its id — the CSS panels it.
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = el('select');
const houseSel = el('select');
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
hField.appendChild(houseSel);
root.appendChild(pField);
root.appendChild(hField);
const saveBtn = el('button', null, 'save models');
const saveState = el('span', 'save-state');
const actions = el('div', 'form-actions');
actions.appendChild(saveBtn);
actions.appendChild(saveState);
root.appendChild(actions);
saveBtn.addEventListener('click', async () => {
try {
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: { player: playerSel.value || null, housekeeper: houseSel.value || null },
});
saveState.textContent = 'saved';
} catch (e) {
banner(e.message);
saveState.textContent = 'not saved';
}
});
return {
fill(models, defaults, list) {
fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);
saveState.textContent = '';
},
};
}