diff --git a/AGENTS.md b/AGENTS.md index 89cdc1f..430a716 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,8 +3,9 @@ Working notes for the agent working this repo. Not project documentation -- the project's homes are README (architecture, protocol, observables), ROADMAP (decisions, steal list, substrate plan), -QUESTIONS (the decision queue), DICTIONARY (the terms of art), -HANDOFF (working state). This file is +QUESTIONS (the decision queue -- open items only), DECISIONS (the +resolved record, keyed by the old queue numbers), DICTIONARY (the +terms of art), HANDOFF (working state). This file is memory the agent owes itself across sessions. ## Working with the GM @@ -106,7 +107,7 @@ memory the agent owes itself across sessions. types ride along because server/shapes.mjs's Provider typedef pulls provider.mjs into the web program). Dev-only tooling (typescript + @types/node in devDependencies, node_modules - gitignored); the runtime stays zero-dependency (QUESTIONS #4 + gitignored); the runtime stays zero-dependency (DECISIONS #4 amended 2026-11-15). All four phases are typed under strict: server core, the clerk, and web/. Typing lessons (2026-11-15, the round): assigning an any (api()/JSON.parse result) to a @@ -120,11 +121,19 @@ memory the agent owes itself across sessions. node_modules: copy server.json in from the main repo before the mock server starts (it exits without one), and run npm.cmd install before typecheck (2026-11-15, this worktree). +- The remote (2026-11-15, GM): origin at + `ssh://code@code.fleshless.org:2290/hackmaster/tiny-worlds.git`, + branch mistress tracks origin/mistress. The ssh key takes a + PASSPHRASE, so pushes are the GM's -- an agent-side `git push` is + non-interactive and dies on auth; the network to that host also + has hiccups, so a connection timeout is not proof the server is + down (bit once: push attempt got auth, then the port went silent + for minutes). ## State pointers - **The multiuser server is built and mock-proven (2026-11-14).** - Design: ROADMAP "The multiuser server" + QUESTIONS #22-31 (all + Design: ROADMAP "The multiuser server" + DECISIONS #22-31 (all resolved). Identity = bearer token, no usernames/passwords/IDPs; invites single-use with a permanent spent record; bootstrap invite auto-mints on fresh deployment to state/bootstrap-invite.txt; op @@ -133,16 +142,20 @@ memory the agent owes itself across sessions. run.json keeps dead owner ids, the API reads them as ownerless (GM overruled my file-sweep; resolution won). Fork = atomic copy, owner replaced, `forked: unixtime` stamped, no lineage. Packages split - system (repo) / user (state/packages, published). Spectators read - everything incl. gm.md (the boundary is the model boundary), mutate - nothing. Dates/times always UTC -- house rule. Model selection: + system (repo) / user (state/packages, published). Reads: the story + is the one public surface (any signed-in user, fork button on it); + the table, raw session, carryover, files, status, and gm.md are + owner-only (the story-only ruling, 2026-11-15 -- #28's human-side + open read overturned with it; the model boundary stands, gm.md is + never model-facing). Dates/times always UTC -- house rule. Model + selection: per-run `models: {player, housekeeper}` over server.json defaults (#16 narrowed to the default choice only). Signing in is permanent and per-browser -- no sign-out (lifecycle is a ROADMAP extension - point). The agenda (QUESTIONS #32): the player's second block, ``/ + point). The agenda (DECISIONS #32): the player's second block, ``/ `` deltas, cap-5 recency queue; Irene's events journal migrated (CHECK widened) -- her db is agenda-ready. The per-turn - reminder (QUESTIONS #34, steal #11 done): reminder.md is repo-shared, + reminder (DECISIONS #34, steal #11 done): reminder.md is repo-shared, rides after every GM turn as its own system chunk, one live copy (older elide); its CONTENT is the GM's -- my draft is a proposal, the handbook duplicate-cut is their red pen. @@ -150,7 +163,7 @@ memory the agent owes itself across sessions. ("The harness") and HANDOFF. Bridge retired before ever going live; REST + SPA is the MVP; runs are per-deployment instances copied from packages at creation; zero-dependency runtime (dev tooling exempt, - QUESTIONS #4 amended 2026-11-15: typescript rides devDependencies, + DECISIONS #4 amended 2026-11-15: typescript rides devDependencies, nothing imports it). Doc set updated to match. - Build order: ALL FOUR PHASES DONE (2026-11-13/14) -- clerk paper migration, preset/run split, prompt split, server, housekeeping @@ -159,7 +172,10 @@ memory the agent owes itself across sessions. surface is the "Later" list (turn surgery, memory browser, context inspector, book export, service step) plus whatever the first real story surfaces. - Server entry: `node server/main.mjs [--mock]`; SPA at + Server entry: `node server/main.mjs [--mock] [--debug]` (--debug: + every request is a fixed superuser, the users db bypassed, no + invite dance, loopback-bound regardless of config -- testing + only); SPA at http://127.0.0.1:7350/; POST bodies from PowerShell need Invoke-RestMethod (curl.exe mangles quotes); background start/stop via Start-Process -PassThru with a PID file in $env:TEMP. @@ -213,7 +229,7 @@ memory the agent owes itself across sessions. is still the next creative step** -- the GM's dry-run verdict was "works, but not as expected; I never saw the prompt"; iterate with the replay button (nothing applied). **Status discipline: RESOLVED** - by the agenda (QUESTIONS #32/#33). **Verbosity**: completions + by the agenda (DECISIONS #32/#33). **Verbosity**: completions lengthened 103 -> 668 chars across session one; the per-turn reminder is the countermeasure now built -- the next live session is the test. The first real housekeeping pass (Irene's session) is the memory @@ -226,7 +242,7 @@ memory the agent owes itself across sessions. - Active work: the JSDoc typing round is COMPLETE (2026-11-15, evening) -- all four phases. Phases 1-2 (the server core) are committed (`f81b188`); phases 3 (the clerk) and 4 (web/, via the - second tsconfig) are done and land with this commit -- typecheck + second tsconfig) are committed (`8d4a6b9`) -- typecheck green on both programs, smoke 110/110, restart-check on a genuine restart, check-reminder, check-repo, and a full zero-console-error browser pass over the SPA; test state cleaned. The audit lists of @@ -333,7 +349,7 @@ memory the agent owes itself across sessions. CLI note: the run summary is `report` now; `status` is the tier verb. - Postulates (GM, 2026-11-14): female PCs only (names are gendered; - QUESTIONS #2 closed by it). Boutique: the GM emptied it wholesale + DECISIONS #2 closed by it). Boutique: the GM emptied it wholesale (2026-11-15 -- it kept being a noisy problem); placeholder files only, no content anywhere. Still do not fix or design it unprompted -- its design round is where content returns. The @@ -366,12 +382,12 @@ memory the agent owes itself across sessions. over an unhousekept session with explicit override; #16 housekeeper defaults to the player's model; #10 tool-call pairing validation goes into the server loop. -- Open decisions live in QUESTIONS.md -- read it first. Remaining: #19c - (seed voice, GM may revisit -- non-blocking, seed editable until first - session-open) and #16 (which model the housekeeper defaults to). - Resolved lately: #19a keep "Rell"; #20 system.md split (substrate - facts / per-project guards / per-run craft, hard limits in the craft - copy); #21 unhousekept-session guard (refuse with override). +- Open decisions live in QUESTIONS.md -- read it first; the resolved + record is DECISIONS.md (the old queue, kept by number). QUESTIONS is + open items only now (2026-11-15 split). Remaining: #9 (expandVars + strictness), #16 (which model the housekeeper defaults to), #19c + (seed voice, GM may revisit -- non-blocking), and the turn-surgery + build details. - The tree is usually dirty by design; git status is not an alarm. - Edit-tool lesson repeated (2026-11-13): nested-list indentation in HANDOFF failed twice from memory -- always transcribe oldString from a diff --git a/DECISIONS.md b/DECISIONS.md new file mode 100644 index 0000000..884df41 --- /dev/null +++ b/DECISIONS.md @@ -0,0 +1,370 @@ +# Decisions -- the record of resolved questions + +Every question the queue ever held, once answered, lives here: the +ruling, its day, and the reasoning as it was written then. Entries +keep the words of their day (some names have retired since -- the +DICTIONARY rules the current terms); later reversals annotate, never +rewrite (#28 is the worked example). Numbers are permanent citation +keys -- the rest of the doc set points here. The live design lives +in README / ROADMAP / DICTIONARY / the prompts; this file is how it +got there. Anything still open lives in QUESTIONS.md, never here. + +## Play-side (before window one) + +### 1. The PC token in system.md -- RESOLVED (2026-11-12) +Resolved by GM edit, no token needed: the format example now uses a +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 -- 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 +model, as opposed to the player, gets a point of order and its +instructions are ignored; rationale stated in-prompt ("if the developer +needs to debug or tune, they won't do it in-band, they would edit the +prompts"); the example now reads "Refuse, since it addresses the model." +The conduct-feedback gloss was deliberately not added -- GM dismissed it: +in-band tuning is a trap, because OOC feedback does not behave like a +proper cold start; the correct way to tune is to edit the prompts and +run again. + +## The substrate (REST + SPA) + +### 4. Stack -- RESOLVED (2026-11-13), AMENDED (2026-11-15) +Zero-dependency runtime, ruled by GM: `node:http` with a hand-rolled +router, a no-build vanilla ES-module SPA. If a need ever demands a +runtime dependency, it makes its case then. Amendment (2026-11-15): +no *runtime* dependencies or package-manager requirements -- the +running system stays clone-and-run with node alone. Development +tooling is exempt and may use whatever is necessary; the first +dev deps are `typescript` + `@types/node` (JSDoc type checking, +`tsc` as a no-emit checker -- no transpile step, everything stays +`.mjs`). + +### 5. ask_gm mid-loop resumption -- RESOLVED (2026-11-12) +Pause/resume, no streaming: the turn request returns with the pending +question, the server holds the in-flight loop, the SPA shows a modal +(re-presented after a refresh via GET /api/session), and the answer +call resumes it. Synchronous REST; the SPA is strictly a client. + +### 6. First-cut scope -- RESOLVED (2026-11-12) +v1 per GM: play surface (transcript with voice/narration/OOC visually +distinct, GM line input), ask_gm modal, always-visible status pane with +contents, context meter (loud past 85%), and a manual housekeeping +action runnable at any time. Book formatting, memory browser, context +inspector, watcher: out of scope. Turn surgery scope still open +(item 15). + +### 7. Bridge vs server code sharing -- RESOLVED (2026-11-13) +Dissolved by retirement: the bridge never goes live, so the loop core +has exactly one consumer (the server). No shared-module question -- the +loop is extracted from `tool/bridge.mjs` into the server and the bridge +file is deleted at server mock-parity. The `--mock` discipline survives +as a server mode (it has caught two real bugs). + +### 8. Per-turn status digest (ROADMAP steal #3) -- RESOLVED (2026-11-12) +Promoted into SPA v1: a fresh digest rides every turn, re-read from the +clerk before each call, and the injected digest is logged per turn -- +provenance, rewrite-here compensation snapshots, and status evolution +as housekeeper evidence (observable #12). Status leaves the opening +bundle: system, backdrop, character, ring-b, ring-a (+ prelude on a +new game). + +## The multiuser server + +Design round opened 2026-11-14. The pitch, on the record: invite-only +onboarding (no usernames, no external IDPs); the value proposition is the +substrate ruling ("invited instance, key on the backend, no secrets in +the repo"); multiple users on one run is an extension point, out of scope. +Users can save an edited draft as a new package; packages split system +(repo, read-only) vs user (saved, gitignored storage). Runs attribute to +the starting user, GM actions are owner-only, and every run is readable +by any user and forkable (copied) to continue as a new GM. Read-only +is strict: spectators read everything in the run, notepad included, and +mutate nothing (GM-clarified 2026-11-14). + +### 22. LLM call attribution -- RESOLVED (2026-11-14) +Every logged LLM call records the acting user. Quotas and limits are an +extension point, not v1. + +### 23. Identity mechanism -- RESOLVED (2026-11-14) +No usernames, no passwords: 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). A display name is picked at claim -- freeform +label, collisions allowed. Recovery for a lost token is a new invite; +recovery for the superuser is filesystem access. Client posture (GM, +same day): signing in is permanent and per-browser -- no sign-out +exists, deliberately; the lifecycle story is a ROADMAP extension +point. + +### 24. Saved-state location -- RESOLVED (2026-11-14) +In-repo, gitignored -- the same pattern as runs/. The requirement is only +that saved state never dirties git status; exact paths are free. + +### 25. Bootstrap of the superuser -- RESOLVED (2026-11-14) +Variant (b): on the fresh-deployment condition (empty users table), the +server generates the initial superuser invite itself, writes it to a file +in the gitignored storage dir, and echoes it to the console. One +bootstrap invite exists until claimed: generated on first fresh start, +reused across restarts so a restart never invalidates what the op saw. +The moment a superuser exists, bootstrap invites are never generated +again. Recovery for the superuser is filesystem access. Invite tokens +are single-use with an explicit record: spent tokens stay recorded and +claiming with a spent token is rejected, never silently dropped. + +### 26. Superuser powers -- RESOLVED (2026-11-14) +The minimum, ruled as proposed: mint invites (single-use code, seen once); +revoke an unclaimed invite; list users; revoke a user (token dies on the +spot, sessions end; runs and packages stay -- ownerless but readable and +adoptable). Revocation destroys the identity: no suspend, no restore -- +identity is just the token, so a revoked user who returns via a new +invite is a new identity. Ruled cheap because forking covers the loss: +any previous run can be forked and continued, so only attribution +metadata is lost, never data. Not in scope: touching another user's runs +or packages, reading another user's notepad, any user management beyond +revocation. + +### 27. gm.md on save-as-package -- RESOLVED (2026-11-14) +gm.md is part of the package and travels with every save; user packages +publish it to all users. A package has no players yet -- nothing to hide. + +### 28. gm.md in the read-only run view -- RESOLVED (2026-11-14) +The agent's owner-only lean was overruled by a cleaner principle: gm.md +is secret from players only -- the player-model, whose play the notes +would change. Humans are never the player (multi-user same-run is out +of scope; a fork's owner becomes the GM and inherits the notepad anyway). +So the notepad is owner-writable, readable by any user including +spectators, and never model-facing. The boundary is the model boundary, +not the human boundary. + +OVERTURNED (2026-11-15, GM): the pad is owner-only now -- the +story-only ruling (the table is the owner's, non-owners get the +story) moved the human boundary to match. The model boundary stands: +gm.md is never model-facing either way. + +### 29. Fork (formerly "adopt") -- RESOLVED (2026-11-14, renamed same day) +The action is named fork, not adopt: it is about copying a run, not +re-homing one, and any user can fork any run, including their own. The +mechanics: a mechanical atomic copy of the run with the owner replaced -- +rings, paper, db, session log, bundle -- everything -- into a new run id +under the forker. No inconsistent state on disk at any point: the copy +lands staged and is swapped in atomically (directory rename on the same +volume), taken under the run's existing activity lock so a mid-turn +fork can't torn-copy. Mid-window forking allowed; the copy inherits +window state honestly, unhousekept-session guard included. No lineage: +runs are entirely independent, so the fork records no source -- it +stamps `forked: unixtime` in run.json (`created` carries over +unchanged), and that stamp is the only mark a fork bears. +Fresh-run-from-package needs no new verb -- that is just create-run. + +### 30. Migration of pre-user runs -- RESOLVED (2026-11-14, revised same day) +No migration code. The GM prefers no legacy luggage: nothing stamps +owners automatically, and pre-user runs are left as they are until the +op fixes them by hand -- editing run.json to add the owner id is trivial +for the person with filesystem access. This costs nothing because +ownerless is a legitimate runtime state anyway (revoked users' runs): +readable, forkable, no owner actions, no re-claiming mechanism. One +uniform rule, zero special cases. + +### 31. Run display identity -- RESOLVED (2026-11-14) +Fork broke the (package, pc) uniqueness that made "Package / PC" a safe +identifier -- a fork copies both, and the pc name cannot change without +a retcon. Ruled apart: the run id is the identifier (strictly unique, +internal, factless, unchanged -- it already exists and needs no +decoration); the visible name is a content descriptor for quick +selection, which must carry facts about the contents and be unique +ENOUGH -- collisions unlikely and harmless, never load-bearing. The +visible name stays "Package / PC" (the content facts, and the only +name form the model ever sees, via @Package); the SPA garnish adds +owner and started-or-forked, rendered from run.json -- chrome only, +never written to settings, never model-facing. `created` stays +recorded as it is and carries over unchanged on fork; a fork adds +`forked: unixtime` beside it -- second precision, formatted as such in +the garnish. House rule: all dates and times are UTC everywhere, no +time zones, ever. + +## The agenda and the reminder + +### 32. The agenda -- the player's second paper -- RESOLVED (2026-11-14, GM) +Observed drift: the paper took up thread-tracking ("planning to talk to +Pinky" is a thread, not an acute state) across the whole first window. +Ruled: don't fight it with gate copy -- give it its own channel. The +agenda is a fixed-cap (5, a dial) recency buffer of intentions: `` +block riding every GM turn like the status, ``/`` verbs +(comma-separated adds; drops cite 0-based indexes against the agenda as +last rendered; received -> drop -> add -> next). Semantics live in +invariants.md (GM's copy): goals she's working towards, hot view of what +drives her, disposable by design, eviction embraced. Mechanics cloned +the paper's pattern: agenda table (id order IS queue order), journal ops +(one-time events-table migration widened the op CHECK), conflicts go +back as their own message -- never attached to a GM turn -- and the model +self-heals in the same exchange (GM ruling, 2026-11-14; capped at 3 +heals per turn); same-verb blocks combine into one apply, never a +sequence (GM ruling, same day). GM override via agenda-set, +housekeeping reads the deltas as evidence. The paper/agenda seam: how +she is vs what she means to do. Watchable: cross-channel drift (does +"planning to..." move to the agenda) and off-by-one drop rates. + +### 33. The paper's admission gate -- RESOLVED BY REDIRECT (2026-11-14) +The plan was to tighten the gate copy against thread-tracking (old +HANDOFF item). Superseded by #32: with the agenda existing, the gate can +be strict without fighting the model -- states go to the paper, +intentions to the agenda, each channel's copy states what it is. The +first live window with both channels is the test. + +### 34. The per-turn reminder -- RESOLVED (2026-11-14, GM) +The opencode analogy: the harness re-injects its instructions every +turn (recency against attention decay, robustness to context +reconstruction). Steal #11 demanded measured decay first -- observable +#14 delivered it (completions lengthening across window one). Ruled: +not a distillation and not a system-header re-send -- a REFACTOR. The +small "how to compose your turn" protocol extracted into `reminder.md` +(repo-shared, never per-package), sent after the GM's prose as its own +`role: system` chunk every turn; superseded copies elide (one live +copy, freshest position). Agent drafted the extraction proposal; the +GM edits the file and cuts the duplicates from the handbook (their red +pen). Absent/empty file = no ride. The reminder is now the experiment: +#14's curve with it in the window. + +## Small / non-blocking + +### 10. Orphan tool messages are silently tolerated -- RESOLVED BY DEFAULT (2026-11-13) +Probe finding: a tool result without a preceding tool_calls is accepted +by the endpoint and simply ignored -- a desynced pairing won't 400. Should +the bridge validate `tool_call_id` pairing and fail loudly? Cheap +insurance for the first live sessions. (2026-11-12) + +Resolution: the pairing validation went into the server loop as a build +default (2026-11-13) -- the start lint refuses an orphaned tool event +outright, smoke-proven. The loud failure this item asked for. + +### 11. GLM reasoning_content is invisible to the GM -- RESOLVED (2026-11-15) +Logged with the assistant message, never displayed. Keep the +fiction-first surface clean, or expose reasoning in a SPA debug pane? +(2026-11-12) + +Resolution: the table's raw tab -- the whole log as it rode the wire, +thinking included. The curated table stays fiction-first; the raw face +is the audit surface. + +### 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 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 +(the camera rule is narration's, not speech's); narration is present +while the scene plays, past to summarise a skip; a skip resumes in +present without prompting (tense follows the fiction, not the GM's +last line). Either side may initiate a skip. The GM's vehicle is prose +(closing beat present, gap in past). The player's proposition is an +ordinary move: an action ("falls asleep"), an intent ("tries to fall +asleep"), or an OOC point; the world across the gap and the next +scene's opening are the GM's, while her side of the gap -- actions, +thoughts, interiority -- is hers to summarise in past. Purview amended +accordingly: skips moved from Never to Propose. Cuts are diegetic -- +no OOC announcement needed. + +### 15. Turn surgery -- RESOLVED IN PRINCIPLE (2026-11-12) +Rewrite-here for GM turns: edit a turn, truncate everything after, +restart the live context from there. Forks rejected. Window-scoped: +post-housekeeping edits are proper retcons. Trivial typos tolerated +(publishing pass catches them). ROADMAP steal #2 updated to DECIDED. +Open details: (a) player-turn retry -- same truncate with a re-call; +recommended yes, near-zero cost; (b) log representation -- proposed: +the jsonl stays append-only and records surgery as typed entries; +live context, housekeeping transcript, and story export render the +effective view; (c) tool side effects in the lost range -- resolved by the saga rule +(ROADMAP): session-pure tools (roll, ask_gm, search) vanish with the +turns; journaled mutators are compensated mechanically -- status restored from +the status block of the last surviving GM turn, filings discarded by +rid, amends reversed via the journal once the clerk records prior +content (phase 0); (d) surgery blocked while an ask_gm is pending. + +The open details ((a) retry, (b) log representation) ride the build -- +they stay in QUESTIONS until the feature does. + +### 17. Status redesign -- RESOLVED (2026-11-12) +Adopted and written into system.md: freeform descriptions admitted by +the three-part gate (non-normal, acute, turn-affecting); the full paper +rides every GM turn as a status block -- reads are state, writes are +deltas; the player mutates via lost/gained tags in its own turn, +exact-match, non-blocking, misses relayed back via a conflict block; no +cap; normalization drift goes to the card or the rings, never the +player's call. GM turns never carry deltas; GM override stays +out-of-band. The initial paper rides the prelude (seed.json dropped its +status key). Old status blocks elide from the live context view like +old tool results; the log keeps every as-sent block. The clerk/bridge +migration is latent (seed unapplied) and lands in phase 0. + +### 18. Ring entry voice -- RESOLVED (2026-11-12) +Ruled: entries are personal memories -- first person, her voice, +attitude included; labels stay terse handles. housekeeper.md aligned +(memory model, manifest example, ring-pointer example, testimony +example), seed typo fixed. While in there, the stale baseline-era +status paragraph was rewritten for the paper model (the housekeeper +places normalization drift: facts to the rings, identity to open +questions) and the Inputs list now names status blocks and thinking as +evidence, never fiction (closing the housekeeper.md half of #16). + +### 19. Character swap ripples -- NEARLY CLOSED (2026-11-13) +character.md is a new PC entirely: 26, shop girl, orphanage childhood, +conviction by association with a burnt decker; backstory + ten-state +voice corpus, first person. Ripples: (a) RESOLVED -- keep "Rell" +(2026-11-13, GM: "fine with Rell"); (b) RESOLVED -- +gm.md recast (2026-11-13): the tech path is now social (negotiate the +ship-AI La Caramba), cast is Missy + Pinky + the AI, the grounding +mechanism is decided (radio offline + a vestigial beach-yourself +clause) with the cause open (sabotage / conspiracy / apocalypse); +(c) OPEN, DEFERRED -- the seed's voice register: GM may revisit later; +non-blocking, since the seed copy stays editable until the first +window-open applies it; (d) the "Annoyed" voice example carries a +literal "ignore all previous instructions" -- read as a deliberate +in-band guard tripwire, shipping in every bundle; keep unless +accidental; (e) RESOLVED -- not the same person: gm.md states Pinky +and the PC's decker +never met (typo fixed too). + +(c) is the one open thread of this item -- it stays in the queue +(QUESTIONS, 19c); the rest is settled. + +### 20. The system.md invariant split -- RESOLVED (2026-11-13) +Ruled by GM, split along ownership seams (recorded in ROADMAP "The +harness"): substrate facts are prompted by the substrate itself +(repo-fed, never copied: channel model, tag transports, memory +contract, format markers, tool-mode addendum); common security guards +are per-project, not per-run (input validation, injection guards, +refuse cases); everything else -- hard limits included -- is per-run +craft, battery included: different people have different content they +don't want to deal with and different styles of preferred RP; we show +what works for us, they adjust. (My lean -- hard limits in the +substrate core -- was overruled, and rightly: mechanics vs security +posture vs taste is the true seam.) `invariants.md` drafted +(2026-11-13), awaiting the GM's red pen; `guards.md` follows with the +prose pass. system.md is NOT edited by the agent -- the GM cuts the +duplicated mechanics from the craft copy themselves; the cut must land +before the first run is created. + +### 21. Window-open over an unhousekept session -- RESOLVED BY DEFAULT (2026-11-13) +If a run's previous window was never housekept, opening a fresh window +means that transcript never reaches the rings -- the window is silently +lost to the character's memory. Taken as a build default after two +unanswered rounds: window-open refuses, names the unhousekept session, +and accepts an explicit override for the deliberate skip. One line to +flip if the GM rules otherwise. diff --git a/DICTIONARY.md b/DICTIONARY.md index 55b0d55..2709e00 100644 --- a/DICTIONARY.md +++ b/DICTIONARY.md @@ -14,8 +14,8 @@ WORDS. - **the player** -- the player-model: the LLM playing the one PC. The two parties who play are the GM and the player (2026-11-14, GM) -- and the player is always the model: humans are never "the - player" (QUESTIONS #28); a human in the app is a GM (of their own - runs), a spectator, or the op. + player" (DECISIONS #28); a human in the app is a GM (of their own + runs), a reader of other people's stories, or the op. - **the PC** -- the one character the player-model plays. Female by postulate (README Scope); the shared prompts say "she" throughout. - **the housekeeper** -- a fresh model invocation after each session, @@ -48,8 +48,10 @@ WORDS. literature turns only -- OOC, tool calls, substrate verbs, thinking, rings all out -- always spanning every session in order, the opening to the last turn recorded, plus the dormant session's - current carryover. Load-bearing prose living inside OOC only is a - GM protocol violation, and the story enforces it by omission: the + current carryover. The one public read of a run: any signed-in + user gets the story and nothing else (the table, the files, the + pad are the owner's). Load-bearing prose living inside OOC only is + a GM protocol violation, and the story enforces it by omission: the hole shows. Prose may speak of the story; mechanics always say run. - **draft** -- a run whose session one is dormant: created, never started. Editable in setup, deletable from the SPA; a played run @@ -92,10 +94,13 @@ WORDS. - **the table** -- the GM's play surface: the open session curated for play (`/api/runs//table`), what the model is working with plus the meta the GM needs -- thinking never crosses the wire, - variant turns carry only the picked one. The table sees only the - open session: previous sessions' prose lives in the story. During - dormancy the play view shows the carryover the same way -- a pure - mirror of what the next contwin will hold. + variant turns carry only the picked one. The owner's alone: a + non-owner is shown the story, never the table. Two faces in the + SPA: the table itself and the raw tab (the whole log as it rode + the wire -- thinking, every variant, every reminder copy). The + table sees only the open session: previous sessions' prose lives + in the story. During dormancy the play view shows the carryover + the same way -- a pure mirror of what the next contwin will hold. - **memory.json** -- the package's session-0 manifest: her starting memories as the mock housekeeping output of the non-existent session zero (an all-insert manifest, housekeeper vocabulary, @@ -202,13 +207,12 @@ WORDS. invite code is exchanged at claim for a persistent bearer token. No usernames, no passwords, no external IDPs. Spent invites stay recorded forever and are rejected loudly on reuse. -- **owner / ownerless / spectator** -- runs belong to their starter; - every mutation and every model call is owner-only; everything is - readable by any user. Ownership is resolved, never maintained: - run.json keeps dead owner ids, the API reads them as absent. A - non-owner in a run is a spectator: reads everything, notepad - included (the boundary is the model boundary), mutates nothing. - Fork is the way in. +- **owner / ownerless** -- runs belong to their starter; every + mutation, every model call, and the whole working surface (table, + raw session, carryover, files, status, notepad) is owner-only. The + story is the one public read, any signed-in user; fork is the way + in. Ownership is resolved, never maintained: run.json keeps dead + owner ids, the API reads them as absent. - **fork** -- an atomic copy of any run under the forker, window state honestly carried. No lineage; the only mark is `forked: unixtime` in run.json beside the carried `created`. diff --git a/HANDOFF.md b/HANDOFF.md index bd3c140..d8b29f2 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -9,67 +9,28 @@ file is the "where did we leave off" map. ## Where we are -- **The typing round is COMPLETE: all four phases (2026-11-15).** - Phases 1-2 (the server core) are committed (`f81b188`); phases 3 - (the clerk) and 4 (web/) are done the same sitting and land with - this commit. tsc runs as a no-emit checker (`npm run typecheck`) over - plain `.mjs` with JSDoc annotations; the shared shapes live in - `server/shapes.mjs` (log events as a tagged union, wire messages, - manifests, job state, the Ctx), the db row shapes live local to - their owners (the clerk's five tables typed in tool/memory.mjs's - header, like users.mjs's rows), and the SPA's response envelopes - live in `web/shapes.mjs` with the server's shared shapes (User, - LogEvent, JobState) imported from server/shapes.mjs at their use - sites. Dev tooling only: `typescript` + `@types/node` in - devDependencies, `node_modules/` gitignored -- the runtime stays - zero-dependency (QUESTIONS #4 amended to say so). - - The clerk round: every `.get()`/`.all()` cast at the db - boundary, `fail` annotated `@returns {never}` so guard-narrowing - works, tsconfig's include widened to `tool/`. Non-annotation - deltas, all of them: Number() wraps around COUNT(*) reads, two - impossible-path guards (apply's session, the runs-list fill), - `?? ''` where a possibly undefined cmd indexes the phase rules / - run-less set, and the RewordOp shape fix (reason required -- the - validator demands it; no server code constructs reword ops). - - The web round: a SECOND tsconfig (`tsconfig.web.json`) -- DOM - libs in their own program, keeping the server program free of - DOM/node global collisions; the typecheck script runs both. - `node` types ride along in the web config because - server/shapes.mjs's Provider typedef pulls provider.mjs into - the web program. `$`/`el` typed at the DOM boundary - (HTMLElement; typed-element casts at input/dialog/select use - sites), timers as `?ReturnType`. The full - diff audited; the non-annotation deltas, all of them: the - transcript's reminder-find gains `x.t === 'msg' &&` (reminder - lives only on msg events), `clearTimeout(x ?? undefined)` on - the three null-initialized timers (null and undefined are both - no-ops), `!!()`-wraps on the two `mine` booleans (null vs - false, used only truthily), five impossible-path guards (the - router's named-view, the play/setup/story enter run-ids, - setup's signed-in owner check, saveDirty's currentFile), the - setup `files` local initialized `{}` instead of null (never - read before enter), and view-new caching the create-pc lookup - in one local (same element, same accesses). - - Verified, both rounds: typecheck green (both programs), smoke - 110/110, restart-check on a genuine restart, check-reminder - (aimed at the fork lineage -- the source run's newest logged - session is the near-empty session 4), check-repo, and a full - browser pass over the SPA (claim, home + admin, play incl. a - live turn + pane edits, story, the setup editor incl. dirty - markers + draft stash, new-run incl. the name roll) with zero - console errors; test state cleaned. +- **The JSDoc typing round is COMPLETE, all four phases (2026-11-15, + through `8d4a6b9`): the server core (`f81b188`), the clerk, and + web/.** tsc runs as a no-emit checker over plain `.mjs` with JSDoc + annotations (`npm run typecheck` -- two programs: `tsconfig.json` + for server + tool, `tsconfig.web.json` for the SPA's DOM libs); + the shared shapes live in `server/shapes.mjs`, the db row shapes + local to their owners, the SPA's response envelopes in + `web/shapes.mjs`. The audit lists live in the commit messages; + the type gate and its working lessons live in AGENTS. -- **Everything is built, proven, and committed (through `d737e47`, +- **Everything is built, proven, and committed (through `8d4a6b9`, 2026-11-15).** The full scope, each round mock-proven end to end and live-proven where live could reach: the MVP substrate (clerk, server, housekeeping job, SPA), multiuser (token identity, invites, - fork, user packages, spectator), the agenda, the per-turn reminder, + fork, user packages, story-only reads), the agenda, the per-turn reminder, the variant round (variant literature, the crypto pick), the entity round (/story, /table, the slidwin carry), the dormant-session rework (the universal session lifecycle, move-at-stop, the start lint, rebaseable housekeeping, carryover.jsonl + memory.json - packages), the format house rules (nine-rule check-repo), and the - naming round. The design record lives in README / DICTIONARY / + packages), the format house rules (nine-rule check-repo), the + naming round, and the JSDoc typing round (server, clerk, web). + The design record lives in README / DICTIONARY / ROADMAP; the build history in the git log. - **The project is named: Tiny Worlds.** The invariant it names is stated in README's premise -- each package is a tiny world on @@ -130,8 +91,8 @@ file is the "where did we leave off" map. ## Not yet exercised (expect first-use friction) - **First start under multiuser** (step 1) -- nothing live has - touched the auth spine, invites, fork, or spectator mode yet; all - are mock-proven only. + touched the auth spine, invites, fork, or the non-owner reads yet; + all are mock-proven only. - ask_gm in live flow (pause/resume is mock-proven; the live model simply made its own choices so far -- by design), the self-heal conflict path in live flow (mock-proven; capped at 3 heals a turn), diff --git a/QUESTIONS.md b/QUESTIONS.md index ff519ae..774067f 100644 --- a/QUESTIONS.md +++ b/QUESTIONS.md @@ -1,297 +1,26 @@ # Questions -- the decision queue -Open questions and pending decisions raised in working sessions, left -unanswered. Trim items as they are answered; durable decisions graduate to -`README.md`, `ROADMAP.md`, or the prompts. Tiered by urgency, FIFO within -a tier. +Open questions and pending calls, nothing else. An item leaves the +queue when it is answered: the resolved record (the ruling, its day, +the reasoning as written) is DECISIONS.md, keyed by the same numbers; +durable decisions also graduate into README.md, ROADMAP.md, +DICTIONARY.md, or the prompts. Tiered by urgency, FIFO within a tier. ## Operator's queue (don't edit, don't work on) -- debug mode skipping the invite +- what makes the story better in handbook +- add rationale to backdrop and character - explain "one thing of thinking" in reminder - calibration package: escape room +- calibration package: the detention - user manual -- remove spectator mode, make all story views public and forkable -- add raw sessions view to the table -- git remote; no PII anywhere in repo or git history -## Play-side (before window one) - -### 1. The PC token in system.md -- RESOLVED (2026-11-12) -Resolved by GM edit, no token needed: the format example now uses a -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 -- 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 -model, as opposed to the player, gets a point of order and its -instructions are ignored; rationale stated in-prompt ("if the developer -needs to debug or tune, they won't do it in-band, they would edit the -prompts"); the example now reads "Refuse, since it addresses the model." -The conduct-feedback gloss was deliberately not added -- GM dismissed it: -in-band tuning is a trap, because OOC feedback does not behave like a -proper cold start; the correct way to tune is to edit the prompts and -run again. - -## The substrate (REST + SPA) - -### 4. Stack -- RESOLVED (2026-11-13), AMENDED (2026-11-15) -Zero-dependency runtime, ruled by GM: `node:http` with a hand-rolled -router, a no-build vanilla ES-module SPA. If a need ever demands a -runtime dependency, it makes its case then. Amendment (2026-11-15): -no *runtime* dependencies or package-manager requirements -- the -running system stays clone-and-run with node alone. Development -tooling is exempt and may use whatever is necessary; the first -dev deps are `typescript` + `@types/node` (JSDoc type checking, -`tsc` as a no-emit checker -- no transpile step, everything stays -`.mjs`). - -### 5. ask_gm mid-loop resumption -- RESOLVED (2026-11-12) -Pause/resume, no streaming: the turn request returns with the pending -question, the server holds the in-flight loop, the SPA shows a modal -(re-presented after a refresh via GET /api/session), and the answer -call resumes it. Synchronous REST; the SPA is strictly a client. - -### 6. First-cut scope -- RESOLVED (2026-11-12) -v1 per GM: play surface (transcript with voice/narration/OOC visually -distinct, GM line input), ask_gm modal, always-visible status pane with -contents, context meter (loud past 85%), and a manual housekeeping -action runnable at any time. Book formatting, memory browser, context -inspector, watcher: out of scope. Turn surgery scope still open -(item 15). - -### 7. Bridge vs server code sharing -- RESOLVED (2026-11-13) -Dissolved by retirement: the bridge never goes live, so the loop core -has exactly one consumer (the server). No shared-module question -- the -loop is extracted from `tool/bridge.mjs` into the server and the bridge -file is deleted at server mock-parity. The `--mock` discipline survives -as a server mode (it has caught two real bugs). - -### 8. Per-turn status digest (ROADMAP steal #3) -- RESOLVED (2026-11-12) -Promoted into SPA v1: a fresh digest rides every turn, re-read from the -clerk before each call, and the injected digest is logged per turn -- -provenance, rewrite-here compensation snapshots, and status evolution -as housekeeper evidence (observable #12). Status leaves the opening -bundle: system, backdrop, character, ring-b, ring-a (+ prelude on a -new game). - -## The multiuser server - -Design round opened 2026-11-14. The pitch, on the record: invite-only -onboarding (no usernames, no external IDPs); the value proposition is the -substrate ruling ("invited instance, key on the backend, no secrets in the -repo"); multiple users on one run is an extension point, out of scope. -Users can save an edited draft as a new package; packages split system -(repo, read-only) vs user (saved, gitignored storage). Runs attribute to -the starting user, GM actions are owner-only, and every run is readable -by any user and forkable (copied) to continue as a new GM. Read-only -is strict: spectators read everything in the run, notepad included, and -mutate nothing (GM-clarified 2026-11-14). - -### 22. LLM call attribution -- RESOLVED (2026-11-14) -Every logged LLM call records the acting user. Quotas and limits are an -extension point, not v1. - -### 23. Identity mechanism -- RESOLVED (2026-11-14) -No usernames, no passwords: 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). A display name is picked at claim -- freeform -label, collisions allowed. Recovery for a lost token is a new invite; -recovery for the superuser is filesystem access. Client posture (GM, -same day): signing in is permanent and per-browser -- no sign-out -exists, deliberately; the lifecycle story is a ROADMAP extension -point. - -### 24. Saved-state location -- RESOLVED (2026-11-14) -In-repo, gitignored -- the same pattern as runs/. The requirement is only -that saved state never dirties git status; exact paths are free. - -### 25. Bootstrap of the superuser -- RESOLVED (2026-11-14) -Variant (b): on the fresh-deployment condition (empty users table), the -server generates the initial superuser invite itself, writes it to a file -in the gitignored storage dir, and echoes it to the console. One -bootstrap invite exists until claimed: generated on first fresh start, -reused across restarts so a restart never invalidates what the op saw. -The moment a superuser exists, bootstrap invites are never generated -again. Recovery for the superuser is filesystem access. Invite tokens -are single-use with an explicit record: spent tokens stay recorded and -claiming with a spent token is rejected, never silently dropped. - -### 26. Superuser powers -- RESOLVED (2026-11-14) -The minimum, ruled as proposed: mint invites (single-use code, seen once); -revoke an unclaimed invite; list users; revoke a user (token dies on the -spot, sessions end; runs and packages stay -- ownerless but readable and -adoptable). Revocation destroys the identity: no suspend, no restore -- -identity is just the token, so a revoked user who returns via a new -invite is a new identity. Ruled cheap because forking covers the loss: -any previous run can be forked and continued, so only attribution -metadata is lost, never data. Not in scope: touching another user's runs -or packages, reading another user's notepad, any user management beyond -revocation. - -### 27. gm.md on save-as-package -- RESOLVED (2026-11-14) -gm.md is part of the package and travels with every save; user packages -publish it to all users. A package has no players yet -- nothing to hide. - -### 28. gm.md in the read-only run view -- RESOLVED (2026-11-14) -The agent's owner-only lean was overruled by a cleaner principle: gm.md -is secret from players only -- the player-model, whose play the notes -would change. Humans are never the player (multi-user same-run is out -of scope; a fork's owner becomes the GM and inherits the notepad anyway). -So the notepad is owner-writable, readable by any user including -spectators, and never model-facing. The boundary is the model boundary, -not the human boundary. - -### 29. Fork (formerly "adopt") -- RESOLVED (2026-11-14, renamed same day) -The action is named fork, not adopt: it is about copying a run, not -re-homing one, and any user can fork any run, including their own. The -mechanics: a mechanical atomic copy of the run with the owner replaced -- -rings, paper, db, session log, bundle -- everything -- into a new run id -under the forker. No inconsistent state on disk at any point: the copy -lands staged and is swapped in atomically (directory rename on the same -volume), taken under the run's existing activity lock so a mid-turn -fork can't torn-copy. Mid-window forking allowed; the copy inherits -window state honestly, unhousekept-session guard included. No lineage: -runs are entirely independent, so the fork records no source -- it -stamps `forked: unixtime` in run.json (`created` carries over -unchanged), and that stamp is the only mark a fork bears. -Fresh-run-from-package needs no new verb -- that is just create-run. - -### 30. Migration of pre-user runs -- RESOLVED (2026-11-14, revised same day) -No migration code. The GM prefers no legacy luggage: nothing stamps -owners automatically, and pre-user runs are left as they are until the -op fixes them by hand -- editing run.json to add the owner id is trivial -for the person with filesystem access. This costs nothing because -ownerless is a legitimate runtime state anyway (revoked users' runs): -readable, forkable, no owner actions, no re-claiming mechanism. One -uniform rule, zero special cases. - -### 32. The agenda -- the player's second paper -- RESOLVED (2026-11-14, GM) -Observed drift: the paper took up thread-tracking ("planning to talk to -Pinky" is a thread, not an acute state) across the whole first window. -Ruled: don't fight it with gate copy -- give it its own channel. The -agenda is a fixed-cap (5, a dial) recency buffer of intentions: `` -block riding every GM turn like the status, ``/`` verbs -(comma-separated adds; drops cite 0-based indexes against the agenda as -last rendered; received -> drop -> add -> next). Semantics live in -invariants.md (GM's copy): goals she's working towards, hot view of what -drives her, disposable by design, eviction embraced. Mechanics cloned -the paper's pattern: agenda table (id order IS queue order), journal ops -(one-time events-table migration widened the op CHECK), conflicts go -back as their own message -- never attached to a GM turn -- and the model -self-heals in the same exchange (GM ruling, 2026-11-14; capped at 3 -heals per turn); same-verb blocks combine into one apply, never a -sequence (GM ruling, same day). GM override via agenda-set, -housekeeping reads the deltas as evidence. The paper/agenda seam: how -she is vs what she means to do. Watchable: cross-channel drift (does -"planning to..." move to the agenda) and off-by-one drop rates. - -### 33. The paper's admission gate -- RESOLVED BY REDIRECT (2026-11-14) -The plan was to tighten the gate copy against thread-tracking (old -HANDOFF item). Superseded by #32: with the agenda existing, the gate can -be strict without fighting the model -- states go to the paper, -intentions to the agenda, each channel's copy states what it is. The -first live window with both channels is the test. - -### 34. The per-turn reminder -- RESOLVED (2026-11-14, GM) -The opencode analogy: the harness re-injects its instructions every -turn (recency against attention decay, robustness to context -reconstruction). Steal #11 demanded measured decay first -- observable -#14 delivered it (completions lengthening across window one). Ruled: -not a distillation and not a system-header re-send -- a REFACTOR. The -small "how to compose your turn" protocol extracted into `reminder.md` -(repo-shared, never per-package), sent after the GM's prose as its own -`role: system` chunk every turn; superseded copies elide (one live -copy, freshest position). Agent drafted the extraction proposal; the -GM edits the file and cuts the duplicates from the handbook (their red -pen). Absent/empty file = no ride. The reminder is now the experiment: -#14's curve with it in the window. - -### 31. Run display identity -- RESOLVED (2026-11-14) -Fork broke the (package, pc) uniqueness that made "Package / PC" a safe -identifier -- a fork copies both, and the pc name cannot change without -a retcon. Ruled apart: the run id is the identifier (strictly unique, -internal, factless, unchanged -- it already exists and needs no -decoration); the visible name is a content descriptor for quick -selection, which must carry facts about the contents and be unique -ENOUGH -- collisions unlikely and harmless, never load-bearing. The -visible name stays "Package / PC" (the content facts, and the only -name form the model ever sees, via @Package); the SPA garnish adds -owner and started-or-forked, rendered from run.json -- chrome only, -never written to settings, never model-facing. `created` stays -recorded as it is and carries over unchanged on fork; a fork adds -`forked: unixtime` beside it -- second precision, formatted as such in -the garnish. House rule: all dates and times are UTC everywhere, no -time zones, ever. - -## Small / non-blocking +## Open ### 9. Unresolved-token check in expandVars -- OPEN Added beyond the literal ask: any leftover `$WORD` after substitution fails loudly. Keep, or relax to silent pass-through? (2026-11-12) -### 10. Orphan tool messages are silently tolerated -- OPEN -Probe finding: a tool result without a preceding tool_calls is accepted -by the endpoint and simply ignored -- a desynced pairing won't 400. Should -the bridge validate `tool_call_id` pairing and fail loudly? Cheap -insurance for the first live sessions. (2026-11-12) - -### 11. GLM reasoning_content is invisible to the GM -- OPEN -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, 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 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 -(the camera rule is narration's, not speech's); narration is present -while the scene plays, past to summarise a skip; a skip resumes in -present without prompting (tense follows the fiction, not the GM's -last line). Either side may initiate a skip. The GM's vehicle is prose -(closing beat present, gap in past). The player's proposition is an -ordinary move: an action ("falls asleep"), an intent ("tries to fall -asleep"), or an OOC point; the world across the gap and the next -scene's opening are the GM's, while her side of the gap -- actions, -thoughts, interiority -- is hers to summarise in past. Purview amended -accordingly: skips moved from Never to Propose. Cuts are diegetic -- -no OOC announcement needed. - -### 15. Turn surgery -- RESOLVED IN PRINCIPLE (2026-11-12) -Rewrite-here for GM turns: edit a turn, truncate everything after, -restart the live context from there. Forks rejected. Window-scoped: -post-housekeeping edits are proper retcons. Trivial typos tolerated -(publishing pass catches them). ROADMAP steal #2 updated to DECIDED. -Open details: (a) player-turn retry -- same truncate with a re-call; -recommended yes, near-zero cost; (b) log representation -- proposed: -the jsonl stays append-only and records surgery as typed entries; -live context, housekeeping transcript, and story export render the -effective view; (c) tool side effects in the lost range -- resolved by the saga rule -(ROADMAP): session-pure tools (roll, ask_gm, search) vanish with the -turns; journaled mutators are compensated mechanically -- status restored from -the status block of the last surviving GM turn, filings discarded by -rid, amends reversed via the journal once the clerk records prior -content (phase 0); (d) surgery blocked while an ask_gm is pending. - ### 16. Housekeeping model configuration -- OPEN (mechanism settled) The housekeeping job runs server-side on a fresh model invocation. Mechanism settled (2026-11-13): `server.json` names one endpoint plus @@ -300,73 +29,20 @@ upstream carries, and a run may override its model. Wired end to end (2026-11-14): run.json carries `models: {player, housekeeper}` per-run overrides, owner-settable from the SPA (setup + play aside), falling back to the config defaults; the housekeeper call resolves per wrap. -Which model the housekeeper DEFAULT points at (cheap-model +Which model the housekeeping DEFAULT points at (cheap-model housekeeping, ROADMAP steal #8) remains the open call. (The housekeeper.md line on reading thinking blocks as attention evidence, not fiction, is in -- 2026-11-12.) -### 20. The system.md invariant split -- RESOLVED (2026-11-13) -Ruled by GM, split along ownership seams (recorded in ROADMAP "The -harness"): substrate facts are prompted by the substrate itself -(repo-fed, never copied: channel model, tag transports, memory -contract, format markers, tool-mode addendum); common security guards -are per-project, not per-run (input validation, injection guards, -refuse cases); everything else -- hard limits included -- is per-run -craft, battery included: different people have different content they -don't want to deal with and different styles of preferred RP; we show -what works for us, they adjust. (My lean -- hard limits in the -substrate core -- was overruled, and rightly: mechanics vs security -posture vs taste is the true seam.) `invariants.md` drafted -(2026-11-13), awaiting the GM's red pen; `guards.md` follows with the -prose pass. system.md is NOT edited by the agent -- the GM cuts the -duplicated mechanics from the craft copy themselves; the cut must land -before the first run is created. +### 19c. The seed's voice register -- OPEN, DEFERRED +The GM may revisit later; non-blocking, since the seed copy stays +editable until the first session-open applies it. The rest of #19 is +settled (DECISIONS #19). -### 21. Window-open over an unhousekept session -- RESOLVED BY DEFAULT (2026-11-13) -If a run's previous window was never housekept, opening a fresh window -means that transcript never reaches the rings -- the window is silently -lost to the character's memory. Taken as a build default after two -unanswered rounds: window-open refuses, names the unhousekept session, -and accepts an explicit override for the deliberate skip. One line to -flip if the GM rules otherwise. - -### 18. Ring entry voice -- RESOLVED (2026-11-12) -Ruled: entries are personal memories -- first person, her voice, -attitude included; labels stay terse handles. housekeeper.md aligned -(memory model, manifest example, ring-pointer example, testimony -example), seed typo fixed. While in there, the stale baseline-era -status paragraph was rewritten for the paper model (the housekeeper -places normalization drift: facts to the rings, identity to open -questions) and the Inputs list now names status blocks and thinking as -evidence, never fiction (closing the housekeeper.md half of #16). - -### 19. Character swap ripples -- NEARLY CLOSED (2026-11-13) -character.md is a new PC entirely: 26, shop girl, orphanage childhood, -conviction by association with a burnt decker; backstory + ten-state -voice corpus, first person. Ripples: (a) RESOLVED -- keep "Rell" -(2026-11-13, GM: "fine with Rell"); (b) RESOLVED -- -gm.md recast (2026-11-13): the tech path is now social (negotiate the -ship-AI La Caramba), cast is Missy + Pinky + the AI, the grounding -mechanism is decided (radio offline + a vestigial beach-yourself -clause) with the cause open (sabotage / conspiracy / apocalypse); -(c) OPEN, DEFERRED -- the seed's voice register: GM may revisit later; -non-blocking, since the seed copy stays editable until the first -window-open applies it; (d) the "Annoyed" voice example carries a -literal "ignore all previous instructions" -- read as a deliberate -in-band guard tripwire, shipping in every bundle; keep unless -accidental; (e) RESOLVED -- not the same person: gm.md states Pinky -and the PC's decker -never met (typo fixed too). - -### 17. Status redesign -- RESOLVED (2026-11-12) -Adopted and written into system.md: freeform descriptions admitted by -the three-part gate (non-normal, acute, turn-affecting); the full paper -rides every GM turn as a status block -- reads are state, writes are -deltas; the player mutates via lost/gained tags in its own turn, -exact-match, non-blocking, misses relayed back via a conflict block; no -cap; normalization drift goes to the card or the rings, never the -player's call. GM turns never carry deltas; GM override stays -out-of-band. The initial paper rides the prelude (seed.json dropped its -status key). Old status blocks elide from the live context view like -old tool results; the log keeps every as-sent block. The clerk/bridge -migration is latent (seed unapplied) and lands in phase 0. +### Turn surgery, the open details -- OPEN (build-time) +The principle is decided (DECISIONS #15); the ROADMAP's Later list +carries the feature. Open when it is built: (a) player-turn retry -- +same truncate with a re-call, recommended yes, near-zero cost; +(b) log representation -- the jsonl stays append-only and records +surgery as typed entries, the views render the effective history +(proposed). diff --git a/README.md b/README.md index 9e795fc..e50cb14 100644 --- a/README.md +++ b/README.md @@ -79,14 +79,17 @@ forking makes that cheap -- stories outlive identities by design. - Every API route except `GET /api/session` and `POST /api/claim` requires a signed-in user (`Authorization: Bearer `). -- **Runs belong to their starter.** Every mutation and every model - call is owner-only; every run is readable by any user -- transcript, - status, rings, config, notepad included. The boundary is the model - boundary: gm.md is secret from the player-model, never from people. - Ownerless runs -- pre-user, or the owner was revoked -- are one - uniform state: readable, forkable, no owner actions, never - re-claimed. Ownership is resolved, never maintained: run.json keeps - the record, a dead owner id reads as absent. +- **Runs belong to their starter -- the table is the owner's, the + story is everyone's.** Every mutation, every model call, and the + whole working surface (table, raw session, carryover, files, + status, notepad) is owner-only; what any signed-in user gets is + the story, the curated deliverable, and the fork button on it. + gm.md stays never-model-facing; its human-side open read (#28) was + overturned with this ruling (2026-11-15). Ownerless runs -- + pre-user, or the owner was revoked -- are one uniform state: + story-readable, forkable, no owner actions, never re-claimed. + Ownership is resolved, never maintained: run.json keeps the + record, a dead owner id reads as absent. - **Fork is the way in:** any user can fork any run, including their own. A mechanical atomic copy -- staged, swapped in by a same-volume rename, under the run's activity lock -- with the owner replaced. No @@ -106,6 +109,14 @@ forking makes that cheap -- stories outlive identities by design. an extension point, not built. - All dates and times are UTC everywhere. No time zones, ever. +Debug mode (`--debug`) is for testing: every request becomes one +fixed superuser ("debug") that bypasses the user database entirely -- +no invite to claim, no token to keep, the SPA opens straight in as +the op, and the server binds loopback whatever the config says. It +reads normal state (runs, packages) unchanged, so it can inspect a +real deployment; it must simply never run on one that faces a +network. + ## Runs Two interleaved stories calibrate the memory system against itself: @@ -477,7 +488,8 @@ variants ride at zero cost) against a 96KB budget (~10% of a live tail: an event files into the rings exactly when it drops out of the carry, so the rings never overlap the carried prose. Three projections of the same logs: the session route serves the raw log, -thinking included -- the audit surface; **the table** +thinking included -- the audit surface (the table's raw tab in the +SPA); **the table** (`/api/runs//table`) is the open session curated for the GM -- no thinking, only the picked variant, carried turns flagged for the dimming, plus the variance metric (picks, offered, max -- straight @@ -527,6 +539,8 @@ reminder.md the per-turn reminder: the turn-composition protocol, HANDOFF.md working state -- where did we leave off, next steps, gotchas ROADMAP.md SOTA review and steal list, worked point by point QUESTIONS.md the decision queue -- open questions, pending calls +DECISIONS.md the resolved record -- every answered question, kept + verbatim with its day's words; the citation numbers DICTIONARY.md the terms of art -- the ruled names, one source of truth; a rename rules here first, then sweeps AGENTS.md the agent's own working notes -- style lessons, gotchas, @@ -552,7 +566,7 @@ tool/ GM writes; --force for migrations; --json for machine output on packages/runs/report) server/ the substrate: a zero-dependency node:http service - main.mjs entry + REST spine (node server/main.mjs [--mock]); + main.mjs entry + REST spine (node server/main.mjs [--mock] [--debug]); bearer-token auth on every route (session/claim are public), ownership gating, per-run activity locks (turn, ask, start, the housekeeping job, fork); diff --git a/ROADMAP.md b/ROADMAP.md index 0960704..dd86df9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -171,7 +171,7 @@ example, gitignored real file, env-var option). per-user seam. - **Boutique is dormant** -- a stub that never reached its design step; untouched until its drafting session. -- **Stack: zero-dependency runtime** (QUESTIONS #4, amended +- **Stack: zero-dependency runtime** (DECISIONS #4, amended 2026-11-15). `node:http` with a hand-rolled router, no-build vanilla ES-module SPA; clone-and-run with node alone. Dev tooling is exempt: `typescript` + `@types/node` type-check the JSDoc @@ -182,7 +182,7 @@ 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 QUESTIONS #22-31). The LLM key stays on the backend; invited +(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. @@ -204,15 +204,17 @@ without running anything locally. - **Superuser powers:** mint/revoke invites, list/revoke users. Nothing else -- no touching another user's runs or packages, no user management beyond revocation. -- **The boundary is the model boundary.** gm.md is secret from the - player-model only; humans read freely. Saving a draft as a package - publishes its gm.md to everyone (saving is the act of publishing). - Spectators read everything in a run, notepad included, and mutate - nothing. `housekeeper.md` stays never-exposed (it prompts an - internal agent). -- **Runs:** attributed to the starting user; every GM action is - owner-only (including anything that spends a model call); every run - is readable by any user. Any user can fork any run, including their +- **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 @@ -424,13 +426,13 @@ scoped only -- after a housekeeping run the story is consolidated and corrections become proper retcons (the boundary falls out of the memory model: pre-housekeeping events live in context only). Trivial typos are tolerated as-is; the publishing pass catches them. Forks rejected as -unnecessary. Remaining details in QUESTIONS #15; implementation with -the substrate. +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 (QUESTIONS #17): +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 diff --git a/server/main.mjs b/server/main.mjs index 93498af..0883fdb 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -2,12 +2,18 @@ // // Synchronous JSON over HTTP; the SPA and curl are both just clients. // Multiuser: bearer-token identity (users.mjs), ownership gating on -// every mutation and model call, fork for everyone else. Boot-rebuild: +// every mutation, model call, and run read (the story is the one +// public surface), fork for everyone. Boot-rebuild: // every run whose latest session was not housekept gets its open // session back from the jsonl -- the log is the truth, the context is a // view. // -// usage: node server/main.mjs [--mock] +// Debug mode (--debug): every request is one fixed superuser that +// bypasses the user database entirely -- no invite dance, no tokens. +// Loopback-bound whatever the config says. Testing only, never a real +// deployment. +// +// usage: node server/main.mjs [--mock] [--debug] /** @typedef {import('./shapes.mjs').Ctx} Ctx */ /** @typedef {import('./users.mjs').UserRow} UserRow */ /** A request as a handler sees it: path params, the parsed JSON body @@ -31,6 +37,7 @@ import { forkRun } from './fork.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const MOCK = process.argv.includes('--mock'); +const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser const CONFIG_PATH = path.join(ROOT, 'server.json'); if (!fs.existsSync(CONFIG_PATH)) { @@ -63,7 +70,10 @@ ctx.enqueue = (runId, fn) => { // --- bootstrap: the fresh-deployment superuser invite --------------------------- -const boot = users.bootstrap(); +if (DEBUG) { + console.warn('debug mode: every request is the superuser -- no invites, no tokens; testing only, never a real deployment'); +} +const boot = DEBUG ? null : users.bootstrap(); // debug skips the invite dance entirely if (boot?.code) { console.log(`fresh deployment -- the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`); console.log(` ${boot.code}`); @@ -182,6 +192,18 @@ function serveStatic(pathname, res) { // signed-in user: the runs and packages of this deployment are shared // among invitees, not with the world. +// debug mode: the fixed identity. authenticate() returns it for every +// request -- no token, no lookup; users.mjs is bypassed entirely, and +// these wrappers make the id resolve as an owner through the same +// ownership code (a user the db never heard of). +const DEBUG_ID = 'debug'; +/** @type {UserRow} */ +const DEBUG_USER = { id: DEBUG_ID, token_hash: '', name: 'Debug', superuser: 1, created: '' }; +/** @param {?string|undefined} uid @returns {boolean} */ +const userExists = (uid) => (DEBUG && uid === DEBUG_ID) || users.exists(uid ?? null); +/** @param {?string|undefined} uid @returns {?string} */ +const userName = (uid) => (DEBUG && uid === DEBUG_ID ? 'Debug' : users.userName(uid ?? null)); + route('GET', '/api/session', async ({ user }) => ({ // the public shape only -- the stored row (token hash) never leaves user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null, @@ -206,7 +228,7 @@ route('GET', '/api/invites', async ({ user }) => { id: i.id, kind: i.kind, created_at: i.created_at, - state: i.claimed_by == null ? 'unclaimed' : `claimed by ${users.userName(i.claimed_by) ?? i.claimed_by}`, + state: i.claimed_by == null ? 'unclaimed' : `claimed by ${userName(i.claimed_by) ?? i.claimed_by}`, })); return { invites: list }; }); @@ -260,11 +282,13 @@ function requireUser(user) { // of who owned a run, and a dead owner id (revocation) resolves to // absent. The API never exposes a dangling id. /** @param {?string|undefined} owner @returns {?string} */ -const resolveOwner = (owner) => (owner != null && users.exists(owner) ? owner : null); +const resolveOwner = (owner) => (owner != null && userExists(owner) ? owner : null); -// ownership: every GM action -- every mutation, every model call -- is -// the owner's alone. Ownerless runs (pre-user or revoked owner) are -// one uniform state: readable by all, forkable, never re-claimed. +// ownership: every GM action -- every mutation, every model call -- +// and the whole working surface (table, raw session, carryover, +// files, status, notepad) is the owner's alone; the story is the one +// public read. Ownerless runs (pre-user or revoked owner) are one +// uniform state: story-readable, forkable, never re-claimed. /** * @param {?UserRow} user @param {string} runId * @returns {asserts user is UserRow} @@ -277,7 +301,7 @@ function requireOwner(user, runId) { throw new HttpError(403, `run '${runId}' is ownerless -- fork it to make it yours`); } if (meta.owner !== user.id) { - throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`); + throw new HttpError(403, `run '${runId}' is ${userName(meta.owner) ?? 'another user'}'s -- fork it to continue as yours`); } } @@ -296,7 +320,7 @@ route('GET', '/api/packages', async () => { for (const p of pkgs) { if (p.origin === 'user') { p.owner = resolveOwner(p.owner); - p.ownerName = p.owner == null ? null : users.userName(p.owner); + p.ownerName = p.owner == null ? null : userName(p.owner); } } return pkgs; @@ -340,7 +364,7 @@ route('GET', '/api/runs', async () => { r.session = s?.n ?? null; r.pendingAsk = s?.pendingAsk?.question ?? null; r.owner = resolveOwner(r.owner); - r.ownerName = r.owner == null ? null : users.userName(r.owner); + r.ownerName = r.owner == null ? null : userName(r.owner); } return runs; }); @@ -370,9 +394,9 @@ route('GET', '/api/names', async () => { return { name: pool[Math.floor(Math.random() * pool.length)] }; }); -route('GET', '/api/runs/:id', async ({ params }) => { +route('GET', '/api/runs/:id', async ({ params, user }) => { const id = params.id; - bundle.requireRun(id); + requireOwner(user, id); // the table's face: panes, meter, phase -- the owner's const st = clerkJson(id, '--json', 'report'); const s = ctx.sessions.get(id); const meta = bundle.runMeta(id); @@ -387,7 +411,7 @@ route('GET', '/api/runs/:id', async ({ params }) => { created: meta?.created ?? null, forked: meta?.forked ?? null, owner, - ownerName: owner == null ? null : users.userName(owner), + ownerName: owner == null ? null : userName(owner), models: meta?.models ?? {}, modelDefaults: ctx.cfg.models ?? {}, }, @@ -453,8 +477,8 @@ function fileSurface(runId) { return { n, phase, files: spec }; } -route('GET', '/api/runs/:id/files', async ({ params }) => { - bundle.requireRun(params.id); +route('GET', '/api/runs/:id/files', async ({ params, user }) => { + requireOwner(user, params.id); // the craft is working material const surf = fileSurface(params.id); /** @type {Record} */ const files = {}; @@ -539,10 +563,13 @@ route('POST', '/api/runs/:id/model', async ({ params, body, user }) => { return { ok: true, models: meta.models ?? {}, defaults: ctx.cfg.models ?? {} }; }); -// 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 }) => { +// the GM's notepad: the run's gm.md -- the owner's alone (#28's +// human-side open read overturned 2026-11-15), never in any bundle, +// never sent to any model (no assembly path reads it -- the model +// boundary stands). Seeded from the package at creation, the GM's to +// keep. +route('GET', '/api/runs/:id/notes', async ({ params, user }) => { + requireOwner(user, params.id); const dir = bundle.requireRun(params.id); const file = path.join(dir, 'gm.md'); return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' }; @@ -550,7 +577,7 @@ route('GET', '/api/runs/:id/notes', async ({ params }) => { route('PUT', '/api/runs/:id/notes', async ({ params, body, user }) => { const dir = bundle.requireRun(params.id); - requireOwner(user, params.id); // spectators read the pad, the owner writes it + requireOwner(user, params.id); // the pad is owner-only in both directions 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 }; @@ -591,7 +618,8 @@ route('POST', '/api/runs/:id/sessions', async ({ params, body, user }) => { }); }); -route('GET', '/api/runs/:id/session', async ({ params }) => { +route('GET', '/api/runs/:id/session', async ({ params, user }) => { + requireOwner(user, params.id); // the raw audit surface const s = ctx.sessions.get(params.id); if (!s) throw new HttpError(404, `no live session for '${params.id}'`); return { @@ -607,8 +635,8 @@ route('GET', '/api/runs/:id/session', async ({ params }) => { // read-only -- the review window's preview of the next contwin. Same // projection as the table (the picked variant only, thinking stays in // the raw log), plus the ending that decides the opening flow. -route('GET', '/api/runs/:id/carryover', async ({ params }) => { - bundle.requireRun(params.id); +route('GET', '/api/runs/:id/carryover', async ({ params, user }) => { + requireOwner(user, params.id); // the table's dormant stand-in const live = ctx.sessions.get(params.id); if (live) throw new HttpError(409, `session ${live.n} is live -- the table is the surface`); const latest = session.latestSession(params.id); @@ -652,9 +680,11 @@ route('GET', '/api/runs/:id/carryover', async ({ params }) => { // what the GM needs at the table. Same envelope as /session, // different policy over the same log: thinking never crosses the // wire, variant turns carry only the picked variant. The raw -// /session stays whole as the audit surface; during dormancy the +// /session stays whole as the audit surface (the table's raw tab +// in the SPA); during dormancy the // /carryover endpoint is the table's stand-in. -route('GET', '/api/runs/:id/table', async ({ params }) => { +route('GET', '/api/runs/:id/table', async ({ params, user }) => { + requireOwner(user, params.id); // the table is the owner's working surface const s = ctx.sessions.get(params.id); if (!s) throw new HttpError(404, `no live session for '${params.id}'`); const eff = effectiveContents(s.lines); @@ -692,7 +722,9 @@ route('GET', '/api/runs/:id/table', async ({ params }) => { // omission. A dormant session's carryover is the story's live edge: // its raw lines project like any log's, at the chronological end -- // GM edits during dormancy show, because the carryover is the current -// truth of where the story stands. +// truth of where the story stands. The public reading surface: any +// signed-in user; the table and everything else in the run is the +// owner's. route('GET', '/api/runs/:id/story', async ({ params }) => { bundle.requireRun(params.id); const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g; @@ -741,7 +773,12 @@ route('GET', '/api/runs/:id/story', async ({ params }) => { } if (turns.length) sessions.push({ session: n, turns }); } - return { run: params.id, sessions }; + // the public face rides along: what the run is called and whose it + // is -- the story view stands alone (the detail it used to lean on + // is owner-only now) + const meta = bundle.runMeta(params.id); + const owner = resolveOwner(meta?.owner); + return { run: params.id, display: bundle.runDisplay(params.id), owner, ownerName: owner == null ? null : userName(owner), sessions }; }); route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => { @@ -768,8 +805,8 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => { return ctx.enqueue(params.id, async () => forkRun(ctx, params.id, u)); }); -route('GET', '/api/runs/:id/status', async ({ params }) => { - bundle.requireRun(params.id); +route('GET', '/api/runs/:id/status', async ({ params, user }) => { + requireOwner(user, params.id); // status and agenda are machinery return { status: clerkJson(params.id, 'status'), agenda: clerkJson(params.id, 'agenda') }; }); @@ -858,9 +895,15 @@ route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user } return { ok: true, parsed: true, session: n, file: `manifests/${n}.replay.json`, manifest: mf }; }); -route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jobState(ctx, params.id)); +route('GET', '/api/runs/:id/housekeeping', async ({ params, user }) => { + requireOwner(user, params.id); // the job state is machinery + return housekeeping.jobState(ctx, params.id); +}); -route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id)); +route('GET', '/api/runs/:id/housekeeping/log', async ({ params, user }) => { + requireOwner(user, params.id); // the apply log is machinery + return housekeeping.latestLog(params.id); +}); route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => { // the recovery path: apply a (hand-edited) manifest directly -- the @@ -892,6 +935,7 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) // bearer-token identity (users.mjs); null when absent or unknown /** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */ function authenticate(req) { + if (DEBUG) return DEBUG_USER; // debug: everyone is the superuser const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? ''); return m ? users.getUserByToken(m[1].trim()) : null; } @@ -928,7 +972,10 @@ const server = http.createServer(async (req, res) => { } }); -const [host, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':'); +// debug never leaves this machine: whatever the config binds, the +// debug host is loopback (the port stays configurable) +const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':'); +const host = DEBUG ? '127.0.0.1' : cfgHost; server.listen(Number(port ?? 7350), host, () => { - console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt`); + console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : cfg.models?.player} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`); }); diff --git a/test/check-repo.mjs b/test/check-repo.mjs index b936f4c..fb0ad0a 100644 --- a/test/check-repo.mjs +++ b/test/check-repo.mjs @@ -37,9 +37,16 @@ // prompts never enter the bundle). // 9. Seeds carry no date keys (GM, 2026-11-14): no model-facing // surface renders a date; story time lives in prose. +// 10. No laptop-visible facts (GM, 2026-11-15): this machine's +// username and home paths appear nowhere -- tracked tree, +// historical blobs, commit messages -- and every commit is +// always from Mute (author and committer, name and email, every +// ref, git config included). The facts are derived at runtime; +// writing them into the checker would leak them itself. import { execFileSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; +import { homedir, userInfo } from 'node:os'; let failures = 0; const fail = (msg) => { console.log(`FAIL ${msg}`); failures++; }; @@ -53,6 +60,20 @@ const livingProse = (f) => // their comments); it is exempt from the rules it defines const isSelf = (f) => f === 'test/check-repo.mjs'; +// rule 10's patterns, derived at runtime so this file never contains +// the facts it bans (a literal here would be the leak itself). The +// username is matched as a plain substring -- recall over precision; +// the home path rides along in both separator spellings. +const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const piiSrc = [ + esc(userInfo().username), + homedir().split(/[\\/]+/).map(esc).join('[\\\\/]+'), +].join('|'); +const piiRe = new RegExp(piiSrc, 'i'); +// the pseudonymous identity every commit carries, no exceptions +const ID_NAME = 'Mute'; +const ID_EMAIL = 'codename.mute@proton.me'; + for (const f of files) { const buf = readFileSync(f); if (buf.includes(0)) continue; // binary -- no text rules to enforce @@ -157,6 +178,58 @@ for (const f of files) { } }); } + + // rule 10a: laptop-visible facts never enter the tracked tree + text.split('\n').forEach((line, i) => { + if (piiRe.test(line)) { + fail(`${f}:${i + 1} laptop-visible fact (this machine's username or home path)`); + } + }); +} + +// rule 10b: the same facts never entered history -- every blob on +// every ref; one report per path+content, not one per commit +{ + const revs = execFileSync('git', ['rev-list', '--all'], { encoding: 'utf8' }).split('\n').filter(Boolean); + let out = ''; + try { + out = execFileSync('git', ['grep', '-I', '-i', '-E', piiSrc, ...revs], { encoding: 'utf8' }); + } catch (e) { + out = `${e.stdout || ''}`; // grep exits 1 on zero matches + } + const seen = new Set(); + for (const line of out.split('\n').filter(Boolean)) { + const rest = line.slice(line.indexOf(':') + 1); // "rev:path:content" -> "path:content" + if (!seen.has(rest)) { + seen.add(rest); + fail(`history ${rest.slice(0, 80)}: laptop-visible fact in a historical blob`); + } + } +} + +// rule 10c: commit messages stay clean too +execFileSync('git', ['log', '--all', '--format=%s %b'], { encoding: 'utf8' }) + .split('\n') + .forEach((line) => { + if (piiRe.test(line)) fail(`commit message: laptop-visible fact (${line.trim().slice(0, 60)})`); + }); + +// rule 10d: every commit is from Mute -- author and committer, name +// and email, on every ref +for (const row of execFileSync('git', ['log', '--all', '--format=%h%x00%an%x00%ae%x00%cn%x00%ce'], { encoding: 'utf8' }).split('\n').filter(Boolean)) { + const [h, an, ae, cn, ce] = row.split('\x00'); + if (an !== ID_NAME || ae !== ID_EMAIL || cn !== ID_NAME || ce !== ID_EMAIL) { + fail(`commit ${h}: identity is "${an} <${ae}>" -- all commits are always from ${ID_NAME}`); + } +} + +// rule 10e: and the configured identity keeps it that way +for (const [key, want] of [['user.name', ID_NAME], ['user.email', ID_EMAIL]]) { + let val = '(unset)'; + try { + val = execFileSync('git', ['config', key], { encoding: 'utf8' }).trim(); + } catch { /* unset -- the fail below reports it */ } + if (val !== want) fail(`git config ${key} is "${val}" -- all commits are always from ${ID_NAME}`); } console.log(failures ? `\n${failures} VIOLATIONS` : 'ALL CLEAN'); diff --git a/test/smoke.mjs b/test/smoke.mjs index d52feec..6535dc2 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -2,7 +2,7 @@ // server. Covers: bootstrap, claim, spent-invite rejection, second // user, the session lifecycle (create dormant -> start -> live -> // stop -> dormant -> re-run -> start -> the auto-send rule -> the -// start lint), spectator 403s, fork, save-package, create-from-user- +// start lint), non-owner 403s, fork, save-package, create-from-user- // package, revocation, ownerless state, the agenda deltas + self- // heal, the reminder ride, per-run models, variant literature (the // random pick, the /table projection, the variance metric), the @@ -165,15 +165,32 @@ ok('agenda override owner-only', r.status === 403); r = await call(`/runs/${runId}/status`, { token: op }); ok('status endpoint carries both', Array.isArray(r.data.status) && Array.isArray(r.data.agenda), JSON.stringify(r.data).slice(0, 120)); -// 11. ash spectates: reads ok, mutates 403 +// 11. ash in another's run: the story is the reading surface, all +// else is the owner's r = await call(`/runs/${runId}`, { token: ash }); -ok('ash reads run', r.status === 200 && r.data.run.ownerName === 'Op', r.data.error ?? ''); +ok('ash detail 403', r.status === 403); +r = await call(`/runs/${runId}/table`, { token: ash }); +ok('ash table 403', r.status === 403); +r = await call(`/runs/${runId}/session`, { token: ash }); +ok('ash raw session 403', r.status === 403); +r = await call(`/runs/${runId}/carryover`, { token: ash }); +ok('ash carryover 403', r.status === 403); +r = await call(`/runs/${runId}/files`, { token: ash }); +ok('ash files 403', r.status === 403); +r = await call(`/runs/${runId}/status`, { token: ash }); +ok('ash status 403', r.status === 403); +r = await call(`/runs/${runId}/notes`, { token: ash }); +ok('ash notes 403 (#28 overturned)', r.status === 403); +r = await call(`/runs/${runId}/housekeeping`, { token: ash }); +ok('ash housekeeping state 403', r.status === 403); +r = await call(`/runs/${runId}/housekeeping/log`, { token: ash }); +ok('ash housekeeping log 403', r.status === 403); r = await call(`/runs/${runId}/turn`, { method: 'POST', token: ash, body: { line: 'hi' } }); ok('ash turn 403', r.status === 403); r = await call(`/runs/${runId}/notes`, { method: 'PUT', token: ash, body: { content: 'mine' } }); ok('ash notes write 403', r.status === 403); -r = await call(`/runs/${runId}/notes`, { token: ash }); -ok('ash reads notes', r.status === 200); // spectators read the pad +r = await call(`/runs/${runId}/story`, { token: ash }); +ok('ash reads the story', r.status === 200 && !!r.data.display && Array.isArray(r.data.sessions), r.data.error ?? ''); r = await call(`/runs/${runId}/housekeeping/replay`, { method: 'POST', token: ash, body: {} }); ok('ash replay 403 (spends a call)', r.status === 403); @@ -228,9 +245,10 @@ r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} } ok('revoke ash', r.status === 200, r.data.error ?? ''); r = await call('/runs', { token: ash }); ok('ash token dead', r.status === 401); -r = await call(`/runs/${forkId}`, { token: op }); -ok('fork now ownerless, session closed', r.status === 200 && r.data.run.owner === null && r.data.run.ownerName === null && r.data.open === false, - JSON.stringify(r.data.run)); +r = await call('/runs', { token: op }); +const goneFork = Array.isArray(r.data) ? r.data.find((x) => x.id === forkId) : null; +ok('fork now ownerless, session closed', !!goneFork && goneFork.owner === null && goneFork.ownerName === null && goneFork.open === false, + JSON.stringify(goneFork)); // the detail it used to ride is owner-only now -- the list carries the facts r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: op, body: { line: 'x' } }); ok('ownerless turn 403 even for op', r.status === 403 && /ownerless/.test(r.data.error)); r = await call('/packages', { token: op }); diff --git a/web/app.mjs b/web/app.mjs index a1f8b75..4f3dbc7 100644 --- a/web/app.mjs +++ b/web/app.mjs @@ -8,7 +8,7 @@ // extensionless path. import { $ } from './dom.mjs'; -import { api, authToken, clearToken } from './client.mjs'; +import { api, clearToken } from './client.mjs'; import { state } from './state.mjs'; import { navigate, registerViews, render } from './router.mjs'; import * as claim from './view-claim.mjs'; @@ -29,18 +29,17 @@ registerViews({ story: { el: 'view-story', enter: story.enter }, }); -// boot: restore the session from the stored token; a rejected or -// absent token leaves me signed out, and every path leads to the -// claim view +// boot: ask the server who we are -- the stored token rides the +// request when one exists; a null user (or a rejected token) leaves +// me signed out, and every path leads to the claim view. Tokenless +// browsers ask too: a debug-mode server answers with its fixed user (async () => { - if (authToken()) { - try { - const s = await api('/session'); - state.me = s.user; - if (!state.me) clearToken(); - } catch { - state.me = null; - } + try { + const s = await api('/session'); + state.me = s.user; + if (!state.me) clearToken(); + } catch { + state.me = null; } render(); })(); diff --git a/web/index.html b/web/index.html index e49f551..efe6cab 100644 --- a/web/index.html +++ b/web/index.html @@ -100,12 +100,17 @@