8ef96c7ac5
The mind r/w round (2026-11-20, on the box run's live evidence: her fifth turn slipped the channel, the emission came out <model>, the guard's heal doubled a story passage): the via echo renders as the per-turn <mind> block (the block on a turn shows the params its prose was inferred with -- calibration pairs exactly), the <model> guard and its mock cue are deleted, STRIP_HERS and the story verbs drop the tag, reasoning_effort stays hidden from her, and the one-shot rule stands (r/w is the tag, not persistence). The box run's log was migrated in the same stroke, no-legacy: the refused emission became the valid mind write it tried to be, the conflict and heal left, the bundle system message regenerated under the new invariants. En-route: check-reminder's logged-turns floor relaxes to >= 1. The native-markup round's first act rides adjacent (2026-11-21): the box log's markup debris cleaned and verified through the real machinery (scan, view, story projection), and the agenda grammar is BULLETS -- blockList is kind-dependent now (status keeps its wire commas, agenda splits lines only), the pane and chip parsers match, and a comma-carrying mock item proves the grammar in the smoke. The two paused guards from that round never get built -- the blocks problem dissolves downstream into real tool calls.
Then the temperature research (2026-11-22/23; TEMP-RESEARCH.md, new at root, is the full record -- scope, the reusable fork-and-edit recipe and its gotchas, the failure taxonomy, hedges, open questions). Two blind sweeps of the box run first: prose VOICE tracks temperature blind (the composed-to-impulsive gradient survives with the number hidden), prose CONTENT was demand effect (round 1's traces read the visible <mind> block and styled to it -- a stage direction, not calibration), so the live push is RETIRED: the loop never renders the current call's settings into her view again, the per-turn via echoes are the whole read side. Thinking is temperature-robust through 1.2 and dies above it in four distinct shapes (shape-mixing 422, unbounded prose soup, reasoning-channel salad, instant salad). The n=20 organic ladder (320 forks, the box run's own moment) put the cliff at 1.2 proper: of twenty turns, 8 empty-prose, 5 soups, 2 refusals -- so the clamp drops to 1.15 ("we declare 1.2 too hot to be useful", GM, 2026-11-23; KNOB_BOUNDS moved, the smoke's conflict-range text with it). Side finding at scale: the restatement attractor -- blind, 50-85% of turns re-state their own <mind>, the value pinned near her recent emissions regardless of what rode.
Round 4 (2026-11-24) audits that corpus for content and changes no code: soft inference errors are temperature-FLAT (the ~30% breakfast error is structural, every rung), CONFABULATION IS A THRESHOLD AT 1.0 (fabrication-heavy reasoning 1.4% below the line vs 26.7% at or above; attribute drift below, invented events above; 1.15 bimodal at 8/20 -- the clamp is outcome-safe, not content-safe), and every mechanical axis is flat under the band: reasoning length, prose length, wall time, register proxies. Under the threshold, temperature is a pure voice knob.
On that evidence the two-subturn turn is DESIGNED (ROADMAP, designed-not-built): (a) full view + max effort + constant mid-band temp, the recall seat; (b) draft + tool oks + low effort + variable temp, the voice seat, the draft's register as the dial's zero point; the state blocks become real tool calls, retiring the strip lists, the strict lint, the block grammar, and the prose-to-blocks seam whole. The 2026-11-28 amendments complete it: the native tool loop carries her thread content-borne across rounds (the "thinking never returns" doctrine was transport fact -- the provider drops the field; the reader-facing rule stands), a purpose param on every tool call, the append-only prefix with the reminder as the one per-call exception (four flavors: orient, continue, draft-now, and (b)'s render contract), the recall tool (player search over its whole run; read-only, therefore rewind-safe by construction -- the records tools retire and their journaled-mutator compensation debt dies unfunded), and inline [...] annotations as the author-to-machine layer, the rationale block retained as the optional whole-turn scope. Three new ROADMAP sections ride: the status scan (the wake-up questions; location, inventory, and weather channels; meters pending), the package-declared ledger (the box order tool and the boutique shop as one mechanism; the measured 45% arithmetic re-derivation tax it kills), and the scene box with its paperdoll agent (TTI register, renderer-neutral, the model never draws a pixel). The helpfulness sweep (75 turns of the run's own reasoning: 62 CLEAN, 13 TRACE, 0 AFFECTED; onset at the punishment-arc OOC turns) and the live reading failures (the legs pronoun, the gag-speech riddle, the shed mind write) are recorded as the evidence base for the reading-rules piece.
The GM's prompt-side edits ride the same commit: invariants' r/w mind section and the agenda's no-trimming/no-metaphor lines (landed against observed behavior in the box run's thinking blocks), the clamp example already reading 1.15, system.md's injection-exception rename, README's protocol passages, DICTIONARY's updates, and the box package's backdrop and carryover content pass. The calibration materials (calibration.md, packager-calibration.md -- the A/B outputs, the flake record, the wrong-woman verdict) are committed as research records at the GM's staging. detention stays untracked WIP.
Verified across the sittings: typecheck green on both programs, smoke ALL PASS (the mind-r/w battery with the mock's script renumber, the clamp's conflict-range text, the comma-carrying agenda item), restart + reminder checks green, check-repo clean, and the debug server restarted on the real state. The substrate deltas in this commit are the mind r/w, the push retirement, and the clamp; everything else is the record.
838 lines
39 KiB
JavaScript
838 lines
39 KiB
JavaScript
// server/session.mjs -- a session's lifecycle and live state.
|
|
//
|
|
// A session is a stateful entity -- dormant -> live -> finished --
|
|
// owning its material under sessions/<n>/: the bundle (frozen prompt
|
|
// copies), the rings db, the canon views, the dumps, the carryover.
|
|
// Dormant is the review window (everything editable); start lints the
|
|
// carryover, freezes the bundle, consumes the carryover into the log
|
|
// and goes live; stop moves the tail into the next dormant session's
|
|
// carryover and freezes this one. No contwin before live.
|
|
//
|
|
// The append-only jsonl is the truth; the in-memory context is a view
|
|
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
|
|
// note / opening) so later features can append their own kinds without
|
|
// a format migration. The one sanctioned break of append-only is the
|
|
// rewind (2026-11-17): a rewind-send truncates the log to its target
|
|
// and lands the new turn in one commit -- fork is the preservation
|
|
// story, no fork no archaeology. The view renderer is pure
|
|
// policy over the log: thinking never goes back, variant turns render
|
|
// only the picked variant, old tool results elide to stubs
|
|
// (the last few and every ask_gm answer stay), old GM-side
|
|
// <status>/<conflict> blocks elide from GM prose -- the current status
|
|
// rides the newest GM turn -- and conflict messages never elide: a
|
|
// mistake stays visible so it is not made again (developer, 2026-11-18).
|
|
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
|
|
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
|
|
/** @typedef {import('./shapes.mjs').PendingAsk} PendingAsk */
|
|
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
|
|
/** @typedef {import('./shapes.mjs').OpeningEvent} OpeningEvent */
|
|
/** @typedef {import('./shapes.mjs').HttpError} HttpError */
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { clerk, clerkTry, clerkJson } from './clerk.mjs';
|
|
import { runDir, requireRun, assembleSystem, assembleBundle, expandVars } from './bundle.mjs';
|
|
import { parseVariants, pickVariant, effectiveContents } from './variants.mjs';
|
|
import { tailStart } from './carry.mjs';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
|
|
/** @param {string} runId */
|
|
const sessionsDir = (runId) => path.join(runDir(runId), 'sessions');
|
|
/** @param {string} runId @param {number} n */
|
|
export const sessionDir = (runId, n) => path.join(sessionsDir(runId), String(n));
|
|
/** @param {string} runId @param {number} n */
|
|
const logFile = (runId, n) => path.join(sessionDir(runId, n), 'log.jsonl');
|
|
/** @param {string} runId @param {number} n */
|
|
const carryFile = (runId, n) => path.join(sessionDir(runId, n), 'carryover.jsonl');
|
|
|
|
/** @param {string} runId @returns {number[]} */
|
|
export function listSessions(runId) {
|
|
if (!fs.existsSync(sessionsDir(runId))) return [];
|
|
return fs.readdirSync(sessionsDir(runId), { withFileTypes: true })
|
|
.filter((d) => d.isDirectory() && /^\d+$/.test(d.name))
|
|
.map((d) => Number(d.name)).sort((a, b) => a - b);
|
|
}
|
|
|
|
/** @param {string} runId @returns {?number} */
|
|
export const latestSession = (runId) => {
|
|
const ns = listSessions(runId);
|
|
return ns.length ? ns[ns.length - 1] : null;
|
|
};
|
|
|
|
/** @param {string} runId @param {number} n @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }} */
|
|
export function sessionMeta(runId, n) {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(path.join(sessionDir(runId, n), 'session.json'), 'utf8'));
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param {string} runId @param {number} n @param {Record<string, unknown>} patch
|
|
* @returns {{ phase?: string, ready?: boolean, [k: string]: unknown }}
|
|
*/
|
|
export function writeMeta(runId, n, patch) {
|
|
const m = { ...sessionMeta(runId, n), ...patch };
|
|
fs.writeFileSync(path.join(sessionDir(runId, n), 'session.json'), JSON.stringify(m, null, 2) + '\n');
|
|
return m;
|
|
}
|
|
|
|
// the run's state is its latest session's: live while one plays,
|
|
// else dormant (the review window). At most one live session exists.
|
|
/** @param {string} runId @returns {?number} */
|
|
export function liveSession(runId) {
|
|
return listSessions(runId).find((n) => sessionMeta(runId, n).phase === 'live') ?? null;
|
|
}
|
|
|
|
/**
|
|
* @param {number} status @param {string} message @param {unknown} [detail]
|
|
* @returns {HttpError}
|
|
*/
|
|
const err = (status, message, detail) => {
|
|
const e = /** @type {HttpError} */ (new Error(message));
|
|
e.status = status;
|
|
if (detail) e.detail = detail;
|
|
return e;
|
|
};
|
|
|
|
// --- session object ----------------------------------------------------------
|
|
|
|
/** @param {string} runId @param {number} n @returns {LiveSession} */
|
|
function makeSession(runId, n) {
|
|
return {
|
|
runId,
|
|
n,
|
|
stamp: String(n),
|
|
file: logFile(runId, n),
|
|
lines: [],
|
|
pendingAsk: null, // { callId, question, calls } -- the whole batch pauses
|
|
mind: null, // the <mind> verb's one-shot layer, rebuilt by derive
|
|
usage: null, // { promptTokens, completionTokens } from the last response
|
|
progress: null, // the turn meter's live record -- set per provider call, cleared at the turn's ends
|
|
/** @param {LogEvent} entry */
|
|
append(entry) {
|
|
this.lines.push(entry);
|
|
fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
|
|
},
|
|
};
|
|
}
|
|
|
|
/** @param {string} file @returns {LogEvent[]} */
|
|
function readLogLines(file) {
|
|
if (!fs.existsSync(file)) {
|
|
throw err(404, `no session log: ${path.relative(ROOT, file)}`);
|
|
}
|
|
const out = [];
|
|
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
if (!line.trim()) continue;
|
|
try {
|
|
out.push(JSON.parse(line));
|
|
} catch {
|
|
// a torn tail line (crash mid-append) is skipped, not fatal
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** @param {string} file @param {LogEvent[]} lines */
|
|
function writeLog(file, lines) {
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
const tmp = `${file}.tmp`;
|
|
fs.writeFileSync(tmp, lines.map((e) => JSON.stringify(e)).join('\n') + (lines.length ? '\n' : ''));
|
|
fs.renameSync(tmp, file); // atomic: a crash never leaves a torn log
|
|
}
|
|
|
|
/** @param {string} runId @param {number} n @returns {LiveSession} */
|
|
export function loadSession(runId, n) {
|
|
const s = makeSession(runId, n);
|
|
s.lines = readLogLines(s.file);
|
|
derive(s);
|
|
return s;
|
|
}
|
|
|
|
// rebuild the derived state from the log alone
|
|
/** @param {LiveSession} s */
|
|
function derive(s) {
|
|
/** @type {?PendingAsk} */
|
|
let pending = null;
|
|
/** @type {?import('./shapes.mjs').RoleParams} */
|
|
let mind = null;
|
|
for (const e of s.lines) {
|
|
if (e.t === 'msg' && e.m.role === 'assistant' && e.m.tool_calls?.length) {
|
|
const ask = e.m.tool_calls.find((c) => c.function.name === 'ask_gm');
|
|
if (ask) {
|
|
let q = '(no question)';
|
|
try { q = JSON.parse(ask.function.arguments || '{}').question ?? q; } catch {}
|
|
pending = { callId: ask.id, question: q, calls: e.m.tool_calls };
|
|
}
|
|
} else if (e.t === 'tool' && pending && e.m.tool_call_id === pending.callId) {
|
|
pending = null;
|
|
} else if (e.t === 'msg' && e.usage) {
|
|
s.usage = { promptTokens: e.usage.prompt_tokens, completionTokens: e.usage.completion_tokens };
|
|
}
|
|
// the mind layer: a statement is live until a player reply
|
|
// consumes it (a failed request consumed nothing -- the req event
|
|
// is not a reply). This makes a restart -- and a session
|
|
// boundary -- honest: her last on-record mind, unconsumed in
|
|
// this log, rides her next turn. Divergence only when a restart
|
|
// lands mid-turn (a tool-call message consumes here but only at
|
|
// turn completion in the live loop); the via records show what
|
|
// actually rode either way.
|
|
if (e.t === 'note' && e.kind === 'mind') mind = e.params;
|
|
else if (e.t === 'msg' && e.m.role === 'assistant') mind = null;
|
|
}
|
|
s.pendingAsk = pending;
|
|
s.mind = mind;
|
|
// a final variant turn that never got its pick (crash between the
|
|
// message and its note) resolves at boot: a fresh random pick,
|
|
// appended as the note it always should have had. Malformed content
|
|
// can't reach the log (the loop validates pre-append), so this only
|
|
// fires on a well-formed block; if it ever doesn't, warn and leave
|
|
// the message stripped-in-view rather than dying on rebuild
|
|
const last = s.lines[s.lines.length - 1];
|
|
if (last?.t === 'msg' && last.m.role === 'assistant' && !last.m.tool_calls?.length
|
|
&& typeof last.m.content === 'string' && /<\/?variants?>/.test(last.m.content)) {
|
|
try {
|
|
const v = parseVariants(last.m.content);
|
|
if (v) s.append({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
|
} catch (e) {
|
|
console.warn(`boot: an unresolved variant turn in session ${s.n} was left as-is: ${e.message}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// split a list of block items. Status is the comma-separated wire
|
|
// grammar; agenda is the bullet list invariants teaches ("The block
|
|
// format is a markdown bullet list") -- one item per line, list
|
|
// markers stripped, and a comma inside a bullet is prose, not a
|
|
// separator (developer, 2026-11-21: the shared comma split taught a
|
|
// grammar the prompt never promised). A present-but-empty block is a
|
|
// deliberate clear (an empty list). Shared with the turn loop (the
|
|
// player's live sets) and the state scan.
|
|
/** @param {string} text @param {'status'|'agenda'} kind @returns {string[]} */
|
|
export function blockList(text, kind) {
|
|
const out = [];
|
|
const wire = kind === 'status';
|
|
for (const m of String(text).matchAll(new RegExp(`<${kind}>([\\s\\S]*?)</${kind}>`, 'g'))) {
|
|
out.push(...m[1].split('\n')
|
|
.flatMap((l) => {
|
|
const bare = l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '');
|
|
return wire ? bare.split(',') : [bare];
|
|
})
|
|
.map((x) => x.trim()).filter(Boolean));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// --- the state scan: the log is the one truth ---------------------------------
|
|
//
|
|
// The full-block protocol made her logged blocks the model's only
|
|
// channel; the clerk's status and agenda tiers were a second home and
|
|
// are retired for it -- the panes, the run detail, and the stamp all
|
|
// read this scan, the db holds no copy. Newest-wins per kind across
|
|
// three sources, all in the log:
|
|
// - her emissions: the <status>/<agenda> blocks at her turn tails
|
|
// (the picked variant's text, for variant literature);
|
|
// - the GM's overrides: the override field on a GM turn -- the
|
|
// composition renders them as if she had stated them (the model
|
|
// never sees an override as an act, only as state);
|
|
// - the state note: the boundary snapshot at a carryover's head.
|
|
// null = never set; [] = deliberately cleared (a present-but-empty
|
|
// block is a clear, absent means unchanged). The agenda cap applies
|
|
// here, on every derivation: an over-cap list is never derivable
|
|
// from the log, the raw event is the only place her seven items live.
|
|
export const AGENDA_CAP = 5;
|
|
|
|
// the same clean the old clerk applies admitted: trim, drop empties,
|
|
// dedupe -- first occurrence wins
|
|
/** @param {string[]} items @returns {string[]} */
|
|
const cleanList = (items) => [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
|
|
|
// blockList + the clean, as one step: what every reader of a block
|
|
// derives from raw text (the scan for her emissions, the loop for its
|
|
// reception notes)
|
|
/** @param {string} text @param {'status'|'agenda'} kind @returns {string[]} */
|
|
export function cleanBlockList(text, kind) {
|
|
return cleanList(blockList(text, kind));
|
|
}
|
|
|
|
/** The state scan: newest-wins across her emissions (the picked
|
|
* variant's text), the GM's records, and the boundary note. The sheet
|
|
* (developer, 2026-11-17) is the second channel: arbitrated run state, never
|
|
* her words -- its sources are the GM's turn records and the note,
|
|
* each record a whole set (absent key means dropped, never kept), and
|
|
* it never caps, never cleans: the GM's ledger is exactly what the GM
|
|
* last set.
|
|
* @param {LogEvent[]} lines @returns {{ status: ?string[], agenda: ?string[], sheet: ?Record<string, unknown> }} */
|
|
export function scanState(lines) {
|
|
const eff = effectiveContents(lines);
|
|
/** @type {?string[]} */ let status = null;
|
|
/** @type {?string[]} */ let agenda = null;
|
|
/** @type {?Record<string, unknown>} */ let sheet = null;
|
|
for (const [i, e] of lines.entries()) {
|
|
if (e.t === 'msg' && e.m.role === 'assistant' && !e.m.tool_calls?.length) {
|
|
const c = eff.has(i) ? eff.get(i) : e.m.content;
|
|
if (typeof c === 'string') {
|
|
if (/<status>/.test(c)) status = cleanBlockList(c, 'status');
|
|
if (/<agenda>/.test(c)) agenda = cleanBlockList(c, 'agenda');
|
|
}
|
|
} else if (e.t === 'msg' && e.m.role === 'user' && e.override) {
|
|
if (e.override.status) status = cleanList(e.override.status);
|
|
if (e.override.agenda) agenda = cleanList(e.override.agenda);
|
|
} else if (e.t === 'msg' && e.m.role === 'user' && e.sheet) {
|
|
sheet = e.sheet;
|
|
} else if (e.t === 'note' && e.kind === 'state') {
|
|
if (e.status) status = cleanList(e.status);
|
|
if (e.agenda) agenda = cleanList(e.agenda);
|
|
if (e.sheet) sheet = e.sheet;
|
|
}
|
|
}
|
|
if (agenda !== null && agenda.length > AGENDA_CAP) agenda = agenda.slice(0, AGENDA_CAP);
|
|
return { status, agenda, sheet };
|
|
}
|
|
|
|
// --- stop: the manual close ----------------------------------------------------
|
|
//
|
|
// (1) move N's tail into the new dormant N+1 as its carryover;
|
|
// (2) freeze N; then the rest -- N+1's bundle and db are copies of
|
|
// N's. The move is at stop: each line exists in exactly one jsonl,
|
|
// ever, no markers on the lines. Crash-safe: a stop.json marker is
|
|
// written before anything is touched, and every step is idempotent --
|
|
// boot resumes a half-finished stop by re-running this over the
|
|
// on-disk state (the move step reconciles against what already
|
|
// landed, so it never moves anything twice).
|
|
/** @param {string} runId @param {number} N */
|
|
export function stopSession(runId, N) {
|
|
const dir = sessionDir(runId, N + 1);
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
fs.writeFileSync(path.join(dir, 'stop.json'), JSON.stringify({ from: N }) + '\n');
|
|
|
|
const src = sessionDir(runId, N);
|
|
const carry = path.join(dir, 'carryover.jsonl');
|
|
const lines = readLogLines(logFile(runId, N));
|
|
if (fs.existsSync(carry)) {
|
|
// the crash landed mid-move: the carryover is written; truncate
|
|
// the log to match it (the moved lines are the carryover now).
|
|
// The boundary state note is not log material -- the reconcile
|
|
// compares the carry's conversation lines only.
|
|
const carried = fs.readFileSync(carry, 'utf8').split('\n').filter((l) => l.trim())
|
|
.map((l) => /** @type {LogEvent} */ (JSON.parse(l)));
|
|
const conv = carried.filter((e) => !(e.t === 'note' && e.kind === 'state'));
|
|
const k = conv.length;
|
|
if (lines.length > k) {
|
|
const tail = lines.slice(lines.length - k).map((e) => JSON.stringify(e));
|
|
if (JSON.stringify(tail) !== JSON.stringify(conv.map((e) => JSON.stringify(e)))) {
|
|
throw err(500, `stop cannot resume: session ${N}'s log does not end with its own carryover -- fix by hand`);
|
|
}
|
|
writeLog(logFile(runId, N), lines.slice(0, lines.length - k));
|
|
} // else: already truncated -- nothing to move
|
|
} else {
|
|
const start = tailStart(lines);
|
|
// the boundary snapshot: the closing log's current state rides at
|
|
// the carry's head, so the new session derives it even when her
|
|
// newest emission fell outside the slidwin tail. The scan reads
|
|
// it newest-wins -- anything inside the tail wins over it by
|
|
// position, so it is safe to write always
|
|
const st = scanState(lines);
|
|
/** @type {LogEvent[]} */ let head = [];
|
|
if (st.status !== null || st.agenda !== null || st.sheet !== null) {
|
|
head = [{ t: 'note', kind: 'state', ...(st.status !== null ? { status: st.status } : {}), ...(st.agenda !== null ? { agenda: st.agenda } : {}), ...(st.sheet !== null ? { sheet: st.sheet } : {}) }];
|
|
}
|
|
const moved = [...head, ...lines.slice(start)];
|
|
fs.writeFileSync(carry, moved.map((e) => JSON.stringify(e)).join('\n') + (moved.length ? '\n' : ''));
|
|
writeLog(logFile(runId, N), lines.slice(0, start));
|
|
}
|
|
|
|
// (2) freeze N; the rest: the copies that make N+1 a real session
|
|
writeMeta(runId, N, { phase: 'finished' });
|
|
fs.cpSync(path.join(src, 'bundle'), path.join(dir, 'bundle'), { recursive: true });
|
|
fs.mkdirSync(path.join(dir, 'db'), { recursive: true });
|
|
// the db copy carries her status and agenda; the rings are the base
|
|
// the housekeeping apply lands on (each run re-copies, so re-runs
|
|
// never double-apply)
|
|
fs.copyFileSync(path.join(src, 'db', 'memory.db'), path.join(dir, 'db', 'memory.db'));
|
|
writeMeta(runId, N + 1, { phase: 'dormant', ready: false });
|
|
fs.rmSync(path.join(dir, 'stop.json'));
|
|
}
|
|
|
|
// a stop that died in flight leaves its marker; boot finishes it
|
|
/** @param {string} runId @returns {?{ from: number, dir: number }} */
|
|
export function findStalledStop(runId) {
|
|
for (const n of listSessions(runId)) {
|
|
const p = path.join(sessionDir(runId, n), 'stop.json');
|
|
if (fs.existsSync(p)) {
|
|
try {
|
|
return { from: JSON.parse(fs.readFileSync(p, 'utf8')).from, dir: n };
|
|
} catch {
|
|
return { from: n - 1, dir: n };
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// --- rewind: the GM's take-back (developer, 2026-11-17) ------------------------------
|
|
//
|
|
// The in-place rollback of the live session, deliberately destructive:
|
|
// the target GM turn and everything after it leave the log, and the
|
|
// send that carries the rewind takes the target's place -- edit-and-
|
|
// resend, the turn-surgery principle of DECISIONS #15. Where the old
|
|
// proposal kept the discarded range as typed cut events, the ruling
|
|
// here is physical truncation: fork is the preservation story (fork
|
|
// before rewinding keeps the branch), and with no fork there is no
|
|
// archaeology. Truncation is also why the feature is cheap -- every
|
|
// reader of the log (the view, the state scan, the carry walk, the
|
|
// story, housekeeping) sees the same shorter log with zero new
|
|
// machinery; the rings never move mid-session, so nothing else needs
|
|
// compensating. The floor is the start marker: the frozen opening
|
|
// never unwinds. Called from the send path only, inside the run's
|
|
// activity lock, after the new line expanded cleanly -- the commit is
|
|
// one landing with the turn that replaces the cut.
|
|
|
|
/**
|
|
* @param {LiveSession} s @param {number} idx the target GM turn's line index
|
|
* @returns {number} the lines dropped
|
|
*/
|
|
export function rewindTo(s, idx) {
|
|
if (!Number.isInteger(idx) || idx < 0 || idx >= s.lines.length) {
|
|
throw err(400, `the rewind target ${JSON.stringify(idx)} is not a line of this session's log`);
|
|
}
|
|
const e = s.lines[idx];
|
|
if (e.t !== 'msg' || e.m.role !== 'user' || e.conflictOnly) {
|
|
throw err(400, 'the rewind target must be one of your turns (a GM turn)');
|
|
}
|
|
// the floor: the LAST start marker (a carried log may hold an older
|
|
// one inside its opening -- only turns after the newest marker are
|
|
// this session's live play)
|
|
let floor = -1;
|
|
for (const [i, x] of s.lines.entries()) {
|
|
if (x.t === 'note' && x.kind === 'start') floor = i;
|
|
}
|
|
if (floor === -1) {
|
|
throw err(409, 'this session predates the rewind build -- its opening boundary is unmarked, so nothing is rewindable');
|
|
}
|
|
if (idx <= floor) {
|
|
throw err(400, 'the opening is frozen -- rewind reaches your turns after it only');
|
|
}
|
|
const dropped = s.lines.length - idx;
|
|
s.lines = s.lines.slice(0, idx);
|
|
writeLog(s.file, s.lines);
|
|
derive(s); // mind and usage re-derive from the shorter log
|
|
return dropped;
|
|
}
|
|
|
|
// --- start: lint, freeze, consume, go live -------------------------------------
|
|
|
|
// the authored carryover's event vocabulary: her opening as msg
|
|
// events (user = the GM, assistant = her). The opening event is
|
|
// RETIRED (developer, 2026-11-16): old carryovers keep theirs as inert
|
|
// history -- tolerated here, never applied. A continuation
|
|
// carryover is real conversation: msg, tool, note, and req events
|
|
// (a failed request's record is machinery like a note), read as
|
|
// recorded.
|
|
// Exported for the file editor's save-time check: only clean
|
|
// openings land.
|
|
/** @param {LogEvent[]} lines @param {{ authored: boolean }} opts @returns {string[]} */
|
|
export function lintCarryover(lines, { authored }) {
|
|
const errors = [];
|
|
let openings = 0;
|
|
lines.forEach((e, i) => {
|
|
const at = `line ${i + 1}`;
|
|
if (authored) {
|
|
if (e.t === 'msg') {
|
|
// authored carryovers are prompt-side: anything may be
|
|
// present that shouldn't be, so m is read permissively and
|
|
// every wrong thing is named
|
|
const m = /** @type {import('./shapes.mjs').WireMessage & Record<string, unknown>} */ (e.m ?? {});
|
|
if (m.role !== 'user' && m.role !== 'assistant') errors.push(`${at}: role must be user (the GM) or assistant (her)`);
|
|
if (typeof m.content !== 'string' || !m.content.trim()) errors.push(`${at}: content must be a non-empty string`);
|
|
if (m.tool_calls?.length) errors.push(`${at}: tool calls are runtime artifacts -- the opening never calls tools`);
|
|
if (m.usage) errors.push(`${at}: usage is runtime metadata`);
|
|
if (m.reasoning_content) errors.push(`${at}: thinking is runtime metadata`);
|
|
if (e.reminder) errors.push(`${at}: the reminder rides every GM turn on its own`);
|
|
if (e.conflictOnly) errors.push(`${at}: conflict traffic is runtime machinery`);
|
|
// the sheet's transport (developer, 2026-11-19, the box round): the
|
|
// record is the only channel -- the tag is view machinery,
|
|
// composed by renderView, never authored by anyone. Hers would
|
|
// never apply (the scan holds the GM's record) and primes the
|
|
// guarded emission; GM prose rides the view and story raw (the
|
|
// GM-side strips do not know the tag)
|
|
if (m.role === 'assistant' && e.sheet !== undefined) {
|
|
errors.push(`${at}: the sheet is the GM's record -- it rides GM turns only`);
|
|
}
|
|
if (typeof m.content === 'string' && /<\/?sheet>/.test(m.content)) {
|
|
errors.push(`${at}: the sheet tag is composed by the view, never authored -- the JSON rides the GM turn as its "sheet" record`);
|
|
}
|
|
} else if (e.t === 'opening') {
|
|
openings++;
|
|
if (!Array.isArray(e.status)) errors.push(`${at}: opening.status must be an array of descriptions`);
|
|
else for (const it of e.status) {
|
|
if (typeof it !== 'string' || !it.trim()) errors.push(`${at}: opening.status items must be non-empty strings`);
|
|
else if (it.includes(',')) errors.push(`${at}: descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
|
}
|
|
} else {
|
|
errors.push(`${at}: authored events are msg or opening only (got ${JSON.stringify(e.t)})`);
|
|
}
|
|
} else if (!['msg', 'tool', 'note', 'req'].includes(e.t)) {
|
|
errors.push(`${at}: a carryover holds conversation events only (got ${JSON.stringify(e.t)})`);
|
|
}
|
|
// both kinds: a variants message must parse strict -- nothing
|
|
// malformed reaches a contwin
|
|
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
|
|
&& /<\/?variants?>/.test(e.m.content)) {
|
|
try {
|
|
parseVariants(e.m.content);
|
|
} catch (e2) {
|
|
errors.push(`${at}: malformed variants block -- ${e2.message}`);
|
|
}
|
|
}
|
|
// both kinds: a GM turn's sheet record is the scan's source -- the
|
|
// route checks object-ness live, the lint covers every hand path
|
|
// (authored carryovers and dormancy edits both pass through here)
|
|
if (e.t === 'msg' && e.m?.role === 'user' && e.sheet !== undefined
|
|
&& (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
|
|
errors.push(`${at}: the sheet record must be a JSON object`);
|
|
}
|
|
// both kinds: the boundary state note must be well-formed (stop
|
|
// writes it; a hand edit must not corrupt it)
|
|
if (e.t === 'note' && e.kind === 'state') {
|
|
/** @type {Record<string, unknown>} */ const st = { status: e.status, agenda: e.agenda };
|
|
for (const k of ['status', 'agenda']) {
|
|
const v = st[k];
|
|
if (v === undefined) continue;
|
|
if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || !x.trim())) {
|
|
errors.push(`${at}: state.${k} must be an array of non-empty strings`);
|
|
}
|
|
}
|
|
if (e.sheet !== undefined && (typeof e.sheet !== 'object' || e.sheet === null || Array.isArray(e.sheet))) {
|
|
errors.push(`${at}: state.sheet must be a JSON object`);
|
|
}
|
|
}
|
|
});
|
|
if (authored && openings > 1) errors.push('at most one opening event');
|
|
// the full-block protocol (developer, 2026-11-16): the initial status rides
|
|
// her last turn in the carryover -- an authored carryover without
|
|
// model turns has no canon point to stamp
|
|
if (authored && !lines.some((e) => e.t === 'msg' && e.m?.role === 'assistant')) {
|
|
errors.push('the authored carryover must contain her opening turn (a model turn) -- the initial status rides it');
|
|
}
|
|
return errors;
|
|
}
|
|
|
|
// the authored carryover is prompt-side: sigils and $vars resolve at
|
|
// freeze, exactly like every bundle file. A continuation carryover is
|
|
// live prose and NEVER expands -- a literal $word typed in play would
|
|
// bomb the unresolved-token check, and the words are already real.
|
|
/** @param {string} runId @param {LogEvent[]} lines @returns {LogEvent[]} */
|
|
function expandCarryover(runId, lines) {
|
|
return /** @type {LogEvent[]} */ (lines.map((e) => {
|
|
if (e.t === 'msg') {
|
|
const m = { ...e.m, content: expandVars(runId, e.m.content) };
|
|
if (e.override) {
|
|
// an authored carryover may carry a GM override (the opening
|
|
// author writes one like any GM turn would); its items are
|
|
// prompt-side like the prose
|
|
/** @type {{ status?: string[], agenda?: string[] }} */ const o = {};
|
|
if (e.override.status) o.status = e.override.status.map((it) => expandVars(runId, it));
|
|
if (e.override.agenda) o.agenda = e.override.agenda.map((it) => expandVars(runId, it));
|
|
return { ...e, m, override: o };
|
|
}
|
|
return { ...e, m };
|
|
}
|
|
if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) };
|
|
return e;
|
|
}));
|
|
}
|
|
|
|
// an unpicked variants event gets its crypto pick at start -- the
|
|
// same dice the loop rolls on reception; a pick already adjacent
|
|
// (real history) is final, re-rolls do not exist
|
|
/** @param {LogEvent[]} lines @returns {LogEvent[]} */
|
|
function resolvePicks(lines) {
|
|
/** @type {LogEvent[]} */
|
|
const out = [];
|
|
for (let i = 0; i < lines.length; i++) {
|
|
const e = lines[i];
|
|
out.push(e);
|
|
const next = lines[i + 1];
|
|
if (e.t === 'msg' && e.m?.role === 'assistant' && typeof e.m.content === 'string'
|
|
&& /<\/?variants?>/.test(e.m.content)
|
|
&& !(next && next.t === 'note' && next.kind === 'pick')) {
|
|
const v = parseVariants(e.m.content); // lint already validated -- never null past the tag test
|
|
if (v) out.push({ t: 'note', kind: 'pick', chosen: pickVariant(v.variants.length), count: v.variants.length });
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** @param {string} runId @param {number} n @returns {LogEvent[]} */
|
|
function readCarryover(runId, n) {
|
|
const p = carryFile(runId, n);
|
|
if (!fs.existsSync(p)) return [];
|
|
const out = [];
|
|
const raw = fs.readFileSync(p, 'utf8').split('\n');
|
|
for (let i = 0; i < raw.length; i++) {
|
|
if (!raw[i].trim()) continue;
|
|
try {
|
|
out.push(JSON.parse(raw[i]));
|
|
} catch {
|
|
throw err(422, `the carryover is not valid JSONL (line ${i + 1} does not parse)`);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* @param {string} runId
|
|
* @param {{ override?: boolean }} [opts]
|
|
* @returns {{ session: LiveSession, autoSend: boolean }}
|
|
*/
|
|
export function startSession(runId, { override = false } = {}) {
|
|
requireRun(runId);
|
|
const n = latestSession(runId);
|
|
if (n == null) throw err(409, 'this run has no sessions -- create builds session one');
|
|
const meta = sessionMeta(runId, n);
|
|
if (meta.phase === 'live') throw err(409, `session ${n} is already live`);
|
|
if (meta.phase !== 'dormant') {
|
|
throw err(409, `session ${n} is ${meta.phase || 'unmarked'} -- a stop died in flight; restart the server to resume it`);
|
|
}
|
|
if (meta.ready !== true && n > 1 && !override) {
|
|
// the deliberate-skip guard: session N-1's transcript never
|
|
// reached the rings. The normal path cannot hit this (N+1's
|
|
// rings do not exist until housekeeping of N produces them).
|
|
throw err(409, `session ${n}'s rings are not ready -- session ${n - 1} was never housekept`, {
|
|
hint: 're-run housekeeping, or POST with {"override": true} to deliberately skip it',
|
|
});
|
|
}
|
|
|
|
const dir = sessionDir(runId, n);
|
|
const authored = n === 1;
|
|
let carry = readCarryover(runId, n);
|
|
const errors = lintCarryover(carry, { authored });
|
|
if (authored) {
|
|
try {
|
|
carry = expandCarryover(runId, carry);
|
|
} catch (e) {
|
|
errors.push(e.message);
|
|
}
|
|
}
|
|
if (errors.length) {
|
|
throw err(422, 'the carryover did not pass the start lint -- nothing started', { errors });
|
|
}
|
|
carry = resolvePicks(carry);
|
|
|
|
// session-0's housekeeping: her starting memories are authored
|
|
// material until this moment -- memory.json applies over a fresh db,
|
|
// so the draft's edits are the rings she actually gets. The clerk
|
|
// scratch-validates first (a refusal touches nothing), and a refusal
|
|
// refuses the start: the draft stays a draft.
|
|
if (n === 1) {
|
|
const mr = clerkTry(runId, '--session', '1', 'reapply');
|
|
if (mr.code !== 0) {
|
|
throw err(422, 'the starting memories did not pass the manifest checks -- nothing started', {
|
|
errors: [(mr.err || mr.out || 'reapply failed').split('\n')[0]],
|
|
});
|
|
}
|
|
// the full-block protocol (developer, 2026-11-16): the initial state
|
|
// rides her last authored turn -- the scan reads her blocks, the
|
|
// stamp renders them, the panes derive them. No seeding, no
|
|
// second home: her opening turn IS the seed. The opening event
|
|
// is retired the same way: old carryovers keep theirs as inert
|
|
// history (tolerated by the lint, never read -- and its old
|
|
// double-landing, pre-bundle and in-carry, dies here)
|
|
}
|
|
|
|
// fresh views, then the bundle: one assembly, baked here and
|
|
// nowhere else -- the frozen snapshot every call of this session
|
|
// renders from
|
|
const rr = clerkTry(runId, '--session', String(n), 'render');
|
|
if (rr.code !== 0) throw err(500, `render failed: ${(rr.err || rr.out).split('\n')[0]}`);
|
|
/** @type {{ role: 'system', content: string }} */
|
|
const system = { role: 'system', content: assembleSystem(runId, dir) };
|
|
const bundle = assembleBundle(runId, dir);
|
|
const partNames = ['backdrop', 'character', 'ring-b', 'ring-a'];
|
|
/** @type {LogEvent[]} */
|
|
const lines = [
|
|
{ t: 'note', kind: 'session', n },
|
|
{ t: 'bundle', m: system, part: 'system' },
|
|
...bundle.map((m, i) => /** @type {LogEvent} */ ({ t: 'bundle', m, part: partNames[i] })),
|
|
...carry,
|
|
// the rewind floor (developer, 2026-11-17): the opening -- authored or
|
|
// carried -- is frozen; live play starts at this line, and a
|
|
// rewind may only ever target GM turns below it
|
|
{ t: 'note', kind: 'start' },
|
|
];
|
|
// the assembled context must be sound before anything lands:
|
|
// tool pairing, variants resolution, every render invariant
|
|
try {
|
|
renderView({ lines, pendingAsk: null });
|
|
} catch (e) {
|
|
throw err(422, `the assembled context is not sound: ${e.message}`);
|
|
}
|
|
|
|
// land: the log written whole, the phase flipped, the carryover
|
|
// consumed (its lines live in the log now -- exactly one jsonl)
|
|
const s = makeSession(runId, n);
|
|
s.lines = lines;
|
|
writeLog(s.file, lines);
|
|
writeMeta(runId, n, { phase: 'live' });
|
|
fs.rmSync(carryFile(runId, n), { force: true });
|
|
derive(s);
|
|
|
|
// the opening flow: a carryover ending on a GM turn is her cue --
|
|
// it sends automatically as the first request of the assembled
|
|
// contwin; otherwise the table waits for the GM's input
|
|
const lastMsg = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...lines].reverse().find((e) => e.t === 'msg' && !e.reminder) ?? null);
|
|
return { session: s, autoSend: lastMsg?.m?.role === 'user' };
|
|
}
|
|
|
|
// --- the view renderer: log + policy -> per-call context ---------------------
|
|
|
|
const STRIP_BLOCKS = /\n?<(status|conflict|agenda)>[\s\S]*?<\/\1>\n?/g;
|
|
// her own blocks never show inline: status and agenda stamp at the
|
|
// canon point (the newest value of each kind at her most recent
|
|
// turn's tail), <mind> is stated per-turn and echoed per-turn (the
|
|
// via record renders as the turn's <mind> block -- the read side of
|
|
// the verb, developer 2026-11-20), <sheet> rides its own chunk -- the
|
|
// log keeps every copy verbatim, the view is policy
|
|
const STRIP_HERS = /(?:\n)?<(status|agenda|mind|sheet)>[\s\S]*?<\/\1>\n?/g;
|
|
|
|
/** The renderer reads only these two of a session -- the start path
|
|
* validates its assembled context with the same policy before going
|
|
* live. */
|
|
/** @typedef {{ lines: LogEvent[], pendingAsk: ?PendingAsk }} SessionView */
|
|
|
|
/** @param {SessionView} s @param {number} [keepToolResults] @returns {ViewMessage[]} */
|
|
export function renderView(s, keepToolResults = 4) {
|
|
const eff = effectiveContents(s.lines);
|
|
/** @type {number[]} */
|
|
const toolIdx = [];
|
|
/** @type {number[]} */
|
|
const reminderIdx = [];
|
|
// the stamping pre-pass (the full-block protocol): the canon point
|
|
// is her most recent prose turn -- the newest status and agenda
|
|
// stamp at its tail, whatever their source (her emission, a GM
|
|
// override, the boundary note -- the state scan's newest-wins).
|
|
// The status is the game world as of her turn; after it the GM's
|
|
// turn happens, then her new turn -- the context must read as that
|
|
// same sequence of events (developer, 2026-11-16)
|
|
const st = scanState(s.lines);
|
|
let lastProse = -1;
|
|
s.lines.forEach((e, i) => {
|
|
if (e.t === 'tool') toolIdx.push(i);
|
|
if (e.t === 'msg' && e.reminder) reminderIdx.push(i);
|
|
if (e.t === 'msg' && e.m.role === 'assistant') {
|
|
const c = eff.has(i) ? eff.get(i) : e.m.content;
|
|
if (typeof c === 'string' && c.trim()) lastProse = i;
|
|
}
|
|
});
|
|
const keep = new Set(toolIdx.slice(-keepToolResults));
|
|
const newestReminder = reminderIdx.length ? reminderIdx[reminderIdx.length - 1] : -1;
|
|
/** @type {ViewMessage[]} */
|
|
const msgs = [];
|
|
for (const [i, e] of s.lines.entries()) {
|
|
if (e.t === 'bundle') {
|
|
msgs.push({ role: e.m.role, content: e.m.content });
|
|
} else if (e.t === 'msg') {
|
|
if (e.reminder) {
|
|
// the per-turn reminder: only the newest copy lives in the
|
|
// context -- superseded ones elide (identical content, freshest
|
|
// position, exactly like the stamped blocks)
|
|
if (i === newestReminder) msgs.push({ role: 'system', content: String(e.m.content ?? '').trim() });
|
|
} else if (e.m.role === 'assistant') {
|
|
// thinking never goes back; the log keeps it. Variant turns
|
|
// render their picked variant -- the unpicked rest never reach
|
|
// a model (the log keeps them). Her blocks strip (STRIP_HERS);
|
|
// the via record renders as the turn's <mind> echo when any
|
|
// params rode (the verb's read side, developer 2026-11-20 --
|
|
// she calibrates the prose against what produced it); the
|
|
// newest status/agenda stamp at the canon point
|
|
let content = eff.has(i) ? (eff.get(i) ?? null) : (e.m.content ?? null);
|
|
if (typeof content === 'string') {
|
|
content = content.replace(STRIP_HERS, '').trim();
|
|
if (e.via && Object.keys(e.via.params ?? {}).length) {
|
|
// the via echo is the mind verb's read side:
|
|
// reasoning_effort is hidden from her (developer, 2026-11-16 --
|
|
// not her call), it rides the raw surfaces only
|
|
const shownVia = { ...e.via.params };
|
|
delete shownVia.reasoning_effort;
|
|
if (Object.keys(shownVia).length) {
|
|
content = `<mind>${JSON.stringify(shownVia)}</mind>\n${content}`;
|
|
}
|
|
}
|
|
if (i === lastProse) {
|
|
// the canonical stamp: status comma-separated (the wire
|
|
// grammar invariants teaches), agenda as bullets. A
|
|
// cleared kind renders its empty tag -- present-but-empty
|
|
// is the deliberate clear the grammar promises
|
|
/** @type {string[]} */ const stamp = [];
|
|
if (st.status !== null) stamp.push(`<status>${st.status.join(', ')}</status>`);
|
|
if (st.agenda !== null) {
|
|
stamp.push(`<agenda>${st.agenda.length ? `\n${st.agenda.map((d) => `- ${d}`).join('\n')}\n` : ''}</agenda>`);
|
|
}
|
|
if (stamp.length) content = `${content}\n${stamp.join('\n')}`;
|
|
}
|
|
}
|
|
const m = /** @type {ViewMessage} */ ({ role: 'assistant', content });
|
|
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
|
|
msgs.push(m);
|
|
} else if (e.conflictOnly) {
|
|
// the self-heal channel stays in the contwin (developer, 2026-11-18):
|
|
// a mistake remains visible so it is not made again. This is
|
|
// why conflicts must be self-contained -- describe the problem
|
|
// in full, quoting the offending emission, because the
|
|
// emission itself strips from the view and an old conflict
|
|
// cannot lean on the turn it answered
|
|
msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() });
|
|
} else {
|
|
// GM prose goes pure (the full-block protocol): the rides were
|
|
// server-composited, never GM words -- strip from every GM
|
|
// turn, old logs included
|
|
msgs.push({ role: e.m.role, content: String(e.m.content ?? '').replace(STRIP_BLOCKS, '').trim() });
|
|
}
|
|
} else if (e.t === 'tool') {
|
|
if (e.ask || keep.has(i)) {
|
|
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: e.m.content });
|
|
} else {
|
|
msgs.push({ role: 'tool', tool_call_id: e.m.tool_call_id, content: '[elided: earlier tool result]' });
|
|
}
|
|
}
|
|
}
|
|
// the sheet chunk (developer, 2026-11-17): arbitrated run state renders as
|
|
// its OWN authoritative system chunk at the freshest end -- never a
|
|
// canon-point stamp, which would read as her words. One live copy by
|
|
// construction (assembled once per view, not logged per turn). An
|
|
// empty object renders too: the channel exists, nothing tracked.
|
|
// She reads it, never writes it -- the guard conflicts an emission.
|
|
if (st.sheet != null) {
|
|
msgs.push({ role: 'system', content: `<sheet>${JSON.stringify(st.sheet)}</sheet>` });
|
|
}
|
|
validatePairing(msgs, s.pendingAsk?.callId);
|
|
return msgs;
|
|
}
|
|
|
|
// tool-call pairing is never broken (the endpoint tolerates orphans
|
|
// silently -- probed 2026-11-12 -- so this one fails quiet unless we check)
|
|
/** @param {ViewMessage[]} msgs @param {?string|undefined} pendingCallId */
|
|
function validatePairing(msgs, pendingCallId) {
|
|
const calls = new Set();
|
|
const results = new Set();
|
|
for (const m of msgs) {
|
|
if (m.role === 'assistant' && m.tool_calls) for (const c of m.tool_calls) calls.add(c.id);
|
|
if (m.role === 'tool') results.add(m.tool_call_id);
|
|
}
|
|
for (const id of results) {
|
|
if (!calls.has(id)) throw new Error(`context invariant violated: orphaned tool result ${id}`);
|
|
}
|
|
for (const id of calls) {
|
|
if (!results.has(id) && id !== pendingCallId) {
|
|
throw new Error(`context invariant violated: tool call ${id} has no result`);
|
|
}
|
|
}
|
|
}
|
|
|
|
export { clerkJson };
|