53f992a5e0
The rewind (GM, 2026-11-17): "session rewind" came off the operator queue and was redesigned simpler than the turn-surgery proposal -- physical truncation, not typed cut events; fork is the preservation story (fork before rewinding keeps the branch, no fork no archaeology), and the derivation model made the simple design free: status, agenda, and the sheet are all scanState-derived from the log, so a cut re-derives every channel with zero compensation, and every log reader (the view, the scan, the carry walk, the story, housekeeping) sees the same shorter log with nothing new between them. As built: the send commits the rewind -- POST /turn takes optional rewind (a log line index naming one of your turns; that turn and everything after it leave the log, the send replaces it) and optional expect (the log line count the client composed against; the log only moves through sends, so a mismatch means a stale tab and refuses before anything rides -- the ask answer carries it too); gmTurn's order is pendingAsk-refusal -> expect -> expand -> truncate -> land, one commit inside the activity lock, a crash between truncate and land leaving a consistent shorter log and no rewound-but-waiting state ever existing; the floor is the start marker ({t:'note', kind:'start'} written once at start right after the carryover) -- the frozen opening never unwinds, the rule reads the LAST marker (a carried log may hold an older one inside its opening), and a pre-build log refuses loudly as unmarked; the player-facing records tools are OFF until rewind-compatible (their verbs mutate the session db, which a truncation does not compensate; the manifest carries ask_gm alone whatever the settings gate says, while the CLI's --gm filings never ride a turn and stand, rewind-safe by construction); and /retry never existed -- resending the same words after a rewind IS the retry (the GM had no recollection of where the idea came from; dropped, subsumed). The SPA stages the gesture client-side until the send: a per-GM-turn rewind control (the transcript walk's onRewind, offered live and ask-free only), two-click armed, the target's EXPANDED words auto-filling the composer (the log is truth, $vars baked), a composer tint plus a note naming the cut in entries (the colour alone says something is pending, not what dies), cancel restoring the pre-gesture state, text in the box disabling the buttons under the rename "to rewind delete your current input" (a visible affordance, not hiding), and a failed send keeping the gesture armed only on a 400 (anything else may have moved the log). The gm.md desync is parked to ROADMAP's deferred list (notes taken at turn 30 surviving a rewind to 20, orphaned from the narrative -- nothing mechanical is safe there, fork covers it meanwhile). Verified: typecheck green on both programs, smoke ALL PASS with +14 rewind assertions (the floor refusals, her-turn refusal, the stale-expect 409, the truncation 45->42 lines, the dead-range sheet record reverting, the story dropping the cut, the marker surviving), restart + reminder checks green, check-repo clean after staging, and a browser pass committing a real rewind through the UI end to end (the gesture staged, cancelled, re-staged, edited, sent: 20 turns to 8 on the table, the wire body exactly {line, expect, rewind}, zero console errors).
The conflict-persistence round (GM, 2026-11-18): conflicts stay in the contwin and are self-contained. The old view policy treated conflicts as transient (visible only while the latest word, elided after) -- overruled: a mistake remains visible so it is not made again. Self-contained means the conflict DESCRIBES ITS PROBLEM IN FULL, quoting the offending emission, because the block it answers strips from the view (STRIP_HERS takes her <model>/<mind>/<sheet>) -- an old conflict cannot lean on the turn it immediately follows, and the quote is the only visible trace of what went wrong. As built: renderView renders conflictOnly unconditionally (the lastGmIdx elision gone, the variable with it); a shared quote() helper (trim, collapse whitespace, cap at 160 -- enough to identify the mistake, never a wall) feeds the guards ("yours said: {...}" on <model> and <sheet>, "(you set: ...)" on the mind verb's per-key refusals, "-- yours: {the block}" on mind JSON that does not parse; the out-of-bounds mind already carried "(got 7)" and keeps its exact form); and the ripple caught: carry.mjs's visibleBytes counted conflicts as zero-cost on the grounds they "elide once the story moves on" -- carried conflicts now render in the new session, so they cost against the 96KB budget like the prose they are. The story keeps omitting conflicts (machinery, not deliverable) and invariants' one line still reads true, so no prompt-side change was needed. Verified: smoke ALL PASS with +3 assertions (both session-1 conflicts rendering in the view despite being old news, the model-guard quote, the sheet-guard quote), restart + reminder checks green, check-repo clean.
The GM's prompt-side edit rides the same commit: the reminder's decision passage gains the checked-action metrics -- three probes for when an action should be written as intent (external conditions: the lever; scope expansion: the mall; unilateral canonisation: the gasp at what is inside), each example attempt-form under the handbook's "the attempt, never the outcome", and the third deliberately bending that line with the price named in the same breath (the reaction is hers to have, the contents never hers to say, and the dud reveal embraced as a subversion vehicle -- purview taught as a negotiation, not a prohibition); the impulsive/irrational line now names the channel ("mention it in the narration"); the two tab-indented continuations normalized to the file's spaces.
Also: the smoke's final line now prints the draft id (a smoke draft survived cleanup because "run ids" never named it -- caught on the runs listing, deleted, the print is the fix). Docs: README's protocol passage carries the rewind and the conflict lifetime, with the records-off notes in the substrate section, the tiers table, and the layout; DECISIONS #15 gains the full amendment (the ruling record: a-g, expect, the ask refusal, records-off, the gm.md park); QUESTIONS' turn-surgery details closed (retry dropped, truncation ruled); ROADMAP's surgery sections built-and-amended, the operator queue line removed, the gm.md desync parked; DICTIONARY gains the rewind entry and amends the conflict and view entries. The box package and detention stay untracked WIP, untouched.
168 lines
12 KiB
JavaScript
168 lines
12 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 */
|
|
/** start: the frozen-opening boundary (rewind, GM, 2026-11-17) --
|
|
* written once at start, right after the consumed carryover: the
|
|
* opening (authored or carried) above it is what a rewind can never
|
|
* reach. A session whose log predates the build carries none, and
|
|
* its rewind refuses loudly. */
|
|
/** @typedef {{ t: 'note', kind: 'start' }} StartNote */
|
|
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote|StartNote} 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 */
|