Files
tiny-worlds/test/smoke.mjs
T
mute 53f992a5e0 the rewind and conflict-persistence rounds, plus the GM's reminder edit: the take-back and the honest error record.
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.
2026-11-18 17:24:37 +00:00

797 lines
59 KiB
JavaScript

// test/smoke.mjs -- end-to-end multiuser pass against the --mock
// server. Covers: bootstrap, claim, spent-invite rejection, second
// user, the model registry (a fresh deployment has no models,
// discover scrapes, refine runs the battery + the curator, registry-
// gated picks, the pick rule's lex tie-break, the named sampling
// knobs, the reasoning-effort knob (the battery's effort probe, the
// max-mean default that sends, the override that rides the turn,
// hidden from the model), the request record -- resolved model +
// effective params on
// every turn, the pass log's model), the mind verb (the player sets
// its sampling for its next turn: one-shot, JSON, bounds enforced,
// conflict-healed, carried unconsumed across a session boundary,
// inherited by a fork), the rewind (GM, 2026-11-17: the send that
// carries it replaces its target GM turn -- physical truncation, the
// frozen-opening floor, the sheet records of the dead range reverting,
// the staleness guard on every send), the conflict channel's
// persistence (GM, 2026-11-18: conflicts stay in the contwin and are
// self-contained -- the offending emission quoted, because the block
// it answers strips from the view), the full-block protocol
// (whole-list status
// and agenda sets, absent = unchanged, the silent over-cap eviction,
// the view stamping at the canon point, the <model> display blocks,
// the emitted-<model> guard, GM prose pure), the state scan (the log
// is the one truth -- no db tier; the GM's block edit rides its turn
// as the override and composes over her newest blocks, the boundary
// state note rides the carry head), the session lifecycle
// (create dormant -> start -> live ->
// stop -> dormant -> re-run -> start -> the auto-send rule -> the
// start lint), the draft's memory.json (authored while draft, the
// start gate applies it, provenance once live), the OOC GM turn,
// non-owner 403s, fork, save-package,
// create-from-user-package, revocation, ownerless state, the
// reminder ride, variant
// literature (the random pick, the /table projection, the variance
// metric), the slidwin (move-at-stop, exactly-one-jsonl), and the
// whole-story /story render with no doubles.
// Prints PASS/FAIL per step; exit code carries the verdict.
//
// Expects a CLEAN state/ (no users) and a running --mock server:
// node server/main.mjs --mock
// node test/smoke.mjs
// Leaves its token + run ids in a temp file for restart-check.mjs.
// Clean up afterwards: Remove-Item state/, delete the smoke runs.
import { readFileSync, writeFileSync, appendFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
import { renderView } from '../server/session.mjs';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const BASE = process.env.RP_BASE ?? 'http://127.0.0.1:7350';
export const TOKEN_FILE = join(tmpdir(), 'tiny-worlds-smoke-token.txt');
let failures = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra !== '' ? ` -- ${extra}` : ''}`);
if (!cond) failures++;
};
const call = async (path, { method = 'GET', token, body } = {}) => {
const res = await fetch(`${BASE}/api${path}`, {
method,
headers: {
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
return { status: res.status, data };
};
const meta = (id) => JSON.parse(readFileSync(`${ROOT}/runs/${id}/run.json`, 'utf8'));
const jsonl = (id, n, f) => readFileSync(`${ROOT}/runs/${id}/sessions/${String(n)}/${f}`, 'utf8')
.trim().split('\n').filter(Boolean).map((l) => JSON.parse(l));
// 1. fresh deployment
let r = await call('/session');
ok('fresh session', r.status === 200 && r.data.user === null && r.data.fresh === true);
// 2. auth required
r = await call('/runs');
ok('runs need auth', r.status === 401);
// 3. bootstrap invite on disk
const code = readFileSync(`${ROOT}/state/bootstrap-invite.txt`, 'utf8').trim();
ok('bootstrap file', code.length === 24, code);
// 4. claim superuser
r = await call('/claim', { method: 'POST', body: { code, name: 'Op' } });
ok('claim op', r.status === 200 && r.data.user.superuser === true, r.data.error ?? '');
const op = r.data.token;
const opId = r.data.user.id;
// 5. invite reuse rejected
r = await call('/claim', { method: 'POST', body: { code, name: 'Sneak' } });
ok('spent invite rejected', r.status === 400 && /already used/.test(r.data.error));
// 6. mint invite -> second user
r = await call('/invites', { method: 'POST', token: op, body: {} });
ok('mint invite', r.status === 200 && r.data.code?.length === 24, r.data.error ?? r.data.code);
const inviteCode = r.data.code;
r = await call('/claim', { method: 'POST', body: { code: inviteCode, name: 'Ash' } });
ok('claim ash', r.status === 200 && r.data.user.superuser === false, r.data.error ?? '');
const ash = r.data.token;
const ashId = r.data.user.id;
// 7. ash cannot mint
r = await call('/invites', { method: 'POST', token: ash, body: {} });
ok('invite mint is op-only', r.status === 403);
// 7b. the model registry: a fresh deployment has no models, discovery
// is the op's two-step act, and model use is registry-gated
r = await call('/models', { token: op });
ok('fresh deployment: no registry', r.status === 200 && r.data.phase === 'none' && r.data.models.length === 0, JSON.stringify({ phase: r.data.phase }));
r = await call('/models/discover', { method: 'POST', token: ash, body: {} });
ok('discover is op-only', r.status === 403);
r = await call('/models/refine', { method: 'POST', token: op, body: {} });
ok('refine refuses before discovery', r.status === 409, r.data.error ?? '');
r = await call('/models/discover', { method: 'POST', token: op, body: {} });
ok('discover scrapes (no inference)', r.status === 200 && r.data.phase === 'preliminary', r.data.error ?? JSON.stringify(r.data));
r = await call('/models', { token: op });
ok('the preliminary list carries the scrape', r.data.phase === 'preliminary'
&& r.data.models.some((m) => m.id === 'mock' && m.status === 'unrefined')
&& r.data.models.every((m) => m.inference === undefined && m.label === undefined), JSON.stringify(r.data.models));
r = await call('/models/refine', { method: 'POST', token: op, body: {} });
ok('refine starts the job', r.status === 200 && r.data.state === 'running', r.data.error ?? JSON.stringify(r.data));
let reg = null;
for (let i = 0; i < 40; i++) {
reg = await call('/models', { token: op });
if (reg.data.job?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('refine applied', reg.data.job?.state === 'applied', JSON.stringify(reg.data.job ?? null));
ok('the refine meter closed its steps', reg.data.job?.steps?.total === 5 && reg.data.job?.steps?.done === 5,
JSON.stringify(reg.data.job?.steps ?? null));
ok('the refine receipt logged every battery and the curator',
(reg.data.job?.lines ?? []).length === 4
&& reg.data.job.lines.some((l) => l.includes('mock: reasoning deep'))
&& reg.data.job.lines.some((l) => l.includes('mock-cheap: reasoning standard'))
&& reg.data.job.lines.some((l) => l.includes('curator (mock-tie): curated')),
JSON.stringify(reg.data.job?.lines ?? null));
ok('the refined registry carries verdicts and curation', reg.data.phase === 'refined'
&& reg.data.models.some((m) => m.id === 'mock' && m.inference === true && m.reasoning === 'deep' && m.label === 'Mock' && m.family === 'mock')
&& reg.data.models.some((m) => m.id === 'mock-tie' && m.reasoning === 'deep' && m.label === 'Mock (tie)')
&& reg.data.models.some((m) => m.id === 'mock-cheap' && m.reasoning === 'standard'), JSON.stringify(reg.data.models));
ok('the effort probe: measured ladders and the max-mean defaults',
reg.data.models.some((m) => m.id === 'mock' && m.effortDefault === 'max' && m.efforts?.max === 500 && m.efforts?.none === 0)
&& reg.data.models.some((m) => m.id === 'mock-cheap' && m.effortDefault === 'high' && m.efforts?.max === undefined),
JSON.stringify(reg.data.models.filter((m) => m.efforts).map((m) => ({ id: m.id, effortDefault: m.effortDefault }))));
const regFile = JSON.parse(readFileSync(`${ROOT}/state/models.json`, 'utf8'));
ok('the pick rule: deepest reasoning wins, full ties settle sort-lex-pick-bottom',
regFile.defaults.player === 'mock-tie' && regFile.defaults.housekeeper === 'mock-tie', JSON.stringify(regFile.defaults));
const cfgModels = JSON.parse(readFileSync(`${ROOT}/server.json`, 'utf8')).models ?? {};
ok('the op\'s explicit config beats the registry default', reg.data.defaults.player === (cfgModels.player ?? regFile.defaults.player),
JSON.stringify({ api: reg.data.defaults.player, cfg: cfgModels.player ?? null }));
// 8. op creates a run -- dormant session one, memory.json waits for
// the start gate
r = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Smokina', name: 'Smoke Story' } });
ok('create run', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const runId = r.data.run?.id;
ok('owner stamped', meta(runId).owner === opId);
r = await call(`/runs/${runId}`, { token: op });
ok('born dormant', r.data.phase === 'dormant' && r.data.sessions === 1 && r.data.draft === true,
JSON.stringify({ phase: r.data.phase, sessions: r.data.sessions }));
ok('the draft holds no rings yet (memory.json waits for the start gate)', r.data.fill.a === 0 && r.data.fill.b === 0, JSON.stringify(r.data.fill));
r = await call(`/runs/${runId}/progress`, { token: op });
ok('the turn meter on a dormant run: idle, no scale', r.status === 200 && r.data.inFlight === false && r.data.scale === null,
JSON.stringify(r.data));
r = await call(`/runs/${runId}/files`, { token: op });
ok('the draft editor surface', r.data.files['carryover.jsonl']?.mode === 'rw' && r.data.files['memory.json']?.mode === 'rw'
&& r.data.files['handbook.md']?.mode === 'rw', JSON.stringify(Object.fromEntries(Object.entries(r.data.files).map(([k, v]) => [k, v.mode]))));
// 8b. the draft's starting memories: memory.json is authored material
// -- a save is a plain file write, and the start gate applies it
const memBefore = r.data.files['memory.json'].content;
const memParsed = JSON.parse(memBefore);
const memEdited = JSON.stringify({
...memParsed,
insert: [...memParsed.insert, { ring: 'a', type: 'fact', label: 'The smoke fact', detail: 'the draft edit landed', reason: 'the draft edit test' }],
}, null, 2) + '\n';
r = await call(`/runs/${runId}/files/memory.json`, { method: 'PUT', token: op, body: { content: memEdited } });
ok('memory.json saves while draft', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/files/memory.json`, { method: 'PUT', token: op, body: { content: '{ not json' } });
ok('a broken memory.json refuses at save', r.status === 400 && /JSON object/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${runId}/files/memory.json`, { method: 'PUT', token: op, body: { content: JSON.stringify({ session: '0', summary: 'bad on purpose', insert: [{ ring: 'x', type: 'fact', label: 'L', reason: 'r' }] }) } });
ok('a bad manifest still saves (the start gate judges it)', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('the start gate refuses the bad manifest', r.status === 422 && /insert\[0\]\.ring must be a\|b/.test(JSON.stringify(r.data.detail ?? {})),
JSON.stringify(r.data).slice(0, 160));
r = await call(`/runs/${runId}`, { token: op });
ok('the refused start landed nothing', r.data.phase === 'dormant' && r.data.draft === true, JSON.stringify({ phase: r.data.phase }));
r = await call(`/runs/${runId}/files/memory.json`, { method: 'PUT', token: op, body: { content: memEdited } });
ok('the good edit goes back in', r.status === 200, r.data.error ?? '');
// 9. start: lint, freeze, consume -- the carryover lands behind the
// bundle. It ends on her turn, so no auto-send: the table waits.
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start', r.status === 200 && r.data.session === 1 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data));
r = await call(`/runs/${runId}`, { token: op });
ok('live', r.data.phase === 'live' && r.data.open === true);
ok('the draft edit is what she starts with', r.data.fill.a === 5 && r.data.fill.b === 1, JSON.stringify(r.data.fill));
const filesLive = await call(`/runs/${runId}/files`, { token: op });
ok('memory.json is provenance once live', filesLive.data.files['memory.json']?.mode === 'ro', filesLive.data.files['memory.json']?.mode ?? 'missing');
ok('her authored blocks are the seed (the scan derives them)', JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","worried"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the opening renders on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /Modesty, decency or respect/.test(e.m.content ?? '')));
ok('the opening event is retired (her authored blocks are the seed)', r.data.entries.every((e) => e.t !== 'opening'), 'an opening event rode the log');
ok('the sigil expanded at start', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /Smokina was staring/.test(e.m.content ?? '')), 'a raw @PC reached the table');
// 10. the exchanges (mock: variant literature with per-variant status
// blocks, the ask, the whole-list sets, the silent eviction, the
// model guard, the mind)
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The tide comes in.*' } });
ok('gm turn -> variant literature', r.status === 200 && r.data.variants?.count === 2 && [0, 1].includes(r.data.variants.chosen), r.data.error ?? JSON.stringify(r.data.variants ?? null));
const pickedStatus = r.data.variants.chosen === 0 ? 'determined' : 'cautious';
r = await call(`/runs/${runId}`, { token: op });
ok("the picked variant's status applied", r.data.status.includes(pickedStatus), JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/session`, { token: op });
ok('raw session keeps the whole block', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /<variants>/.test(e.m.content ?? '')), 'no <variants> in the raw log');
const pickNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'pick');
ok('pick note logged (the metric)', !!pickNote && pickNote.count === 2 && [0, 1].includes(pickNote.chosen), JSON.stringify(pickNote ?? null));
const viaMsg = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && e.via);
ok('the request record rides the turn (resolved model + effective params, the measured effort default included)',
!!viaMsg && viaMsg.via.model === 'mock' && JSON.stringify(viaMsg.via.params) === '{"reasoning_effort":"max"}', JSON.stringify(viaMsg?.via ?? null));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the table carries only the picked variant', r.data.entries.every((e) => e.t !== 'msg' || e.m.role !== 'assistant' || !/<\/?variants?>/.test(e.m.content ?? '')), 'variant syntax leaked into the table');
ok('the picked turn is her turn on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && e.m.content.includes(`<status>cuffed, belted, naked, barefoot, ${pickedStatus}</status>`)), pickedStatus);
ok('the table drops thinking', r.data.entries.every((e) => e.m?.reasoning_content === undefined));
ok('the variance metric', r.data.variance.picks === 1 && r.data.variance.offered === 2 && r.data.variance.maxVariants === 2, JSON.stringify(r.data.variance));
r = await call(`/runs/${runId}/progress`, { token: op });
ok('the turn meter reads idle between turns, scaled by her history',
r.status === 200 && r.data.inFlight === false && r.data.scaleKind === 'history' && typeof r.data.scale === 'number' && r.data.scale > 0,
JSON.stringify(r.data));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She sets off.*' } });
ok('gm turn -> pending ask', r.status === 200 && !!r.data.pendingAsk, r.data.error ?? r.data.pendingAsk);
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'yes, clear toward the bow' } });
ok('ask answered', r.status === 200, r.data.error ?? '');
// 10b. the full-block protocol: a present block is a whole-list SET
// (absent = unchanged, never blank); an over-cap agenda evicts from
// the bottom silently -- to her; the note shows the GM
r = await call(`/runs/${runId}`, { token: op });
ok('the agenda block sets the whole list', JSON.stringify(r.data.agenda) === '["find fresh water","signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
ok('the status block sets the whole list', JSON.stringify(r.data.status.slice(-2)) === '["settled","curious about the clicking"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Evening comes.*' } });
ok('a restated agenda replaces the list', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('agenda after restatement', JSON.stringify(r.data.agenda) === '["signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Night falls.*' } });
ok('the over-cap turn is clean (eviction is silent)', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
r = await call(`/runs/${runId}`, { token: op });
ok('an over-cap agenda keeps the top five', JSON.stringify(r.data.agenda) === '["item one","item two","item three","item four","item five"]', JSON.stringify(r.data.agenda));
ok('the omitted status means unchanged',
JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","settled","curious about the clicking"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/session`, { token: op });
const evictNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'agenda' && e.evicted?.length);
ok('the eviction is visible to the GM (the note)',
!!evictNote && JSON.stringify(evictNote.evicted) === '["item six","item seven"]', JSON.stringify(evictNote ?? null));
ok('the log keeps all seven items (raw is the only place they live)',
r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /- item six\n- item seven/.test(e.m.content ?? '')), 'her emission was capped in the log');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Dawn breaks.*' } });
ok('next gm turn is clean', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
// 10c. the <model> guard: display-only -- the conflict points at
// <mind>, the heal restates plain, and the turn heals in the same turn
r = await call(`/runs/${runId}/session`, { token: op });
const guardConflict = r.data.entries.find((e) => e.conflictOnly && /read-only display/.test(e.m.content));
ok('an emitted <model> block conflicts', !!guardConflict, guardConflict?.m.content ?? 'no conflict');
ok('the guard conflict healed in the same turn',
!!guardConflict && r.data.entries.slice(r.data.entries.indexOf(guardConflict)).some((e) => e.t === 'msg' && e.m.role === 'assistant' && /watching the water/.test(e.m.content ?? '')),
'no heal');
// 10d. the mind verb: <mind>{"temperature": 1.2}</mind> sets her
// sampling for her NEXT turn (one-shot, JSON, max_tokens excluded)
r = await call(`/runs/${runId}/session`, { token: op });
const mindSetter = r.data.entries.filter((e) => e.t === 'msg' && e.m.role === 'assistant').find((e) => /race ahead of her feet/.test(e.m.content ?? ''));
ok('the mind verb: the setting turn does not ride at it (next turn only)',
mindSetter?.via?.params?.temperature === undefined, JSON.stringify(mindSetter?.via ?? null));
ok('the mind verb: the note records the statement',
r.data.entries.some((e) => e.t === 'note' && e.kind === 'mind' && e.params?.temperature === 1.2), 'no mind note');
const guardTurn = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && /squints at the horizon/.test(e.m.content ?? ''));
ok('the mind verb: her next turn rides at the stated mind',
guardTurn?.via?.params?.temperature === 1.2, JSON.stringify(guardTurn?.via ?? null));
const lastGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
ok('no conflict attached to the GM turn', !/<conflict>/.test(lastGm.m.content), lastGm.m.content.slice(-100));
ok('GM prose goes pure', !/<\/?(status|agenda)>/.test(lastGm.m.content), lastGm.m.content.slice(-120));
r = await call(`/runs/${runId}/status`, { method: 'POST', token: op, body: { items: [] } });
ok('the out-of-band status route is retired', r.status === 404, `${r.status}`);
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: op, body: { items: [] } });
ok('the out-of-band agenda route is retired', r.status === 404, `${r.status}`);
// 10d. an OOC GM turn: the paren channel carries no cache blocks -- an
// OOC exchange does not move her state, the next IC turn re-carries them
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( mock GM checking in )' } });
ok('ooc gm turn sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
const oocGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
ok('the ooc turn carries no cache blocks', /\( mock GM checking in \)/.test(oocGm.m.content) && !/<\/?(status|agenda)>/.test(oocGm.m.content), oocGm.m.content.slice(-90));
// the OOC reply states an out-of-bounds mind: the conflict names the
// range, the heal restates -- and the turn after the riding turn is
// back at defaults (one-shot)
const scatterTurn = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && /thoughts scatter/.test(e.m.content ?? ''));
ok('the mind is one-shot (the turn after the riding turn is at defaults)',
scatterTurn?.via?.params?.temperature === undefined, JSON.stringify(scatterTurn?.via ?? null));
const mindConflict = r.data.entries.find((e) => e.conflictOnly && /must be at least 0 and up to 2/.test(e.m.content));
ok('an out-of-bounds mind conflicts with the range named', !!mindConflict, mindConflict?.m.content ?? 'no conflict');
ok('the mind conflict healed in-turn',
!!mindConflict && r.data.entries.slice(r.data.entries.indexOf(mindConflict)).some((e) => e.t === 'note' && e.kind === 'mind' && e.params?.temperature === 1.2),
'no healed restatement');
ok('the mind statements number two (the refused one never stashed)',
r.data.entries.filter((e) => e.t === 'note' && e.kind === 'mind').length === 2, 'wrong count');
// 10e. the view policy (the full-block protocol): render the session
// log through the same renderer the loop uses and assert the stamping
const view1 = renderView({ lines: jsonl(runId, 1, 'log.jsonl'), pendingAsk: null });
const her1 = view1.filter((m) => m.role === 'assistant');
const lastHer = [...her1].reverse().find((m) => typeof m.content === 'string' && /breathes until the numbers behave/.test(m.content));
ok('the view stamps the newest status and agenda at her latest turn',
!!lastHer && /<status>cuffed, belted, naked, barefoot, settled, curious about the clicking<\/status>/.test(lastHer.content)
&& /<agenda>\n- item one\n- item two\n- item three\n- item four\n- item five\n<\/agenda>/.test(lastHer.content),
(lastHer?.content ?? 'none').slice(-260));
ok('the capped agenda is what derives (the eviction stays silent to her)',
!!lastHer && (lastHer.content.match(/<agenda>/g) ?? []).length === 1 && !/item (six|seven)/.test(lastHer.content),
'the stamp leaked the over-cap items');
ok('superseded copies strip from the view',
her1.filter((m) => m !== lastHer).every((m) => !/<\/?(status|agenda)>/.test(String(m.content ?? ''))), '');
ok('her mind tags are write-only (stripped from the view)',
her1.every((m) => !/<mind>/.test(String(m.content ?? ''))), '');
ok('an emitted <model> block strips from the view',
her1.every((m) => !/\n<model>/.test(String(m.content ?? ''))), '');
const viewConflicts = view1.filter((m) => m.role === 'user' && /^<conflict>/.test(String(m.content ?? '')));
ok('past conflicts stay in the context (a mistake remains visible, GM 2026-11-18)',
viewConflicts.length === 2, `${viewConflicts.length} render`);
ok('a conflict describes its problem in full (the stripped emission quoted)',
viewConflicts.some((m) => /yours said: \{"temperature": 0\.1\}/.test(String(m.content ?? ''))), '');
ok('each past turn carries its <model> block when params rode',
her1.some((m) => String(m.content ?? '').startsWith('<model>{"temperature":1.2}</model>')), '');
ok('the <model> block hides the effort knob (not her call)',
her1.every((m) => !/reasoning_effort/.test(String(m.content ?? ''))), 'the effort leaked into her display');
ok('GM prose goes pure in the view',
view1.filter((m) => m.role === 'user').every((m) => !/<\/?(status|agenda)>/.test(String(m.content ?? ''))), '');
// 10c. the reminder: a system chunk after every GM turn, one live copy
r = await call(`/runs/${runId}/session`, { token: op });
const reminders = r.data.entries.filter((e) => e.reminder);
ok('reminder rode every GM turn', reminders.length === 6 && reminders.every((x) => x.m.role === 'system'), `${reminders.length} in the log`);
ok('reminder carries the turn protocol', /How to compose your turn/i.test(reminders[0]?.m.content ?? ''), (reminders[0]?.m.content ?? '').slice(0, 60));
r = await call(`/runs/${runId}/status`, { token: op });
ok('status endpoint carries both', Array.isArray(r.data.status) && Array.isArray(r.data.agenda), JSON.stringify(r.data).slice(0, 120));
// 11. ash in another's run: the story is the reading surface, all
// else is the owner's
r = await call(`/runs/${runId}`, { token: ash });
ok('ash detail 403', r.status === 403);
r = await call(`/runs/${runId}/table`, { token: ash });
ok('ash table 403', r.status === 403);
r = await call(`/runs/${runId}/session`, { token: ash });
ok('ash raw session 403', r.status === 403);
r = await call(`/runs/${runId}/carryover`, { token: ash });
ok('ash carryover 403', r.status === 403);
r = await call(`/runs/${runId}/files`, { token: ash });
ok('ash files 403', r.status === 403);
r = await call(`/runs/${runId}/status`, { token: ash });
ok('ash status 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { token: ash });
ok('ash notes 403 (#28 overturned)', r.status === 403);
r = await call(`/runs/${runId}/housekeeping`, { token: ash });
ok('ash housekeeping state 403', r.status === 403);
r = await call(`/runs/${runId}/housekeeping/log`, { token: ash });
ok('ash housekeeping log 403', r.status === 403);
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: ash, body: { line: 'hi' } });
ok('ash turn 403', r.status === 403);
r = await call(`/runs/${runId}/progress`, { token: ash });
ok('ash progress 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { method: 'PUT', token: ash, body: { content: 'mine' } });
ok('ash notes write 403', r.status === 403);
r = await call(`/runs/${runId}/story`, { token: ash });
ok('ash reads the story', r.status === 200 && !!r.data.display && Array.isArray(r.data.sessions), r.data.error ?? '');
r = await call(`/runs/${runId}/housekeeping/replay`, { method: 'POST', token: ash, body: {} });
ok('ash replay 403 (spends a call)', r.status === 403);
// 12. ash forks
r = await call(`/runs/${runId}/fork`, { method: 'POST', token: ash, body: {} });
ok('fork', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const forkId = r.data.run;
const fm = meta(forkId);
ok('fork owner + forked stamp', fm.owner === ashId && Number.isInteger(fm.forked) && fm.created === meta(runId).created,
`owner=${fm.owner} forked=${fm.forked} created=${fm.created}`);
r = await call(`/runs/${forkId}`, { token: ash });
ok('fork live session carried over', r.status === 200 && r.data.open === true, r.data.error ?? '');
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She looks around.*' } });
ok('ash turns on the fork', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${forkId}/session`, { token: ash });
const forkReply = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
ok('the fork inherits her unconsumed mind', forkReply?.via?.params?.temperature === 1.2, JSON.stringify(forkReply?.via ?? null));
// 10f. the GM's block edit rides its turn (the override): the log
// records the field, the composition overwrites her newest blocks
// with it, the log keeps her words verbatim, and the model never
// sees an override as an act -- only as state
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*A cooler wind picks up.*', agenda: ['climb the ridge', 'rest'] } });
ok('the override turn sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
const ovrTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && e.override);
ok('the override rides its GM turn as the record',
!!ovrTurn && JSON.stringify(ovrTurn.override.agenda) === '["climb the ridge","rest"]' && ovrTurn.override.status === undefined,
JSON.stringify(ovrTurn?.override ?? null));
ok('the override turn\'s prose stays pure', !/<\/?(status|agenda)>/.test(String(ovrTurn?.m.content ?? '')), String(ovrTurn?.m.content ?? '').slice(-80));
r = await call(`/runs/${runId}/status`, { token: op });
ok('the composed agenda is the override', JSON.stringify(r.data.agenda) === '["climb the ridge","rest"]', JSON.stringify(r.data.agenda));
ok('the untouched status derives unchanged',
JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","settled","curious about the clicking"]', JSON.stringify(r.data.status));
const view1b = renderView({ lines: jsonl(runId, 1, 'log.jsonl'), pendingAsk: null });
const lastHerB = [...view1b].reverse().find((m) => m.role === 'assistant' && typeof m.content === 'string' && m.content.trim());
ok('the composition stamps the override at her canon point',
/<agenda>\n- climb the ridge\n- rest\n<\/agenda>/.test(lastHerB.content), String(lastHerB.content).slice(-180));
ok('the log keeps her words verbatim (the over-cap emission is intact)',
jsonl(runId, 1, 'log.jsonl').some((e) => e.t === 'msg' && e.m.role === 'assistant' && /- item six\n- item seven/.test(e.m.content ?? '')),
'her emission was rewritten');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc with an edit )', status: ['x'] } });
ok('an override cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? '');
// 12b. models: per-run overrides of the deployment defaults, the
// registry-gated picks, and the named sampling knobs
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
ok('set models', r.status === 200 && r.data.models.player === 'mock' && r.data.models.housekeeper === 'mock-cheap', JSON.stringify(r.data));
ok('models stamped in run.json', meta(forkId).models?.player === 'mock' && meta(forkId).models?.housekeeper === 'mock-cheap');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: 0.7, max_tokens: 4096 } } } });
ok('set knobs', r.status === 200 && r.data.params.player?.temperature === 0.7 && r.data.params.player?.max_tokens === 4096, JSON.stringify(r.data));
ok('knobs stamped in run.json', meta(forkId).params?.player?.temperature === 0.7);
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { temperature: null } } } });
ok('a null knob clears', r.status === 200 && r.data.params.player?.temperature === undefined && r.data.params.player?.max_tokens === 4096, JSON.stringify(r.data.params));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'low' } } } });
ok('the effort knob sets', r.status === 200 && r.data.params.player?.reasoning_effort === 'low', JSON.stringify(r.data.params));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'turbo' } } } });
ok('a bogus effort level refuses', r.status === 400 && /must be one of/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: null } } } });
ok('a null effort clears back to the measured default', r.status === 200 && r.data.params.player?.reasoning_effort === undefined, JSON.stringify(r.data.params));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { reasoning_effort: 'low' } } } });
ok('the effort override stays for the turn', r.status === 200 && r.data.params.player?.reasoning_effort === 'low', JSON.stringify(r.data.params));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { params: { player: { vibes: 1 } } } });
ok('an unknown knob refuses', r.status === 400 && /unknown knob/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'not-a-model' } });
ok('a model outside the registry refuses', r.status === 400 && /registry/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
ok('clear a role back to default', r.status === 200 && r.data.models.housekeeper === undefined && r.data.models.player === 'mock', JSON.stringify(r.data));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: 'x' } });
ok('model set is owner-only', r.status === 403);
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
ok('unknown role rejected', r.status === 400);
r = await call(`/runs/${forkId}`, { token: ash });
ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !!r.data.run.modelDefaults?.player && r.data.run.params?.player?.max_tokens === 4096 && !!r.data.run.paramDefaults, JSON.stringify(r.data.run.models));
// a turn on the knob-carrying run: the recording proves what was
// sent -- the run's knob under the mind layer (her restated mind
// rides over the run layer, the layering the tunables round built)
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She keeps watch.*' } });
ok('gm turn on the fork (post-knobs)', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${forkId}/session`, { token: ash });
const viaTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
ok('the recorded request carries the run\'s knobs under the mind layer',
!!viaTurn?.via && viaTurn.via.model === 'mock' && viaTurn.via.params.max_tokens === 4096 && viaTurn.via.params.temperature === 1.2
&& viaTurn.via.params.reasoning_effort === 'low',
JSON.stringify(viaTurn?.via ?? null));
r = await call('/models', { token: ash });
ok('model listing (the registry)', r.status === 200 && r.data.phase === 'refined' && r.data.models.some((m) => m.id === 'mock' && m.label === 'Mock'), JSON.stringify(r.data.phase));
// 13. ash saves a draft as a package (save-package is a draft act --
// the played-run refusal is checked at the end)
r = await call('/runs', { method: 'POST', token: ash, body: { package: 'la-caramba', pc: 'Ashling', name: 'Ash Draft' } });
ok('ash creates a draft', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const draftId = r.data.run?.id;
r = await call('/packages', { method: 'POST', token: ash, body: { from: draftId, name: 'Ash Pack' } });
ok('save-package', r.status === 200 && !!r.data.package?.id, r.data.error ?? r.data.package?.id);
const pkgId = r.data.package?.id;
r = await call('/packages', { token: op });
const saved = r.data.find((p) => p.name === pkgId);
ok('package listed with origin', !!saved && saved.origin === 'user' && saved.ownerName === 'Ash'
&& saved.pc === null && saved.display === 'Ash Pack', JSON.stringify(saved));
// 14. op creates a run from the user package
r = await call('/runs', { method: 'POST', token: op, body: { package: pkgId, pc: 'Secondina', name: 'Second Story' } });
ok('create from user package', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const secondId = r.data.run?.id;
// 15. op revokes ash -- identity destroyed, data stays
r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} });
ok('revoke ash', r.status === 200, r.data.error ?? '');
r = await call('/runs', { token: ash });
ok('ash token dead', r.status === 401);
r = await call('/runs', { token: op });
const goneFork = Array.isArray(r.data) ? r.data.find((x) => x.id === forkId) : null;
ok('fork now ownerless, session closed', !!goneFork && goneFork.owner === null && goneFork.ownerName === null && goneFork.open === false,
JSON.stringify(goneFork)); // the detail it used to ride is owner-only now -- the list carries the facts
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: op, body: { line: 'x' } });
ok('ownerless turn 403 even for op', r.status === 403 && /ownerless/.test(r.data.error));
r = await call('/packages', { token: op });
const saved2 = r.data.find((p) => p.name === pkgId);
ok('user package survives, ownerless', !!saved2 && saved2.owner === null && saved2.ownerName === null && saved2.display === 'Ash Pack',
JSON.stringify(saved2));
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const reforkId = r.data.run;
ok('fork carries the models', meta(reforkId).models?.player === 'mock');
// 16. users list, self-revoke refused
r = await call('/users', { token: op });
ok('users list', r.status === 200 && r.data.users.length === 1 && r.data.users[0].id === opId);
r = await call(`/users/${opId}/revoke`, { method: 'POST', token: op, body: {} });
ok('self-revoke refused', r.status === 409);
// 17. stop: the tail MOVES into dormant session 2 (the slidwin),
// housekeeping runs over what remains, the re-run rebases, start
// consumes the carry behind the bundle
const stopAndSettle = async (label) => {
r = await call(`/runs/${runId}/housekeeping`, { method: 'POST', token: op, body: {} });
ok(`${label} triggered`, r.status === 200 && r.data.state === 'running', r.data.error ?? JSON.stringify(r.data));
let hk = null;
for (let i = 0; i < 40; i++) {
hk = await call(`/runs/${runId}/housekeeping`, { token: op });
if (hk.data.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok(`${label} applied`, hk.data.state === 'applied', JSON.stringify(hk.data));
return hk;
};
await stopAndSettle('stop (session 1)');
r = await call(`/runs/${runId}`, { token: op });
ok('dormant after stop', r.data.phase === 'dormant' && r.data.sessions === 2 && r.data.ready === true,
JSON.stringify({ phase: r.data.phase, sessions: r.data.sessions, ready: r.data.ready }));
r = await call(`/runs/${runId}/housekeeping`, { token: op });
ok('the job names the pass and the target', r.data.state === 'applied' && r.data.session === 1 && r.data.target === 2, JSON.stringify(r.data));
r = await call(`/runs/${runId}/housekeeping/log`, { token: op });
ok('the pass log names its model', r.status === 200 && /housekeeper: mock/.test(r.data.content), r.status === 200 ? r.data.content.split('\n').slice(0, 3).join(' / ') : r.data.error);
// the move: each line exists in exactly one jsonl, ever
const log1 = jsonl(runId, 1, 'log.jsonl');
const carry2 = jsonl(runId, 2, 'carryover.jsonl');
ok('the tail moved out of session 1', carry2.length > 0 && log1.every((e) => !carry2.some((c) => JSON.stringify(c) === JSON.stringify(e))),
`${carry2.length} carried lines`);
ok('the boundary state note rides the carry head',
carry2[0]?.t === 'note' && carry2[0]?.kind === 'state'
&& JSON.stringify(carry2[0]?.agenda) === '["climb the ridge","rest"]'
&& JSON.stringify(carry2[0]?.status) === '["cuffed","belted","naked","barefoot","settled","curious about the clicking"]',
JSON.stringify(carry2[0] ?? null));
ok('the carry holds whole exchanges', carry2[1]?.t === 'msg' && carry2[1]?.m?.role === 'user' && !carry2[1]?.conflictOnly
&& carry2.some((e) => e.t === 'msg' && e.m.role === 'assistant'), carry2[1]?.t ?? 'nothing carried');
ok('the carry ends on her turn (no auto-send)', [...carry2].reverse().find((e) => e.t === 'msg' && !e.reminder)?.m?.role === 'assistant');
ok('no markers anywhere in the logs', log1.concat(carry2).every((e) => e.carried === undefined));
r = await call(`/runs/${runId}/carryover`, { token: op });
ok('the dormant preview renders the carry', r.status === 200 && r.data.session === 2 && r.data.ends === 'player' && r.data.entries.length === carry2.length,
JSON.stringify({ ends: r.data.ends, n: r.data.entries?.length }));
// the story reads whole, through dormancy, with no doubles
r = await call(`/runs/${runId}/story`, { token: op });
const gmTexts = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'gm').map((t) => t.text));
ok('the story has every GM turn exactly once', gmTexts.length === 6 && new Set(gmTexts).size === 6, `${gmTexts.length} gm turns across ${r.data.sessions.length} sessions`);
ok('the story carries no OOC', r.data.sessions.every((s) => s.turns.every((t) => !/^\(/.test(t.text) && !/\( mock GM checking in \)/.test(t.text))), 'OOC leaked into the story');
ok('the story reads the dormant carryover at the live edge', r.data.sessions.some((s) => s.turns.length >= 10));
const storyPlayer = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'player').map((t) => t.text));
ok('the story strips the verbs', storyPlayer.every((t) => !/<\/?(lost|gained|add|drop|mind|status|agenda|model|sheet)>/.test(t)), '');
ok('the story carries no variant syntax', storyPlayer.every((t) => !/<\/?variants?>/.test(t)), '');
ok('the story strips the rides from GM prose', r.data.sessions.every((s) => s.turns.every((t) => t.who !== 'gm' || !/<\/?(status|agenda)>/.test(t.text))), '');
// the re-run: a fresh pass, rebased -- never double-applying
await stopAndSettle('re-run housekeeping (session 1)');
r = await call(`/runs/${runId}`, { token: op });
ok('still dormant, still ready', r.data.phase === 'dormant' && r.data.sessions === 2 && r.data.ready === true);
r = await call(`/runs/${runId}`, { token: op });
ok('the rebase kept the rings single-applied', r.data.fill.b === 2 && r.data.fill.a === 5, JSON.stringify(r.data.fill)); // 4 packaged + 1 draft edit + 1 inserted, once
// start session 2: the carry lands behind the bundle
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start session 2', r.status === 200 && r.data.session === 2 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the carry landed behind the bundle', r.data.entries.some((e) => e.t === 'bundle' && e.part === 'ring-a')
&& r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /breathes until the numbers behave/.test(e.m.content ?? '')));
ok('the frozen bundle is session 2\'s own', r.data.entries.some((e) => e.t === 'bundle') && r.data.session === 2);
r = await call(`/runs/${runId}`, { token: op });
ok('her agenda carried across the stop', r.data.agenda.includes('climb the ridge'), JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She wakes on the sand.*' } });
ok('session 2 plays on', r.status === 200 && !!r.data.player, r.data.error ?? '');
// her last stated mind, unconsumed in the carried log, rode that turn
r = await call(`/runs/${runId}/session`, { token: op });
const s2Reply = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
ok('an unconsumed mind carries across the session boundary',
s2Reply?.via?.params?.temperature === 1.2, JSON.stringify(s2Reply?.via ?? null));
// 18. the auto-send rule: stop again, hand-append a GM turn to the
// carryover (the future editor's one edit), start -- the turn fires
await stopAndSettle('stop (session 2)');
r = await call(`/runs/${runId}`, { token: op });
ok('session 3 dormant', r.data.phase === 'dormant' && r.data.sessions === 3);
appendFileSync(`${ROOT}/runs/${runId}/sessions/3/carryover.jsonl`,
JSON.stringify({ t: 'msg', m: { role: 'user', content: '*A sail on the horizon.*' } }) + '\n');
r = await call(`/runs/${runId}/carryover`, { token: op });
ok('the carryover now ends on a GM turn', r.data.ends === 'gm', r.data.ends ?? 'none');
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start auto-sends the GM-ending carryover', r.status === 200 && r.data.autoSend === true && !!r.data.player,
r.data.error ?? JSON.stringify({ autoSend: r.data.autoSend, player: r.data.player?.slice(0, 40) }));
r = await call(`/runs/${runId}/session`, { token: op });
ok('her reply answered the carried cue', [...r.data.entries].reverse().find((e) => e.t === 'msg' && !e.reminder)?.m?.role === 'assistant');
const s3Reply = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
ok('the mind is one-shot (spent by the turn that rode it)',
s3Reply?.via?.params?.temperature === undefined, JSON.stringify(s3Reply?.via ?? null));
// 19. the start lint: a malformed carryover refuses, nothing starts
await stopAndSettle('stop (session 3)');
writeFileSync(`${ROOT}/runs/${runId}/sessions/4/carryover.jsonl`,
JSON.stringify({ t: 'tool', m: { role: 'tool', tool_call_id: 'x', content: 'nope' } }) + '\n');
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('the start refuses an orphaned tool event', r.status === 422 && /conversation events only|orphaned tool result/.test(r.data.detail?.errors?.join(' ') ?? r.data.error ?? ''),
JSON.stringify(r.data.detail?.errors ?? r.data.error));
r = await call(`/runs/${runId}`, { token: op });
ok('nothing started', r.data.phase === 'dormant' && r.data.session === null);
// 20. the deliberate-skip override: session 4 is ready, but flip it
// back by hand and the guard demands the override
const s4meta = `${ROOT}/runs/${runId}/sessions/4/session.json`;
writeFileSync(s4meta, JSON.stringify({ phase: 'dormant', ready: false }, null, 2) + '\n');
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('the unhousekept guard refuses', r.status === 409 && /never housekept/.test(r.data.error) && !!r.data.detail?.hint, r.data.error ?? '');
writeFileSync(s4meta, JSON.stringify({ phase: 'dormant', ready: true }, null, 2) + '\n');
writeFileSync(`${ROOT}/runs/${runId}/sessions/4/carryover.jsonl`,
JSON.stringify({ t: 'msg', m: { role: 'assistant', content: '*She watches the sail.*' } }) + '\n');
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start session 4 after the fix', r.status === 200 && r.data.session === 4, r.data.error ?? '');
// 21. save-package is a draft act: a played run refuses
r = await call('/packages', { method: 'POST', token: op, body: { from: runId, name: 'Nope' } });
ok('save-package refuses a played run', r.status === 400 && /draft act/.test(r.data.error), r.data.error ?? '');
// 22. GM-input expansion: strict at ingestion, the refused line hands back
r = await call(`/runs/${runId}/session`, { token: op });
const beforeCount = r.data.entries.length;
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: 'she mutters $Bogus under her breath' } });
ok('an unresolved $var refuses the turn', r.status === 400 && /unresolved token/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
ok('the refused line never landed', r.data.entries.length === beforeCount, `${beforeCount} -> ${r.data.entries.length}`);
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She says her own name out loud: @PC.*' } });
ok('a live turn with a sigil sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
const liveGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
ok('the log records the expanded line', /name out loud: Smokina/.test(String(liveGm?.m.content ?? '')) && !/@PC\b/.test(String(liveGm?.m.content ?? '')), String(liveGm?.m.content ?? '').slice(0, 90));
// 23. the sheet (GM, 2026-11-17): the GM's ledger of arbitrated run
// state -- records ride GM turns newest-wins, render as their own
// authoritative chunk (never a stamp at her canon point), cross the
// boundary on the state note, and stay read-only for her (the guard)
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger opens.*', sheet: { gp: 10, bp: 0 } } });
ok('a turn with a sheet record sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('the scan derives the sheet newest-wins', JSON.stringify(r.data.sheet) === '{"gp":10,"bp":0}', JSON.stringify(r.data.sheet));
// session 4's log starts the script over, so this turn lands on the
// script's ask position -- answer it, then the view asserts (pairing
// must be whole for renderView)
if (r.data.pendingAsk) {
const preAsk = await call(`/runs/${runId}/session`, { token: op });
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'clear enough', expect: preAsk.data.entries.length } });
ok('the sheet battery answers the script ask (a fresh expect passes)', r.status === 200, r.data.error ?? '');
}
{
const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null });
const chunk = [...view].reverse().find((m) => m.role === 'system' && /<sheet>/.test(String(m.content)));
ok('the sheet renders as its own authoritative chunk at the freshest end',
!!chunk && chunk.content === '<sheet>{"gp":10,"bp":0}</sheet>', chunk?.content ?? 'no chunk');
ok('the sheet chunk is the one live copy',
view.filter((m) => m.role === 'system' && String(m.content ?? '').startsWith('<sheet>')).length === 1, '');
}
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger moves.*', sheet: { gp: 7 } } });
ok('a second sheet record sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('a sheet record is a whole set (absent key dropped, never kept)', JSON.stringify(r.data.sheet) === '{"gp":7}', JSON.stringify(r.data.sheet));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc sheet test', sheet: { gp: 1 } } });
ok('a sheet record cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No ledger here.*', sheet: 'not an object' } });
ok('a malformed sheet refuses the turn', r.status === 400 && /JSON object/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('the refused turns landed nothing (the sheet stands)', JSON.stringify(r.data.sheet) === '{"gp":7}', JSON.stringify(r.data.sheet));
// the guard: she emits a <sheet> -- display-only, the conflict points
// at prose, the heal completes the turn, and her emission never applies
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She eyes the floating numbers.*' } });
ok('the sheet-guard turn completes via the heal', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
ok('an emitted <sheet> conflicts with the pointer at prose',
r.data.entries.some((e) => e.t === 'msg' && e.conflictOnly && /GM's ledger -- propose changes in prose/.test(String(e.m.content ?? ''))),
'no conflict found');
ok('the log keeps her emitted sheet verbatim (the raw surface)',
r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /<sheet>\{"gp": 99\}<\/sheet>/.test(String(e.m.content ?? ''))), 'her emission was rewritten');
ok('her emitted sheet never applies (the scan holds the GM\'s record)',
JSON.stringify((await call(`/runs/${runId}`, { token: op })).data.sheet) === '{"gp":7}', '');
{
const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null });
ok('the view strips her emitted sheet (the chunk alone carries it)',
view.every((m) => m.role !== 'assistant' || !/<sheet>/.test(String(m.content ?? ''))), 'her emission rode the view');
const sheetConf = view.find((m) => m.role === 'user' && /GM's ledger/.test(String(m.content ?? '')));
ok('the sheet guard quotes her emission (self-contained)',
!!sheetConf && /yours said: \{"gp": 99\}/.test(String(sheetConf?.content ?? '')), String(sheetConf?.content ?? 'no conflict in the view'));
}
r = await call(`/runs/${runId}/story`, { token: op });
ok('the story strips her emitted sheet',
r.data.sessions.every((s) => s.turns.every((t) => !/<\/?sheet>/.test(t.text))), 'leaked into the story');
// the empty ledger is live, not absent: {} renders its chunk
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The ledger empties.*', sheet: {} } });
ok('an empty sheet record sends (a deliberate empty ledger)', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('the empty ledger derives as itself', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet));
{
const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null });
const chunk = [...view].reverse().find((m) => m.role === 'system' && /<sheet>/.test(String(m.content)));
ok('the empty ledger renders its chunk', chunk?.content === '<sheet>{}</sheet>', chunk?.content ?? 'no chunk');
}
// the boundary: the note carries the sheet, the new session derives it
await stopAndSettle('stop (session 4)');
{
const carry5 = jsonl(runId, 5, 'carryover.jsonl');
ok('the boundary note carries the sheet', carry5[0]?.t === 'note' && carry5[0]?.kind === 'state' && JSON.stringify(carry5[0]?.sheet) === '{}', JSON.stringify(carry5[0] ?? null));
}
r = await call(`/runs/${runId}`, { token: op });
ok('the dormant read derives the sheet (the note is the live edge)', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet));
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start session 5', r.status === 200 && r.data.session === 5 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data));
r = await call(`/runs/${runId}`, { token: op });
ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JSON.stringify(r.data.sheet) === '{}', JSON.stringify(r.data.sheet));
{
const view = renderView({ lines: jsonl(runId, 5, 'log.jsonl'), pendingAsk: null });
const chunk = [...view].reverse().find((m) => m.role === 'system' && /<sheet>/.test(String(m.content)));
ok('session 5 renders the sheet chunk from the carried note', chunk?.content === '<sheet>{}</sheet>', chunk?.content ?? 'no chunk');
}
// 24. the rewind (GM, 2026-11-17): the GM's take-back. The send that
// carries rewind replaces the target GM turn -- the target and
// everything after it leave the log (physical truncation; fork is the
// preservation story). The floor is the start marker (the frozen
// opening), and every send guards against a stale view via expect.
{
// the floor marker rides session 5's log, after the carry
const s5 = jsonl(runId, 5, 'log.jsonl');
const marker = s5.map((e, i) => (e.t === 'note' && e.kind === 'start' ? i : -1)).filter((i) => i >= 0).pop();
ok('the start marker rides the log (the rewind floor)', marker != null && marker >= 0, String(marker ?? 'none'));
// two turns with ledger records: the rewind will revert the second
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery one.*', sheet: { rb: 1 } } });
ok('rewind battery: turn one sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery two.*', sheet: { rb: 2 } } });
ok('rewind battery: turn two sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('rewind battery: the second record leads', JSON.stringify(r.data.sheet) === '{"rb":2}', JSON.stringify(r.data.sheet));
const now = await call(`/runs/${runId}/session`, { token: op });
const len = now.data.entries.length;
const target = now.data.entries.findIndex((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly && /Rewind battery one\./.test(String(e.m.content ?? '')));
ok('the target GM turn is addressed by log index', target >= 0, String(target));
// the staleness guard: a wrong expect refuses before anything rides
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Stale.*', expect: len - 1 } });
ok('a stale expect refuses the send', r.status === 409 && /stale/.test(r.data.error), r.data.error ?? '');
// her turn is not a valid target
const herIdx = now.data.entries.map((e, i) => (e.t === 'msg' && e.m.role === 'assistant' && !e.m.tool_calls?.length ? i : -1)).filter((i) => i >= 0).pop();
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No.*', rewind: herIdx, expect: len } });
ok('her turn is not a rewind target', r.status === 400 && /your turns/.test(r.data.error), r.data.error ?? '');
// the frozen opening: a carried GM turn (above the marker) refuses
const carriedGm = now.data.entries.findIndex((e, i) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly && i < (marker ?? 0));
ok('the battery found a carried GM turn above the floor', carriedGm >= 0, 'none before the marker');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No.*', rewind: carriedGm, expect: len } });
ok('the frozen opening refuses the rewind', r.status === 400 && /frozen/.test(r.data.error), r.data.error ?? '');
// the refusals landed nothing
r = await call(`/runs/${runId}/session`, { token: op });
ok('the refused rewinds touched nothing', r.data.entries.length === len, `${len} -> ${r.data.entries.length}`);
// the rewind send itself: the edited turn replaces its target, the
// ledger record restated as part of the rewrite
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery one, edited.*', sheet: { rb: 1 }, rewind: target, expect: len } });
ok('the rewind send lands', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
ok('the log truncated (the target replaced, everything after it gone)',
r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'user' && /Rewind battery one, edited/.test(String(e.m.content ?? '')))
&& r.data.entries.every((e) => !/Rewind battery (one\.|two)/.test(JSON.stringify(e)))
&& r.data.entries.length < len,
`${len} -> ${r.data.entries.length}`);
ok('the marker survives the cut (the floor holds)', r.data.entries.some((e) => e.t === 'note' && e.kind === 'start'), '');
r = await call(`/runs/${runId}`, { token: op });
ok("the dead range's records re-derive away (the sheet reverts)", JSON.stringify(r.data.sheet) === '{"rb":1}', JSON.stringify(r.data.sheet));
r = await call(`/runs/${runId}/story`, { token: op });
ok('the story drops the cut range', r.data.sessions.every((s) => s.turns.every((t) => !/Rewind battery two/.test(t.text))), 'the dropped prose survived in the story');
}
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);