diff --git a/AGENTS.md b/AGENTS.md index 4b587bc..8361bdf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,13 @@ memory the agent owes itself across sessions. 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. + nothing. 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): second player paper, ``/ + `` deltas, cap-5 recency queue; Irene's events journal + migrated (CHECK widened) — her db is agenda-ready. - Substrate design round complete (2026-11-13); rulings live in ROADMAP ("The harness") and HANDOFF. Bridge retired before ever going live; REST + SPA is the MVP; runs are per-deployment instances copied from diff --git a/HANDOFF.md b/HANDOFF.md index 39dfae7..3bca422 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -139,10 +139,13 @@ file is the "where did we leave off" map. is unseen so far. Iterate: read housekeeper.md, tweak, replay — the dry-run button re-runs the wrap over the session log with nothing applied. -3. **Status discipline (GM wants the section tightened).** The paper - has taken up thread-tracking ("planning to talk to Pinky" is a - thread, not an acute state); the admission-gate copy in - invariants.md's paper section wants tightening. +3. ~~**Status discipline**~~ — RESOLVED BY REDIRECT (2026-11-14, + QUESTIONS #32/#33): the paper's thread-tracking drift got its own + channel. The agenda (``/``/``, cap-5 recency + queue, invariants.md GM-written) is built end to end; the gate + fight is over by design. The test is the next live window: watch + cross-channel drift and drop off-by-ones alongside observables + #12/#14. 4. **Keep playing.** Observables #12 (does the paper stay small and match the transcripts) and #14 (one thing per turn vs lengthening turns — completions grew 103 to 668 chars across window one) are @@ -185,6 +188,31 @@ wait for text that only exists POST-render (a card name, the window-info line), never the static skeleton; and CSS text-transform still uppercases wait targets. +Model selection wired (GM, same day): run.json now carries +`models: {player, housekeeper}` per-run overrides (replacing the old +singular `model` key — no run ever carried it), owner-settable via +POST /api/runs/:id/model and the SPA (setup box for drafts, play-aside +pane for started runs), falling back to the server.json defaults; the +housekeeper call resolves per wrap. Smoke 42/42, UI verified (setup +select + save, carried override visible on a fork's play view, +spectator pane hidden). #16's open call is now only the DEFAULT. + +The agenda built (GM-designed, same day, QUESTIONS #32): the player's +second paper — intentions, not states. `` rides every GM turn +(numbered from the top, as cited), ``/`` deltas apply +received -> drop -> add, cap 5 with bottom-eviction, GM override + SPA +pane, housekeeping reads the deltas as evidence. Conflict delivery +re-ruled mid-build: a conflict goes back as its own message (clean of +prose), the model self-heals in the same exchange, capped at 3 heals a +turn — the `conflict` pending-state is gone entirely. Same-verb blocks +combine into one apply, never a sequence. The events journal CHECK was +widened (one-time lazy migration — ran clean on Irene's db, all rows +preserved). Invariants gained the substrate-tag syntax rule (any +`` line is OOC; unknown tags reported to GM) — the SPA register +parser follows it. Session-route fix rode along: /api/session returns +the public user shape only (it was leaking the token hash). Smoke +56/56, UI verified end to end. + ## Working agreements with the GM - **"I draft, you cut"** for all creative content. diff --git a/QUESTIONS.md b/QUESTIONS.md index 67025a9..e7222d8 100644 --- a/QUESTIONS.md +++ b/QUESTIONS.md @@ -158,6 +158,33 @@ 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. + ### 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 @@ -240,10 +267,14 @@ content (phase 0); (d) surgery blocked while an ask_gm is pending. The housekeeping job runs server-side on a fresh model invocation. Mechanism settled (2026-11-13): `server.json` names one endpoint plus default models (player, housekeeper), `GET /api/models` lists what the -upstream carries, and a run may override its model. Which model the -housekeeper 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.) +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 +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 diff --git a/README.md b/README.md index cd6c245..157eb41 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,11 @@ forking makes that cheap — stories outlive identities by design. a user can save their run's craft as a user package under `state/packages/` — published to everyone, gm.md included (saving is the act of publishing), the pc never riding. +- **Models are per-run over the deployment defaults.** `server.json` + names the defaults (player, housekeeper); a run's owner overrides + either role from the upstream listing — in setup for drafts, in the + play aside for started runs. Each call resolves fresh, so a + mid-window switch simply takes the next turn. - Every logged LLM call records the acting user. Quotas and limits are an extension point, not built. - All dates and times are UTC everywhere. No time zones, ever. @@ -199,8 +204,12 @@ window, and sends turn-0 as the first GM turn in one action. citing one is the precise way to reference a memory. The paper travels in-band: the current `` block rides every GM turn, and the player mutates it with ``/`` tags in its own - turns (the clerk applies the deltas — exact match — and misses ride - back as a `` block on the next GM turn). Records work + turns (the clerk applies the deltas — same-verb blocks combine into + one apply — and misses go back as a `` turn of their own: + clean of prose, read it and adjust; the model heals in the same + exchange). The agenda rides alongside: `` on every GM turn, + ``/`` deltas in the player's turns — drops cite the + indexes it was shown. Records work travels the tools (`records_search`/`file`/`amend`/`discard`) when the run provides them; the CLI equivalents remain for the GM (`--gm` marks GM-authorized writes). The full play protocol — format, @@ -231,22 +240,26 @@ State lives in **SQLite** (`runs//db/memory.db`); `canon/ring-*.md` are generated views. Markdown survives as rendering, dies as storage — the models see prose, the machine sees rows. -Memory is **six tiers**: +Memory is **seven tiers**: | tier | what | in context | who writes it | |---|---|---|---| | **backdrop** | the world as everyone knows it — public knowledge, the general setting; never memory, never forgotten | always | GM, rarely (retcons) | | **identity** | the character sheet — concept, drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent | | **status** | her piece of paper — descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | every GM turn, as its `` block | **the player** (``/`` deltas in its turns); GM override out-of-band | +| **agenda** | her hot queue of intentions — what she's working towards right now; a fixed-cap recency buffer (new on top, overflow evicts the bottom), disposable by design | every GM turn, as its `` block | **the player** (``/`` deltas in its turns, drops by index); GM override out-of-band | | **rings A/B** | salient memory — facts, on her mind, MRU-evicted | always | housekeeper manifest | | **records** | her files — the card index, the ledger. Narrow query only, hard cap 10 (in the tool, not the prompt), never bulk-loaded | never — on demand | **the player** (`file`/`amend`/`discard` at her desk); GM seeds; housekeeper only `archive`s | | **cold** | forgotten or vetoed | never — not even queryable | GM only (`revive`) | The boundary that keeps the tiers honest: **stances are feelings (status, the player's); facts are facts (rings, the housekeeper's).** The -housekeeper never writes feelings; the player never rewrites facts. And -if she doesn't file it, it's not in her files — records reflect what the -character actually kept, nothing more. +housekeeper never writes feelings; the player never rewrites facts. The +paper and the agenda split the player's own two surfaces along the same +seam: **how she is (status) vs what she means to do (agenda)** — states +fade with the situation, intentions persist until dropped or evicted. +And if she doesn't file it, it's not in her files — records reflect what +the character actually kept, nothing more. Records access is **diegetic and per-run**: `packages//settings.json` gates it. The boutique's keeper has her card index on the shop PC @@ -453,13 +466,14 @@ config.json the default package names-female.txt the name dictionary — one name per line; the new-run form rolls an unused one for the main character tool/ - memory.mjs the clerk: packages, runs, create, init, seed, render, - apply, insert, delete, revive, file, amend, discard, - search, unarchive, paper, paper-apply, paper-set, - paper-ingest, pick, dump, restore, status - (--run ; --gm for GM writes; --force for - migrations; --json for machine output on - packages/runs/status) + memory.mjs the clerk: packages, runs, create, save-package, init, + seed, render, apply, insert, delete, revive, file, + amend, discard, search, unarchive, paper, paper-apply, + paper-set, paper-ingest, agenda, agenda-apply, + agenda-set, pick, dump, restore, status + (--run ; --owner stamps a run's owner; --gm for + GM writes; --force for migrations; --json for machine + output on packages/runs/status) server/ the substrate: a zero-dependency node:http service main.mjs entry + REST spine (node server/main.mjs [--mock]); bearer-token auth on every route (session/claim are @@ -501,7 +515,7 @@ web/ the SPA — no build, vanilla ES modules, path-routed server.example.json copy to server.json (gitignored) — bind, endpoint + key env, models, contextWindow, params passthrough db/ - schema.sql entries, records, paper, events journal (shared) + schema.sql entries, records, paper, agenda, events journal (shared) state/ per-deployment people + shared packages (gitignored): deployment.db (users, invites), bootstrap-invite.txt, packages/ (user-saved, published to everyone) @@ -509,7 +523,8 @@ runs/ per-deployment run state (gitignored) — one anonymous id per run (carries no facts): the copied package, the craft prompt (handbook.md), run.json (lineage, owner, `forked` stamp on a fork, - model override), db/, canon/ (rendered views), dumps/, + models — per-run player/housekeeper overrides), + db/, canon/ (rendered views), dumps/, log/, manifests/, sessions/ packages/ system presets — authored content only, never state la-caramba/ backdrop.md, turn-0.md (new-game opener), character.md, diff --git a/ROADMAP.md b/ROADMAP.md index 94eedcb..6bdd18b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -112,10 +112,13 @@ example, gitignored real file, env-var option). - **Per-run model selection.** `server.json` names one endpoint (baseUrl, key) plus default models (player, housekeeper). `GET /api/models` asks the upstream what it carries; the user selects - from the list. A run may carry a model override (default: player) — - the comparison rig: same package, different models, identical - prompts. The housekeeper's model choice stays open (#16); the - mechanism is settled. + from the list. A run may carry per-run overrides for both roles + (`run.json` `models: {player, housekeeper}`, wired in the SPA + 2026-11-14 — setup for drafts, the play aside for started runs; + each call resolves fresh, so a mid-window switch takes the next + turn) — the comparison rig: same package, different models, + identical prompts. Which model the housekeeper DEFAULT points at + stays open (#16); the mechanism is settled. - **The player prompt is battery included, split along ownership seams (ruled 2026-11-13; cut executed by the GM 2026-11-14).** Three tiers, three files: diff --git a/db/schema.sql b/db/schema.sql index c1c6a62..140da42 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -39,6 +39,19 @@ CREATE TABLE IF NOT EXISTS paper ( added TEXT NOT NULL ); +-- her agenda: the hot queue of what drives her — intentions, not +-- states (those live on the paper). Id order IS queue order: +-- newest-added at the top, the bottom evicted on overflow — a recency +-- ring buffer for free. The player mutates it with / +-- deltas (comma-separated adds, index-based drops); the GM overrides +-- with agenda-set. Items never contain commas: the add transport is +-- comma-separated, same as the paper's descriptions. +CREATE TABLE IF NOT EXISTS agenda ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + descr TEXT NOT NULL UNIQUE, + added TEXT NOT NULL +); + -- append-only audit journal; nothing here is ever updated or deleted. -- target is 'e' for entries, 'r' for records, 'p' for paper -- rows, 'paper' for whole-paper replaces. @@ -48,7 +61,7 @@ CREATE TABLE IF NOT EXISTS paper ( CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, window TEXT NOT NULL, - op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set')), + op TEXT NOT NULL CHECK (op IN ('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')), target TEXT NOT NULL, reason TEXT NOT NULL DEFAULT '', prior TEXT NOT NULL DEFAULT '' diff --git a/invariants.md b/invariants.md index 3fe964f..e8ee76e 100644 --- a/invariants.md +++ b/invariants.md @@ -1,5 +1,6 @@ # Syntax +- **Substrate** lines start with an opening ``. These are always OOC. Report unknown tags to GM. - **OOC** lines `(start with a parenthesis`, the closing paren is optional. Match the GM's style. - **Speech** is plain text, first person, and understood to be spoken aloud — anyone present hears it. - **Everything else** — actions, descriptions, thoughts and interior life — is *italic*, third person. @@ -13,6 +14,8 @@ Anyone home? ( Just play along, I got this. ) ``` +Humans make mistakes, but syntax is important for the play protocol. If something doesn't make sense, ask GM. + # Tools The tool manifest is included with every turn. Each tool's description is prefixed with the nature of its output: `[IC]` or `[OOC]`. @@ -59,7 +62,7 @@ What belongs on the paper passes a three-part gate. A token must be: 3. something that **may affect the turn**. Bored, shivering, proud, ashamed, naked, hungry, cuffed, on edge, craves a smoke, afterglow, full bladder, barefoot, in pain — all pass. -Warm when the weather is warm, liking puppies, being on the pill — none do: normal, ambient, or chronic. If the prose already carries it +Warm (when the weather is warm), liking puppies, being on the pill — none do: normal, ambient, or chronic. If the prose already carries it clearly, leave it off the paper. There is no exhaustive inventory of possible tokens, all listed are examples. What stops being true leaves the paper the turn it stops. If a non-normal state becomes the new normal, stop listing it @@ -68,7 +71,32 @@ What stops being true leaves the paper the turn it stops. If a non-normal state What can't be expressed as a status token doesn't belong on the paper. "Trusts Marta less" is not a status, it gets established in the prose or derived from memory. For contrast, "suspicious" is a status token when your character does feel this way. -## Errors feedback +# Player's agenda -You may receive a `` block attached to the GM's turn if an error happened while satisfying your request. Read the error -and adjust. If unsure, ask GM. +A very similar `` block has the same lifecycle, but different purpose. Your verbs to edit it are `` and ``. Instead of +the current situation, it should hold goals that your character is working towards right now. This isn't a storage space for detailed plans, +it's the hot view of what drives the character. The goals may be long term, but they should represent what's currently on the mind. + +The list is a fixed size ordered ring buffer that's intentionally tiny. If you add a new item on the full agenda, the last one gets evicted. +New items arrive at the top, imitating recency bias. The items form a queue ("First buy groceries, then make dinner."). You can reorder items +by dropping them and adding back. + +When using the `` verb, reference the items by their 0-based index: `0,2,3`. When using the `` verb, keep the items +terse and to the primary point: `investigate the crash site, report to HQ` (these are two separate items). An item should hold +one thing, the queue provides composition. + +Order of execution: the `` block you've received -> `` -> `` -> the `` block you will receive on the next turn. + +Some related intel: + +- Humans work broadly this way too, they find themselves holding a couple points in their head front and center. They forget easily. One + distraction and I don't know why I came to the kitchen anymore. I have to reconstruct the context ground up, and sometimes it's lost. +- Eagerly drop completed items from the list when your character considers a thing done, or moves on to a superseding plan. +- Treat the list as disposable, nothing from it is important. It's your L1 cache. +- Embrace eviction, it's a useful tool to make the story better. A person moving from one thing to another is natural. +- When deciding a turn, consider broader context. Something may come up that is more important than anything on the list. + +# Errors feedback + +You may receive a `` block as the GM's turn if an error happened while satisfying your request. Read the error and adjust. +If unsure, ask GM. diff --git a/server/housekeeping.mjs b/server/housekeeping.mjs index e0910dd..fa56404 100644 --- a/server/housekeeping.mjs +++ b/server/housekeeping.mjs @@ -32,6 +32,10 @@ export function renderTranscript(lines) { for (const e of lines) { if (e.t === 'bundle') continue; // context, not exchange — provided as separate inputs if (e.t === 'msg') { + if (e.m.role === 'user' && e.conflictOnly) { + L.push('[conflict — answered in-band]', e.m.content.replace(/<\/?conflict>/g, '').trim(), ''); + continue; + } if (e.m.role === 'user') { L.push('[GM]', e.m.content, ''); } else if (e.m.role === 'assistant') { @@ -48,6 +52,8 @@ export function renderTranscript(lines) { if (e.t === 'note') { if (e.kind === 'paper') { L.push(`[paper] lost: ${JSON.stringify(e.applied?.lost ?? [])}, gained: ${JSON.stringify(e.applied?.gained ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, ''); + } else if (e.kind === 'agenda') { + L.push(`[agenda] added: ${JSON.stringify(e.applied?.added ?? [])}, dropped: ${JSON.stringify(e.applied?.dropped ?? [])}, evicted: ${JSON.stringify(e.applied?.evicted ?? [])}${e.conflicts?.length ? ` — conflicts: ${e.conflicts.join('; ')}` : ''}`, ''); } else if (e.kind === 'ask') { L.push(`[ask_gm pending] ${e.question}`, ''); } else if (e.kind === 'window') { @@ -139,8 +145,12 @@ async function runJob(ctx, runId, stamp, lines, user) { } async function callHousekeeper(ctx, runId, messages, user) { - const model = ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player ?? null; - if (!model) throw new Error('no housekeeper model configured (server.json models.housekeeper)'); + const meta = ctx.runMeta?.(runId) ?? {}; + const model = meta.models?.housekeeper + ?? ctx.cfg.models?.housekeeper + ?? ctx.cfg.models?.player + ?? null; + if (!model) throw new Error('no housekeeper model resolved (server.json models.housekeeper, or a per-run override)'); // attribution (#22): every LLM call names the acting user console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`); const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {}); diff --git a/server/loop.mjs b/server/loop.mjs index 3d5e2d4..76fe5d4 100644 --- a/server/loop.mjs +++ b/server/loop.mjs @@ -31,11 +31,10 @@ export async function gmTurn(ctx, runId, line, user) { const s = needSession(ctx, runId); if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)'); const paper = clerkJson(runId, 'paper'); // fresh per turn - let content = `${line.trim()}\n\n${paper.join(', ')}`; - if (s.conflict) { - content += `\n${s.conflict}`; - s.conflict = null; - } + const agenda = clerkJson(runId, 'agenda'); // fresh per turn + // the wire renders the queue as the model cites it: numbered from the top + const agendaWire = agenda.map((d, i) => `${i}. ${d}`).join('; '); + const content = `${line.trim()}\n\n${paper.join(', ')}\n${agendaWire}`; s.append({ t: 'msg', m: { role: 'user', content } }); return runLoop(ctx, runId, user); } @@ -80,6 +79,7 @@ async function runLoop(ctx, runId, user) { const s = ctx.sessions.get(runId); const tools = toolList(runId); const out = { tools: [] }; + let heals = 0; for (;;) { const view = renderView(s); let msg; @@ -114,13 +114,31 @@ async function runLoop(ctx, runId, user) { continue; // let the model see the results before ending its turn } - // final player message — paper deltas ride the turn text itself + // final player message — the paper and agenda deltas ride the turn + // text. Same-verb blocks combine into one apply (the clerk's + // collectors gather every block before executing anything), never a + // sequence of applies. const text = msg.content ?? ''; + const carry = []; if (/<(lost|gained)>/.test(text)) { const r = clerkJson(runId, 'paper-apply', text); s.append({ t: 'note', kind: 'paper', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts }); - if (r.conflicts?.length) s.conflict = r.conflicts.join('; '); + carry.push(...(r.conflicts ?? [])); } + if (/<(add|drop)>/.test(text)) { + const r = clerkJson(runId, 'agenda-apply', text); + s.append({ t: 'note', kind: 'agenda', applied: { added: r.added, dropped: r.dropped, evicted: r.evicted }, conflicts: r.conflicts }); + carry.push(...(r.conflicts ?? [])); + } + if (carry.length && heals < 3) { + // a conflict answers for itself: it goes back as its own message, + // not attached to a GM turn — clean of prose, easy to read, easy + // to heal. Capped so a confused model cannot ping-pong forever. + heals++; + s.append({ t: 'msg', m: { role: 'user', content: `${carry.join('; ')}` }, conflictOnly: true }); + continue; + } + if (carry.length) out.conflicts = carry; // healing gave up — the transcript shows it out.player = text; return out; } @@ -128,7 +146,7 @@ async function runLoop(ctx, runId, user) { function resolveModel(ctx, runId) { const meta = ctx.runMeta(runId) ?? {}; - return meta.model ?? ctx.cfg.models?.player ?? null; + return meta.models?.player ?? ctx.cfg.models?.player ?? null; } // --- the mock model ---------------------------------------------------------- @@ -154,7 +172,20 @@ function mockModel(s, view) { return call('ask_gm', { question: 'From where she stands, does the deck look clear toward the bow?' }, `mock-ask-${s.lines.length}`); } if (assistantCount === 3) { - return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\nworried\nsettled' }; + // two and two blocks on one turn: same-verb blocks + // combine into one apply, never a sequence — the smoke asserts the + // merged, order-preserving result + return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\nworried\nsettled\ncurious about the clicking\nfind fresh water\nsignal any passing ship, build a shelter' }; + } + if (assistantCount === 4) { + return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n0' }; + } + if (assistantCount === 5) { + return { role: 'assistant', content: 'Mock: *She squints at the horizon.*\n9' }; + } + if (assistantCount === 6) { + // the self-heal: this fires in answer to the conflict-only message + return { role: 'assistant', content: 'Mock: *She shakes her head — no such thing on the list.*\n0, 1' }; } return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' }; } diff --git a/server/main.mjs b/server/main.mjs index 0eb292d..4a8c55c 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -154,7 +154,8 @@ function serveStatic(pathname, res) { // among invitees, not with the world. route('GET', '/api/session', async ({ user }) => ({ - user, // null when signed out or the token is stale + // the public shape only — the stored row (token hash) never leaves + user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null, fresh: users.userCount() === 0, }), { public: true }); @@ -332,7 +333,8 @@ route('GET', '/api/runs/:id', async ({ params }) => { forked: meta?.forked ?? null, owner, ownerName: owner == null ? null : users.userName(owner), - model: meta?.model ?? null, + models: meta?.models ?? {}, + modelDefaults: ctx.cfg.models ?? {}, }, display: bundle.runDisplay(id), open: !!s, @@ -341,6 +343,7 @@ route('GET', '/api/runs/:id', async ({ params }) => { window: s?.stamp ?? null, fresh: s?.fresh ?? false, paper: st.paper, + agenda: st.agenda, records: st.records, fill: st.rings, events: st.events, @@ -417,6 +420,33 @@ route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => { return { ok: true, vars: settings.vars }; }); +// the run's models: per-run overrides of the deployment defaults +// (server.json), selected from the upstream listing (GET /api/models). +// Owner-only, changeable at any time — every call resolves fresh, so a +// mid-window switch simply takes the next turn. null clears a role +// back to its deployment default. +route('POST', '/api/runs/:id/model', async ({ params, body, user }) => { + const id = params.id; + bundle.requireRun(id); + requireOwner(user, id); + for (const k of Object.keys(body)) { + if (k !== 'player' && k !== 'housekeeper') throw new HttpError(400, `unknown model role: ${k} — player and housekeeper`); + } + const meta = bundle.runMeta(id) ?? {}; + const models = meta.models ?? {}; + for (const role of ['player', 'housekeeper']) { + if (body[role] === undefined) continue; + if (body[role] === null) { delete models[role]; continue; } + const m = String(body[role]).trim(); + if (!m) throw new HttpError(400, `${role}: a model name, or null to fall back to the deployment default`); + models[role] = m; + } + if (Object.keys(models).length) meta.models = models; + else delete meta.models; + fs.writeFileSync(path.join(bundle.runDir(id), 'run.json'), JSON.stringify(meta, null, 2) + '\n'); + 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. @@ -504,8 +534,7 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => { route('GET', '/api/runs/:id/status', async ({ params }) => { bundle.requireRun(params.id); - const s = ctx.sessions.get(params.id); - return { paper: clerkJson(params.id, 'paper'), conflict: s?.conflict ?? null }; + return { paper: clerkJson(params.id, 'paper'), agenda: clerkJson(params.id, 'agenda') }; }); // the GM's out-of-band paper override: whole-paper replace via the @@ -526,6 +555,24 @@ route('POST', '/api/runs/:id/paper', async ({ params, body, user }) => { return { ok: true, paper }; }); +// the GM's out-of-band agenda override: whole-queue replace via the +// clerk (journaled). Items land in written order, first = top; an +// empty array clears it. Commas are the add transport's separator — +// an item containing one is a 400, not a silent split later. +route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => { + const id = params.id; + bundle.requireRun(id); + requireOwner(user, id); + const items = body.items; + if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the agenda'); + for (const it of items) { + if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string'); + if (it.includes(',')) throw new HttpError(400, `items never contain commas (the add transport is comma-separated): ${JSON.stringify(it)}`); + } + const agenda = clerkJson(id, '--gm', 'agenda-set', ...items); + return { ok: true, agenda }; +}); + route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => { // ends the window and kicks the async chain; poll GET for the outcome requireOwner(user, params.id); diff --git a/server/session.mjs b/server/session.mjs index 8846db6..c169c02 100644 --- a/server/session.mjs +++ b/server/session.mjs @@ -53,7 +53,6 @@ function makeSession(runId, st) { file: sessionFile(runId, st), lines: [], pendingAsk: null, // { callId, question, calls } — the whole batch pauses - conflict: null, // carried to the next GM turn as a block usage: null, // { promptTokens, completionTokens } from the last response fresh: false, append(entry) { @@ -153,10 +152,6 @@ function derive(s) { } } else if (e.t === 'tool' && pending && e.m.tool_call_id === pending.callId) { pending = null; - } else if (e.t === 'note' && e.kind === 'paper') { - s.conflict = e.conflicts?.length ? e.conflicts.join('; ') : null; - } else if (e.t === 'msg' && e.m.role === 'user') { - s.conflict = null; // it rode this GM turn } else if (e.t === 'msg' && e.usage) { s.usage = { promptTokens: e.usage.prompt_tokens, completionTokens: e.usage.completion_tokens }; } @@ -166,7 +161,7 @@ function derive(s) { // --- the view renderer: log + policy -> per-call context --------------------- -const STRIP_BLOCKS = /\n?<(status|conflict)>[\s\S]*?<\/\1>\n?/g; +const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g; export function renderView(s, keepToolResults = 4) { const toolIdx = []; @@ -186,13 +181,17 @@ export function renderView(s, keepToolResults = 4) { const m = { role: 'assistant', content: e.m.content ?? null }; if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls; msgs.push(m); + } else if (e.conflictOnly) { + // transient error traffic: visible while it is the latest word + // (the model answers it), elided entirely once the story moves + // on — the log keeps it for provenance + if (i === lastGmIdx) msgs.push({ role: e.m.role, content: e.m.content.trim() }); } else if (i === lastGmIdx) { // the newest GM turn keeps its blocks as-sent: the current - // paper rides it, and a pending conflict rides it — the - // model must see both + // paper and agenda ride it msgs.push({ role: e.m.role, content: e.m.content.trim() }); } else { - // older GM turns: status/conflict blocks elide + // older GM turns: status/agenda/conflict blocks elide msgs.push({ role: e.m.role, content: e.m.content.replace(STRIP_BLOCKS, '').trim() }); } } else if (e.t === 'tool') { diff --git a/tool/memory.mjs b/tool/memory.mjs index d5602ff..e14757a 100644 --- a/tool/memory.mjs +++ b/tool/memory.mjs @@ -43,6 +43,14 @@ // (no descrs = clear it) // paper-ingest read a file's block into the paper // (turn-0 at new-game) +// agenda the agenda, as JSON (the intentions tier) +// agenda-apply "" apply / deltas from a player +// turn; drops are 0-based indexes against +// the agenda as last rendered; JSON result +// (added / dropped / evicted / conflicts / +// agenda) +// agenda-set "item" ... GM override: replace the whole agenda +// (no items = clear it) // pick "a" "b" "c" ... dice for prose — uniform random choice // dump canonical dump to dumps/memory.sql // (also auto-written by every mutation) @@ -65,6 +73,7 @@ const RUNS_DIR = path.join(ROOT, 'runs'); // dials — retune freely const CAPS = { a: 500, b: 3000 }; +const AGENDA_CAP = 5; // dial — retune freely (invariants.md: "intentionally tiny") const TYPES = ['place', 'person', 'fact', 'thread']; const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models @@ -154,9 +163,40 @@ function openDb() { } const db = new DatabaseSync(DB_PATH); db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8')); + migrateEventsCheck(db); return db; } +// the events CHECK names every legal op; a db opened before the agenda +// carries the narrower list and would reject agenda journaling. SQLite +// cannot alter a CHECK in place, so this rebuilds events once — the +// table is append-only, the copy is exact. (Mirrors db/schema.sql.) +function migrateEventsCheck(db) { + const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'events'").get(); + if (!row || row.sql.includes('agenda-add')) return; + const OPS = "('insert', 'touch', 'promote', 'demote', 'reword', 'delete', 'evict', 'revive', 'record', 'archive', 'unarchive', 'amend', 'discard', 'paper-add', 'paper-drop', 'paper-set', 'agenda-add', 'agenda-drop', 'agenda-evict', 'agenda-set')"; + db.exec('BEGIN'); + try { + db.exec(`CREATE TABLE events_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + window TEXT NOT NULL, + op TEXT NOT NULL CHECK (op IN ${OPS}), + target TEXT NOT NULL, + reason TEXT NOT NULL DEFAULT '', + prior TEXT NOT NULL DEFAULT '' + )`); + db.exec('INSERT INTO events_new SELECT * FROM events'); + db.exec('DROP TABLE events'); + db.exec('ALTER TABLE events_new RENAME TO events'); + db.exec('CREATE INDEX IF NOT EXISTS events_window ON events (window)'); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + fail(`events migration failed: ${e.message}`); + } + if (!QUIET) console.log(`(migrated: events journal widened for the agenda ops — ${rel(DB_PATH)})`); +} + const parseId = (s) => { const m = /^e(\d+)$/.exec(String(s ?? '').trim()); return m ? Number(m[1]) : null; @@ -214,6 +254,25 @@ function renderStatus(db) { return { file, count: rows.length }; } +// the agenda view: the queue, top (newest) first, numbered as the wire +// renders it — what the model cites, what the GM reads +function renderAgenda(db) { + const items = agendaList(db); + const lines = [ + '# Agenda — what drives her', + '', + 'The queue is the player\'s — intentions, not facts; facts live in the rings.', + '', + ]; + if (!items.length) lines.push('(a clear head — nothing queued)'); + items.forEach((d, i) => lines.push(`- ${i}. ${d}`)); + lines.push(''); + const file = path.join(CANON_DIR, 'agenda.md'); + fs.mkdirSync(CANON_DIR, { recursive: true }); + fs.writeFileSync(file, lines.join('\n')); + return { file, count: items.length }; +} + function renderAll(db) { for (const ring of RINGS) { const { file, count } = renderRing(db, ring); @@ -221,6 +280,8 @@ function renderAll(db) { } const { file, count } = renderStatus(db); if (!QUIET) console.log(`${rel(file)} — ${count} descriptions`); + const a = renderAgenda(db); + if (!QUIET) console.log(`${rel(a.file)} — ${a.count} queued`); } // canonical serialization: id-ordered, one row per line, restorable SQL. @@ -243,6 +304,9 @@ function dumpDb(db) { for (const r of db.prepare('SELECT * FROM paper ORDER BY id').all()) { L.push(`INSERT INTO paper VALUES (${r.id},${q(r.descr)},${q(r.added)});`); } + for (const r of db.prepare('SELECT * FROM agenda ORDER BY id').all()) { + L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`); + } for (const r of db.prepare('SELECT * FROM events ORDER BY id').all()) { L.push(`INSERT INTO events VALUES (${r.id},${q(r.window)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`); } @@ -693,7 +757,7 @@ function cmdCreate(pkgName, pc, displayName, model) { settings.name = displayName?.trim() || settings.name || pkgName; fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n'); const meta = { package: pkgName, created: today() }; - if (model) meta.model = model; + if (model) meta.models = { player: model }; if (ownerOverride) meta.owner = ownerOverride; fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n'); @@ -720,20 +784,20 @@ function cmdRuns() { if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json found++; let pkg = '?'; - let model = null; + let models = null; let owner = null; let created = null; let forked = null; try { const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8')); pkg = meta.package ?? '?'; - model = meta.model ?? null; + models = meta.models ?? null; owner = meta.owner ?? null; created = meta.created ?? null; forked = meta.forked ?? null; } catch {} const st = readRunSettings(runDir); - const base = { id: d.name, package: pkg, model, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) }; + const base = { id: d.name, package: pkg, models, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) }; const dbPath = path.join(runDir, 'db', 'memory.db'); if (!fs.existsSync(dbPath)) { list.push({ ...base, initialized: false }); continue; } const db = new DatabaseSync(dbPath); @@ -993,6 +1057,117 @@ function cmdPaperIngest(filePath) { dumpDb(db); } +// --- the agenda (intentions tier) --------------------------------------------- +// +// The hot queue of what drives her: goals she is working towards right +// now — intentions, never states (those are the paper's). Fixed cap +// (a dial); id order IS queue order — adds land at the top in written +// order, overflow evicts the bottom, a recency ring buffer for free. +// The player mutates via / in its own turns: drops are +// 0-based indexes against the agenda as last rendered, adds are +// comma-separated. The GM overrides whole-list with agenda-set. + +const agendaList = (db) => db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all().map((r) => r.descr); + +function cmdAgenda() { + console.log(JSON.stringify(agendaList(openDb()))); +} + +function cmdAgendaApply(text) { + const db = openDb(); + const added = []; + const dropped = []; + const evicted = []; + const conflicts = []; + const adds = []; + for (const m of String(text ?? '').matchAll(/([\s\S]*?)<\/add>/g)) adds.push(...splitDescrs(m[1])); + const drops = []; + for (const m of String(text ?? '').matchAll(/([\s\S]*?)<\/drop>/g)) { + drops.push(...String(m[1]).split(/[\n,]/).map((x) => x.trim()).filter(Boolean)); + } + if (!adds.length && !drops.length) { + console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) })); + return; + } + const win = AS_GM ? 'gm' : 'pc'; + db.exec('BEGIN'); + try { + // order of execution (invariants.md): received block -> drop -> add + // -> next block. Indexes resolve against the same snapshot, so a + // multi-drop never shifts under itself. + const snapshot = agendaList(db); + const kill = []; + for (const d of drops) { + if (!/^\d+$/.test(d)) { conflicts.push(`not an agenda index: ${JSON.stringify(d)}`); continue; } + const i = Number(d); + if (i >= snapshot.length) { + conflicts.push(`agenda has no item at index ${i}${snapshot.length ? '' : ' — it is empty'}`); + continue; + } + kill.push(i); + } + for (const i of [...new Set(kill)].sort((a, b) => b - a)) { + const descr = snapshot[i]; + const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(descr); + db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id); + journal(db, win, 'agenda-drop', `a${row.id}`, 'delta', descr); + dropped.push(descr); + } + // adds land at the top in written order (first item = the top slot): + // insert in reverse, id order does the rest. Already queued is a + // no-op, not a conflict — reorder is drop-then-add, by design. + for (const item of [...new Set(adds)].reverse()) { + if (db.prepare('SELECT 1 FROM agenda WHERE descr = ?').get(item)) continue; + const res = db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(item, today()); + journal(db, win, 'agenda-add', `a${Number(res.lastInsertRowid)}`, 'delta'); + added.push(item); + } + // overflow: the bottom sinks off the list — by design, not an error + const over = agendaList(db); + for (let i = over.length - 1; i >= AGENDA_CAP; i--) { + const row = db.prepare('SELECT id FROM agenda WHERE descr = ?').get(over[i]); + db.prepare('DELETE FROM agenda WHERE id = ?').run(row.id); + journal(db, win, 'agenda-evict', `a${row.id}`, 'agenda overflow (auto)'); + evicted.push(over[i]); + } + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + fail(`agenda-apply failed, rolled back: ${e.message}`); + } + console.log(JSON.stringify({ added, dropped, evicted, conflicts, agenda: agendaList(db) })); + renderAll(db); + dumpDb(db); +} + +// whole-list replace (GM override); the journal keeps the prior queue +// so turn surgery can compensate mechanically (the saga rule) +function setAgenda(db, items, reason, win) { + const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean); + const prior = agendaList(db); + db.exec('BEGIN'); + try { + db.prepare('DELETE FROM agenda').run(); + for (const d of [...clean].reverse()) { // first item = the top of the queue + db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(d, today()); + } + journal(db, win, 'agenda-set', 'agenda', reason, JSON.stringify(prior)); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + fail(`agenda-set failed, rolled back: ${e.message}`); + } + return clean; +} + +function cmdAgendaSet(items) { + const db = openDb(); + const clean = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc'); + console.log(JSON.stringify(clean)); + renderAll(db); + dumpDb(db); +} + function cmdPick(options) { if (options.length < 2) fail('usage: pick "option one" "option two" [...]'); const choice = options[Math.floor(Math.random() * options.length)]; @@ -1037,6 +1212,7 @@ function cmdStatus() { records: db.prepare('SELECT COUNT(*) AS n FROM records').get().n, recordsEnabled: recordsEnabled(), paper: paperList(db), + agenda: agendaList(db), events: db.prepare('SELECT COUNT(*) AS n FROM events').get().n, rings: {}, sinking: {}, @@ -1092,6 +1268,9 @@ switch (cmd) { case 'paper-apply': (args.length >= 1) ? cmdPaperApply(args.join(' ')) : fail('usage: paper-apply ""'); break; case 'paper-set': cmdPaperSet(args); break; // no args = clear the paper (a legitimate GM override) case 'paper-ingest': (args.length === 1) ? cmdPaperIngest(args[0]) : fail('usage: paper-ingest '); break; + case 'agenda': cmdAgenda(); break; + case 'agenda-apply': (args.length >= 1) ? cmdAgendaApply(args.join(' ')) : fail('usage: agenda-apply ""'); break; + case 'agenda-set': cmdAgendaSet(args); break; // no args = clear the agenda case 'pick': cmdPick(args); break; case 'search': cmdSearch(args); break; case 'unarchive': (args.length >= 1) ? cmdUnarchive(args[0], args[1]) : fail('usage: unarchive [a|b]'); break; @@ -1099,6 +1278,6 @@ switch (cmd) { case 'dump': cmdDump(); break; case 'restore': cmdRestore(FORCE); break; default: - console.error('usage: node tool/memory.mjs '); + console.error('usage: node tool/memory.mjs '); process.exit(1); } diff --git a/web/app.mjs b/web/app.mjs index 6d93941..bfd6b79 100644 --- a/web/app.mjs +++ b/web/app.mjs @@ -113,14 +113,17 @@ function renderContent(el, text, { extract }) { let body = String(text ?? ''); let status = null; let conflict = null; + let agenda = null; if (extract) { const sm = body.match(/([\s\S]*?)<\/status>/); if (sm) { status = sm[1]; body = body.replace(sm[0], ''); } const cm = body.match(/([\s\S]*?)<\/conflict>/); if (cm) { conflict = cm[1]; body = body.replace(cm[0], ''); } + const am = body.match(/([\s\S]*?)<\/agenda>/); + if (am) { agenda = am[1]; body = body.replace(am[0], ''); } } const tags = []; - for (const m of body.matchAll(/<(lost|gained)>([\s\S]*?)<\/\1>/g)) { + for (const m of body.matchAll(/<(lost|gained|add|drop)>([\s\S]*?)<\/\1>/g)) { tags.push({ kind: m[1], items: m[2].split('\n').flatMap((l) => l.split(',')).map((x) => x.trim()).filter(Boolean) }); } for (const t of tags) body = body.replace(new RegExp(`<${t.kind}>[\\s\\S]*?`), ''); @@ -137,6 +140,16 @@ function renderContent(el, text, { extract }) { el.appendChild(d); continue; } + if (t.startsWith('<')) { + // substrate lines: an opening is always OOC (invariants.md). + // Known blocks were extracted above; whatever remains is an + // unknown or unbalanced tag — keep it visible, styled as OOC + const d = document.createElement('div'); + d.className = 'line ooc'; + d.textContent = t; + el.appendChild(d); + continue; + } const stars = (line.match(/\*/g) ?? []).length; if (!narr && stars % 2 === 0) { // balanced: spans carry the registers — mixed lines @@ -183,7 +196,7 @@ function renderContent(el, text, { extract }) { } el.appendChild(wrap); } - return { status, conflict }; + return { status, conflict, agenda }; } // --- transcript --------------------------------------------------------------- @@ -222,6 +235,11 @@ function renderTranscript(entries) { } flushBundle(); if (e.t === 'msg') { + if (e.m.role === 'user' && e.conflictOnly) { + // the self-heal message: error traffic on its own, never GM prose + t.appendChild(el('div', 'machinery', `[conflict] ${String(e.m.content).replace(/<\/?conflict>/g, '').trim()}`)); + continue; + } if (e.m.role === 'user') gmTurn(e.m.content, 'GM'); else if (e.m.role === 'assistant') playerTurn(e); continue; @@ -281,6 +299,47 @@ function renderPaper(paper) { p.textContent = state.paper.join(', '); // compact, mirroring the wire format } +// the agenda pane mirrors the wire: the queue numbered from the top, +// exactly as the model cites it +function renderAgenda(agenda) { + state.agenda = agenda ?? []; + const a = $('agenda'); + if (!state.agenda.length) { + a.textContent = 'a clear head'; + a.classList.add('empty'); + return; + } + a.classList.remove('empty'); + a.textContent = state.agenda.map((d, i) => `${i}. ${d}`).join('; '); +} + +// the GM's out-of-band agenda override: whole-queue replace via agenda-set +function editAgenda() { + $('agenda-edit-area').value = state.agenda.join('\n'); + $('agenda').hidden = true; + $('agenda-edit').hidden = true; + $('agenda-editor').hidden = false; + $('agenda-edit-area').focus(); +} +function cancelAgendaEdit() { + $('agenda-editor').hidden = true; + $('agenda').hidden = false; + $('agenda-edit').hidden = false; +} +async function saveAgenda() { + const items = $('agenda-edit-area').value + .split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(',')) + .map((x) => x.trim()).filter(Boolean); + try { + await api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } }); + } catch (e) { + banner(e.message); + return; // stay in the editor — nothing was changed + } + cancelAgendaEdit(); + render(); +} + // the GM's out-of-band override: whole-paper replace via paper-set function editPaper() { $('paper-edit-area').value = state.paper.join('\n'); @@ -386,6 +445,7 @@ function show(view) { $('conflict').hidden = true; renderMeter(null); cancelPaperEdit(); // a stale open editor must never leave the pane hidden + cancelAgendaEdit(); if (view !== 'play') $('ask-modal').close(); } @@ -421,7 +481,7 @@ async function viewHome(seq) { // the name carries the content facts plus the ownership garnish; // started-or-forked rides the meta — chrome, never model-facing card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`)); - card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.model ? ` · ${r.model}` : ''}`)); + card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.models?.player ? ` · ${r.models.player}` : ''}`)); card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r))); // another user's draft is read-only: the play view says so; your own opens the editor card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`)); @@ -543,6 +603,46 @@ async function pickPackage(p) { if ($('create-pc').value === '' && roll?.name) $('create-pc').value = roll.name; } +// --- models: per-run overrides of the deployment defaults -------------------- +// +// The upstream listing is fetched once per session (a live /models +// call every render would hammer the endpoint for a list that rarely +// changes). A select's "" value means "deployment default"; a current +// override missing from the listing stays selectable, so a stale pick +// never silently rewrites itself. + +async function modelList() { + if (!state.modelList) state.modelList = await api('/models').catch(() => []); + return state.modelList; +} + +function fillModelSelect(sel, current, list, def) { + sel.textContent = ''; + const mk = (v, label) => { + const o = el('option', null, label); + o.value = v; + sel.appendChild(o); + }; + mk('', `deployment default${def ? ` — ${def}` : ' (unset)'}`); + const opts = [...list]; + if (current && !opts.includes(current)) opts.push(current); + for (const m of opts) mk(m, m); + sel.value = current ?? ''; +} + +async function saveModels(playerSel, housekeeperSel, stateEl) { + try { + await api(`/runs/${state.runId}/model`, { + method: 'POST', + body: { player: playerSel.value || null, housekeeper: housekeeperSel.value || null }, + }); + stateEl.textContent = 'saved'; + } catch (e) { + banner(e.message); + stateEl.textContent = 'not saved'; + } +} + // --- setup: the editor + start ----------------------------------------------------- // one list, in bundle-assembly order: the repo-fed system message @@ -603,8 +703,7 @@ async function viewSetup(id, seq) { api(`/runs/${id}/files`), api('/prompts'), ]); - } catch (e) { - if (e.status === 404) { + } catch (e) { if (e.status === 404) { const from = location.pathname; navigate('/'); // render() clears the banner first — set it after banner(`run ${id} is gone — deleted?`); @@ -641,6 +740,13 @@ async function viewSetup(id, seq) { varsList.appendChild(row); } + // models: per-run overrides, selected from the upstream listing + const mlist = await modelList(); + if (seq !== state.seq) return; + fillModelSelect($('model-player'), detail.run.models?.player ?? null, mlist, detail.run.modelDefaults?.player); + fillModelSelect($('model-housekeeper'), detail.run.models?.housekeeper ?? null, mlist, detail.run.modelDefaults?.housekeeper); + $('models-state').textContent = ''; + const nav = $('setup-files'); nav.textContent = ''; state.fileSpecs = {}; @@ -871,11 +977,13 @@ async function refreshPlay(id, seq) { + (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating'); renderMeter(detail); renderPaper(detail.paper); + renderAgenda(detail.agenda); $('conflict').hidden = true; // spectator mode: read everything, mutate nothing — the fork is the // way in. Ownerless runs are spectators for everyone alike. $('paper-edit').hidden = !mine; + $('agenda-edit').hidden = !mine; $('gm-notes').readOnly = !mine; let beatNeeded = false; @@ -900,6 +1008,15 @@ async function refreshPlay(id, seq) { ? 'GM line — Enter sends, Shift+Enter newlines' : 'spectating — fork this run to continue it as yours'; + // models: the owner's per-run overrides + $('models-pane').hidden = !mine; + if (mine) { + const mlist = await modelList(); + if (seq !== state.seq) return; + fillModelSelect($('pm-player'), detail.run.models?.player ?? null, mlist, detail.run.modelDefaults?.player); + fillModelSelect($('pm-housekeeper'), detail.run.models?.housekeeper ?? null, mlist, detail.run.modelDefaults?.housekeeper); + } + // pending ask: the modal re-presents after a refresh — the owner's // to answer; a spectator follows the thread in the transcript if (detail.pendingAsk && mine) { @@ -1188,6 +1305,8 @@ $('setup-vars-save').addEventListener('click', async () => { } }); $('setup-save').addEventListener('click', saveFile); +$('models-save').addEventListener('click', () => saveModels($('model-player'), $('model-housekeeper'), $('models-state'))); +$('pm-save').addEventListener('click', () => saveModels($('pm-player'), $('pm-housekeeper'), $('pm-state'))); $('setup-delete').addEventListener('click', deleteDraft); $('setup-edit').addEventListener('input', () => { if (state.currentFile) stashDraft(state.currentFile); @@ -1215,6 +1334,9 @@ $('hk-replay').addEventListener('click', replayWrap); $('paper-edit').addEventListener('click', editPaper); $('paper-cancel').addEventListener('click', cancelPaperEdit); $('paper-save').addEventListener('click', savePaper); +$('agenda-edit').addEventListener('click', editAgenda); +$('agenda-cancel').addEventListener('click', cancelAgendaEdit); +$('agenda-save').addEventListener('click', saveAgenda); $('gm-notes').addEventListener('input', notesInput); $('gm-notes').addEventListener('blur', saveNotes); window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce diff --git a/web/index.html b/web/index.html index a13958c..7cc7272 100644 --- a/web/index.html +++ b/web/index.html @@ -78,6 +78,15 @@ +
+

models — per-run, over the deployment defaults

+ + +
+ + +
+
@@ -119,6 +128,20 @@
+
+
+

her agenda

+ +
+
+ +

gm notes

@@ -141,6 +164,13 @@

a copy of this run — yours to continue

+