Files
tiny-worlds/server/shapes.mjs
T
mute eefb721675 the sheet round: the GM's ledger of arbitrated run state -- the second state channel, split from status and agenda by truth model (GM, 2026-11-17). The rulings first: status and agenda are narrative self-report (their truth is "she said so", the scan caches her latest words); the sheet is actual run state (its truth is "the GM set so", the record IS the truth event -- nothing cached from anyone's words). The override channel promoted to a standing section, and that precedent decided the presentation: the sheet renders as its OWN authoritative system chunk at the freshest end, never a canon-point stamp, which would read as her words -- the same reason the override composes as hers and the sheet never does. Schemaless JSON in the tag (the mind-verb philosophy: the substrate teaches the channel, the package teaches the vocabulary -- the invariants rule the GM wrote is one universal paragraph with deliberately non-box examples, clothes and grades, and the propose-additions line as her schema-evolution channel); details learnt in-place; NO package gating -- the channel is universal and "optional, if given" makes the invariant forward-compatible in every bundle that never sets one. The build: a sheet record rides the GM turn like the override (readSheet: object-ness is the route's only law, 400 loud on arrays and scalars, nothing appended; OOC turns refuse it exactly like block edits); scanState derives newest-wins whole-set -- an absent key drops, never keeps, and {} is a live empty ledger (a truthy check, never falsy); the boundary state note carries it across stops and the dormant read path serves it; renderView appends the chunk once per assembly so one live copy holds by construction; the guard is the <model> sibling (an emitted <sheet> conflicts with "the GM's ledger -- propose changes in prose", healed in-turn, cap 3, and her emission never applies -- the scan holds the GM's record); every strip surface learned the tag (the view's STRIP_HERS, the story's verbs, the table's chip regex -- the standing grep-every-strip-list lesson, applied); and the web gains sheetEditor, the paneEditor's JSON sibling in widgets.mjs (same stage/pending/discard pattern, bad JSON refuses at the stage), the third pane in the aside, the send attaching body.sheet, and [sheet] machinery lines on both table and raw walks. The mock's sheet-guard branch is CUE-KEYED, not position-keyed: the carried tail shifts the script's counts (session 4's log starts the script over -- the battery's first attempt landed on the ask position and crashed renderView on the unpaired call; the battery now answers the script ask and moves on), while a marked GM turn is immune to every shift -- mockModel reads the view, the marked turn earns the emission, the conflict it earns earns the plain-prose heal. check-reminder is sheet-aware (the chunk is a legitimate third system surface; the count and freshest-end assertions tolerate exactly one, and the freshest-end check now allows her latest reply and/or the chunk to follow the reminder). Verified: smoke ALL PASS with +15 sheet assertions (newest-wins, whole-set semantics, the chunk one-live-copy -- ANCHORED with startsWith because the invariants bundle itself mentions the tag and a bare regex matches it twice, an honest test bug caught by an honest test), the guard's conflict and heal with her emission kept verbatim in the raw log and never applied, the view and story strips, the empty ledger rendering its chunk, the boundary note carrying the sheet, the dormant read deriving it, and session 5 deriving it from the carried note end to end), restart + reminder checks green, typecheck green on both programs, check-repo clean (it caught the round's own prose twice: "window" is a retired term in README, the contwin vocabulary wins), and a browser pass over the pane end to end with zero console errors -- staging, the pending marker, the ride, the scan re-render, and both machinery lines on the table. Docs: README's protocol passage carries the sheet with the numbers-live-on-the-sheet line (prose numbers die with the contwin; sheet numbers ride the scan forever) -- NOT in the memory tiers table, where the first draft wrongly put it (the GM's ruling: the sheet belongs in neither memories nor records); the identity tier lost its loose "character sheet" name now that the term is technical; DICTIONARY gains the sheet entry with the history line (dice retired into variant literature, sheets arrived as the state machinery -- the tabletop metaphor completing while its realism stays advisory, players hold their own pencils in the real thing and we don't, for drift); ROADMAP parks the bookkeeper extension (the housekeeper's arithmetic sibling: reads the setting's rules prose and the latest turns, computes the ledger delta from a purchase in her prose, lands it as a STAGED edit -- applied on the GM's next turn or discarded; sheet-only authority, curator fallback, per-package opt-in because an agent cannot bookkeep what is not arithmetic). The GM's prompt-side edits ride the same commit: invariants' "Character's sheet" section (the universal rule, the trailing-clause flag taken in review), the reminder's inventory line gaining "the sheet (optional)", and la caramba's gm.md lore updates. The box package (the first consumer) and detention stay untracked WIP, untouched. The 2026-11-17 roadmap audit rides the same commit (GM: "done items can retire"): retired outright -- the SPA-vs-bridge and voice-examples decisions (long resolved) and steal items #1, #3, #4, #8, #11 (done, or in #8's case never work -- the housekeeper model is per-run selection, built); retired with tombstones -- the multiuser section (built 2026-11-14, the rulings live in DECISIONS #22-31 and README, the lifecycle tail kept visible) and the SPA v1 section (all four phases done, the API sketch superseded by README's living API docs, the substrate doctrine in README), with the one unbuilt design it held -- the turn-surgery saga rule -- surviving as its own bullet cross-referenced at steal #2; amended in place, dated -- seed.json (dead, successors named: the authored carryover and memory.json), turn-0.md (dead: her authored opening turn), the upstream model listing (never queried in play since discovery), the delta-tag transport (the full-block protocol, the sheet named), the service step (multiuser built, hosting remains), the carryover editor (the raw file-editor surface exists, the purpose-built UI stays deferred); kept -- the operator's queue, the landscape and receipts, the live constraints, the open steals with numbering preserved so cross-references resolve, the deferred tasks, the distant points, the rejections, the notes. 582 lines to 338; the first deletion pass duplicated the steal-list header and the verification re-read caught it
2026-11-17 22:50:59 +00:00

162 lines
11 KiB
JavaScript

// server/shapes.mjs -- the shared type declarations. No runtime code:
// this module exists so the tsc checker (JSDoc mode, no emit) and the
// humans reading the code agree on the load-bearing shapes. Every
// module types against these; the smoke owns their behavioral truth.
//
// The naming follows the code's own words: a log line is an event, a
// wire message is exactly what the API carried, the view is what the
// model sees on any call.
export {};
/** A role on the chat wire. */
/** @typedef {'user'|'assistant'|'system'|'tool'} Role */
/** One function call attached to an assistant message. */
/** @typedef {{ id: string, type: 'function', function: { name: string, arguments: string } }} ToolCall */
/** A tool definition on the wire: what the API receives in `tools`. */
/** @typedef {{ type: 'function', function: { name: string, description: string, parameters: { type: string, properties: Record<string, unknown>, required?: string[] } } }} ToolDef */
/** A chat message exactly as it rides the wire (OpenAI-compatible). */
/** @typedef {{ role: Role, content: ?string, tool_calls?: ToolCall[], reasoning_content?: string }} WireMessage */
/** Token usage, as the provider reports it and the log records it.
* completion_tokens_details carries the reasoning split when the
* provider states it (the discovery battery measures it). */
/** @typedef {{ prompt_tokens: number, completion_tokens: number, completion_tokens_details?: { reasoning_tokens?: ?number } }} Usage */
/** msg: one recorded turn (m is exactly what the wire carried). The
* reminder and conflictOnly flags are the only server-side marks --
* everything else about a turn lives in its content. via is the
* request record: the resolved model and the effective params (the
* merged layer actually sent) -- model-facing surfaces never render
* it, the raw surfaces always do. override is the GM's block edit,
* arriving with a non-OOC GM turn: the log's record of it. The
* composition overwrites her newest blocks with these values (the
* scan reads it newest-wins); the log itself never changes. */
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] }, sheet?: Record<string, unknown> }} MsgEvent */
/** req: a failed provider request -- the resolved model, the
* effective params, and the failure. No message resulted (the turn
* fails loud, the retry is the user's); this is the record of what
* was attempted, surfaced on the raw surfaces like a note. */
/** @typedef {{ t: 'req', model: string, params: RoleParams, fail: string }} ReqEvent */
/** tool: a tool result, paired to its call (pairing is a context
* invariant, checked at render). */
/** @typedef {{ t: 'tool', m: { role: 'tool', tool_call_id: string, content: string }, ask?: boolean }} ToolEvent */
/** note: the machine's own annotations -- never shown to the model,
* rendered as garnish in the SPA. Historical logs carry older kind
* names and the delta-shaped fields from before the full-block
* protocol; readers must not assume this union is exhaustive. */
/** @typedef {{ t: 'note', kind: 'session', n: number }} SessionNote */
/** @typedef {{ t: 'note', kind: 'ask', question: string }} AskNote */
/** @typedef {{ t: 'note', kind: 'pick', chosen: number, count: number }} PickNote */
/** @typedef {{ t: 'note', kind: 'status', applied?: { lost: string[], gained: string[] }, set?: string[], conflicts?: string[] }} StatusNote */
/** @typedef {{ t: 'note', kind: 'agenda', applied?: { added: string[], dropped: string[], evicted: string[] }, set?: string[], evicted?: string[], conflicts?: string[] }} AgendaNote */
/** @typedef {{ t: 'note', kind: 'mind', params: RoleParams }} MindNote */
/** state: the boundary snapshot -- stop writes it at the carryover's
* head when the closing log holds any status or agenda, so the new
* session derives state even when her newest emission fell outside
* the slidwin tail. Machinery like every note: never rendered, the
* scan reads it newest-wins (it loses to any emission inside the
* tail by position). */
/** @typedef {{ t: 'note', kind: 'state', status?: string[], agenda?: string[], sheet?: Record<string, unknown> }} StateNote */
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote} NoteEvent */
/** bundle: one frozen prompt part (system, backdrop, character, rings). */
/** @typedef {{ t: 'bundle', m: { role: 'user'|'system', content: string }, part: string }} BundleEvent */
/** opening: her opening status -- authored carryovers only, at most one. */
/** @typedef {{ t: 'opening', status: string[] }} OpeningEvent */
/** Any line of a session log or carryover, in either direction. */
/** @typedef {MsgEvent|ToolEvent|NoteEvent|BundleEvent|OpeningEvent|ReqEvent} LogEvent */
/** The pending ask, held on the session object while a turn waits. */
/** @typedef {{ callId: string, question: string, calls: ToolCall[] }} PendingAsk */
/** A live session: the log in memory, its derived state, the appender.
* The log is the truth; everything on this object is rebuilt from it.
* mind is the one-shot mind layer (the <mind> verb): the params her
* NEXT turn rides at, cleared when that turn completes -- derived
* from the last mind note, so a restart mid-window loses nothing. */
/** @typedef {{ runId: string, n: number, stamp: string, file: string, lines: LogEvent[], pendingAsk: ?PendingAsk, mind: ?RoleParams, usage: ?{ promptTokens: number, completionTokens: number }, progress: ?TurnProgress, append: (entry: LogEvent) => void }} LiveSession */
/** The turn meter's live record: what the streaming callback knows. `phase` is what is arriving now; `started` is the provider call's epoch ms. */
/** @typedef {{ phase: 'thinking'|'prose', thinking: number, prose: number, started: number }} TurnProgress */
/** run.json: lineage, ownership, per-run model overrides and knobs. */
/** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string }, params?: { player?: ?RoleParams, housekeeper?: ?RoleParams } }} RunMeta */
/** The named sampling knobs, per role -- the well-known, widely
* supported set, plus the reasoning-effort enum (GM, 2026-11-16:
* first-class, hidden from the model -- not her call). Numbers ride
* the wire verbatim; null clears; reasoning_effort is one of the
* effort ladder's levels. */
/** @typedef {{ temperature?: number, top_p?: number, top_k?: number, repetition_penalty?: number, max_tokens?: number, reasoning_effort?: string }} RoleParams */
/** One model of the discovered registry. Preliminary entries carry
* the scrape only (status unrefined); refined entries carry the
* battery's verdicts and the curator's presentation. think is the
* battery's best measured thinking-token count -- the pick rule
* ranks on it (the bucket is display). efforts is the
* reasoning-effort probe: the measured mean thinking per level of
* the ladder; effortDefault is the level with the highest observed
* mean (GM, 2026-11-16: maximum thinking by default, overridable)
* -- null when the model shows no thinking or no level moved it. */
/** @typedef {{ id: string, input: ?number, output: ?number, status?: 'unrefined', inference?: boolean, fail?: string, think?: ?number, reasoning?: 'off'|'low'|'standard'|'deep'|null, offSwitch?: Record<string, unknown>|null, efforts?: ?Record<string, number>, effortDefault?: ?string, latency?: ?number, family?: ?string, label?: ?string, description?: ?string, roles?: { player: boolean, housekeeper: boolean } }} RegistryModel */
/** state/models.json: the deployment's model registry -- the truth of
* what is selectable. Written by discovery (the scrape) and refine
* (the battery + the curator pass); read by the selectors, the model
* routes, and the turn loop. */
/** @typedef {{ phase: 'preliminary'|'refined', endpoint: ?string, discovered: string, refined: ?string, defaults: { player: ?string, housekeeper: ?string }, models: RegistryModel[], curator?: string }} ModelRegistry */
/** settings.json: identity (pc/name are the @ sigils), declared vars,
* the records flag. */
/** @typedef {{ pc?: string, name?: string, records?: boolean, vars?: Record<string, string> }} RunSettings */
/** A housekeeping manifest -- the housekeeper's whole write surface. */
/** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */
/** @typedef {{ id: string, reason: string }} RefOp */
/** @typedef {{ id: string, detail: string, reason: string }} RewordOp */
/** @typedef {{ type: string, label: string, detail: string }} RecordOp */
/** @typedef {{ session: string, summary: string, insert?: InsertOp[], touch?: RefOp[], promote?: RefOp[], demote?: RefOp[], reword?: RewordOp[], delete?: RefOp[], archive?: RefOp[], record?: RecordOp[], inventions?: string[], open_questions?: string[] }} Manifest */
/** The housekeeping job state (GET /housekeeping); discovery's refine
* job reuses the shape under its own map key. */
/** @typedef {{ state: 'idle'|'running'|'applied'|'pending'|'rejected', phase?: 'stop'|'rerun'|'refine', session?: number, target?: number, started?: string, stopped?: boolean, manifest?: string, reason?: string, steps?: { total: number, done: number, label: string, chars?: number }, lines?: string[] }} JobState */
/** The clerk boundary's result: exit code plus separated streams. */
/** @typedef {{ code: number, out: string, err: string }} ClerkResult */
/** One message of the rendered per-call view -- what the model sees. */
/** @typedef {{ role: Role, content: ?string, tool_calls?: ToolCall[], tool_call_id?: string }} ViewMessage */
/** A chat completion response (OpenAI-compatible). */
/** @typedef {{ choices: { message: WireMessage, finish_reason: ?string }[], usage?: Usage }} ChatResponse */
/** An Error carrying an HTTP status (and optional detail payload) --
* the server's only error shape. */
/** @typedef {Error & { status?: number, detail?: unknown }} HttpError */
/** The acting user, as the auth spine resolves a bearer token. */
/** @typedef {{ id: string, name: string, superuser: boolean }} User */
/** The acting user as the loops and jobs log it: attribution needs
* only the id (users.mjs's row, with its numeric superuser flag,
* flows in fine). */
/** @typedef {{ id: string }} Actor */
/** The provider client (provider.mjs's own return type). */
/** @typedef {ReturnType<typeof import('./provider.mjs').makeProvider>} Provider */
/** server.json as parsed. params is per-role sampling knobs -- the
* deployment-default layer the run's own params override. */
/** @typedef {{ bind?: string, port?: number, endpoint?: { baseUrl?: string, apiKey?: string, apiKeyEnv?: string }, models: { player?: ?string, housekeeper?: ?string }, contwin?: number, contextWindow?: number, params?: { player?: RoleParams, housekeeper?: RoleParams } }} ServerCfg */
/** The server context: the one object threaded through every module.
* locks/enqueue are the per-run activity lock (main.mjs). */
/** @typedef {{ mock: boolean, cfg: ServerCfg, provider: Provider, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */