Files
tiny-worlds/test/smoke.mjs
T

361 lines
24 KiB
JavaScript

// test/smoke.mjs -- end-to-end multiuser pass against the --mock
// server. Covers: bootstrap, claim, spent-invite rejection, second
// user, the session lifecycle (create dormant -> start -> live ->
// stop -> dormant -> re-run -> start -> the auto-send rule -> the
// start lint), spectator 403s, fork, save-package, create-from-user-
// package, revocation, ownerless state, the agenda deltas + self-
// heal, the reminder ride, per-run models, variant literature (the
// random pick, the /table projection, the variance metric), the
// slidwin (move-at-stop, exactly-one-jsonl), and the whole-story
// /story render with no doubles.
// Prints PASS/FAIL per step; exit code carries the verdict.
//
// Expects a CLEAN state/ (no users) and a running --mock server:
// node server/main.mjs --mock
// node test/smoke.mjs
// Leaves its token + run ids in a temp file for restart-check.mjs.
// Clean up afterwards: Remove-Item state/, delete the smoke runs.
import { readFileSync, writeFileSync, appendFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
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(), 'rp-test-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);
// 8. op creates a run -- dormant session one, memory applied at creation
r = await call('/runs', { method: 'POST', token: op, body: { package: 'la-caramba', pc: 'Smokina', name: 'Smoke Story' } });
ok('create run', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const runId = r.data.run?.id;
ok('owner stamped', meta(runId).owner === opId);
r = await call(`/runs/${runId}`, { token: op });
ok('born dormant', r.data.phase === 'dormant' && r.data.sessions === 1 && r.data.draft === true,
JSON.stringify({ phase: r.data.phase, sessions: r.data.sessions }));
ok('memory applied at creation', r.data.fill.a === 4 && r.data.fill.b === 1, JSON.stringify(r.data.fill));
r = await call(`/runs/${runId}/files`, { token: op });
ok('the draft editor surface', r.data.files['carryover.jsonl']?.mode === 'rw' && r.data.files['memory.json']?.mode === 'ro'
&& r.data.files['handbook.md']?.mode === 'rw', JSON.stringify(Object.fromEntries(Object.entries(r.data.files).map(([k, v]) => [k, v.mode]))));
// 9. start: lint, freeze, consume -- the carryover lands behind the
// bundle. It ends on her turn, so no auto-send: the table waits.
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start', r.status === 200 && r.data.session === 1 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data));
r = await call(`/runs/${runId}`, { token: op });
ok('live', r.data.phase === 'live' && r.data.open === true);
ok('the opening status applied', JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","worried"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the opening renders on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /Modesty, decency or respect/.test(e.m.content ?? '')));
ok('the opening event rides the log', r.data.entries.some((e) => e.t === 'opening'));
ok('the sigil expanded at start', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /Smokina was staring/.test(e.m.content ?? '')), 'a raw @PC reached the table');
// 10. the exchanges (mock: variant literature, the ask, the deltas, the self-heal)
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The tide comes in.*' } });
ok('gm turn -> variant literature', r.status === 200 && r.data.variants?.count === 2 && [0, 1].includes(r.data.variants.chosen), r.data.error ?? JSON.stringify(r.data.variants ?? null));
const pickedDelta = r.data.variants.chosen === 0 ? 'determined' : 'cautious';
r = await call(`/runs/${runId}`, { token: op });
ok("the picked variant's delta applied", r.data.status.includes(pickedDelta), JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/session`, { token: op });
ok('raw session keeps the whole block', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /<variants>/.test(e.m.content ?? '')), 'no <variants> in the raw log');
const pickNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'pick');
ok('pick note logged (the metric)', !!pickNote && pickNote.count === 2 && [0, 1].includes(pickNote.chosen), JSON.stringify(pickNote ?? null));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the table carries only the picked variant', r.data.entries.every((e) => e.t !== 'msg' || e.m.role !== 'assistant' || !/<\/?variants?>/.test(e.m.content ?? '')), 'variant syntax leaked into the table');
ok('the picked turn is her turn on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && e.m.content.includes(`<gained>${pickedDelta}`)), pickedDelta);
ok('the table drops thinking', r.data.entries.every((e) => e.m?.reasoning_content === undefined));
ok('the variance metric', r.data.variance.picks === 1 && r.data.variance.offered === 2 && r.data.variance.maxVariants === 2, JSON.stringify(r.data.variance));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She sets off.*' } });
ok('gm turn -> pending ask', r.status === 200 && !!r.data.pendingAsk, r.data.error ?? r.data.pendingAsk);
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'yes, clear toward the bow' } });
ok('ask answered', r.status === 200, r.data.error ?? '');
// 10b. the agenda: same-verb blocks combine (two <add> and two <gained>
// blocks in one turn); a bad drop conflicts, and the conflict goes back
// as its own message -- the model heals inside the same turn
r = await call(`/runs/${runId}`, { token: op });
ok('two add blocks combined, order kept', JSON.stringify(r.data.agenda) === '["find fresh water","signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
ok('two gained blocks combined', JSON.stringify(r.data.status.slice(-2)) === '["settled","curious about the clicking"]', JSON.stringify(r.data.status));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Evening comes.*' } });
ok('gm turn (drop)', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('agenda after drop', JSON.stringify(r.data.agenda) === '["signal any passing ship","build a shelter"]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Night falls.*' } });
ok('bad drop self-heals in the same turn', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
r = await call(`/runs/${runId}`, { token: op });
ok('heal applied (multi-index drop)', JSON.stringify(r.data.agenda) === '[]', JSON.stringify(r.data.agenda));
r = await call(`/runs/${runId}/session`, { token: op });
const conflictMsg = r.data.entries.find((e) => e.conflictOnly);
ok('conflict went as its own message', !!conflictMsg && /<conflict>agenda has no item at index 9<\/conflict>/.test(conflictMsg.m.content), conflictMsg?.m.content ?? 'none');
const cIdx = r.data.entries.indexOf(conflictMsg);
ok('the model answered the conflict', r.data.entries.slice(cIdx + 1).some((e) => e.t === 'msg' && e.m.role === 'assistant'), '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Dawn breaks.*' } });
ok('next gm turn is clean', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
const lastGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
ok('no conflict attached to the GM turn', !/<conflict>/.test(lastGm.m.content), lastGm.m.content.slice(-100));
ok('the empty agenda rides honestly', /<agenda><\/agenda>/.test(lastGm.m.content), lastGm.m.content.slice(-120));
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: op, body: { items: ['climb the ridge', 'rest'] } });
ok('agenda-set (GM override)', r.status === 200 && JSON.stringify(r.data.agenda) === '["climb the ridge","rest"]', JSON.stringify(r.data.agenda));
// 10c. the reminder: a system chunk after every GM turn, one live copy
r = await call(`/runs/${runId}/session`, { token: op });
const reminders = r.data.entries.filter((e) => e.reminder);
ok('reminder rode every GM turn', reminders.length === 5 && 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}/agenda`, { method: 'POST', token: ash, body: { items: [] } });
ok('agenda override owner-only', r.status === 403);
r = await call(`/runs/${runId}/status`, { token: op });
ok('status endpoint carries both', Array.isArray(r.data.status) && Array.isArray(r.data.agenda), JSON.stringify(r.data).slice(0, 120));
// 11. ash spectates: reads ok, mutates 403
r = await call(`/runs/${runId}`, { token: ash });
ok('ash reads run', r.status === 200 && r.data.run.ownerName === 'Op', r.data.error ?? '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: ash, body: { line: 'hi' } });
ok('ash turn 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { method: 'PUT', token: ash, body: { content: 'mine' } });
ok('ash notes write 403', r.status === 403);
r = await call(`/runs/${runId}/notes`, { token: ash });
ok('ash reads notes', r.status === 200); // spectators read the pad
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 ?? '');
// 12b. models: per-run overrides of the deployment defaults
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
ok('set models', r.status === 200 && r.data.models.player === 'mock' && r.data.models.housekeeper === 'mock-cheap', JSON.stringify(r.data));
ok('models stamped in run.json', meta(forkId).models?.player === 'mock' && meta(forkId).models?.housekeeper === 'mock-cheap');
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { housekeeper: null } });
ok('clear a role back to default', r.status === 200 && r.data.models.housekeeper === undefined && r.data.models.player === 'mock', JSON.stringify(r.data));
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: op, body: { player: 'x' } });
ok('model set is owner-only', r.status === 403);
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { bard: 'x' } });
ok('unknown role rejected', r.status === 400);
r = await call(`/runs/${forkId}`, { token: ash });
ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !!r.data.run.modelDefaults?.player, JSON.stringify(r.data.run.models));
r = await call('/models', { token: ash });
ok('model listing', r.status === 200 && Array.isArray(r.data) && r.data.includes('mock'));
// 13. ash saves a draft as a package (save-package is a draft act --
// the played-run refusal is checked at the end)
r = await call('/runs', { method: 'POST', token: ash, body: { package: 'la-caramba', pc: 'Ashling', name: 'Ash Draft' } });
ok('ash creates a draft', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const draftId = r.data.run?.id;
r = await call('/packages', { method: 'POST', token: ash, body: { from: draftId, name: 'Ash Pack' } });
ok('save-package', r.status === 200 && !!r.data.package?.id, r.data.error ?? r.data.package?.id);
const pkgId = r.data.package?.id;
r = await call('/packages', { token: op });
const saved = r.data.find((p) => p.name === pkgId);
ok('package listed with origin', !!saved && saved.origin === 'user' && saved.ownerName === 'Ash'
&& saved.pc === null && saved.display === 'Ash Pack', JSON.stringify(saved));
// 14. op creates a run from the user package
r = await call('/runs', { method: 'POST', token: op, body: { package: pkgId, pc: 'Secondina', name: 'Second Story' } });
ok('create from user package', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const secondId = r.data.run?.id;
// 15. op revokes ash -- identity destroyed, data stays
r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} });
ok('revoke ash', r.status === 200, r.data.error ?? '');
r = await call('/runs', { token: ash });
ok('ash token dead', r.status === 401);
r = await call(`/runs/${forkId}`, { token: op });
ok('fork now ownerless, session closed', r.status === 200 && r.data.run.owner === null && r.data.run.ownerName === null && r.data.open === false,
JSON.stringify(r.data.run));
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: op, body: { line: 'x' } });
ok('ownerless turn 403 even for op', r.status === 403 && /ownerless/.test(r.data.error));
r = await call('/packages', { token: op });
const saved2 = r.data.find((p) => p.name === pkgId);
ok('user package survives, ownerless', !!saved2 && saved2.owner === null && saved2.ownerName === null && saved2.display === 'Ash Pack',
JSON.stringify(saved2));
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const reforkId = r.data.run;
ok('fork carries the models', meta(reforkId).models?.player === 'mock');
// 16. users list, self-revoke refused
r = await call('/users', { token: op });
ok('users list', r.status === 200 && r.data.users.length === 1 && r.data.users[0].id === opId);
r = await call(`/users/${opId}/revoke`, { method: 'POST', token: op, body: {} });
ok('self-revoke refused', r.status === 409);
// 17. stop: the tail MOVES into dormant session 2 (the slidwin),
// housekeeping runs over what remains, the re-run rebases, start
// consumes the carry behind the bundle
const stopAndSettle = async (label) => {
r = await call(`/runs/${runId}/housekeeping`, { method: 'POST', token: op, body: {} });
ok(`${label} triggered`, r.status === 200 && r.data.state === 'running', r.data.error ?? JSON.stringify(r.data));
let hk = null;
for (let i = 0; i < 40; i++) {
hk = await call(`/runs/${runId}/housekeeping`, { token: op });
if (hk.data.state !== 'running') break;
await new Promise((res) => setTimeout(res, 100));
}
ok(`${label} applied`, hk.data.state === 'applied', JSON.stringify(hk.data));
return hk;
};
await stopAndSettle('stop (session 1)');
r = await call(`/runs/${runId}`, { token: op });
ok('dormant after stop', r.data.phase === 'dormant' && r.data.sessions === 2 && r.data.ready === true,
JSON.stringify({ phase: r.data.phase, sessions: r.data.sessions, ready: r.data.ready }));
r = await call(`/runs/${runId}/housekeeping`, { token: op });
ok('the job names the pass and the target', r.data.state === 'applied' && r.data.session === 1 && r.data.target === 2, JSON.stringify(r.data));
// the move: each line exists in exactly one jsonl, ever
const log1 = jsonl(runId, 1, 'log.jsonl');
const carry2 = jsonl(runId, 2, 'carryover.jsonl');
ok('the tail moved out of session 1', carry2.length > 0 && log1.every((e) => !carry2.some((c) => JSON.stringify(c) === JSON.stringify(e))),
`${carry2.length} carried lines`);
ok('the carry holds whole exchanges', carry2[0]?.t === 'msg' && carry2[0]?.m?.role === 'user' && !carry2[0]?.conflictOnly
&& carry2.some((e) => e.t === 'msg' && e.m.role === 'assistant'), carry2[0]?.t ?? 'nothing carried');
ok('the carry ends on her turn (no auto-send)', [...carry2].reverse().find((e) => e.t === 'msg' && !e.reminder)?.m?.role === 'assistant');
ok('no markers anywhere in the logs', log1.concat(carry2).every((e) => e.carried === undefined));
r = await call(`/runs/${runId}/carryover`, { token: op });
ok('the dormant preview renders the carry', r.status === 200 && r.data.session === 2 && r.data.ends === 'player' && r.data.entries.length === carry2.length,
JSON.stringify({ ends: r.data.ends, n: r.data.entries?.length }));
// the story reads whole, through dormancy, with no doubles
r = await call(`/runs/${runId}/story`, { token: op });
const gmTexts = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'gm').map((t) => t.text));
ok('the story has every GM turn exactly once', gmTexts.length === 5 && new Set(gmTexts).size === 5, `${gmTexts.length} gm turns across ${r.data.sessions.length} sessions`);
ok('the story reads the dormant carryover at the live edge', r.data.sessions.some((s) => s.turns.length >= 10));
const storyPlayer = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'player').map((t) => t.text));
ok('the story strips the verbs', storyPlayer.every((t) => !/<\/?(lost|gained|add|drop)>/.test(t)), '');
ok('the story carries no variant syntax', storyPlayer.every((t) => !/<\/?variants?>/.test(t)), '');
ok('the story strips the rides from GM prose', r.data.sessions.every((s) => s.turns.every((t) => t.who !== 'gm' || !/<\/?(status|agenda)>/.test(t.text))), '');
// the re-run: a fresh pass, rebased -- never double-applying
await stopAndSettle('re-run housekeeping (session 1)');
r = await call(`/runs/${runId}`, { token: op });
ok('still dormant, still ready', r.data.phase === 'dormant' && r.data.sessions === 2 && r.data.ready === true);
r = await call(`/runs/${runId}`, { token: op });
ok('the rebase kept the rings single-applied', r.data.fill.b === 2 && r.data.fill.a === 4, JSON.stringify(r.data.fill)); // 1 seeded + 1 inserted, once
// start session 2: the carry lands behind the bundle
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('start session 2', r.status === 200 && r.data.session === 2 && r.data.autoSend === false, r.data.error ?? JSON.stringify(r.data));
r = await call(`/runs/${runId}/table`, { token: op });
ok('the carry landed behind the bundle', r.data.entries.some((e) => e.t === 'bundle' && e.part === 'ring-a')
&& r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /waits for the world to move/.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 ?? '');
// 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');
// 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 ?? '');
console.log(`\nrun ids: source=${runId} fork=${forkId} second=${secondId} refork=${reforkId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);