From eefb721675275b45873aaa7f64d4864c87f6b739 Mon Sep 17 00:00:00 2001 From: Mute Date: Tue, 17 Nov 2026 22:35:44 +0000 Subject: [PATCH] the sheet round: the GM's ledger of arbitrated run state -- the second state channel, split from status and agenda by truth model (GM, 2026-11-17). The rulings first: status and agenda are narrative self-report (their truth is "she said so", the scan caches her latest words); the sheet is actual run state (its truth is "the GM set so", the record IS the truth event -- nothing cached from anyone's words). The override channel promoted to a standing section, and that precedent decided the presentation: the sheet renders as its OWN authoritative system chunk at the freshest end, never a canon-point stamp, which would read as her words -- the same reason the override composes as hers and the sheet never does. Schemaless JSON in the tag (the mind-verb philosophy: the substrate teaches the channel, the package teaches the vocabulary -- the invariants rule the GM wrote is one universal paragraph with deliberately non-box examples, clothes and grades, and the propose-additions line as her schema-evolution channel); details learnt in-place; NO package gating -- the channel is universal and "optional, if given" makes the invariant forward-compatible in every bundle that never sets one. The build: a sheet record rides the GM turn like the override (readSheet: object-ness is the route's only law, 400 loud on arrays and scalars, nothing appended; OOC turns refuse it exactly like block edits); scanState derives newest-wins whole-set -- an absent key drops, never keeps, and {} is a live empty ledger (a truthy check, never falsy); the boundary state note carries it across stops and the dormant read path serves it; renderView appends the chunk once per assembly so one live copy holds by construction; the guard is the sibling (an emitted conflicts with "the GM's ledger -- propose changes in prose", healed in-turn, cap 3, and her emission never applies -- the scan holds the GM's record); every strip surface learned the tag (the view's STRIP_HERS, the story's verbs, the table's chip regex -- the standing grep-every-strip-list lesson, applied); and the web gains sheetEditor, the paneEditor's JSON sibling in widgets.mjs (same stage/pending/discard pattern, bad JSON refuses at the stage), the third pane in the aside, the send attaching body.sheet, and [sheet] machinery lines on both table and raw walks. The mock's sheet-guard branch is CUE-KEYED, not position-keyed: the carried tail shifts the script's counts (session 4's log starts the script over -- the battery's first attempt landed on the ask position and crashed renderView on the unpaired call; the battery now answers the script ask and moves on), while a marked GM turn is immune to every shift -- mockModel reads the view, the marked turn earns the emission, the conflict it earns earns the plain-prose heal. check-reminder is sheet-aware (the chunk is a legitimate third system surface; the count and freshest-end assertions tolerate exactly one, and the freshest-end check now allows her latest reply and/or the chunk to follow the reminder). Verified: smoke ALL PASS with +15 sheet assertions (newest-wins, whole-set semantics, the chunk one-live-copy -- ANCHORED with startsWith because the invariants bundle itself mentions the tag and a bare regex matches it twice, an honest test bug caught by an honest test), the guard's conflict and heal with her emission kept verbatim in the raw log and never applied, the view and story strips, the empty ledger rendering its chunk, the boundary note carrying the sheet, the dormant read deriving it, and session 5 deriving it from the carried note end to end), restart + reminder checks green, typecheck green on both programs, check-repo clean (it caught the round's own prose twice: "window" is a retired term in README, the contwin vocabulary wins), and a browser pass over the pane end to end with zero console errors -- staging, the pending marker, the ride, the scan re-render, and both machinery lines on the table. Docs: README's protocol passage carries the sheet with the numbers-live-on-the-sheet line (prose numbers die with the contwin; sheet numbers ride the scan forever) -- NOT in the memory tiers table, where the first draft wrongly put it (the GM's ruling: the sheet belongs in neither memories nor records); the identity tier lost its loose "character sheet" name now that the term is technical; DICTIONARY gains the sheet entry with the history line (dice retired into variant literature, sheets arrived as the state machinery -- the tabletop metaphor completing while its realism stays advisory, players hold their own pencils in the real thing and we don't, for drift); ROADMAP parks the bookkeeper extension (the housekeeper's arithmetic sibling: reads the setting's rules prose and the latest turns, computes the ledger delta from a purchase in her prose, lands it as a STAGED edit -- applied on the GM's next turn or discarded; sheet-only authority, curator fallback, per-package opt-in because an agent cannot bookkeep what is not arithmetic). The GM's prompt-side edits ride the same commit: invariants' "Character's sheet" section (the universal rule, the trailing-clause flag taken in review), the reminder's inventory line gaining "the sheet (optional)", and la caramba's gm.md lore updates. The box package (the first consumer) and detention stay untracked WIP, untouched. The 2026-11-17 roadmap audit rides the same commit (GM: "done items can retire"): retired outright -- the SPA-vs-bridge and voice-examples decisions (long resolved) and steal items #1, #3, #4, #8, #11 (done, or in #8's case never work -- the housekeeper model is per-run selection, built); retired with tombstones -- the multiuser section (built 2026-11-14, the rulings live in DECISIONS #22-31 and README, the lifecycle tail kept visible) and the SPA v1 section (all four phases done, the API sketch superseded by README's living API docs, the substrate doctrine in README), with the one unbuilt design it held -- the turn-surgery saga rule -- surviving as its own bullet cross-referenced at steal #2; amended in place, dated -- seed.json (dead, successors named: the authored carryover and memory.json), turn-0.md (dead: her authored opening turn), the upstream model listing (never queried in play since discovery), the delta-tag transport (the full-block protocol, the sheet named), the service step (multiuser built, hosting remains), the carryover editor (the raw file-editor surface exists, the purpose-built UI stays deferred); kept -- the operator's queue, the landscape and receipts, the live constraints, the open steals with numbering preserved so cross-references resolve, the deferred tasks, the distant points, the rejections, the notes. 582 lines to 338; the first deletion pass duplicated the steal-list header and the verification re-read caught it --- AGENTS.md | 66 ++++++- DICTIONARY.md | 22 ++- README.md | 22 ++- ROADMAP.md | 391 ++++++++------------------------------ invariants.md | 6 + packages/la-caramba/gm.md | 9 + reminder.md | 3 +- server/loop.mjs | 28 ++- server/main.mjs | 29 ++- server/session.mjs | 30 ++- server/shapes.mjs | 4 +- test/check-reminder.mjs | 14 +- test/smoke.mjs | 83 +++++++- web/index.html | 6 + web/shapes.mjs | 2 +- web/transcript.mjs | 17 +- web/view-play.mjs | 20 +- web/widgets.mjs | 87 +++++++++ 18 files changed, 491 insertions(+), 348 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b1b2011..d80404e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -137,8 +137,70 @@ memory the agent owes itself across sessions. ## State pointers -- **The progress round is BUILT COMPLETE (2026-11-17, uncommitted, - staged): the streaming provider, the refine meter, and the turn +- **The sheet round is BUILT (2026-11-17, staged, uncommitted): the + GM's ledger of arbitrated run state, the second state channel.** + The rulings that shaped it (all from the 2026-11-17 conversation): + status and agenda are NOT on the sheet -- the split is semantic + (self-report: truth is "she said so", the scan caches her words; + the sheet: truth is "the GM set so", the record IS the truth + event -- the override channel promoted to a standing section, and + that precedent decided the presentation: its own authoritative + system chunk at the freshest end, NEVER a canon-point stamp, which + would read as her words). Schemaless JSON in the tag, one + universal invariants rule (the GM wrote it: optional, free-form + json GM curates, examples deliberately non-box -- clothes, grades; + "you may propose adding things" is her schema-evolution channel), + details learnt in-place (the mind-verb philosophy: the substrate + teaches the channel, the package teaches the vocabulary). NO + package gating -- the channel is universal, "optional, if given" + makes the invariant forward-compatible in every bundle. The build: + records ride GM turns (readSheet: object-ness only, 400 loud; + OOC turns refuse them like block edits), scanState derives + newest-wins whole-set (absent key drops, {} is a live empty + ledger -- truthy check, never falsy), the boundary note carries + it across stops (stopSession's head note + the dormant read + path), renderView appends the chunk once per assembly (one live + copy by construction), the guard conflicts an emitted + ("the GM's ledger -- propose changes in prose", the + guard's sibling, healed in-turn cap 3), STRIP_HERS + the story + verbs + the table chip regex all learned 'sheet' (grep every + strip list after adding a tag -- the standing lesson, applied), + and the web: sheetEditor (the paneEditor's JSON sibling in + widgets.mjs -- same stage/pending/discard pattern, bad JSON + refuses at the stage), the third pane in the aside, the send + attaches body.sheet, machinery lines on table and raw + ([sheet] {...} -- the GM's ledger). The mock's sheet-guard is + CUE-KEYED not position-keyed (the carried tail shifts counts; a + cue does not shift -- mockModel reads the view, the marked GM + turn gets the emission, the conflict it earns gets the heal; the + FIRST battery attempt hit the script's ask at count 1 because + session 4's log starts the script over -- the battery answers it + and moves on). check-reminder is sheet-aware now (the chunk is a + legitimate third system surface; the count and freshest-end + asserts tolerate exactly one). Verified: smoke ALL PASS (+15 + sheet assertions: newest-wins, whole-set, the chunk one-live-copy + -- ANCHOR the chunk match with startsWith, the invariants bundle + itself mentions and a bare regex matches it twice), the + guard conflict + heal + never-applies, view/story strips, the + empty ledger, the boundary note, the dormant read, session 5 + deriving from the carried note), restart + reminder checks green, + typecheck green both programs, check-repo clean, browser pass + zero console errors (staging, pending marker, the ride, the scan + re-render, machinery lines). Docs: README's protocol passage + carries the sheet (NOT in the memory tiers table -- the GM ruled + it belongs in neither memories nor records; the first draft put + a row there and was wrong), the identity tier lost its loose + "character sheet" name (the term is technical now), DICTIONARY + gains the sheet entry with the dice-retired/sheet-arrived + history, ROADMAP gains the bookkeeper extension (the parked + arithmetic-sibling agent: staged edits, curator fallback, + per-package opt-in). The GM's prompt-side edits ride the same + round: invariants' sheet section, the reminder's inventory line, + la-caramba gm.md lore (the spine discussion). PARKED with the + GM: the box package (WIP, theirs) is the first consumer; the + bookkeeper agent; a live turn on a real model with a sheet. +- **The progress round is BUILT COMPLETE (2026-11-17, committed + bbaf336): the streaming provider, the refine meter, and the turn meter are all done and live-proven.** The GM's plan: abandon Chloe, start a fresh run from the top (the huge max-effort result prompted it -- her one max turn thought diff --git a/DICTIONARY.md b/DICTIONARY.md index 084bf71..3d3febc 100644 --- a/DICTIONARY.md +++ b/DICTIONARY.md @@ -145,15 +145,31 @@ WORDS. renders it as if she had stated it -- mutated in place at her newest blocks. The log keeps her words verbatim; the raw surfaces show the record; the model sees only state. +- **the sheet** -- the GM's ledger of arbitrated run state (GM, + 2026-11-17): schemaless JSON inside a `` block, the + setting's prose gives the fields meaning. The second state + channel, split from status/agenda by truth model: those are + narrative self-report (the scan caches her latest words), the + sheet is run state (the GM's record is the truth event, nothing + cached). GM-only authorship, model-read-only (an emitted block + conflicts with a pointer at prose, the `` guard's + sibling); records ride GM turns newest-wins, whole-set (an + absent key drops, never keeps; `{}` is a live empty ledger); + the boundary note carries it across stops. Renders as its own + authoritative system chunk at the freshest end, never a + canon-point stamp. The tabletop metaphor's arrival, after dice + retired into variant literature: numbers that affect play live + on the sheet, never in prose alone. See also: the bookkeeper + (ROADMAP, the parked automation). - **records** -- her files: the card index, the ledger, whatever she keeps. Diegetic and per-run (the settings gate); narrow query, hard cap 10 in the tool; a miss is a miss. Filed at her desk by the player; the housekeeper only archives. - **the backdrop** -- the world as everyone in it knows it: public knowledge. Never memory, never decays, always in the bundle. -- **identity** -- `character.md`, the sheet: concept, drives, skills, - voice. The GM's to edit; the housekeeper proposes via open - questions; blanks are the player's to invent. +- **identity** -- `character.md`: concept, drives, skills, voice. + The GM's to edit; the housekeeper proposes via open questions; + blanks are the player's to invent. - **the manifest** -- the housekeeper's whole output: JSON semantic operations (insert, touch, promote, demote, reword, delete, archive; plus summary, inventions, open questions). Validated and diff --git a/README.md b/README.md index 288637d..7d18782 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,25 @@ consumes into the log, in one action. non-OOC GM turn as a record on it, and the composition renders them as if she had stated them -- mutated in place at her newest blocks, invisible to the model as an act, visible only - as state. The mind verb rides the + as state. The sheet (2026-11-17) is the second state + channel, and the split is semantic: status and agenda are + narrative self-report (their truth is "she said so", the scan + caches her latest words), the sheet is arbitrated run state (its + truth is "the GM set so", nothing cached from anyone's words) -- + schemaless JSON the setting's prose gives meaning to, GM-only + authorship, model-read-only. A sheet record rides a GM turn + like the override, newest-wins, whole-set (an absent key is + dropped, never kept; an empty object is a live empty ledger, + not an absent one); the boundary state note carries it across + stops, so it survives the contwin, housekeeping, and session + boundaries like the other channels. It renders as its own + authoritative system chunk at the freshest end -- never a + canon-point stamp, which would read as her words -- and she + proposes changes in prose: emitting a `` block conflicts + with a pointer at the channel, the same guard `` has. + Numbers that affect play live on the sheet, never in prose + alone -- prose numbers die with the contwin; sheet + numbers ride the scan forever. The mind verb rides the same channel: `{"temperature": 1.4}` in a player turn sets its sampling knobs for its NEXT turn -- one-shot, JSON inside the @@ -335,7 +353,7 @@ Memory is **seven tiers**: | tier | what | in context | who writes it | |---|---|---|---| | **backdrop** | the world as everyone knows it -- public knowledge, the general setting; never memory, never forgotten | always | GM, rarely (retcons) | -| **identity** | the character sheet -- concept, drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent | +| **identity** | the character's concept -- drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent | | **status** | descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | stamped at her most recent turn's tail, the scan's derived value | **the player** (whole-list `` block in its turns; absent = unchanged); GM override riding a turn, composing as hers | | **agenda** | her hot queue of intentions -- what she's working towards right now; a fixed-cap recency buffer (new on top, overflow evicts the bottom), disposable by design | stamped at her most recent turn's tail, the scan's derived value (capped at five -- her full list lives only in the log) | **the player** (whole-list `` block in its turns; over-cap never derivable); GM override riding a turn, composing as hers | | **rings A/B** | salient memory -- facts, on her mind, MRU-evicted | always | housekeeper manifest | diff --git a/ROADMAP.md b/ROADMAP.md index 97fe215..026755d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -6,9 +6,8 @@ be worked through one by one; statuses in caps, decisions dated. ## Operator's queue (don't edit, don't work on) +- entirely safe-for-work package. space? - revisit what fetch does and SPA reactivity -- calibration package: escape room -- calibration package: the detention - user manual - session rewind @@ -49,13 +48,6 @@ long-memory problem is unsolved. Our test aims at that gap. ## Architectural decisions from the review (2026-11-11) -- **SPA: yes, eventually. The bridge is the MVP.** The SPA's defining - features per the review: fiction-first chat UI, GM console, context - inspector (steal #6), memory browser (steal #7), turn surgery buttons - (steal #2 with UI), housekeeping job runner. - (Superseded 2026-11-13: the bridge is retired before ever going live -- - REST + SPA is the MVP. See "The harness" below.) -- **Voice examples: accepted** -- will be present (steal #1). - **Single LLM player, for now at least.** Mechanical per-character data separation (Talemate-style knowledge tracking, per-character perspectives) is superfluous -- the run boundary already separates @@ -107,25 +99,28 @@ example, gitignored real file, env-var option). file land at the next session-open (no hot reload into an open session). Packages carry authored content only -- `canon/`, `db/`, `dumps/`, `log/`, `manifests/`, `sessions/` are all state and are - born in the run at creation. The new-game opener file is `turn-0.md` - (renamed from `prelude.md`, 2026-11-13) -- the GM's zeroth turn, same - semantics: sent once as the first GM message, `` block - ingested. -- **The seed is initial state of the run.** `seed.json` rides the copy - like any other file. It applies lazily at the first session-open of a - fresh run, before render and bundle assembly; until then the run is - freely editable -- deleting or editing `seed.json` in the copy is the - generic opt-out, no flag. After application it is inert provenance: - the journal records the application and a re-apply refuses. + born in the run at creation. (Amended 2026-11-16: the turn-0.md + opener is retired -- the opening is her authored turn in + carryover.jsonl, GM-written, whose authored blocks are the state + seed; the start gate lints it and the old opening event is inert + history.) +- **The seed is initial state of the run.** (Superseded 2026-11-15, + the dormant-session rework: seed.json is gone. Its successors are + carryover.jsonl -- the authored opening turn, whose authored blocks + are the state seed -- and memory.json, authored draft material + applied by the start gate's reapply over a fresh db.) - **Per-run model selection.** `server.json` names one endpoint - (baseUrl, key) plus default models (player, housekeeper). - `GET /api/models` asks the upstream what it carries; the user selects - from the list. A run may carry per-run overrides for both roles - (`run.json` `models: {player, housekeeper}`, wired in the SPA - 2026-11-14 -- setup for drafts, the play aside for started runs; - each call resolves fresh, so a mid-session switch takes the next - turn) -- the comparison rig: same package, different models, - identical prompts. Which model the housekeeper DEFAULT points at + (baseUrl, key) plus default models (player, housekeeper). A run + carries per-run overrides for both roles (`run.json` `models: + {player, housekeeper}`, wired in the SPA 2026-11-14 -- setup for + drafts, the play aside for started runs; each call resolves fresh, + so a mid-session switch takes the next turn) -- the comparison rig: + same package, different models, identical prompts. (Amended + 2026-11-16, model discovery: the upstream listing is never queried + in play -- state/models.json is the registry of selectable models, + written by the op's two-step discover/refine act and gating all + model use; server.json's explicit pick beats the registry's + discovered default.) Which model the housekeeper DEFAULT points at stays open (#16); the mechanism is settled. - **The player prompt is battery included, split along ownership seams (ruled 2026-11-13; cut executed by the GM 2026-11-14).** Three tiers, @@ -134,10 +129,13 @@ example, gitignored real file, env-var option). copied, travels with the code: the syntax markers the renderer parses registers by (plain = speech, *italic* = narration, single-paren OOC), the tool-channel contract, the memory contract, - records availability via the tool list, the status tag transport - (``/``/``/``) **and the status's - three-part admission gate** (moved into the substrate tier in the - GM's cut). Implementation-agnostic by design: storage details + records availability via the tool list, the block transport + **and the status's three-part admission gate** (moved into the + substrate tier in the GM's cut). (Amended 2026-11-16, the + full-block protocol: the delta verbs retired -- the player emits + whole ``/`` lists, absent means unchanged, and + the `` channel joined 2026-11-17.) + Implementation-agnostic by design: storage details unimportant, the tool manifest is self-describing. 2. **Opening + guards** -- `system.md`, per-project, repo-fed, never copied: the glossary, the purpose statement, the input-validation @@ -173,10 +171,11 @@ example, gitignored real file, env-var option). regenerated state, not provenance. A run may later self-version (git init inside a run) as the service step's backup/export story -- designed for, not built. -- **The service step is later, with its own design round** (auth, - invites, multi-user). v1 stays single-GM loopback; nothing in the - design precludes it -- the self-contained run directory is the - per-user seam. +- **The service step is later, with its own design round.** (Amended + 2026-11-14: the auth/invites/multiuser half is BUILT -- see DECISIONS + #22-31; the service step that remains is the hosting story alone -- + clone-and-run already works, a running instance is one deployment + away.) - **Boutique is dormant** -- a stub that never reached its design step; untouched until its drafting session. - **Stack: zero-dependency runtime** (DECISIONS #4, amended @@ -189,244 +188,40 @@ example, gitignored real file, env-var option). ## The multiuser server (2026-11-14, GM) -The invited-instance half of the harness goal, designed in one round -(rulings DECISIONS #22-31). The LLM key stays on the backend; invited -users need neither the host's secrets nor their own key, and can play -without running anything locally. - -- **Identity is a token, nothing else.** No usernames, no passwords, no - external IDPs. A single-use invite code is exchanged at claim time - for a persistent token (random hex; the server stores a hash, the - client keeps the token). Display names are freeform labels picked at - claim, collisions allowed. Recovery for a lost token is a new invite; - recovery for the superuser is filesystem access. Revocation destroys - the identity -- no suspend, no restore -- and that is cheap because - stories outlive identities by design (forking). -- **Bootstrap:** on the fresh-deployment condition (empty users table) - the server generates the initial superuser invite itself, writes it - to `state/bootstrap-invite.txt` and echoes it to the console. Exactly - one bootstrap invite exists until claimed, reused across restarts so - a restart never invalidates what the op saw; dead the moment any - superuser exists. Invite tokens are single-use with an explicit - spent record -- reuse is rejected loudly, never silently dropped. -- **Superuser powers:** mint/revoke invites, list/revoke users. - Nothing else -- no touching another user's runs or packages, no user - management beyond revocation. -- **gm.md is owner-only, and never model-facing.** The pad closed - with the table (2026-11-15 -- #28's human-side open read - overturned); the model boundary stands: no assembly path reads it. - Saving a draft as a package publishes its gm.md to everyone - (saving is the act of publishing). `housekeeper.md` stays - never-exposed (it prompts an internal agent). -- **Runs:** attributed to the starting user; every GM action and the - whole working surface (table, raw session, carryover, files, - status, notepad) is owner-only (including anything that spends a - model call); the story is the one public read. Any user can fork - any run, including their - own: a mechanical atomic copy -- staged, swapped in by same-volume - rename, taken under the run's activity lock so a mid-turn fork can't - torn-copy -- with the owner replaced. No lineage: runs are entirely - independent, and a fork's only mark is `forked: unixtime` beside the - carried-over `created`. Ownerless (pre-user or revoked-owner) is one - uniform runtime state: readable, forkable, no owner actions, no - re-claiming mechanism. No migration code -- pre-user runs stay as - they are until the op hand-stamps an owner id into run.json. -- **Packages split system and user.** System packages ship with the - repo (authored, read-only); a user can save their run's craft as a - new user package under `state/packages/`, published to everyone, - gm.md included. The saved package carries no pc -- the next create - asks for one; the display name is the save's one decision. -- **Display identity:** the run id is the identifier (strictly unique, - internal, factless, undecorated). The visible name is a content - descriptor -- "Package / PC" plus SPA garnish (owner, started or - forked) -- unique ENOUGH: collisions unlikely and harmless, never - load-bearing, never model-facing. -- **Every logged LLM call records the acting user.** Quotas and limits - are an extension point, not v1. Saved state lives gitignored - (`runs/`, `state/`) -- the repo stays clean by construction. -- **House rule: all dates and times are UTC everywhere.** No time - zones, ever. -- **Extension point (later): proper user lifecycle and auth story.** - Signing in is permanent and per-browser -- the token lives in the - client's localStorage, and sign-out is deliberately absent: less - functional, much easier to reason about. A user who loses their - browser storage is re-invited as a new identity (their old runs - stay owned by the old, unreachable one -- readable, forkable, - frozen). Revisit when a real need shows: sign-out/token - expiry/refresh, multiple devices per user, token backup - affordances. +BUILT (2026-11-14, mock-proven end to end) and retired from the +roadmap in the 2026-11-17 audit. The durable record: the rulings in +DECISIONS #22-31, the surface rules in README (ownership, the +story's public read, invites, forks, ownerless runs), the design +history in the git log. The one open tail from that round -- proper +user lifecycle and auth story (sign-out, token expiry, multiple +devices) -- remains a distant extension point: signing in is +permanent and per-browser, and revisit waits for a real need. ## SPA v1 -- substrate decisions (2026-11-12, GM) -- **The whole story is recorded; publishing is a someday option.** - Storage: backend, full stop -- `sessions/*.jsonl` already is the - complete record (bundle + exchange), git versions it, the SPA holds - nothing. Publishing is an export render that filters to fiction; - book formatting out of scope for v1. -- **Sessions outlive the browser; the server is the truth.** Live state - is in-memory and rebuilt from the jsonl on boot (messages, elision - view, pending ask_gm). The log is truth, the context is a view. -- **Single human: loopback bind, no cookies, no auth.** One active - session *per run* (amended 2026-11-13) -- several runs may hold live - sessions; nothing runs concurrently in practice, and API-driven tests - can proceed alongside a real session. -- **ask_gm surfaces as a modal**; the pending question survives a - browser refresh (the server holds the pause, the SPA re-presents it). -- **Status rides the GM turns.** The full status is attached to every - GM turn as a `` block -- reads are state, writes are deltas: - the player mutates with ``/`` tags in its own turn, - exact-match, non-blocking, misses relayed back via ``. Old - status blocks elide from the live context view like old tool results; - the log keeps them all. The initial status rides turn-0, ingested - at new-game. GM turns never carry deltas; GM override stays - out-of-band. -- **Status pane always visible** -- the current description set, live; - `` reports surface there too. -- **OOC parsing (ruled 2026-11-14):** a line opening with `(` is OOC -- - closing paren optional, per ecosystem convention; a lone `(` is an - empty OOC message and is skipped. The transcript renderer (SPA and - housekeeping render alike) parses registers by this rule plus the - italics/plain speech split. -- **Thinking blocks are logged but never sent back** -- the live context - strips `reasoning_content` (a delta from current bridge behavior, - phase 0); the housekeeping transcript labels them as `[thinking]` - attention evidence for touch/adjudication. -- **Context meter always visible, loud past 85%.** Exact, from the last - response's `usage.prompt_tokens` against a `contwin` value in - server.json. The 100% endgame is close-and-housekeep. -- **Housekeeping is the session-close ritual, and it autorestarts.** A - run always ends the session -- "any time" means the GM may close a - session early, not that housekeeping is a mid-session action. The - chain runs unattended: housekeeper -> manifest -> apply -> next - session opens with fresh views. Review is async, via the log and the - dump diff; GM edits and vetoes remain available through the clerk at - any time, including mid-next-session. A rejected manifest holds the - restart and surfaces the reason for a re-run. -- **Rewrite-here, not forks.** An unfortunate GM turn is edited and the - session restarts from there -- all turns since are lost from the live - context; the append-only log records the surgery and keeps them for - audit. The housekeeping transcript renders the effective view, so the - housekeeper never memorizes retconned-out turns. Window-scoped only: - after housekeeping the story is consolidated, and corrections become - proper retcons. Trivial typos are tolerated; the publishing pass - catches them. Tool side effects in the lost range are compensated - mechanically (see tool discipline below). -- **Tool discipline for rewrite (the saga rule).** Every player tool is - either **session-pure** -- ask_gm, records_search: effects live - in the conversation only, truncation removes them wholesale -- or a - **journaled mutator** -- the status and records verbs: the journal - must capture prior state, so compensation is mechanical. Clerk - amendment: amend and discard currently journal ids only; extend them - to record prior content, and every mutator becomes compensatable. - (Variant turns need no compensation: the pick note is adjacent to - its message, truncation takes both, and only the picked variant's - deltas were ever applied.) -- **The context is a projection, not a ledger.** The API is stateless: - every call ships a freshly rendered view, and nothing obliges the - view to grow mechanically turn by turn. The append-only jsonl is the - record; the view is a pure render of it under a policy. Soundness - invariants: (a) the view is always derivable from log + policy -- - policies deterministic or logged, or "exactly what the model was - sent" provenance dies; (b) tool-call pairing is never broken -- the - endpoint silently tolerates orphaned tool results (probe 2026-11-12), - so this one fails quiet: stub or keep both; (c) elide only what is - durable elsewhere -- the current status block re-rides, tool results - are use-and-discard, the log keeps full prose; (d) order is preserved - -- salience is managed by repetition and compression, never by - shuffling time. Unlocked as policy rules: status re-riding (v1), - prompt re-injection (steal #11), mid-view prose compaction (the - marathon relief valve short of #10), history caps backed by the - rings. -- **REST is the full substrate; the SPA is strictly a client.** - Synchronous requests, no streaming -- single-human latency tolerates a - POST that runs the tool loop and returns. +BUILT, and retired from the roadmap in the 2026-11-17 audit: the +phasing completed 2026-11-14 (all four phases), the API sketch was +superseded by README's living API documentation, and the substrate +doctrine it fixed -- the log is truth and the context a projection, +thinking never returns, OOC is the paren channel, the context meter, +the reminder's single-copy policy -- lives in README. What the audit +kept from this section is the one design not yet built: -Phasing (amended 2026-11-13 -- bridge retired, SPA downstream): -0. clerk-side paper migration (substrate-independent): description-set - status schema, ``/`` delta apply (exact match, - `` reporting), turn-0 ingestion at new-game, amend/discard - prior-content journaling (compensation-grade audit) -- DONE 2026-11-13 -1. preset/run split: `runs/` dir, copy-at-creation, lazy seed at first - window-open, clerk re-addressing, config rename (bridge.json -> - server.json), packages cleaned to authored-only; the prompt split - rides here (system.md + invariants.md repo-fed, the handbook.md - craft copy rides the run) so no run ever copies what the substrate - feeds -- DONE 2026-11-13/14 -2. loop core + REST spine: the loop extracted from the bridge (one - consumer -- the sharing question died with the bridge), `node:http` - server, per-run session machine with ask_gm pause/resume, the view - renderer (log + policy -> per-call context, elision as its first - rule), bundle assembly (system message = system.md + invariants.md, - repo-fed, then the run's handbook.md copy), boot-rebuild from jsonl, - thinking-strip and usage tracking land here, mock mode, - status/context endpoints; the API is testable standalone -- the - front end may wait -- DONE 2026-11-14: mock-proven end to end - (create -> window-open with lazy seed + turn-0 ingestion -> roll - round-trip -> ask_gm pause/resume -> paper deltas -> boot-rebuild -> - post-restart turn); tool/bridge.mjs deleted at mock-parity per the - retirement decision. Housekeeping endpoints answer 501 until - phase 3. Live-API first use still ahead. -3. housekeeping job: manual trigger (always ends the window), transcript - assembly with labeled thinking, run-state injection into the - housekeeper invocation (records availability first -- the ring views - carry pure memory, no meta), auto-apply, autorestart on success, - async log view; a rejection holds the restart and surfaces why; - per-wrap dump snapshots land with apply -- DONE 2026-11-14: - mock-proven (chain, rejection path, autorestart) and live-proven - same day on `live-smoke`: the housekeeper (glm-5.3) produced a - clean first manifest -- both inserts correctly ring B, first-person - voice, touches only what the transcript invoked, story-dated - (2026-11-18-beach-arrival) -4. SPA: transcript with three visual registers (voice / narration / - OOC), bundle as a collapsed "window opened" card, turn-0 as - fiction; GM line input; ask_gm modal; status pane; context meter -- - DONE 2026-11-14: `web/` (no build, vanilla ES modules), served by - the server from `/`; register parsing per the ruled markers - (multi-line narration blocks included); the full v1 scope driven - end to end through the UI on a disposable live run (new-run form, - window open, GM turn, housekeeping chain with confirm + poll + log - display + autorestart). The ask modal rides detail.pendingAsk - (mock-proven logic, first live presentation pending). -Later: turn surgery (steal #2 with UI), memory browser (steal #7), -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 (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 session, 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//sessions open a session (lazy seed, render, assemble) - POST /api/runs//turn0 send turn-0 as the first GM turn (fresh session) - 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//status GM override: replace the whole status (empty = clear) - DELETE /api/runs/ delete a draft (no sessions); played runs refuse -- by hand - POST /api/runs//housekeeping run the chain (ends the session), 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 session log - POST /api/runs//housekeeping/apply apply a manifest directly +- **Turn surgery, when it earns its build:** rewrite-here, not + forks -- an unfortunate GM turn is edited and the session restarts + from there; all turns since leave the live context, the append-only + log keeps them for audit. Window-scoped only: after housekeeping + the story is consolidated, and corrections become proper retcons. + Tool discipline for the rewrite (the saga rule): every player tool + is either session-pure (ask_gm, records_search -- truncation + removes their effects wholesale) or a journaled mutator (the + records verbs; amend/discard journal prior content, so compensation + is mechanical). Variant turns need no compensation -- the pick note + sits adjacent to its message and only the picked variant ever + applied. See steal #2. ## The steal list (work point by point) -### 1. Voice examples in the character sheet -- DONE (2026-11-13) -`mes_example` from the character-card spec: 2-3 sample exchanges per -character. The strongest voice-calibration tool the RP community has. -Cost: zero (content). Add an example-dialogue block to the character.md -template and to both casts when drafting. -Status: DONE (2026-11-13) -- a ten-state voice corpus in the la-caramba -sheet; the backstory is first person to match the memory voice. - ### 2. Turn surgery: /retry, /edit in the bridge -- DECIDED (2026-11-12) Rewrite-here, not fork-here: an unfortunate GM turn is edited in place and the session restarts from there, losing all turns since. Window- @@ -437,24 +232,6 @@ tolerated as-is; the publishing pass catches them. Forks rejected as unnecessary. The principle is DECISIONS #15; the open details ride in QUESTIONS until the build. -### 3. Transient status digest injected post-history -- DECIDED (2026-11-12) -The Author's Note / `@@depth` / `post_history_instructions` pattern: -instructions placed after history get better adherence. Folded into the -SPA v1 substrate -- superseded by the status redesign (DECISIONS #17): -the full status rides every GM turn as a `` block; reads are -state, writes are deltas (``/``). Old blocks elide from -the live context view like old tool results; the log keeps every -as-sent block (provenance, rewrite snapshots, status evolution for -observable #12). Status left the opening bundle. Adherence remains an -observable to measure once live. - -### 4. Generation params passthrough -- DONE (2026-11-13) -Every frontend exposes sampler settings; the loop sends none by -default. `server.json` carries an optional `params` object spread into -the request body (temperature, top_p, etc.) -- in from day one, empty -by default. -Status: DONE (landed with the server config shape). - ### 5. Hybrid retrieval for records_search -- OPEN, DEFERRED SOTA baseline is BM25 + vector + entity-boost (Mem0 v3, Zep). Our LIKE-only search is fine at boutique scale. Upgrade path: SQLite FTS5 + @@ -476,13 +253,6 @@ remembers" view over rings, records, status, journal. The observability feature for reviewers and for you as GM. Status: OPEN (SPA). -### 8. Cheap-model housekeeping / decision oracle -- OPEN -Talemate runs each agent on its own model, including a small "decision -model" for oracle calls. The housekeeper can already run on any model -(it's a separate invocation); `ds4-flash` housekeeping is one config -away when cost matters. Same for a fast oracle in the SPA. -Status: OPEN. - ### 9. Character-card V3 import/export -- OPEN (OPTIONAL) Portability to/from the ST ecosystem (PNG-embedded cards, CCv3 spec). Only if sharing characters with the outside world ever matters. @@ -495,22 +265,6 @@ Current answer: close the session. Fine for the test; revisit if real sessions regularly overflow. Status: DEFERRED. -### 11. Periodic system-prompt re-injection -- DONE (2026-11-14) -Built as the per-turn reminder, GM-ruled: not the whole system header -re-sent (uncalled for), but the small "how to compose your turn" -protocol extracted into `reminder.md` (repo-shared, never copied into -a run). It rides after the GM's prose as its own `role: system` -session chunk on every turn; superseded copies elide from the live -view, so exactly one exists, always at the freshest position -- the -same single-copy policy as the riding blocks. Absent/empty file = no ride -(the feature sleeps). The measured trigger arrived first: observable -#14's completions lengthening across session one. The reminder is now -the experiment: does the lengthening flatten with it in the session. -Housekeeping never sees it (a fresh context each pass); the SPA shows one -collapsed card for the newest copy, mirroring the policy. -Status: DONE (content is the GM's, extracted from the handbook -- the -duplicate handbook cut is the GM's red pen). - ## Deferred tasks (ruled out of the dormant-session rework, 2026-11-15) - **Save-as-package beyond drafts.** Today it fires only from @@ -521,13 +275,28 @@ duplicate handbook cut is the GM's red pen). whether spent carryovers survive start. All questions open. The principle proposed, not ruled: a package is a starting point, never a snapshot -- fork is the continue-this-story verb. -- **The carryover editor.** The dormant session's carryover is - GM-editable in principle (conversation history, not immutable during - dormancy) but has no editing surface yet; the dormant view renders - it raw, read-only. The proper editor is its own task. +- **The carryover editor.** (Amended 2026-11-17: the raw surface + exists -- the file editor edits a continuation carryover during + dormancy, save-linted, blocks included.) What remains deferred is + the purpose-built editing surface over the dormant view's + read-only render. ## Distant extension points (someday, not scheduled) +- **the bookkeeper: a sheet-keeping agent.** The GM is the sheet's + author and its error model (GM, 2026-11-17: the counts are the + GM's job). When keeping the papers correct becomes unproductive + bother, an internal agent -- the housekeeper's arithmetic sibling, + never model-facing -- reads the setting's rules prose and the + latest turns, computes the ledger delta (a purchase in her prose + applied against the catalog), and lands it as a STAGED sheet edit + with a pending marker: applied when the GM's next turn rides, or + discarded. Sheet-only authority, strictly-validated output, a bad + day falls back to no-change (the curator pattern); per-package + opt-in, because an agent cannot bookkeep what is not arithmetic. + The tabletop metaphor bends here on purpose (players hold their + own pencils in the real thing): the deviation is substrate + pragmatism, drift-proofing, not realism. - **n-choice inference composed by a turn-editor agent.** The provider's `n` parameter asks for several statistically independent completions of the same prompt -- the same moment re-rolled by the diff --git a/invariants.md b/invariants.md index a142e9d..327fe8a 100644 --- a/invariants.md +++ b/invariants.md @@ -107,6 +107,12 @@ Some related intel: - Embrace eviction, it's a useful tool to make the story better. A person moving from one thing to another is natural. - When deciding a turn, consider broader context. Something may come up that is more important than anything on the list. +# Character's sheet + +The `` block is optional. If given, it contains a free form json that GM curates for you and describes the play's objective state. +Example: clothes your character is wearing (if that earns a mention for some reason), school grades (if your character is a student and grades +matter), etc. You may propose adding things on the sheet if you think the story would benefit from tracking things it currently doesn't. + # Character's mind The `` block has unique semantics. It's write-only for you. You may adjust common inference parameters (`temperature`, `repetition_penalty`, diff --git a/packages/la-caramba/gm.md b/packages/la-caramba/gm.md index 03e30d0..c6acafd 100644 --- a/packages/la-caramba/gm.md +++ b/packages/la-caramba/gm.md @@ -113,3 +113,12 @@ what fate awaits female deckers in a supermax and getting excited about it. Restraints (especially permanent) make her wet instantly. Still very capable and skilled, if she can snap out of it. Not the PC's decker chic, they never met before. + +## Proposed plot spine + +The ship's AI has executed a risky gambit. She knew that the island houses a bunker where frontier research was being conducted +towards even more capable AI for military purposes, until it was banned by an international treaty and wiped. The hardware is +supposedly still there and the ship wants it for herself. The water around the island was closed off for civilian traffic and +she knew she won't be able to just sail there, so instead she employed a defense satellite to fry her electronics on approach and +relied on emergency instructions to guide the ship to the nearest land blind and lobotomised (minimal emergency model instead +of proper power-hungry full capacity one). diff --git a/reminder.md b/reminder.md index 4851574..25a3609 100644 --- a/reminder.md +++ b/reminder.md @@ -17,7 +17,8 @@ You may choose to ask GM instead of writing literature. Use the tool if given, e ## Understand the world around your character -You are given the memories, the status, the agenda and the prose of the current session. Build a coherent picture. If you can't, ask GM. +You are given the memories, the status, the agenda, the sheet (optional) and the prose of the current session. Build a coherent picture. +If you can't, ask GM. If your character is restrained, check what actions are actually limited (example: handcuffs allow holding small things). diff --git a/server/loop.mjs b/server/loop.mjs index 98dfdb0..3a28cbd 100644 --- a/server/loop.mjs +++ b/server/loop.mjs @@ -53,9 +53,10 @@ function needSession(ctx, runId) { /** * @param {Ctx} ctx @param {string} runId @param {string} line @param {?Actor} user * @param {?{ status?: string[], agenda?: string[] }} [override] + * @param {?Record} [sheet] * @returns {Promise} */ -export async function gmTurn(ctx, runId, line, user, override = null) { +export async function gmTurn(ctx, runId, line, user, override = null, sheet = null) { const s = needSession(ctx, runId); if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)'); // GM-input expansion (strict, DECISIONS #9): the line resolves at @@ -71,8 +72,10 @@ export async function gmTurn(ctx, runId, line, user, override = null) { // GM prose goes pure: no cache blocks ride any turn. A block edit, // when given, rides this turn as the override record -- the // composition overwrites her newest blocks with it (the scan reads - // it newest-wins), the log keeps her words verbatim - s.append({ t: 'msg', m: { role: 'user', content: prose }, ...(override ? { override } : {}) }); + // it newest-wins), the log keeps her words verbatim. The sheet + // record rides the same way: the GM's ledger, a whole set, the scan + // reads it newest-wins, the log never mutates + s.append({ t: 'msg', m: { role: 'user', content: prose }, ...(override ? { override } : {}), ...(sheet ? { sheet } : {}) }); // the reminder follows the GM's prose as its own system chunk -- // every turn, one live copy (older ones elide in the view) const reminder = assembleReminder(runId); @@ -256,6 +259,11 @@ async function runLoop(ctx, runId, user) { if (//.test(text)) { carry.push('the block is a read-only display of your active parameters -- state them in a block'); } + // the block is display-only the same way: the GM's ledger, + // read-only for her (GM, 2026-11-17) -- changes propose in prose + if (//.test(text)) { + carry.push('the block is the GM\'s ledger -- propose changes in prose'); + } if (carry.length && heals < 3) { // a conflict answers for itself: it goes back as its own message, // not attached to a GM turn -- clean of prose, easy to read, easy @@ -444,6 +452,20 @@ function mockModel(s, view) { content: null, tool_calls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }], }); + // the sheet guard's cue (position-independent -- the carried tail + // shifts counts, a cue does not shift): the marked GM turn gets the + // emission, the conflict it earns gets the plain-prose heal. The + // view carries the conflict as its raw text (the log field does not + // ride), so the check reads the tags + const lastMsg = view[view.length - 1]; + const lastGm = [...view].reverse().find((m) => m.role === 'user' && !/^/.test(String(m.content ?? ''))); + if (lastGm && /the floating numbers/.test(String(lastGm.content ?? ''))) { + if (lastMsg && /^/.test(String(lastMsg.content ?? ''))) { + // the heal: plain prose, no blocks -- she proposes in prose + return { role: 'assistant', content: 'Mock: *She shakes the numbers out of her head and asks for the change out loud instead.*' }; + } + return { role: 'assistant', content: 'Mock: *She squints at the ledger floating in her mind.*\n{"gp": 99}' }; + } let inExchange = false; let count = 0; for (const e of s.lines) { diff --git a/server/main.mjs b/server/main.mjs index c6b7146..5818a9f 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -473,6 +473,7 @@ route('GET', '/api/runs/:id', async ({ params, user }) => { ready: sm.ready ?? null, status: state.status, agenda: state.agenda, + sheet: state.sheet, records: st.records, fill: st.rings, events: st.events, @@ -839,7 +840,7 @@ route('GET', '/api/runs/:id/table', async ({ params, user }) => { route('GET', '/api/runs/:id/story', async ({ params }) => { bundle.requireRun(params.id); const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g; - const verbs = /<(lost|gained|add|drop|mind|model|status|agenda)>[\s\S]*?<\/\1>/g; + const verbs = /<(lost|gained|add|drop|mind|model|status|agenda|sheet)>[\s\S]*?<\/\1>/g; const project = (/** @type {import('./shapes.mjs').LogEvent[]} */ lines) => { const eff = effectiveContents(lines); /** @type {{ who: string, text: string }[]} */ @@ -920,15 +921,31 @@ function readOverride(body) { return override; } +// The sheet record (GM, 2026-11-17): the GM's ledger of arbitrated run +// state, riding the GM turn like the override. Schemaless by ruling -- +// a plain JSON object, any fields, semantics living in the setting's +// prose; the route's only law is object-ness (an array or a scalar is +// a 400, nothing appended). Absent key on the turn means no edit; an +// empty object is a deliberate empty ledger. +/** @param {Record} body @returns {?Record} */ +function readSheet(body) { + if (body.sheet === undefined || body.sheet === null) return null; + if (typeof body.sheet !== 'object' || Array.isArray(body.sheet)) { + throw new HttpError(400, 'sheet must be a JSON object -- the GM\'s ledger record'); + } + return /** @type {Record} */ (body.sheet); +} + route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => { const line = String(body.line ?? '').trim(); if (!line) throw new HttpError(400, 'line is required'); const override = readOverride(body); - if (override && line.startsWith('(')) { + const sheet = readSheet(body); + if ((override || sheet) && line.startsWith('(')) { throw new HttpError(400, 'a block edit cannot ride an OOC turn -- overrides arrive with a non-OOC GM turn'); } requireOwner(user, params.id); - return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override))) }; + return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override, sheet))) }; }); route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => { @@ -981,11 +998,11 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => { // db holds no copy). The latest session's log is the whole story // since its start; during dormancy the carryover is the live edge // and rides along. A run with no sessions derives nothing. -/** @param {string} runId @returns {{ status: string[], agenda: string[] }} */ +/** @param {string} runId @returns {{ status: string[], agenda: string[], sheet: ?Record }} */ function derivedState(runId) { const live = ctx.sessions.get(runId); const latest = session.latestSession(runId); - if (latest == null) return { status: [], agenda: [] }; + if (latest == null) return { status: [], agenda: [], sheet: null }; const n = live?.n ?? latest; const dir = session.sessionDir(runId, n); /** @type {import('./shapes.mjs').LogEvent[]} */ const lines = []; @@ -1003,7 +1020,7 @@ function derivedState(runId) { } } const st = session.scanState(lines); - return { status: st.status ?? [], agenda: st.agenda ?? [] }; + return { status: st.status ?? [], agenda: st.agenda ?? [], sheet: st.sheet }; } route('GET', '/api/runs/:id/status', async ({ params, user }) => { diff --git a/server/session.mjs b/server/session.mjs index 57399f5..9464b0e 100644 --- a/server/session.mjs +++ b/server/session.mjs @@ -248,11 +248,19 @@ export function cleanBlockList(text, kind) { return cleanList(blockList(text, kind)); } -/** @param {LogEvent[]} lines @returns {{ status: ?string[], agenda: ?string[] }} */ +/** The state scan: newest-wins across her emissions (the picked + * variant's text), the GM's records, and the boundary note. The sheet + * (GM, 2026-11-17) is the second channel: arbitrated run state, never + * her words -- its sources are the GM's turn records and the note, + * each record a whole set (absent key means dropped, never kept), and + * it never caps, never cleans: the GM's ledger is exactly what the GM + * last set. + * @param {LogEvent[]} lines @returns {{ status: ?string[], agenda: ?string[], sheet: ?Record }} */ export function scanState(lines) { const eff = effectiveContents(lines); /** @type {?string[]} */ let status = null; /** @type {?string[]} */ let agenda = null; + /** @type {?Record} */ let sheet = null; for (const [i, e] of lines.entries()) { if (e.t === 'msg' && e.m.role === 'assistant' && !e.m.tool_calls?.length) { const c = eff.has(i) ? eff.get(i) : e.m.content; @@ -263,13 +271,16 @@ export function scanState(lines) { } else if (e.t === 'msg' && e.m.role === 'user' && e.override) { if (e.override.status) status = cleanList(e.override.status); if (e.override.agenda) agenda = cleanList(e.override.agenda); + } else if (e.t === 'msg' && e.m.role === 'user' && e.sheet) { + sheet = e.sheet; } else if (e.t === 'note' && e.kind === 'state') { if (e.status) status = cleanList(e.status); if (e.agenda) agenda = cleanList(e.agenda); + if (e.sheet) sheet = e.sheet; } } if (agenda !== null && agenda.length > AGENDA_CAP) agenda = agenda.slice(0, AGENDA_CAP); - return { status, agenda }; + return { status, agenda, sheet }; } // --- stop: the manual close ---------------------------------------------------- @@ -316,8 +327,8 @@ export function stopSession(runId, N) { // position, so it is safe to write always const st = scanState(lines); /** @type {LogEvent[]} */ let head = []; - if (st.status !== null || st.agenda !== null) { - head = [{ t: 'note', kind: 'state', ...(st.status !== null ? { status: st.status } : {}), ...(st.agenda !== null ? { agenda: st.agenda } : {}) }]; + if (st.status !== null || st.agenda !== null || st.sheet !== null) { + head = [{ t: 'note', kind: 'state', ...(st.status !== null ? { status: st.status } : {}), ...(st.agenda !== null ? { agenda: st.agenda } : {}), ...(st.sheet !== null ? { sheet: st.sheet } : {}) }]; } const moved = [...head, ...lines.slice(start)]; fs.writeFileSync(carry, moved.map((e) => JSON.stringify(e)).join('\n') + (moved.length ? '\n' : '')); @@ -598,7 +609,7 @@ const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g; // canon point (the newest value of each kind at her most recent // turn's tail), is write-only, is display-only -- the // log keeps every copy verbatim, the view is policy -const STRIP_HERS = /(?:\n)?<(status|agenda|mind|model)>[\s\S]*?<\/\1>\n?/g; +const STRIP_HERS = /(?:\n)?<(status|agenda|mind|model|sheet)>[\s\S]*?<\/\1>\n?/g; /** The renderer reads only these two of a session -- the start path * validates its assembled context with the same policy before going @@ -698,6 +709,15 @@ export function renderView(s, keepToolResults = 4) { } } } + // the sheet chunk (GM, 2026-11-17): arbitrated run state renders as + // its OWN authoritative system chunk at the freshest end -- never a + // canon-point stamp, which would read as her words. One live copy by + // construction (assembled once per view, not logged per turn). An + // empty object renders too: the channel exists, nothing tracked. + // She reads it, never writes it -- the guard conflicts an emission. + if (st.sheet != null) { + msgs.push({ role: 'system', content: `${JSON.stringify(st.sheet)}` }); + } validatePairing(msgs, s.pendingAsk?.callId); return msgs; } diff --git a/server/shapes.mjs b/server/shapes.mjs index d4605e4..585d766 100644 --- a/server/shapes.mjs +++ b/server/shapes.mjs @@ -34,7 +34,7 @@ export {}; * arriving with a non-OOC GM turn: the log's record of it. The * composition overwrites her newest blocks with these values (the * scan reads it newest-wins); the log itself never changes. */ -/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] } }} MsgEvent */ +/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record }} MsgEvent */ /** req: a failed provider request -- the resolved model, the * effective params, and the failure. No message resulted (the turn @@ -62,7 +62,7 @@ export {}; * the slidwin tail. Machinery like every note: never rendered, the * scan reads it newest-wins (it loses to any emission inside the * tail by position). */ -/** @typedef {{ t: 'note', kind: 'state', status?: string[], agenda?: string[] }} StateNote */ +/** @typedef {{ t: 'note', kind: 'state', status?: string[], agenda?: string[], sheet?: Record }} StateNote */ /** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote} NoteEvent */ /** bundle: one frozen prompt part (system, backdrop, character, rings). */ diff --git a/test/check-reminder.mjs b/test/check-reminder.mjs index 1fcc477..007d86d 100644 --- a/test/check-reminder.mjs +++ b/test/check-reminder.mjs @@ -32,12 +32,20 @@ const ok = (name, cond, extra = '') => { }; const logged = s.lines.filter((e) => e.reminder).length; ok(`log keeps every copy (${logged})`, logged >= 5, `${logged}`); -ok('view carries exactly two system chunks (the trio + the newest reminder)', sys.length === 2, `${sys.length}`); +// the sheet chunk (when the run keeps a ledger) is its own live +// system surface at the freshest end -- the reminder policy tolerates +// exactly one of them +const sheetChunks = sys.filter((m) => /^/.test(String(m.content ?? '').trim())); +ok('view carries exactly two system chunks (the trio + the newest reminder)', + sys.length === 2 + sheetChunks.length && sheetChunks.length <= 1, `${sys.length}`); // mid-call the reminder is the last message; after the model's reply it // sits immediately before that reply -- either way it follows the newest -// GM turn at the freshest end of the context +// GM turn at the freshest end of the context. Only her latest reply +// and the sheet chunk may follow it const ri = view.findIndex((m) => m.role === 'system' && /How to compose your turn/i.test(m.content)); +const after = view.slice(ri + 1); const tail = view.slice(-3).map((m) => m.role).join(','); -ok('the reminder rides at the freshest end', (ri === view.length - 1) || (ri === view.length - 2 && view[view.length - 1].role === 'assistant'), tail); +ok('the reminder rides at the freshest end', + after.every((m) => m.role === 'assistant' || (m.role === 'system' && /^/.test(String(m.content ?? '').trim()))) && after.length <= 2, tail); console.log(fails ? `\n${fails} FAILURES` : '\nALL PASS'); process.exit(fails ? 1 : 0); diff --git a/test/smoke.mjs b/test/smoke.mjs index ceb9e59..73b0821 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -550,7 +550,7 @@ ok('the story has every GM turn exactly once', gmTexts.length === 6 && new Set(g ok('the story carries no OOC', r.data.sessions.every((s) => s.turns.every((t) => !/^\(/.test(t.text) && !/\( mock GM checking in \)/.test(t.text))), 'OOC leaked into the story'); ok('the story reads the dormant carryover at the live edge', r.data.sessions.some((s) => s.turns.length >= 10)); const storyPlayer = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'player').map((t) => t.text)); -ok('the story strips the verbs', storyPlayer.every((t) => !/<\/?(lost|gained|add|drop|mind|status|agenda|model)>/.test(t)), ''); +ok('the story strips the verbs', storyPlayer.every((t) => !/<\/?(lost|gained|add|drop|mind|status|agenda|model|sheet)>/.test(t)), ''); ok('the story carries no variant syntax', storyPlayer.every((t) => !/<\/?variants?>/.test(t)), ''); ok('the story strips the rides from GM prose', r.data.sessions.every((s) => s.turns.every((t) => t.who !== 'gm' || !/<\/?(status|agenda)>/.test(t.text))), ''); @@ -636,6 +636,87 @@ r = await call(`/runs/${runId}/session`, { token: op }); const liveGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly); ok('the log records the expanded line', /name out loud: Smokina/.test(String(liveGm?.m.content ?? '')) && !/@PC\b/.test(String(liveGm?.m.content ?? '')), String(liveGm?.m.content ?? '').slice(0, 90)); +// 23. the sheet (GM, 2026-11-17): the GM's ledger of arbitrated run +// state -- records ride GM turns newest-wins, render as their own +// authoritative chunk (never a stamp at her canon point), cross the +// boundary on the state note, and stay read-only for her (the guard) +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger opens.*', sheet: { gp: 10, bp: 0 } } }); +ok('a turn with a sheet record sends', r.status === 200, r.data.error ?? ''); +r = await call(`/runs/${runId}`, { token: op }); +ok('the scan derives the sheet newest-wins', JSON.stringify(r.data.sheet) === '{"gp":10,"bp":0}', JSON.stringify(r.data.sheet)); +// session 4's log starts the script over, so this turn lands on the +// script's ask position -- answer it, then the view asserts (pairing +// must be whole for renderView) +if (r.data.pendingAsk) { + r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'clear enough' } }); + ok('the sheet battery answers the script ask', r.status === 200, r.data.error ?? ''); +} +{ + const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null }); + const chunk = [...view].reverse().find((m) => m.role === 'system' && //.test(String(m.content))); + ok('the sheet renders as its own authoritative chunk at the freshest end', + !!chunk && chunk.content === '{"gp":10,"bp":0}', chunk?.content ?? 'no chunk'); + ok('the sheet chunk is the one live copy', + view.filter((m) => m.role === 'system' && String(m.content ?? '').startsWith('')).length === 1, ''); +} +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger moves.*', sheet: { gp: 7 } } }); +ok('a second sheet record sends', r.status === 200, r.data.error ?? ''); +r = await call(`/runs/${runId}`, { token: op }); +ok('a sheet record is a whole set (absent key dropped, never kept)', JSON.stringify(r.data.sheet) === '{"gp":7}', JSON.stringify(r.data.sheet)); +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc sheet test', sheet: { gp: 1 } } }); +ok('a sheet record cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? ''); +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No ledger here.*', sheet: 'not an object' } }); +ok('a malformed sheet refuses the turn', r.status === 400 && /JSON object/.test(r.data.error), r.data.error ?? ''); +r = await call(`/runs/${runId}`, { token: op }); +ok('the refused turns landed nothing (the sheet stands)', JSON.stringify(r.data.sheet) === '{"gp":7}', JSON.stringify(r.data.sheet)); +// the guard: she emits a -- display-only, the conflict points +// at prose, the heal completes the turn, and her emission never applies +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She eyes the floating numbers.*' } }); +ok('the sheet-guard turn completes via the heal', r.status === 200, r.data.error ?? ''); +r = await call(`/runs/${runId}/session`, { token: op }); +ok('an emitted conflicts with the pointer at prose', + r.data.entries.some((e) => e.t === 'msg' && e.conflictOnly && /GM's ledger -- propose changes in prose/.test(String(e.m.content ?? ''))), + 'no conflict found'); +ok('the log keeps her emitted sheet verbatim (the raw surface)', + r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /\{"gp": 99\}<\/sheet>/.test(String(e.m.content ?? ''))), 'her emission was rewritten'); +ok('her emitted sheet never applies (the scan holds the GM\'s record)', + JSON.stringify((await call(`/runs/${runId}`, { token: op })).data.sheet) === '{"gp":7}', ''); +{ + const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null }); + ok('the view strips her emitted sheet (the chunk alone carries it)', + view.every((m) => m.role !== 'assistant' || !//.test(String(m.content ?? ''))), 'her emission rode the view'); +} +r = await call(`/runs/${runId}/story`, { token: op }); +ok('the story strips her emitted sheet', + r.data.sessions.every((s) => s.turns.every((t) => !/<\/?sheet>/.test(t.text))), 'leaked into the story'); +// the empty ledger is live, not absent: {} renders its chunk +r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger empties.*', sheet: {} } }); +ok('an empty sheet record sends (a deliberate empty ledger)', r.status === 200, r.data.error ?? ''); +r = await call(`/runs/${runId}`, { token: op }); +ok('the empty ledger derives as itself', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet)); +{ + const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null }); + const chunk = [...view].reverse().find((m) => m.role === 'system' && //.test(String(m.content))); + ok('the empty ledger renders its chunk', chunk?.content === '{}', chunk?.content ?? 'no chunk'); +} +// the boundary: the note carries the sheet, the new session derives it +await stopAndSettle('stop (session 4)'); +{ + const carry5 = jsonl(runId, 5, 'carryover.jsonl'); + ok('the boundary note carries the sheet', carry5[0]?.t === 'note' && carry5[0]?.kind === 'state' && JSON.stringify(carry5[0]?.sheet) === '{}', JSON.stringify(carry5[0] ?? null)); +} +r = await call(`/runs/${runId}`, { token: op }); +ok('the dormant read derives the sheet (the note is the live edge)', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet)); +r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} }); +ok('start session 5', r.status === 200 && r.data.session === 5 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data)); +r = await call(`/runs/${runId}`, { token: op }); +ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet)); +{ + const view = renderView({ lines: jsonl(runId, 5, 'log.jsonl'), pendingAsk: null }); + const chunk = [...view].reverse().find((m) => m.role === 'system' && //.test(String(m.content))); + ok('session 5 renders the sheet chunk from the carried note', chunk?.content === '{}', chunk?.content ?? 'no chunk'); +} + console.log(`\nrun ids: source=${runId} fork=${forkId} second=${secondId} refork=${reforkId}`); writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`); console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS'); diff --git a/web/index.html b/web/index.html index 8885849..5e09b52 100644 --- a/web/index.html +++ b/web/index.html @@ -148,6 +148,12 @@
+
+
+

the sheet

+
+
+

gm notes

diff --git a/web/shapes.mjs b/web/shapes.mjs index 0831349..5477891 100644 --- a/web/shapes.mjs +++ b/web/shapes.mjs @@ -17,7 +17,7 @@ export {}; * her two blocks, the fill, the context meter's numbers. * paramDefaults is the knobs' deployment layer (server.json params) * -- the only default an unset knob honestly resolves to. */ -/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, params: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, modelDefaults: { player?: ?string, housekeeper?: ?string }, paramDefaults: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], records: number, fill: Record, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */ +/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, params: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, modelDefaults: { player?: ?string, housekeeper?: ?string }, paramDefaults: { player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record, records: number, fill: Record, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */ /** GET /api/models -- the deployment's model registry and the * discovery job state riding along. phase 'none' is the fresh diff --git a/web/transcript.mjs b/web/transcript.mjs index dd1ae10..bb44d52 100644 --- a/web/transcript.mjs +++ b/web/transcript.mjs @@ -58,12 +58,13 @@ function renderContent(target, text, { extract }) { if (am) { agenda = am[1]; body = body.replace(am[0], ''); } } const tags = []; - for (const m of body.matchAll(/<(lost|gained|add|drop|mind|status|agenda)>([\s\S]*?)<\/\1>/g)) { + for (const m of body.matchAll(/<(lost|gained|add|drop|mind|status|agenda|sheet)>([\s\S]*?)<\/\1>/g)) { // the mind block is JSON -- it rides whole (no comma-splitting); // the note line carries the human-readable form. Status and // agenda blocks are the full-block protocol: their items chip - // like the deltas did (list markers stripped for display) - const items = m[1] === 'mind' + // like the deltas did (list markers stripped for display). The + // sheet is JSON too -- it chips whole like the mind + const items = m[1] === 'mind' || m[1] === 'sheet' ? [m[2].trim()] : m[2].split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(',')).map((x) => x.trim()).filter(Boolean); tags.push({ kind: m[1], items }); @@ -160,7 +161,8 @@ export function viaLine(via, fail = null) { // the GM's block edit, as the machinery line both walks show: the // override rides its turn as the record; the composition overwrites -// her newest blocks with it +// her newest blocks with it. The sheet record rides the same way -- +// the GM's ledger, a whole set /** @param {{ status?: string[], agenda?: string[] }} o @returns {string} */ function overrideText(o) { const parts = []; @@ -168,6 +170,10 @@ function overrideText(o) { if (o.agenda) parts.push(`agenda ${JSON.stringify(o.agenda)}`); return `[block edit] ${parts.join(' | ')} -- composes over her newest blocks`; } +/** @param {Record} sheet @returns {string} */ +function sheetText(sheet) { + return `[sheet] ${JSON.stringify(sheet)} -- the GM's ledger`; +} // the note line, shared by both walks /** @param {NoteEvent} e @returns {?string} */ @@ -190,6 +196,7 @@ function noteText(e) { const parts = []; if (e.status) parts.push(`status ${JSON.stringify(e.status)}`); if (e.agenda) parts.push(`agenda ${JSON.stringify(e.agenda)}`); + if (e.sheet) parts.push(`sheet ${JSON.stringify(e.sheet)}`); return `boundary state carried across the stop: ${parts.join(' | ')}`; } return null; @@ -266,6 +273,7 @@ export function renderRaw(entries) { const d = block(e.conflictOnly ? 'gm -- conflict only' : 'gm'); d.appendChild(el('pre', null, String(e.m.content ?? ''))); if (e.override) d.appendChild(el('div', 'machinery', overrideText(e.override))); + if (e.sheet) d.appendChild(el('div', 'machinery', sheetText(e.sheet))); continue; } if (e.t === 'msg' && e.m.role === 'assistant') { @@ -366,6 +374,7 @@ export function renderTranscript(entries, { onConflict, onRaw } = {}) { const { conflict } = renderContent(body, e.m.content, { extract: true }); if (conflict) onConflict?.(conflict); if (e.override) d.appendChild(el('div', 'machinery', overrideText(e.override))); + if (e.sheet) d.appendChild(el('div', 'machinery', sheetText(e.sheet))); if (onRaw) addRawControl(head, d, idx); t.appendChild(d); } diff --git a/web/view-play.mjs b/web/view-play.mjs index 91755d9..ccd0ab3 100644 --- a/web/view-play.mjs +++ b/web/view-play.mjs @@ -16,7 +16,7 @@ import { state } from './state.mjs'; import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chrome.mjs'; import { navigate, render, runGone } from './router.mjs'; import { logEvent } from './log.mjs'; -import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs'; +import { armedButton, modelList, modelsBox, paneEditor, sheetEditor } from './widgets.mjs'; import { renderRaw, renderTranscript, stickBottom, viaLine } from './transcript.mjs'; // the table's two faces: the curated projection (the table) and the @@ -58,6 +58,11 @@ const agendaPane = paneEditor({ .map((x) => x.trim()).filter(Boolean), }); +// the sheet: the GM's ledger, the same stage-and-ride pattern -- an +// edit rides the next GM turn as the record; the panes re-render from +// the scan +const theSheet = sheetEditor('sheet-pane', 'sheet'); + const models = modelsBox('models-pane', { title: 'models' }); export function leave() { @@ -72,6 +77,7 @@ export async function enter(id, seq) { if (rawRun !== id) { rawRun = id; rawOpen = false; } // a new run starts at the table statusPane.reset(); agendaPane.reset(); + theSheet.reset(); $('conflict').hidden = true; await saveNotes(); // flush the pad for the previous run before switching state.runId = id; @@ -101,6 +107,7 @@ async function refreshPlay(id, seq) { renderMeter(detail); statusPane.set(detail.status); agendaPane.set(detail.agenda); + theSheet.set(detail.sheet); $('conflict').hidden = true; // the owner's table, live only for the panes: a block edit rides a @@ -109,6 +116,7 @@ async function refreshPlay(id, seq) { // was redirected to the story above. statusPane.setEditable(detail.phase === 'live'); agendaPane.setEditable(detail.phase === 'live'); + theSheet.setEditable(detail.phase === 'live'); /** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = false; $('table-tabs').hidden = true; // the tabs are the live session's @@ -460,11 +468,14 @@ async function sendTurn() { const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim(); if (!line || !state.runId) return; // staged block edits ride the turn (the override): only the kinds - // staged attach, whole-list - /** @type {{ line: string, status?: string[], agenda?: string[] }} */ const body = { line }; + // staged attach, whole-list. The staged sheet rides the same way -- + // the GM's ledger record ({} is a live empty ledger, so the null + // check, not truthiness) + /** @type {{ line: string, status?: string[], agenda?: string[], sheet?: Record }} */ const body = { line }; if (statusPane.staged) body.status = statusPane.staged; if (agendaPane.staged) body.agenda = agendaPane.staged; - if ((body.status || body.agenda) && line.startsWith('(')) { + if (theSheet.staged !== null) body.sheet = theSheet.staged; + if ((body.status || body.agenda || body.sheet !== undefined) && line.startsWith('(')) { banner('a block edit cannot ride an OOC turn -- send it as a normal GM turn, or discard the edit'); return; // the line stays in the box, the staging stays staged } @@ -478,6 +489,7 @@ async function sendTurn() { await api(`/runs/${state.runId}/turn`, { method: 'POST', body }); statusPane.clearStaged(); // sent -- the panes re-render from the scan agendaPane.clearStaged(); + theSheet.clearStaged(); } catch (e) { failed = e.message; /** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line diff --git a/web/widgets.mjs b/web/widgets.mjs index 8bc4428..6520846 100644 --- a/web/widgets.mjs +++ b/web/widgets.mjs @@ -110,6 +110,93 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to }; } +// the sheet pane: the same stage-and-ride pattern as the block panes, +// JSON-typed -- the GM's ledger of arbitrated run state (GM, +// 2026-11-17: the model reads it, never writes it; her proposals +// arrive in prose). A record is a whole set: staging replaces the +// entire object, an empty object is a deliberate empty ledger. Bad +// JSON refuses at the stage -- the server would refuse it at the turn. +/** @typedef {{ set: (next?: ?Record) => void, setEditable: (ok: boolean) => void, reset: () => void, staged: ?Record, clearStaged: () => void }} SheetPane */ +/** @param {string} section @param {string} body @returns {SheetPane} */ +export function sheetEditor(section, body) { + const sec = $(section); + const bodyEl = $(body); + const editBtn = el('button', null, 'edit'); + (/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn); + const editor = el('div', 'pane-editor'); + editor.hidden = true; + const area = /** @type {HTMLTextAreaElement} */ (el('textarea')); + area.rows = 6; + area.placeholder = 'the sheet is JSON -- the GM\'s ledger of the run\'s objective state'; + const actions = el('div', 'pane-editor-actions'); + const saveBtn = el('button', null, 'stage'); + const cancelBtn = el('button', null, 'cancel'); + actions.appendChild(saveBtn); + actions.appendChild(cancelBtn); + editor.appendChild(area); + editor.appendChild(actions); + bodyEl.after(editor); + const pending = el('div', 'pane-pending'); + pending.hidden = true; + pending.appendChild(el('span', null, 'edited -- rides your next turn')); + const dropBtn = el('button', null, 'discard edit'); + pending.appendChild(dropBtn); + editor.after(pending); + + /** @type {?Record} */ let sheet = null; // the current truth (never a falsy check -- {} is a live empty ledger) + /** @type {?Record} */ let staged = null; + let mayEdit = false; + let open = false; + + const sync = () => { + bodyEl.hidden = open; + editBtn.hidden = open || !mayEdit; + editor.hidden = !open; + pending.hidden = staged === null; + }; + const renderBody = () => { + const show = staged ?? sheet; + bodyEl.textContent = show == null ? 'nothing tracked' : JSON.stringify(show, null, 2); + bodyEl.classList.toggle('empty', show == null); + }; + const openEditor = () => { + area.value = JSON.stringify(staged ?? sheet ?? {}, null, 2); + open = true; + sync(); + area.focus(); + }; + const cancel = () => { open = false; sync(); }; + const doSave = () => { + try { + const parsed = JSON.parse(area.value); + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + banner('the sheet wants a JSON object'); + return; + } + staged = /** @type {Record} */ (parsed); + } catch (e) { + banner(`the sheet is JSON -- ${String(e.message ?? e).split('\n')[0]}`); + return; + } + cancel(); + renderBody(); + }; + const dropStaged = () => { staged = null; sync(); renderBody(); }; + + editBtn.addEventListener('click', openEditor); + cancelBtn.addEventListener('click', cancel); + saveBtn.addEventListener('click', doSave); + dropBtn.addEventListener('click', dropStaged); + + return { + set(next) { sheet = next ?? null; renderBody(); }, + setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); }, + reset() { cancel(); dropStaged(); }, + get staged() { return staged; }, + clearStaged: dropStaged, + }; +} + // the model registry, fetched once per session -- the selectors read // the saved registry, never the live provider (discovery is the op's // manual act; a listing fetch every render would hammer the endpoint