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