the 2026-11-16 rounds, the whole day in one commit: model discovery (the two-step op act -- discover scrapes the provider metadata, refine runs the deterministic battery over every id and hands the adjudicated results to the best passing model for the curated registry; state/models.json is the truth of selectable models and gates all model use, a fresh deployment has none; the five named sampling knobs ride run.json params over server.json params, sent only when set; the curator call retries once on the host's network hiccups, its output strictly validated with the machine-list fallback, and the do-not-deliberate line keeps its thinking tokens down); the pick rule reworked on the GM's rulings -- the dv endpoint's 5.2/5.3-max flip was an alias (one model behind both ids), the rank keys on the reasoning bucket not the raw token count (within-bucket differences are sampling noise, the thresholds sit in the endpoint's observed gaps) and full ties settle sort-lex-pick-bottom, with the mock registry carrying a canned tie pair (mock/mock-tie) and the smoke asserting the lex-bottom pick; the play-protocol batch (OOC GM turns carry no cache blocks, memory.json is authored draft applied by the start gate's reapply over a fresh db, /story filters OOC whole, the per-turn raw control on the table); the tunables UX round (web/knobs.mjs: the definitions table with the GM's hint texts and the probed this-endpoint bounds, the per-knob explicit override toggle replacing implicit empty-means-unset diffing, the shared focus-driven hint bar; the run detail and /model responses carry paramDefaults, the deployment layer -- the only default anyone can honestly name); request recording (every provider call lands its resolved model + effective params on the msg event as via, a failed call lands a req event with the failure, both surface on the raw tab and the per-turn raw control on no model-facing surface, a req riding the slidwin tail passes the start lint as conversation machinery; the housekeeping pass log names its model via the clerk's --model flag); the mind verb (<mind> JSON in a player turn sets its sampling for its next turn -- one-shot, max_tokens excluded, a budget not a mind; bounds enforced in KNOB_BOUNDS with the range named in the conflict and the heal restatement the statement that counts; derive() makes a statement live until a player reply consumes it, honest across restarts, session boundaries and forks -- an unconsumed mind rides on); the full-block protocol (the GM rewrote system/invariants/reminder to eliminate the diff verbs: she emits whole <status>/<agenda> at her turn tail, a present block is a whole-list set, absent means unchanged never blank, over-cap agendas evict from the bottom silently -- ruled a feature, silent to her, the note shows the GM; renderView strips every copy and stamps the newest of each kind at the tail of her most recent prose turn, her own emission, so the context reads as the same sequence of events the game had; GM prose goes pure, old logs' composited rides strip, they were never GM words; <mind> is write-only, its tags strip from the view; every turn of hers carries its <model> block -- the params it rode, bare JSON from the via record, the current call included, suppressed when nothing is set, emitting one refused with a pointer at <mind>; the clerk's status-apply/agenda-apply delta verbs RETIRED with their dispatch and collectors, status-set/agenda-set are the player path now; the story strips her blocks, the table chips them; the smoke imports renderView and asserts the view policy directly -- the pattern for testing view-only policy no API exposes); and the opening event RETIRED (the start gate seeds the clerk from her last authored turn's blocks -- the GM moved la-caramba's initial status into her opening turn; old carryovers keep their events as inert history; the event's pre-existing double-landing in every started log, pre-bundle and in-carry, died with the branch); smoke ALL PASS + restart + reminder + repo checks green, browser passes over the knob UX and the new chips and notes with zero console errors, typecheck green on both programs; README and DICTIONARY carry the durable design, HANDOFF trimmed to the map

This commit is contained in:
2026-11-16 21:32:02 +00:00
parent 193dc336be
commit 894737fcf3
30 changed files with 2193 additions and 518 deletions
+222 -45
View File
@@ -3,13 +3,20 @@
// Synchronous REST: a POST runs the tool loop and returns. ask_gm
// pauses mid-turn -- the whole tool-call batch waits (pairing stays
// sound), the request returns with the pending question, and the
// answer call resumes the loop. The status is re-read from the clerk
// before every GM turn and rides it as a <status> block; the player's
// <lost>/<gained> deltas apply after its final message, and any
// conflicts ride the next GM turn as a <conflict> block. GM input
// expands at ingestion (strict, DECISIONS #9): @PC/@Package and $vars
// resolve before the line is logged; an expansion error refuses the
// turn and the line is handed back for editing.
// answer call resumes the loop. GM prose goes pure (the full-block
// protocol, GM 2026-11-16): no cache blocks ride any turn -- her
// <status>/<agenda>/<mind> blocks ride at her own tail, the view
// stamps the newest of each kind at her most recent turn, and the
// clerk holds the one truth for the panes. The player's present
// blocks are whole-list SETs (absent means unchanged, never blank);
// conflicts (a refused <mind>, an emitted <model>) ride the
// self-heal channel. GM input expands at ingestion (strict,
// DECISIONS #9): @PC/@Package and $vars resolve before the line is
// logged; an expansion error refuses the turn and the line is handed
// back for editing. Every provider request records its resolved
// model and effective params on the resulting msg event (via); a
// failed call lands a req event with the failure -- the turn still
// fails loud.
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
/** @typedef {import('./shapes.mjs').Actor} Actor */
@@ -17,8 +24,9 @@
import { clerkJson } from './clerk.mjs';
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
import { renderView } from './session.mjs';
import { renderView, blockList } from './session.mjs';
import { parseVariants, pickVariant } from './variants.mjs';
import { registry, usable } from './discovery.mjs';
export class HttpError extends Error {
/**
@@ -58,12 +66,10 @@ export async function gmTurn(ctx, runId, line, user) {
} catch (e) {
throw new HttpError(400, `the line was not sent -- ${e.message}`);
}
const status = /** @type {string[]} */ (clerkJson(runId, 'status')); // fresh per turn
const agenda = /** @type {string[]} */ (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 = `${prose}\n\n<status>${status.join(', ')}</status>\n<agenda>${agendaWire}</agenda>`;
s.append({ t: 'msg', m: { role: 'user', content } });
// GM prose goes pure: no cache blocks ride any turn. Her blocks
// stamp at her own tail in the view (renderView); the clerk holds
// the one truth for the panes
s.append({ t: 'msg', m: { role: 'user', content: prose } });
// the reminder follows the GM's prose as its own system chunk --
// every turn, one live copy (older ones elide in the view)
const reminder = assembleReminder(runId);
@@ -119,14 +125,34 @@ async function runLoop(ctx, runId, user) {
let heals = 0;
for (;;) {
const view = renderView(s);
// the request's resolved params: the mind layer rides over the
// run and deployment layers. The current call's <model> block
// shows them to her when anything is set -- nothing set means no
// block (the absent grammar); the via record lands the same truth
const params = { ...resolveParams(ctx, runId, 'player'), ...(s.mind ?? {}) };
if (Object.keys(params).length) {
view.push({ role: 'system', content: `<model>${JSON.stringify(params)}</model>` });
}
let msg;
/** @type {{ model: string, params: Record<string, number> }} */ let via;
if (ctx.mock) {
// the synthetic marker: no provider call happens, but the knobs
// resolve for real (the mind layer included), so the smoke can
// assert the recording
msg = mockModel(s, view);
via = { model: 'mock', params };
} else {
const model = resolveModel(ctx, runId);
via = { model, params };
// 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, view, tools, ctx.cfg.params ?? {});
let data;
try {
data = await ctx.provider.chat(model, view, tools, params);
} catch (e) {
s.append({ t: 'req', model, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) });
throw e;
}
msg = data.choices[0].message;
s.usage = data.usage
? { promptTokens: data.usage.prompt_tokens, completionTokens: data.usage.completion_tokens }
@@ -134,7 +160,7 @@ async function runLoop(ctx, runId, user) {
}
if (msg.tool_calls?.length) {
const ask = msg.tool_calls.find((c) => c.function.name === 'ask_gm');
s.append({ t: 'msg', m: msg, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
s.append({ t: 'msg', m: msg, via, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
if (ask) {
let q = '(no question)';
try { q = JSON.parse(ask.function.arguments || '{}').question ?? q; } catch {}
@@ -162,7 +188,7 @@ async function runLoop(ctx, runId, user) {
} catch (e) {
throw new HttpError(422, `the player emitted a malformed variants block -- nothing applied; the turn is lost, retry: ${e.message}`);
}
s.append({ t: 'msg', m: msg, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
s.append({ t: 'msg', m: msg, via, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) });
let text;
if (vv) {
const chosen = pickVariant(vv.variants.length);
@@ -173,20 +199,34 @@ async function runLoop(ctx, runId, user) {
text = msg.content ?? '';
}
// the status and agenda deltas ride the turn text (the picked
// variant's, for variant literature). Same-verb blocks combine
// into one apply (the clerk's collectors gather every block before
// executing anything), never a sequence of applies.
// the status and agenda ride the turn text (the picked variant's,
// for variant literature). The full-block protocol (GM,
// 2026-11-16): a present block is a whole-list SET -- absent
// means unchanged, never blank; a present-but-empty block is a
// deliberate clear. Same-verb blocks combine into one set.
const carry = [];
if (/<(lost|gained)>/.test(text)) {
const r = clerkJson(runId, 'status-apply', text);
s.append({ t: 'note', kind: 'status', applied: { lost: r.lost, gained: r.gained }, conflicts: r.conflicts });
carry.push(...(r.conflicts ?? []));
if (/<status>/.test(text)) {
const set = clerkJson(runId, 'status-set', ...blockList(text, 'status'));
s.append({ t: 'note', kind: 'status', set });
}
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 (/<agenda>/.test(text)) {
const r = clerkJson(runId, 'agenda-set', ...blockList(text, 'agenda'));
// the eviction is silent to her, visible to the GM (the note)
s.append({ t: 'note', kind: 'agenda', set: r.set, evicted: r.evicted });
}
// the mind verb: parse now so a refused statement heals in-turn
// like any conflict; the stash itself lands only at the completing
// return (a healed restatement is the statement that counts)
/** @type {Record<string, number>} */ let mindNext = {};
if (/<mind>/.test(text)) {
const mind = parseMind(text);
carry.push(...mind.errors);
mindNext = mind.params;
}
// the <model> block is display-only: the read side of the mind
// verb, never hers to emit
if (/<model>/.test(text)) {
carry.push('the <model> block is a read-only display of your active parameters -- state them in a <mind> block');
}
if (carry.length && heals < 3) {
// a conflict answers for itself: it goes back as its own message,
@@ -197,17 +237,138 @@ async function runLoop(ctx, runId, user) {
continue;
}
if (carry.length) out.conflicts = carry; // healing gave up -- the transcript shows it
// the mind verb is one-shot: this completing turn consumed the
// mind it rode with; a fresh statement restates it for the next
s.mind = Object.keys(mindNext).length ? mindNext : null;
if (Object.keys(mindNext).length) s.append({ t: 'note', kind: 'mind', params: mindNext });
out.player = text;
return out;
}
}
/** @param {Ctx} ctx @param {string} runId @returns {?string} */
/** @param {Ctx} ctx @param {string} runId @returns {string} */
function resolveModel(ctx, runId) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
return meta.models?.player ?? ctx.cfg.models?.player ?? null;
const reg = registry();
// resolution: the run's pick, the op's server.json pick, the
// registry's discovered default -- then the registry gate: model
// use is disabled until the op discovers, and a model the battery
// disqualified never plays
const model = meta.models?.player ?? ctx.cfg.models?.player ?? reg?.defaults.player ?? null;
if (!model) {
throw new HttpError(409, reg
? 'no player model resolved -- set one for this run (POST /model), or a deployment default (server.json, or the registry\'s discovered pick)'
: 'no models discovered yet -- the op runs discovery from the admin block first');
}
if (!usable(reg, model)) {
throw new HttpError(409, `model '${model}' is not in the deployment's model registry${reg ? ' (or failed the inference probe)' : ''} -- pick a discovered model`);
}
return model;
}
/** The effective sampling knobs for a role: the deployment default
* layer (server.json params) under the run's own overrides. */
/** @param {Ctx} ctx @param {string} runId @param {'player'|'housekeeper'} role @returns {Record<string, number>} */
function resolveParams(ctx, runId, role) {
const meta = ctx.runMeta(runId) ?? /** @type {import('./shapes.mjs').RunMeta} */ ({});
return {
...(ctx.cfg.params?.[role] ?? {}),
...(meta.params?.[role] ?? {}),
};
}
export { resolveModel, resolveParams };
// --- the mind verb ------------------------------------------------------------
//
// <mind>{"temperature": 1.4}</mind> -- the player sets its own sampling
// knobs for its NEXT turn, to reflect the character's mind (GM,
// 2026-11-16: tag form, one-shot, no GM lock; the block carries a
// JSON object -- models emit JSON natively; the parameters need no
// model-facing explanation, they live native in base training).
// max_tokens is excluded by ruling (GM, 2026-11-16) -- it is a
// budget, not a mind. A substrate verb like the deltas: parsed from
// the picked variant's text after the final message, merged over the
// run and deployment layers for every call of the next turn, then
// spent. The bounds are the probed this-endpoint knowledge --
// enforced here, strictly, with the range named in the conflict so
// she can heal. The web's definitions table (web/knobs.mjs) carries
// the bounds as display prose for all five knobs; this table is the
// mind verb's validator, the four that are hers to set.
/** One knob's validated range. An absent bound is unknown (no limit
* stated); minExclusive excludes the min itself (top_p refuses 0,
* repetition_penalty refuses 0). */
/** @typedef {{ min?: number, max?: number, minExclusive?: boolean }} KnobRange */
/** @type {Record<string, KnobRange>} */
const KNOB_BOUNDS = {
temperature: { min: 0, max: 2 },
top_p: { min: 0, max: 1, minExclusive: true },
top_k: {}, // unbounded -- -1 and 0 both mean the filter is off
repetition_penalty: { min: 0, minExclusive: true },
};
/** @param {string} key @param {KnobRange} r @returns {string} */
function rangeText(key, r) {
if (r.min !== undefined && r.max !== undefined) {
return `${key} must be ${r.minExclusive ? 'above' : 'at least'} ${r.min} and up to ${r.max}`;
}
if (r.min !== undefined) return `${key} must be ${r.minExclusive ? 'above' : `${r.min} or more`}`;
if (r.max !== undefined) return `${key} must be at most ${r.max}`;
return `${key} accepts any number (-1 and 0 turn the filter off)`;
}
/** Parse one turn's <mind> blocks: a JSON object of knobs per block,
* all blocks combined (last wins per key, the same-verb rule). Every
* wrong thing is named -- the caller rides the conflict path, and
* she heals by restating.
* @param {string} text @returns {{ params: Record<string, number>, errors: string[] }}
*/
function parseMind(text) {
/** @type {Record<string, number>} */ const params = {};
/** @type {string[]} */ const errors = [];
const blocks = [...text.matchAll(/<mind>([\s\S]*?)<\/mind>/g)].map((m) => m[1]);
for (const block of blocks) {
let obj;
try {
obj = JSON.parse(block);
} catch (e) {
errors.push(`the <mind> block wants a JSON object (${String(e.message ?? e).split('\n')[0].slice(0, 120)})`);
continue;
}
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
errors.push('the <mind> block wants a JSON object of knobs');
continue;
}
for (const [key, v] of Object.entries(obj)) {
if (key === 'max_tokens') {
errors.push('max_tokens is not hers to set -- the mind verb sets temperature, top_p, top_k, repetition_penalty');
continue;
}
const range = KNOB_BOUNDS[key];
if (!range) {
errors.push(`the <mind> block names an unknown knob: ${key} -- ${Object.keys(KNOB_BOUNDS).join(', ')}`);
continue;
}
if (typeof v !== 'number' || !Number.isFinite(v)) {
errors.push(`the <mind> block wants a number for ${key}`);
continue;
}
if ((range.min !== undefined && (range.minExclusive ? v <= range.min : v < range.min))
|| (range.max !== undefined && v > range.max)) {
errors.push(`the <mind> block was refused on this endpoint's bounds: ${rangeText(key, range)} (got ${v})`);
continue;
}
params[key] = v;
}
}
if (blocks.length && !Object.keys(params).length && !errors.length) {
errors.push('the <mind> block is empty -- it wants a JSON object of knobs');
}
return { params, errors };
}
export { parseMind };
// --- the mock model ----------------------------------------------------------
//
// A scripted stand-in that exercises the loop without a key. The
@@ -217,10 +378,12 @@ function resolveModel(ctx, runId) {
// never counts; a continuation carryover's exchanges DO, so a
// carried history shifts the first turn's script position, and the
// smoke knows exactly where that is. Turn one offers variant
// literature (the random pick), turn two asks (the pause/resume
// path), the answer lands with status and agenda deltas (the tag
// transports), then the drops, a bad drop, its self-heal, and
// everything after is plain prose.
// literature (the random pick, each variant with its own status
// block), turn two asks (the pause/resume path), the answer lands
// whole-list status and agenda sets, then a restated agenda, an
// over-cap agenda with a valid mind, the <model> guard and its
// plain-prose heal, an out-of-bounds mind and its restating heal,
// and everything after is plain prose.
/** @typedef {import('./shapes.mjs').WireMessage} WireMessage */
/**
@@ -245,27 +408,41 @@ function mockModel(s, view) {
const toolResults = view.filter((m) => m.role === 'tool').length;
if (count === 0) {
// variant literature: two complete candidate turns, each with its
// own delta -- only the picked one's ever applies
return { role: 'assistant', content: '<variants>\n<variant>\n*She presses on along the hull, palms flat against the warm metal.*\n<gained>determined</gained>\n</variant>\n<variant>\n*She doubles back to the container and crouches in its shadow.*\n<gained>cautious</gained>\n</variant>\n</variants>' };
// own status block -- only the picked one's ever applies
return { role: 'assistant', content: '<variants>\n<variant>\n*She presses on along the hull, palms flat against the warm metal.*\n<status>cuffed, belted, naked, barefoot, determined</status>\n</variant>\n<variant>\n*She doubles back to the container and crouches in its shadow.*\n<status>cuffed, belted, naked, barefoot, cautious</status>\n</variant>\n</variants>' };
}
if (count === 1 && toolResults === 0) {
return call('ask_gm', { question: 'From where she stands, does the deck look clear toward the bow?' }, `mock-ask-${s.lines.length}`);
}
if (count === 2 && toolResults >= 1) {
// two <gained> and two <add> 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.*\n<lost>worried</lost>\n<gained>settled</gained>\n<gained>curious about the clicking</gained>\n<add>find fresh water</add>\n<add>signal any passing ship, build a shelter</add>' };
// the full-block protocol: whole-list sets
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<status>cuffed, belted, naked, barefoot, settled, curious about the clicking</status>\n<agenda>find fresh water\nsignal any passing ship\nbuild a shelter</agenda>' };
}
if (count === 3) {
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<drop>0</drop>' };
// a restated agenda replaces the list (the first item is done)
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<agenda>signal any passing ship\nbuild a shelter</agenda>' };
}
if (count === 4) {
return { role: 'assistant', content: 'Mock: *She squints at the horizon.*\n<drop>9</drop>' };
// an over-cap agenda evicts from the bottom, silently; a valid
// mind rides the same turn
return { role: 'assistant', content: 'Mock: *Her thoughts race ahead of her feet.*\n<agenda>item one\nitem two\nitem three\nitem four\nitem five\nitem six\nitem seven</agenda>\n<mind>{"temperature": 1.2}</mind>' };
}
if (count === 5) {
// 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.*\n<drop>0, 1</drop>' };
// the <model> block is display-only: the guard conflicts
return { role: 'assistant', content: 'Mock: *She squints at the horizon.*\n<model>{"temperature": 0.1}</model>' };
}
if (count === 6) {
// the guard's heal: plain prose, no blocks -- omitted means unchanged
return { role: 'assistant', content: 'Mock: *She shakes her head and gets back to watching the water.*' };
}
if (count === 7) {
// an out-of-bounds mind: the conflict names the range
return { role: 'assistant', content: 'Mock: *Her thoughts scatter.*\n<mind>{"temperature": 7}</mind>' };
}
if (count === 8) {
// the heal's restatement -- the statement that counts (and the
// last word of the session, so it rides the boundary unconsumed)
return { role: 'assistant', content: 'Mock: *She breathes until the numbers behave.*\n<mind>{"temperature": 1.2}</mind>' };
}
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
}