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

724 lines
53 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 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 ?? ''))), '');
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) {
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'clear enough' } });
ok('the sheet battery answers the script ask', 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');
}
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');
}
console.log(`\nrun ids: source=${runId} 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);