Files
tiny-worlds/test/smoke.mjs
T

216 lines
13 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, run lifecycle, spectator 403s, fork, save-package,
// create-from-user-package, revocation, ownerless state, the agenda
// deltas + self-heal, the reminder ride, per-run models.
// 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 } 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'));
// 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
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);
// 9. start: session + turn0 (mock: roll, then reply)
r = await call(`/runs/${runId}/sessions`, { method: 'POST', token: op, body: {} });
ok('session open', r.status === 200, r.data.error ?? r.data.session);
r = await call(`/runs/${runId}/turn0`, { method: 'POST', token: op, body: {} });
ok('turn0', r.status === 200, r.data.error ?? '');
// 10. a plain turn (mock: asks) + the answer
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*The tide comes in.*' } });
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: '*She sets off.*' } });
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: '*Evening comes.*' } });
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: '*Night falls.*' } });
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 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 the fork as a package
r = await call('/packages', { method: 'POST', token: ash, body: { from: forkId, name: 'Forked 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 === 'Forked 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 === 'Forked 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);
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);