Files
tiny-worlds/test/smoke.mjs
T

1267 lines
94 KiB
JavaScript
Raw Normal View History

// test/smoke.mjs -- end-to-end multiuser pass against the --mock
// server. Covers: bootstrap, claim, spent-invite rejection, second
// user, the provider round (developer, 2026-11-18: the self-heal boot --
// the empty provider list auto-added and discovered; the op acts
// ride the per-provider surface -- the binary add choice, the o/f
// singleton's authless guard, the selection {model, effort} that
// names the refine curator, per-provider refine with the meter and
// the receipt, the spec-keyed adjudication cache, the run spec
// picks {provider, model, effort} with no unset effort, the
// invalidation surface -- a removed provider blocks its runs until
// the GM re-picks, the removal guard on the singleton, the request
// record -- resolved spec + effective params on
2026-11-16 21:32:02 +00:00
// 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, r/w since 2026-11-20 -- the emitted blocks
// strip, the via echo renders as the per-turn <mind> block), the
// rewind (developer, 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 (developer, 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
2026-11-16 21:32:02 +00:00
// and agenda sets, absent = unchanged, the silent over-cap eviction,
// the view stamping at the canon point, GM prose pure), the state scan (the log
2026-11-16 22:49:50 +00:00
// 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
2026-11-16 21:32:02 +00:00
// (create dormant -> start -> live ->
// stop -> dormant -> re-run -> start -> the auto-send rule -> the
2026-11-16 21:32:02 +00:00
// 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, readdirSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
import { renderView, lintCarryover } from '../server/session.mjs';
import { noCloneGate, splitDraft } from '../server/packager.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. providers and the registry: the fresh deployment self-heals
// (the empty provider list is auto-added and discovered at boot),
// the op's acts ride the per-provider surface (selection, discover,
// refine), the adjudication cache survives churn, and model use
// stays registry-gated
{
r = await call('/models', { token: op });
let boot = r.data.providers ?? [];
for (let i = 0; i < 50 && boot.filter((p) => p.models.length > 0).length < 2; i++) {
await new Promise((res) => setTimeout(res, 100));
r = await call('/models', { token: op });
boot = r.data.providers ?? [];
}
ok('the self-heal boot: the empty provider list is auto-added and discovered',
boot.length === 2 && boot.every((p) => ['mock-a', 'mock-b'].includes(p.slug) && p.phase === 'preliminary' && p.models.length > 0),
JSON.stringify(boot.map((p) => [p.slug, p.phase, p.models.length])));
const cfgFile = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
ok('the config file holds the provider entities (server-written state)',
cfgFile.providers.length === 2 && cfgFile.providers.every((p) => typeof p.slug === 'string' && typeof p.baseUrl === 'string'),
JSON.stringify(cfgFile.providers?.map((p) => p.slug)));
// the op's acts are op-only
r = await call('/providers', { method: 'POST', token: ash, body: { slug: 'nope', baseUrl: 'https://x.example/v1' } });
ok('provider add is op-only', r.status === 403);
// the add flow: bad inputs refuse
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'Bad Slug', baseUrl: 'https://x.example/v1' } });
ok('a bad slug refuses', r.status === 400 && /slug/.test(r.data.error), r.data.error ?? '');
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-a', baseUrl: 'https://x.example/v1' } });
ok('a duplicate slug refuses', r.status === 409, r.data.error ?? '');
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'nope', baseUrl: 'not a url' } });
ok('a bad baseUrl refuses', r.status === 400 && /baseUrl/.test(r.data.error), r.data.error ?? '');
// the binary choice: the o/f singleton adds and discovers (the
// mock surface serves any slug), and never takes a key
r = await call('/providers', { method: 'POST', token: op, body: { builtin: true } });
ok('the o/f singleton adds and discovers', r.status === 200 && r.data.provider === 'opencode/free' && r.data.models > 0, JSON.stringify(r.data));
r = await call('/providers', { method: 'POST', token: op, body: { builtin: true } });
ok('the singleton is single', r.status === 409 && /already/.test(r.data.error), r.data.error ?? '');
r = await call(`/providers/${encodeURIComponent('opencode/free')}/auth`, { method: 'POST', token: op, body: { apiKey: 'sk-x' } });
ok('the o/f singleton never takes a key', r.status === 403 && /anonymous/.test(r.data.error), r.data.error ?? '');
// the selection: the provider's default {model, effort} -- also
// the refine curator
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
ok('refine requires the selection (the default is the curator)', r.status === 409 && /select/.test(r.data.error), r.data.error ?? '');
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'nope', effort: 'max' } });
ok('a selection outside the registry refuses', r.status === 400 && /registry/.test(r.data.error), r.data.error ?? '');
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', 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('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
ok('the selection lands (the provider default)', r.status === 200 && JSON.stringify(r.data.default) === '{"model":"mock","effort":"max"}', JSON.stringify(r.data));
r = await call('/providers/mock-b/default', { method: 'POST', token: op, body: { model: 'mock-cheap', effort: 'high' } });
ok('the second provider selects too', r.status === 200, r.data.error ?? '');
// refine: per provider, the meter, the receipt, the verdicts
r = await call('/providers/mock-a/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 jobA = null;
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
jobA = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
if (jobA?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('refine applied', jobA?.state === 'applied', JSON.stringify(jobA ?? null));
ok('the refine meter closed its steps (one per model + the curator\'s two)', jobA?.steps?.total === 4 && jobA?.steps?.done === 4,
JSON.stringify(jobA?.steps ?? null));
ok('the refine receipt logged every battery and the curator',
(jobA?.lines ?? []).length === 3
&& jobA.lines.some((l) => l.includes('mock: reasoning deep'))
&& jobA.lines.some((l) => l.includes('mock-tie: reasoning deep'))
&& jobA.lines.some((l) => l.includes('curator (mock): curated')),
JSON.stringify(jobA?.lines ?? null));
r = await call('/providers/mock-b/refine', { method: 'POST', token: op, body: {} });
ok('the second provider refines', r.status === 200, r.data.error ?? '');
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
if ((r.data.providers ?? []).find((p) => p.slug === 'mock-b')?.job?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
const refined = (r.data.providers ?? []);
const secA = refined.find((p) => p.slug === 'mock-a');
const secB = refined.find((p) => p.slug === 'mock-b');
ok('the refined sections carry verdicts and curation',
secA?.phase === 'refined' && secA.models.some((m) => m.id === 'mock' && m.inference === true && m.reasoning === 'deep' && m.label === 'Mock' && m.family === 'mock')
&& secA.models.some((m) => m.id === 'mock-tie' && m.reasoning === 'deep' && m.label === 'Mock (tie)')
&& secB?.phase === 'refined' && secB.models.some((m) => m.id === 'mock-cheap' && m.reasoning === 'standard'),
JSON.stringify({ a: secA?.models.map((m) => [m.id, m.label]), b: secB?.models.map((m) => [m.id, m.label]) }));
ok('the curator\'s recommendation is intel on the section (never auto-applied)',
JSON.stringify(secA?.recommendation ?? null) === '{"model":"mock","effort":"max"}' && JSON.stringify(secA.default) === '{"model":"mock","effort":"max"}',
JSON.stringify({ recommendation: secA?.recommendation, default: secA.default }));
ok('the effort probe: measured ladders and the max-mean defaults',
secA?.models.some((m) => m.id === 'mock' && m.effortDefault === 'max' && m.efforts?.max === 500 && m.efforts?.none === 0)
&& secB?.models.some((m) => m.id === 'mock-cheap' && m.effortDefault === 'high' && m.efforts?.max === undefined),
JSON.stringify([...(secA?.models ?? []), ...(secB?.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 registry file is per-provider sections (the section names the route)',
regFile.providers?.['mock-a']?.models?.length === 2 && regFile.providers?.['mock-b']?.models?.length === 1
&& regFile.providers['mock-b'].models[0].id === 'mock-cheap'
&& regFile.providers['mock-a'].models.every((m) => m.endpoint === undefined),
JSON.stringify(Object.entries(regFile.providers ?? {}).map(([s, x]) => [s, x.models.length])));
// the adjudication cache: a re-refine over the same tuple reuses
// every entry -- churn is the point (o/f rotates models; the
// survivors keep their measured selves between refines)
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
ok('a re-refine starts', r.status === 200, r.data.error ?? '');
let jobC = null;
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
jobC = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
if (jobC?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('the cached re-refine applied', jobC?.state === 'applied', JSON.stringify(jobC ?? null));
ok('the cache served both models',
(jobC?.lines ?? []).filter((l) => l.includes('from cache')).length === 2
&& jobC.lines.some((l) => l.includes('curator')),
JSON.stringify(jobC?.lines ?? null));
const cacheFile = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
const cacheKeys = Object.keys(cacheFile.entries ?? {}).filter((k) => k.startsWith('mock-a::'));
ok('the cache file holds the adjudications under their spec tuples',
cacheKeys.length === 2 && cacheKeys.every((k) => k.startsWith('mock-a::') && k.includes('::max::mock::max')),
JSON.stringify(Object.keys(cacheFile.entries ?? {})));
}
// 7c. the add-flow machine (developer, 2026-11-19): discovery is the probe.
// A keyless working endpoint never sees a key field; a 401/403 stands
// the provider broken and opens the key path (checked on reception,
// saved on success, asked again on refusal -- a failed candidate
// never saves); every other failure refuses the add outright,
// nothing stands. The key removal probes again, and o/f never asks.
{
// the add takes no key -- the auth route is the only key path
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-keyed', baseUrl: 'https://k.example/v1', apiKey: 'sk-x' } });
ok('apiKey on the add refuses', r.status === 400 && /apiKey/.test(r.data.error), r.data.error ?? '');
// a dead endpoint: the add is refused outright, nothing stands
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-dead', baseUrl: 'https://dead.example/v1' } });
ok('a non-auth discovery failure refuses the add', r.status === 500 && /did not answer/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
r = await call('/models', { token: op });
ok('the refused add left no card behind', !(r.data.providers ?? []).some((p) => p.slug === 'mock-dead'), JSON.stringify((r.data.providers ?? []).map((p) => p.slug)));
const cfgNoDead = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
ok('the refused add never reached the config', !cfgNoDead.providers.some((p) => p.slug === 'mock-dead'), '');
// an auth-shaped refusal: the provider stands broken, the ask opens
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-auth', baseUrl: 'https://auth.example/v1' } });
ok('a 401 listing stands the provider broken', r.status === 401 && /refused/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
r = await call('/models', { token: op });
const authCard = (r.data.providers ?? []).find((p) => p.slug === 'mock-auth');
ok('the broken card carries the probe record (the ask)', authCard?.phase === 'none' && authCard?.probe?.outcome === 'auth' && authCard?.hasKey === false, JSON.stringify(authCard?.probe ?? null));
// the key path: checked on reception, saved on success
r = await call('/providers/mock-auth/auth', { method: 'POST', token: op, body: { apiKey: 'sk-mock' } });
ok('a working key lands (probe-then-save)', r.status === 200 && r.data.models > 0, JSON.stringify(r.data));
const cfgKeyed = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
ok('the successful key saved', cfgKeyed.providers.find((p) => p.slug === 'mock-auth')?.apiKey === 'sk-mock', '');
r = await call('/models', { token: op });
ok('the keyed card reads working', (r.data.providers ?? []).find((p) => p.slug === 'mock-auth')?.probe?.outcome === 'ok', '');
// a key that still meets the refusal is never saved
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-lock', baseUrl: 'https://lock.example/v1' } });
ok('the locked provider stands broken too', r.status === 401 && /refused/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
r = await call('/providers/mock-lock/auth', { method: 'POST', token: op, body: { apiKey: 'sk-nope' } });
ok('a refused key is not saved (the ask repeats)', r.status === 401 && /refuses every listing/.test(r.data.error), `${r.status} ${r.data.error ?? ''}`);
const cfgLock = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
ok('the failed key never reached the config', cfgLock.providers.find((p) => p.slug === 'mock-lock')?.apiKey === undefined, '');
// the key removal: the control for a provider gone public (or the
// first half of a replacement -- the ask re-opens on the 401)
r = await call('/providers/mock-auth/auth', { method: 'DELETE', token: op, body: {} });
ok('the key removes', r.status === 200, JSON.stringify(r.data));
const cfgUnkeyed = JSON.parse(readFileSync(`${ROOT}/state/config.json`, 'utf8'));
ok('the key left the config', cfgUnkeyed.providers.find((p) => p.slug === 'mock-auth')?.apiKey === undefined, '');
r = await call('/models', { token: op });
ok('the keyless probe re-met the 401 (the ask re-opened)', (r.data.providers ?? []).find((p) => p.slug === 'mock-auth')?.probe?.outcome === 'auth', '');
r = await call('/providers/mock-lock/auth', { method: 'DELETE', token: op, body: {} });
ok('removing a missing key refuses', r.status === 404, `${r.status}`);
r = await call(`/providers/${encodeURIComponent('opencode/free')}/auth`, { method: 'DELETE', token: op, body: {} });
ok('the o/f singleton never loses a key it never had', r.status === 403 && /anonymous/.test(r.data.error), r.data.error ?? '');
// the machine's fixtures leave before the later counts
for (const slug of ['mock-auth', 'mock-lock']) {
await call(`/providers/${slug}`, { method: 'DELETE', token: op, body: {} });
}
r = await call('/models', { token: op });
ok('the fixtures cleaned up', !(r.data.providers ?? []).some((p) => p.slug === 'mock-auth' || p.slug === 'mock-lock'), '');
2026-11-16 21:32:02 +00:00
}
// 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', spec: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
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 }));
2026-11-16 21:32:02 +00:00
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));
2026-11-17 02:21:38 +00:00
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 });
2026-11-16 21:32:02 +00:00
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]))));
2026-11-16 21:32:02 +00:00
// 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);
2026-11-16 21:32:02 +00:00
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');
2026-11-16 22:49:50 +00:00
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 ?? '')));
2026-11-16 21:32:02 +00:00
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');
2026-11-16 21:32:02 +00:00
// 10. the exchanges (mock: variant literature with per-variant status
// blocks, the ask, the whole-list sets, the silent eviction, 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));
2026-11-16 21:32:02 +00:00
const pickedStatus = r.data.variants.chosen === 0 ? 'determined' : 'cautious';
r = await call(`/runs/${runId}`, { token: op });
2026-11-16 21:32:02 +00:00
ok("the picked variant's status applied", r.data.status.includes(pickedStatus), JSON.stringify(r.data.status));
ok('the context gauge reads the discovered window (the registry input ceiling, never a declared config)',
r.data.context?.contwin === 524288 && r.data.context?.pct === Math.round((100 * r.data.context.used) / 524288),
JSON.stringify(r.data.context ?? null));
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));
2026-11-16 21:32:02 +00:00
const viaMsg = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && e.via);
2026-11-16 23:52:58 +00:00
ok('the request record rides the turn (resolved model + effective params, the measured effort default included)',
!!viaMsg && viaMsg.via.model === 'mock' && viaMsg.via.provider === 'mock-a' && 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');
2026-11-16 21:32:02 +00:00
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));
2026-11-17 02:21:38 +00:00
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 ?? '');
2026-11-16 21:32:02 +00:00
// 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 });
2026-11-16 21:32:02 +00:00
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.*' } });
2026-11-16 21:32:02 +00:00
ok('a restated agenda replaces the list', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('agenda after restatement (a comma inside an item is prose, not a separator)',
JSON.stringify(r.data.agenda) === '["signal any passing ship, or swim for it","build a shelter"]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Night falls.*' } });
2026-11-16 21:32:02 +00:00
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 });
2026-11-16 21:32:02 +00:00
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 });
2026-11-16 21:32:02 +00:00
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));
2026-11-16 22:49:50 +00:00
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.*' } });
2026-11-16 21:32:02 +00:00
ok('next gm turn is clean', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
// 10c. the mind verb: <mind>{"temperature": 1.15}</mind> sets her
2026-11-16 21:32:02 +00:00
// sampling for her NEXT turn (one-shot, JSON, max_tokens excluded)
r = await call(`/runs/${runId}/session`, { token: op });
2026-11-16 21:32:02 +00:00
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.15), 'no mind note');
const ridingTurn = r.data.entries.find((e) => e.t === 'msg' && e.m.role === 'assistant' && /watches the water and waits for the world to move/.test(e.m.content ?? ''));
2026-11-16 21:32:02 +00:00
ok('the mind verb: her next turn rides at the stated mind',
ridingTurn?.via?.params?.temperature === 1.15, JSON.stringify(ridingTurn?.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));
2026-11-16 21:32:02 +00:00
ok('GM prose goes pure', !/<\/?(status|agenda)>/.test(lastGm.m.content), lastGm.m.content.slice(-120));
2026-11-16 22:49:50 +00:00
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}`);
2026-11-16 21:32:02 +00:00
// 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 1\.15/.test(e.m.content));
2026-11-16 21:32:02 +00:00
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.15),
2026-11-16 21:32:02 +00:00
'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)
2026-11-16 22:49:50 +00:00
&& /<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');
2026-11-16 21:32:02 +00:00
ok('superseded copies strip from the view',
her1.filter((m) => m !== lastHer).every((m) => !/<\/?(status|agenda)>/.test(String(m.content ?? ''))), '');
ok('her emitted mind blocks strip (the machinery echo is the only <mind> in her turns)',
her1.every((m) => {
const c = String(m.content ?? '');
const first = c.indexOf('<mind>');
return first === -1 || (first === 0 && c.indexOf('<mind>', 1) === -1);
}), '');
const viewConflicts = view1.filter((m) => m.role === 'user' && /^<conflict>/.test(String(m.content ?? '')));
ok('past conflicts stay in the context (a mistake remains visible, developer 2026-11-18)',
viewConflicts.length === 1, `${viewConflicts.length} render`);
ok('a conflict describes its problem in full (the refused value quoted)',
viewConflicts.some((m) => /\(got 7\)/.test(String(m.content ?? ''))), '');
ok('each past turn carries its <mind> echo when params rode',
her1.some((m) => String(m.content ?? '').startsWith('<mind>{"temperature":1.15}</mind>')), '');
ok('the <mind> echo hides the effort knob (not her call)',
2026-11-16 23:52:58 +00:00
her1.every((m) => !/reasoning_effort/.test(String(m.content ?? ''))), 'the effort leaked into her display');
2026-11-16 21:32:02 +00:00
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);
2026-11-16 21:32:02 +00:00
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));
2026-11-15 22:37:06 +00:00
// 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 });
2026-11-15 22:37:06 +00:00
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);
2026-11-17 02:21:38 +00:00
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);
2026-11-15 22:37:06 +00:00
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 ?? '');
2026-11-16 21:32:02 +00:00
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.15, JSON.stringify(forkReply?.via ?? null));
2026-11-16 22:49:50 +00:00
// 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: the run's spec picks {provider, model, effort},
// registry-gated, owner-only. The per-run params layer is gone (developer,
// 2026-11-18): the <mind> verb is the only sampling source, per-turn
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'mock-cheap', effort: 'low' }, housekeeper: { provider: 'mock-a', model: 'mock-tie', effort: 'max' } } });
ok('set spec picks',
r.status === 200 && JSON.stringify(r.data.models.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
&& JSON.stringify(r.data.models.housekeeper) === '{"provider":"mock-a","model":"mock-tie","effort":"max"}',
JSON.stringify(r.data));
ok('the specs are stamped in run.json', JSON.stringify(meta(forkId).models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'mock-cheap', effort: 'turbo' } } });
2026-11-16 23:52:58 +00:00
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: { player: { provider: 'nope', model: 'x', effort: 'low' } } });
ok('an unconfigured provider refuses', r.status === 400 && /no provider named/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: { provider: 'mock-b', model: 'not-a-model', effort: 'low' } } });
ok('a model outside the registry refuses', r.status === 400 && /not usable/.test(r.data.error), r.data.error ?? '');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
ok('clear a role (the housekeeper inherits the player provider\'s default)',
r.status === 200 && r.data.models.housekeeper === undefined && r.data.modelState?.housekeeper?.ok === true && r.data.modelState.housekeeper.inherited === true,
JSON.stringify(r.data.modelState ?? null));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
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 the picks, their health, and the provider defaults',
JSON.stringify(r.data.run.models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}'
&& r.data.run.modelState?.player?.ok === true
&& Array.isArray(r.data.run.providerDefaults) && r.data.run.providerDefaults.length >= 2,
JSON.stringify({ models: r.data.run.models, modelState: r.data.run.modelState }));
// a turn on the re-picked run: the recording proves what was sent --
// the spec's effort riding under the mind layer (her restated mind is
// the only params source, layered over nothing)
2026-11-16 21:32:02 +00:00
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She keeps watch.*' } });
ok('gm turn on the fork (post-picks)', r.status === 200, r.data.error ?? '');
2026-11-16 21:32:02 +00:00
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 spec under the mind layer',
!!viaTurn?.via && viaTurn.via.model === 'mock-cheap' && viaTurn.via.provider === 'mock-b'
&& viaTurn.via.params.temperature === 1.15 && viaTurn.via.params.reasoning_effort === 'low',
2026-11-16 21:32:02 +00:00
JSON.stringify(viaTurn?.via ?? null));
r = await call('/models', { token: ash });
ok('model listing (the per-provider registry)',
r.status === 200 && (r.data.providers ?? []).some((p) => p.slug === 'mock-a' && p.phase === 'refined' && p.models.some((m) => m.id === 'mock' && m.label === 'Mock')),
JSON.stringify((r.data.providers ?? []).map((p) => [p.slug, p.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;
// 14b. the package fork battery (developer, 2026-11-19): fork is the
// copy-to-author act -- any package, the scaffold flag preserved
// (the flag is the package's doneness state: a scaffold fork stays a
// scaffold until the editor flips it off), the editor is the owner's
// alone, and create refuses a scaffold on both ends
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'template', name: 'My Scaffold' } });
ok('fork the template', r.status === 200 && r.data.package?.forked === 'template' && !!r.data.package?.id, JSON.stringify(r.data.package ?? r.data.error));
const tplFork = r.data.package?.id;
r = await call('/packages', { token: op });
const tplForkEntry = r.data.find((p) => p.name === tplFork);
ok('the fork is a user package, owner-stamped, scaffold preserved, pc stripped',
!!tplForkEntry && tplForkEntry.origin === 'user' && tplForkEntry.ownerName === 'Op' && tplForkEntry.scaffold === true
&& tplForkEntry.display === 'My Scaffold' && tplForkEntry.pc === null,
JSON.stringify(tplForkEntry ?? null));
r = await call('/runs', { method: 'POST', token: op, body: { package: 'template', pc: 'Nobody', name: 'x' } });
ok('create from a scaffold refuses', r.status === 400 && /scaffold/.test(r.data.error), r.data.error ?? '');
r = await call('/runs', { method: 'POST', token: op, body: { package: tplFork, pc: 'Nobody', name: 'x' } });
ok('create from the scaffold fork refuses too (the flag rides)', r.status === 400 && /scaffold/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'la-caramba', name: 'Caramba Variant' } });
ok('fork a playable package', r.status === 200 && r.data.package?.forked === 'la-caramba', JSON.stringify(r.data.package ?? r.data.error));
const carambaFork = r.data.package?.id;
r = await call('/packages', { token: op });
ok('a fork of a playable package carries no scaffold', r.data.find((p) => p.name === carambaFork)?.scaffold === false,
JSON.stringify(r.data.find((p) => p.name === carambaFork) ?? null));
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'template' } });
ok('fork needs a display name', r.status === 400, r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'nope', name: 'x' } });
ok('fork of an unknown package refuses', r.status === 400 && /no such package/.test(r.data.error), r.data.error ?? '');
// 14c. the package editor: the owner's authoring surface, every file
// rw (settings included -- raw JSON for now), the cheap save lints,
// and the ready-to-run flip
r = await call(`/packages/${tplFork}/files`, { token: op });
ok('the owner reads the editor surface',
r.status === 200 && r.data.files['settings.json']?.exists === true && r.data.scaffold === true && r.data.display === 'My Scaffold',
JSON.stringify(r.data.files ? { display: r.data.display, scaffold: r.data.scaffold } : r.data));
r = await call(`/packages/${tplFork}/files`, { token: ash });
ok("the editor is the owner's", r.status === 403, r.data.error ?? '');
r = await call('/packages/la-caramba/files', { token: op });
ok('system packages refuse the editor (repo-side)', r.status === 403 && /repo-side/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/nope/files', { token: op });
ok('an unknown package 404s', r.status === 404, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/settings.json`, { method: 'PUT', token: op, body: { content: '{ not json' } });
ok('settings must parse (the raw JSON editor)', r.status === 400 && /JSON object/.test(r.data.error), r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/carryover.jsonl`, { method: 'PUT', token: op, body: { content: 'nope' } });
ok('the carryover save lint holds on the package editor', r.status === 400, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/backdrop.md`, { method: 'PUT', token: op, body: { content: '# My forked backdrop\n\nA new island.\n' } });
ok('the owner writes a file', r.status === 200, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/handbook.md`, { method: 'PUT', token: op, body: { content: "# The fork's own handbook\n\nCraft marker: unique-to-the-fork.\n" } });
ok('the handbook is authorable on the package', r.status === 200, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/settings.json`, { method: 'PUT', token: op, body: { content: JSON.stringify({ records: false, scaffold: false, name: 'My Scaffold' }, null, 2) + '\n' } });
ok('the ready-to-run flip (scaffold off)', r.status === 200, r.data.error ?? '');
r = await call('/packages', { token: op });
ok('the listing reflects the flip', r.data.find((p) => p.name === tplFork)?.scaffold === false, '');
r = await call('/runs', { method: 'POST', token: op, body: { package: tplFork, pc: 'Forkina', name: 'Fork Story' } });
ok('create from the flipped fork', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const forkRunId = r.data.run?.id;
r = await call(`/runs/${forkRunId}/files`, { token: op });
ok("the handbook round-trips (the package's own beats the repo default)",
r.data.files['handbook.md']?.content?.includes('unique-to-the-fork') === true,
JSON.stringify((r.data.files['handbook.md']?.content ?? '').slice(0, 60)));
// 14d. the packager (developer, 2026-11-19): literature into scaffold
// packages. Two modes -- character (her only, over the template base)
// and full (character + setting, the cut in the caller's words); the
// material rides as tool output; the gates refuse before anything
// lands; settings are the caller's, never the model's. The smoke
// fixture is original synthetic prose (a desert monastery library) --
// never a real source; the mock world serves canned outputs.
{
const FIXTURE = [
'The monastery sat where the salt road ended, a box of yellow stone with one tower, and Sister Vell kept its library the way her order had for two hundred years: by hand, by candle, and by a ledger nobody outside the walls had ever read.',
'The books came in with the caravans twice a year, bought by the pound from estate sales in cities the sisters had never seen. A book that arrived damp was dried page by page in the tower, and a book that arrived torn was copied before it was shelved, because the order held that a text exists only while someone can still read it.',
'This season the caravan brought eleven crates and one locked case with no manifest, and the caravan master would say only that it was paid through to the monastery and that he had not looked inside, which Sister Vell wrote down in the ledger as a fact about him rather than a fact about the case.',
].join('\n\n');
const poll = async () => {
for (let i = 0; i < 100; i++) {
const s = await call('/packager', { token: op });
if (s.data.state !== 'running') return s.data;
await new Promise((res) => setTimeout(res, 100));
}
return { state: 'stuck' };
};
// the gate units, first: a planted overlap refuses, and sections
// parse whole (the probe's first-line truncation lesson)
ok('the no-clone gate catches a verbatim overlap',
noCloneGate(FIXTURE, { 'character.md': `She wrote it down in the ledger as a fact about him rather than a fact about the case, and moved on.` }).clean === false,
'a planted 7-word clone passed the gate');
ok('the no-clone gate passes clean prose',
noCloneGate(FIXTURE, { 'character.md': 'She keeps a private ledger of facts about people, which is a habit and not an accusation, and it has never once been wrong about the weather.' }).clean === true,
'clean prose refused');
{
const secs = splitDraft('=== backdrop.md ===\nline one of the world.\nline two of the world.\n=== character.md ===\nher, entire.');
ok('the draft splitter reads whole sections', secs['backdrop.md'] === 'line one of the world.\nline two of the world.' && secs['character.md'] === 'her, entire.',
JSON.stringify(secs));
}
// the validation surface
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'nope', name: 'x', pc: 'y', source: FIXTURE } });
ok('a bad mode refuses', r.status === 400, r.data.error ?? '');
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'full', name: 'x', pc: 'y', source: FIXTURE } });
ok('full mode requires the cut', r.status === 400 && /cut/.test(r.data.error), r.data.error ?? '');
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'full', name: 'x', pc: 'y', cut: 'at the end', source: '' } });
ok('the source is required', r.status === 400 && /source/.test(r.data.error), r.data.error ?? '');
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'character', name: 'x', pc: 'y', source: FIXTURE, spec: { provider: 'mock-a', model: 'nope', effort: 'max' }, who: 'Sister Vell' } });
ok('a bad spec refuses', r.status === 400 && /not usable/.test(r.data.error), r.data.error ?? '');
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'character', name: 'x', pc: 'y', source: FIXTURE } });
ok('character mode requires who (the character to lift)', r.status === 400 && /who/.test(r.data.error), r.data.error ?? '');
// character mode: her only, over the template base
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'character', name: 'Coastal Light', pc: 'Vell', who: 'Sister Vell, the librarian', records: true, source: FIXTURE } });
ok('a character packaging starts', r.status === 200 && ['running', 'applied'].includes(r.data.state), JSON.stringify(r.data));
const charJob = await poll();
ok('the character packaging lands', charJob.state === 'applied' && !!charJob.package?.id, JSON.stringify(charJob));
ok('one call: extraction then files in a single output',
(charJob.lines?.[0] ?? '').startsWith('packaged:') && /extraction \d+, draft \d+/.test(charJob.lines?.[0] ?? ''),
JSON.stringify({ first: charJob.lines?.[0] ?? null }));
const charPkg = charJob.package?.id;
r = await call('/packages', { token: op });
const charEntry = r.data.find((p) => p.name === charPkg);
ok('the landed package is a scaffold with the caller\'s settings',
!!charEntry && charEntry.scaffold === true && charEntry.display === 'Coastal Light' && charEntry.pc === 'Vell' && charEntry.records === true && charEntry.origin === 'user' && charEntry.ownerName === 'Op',
JSON.stringify(charEntry ?? null));
r = await call(`/packages/${charPkg}/files`, { token: op });
ok('character mode overwrites character.md only (her, distilled)',
r.data.files['character.md']?.content?.includes('@PC') === true && r.data.files['character.md'].content.includes('keep the light') === true,
JSON.stringify((r.data.files['character.md']?.content ?? '').slice(0, 80)));
ok('the template base holds the un-drafted files',
r.data.files['backdrop.md']?.content?.trim() === readFileSync(`${ROOT}/packages/template/backdrop.md`, 'utf8').trim()
&& r.data.files['carryover.jsonl']?.content?.trim() === readFileSync(`${ROOT}/packages/template/carryover.jsonl`, 'utf8').trim(),
'an un-drafted file drifted from the template base');
// the refusal: a named character who is not a woman refuses loud,
// nothing lands (the mock's cue is the fixture's own caravan master)
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'character', name: 'The Caravan Master', pc: 'x', who: 'the caravan master', source: FIXTURE } });
ok('a character packaging starts (the refusal case)', r.status === 200 && ['running', 'rejected'].includes(r.data.state), JSON.stringify(r.data));
const refusedJob = await poll();
ok('not-a-woman refuses loud, nothing lands',
refusedJob.state === 'rejected' && /is a man/.test(refusedJob.reason ?? '') && refusedJob.package === null,
JSON.stringify(refusedJob));
// the fit check (developer, 2026-11-20): no chunks ever -- the
// full source in one read, and an oversized source refuses with
// the arithmetic (mock's contwin: 524288 tokens; the threshold is
// (contwin - overhead) * 4 chars, so build past it explicitly)
let HUGE = FIXTURE;
while (HUGE.length < (524288 - 32_000) * 4 + 4096) HUGE += '\n\n' + FIXTURE;
r = await call('/packager', { method: 'POST', token: op, body: { mode: 'character', name: 'Too Big', pc: 'Vell', who: 'Sister Vell, the librarian', source: HUGE } });
ok('an oversized source refuses with the arithmetic',
r.status === 413 && /contwin/.test(r.data.error) && /compact/.test(r.data.error),
r.data.error ?? '');
// full mode: the whole file set, the cut riding the assemble call
r = await call('/packager', { method: 'POST', token: ash, body: { mode: 'full', name: 'The Salt Road', pc: 'Vell', records: false, cut: 'cut where she writes the case into the ledger; the caravan is still in the courtyard', source: FIXTURE } });
ok('any user can package (a full packaging starts)', r.status === 200, r.data.error ?? JSON.stringify(r.data));
const fullJob = await poll();
ok('the full packaging lands', fullJob.state === 'applied' && !!fullJob.package?.id, JSON.stringify(fullJob));
const fullPkg = fullJob.package?.id;
r = await call(`/packages/${fullPkg}/files`, { token: ash });
ok('full mode drafts every file over the base',
r.data.files['backdrop.md']?.content?.includes('the point and the harbour') === true
&& r.data.files['gm.md']?.content?.includes('non-canon') === true
&& r.data.files['memory.json']?.content?.includes('"session": "0"') === true,
JSON.stringify(Object.fromEntries(Object.entries(r.data.files).map(([k, v]) => [k, (/** @type {{ content?: string }} */ (v)).content?.slice(0, 40) ?? '']))));
ok('the landed gm.md marks the proposals non-canon (full intel, GM-proposed, not truth)',
/proposals/i.test(r.data.files['gm.md']?.content ?? '') && /non-canon/i.test(r.data.files['gm.md']?.content ?? ''),
(r.data.files['gm.md']?.content ?? '').slice(0, 80));
ok('the caller\'s settings landed (never a model output)',
JSON.parse(readFileSync(`${ROOT}/state/packages/${fullPkg}/settings.json`, 'utf8')).pc === 'Vell',
readFileSync(`${ROOT}/state/packages/${fullPkg}/settings.json`, 'utf8'));
// the spent source: derived material retained, the book deleted
const workdirs = readdirSync(`${ROOT}/state/packager`).sort();
const last = `${ROOT}/state/packager/${workdirs[workdirs.length - 1]}`;
ok('the source is deleted after the run (derived material retained)',
!existsSync(`${last}/source.txt`) && existsSync(`${last}/draft.txt`),
`${workdirs[workdirs.length - 1]}: ${readdirSync(last).join(', ')}`);
}
// 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);
2026-11-15 22:37:06 +00:00
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(`/packages/${pkgId}/files`, { token: op });
ok('an ownerless package refuses the editor (readable, forkable, never editable)', r.status === 403 && /not yours/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: pkgId, name: 'Ash Pack Continued' } });
ok('an ownerless package is forkable (the copy is yours)', r.status === 200 && r.data.package?.forked === pkgId, JSON.stringify(r.data.package ?? r.data.error));
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 model specs', JSON.stringify(meta(reforkId).models?.player) === '{"provider":"mock-b","model":"mock-cheap","effort":"low"}');
// 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));
2026-11-16 21:32:02 +00:00
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`);
2026-11-16 22:49:50 +00:00
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));
2026-11-16 22:49:50 +00:00
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`);
2026-11-16 21:32:02 +00:00
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));
2026-11-17 22:35:44 +00:00
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 });
2026-11-16 21:32:02 +00:00
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')
2026-11-16 21:32:02 +00:00
&& 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 ?? '');
2026-11-16 21:32:02 +00:00
// 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.15, JSON.stringify(s2Reply?.via ?? null));
2026-11-16 21:32:02 +00:00
// 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');
2026-11-16 21:32:02 +00:00
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 ?? '');
2026-11-15 23:45:15 +00:00
// 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 (developer, 2026-11-17): the GM's ledger of arbitrated run
2026-11-17 22:35:44 +00:00
// 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 ?? '');
2026-11-17 22:35:44 +00:00
}
{
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'));
2026-11-17 22:35:44 +00:00
}
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');
}
// 23b. the sheet's transport at the lint (the box round, developer, 2026-11-19):
// the record is the only channel, the tag is view machinery -- the
// authored gate names every wrong shape, the boundary note is checked
// on both kinds, and her carried emission stays legitimate history
{
const la = (a) => lintCarryover(a, { authored: true });
ok('lint: a scalar sheet record is named', la([
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: 'nope' },
]).some((e) => e.includes('sheet record must be a JSON object')), '');
ok('lint: an array sheet record is named', la([
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: ['nope'] },
]).some((e) => e.includes('sheet record must be a JSON object')), '');
ok('lint: a sheet record on her turn is named', la([
{ t: 'msg', m: { role: 'assistant', content: 'x' }, sheet: {} },
]).some((e) => e.includes('rides GM turns only')), '');
ok('lint: the tag in her authored turn is named', la([
{ t: 'msg', m: { role: 'assistant', content: 'x <sheet>{}</sheet>' } },
]).some((e) => e.includes('never authored')), '');
ok('lint: the tag in GM prose is named', la([
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
{ t: 'msg', m: { role: 'user', content: 'y <sheet>{}</sheet>' } },
]).some((e) => e.includes('never authored')), '');
ok('lint: a good sheet record passes clean', la([
{ t: 'msg', m: { role: 'assistant', content: 'x' } },
{ t: 'msg', m: { role: 'user', content: 'y' }, sheet: { GP: 0 } },
]).length === 0, '');
ok('lint: a scalar sheet on a boundary note is named (both kinds)', lintCarryover([
{ t: 'note', kind: 'state', status: [], sheet: 7 },
], { authored: false }).some((e) => e.includes('state.sheet must be a JSON object')), '');
ok('lint: her emitted sheet in a carried tail is legitimate history', lintCarryover([
{ t: 'msg', m: { role: 'user', content: 'y' } },
{ t: 'msg', m: { role: 'assistant', content: 'x <sheet>{"gp": 99}</sheet>' } },
], { authored: false }).length === 0, '');
}
// 24. the rewind (developer, 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');
}
// 24b. invalidation and the removal guard (developer, 2026-11-18): a run's
// picks are settings the run came with -- when the server stops
// carrying them (the provider removed), the run blocks until the GM
// sets them up again; and the o/f singleton is removable only while
// another provider stands in its place (the empty list is an error
// state; the fallback is what keeps it unreachable)
{
// a custom provider, a run riding it
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-c', baseUrl: 'https://mock.c.example/v1' } });
ok('a custom provider adds and discovers', r.status === 200 && r.data.models > 0, JSON.stringify(r.data));
// the failures-never-cache rule (developer, 2026-11-19): a failure is the
// absence of a measurement, not a measurement -- mock-fail lands
// its verdict fresh at every refine, while the passing models
// persist from the cache
r = await call('/providers/mock-c/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
ok('the custom provider selects its curator', r.status === 200, r.data.error ?? '');
r = await call('/providers/mock-c/refine', { method: 'POST', token: op, body: {} });
ok('the custom provider refines', r.status === 200, r.data.error ?? '');
let jobCC = null;
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
jobCC = (r.data.providers ?? []).find((p) => p.slug === 'mock-c')?.job ?? null;
if (jobCC?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('the mock-c refine applied', jobCC?.state === 'applied', JSON.stringify(jobCC?.reason ?? null));
ok('the failing model landed its verdict with the no-cache marker',
(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: failed the tool probe') && l.includes('never cached')),
JSON.stringify(jobCC?.lines ?? null));
const cacheFail = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
ok('the failure is absent from the cache',
!Object.keys(cacheFail.entries ?? {}).some((k) => k.startsWith('mock-c::mock-fail::')),
JSON.stringify(Object.keys(cacheFail.entries ?? {}).filter((k) => k.startsWith('mock-c::'))));
r = await call('/providers/mock-c/refine', { method: 'POST', token: op, body: {} });
ok('the re-refine starts', r.status === 200, r.data.error ?? '');
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
jobCC = (r.data.providers ?? []).find((p) => p.slug === 'mock-c')?.job ?? null;
if (jobCC?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('the re-refine re-probed the failure (never from cache)',
(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: failed the tool probe'))
&& !(jobCC?.lines ?? []).some((l) => l.includes('mock-fail: from cache')),
JSON.stringify(jobCC?.lines ?? null));
ok('the passing models served from cache on the re-refine',
(jobCC?.lines ?? []).filter((l) => l.includes('from cache')).length === 3,
JSON.stringify(jobCC?.lines ?? null));
const failRun = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Failcheck', name: 'Fail Check', spec: { provider: 'mock-c', model: 'mock-fail', effort: 'max' } } });
ok('the failing model is not selectable (the registry gates it)', failRun.status === 400, 'a failed model was selectable');
if (failRun.status === 200) await call(`/runs/${failRun.data.run.id}`, { method: 'DELETE', token: op, body: {} }); // never expected -- the backstop
r = await call('/runs', { token: op });
ok('the refused create left no orphan run (validate before anything lands)', !(r.data ?? []).some((x) => x.pc === 'Failcheck'), 'an orphan dir survived the refusal');
r = await call(`/runs/${reforkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-c', model: 'mock', effort: 'high' } } });
ok('the refork re-picks onto the custom provider', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*Riding the custom provider.*' } });
ok('the turn rides the custom provider', r.status === 200, r.data.error ?? '');
// the removal: the run invalidates, loudly, on every surface
r = await call('/providers/mock-c', { method: 'DELETE', token: op, body: {} });
ok('the custom provider removes', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${reforkId}`, { token: op });
ok('the run\'s health carries the note (the invalidation surface)',
r.data.run.modelState?.player?.ok === false && /no longer configured/.test(r.data.run.modelState.player.note ?? ''),
JSON.stringify(r.data.run.modelState ?? null));
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*No.*' } });
ok('the send refuses with the same note', r.status === 409 && /no longer configured/.test(r.data.error), r.data.error ?? '');
const goneFile = JSON.parse(readFileSync(`${ROOT}/state/models.json`, 'utf8'));
ok('the provider\'s registry section went with it', goneFile.providers?.['mock-c'] === undefined, JSON.stringify(Object.keys(goneFile.providers ?? {})));
const goneCache = JSON.parse(readFileSync(`${ROOT}/state/refine-cache.json`, 'utf8'));
ok('the provider\'s cache entries went with it', !Object.keys(goneCache.entries ?? {}).some((k) => k.startsWith('mock-c::')), JSON.stringify(Object.keys(goneCache.entries ?? {})));
// the GM sets it up again: the run unblocks
r = await call(`/runs/${reforkId}/model`, { method: 'POST', token: op, body: { player: { provider: 'mock-a', model: 'mock', effort: 'max' } } });
ok('the re-pick lands', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${reforkId}/turn`, { method: 'POST', token: op, body: { line: '*Back on the stand-ins.*' } });
ok('the run plays again after the re-pick', r.status === 200, r.data.error ?? '');
// the removal guard: pare down to the singleton, then it holds
r = await call('/providers/mock-b', { method: 'DELETE', token: op, body: {} });
ok('mock-b removes (a stand-in, not the fallback)', r.status === 200, r.data.error ?? '');
r = await call('/providers/mock-a', { method: 'DELETE', token: op, body: {} });
ok('mock-a removes', r.status === 200, r.data.error ?? '');
r = await call(`/providers/${encodeURIComponent('opencode/free')}`, { method: 'DELETE', token: op, body: {} });
ok('the singleton holds while it is all that stands', r.status === 409 && /fallback/.test(r.data.error), r.data.error ?? '');
// restore the mock world for the restart checks: re-add, rediscover,
// re-select, re-refine (fresh -- the cache purged with the provider)
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-a', baseUrl: 'https://mock.a.example/v1' } });
ok('mock-a re-adds', r.status === 200, r.data.error ?? '');
r = await call('/providers', { method: 'POST', token: op, body: { slug: 'mock-b', baseUrl: 'https://mock.b.example/v1' } });
ok('mock-b re-adds', r.status === 200, r.data.error ?? '');
r = await call('/providers/mock-a/default', { method: 'POST', token: op, body: { model: 'mock', effort: 'max' } });
ok('mock-a re-selects', r.status === 200, r.data.error ?? '');
r = await call('/providers/mock-b/default', { method: 'POST', token: op, body: { model: 'mock-cheap', effort: 'high' } });
ok('mock-b re-selects', r.status === 200, r.data.error ?? '');
r = await call('/providers/mock-a/refine', { method: 'POST', token: op, body: {} });
ok('mock-a re-refines (fresh probes -- the cache purged)', r.status === 200, r.data.error ?? '');
let jobR = null;
for (let i = 0; i < 40; i++) {
r = await call('/models', { token: op });
jobR = (r.data.providers ?? []).find((p) => p.slug === 'mock-a')?.job ?? null;
if (jobR?.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok('the restored world refined', jobR?.state === 'applied', JSON.stringify(jobR ?? null));
}
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId} fork-story=${forkRunId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);