variant round: roll retired, chance is variant literature (strict parse, crypto pick on reception, picked-only rendering, /story variance metric); entity round: /story the whole deliverable, /table the play projection, the slidwin carry (smart contwin cutoff, whole exchanges, housekeeper reads session-minus-tail); dormant-session rework: universal session lifecycle (dormant->live->finished, sessions/<n> storage), move-at-stop, start lint + auto-send rule, rebaseable housekeeping, turn-0 -> carryover.jsonl, seed -> memory.json, draft-only save-package; format house rules enforced by the nine-rule check-repo (ascii bytes, no text-mutating css); smoke 105/105 + restart + reminder + browser pass green, irene hand-migrated to the new layout

This commit is contained in:
2026-11-15 14:35:00 +00:00
parent c51d31078e
commit fa3f23b474
51 changed files with 3477 additions and 1719 deletions
+20 -11
View File
@@ -1,31 +1,40 @@
// test/check-reminder.mjs — unit-verifies the reminder elision
// test/check-reminder.mjs -- unit-verifies the reminder elision
// policy: the live context carries exactly one reminder (the newest),
// sitting at the freshest end, next to the one system trio from the
// bundle. Run against a run id that has GM turns:
// node test/check-reminder.mjs <runId>
import { loadSession, renderView } from '../server/session.mjs';
import { readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { loadSession, renderView, listSessions } from '../server/session.mjs';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const runId = process.argv[2];
const dir = join(ROOT, 'runs', runId, 'sessions');
const latest = readdirSync(dir).filter((f) => f.endsWith('.jsonl')).sort().pop().replace(/\.jsonl$/, '');
const s = loadSession(runId, latest);
if (!runId) {
console.error('usage: node test/check-reminder.mjs <runId>');
process.exit(1);
}
// the newest session that has a log (a dormant latest has none)
let s = null;
for (const n of [...listSessions(runId)].reverse()) {
try {
s = loadSession(runId, n);
break;
} catch {}
}
if (!s) {
console.error(`no session log under runs/${runId}/sessions/*/log.jsonl`);
process.exit(1);
}
const view = renderView(s);
const sys = view.filter((m) => m.role === 'system');
let fails = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` -- ${extra}` : ''}`);
if (!cond) fails++;
};
const logged = s.lines.filter((e) => e.reminder).length;
ok(`log keeps every copy (${logged})`, logged >= 5, `${logged}`);
ok('view carries exactly two system chunks (the trio + the newest reminder)', sys.length === 2, `${sys.length}`);
// mid-call the reminder is the last message; after the model's reply it
// sits immediately before that reply — either way it follows the newest
// sits immediately before that reply -- either way it follows the newest
// GM turn at the freshest end of the context
const ri = view.findIndex((m) => m.role === 'system' && /How to compose your turn/i.test(m.content));
const tail = view.slice(-3).map((m) => m.role).join(',');
+161
View File
@@ -0,0 +1,161 @@
// test/check-repo.mjs -- the repo's rules, enforced. Static scan of
// git-tracked files; no server needed:
// node test/check-repo.mjs
//
// 1. ASCII bytes everywhere (GM, 2026-11-15). No unicode in any
// tracked file; gitignored state (runs/, state/, server.json) is
// per-deployment and exempt. The ENCODING is the problem, never
// the visual: rendered glyphs travel ASCII-safe (\u escapes in
// JS, entities in HTML), never verbatim bytes.
// 2. No text-mutating CSS (GM, 2026-11-15). Rendered text must
// match authored text: no text-transform (any value, inline
// styles included), no generated content (content:, ::before and
// ::after included), no caps font variants. Authored content is
// fine -- want caps on screen, write caps in the source.
// 3. No HTML comments in prose or prompt files (GM, 2026-11-14):
// purpose descriptions live in README, AGENTS, or code comments.
// gm.md files are exempt -- GM-private, flagged to the GM, never
// agent-edited.
// 4. Retired terms stay retired (DICTIONARY rules the terms). The
// living prose -- README, the root prompts, the packages --
// never says: the wrap, prelude, paper (the old status), window
// (the old session; a line naming contwin may gloss it as the
// context window), turn-0, seed (memory.json is the name).
// Historical records keep the vocabulary of
// their day; gm.md is GM-private, flagged never fixed.
// 5. Zero-dependency stack (GM, 2026-11-13): every import is
// node: builtin or relative. No package manager, ever.
// 6. UTC discipline (GM, 2026-11-14): no locale- or timezone-
// dependent date formatting in code. No time zones, ever.
// 7. web/ static files never start with "api" -- the server's route
// guard matches the /api prefix, so web/api.mjs 404s as a bogus
// API route (bit once, 2026-11-14).
// 8. The bundle boundary (GM, 2026-11-14): server/bundle.mjs names
// neither gm.md (never model-facing) nor housekeeper.md (agent
// prompts never enter the bundle).
// 9. Seeds carry no date keys (GM, 2026-11-14): no model-facing
// surface renders a date; story time lives in prose.
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
let failures = 0;
const fail = (msg) => { console.log(`FAIL ${msg}`); failures++; };
const files = execFileSync('git', ['ls-files'], { encoding: 'utf8' }).split('\n').filter(Boolean);
const ROOT_PROMPTS = new Set(['system.md', 'invariants.md', 'handbook.md', 'housekeeper.md', 'reminder.md']);
const livingProse = (f) =>
f === 'README.md' || ROOT_PROMPTS.has(f)
|| (f.startsWith('packages/') && !f.endsWith('gm.md'));
// the checker's own source names what it bans (the rule patterns and
// their comments); it is exempt from the rules it defines
const isSelf = (f) => f === 'test/check-repo.mjs';
for (const f of files) {
const buf = readFileSync(f);
if (buf.includes(0)) continue; // binary -- no text rules to enforce
const text = buf.toString('utf8');
// rule 1: ascii bytes
text.split('\n').forEach((line, i) => {
for (const ch of line) {
if (ch.charCodeAt(0) > 0x7f) {
fail(`${f}:${i + 1} non-ascii U+${ch.charCodeAt(0).toString(16).padStart(4, '0')} "${ch}"`);
break; // one report per line is plenty
}
}
});
// rule 2: no text-mutating css. text-transform is linted in every
// code file (it only ever appears as a css property -- inline
// style attributes included); content: and font-variant are css
// file checks (content is a common js object key, and the docs
// discuss the rule by name)
if (/\.(css|html|mjs|js)$/.test(f) && !isSelf(f)) {
text.split('\n').forEach((line, i) => {
if (/text-transform/i.test(line)) {
fail(`${f}:${i + 1} text-mutating css: text-transform`);
}
});
}
if (f.endsWith('.css')) {
const stripped = text.replace(/\/\*[\s\S]*?\*\//g, ''); // comments are prose, not style
stripped.split('\n').forEach((line, i) => {
if (/(?<![-\w])content:\s/.test(line)) {
fail(`${f}:${i + 1} text-mutating css: generated content (${line.trim().slice(0, 60)})`);
}
if (/font-variant[^;]*caps/.test(line)) {
fail(`${f}:${i + 1} text-mutating css: caps font variant`);
}
});
}
// rule 3: no html comments in prose/prompt files
if (f.endsWith('.md') && !f.endsWith('gm.md')) {
text.split('\n').forEach((line, i) => {
if (line.includes('<!--')) fail(`${f}:${i + 1} html comment in a prose file`);
});
}
// rule 4: retired terms in living prose
if (livingProse(f)) {
text.split('\n').forEach((line, i) => {
if (/\bthe wrap\b/i.test(line)) fail(`${f}:${i + 1} retired term: "the wrap" (housekeeping)`);
if (/prelude/i.test(line)) fail(`${f}:${i + 1} retired term: "prelude" (turn-0)`);
if (/\bpaper\b/i.test(line)) fail(`${f}:${i + 1} retired term: "paper" (status)`);
// lowercase "window(s)" is the retired session; "Windows" the OS
// is consumed as-is; a line naming contwin may gloss its meaning
if (!/contwin/i.test(line) && /\bwindows?\b/.test(line)) {
fail(`${f}:${i + 1} retired term: "window" (session / contwin)`);
}
if (/turn-0/i.test(line)) fail(`${f}:${i + 1} retired term: "turn-0" (the carryover)`);
if (/\bseed(ed|s|ing)?\b/i.test(line)) fail(`${f}:${i + 1} retired term: "seed" (memory.json -- her starting memories)`);
});
}
// rule 5: zero-dependency imports
if (f.endsWith('.mjs')) {
for (const m of text.matchAll(/from\s+['"]([^'"]+)['"]/g)) {
const spec = m[1];
if (!spec.startsWith('node:') && !spec.startsWith('./') && !spec.startsWith('../')) {
fail(`${f}: non-builtin import "${spec}" -- the stack is zero-dependency`);
}
}
}
// rule 6: utc discipline
if (/\.(mjs|js)$/.test(f) && !isSelf(f)) {
text.split('\n').forEach((line, i) => {
if (/toLocale|getTimezoneOffset/.test(line)) {
fail(`${f}:${i + 1} locale/timezone-dependent formatting (UTC everywhere)`);
}
});
}
// rule 7: web static naming
if (f.startsWith('web/') && f.split('/').pop().startsWith('api')) {
fail(`${f}: a web/ static name starting with "api" 404s as a bogus API route`);
}
// rule 8: the bundle boundary
if (f === 'server/bundle.mjs') {
text.split('\n').forEach((line, i) => {
if (/gm\.md|housekeeper\.md/.test(line)) {
fail(`${f}:${i + 1} the bundle must not name gm.md or housekeeper.md`);
}
});
}
// rule 9: dateless memory -- no model-facing surface renders a date;
// story time lives in prose
if (f === 'memory.json' || (f.startsWith('packages/') && f.endsWith('memory.json'))) {
text.split('\n').forEach((line, i) => {
if (/"[^"]*date[^"]*"\s*:/i.test(line)) {
fail(`${f}:${i + 1} a memory manifest carries a date key -- story time lives in prose`);
}
});
}
}
console.log(failures ? `\n${failures} VIOLATIONS` : 'ALL CLEAN');
process.exit(failures ? 1 : 0);
+2 -2
View File
@@ -1,4 +1,4 @@
// test/restart-check.mjs — after a server restart: the token
// test/restart-check.mjs -- after a server restart: the token
// survives, the boot-rebuild reopened the unhousekept sessions, the
// runs list is whole. Reads the token + run ids smoke.mjs left in
// the temp file; run against the restarted --mock server:
@@ -18,7 +18,7 @@ const call = async (path, tok) => {
};
let failures = 0;
const ok = (name, cond, extra = '') => {
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` -- ${extra}` : ''}`);
if (!cond) failures++;
};
+168 -23
View File
@@ -1,8 +1,13 @@
// test/smoke.mjs — end-to-end multiuser pass against the --mock
// 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.
// 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:
@@ -11,7 +16,7 @@
// 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 { readFileSync, writeFileSync, appendFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
@@ -22,7 +27,7 @@ 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}` : ''}`);
console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra !== '' ? ` -- ${extra}` : ''}`);
if (!cond) failures++;
};
const call = async (path, { method = 'GET', token, body } = {}) => {
@@ -38,6 +43,8 @@ const call = async (path, { method = 'GET', token, body } = {}) => {
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');
@@ -74,35 +81,63 @@ const ashId = r.data.user.id;
r = await call('/invites', { method: 'POST', token: ash, body: {} });
ok('invite mint is op-only', r.status === 403);
// 8. op creates a run
// 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: session + turn0 (mock: roll, then reply)
// 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('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 ?? '');
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. a plain turn (mock: asks) + the answer
// 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
// 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.*' } });
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: '*Evening comes.*' } });
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));
@@ -111,7 +146,7 @@ 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.*' } });
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);
@@ -123,7 +158,7 @@ ok('agenda-set (GM override)', r.status === 200 && 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 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);
@@ -151,7 +186,7 @@ ok('fork owner + forked stamp', fm.owner === ashId && Number.isInteger(fm.forked
`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 ?? '');
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 ?? '');
@@ -170,21 +205,25 @@ ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !
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' } });
// 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 === 'Forked Pack', JSON.stringify(saved));
&& 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
// 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 });
@@ -196,7 +235,7 @@ r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: op, body: { line
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',
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);
@@ -209,6 +248,112 @@ ok('users list', r.status === 200 && r.data.users.length === 1 && r.data.users[0
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');