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
2026-11-15 14:35:00 +00:00
// server/main.mjs -- entry + REST spine.
2026-11-14 03:15:53 +00:00
//
2026-11-14 20:01:15 +00:00
// Synchronous JSON over HTTP; the SPA and curl are both just clients.
// Multiuser: bearer-token identity (users.mjs), ownership gating on
// every mutation and model call, fork for everyone else. Boot-rebuild:
// every run whose latest session was not housekept gets its open
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
2026-11-15 14:35:00 +00:00
// session back from the jsonl -- the log is the truth, the context is a
2026-11-14 20:01:15 +00:00
// view.
2026-11-14 03:15:53 +00:00
//
// usage: node server/main.mjs [--mock]
import fs from 'node:fs' ;
import path from 'node:path' ;
import http from 'node:http' ;
import { fileURLToPath } from 'node:url' ;
import { makeProvider } from './provider.mjs' ;
2026-11-14 20:01:15 +00:00
import { clerkRaw , clerkRawJson , clerkJson , clerk } from './clerk.mjs' ;
2026-11-14 03:15:53 +00:00
import * as bundle from './bundle.mjs' ;
import * as session from './session.mjs' ;
import * as housekeeping from './housekeeping.mjs' ;
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
2026-11-15 14:35:00 +00:00
import { effectiveContents } from './variants.mjs' ;
import { gmTurn , answerAsk , openingCall , HttpError } from './loop.mjs' ;
2026-11-14 20:01:15 +00:00
import * as users from './users.mjs' ;
import { forkRun } from './fork.mjs' ;
2026-11-14 03:15:53 +00:00
const ROOT = path . resolve ( path . dirname ( fileURLToPath ( import . meta . url )), '..' );
const MOCK = process . argv . includes ( '--mock' );
const CONFIG_PATH = path . join ( ROOT , 'server.json' );
if ( ! fs . existsSync ( CONFIG_PATH )) {
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
2026-11-15 14:35:00 +00:00
console . error ( 'no server.json -- copy server.example.json and set your key in it (or via apiKeyEnv)' );
2026-11-14 03:15:53 +00:00
process . exit ( 1 );
}
const cfg = JSON . parse ( fs . readFileSync ( CONFIG_PATH , 'utf8' ));
2026-11-14 23:48:27 +00:00
if ( cfg . contextWindow && ! cfg . contwin ) console . warn ( 'config: contextWindow was renamed to contwin - the meter stays null until fixed' );
2026-11-14 03:15:53 +00:00
const provider = makeProvider ( cfg . endpoint ?? {});
const ctx = { mock : MOCK , cfg , provider , sessions : new Map (), jobs : new Map (), runMeta : bundle . runMeta };
2026-11-14 20:01:15 +00:00
// --- the per-run activity lock ---------------------------------------------------
//
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
2026-11-15 14:35:00 +00:00
// Serializes every async mutation span (turn, ask, start, the
2026-11-14 20:01:15 +00:00
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
2026-11-14 23:48:27 +00:00
// Sync-only handlers (status-set, file writes) need no lock: they
2026-11-14 20:01:15 +00:00
// block the event loop and are atomic by construction.
ctx . locks = new Map ();
ctx . enqueue = ( runId , fn ) => {
const prev = ctx . locks . get ( runId ) ?? Promise . resolve ();
const next = prev . then ( fn , fn ); // run regardless of a prior failure
ctx . locks . set ( runId , next . catch (() => {}));
return next ;
};
// --- bootstrap: the fresh-deployment superuser invite ---------------------------
const boot = users . bootstrap ();
if ( boot ? . code ) {
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
2026-11-15 14:35:00 +00:00
console . log ( `fresh deployment -- the superuser invite (also at ${ path . relative ( ROOT , users . bootstrapFile ) } ):` );
2026-11-14 20:01:15 +00:00
console . log ( ` ${ boot . code } ` );
} else if ( boot ? . reused ) {
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
2026-11-15 14:35:00 +00:00
console . log ( `fresh deployment -- the superuser invite waits at ${ path . relative ( ROOT , users . bootstrapFile ) } ` );
2026-11-14 20:01:15 +00:00
}
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
2026-11-15 14:35:00 +00:00
// --- boot --------------------------------------------------------------------
//
// The log is the truth, the context is a view. A stop that died in
// flight resumes first (every step idempotent); then every live
// session reopens from its jsonl.
2026-11-14 03:15:53 +00:00
if ( fs . existsSync ( path . join ( ROOT , 'runs' ))) {
for ( const d of fs . readdirSync ( path . join ( ROOT , 'runs' ), { withFileTypes : true })) {
2026-11-14 20:01:15 +00:00
if ( ! d . isDirectory () || d . name . startsWith ( '.' )) continue ; // .staging-* is never a run
2026-11-14 03:15:53 +00:00
if ( ! fs . existsSync ( path . join ( ROOT , 'runs' , d . name , 'run.json' ))) continue ;
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
2026-11-15 14:35:00 +00:00
const stalled = session . findStalledStop ( d . name );
if ( stalled ) {
session . stopSession ( d . name , stalled . from );
console . log ( `boot: resumed the interrupted stop of session ${ stalled . from } in ' ${ d . name } ' -- housekeeping is pending, re-run it` );
2026-11-14 03:15:53 +00:00
}
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
2026-11-15 14:35:00 +00:00
const live = session . liveSession ( d . name );
if ( live != null ) ctx . sessions . set ( d . name , session . loadSession ( d . name , live ));
2026-11-14 03:15:53 +00:00
}
}
// --- http plumbing -----------------------------------------------------------
const send = ( res , status , body ) => {
const data = JSON . stringify ( body );
res . writeHead ( status , { 'content-type' : 'application/json' , 'content-length' : Buffer . byteLength ( data ) });
res . end ( data );
};
const readBody = ( req ) => new Promise (( resolve , reject ) => {
const chunks = [];
let size = 0 ;
req . on ( 'data' , ( c ) => {
size += c . length ;
if ( size > 1024 * 1024 ) { reject ( new HttpError ( 413 , 'body too large' )); req . destroy (); return ; }
chunks . push ( c );
});
req . on ( 'end' , () => {
if ( ! chunks . length ) return resolve ({});
try { resolve ( JSON . parse ( Buffer . concat ( chunks ). toString ( 'utf8' ))); }
catch { reject ( new HttpError ( 400 , 'body is not valid JSON' )); }
});
req . on ( 'error' , reject );
});
const routes = [];
2026-11-14 20:01:15 +00:00
const route = ( method , pattern , handler , opts = {}) =>
routes . push ({ method , segs : pattern . split ( '/' ). filter ( Boolean ), handler , publicRoute : opts . public === true });
2026-11-14 03:15:53 +00:00
const match = ( method , pathname ) => {
const segs = pathname . split ( '/' ). filter ( Boolean );
outer : for ( const r of routes ) {
if ( r . method !== method || r . segs . length !== segs . length ) continue ;
const params = {};
for ( let i = 0 ; i < segs . length ; i ++ ) {
if ( r . segs [ i ]. startsWith ( ':' )) params [ r . segs [ i ]. slice ( 1 )] = decodeURIComponent ( segs [ i ]);
else if ( r . segs [ i ] !== segs [ i ]) continue outer ;
}
2026-11-14 20:01:15 +00:00
return { handler : r . handler , params , publicRoute : r . publicRoute };
2026-11-14 03:15:53 +00:00
}
return null ;
};
// --- static: the SPA in web/ -----------------------------------------------
// The API lives under /api/*; everything else serves web/ (index.html
// at /). Traversal-guarded; the SPA is a client like curl is.
const WEB_DIR = path . join ( ROOT , 'web' );
const MIME = {
'.html' : 'text/html; charset=utf-8' ,
'.js' : 'text/javascript; charset=utf-8' ,
'.mjs' : 'text/javascript; charset=utf-8' ,
'.css' : 'text/css; charset=utf-8' ,
'.svg' : 'image/svg+xml' ,
'.json' : 'application/json' ,
};
function serveStatic ( pathname , res ) {
let rel = decodeURIComponent ( pathname ). replace ( /^\/+/ , '' );
if ( ! rel ) rel = 'index.html' ;
const file = path . resolve ( WEB_DIR , rel );
if ( ! file . startsWith ( WEB_DIR + path . sep ) || ! fs . existsSync ( file ) || ! fs . statSync ( file ). isFile ()) {
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
2026-11-15 14:35:00 +00:00
// SPA fallback: client-side routes are extensionless paths --
2026-11-14 09:04:13 +00:00
// serve the shell; anything that looks like a file stays a 404
if ( path . extname ( rel )) { send ( res , 404 , { error : `no such file: ${ rel } ` }); return ; }
const shell = fs . readFileSync ( path . join ( WEB_DIR , 'index.html' ));
res . writeHead ( 200 , { 'content-type' : 'text/html; charset=utf-8' , 'content-length' : shell . length });
res . end ( shell );
2026-11-14 03:15:53 +00:00
return ;
}
const data = fs . readFileSync ( file );
res . writeHead ( 200 , { 'content-type' : MIME [ path . extname ( file )] ?? 'application/octet-stream' , 'content-length' : data . length });
res . end ( data );
}
2026-11-14 20:01:15 +00:00
// --- identity: session, claim, invites, users ---------------------------------
//
// Identity is a bearer token (server/users.mjs). Two routes are
// public: reading your own session (null when signed out) and
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
2026-11-15 14:35:00 +00:00
// claiming an invite. Everything else -- reads included -- requires a
2026-11-14 20:01:15 +00:00
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
route ( 'GET' , '/api/session' , async ({ user }) => ({
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
2026-11-15 14:35:00 +00:00
// the public shape only -- the stored row (token hash) never leaves
2026-11-14 21:15:32 +00:00
user : user ? { id : user . id , name : user . name , superuser : user . superuser === 1 } : null ,
2026-11-14 20:01:15 +00:00
fresh : users . userCount () === 0 ,
}), { public : true });
route ( 'POST' , '/api/claim' , async ({ body }) => {
const r = users . claimInvite ( body . code , body . name );
return { token : r . token , user : r . user };
}, { public : true });
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
2026-11-15 14:35:00 +00:00
// superuser: mint an invite -- the code is returned once, never stored
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/invites' , async ({ user }) => {
requireSuperuser ( user );
return users . mintInvite ( user . id );
});
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
2026-11-15 14:35:00 +00:00
// superuser: the invite ledger, hashes only -- codes are never listed
2026-11-14 20:01:15 +00:00
route ( 'GET' , '/api/invites' , async ({ user }) => {
requireSuperuser ( user );
const list = users . listInvites (). map (( i ) => ({
id : i . id ,
kind : i . kind ,
created_at : i . created_at ,
state : i . claimed_by == null ? 'unclaimed' : `claimed by ${ users . userName ( i . claimed_by ) ?? i . claimed_by } ` ,
}));
return { invites : list };
});
// superuser: revoke an unclaimed invite (handed to the wrong chat)
route ( 'DELETE' , '/api/invites/:id' , async ({ params , user }) => {
requireSuperuser ( user );
if ( ! users . revokeInvite ( Number ( params . id ))) throw new HttpError ( 409 , 'no such unclaimed invite' );
return { ok : true };
});
route ( 'GET' , '/api/users' , async ({ user }) => {
requireSuperuser ( user );
return { users : users . listUsers () };
});
// revocation destroys the identity: the token dies with the row. Their
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
2026-11-15 14:35:00 +00:00
// runs and packages stay on disk untouched -- the record of ownership
2026-11-14 20:01:15 +00:00
// keeps its dead id, which resolves to ownerless everywhere it is
2026-11-14 23:48:27 +00:00
// read. Only the live map is reconciled: their open sessions close.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/users/:id/revoke' , async ({ params , user }) => {
requireSuperuser ( user );
if ( params . id === user . id ) throw new HttpError ( 409 , 'revoking yourself would lock the deployment out of its superuser' );
if ( ! users . revokeUser ( params . id )) throw new HttpError ( 404 , `no such user: ${ params . id } ` );
for ( const id of [... ctx . sessions . keys ()]) {
if ( bundle . runMeta ( id ) ? . owner === params . id ) ctx . sessions . delete ( id );
}
return { ok : true };
});
function requireSuperuser ( user ) {
if ( ! user ? . superuser ) throw new HttpError ( 403 , 'superuser only' );
}
// ownership is resolved, never maintained: run.json keeps the record
// of who owned a run, and a dead owner id (revocation) resolves to
// absent. The API never exposes a dangling id.
const resolveOwner = ( owner ) => ( owner != null && users . exists ( owner ) ? owner : null );
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
2026-11-15 14:35:00 +00:00
// ownership: every GM action -- every mutation, every model call -- is
2026-11-14 20:01:15 +00:00
// the owner's alone. Ownerless runs (pre-user or revoked owner) are
// one uniform state: readable by all, forkable, never re-claimed.
function requireOwner ( user , runId ) {
bundle . requireRun ( runId ); // 404 when it doesn't exist
const meta = bundle . runMeta ( runId ) ?? {};
if ( resolveOwner ( meta . owner ) == null ) {
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
2026-11-15 14:35:00 +00:00
throw new HttpError ( 403 , `run ' ${ runId } ' is ownerless -- fork it to make it yours` );
2026-11-14 20:01:15 +00:00
}
if ( meta . owner !== user . id ) {
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
2026-11-15 14:35:00 +00:00
throw new HttpError ( 403 , `run ' ${ runId } ' is ${ users . userName ( meta . owner ) ?? 'another user' } 's -- fork it to continue as yours` );
2026-11-14 20:01:15 +00:00
}
return meta ;
}
2026-11-14 03:15:53 +00:00
// --- routes -------------------------------------------------------------------
2026-11-14 09:04:13 +00:00
route ( 'GET' , '/api' , async () => ({
2026-11-15 14:46:00 +00:00
service : 'tiny-worlds' , mock : MOCK , openSessions : ctx . sessions . size ,
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
2026-11-15 14:35:00 +00:00
// the live session inventory -- debugging state divergence at a glance
sessions : [... ctx . sessions . entries ()]. map (([ id , s ]) => ({ run : id , session : s . n , pendingAsk : !! s . pendingAsk })),
2026-11-14 09:04:13 +00:00
}));
2026-11-14 03:15:53 +00:00
route ( 'GET' , '/api/models' , async () => ( MOCK ? [ 'mock' ] : await provider . models ()));
2026-11-14 20:01:15 +00:00
route ( 'GET' , '/api/packages' , async () => {
const pkgs = clerkRawJson ( 'packages' );
for ( const p of pkgs ) {
if ( p . origin === 'user' ) {
p . owner = resolveOwner ( p . owner );
p . ownerName = p . owner == null ? null : users . userName ( p . owner );
}
}
return pkgs ;
});
// save a run's craft as a new user package, published to every user
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
2026-11-15 14:35:00 +00:00
// (gm.md included -- saving is the act of publishing). The pc never
2026-11-14 20:01:15 +00:00
// rides: the next create asks for one.
route ( 'POST' , '/api/packages' , async ({ body , user }) => {
const from = String ( body . from ?? '' ). trim ();
const name = String ( body . name ?? '' ). trim ();
if ( ! from ) throw new HttpError ( 400 , 'from (a run id) is required' );
if ( ! name ) throw new HttpError ( 400 , 'name (the new package\'s display name) is required' );
requireOwner ( user , from );
const r = clerk ( from , '--json' , '--owner' , user . id , 'save-package' , name );
if ( r . code !== 0 ) throw new HttpError ( 400 , r . err || r . out || 'save-package failed' );
return { package : JSON . parse ( r . out ) };
});
2026-11-14 03:15:53 +00:00
2026-11-14 22:00:04 +00:00
// the repo-fed prompts, read-only: per-project opening + guards,
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
2026-11-15 14:35:00 +00:00
// substrate invariants, and the per-turn reminder -- never copied into
2026-11-14 22:00:04 +00:00
// a run, so the editor shows them as context, not as something to edit
route ( 'GET' , '/api/prompts' , async () => {
const readOpt = ( f ) => ( fs . existsSync ( path . join ( ROOT , f )) ? fs . readFileSync ( path . join ( ROOT , f ), 'utf8' ). trim () : null );
return {
system : readOpt ( 'system.md' ),
invariants : readOpt ( 'invariants.md' ),
reminder : readOpt ( 'reminder.md' ),
};
});
2026-11-14 09:04:13 +00:00
// the clerk's list, enriched with what the server already knows: the
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
2026-11-15 14:35:00 +00:00
// live session, the pending ask, and the phase bookkeeping. A run's
// state is its latest session's -- live while one plays, else dormant
// (the review window); a draft is a dormant session one.
2026-11-14 09:04:13 +00:00
route ( 'GET' , '/api/runs' , async () => {
const runs = clerkRawJson ( 'runs' );
for ( const r of runs ) {
const s = ctx . sessions . get ( r . id );
r . open = !! s ;
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
2026-11-15 14:35:00 +00:00
r . session = s ? . n ?? null ;
2026-11-14 09:04:13 +00:00
r . pendingAsk = s ? . pendingAsk ? . question ?? null ;
2026-11-14 20:01:15 +00:00
r . owner = resolveOwner ( r . owner );
r . ownerName = r . owner == null ? null : users . userName ( r . owner );
2026-11-14 09:04:13 +00:00
}
return runs ;
});
// create: the pc's name is required (unique per package); the
// package display name defaults to the package's own. The id is
// anonymous, generated by the clerk.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs' , async ({ body , user }) => {
2026-11-14 03:15:53 +00:00
const pkg = String ( body . package ?? '' ). trim ();
2026-11-14 09:04:13 +00:00
const pc = String ( body . pc ?? '' ). trim ();
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
2026-11-15 14:35:00 +00:00
if ( ! /^[a-z0-9-]+$/ . test ( pkg )) throw new HttpError ( 400 , 'package must be a slug -- see GET /api/packages' );
if ( ! pc ) throw new HttpError ( 400 , 'pc is required -- the main character\'s name, distinct per package' );
2026-11-14 09:04:13 +00:00
const name = body . name === undefined ? undefined : String ( body . name );
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
2026-11-15 14:35:00 +00:00
const r = clerkRaw ( '--quiet' , '--json' , '--owner' , user . id , 'create' , pkg , pc , ...( name !== undefined ? [ name ] : []), ...( body . model ? [ String ( body . model )] : []));
2026-11-14 03:15:53 +00:00
if ( r . code !== 0 ) throw new HttpError ( 400 , r . err || r . out || 'create failed' );
2026-11-14 09:04:13 +00:00
const run = JSON . parse ( r . out );
return { run , dir : `runs/ ${ run . id } ` };
});
// a name to play as: rolled from the dictionary, unused by any run
route ( 'GET' , '/api/names' , async () => {
const all = fs . readFileSync ( path . join ( ROOT , 'names-female.txt' ), 'utf8' ). split ( '\n' ). map (( l ) => l . trim ()). filter ( Boolean );
const used = new Set ( clerkRawJson ( 'runs' ). flatMap (( r ) => ( r . pc ? [ String ( r . pc ). toLowerCase ()] : [])));
const free = all . filter (( n ) => ! used . has ( n . toLowerCase ()));
const pool = free . length ? free : all ; // a fully-used dictionary still suggests
return { name : pool [ Math . floor ( Math . random () * pool . length )] };
2026-11-14 03:15:53 +00:00
});
route ( 'GET' , '/api/runs/:id' , async ({ params }) => {
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 23:48:27 +00:00
const st = clerkJson ( id , '--json' , 'report' );
2026-11-14 03:15:53 +00:00
const s = ctx . sessions . get ( id );
const meta = bundle . runMeta ( id );
2026-11-14 20:01:15 +00:00
const owner = resolveOwner ( meta ? . owner );
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
2026-11-15 14:35:00 +00:00
const latest = session . latestSession ( id );
const sm = latest == null ? {} : session . sessionMeta ( id , latest );
const phase = s ? 'live' : ( sm . phase ?? null );
2026-11-14 03:15:53 +00:00
return {
2026-11-14 20:01:15 +00:00
run : {
id ,
package : meta ? . package ?? null ,
created : meta ? . created ?? null ,
forked : meta ? . forked ?? null ,
owner ,
ownerName : owner == null ? null : users . userName ( owner ),
2026-11-14 21:15:32 +00:00
models : meta ? . models ?? {},
modelDefaults : ctx . cfg . models ?? {},
2026-11-14 20:01:15 +00:00
},
2026-11-14 09:04:13 +00:00
display : bundle . runDisplay ( id ),
2026-11-14 03:15:53 +00:00
open : !! s ,
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
2026-11-15 14:35:00 +00:00
phase ,
session : s ? . n ?? null ,
sessions : latest ?? 0 ,
draft : phase === 'dormant' && latest === 1 , // a never-started run
ready : sm . ready ?? null ,
2026-11-14 23:48:27 +00:00
status : st . status ,
2026-11-14 21:15:32 +00:00
agenda : st . agenda ,
2026-11-14 03:15:53 +00:00
records : st . records ,
fill : st . rings ,
events : st . events ,
pendingAsk : s ? . pendingAsk ? . question ?? null ,
usage : s ? . usage ?? null ,
context : s ? . usage ? {
used : s . usage . promptTokens ,
2026-11-14 23:48:27 +00:00
contwin : cfg . contwin ?? null ,
pct : cfg . contwin ? Math . round (( 100 * s . usage . promptTokens ) / cfg . contwin ) : null ,
2026-11-14 03:15:53 +00:00
} : null ,
};
});
2026-11-14 09:04:13 +00:00
// --- run files: the editor's surface ------------------------------------------
//
// A fixed whitelist, not a path API: state dirs are the clerk's
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
2026-11-15 14:35:00 +00:00
// alone. The ADDRESSED session is the live one while one plays, else
// the latest (the dormant one during the review window). Its bundle
// (the frozen craft) is writable only while dormant; the authored
// carryover of session one is authoring material (writable), a
// continuation carryover is conversation (read-only until the editor
// task); memory.json is inert provenance, read-only. housekeeper.md
// is substrate-internal (repo-fed at housekeeping, never copied, not
// exposed here) and gm.md lives only in the notepad endpoints (the
// play-view pad); config is read-only (vars and lineage are easy to
// break blind).
function fileSurface ( runId ) {
const live = ctx . sessions . get ( runId );
const latest = session . latestSession ( runId );
if ( latest == null ) throw new HttpError ( 409 , 'this run has no sessions' );
const n = live ? . n ?? latest ;
const dir = session . sessionDir ( runId , n );
const phase = live ? 'live' : session . sessionMeta ( runId , n ). phase ;
const dormant = phase === 'dormant' ;
const rw = dormant ? 'rw' : 'ro' ;
const root = bundle . runDir ( runId );
const spec = {
'handbook.md' : { mode : rw , path : path . join ( dir , 'bundle' , 'handbook.md' ) },
'backdrop.md' : { mode : rw , path : path . join ( dir , 'bundle' , 'backdrop.md' ) },
'character.md' : { mode : rw , path : path . join ( dir , 'bundle' , 'character.md' ) },
'carryover.jsonl' : { mode : dormant && n === 1 ? 'rw' : 'ro' , path : path . join ( dir , 'carryover.jsonl' ) },
'memory.json' : { mode : 'ro' , path : path . join ( dir , 'memory.json' ) }, // session one's provenance; absent later
'settings.json' : { mode : 'ro' , path : path . join ( root , 'settings.json' ) },
'run.json' : { mode : 'ro' , path : path . join ( root , 'run.json' ) },
};
return { n , phase , files : spec };
}
2026-11-14 09:04:13 +00:00
route ( 'GET' , '/api/runs/:id/files' , async ({ params }) => {
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
2026-11-15 14:35:00 +00:00
bundle . requireRun ( params . id );
const surf = fileSurface ( params . id );
2026-11-14 09:04:13 +00:00
const files = {};
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
2026-11-15 14:35:00 +00:00
for ( const [ f , spec ] of Object . entries ( surf . files )) {
files [ f ] = fs . existsSync ( spec . path )
? { mode : spec . mode , exists : true , content : fs . readFileSync ( spec . path , 'utf8' ) }
: { mode : spec . mode , exists : false };
2026-11-14 09:04:13 +00:00
}
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
2026-11-15 14:35:00 +00:00
return { session : surf . n , phase : surf . phase , files };
2026-11-14 09:04:13 +00:00
});
2026-11-14 20:01:15 +00:00
route ( 'PUT' , '/api/runs/:id/files/:path' , async ({ params , body , user }) => {
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
2026-11-15 14:35:00 +00:00
bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
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
2026-11-15 14:35:00 +00:00
const surf = fileSurface ( params . id );
2026-11-14 09:04:13 +00:00
const f = params . path ;
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
2026-11-15 14:35:00 +00:00
const spec = surf . files [ f ];
if ( ! spec ) throw new HttpError ( 404 , `no such run file in the API surface: ${ f } ` );
if ( spec . mode !== 'rw' ) throw new HttpError ( 403 , ` ${ f } is read-only (session ${ surf . n } is ${ surf . phase } )` );
2026-11-14 09:04:13 +00:00
if ( typeof body . content !== 'string' || ! body . content . trim ()) throw new HttpError ( 400 , 'content (a non-empty string) is required' );
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
2026-11-15 14:35:00 +00:00
if ( f === 'carryover.jsonl' ) {
// the save-time lint: only clean openings land (the start lint is
// the backstop, not the first line of defense)
const lines = [];
const raw = body . content . split ( '\n' );
for ( let i = 0 ; i < raw . length ; i ++ ) {
if ( ! raw [ i ]. trim ()) continue ;
try {
lines . push ( JSON . parse ( raw [ i ]));
} catch {
throw new HttpError ( 400 , `not valid JSONL: line ${ i + 1 } does not parse` );
}
}
const errors = session . lintCarryover ( lines , { authored : surf . n === 1 });
if ( errors . length ) throw new HttpError ( 400 , `the carryover did not pass the lint: ${ errors . join ( '; ' ) } ` );
2026-11-14 09:04:13 +00:00
}
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
2026-11-15 14:35:00 +00:00
fs . writeFileSync ( spec . path , body . content );
2026-11-14 09:04:13 +00:00
return { ok : true , file : f , bytes : Buffer . byteLength ( body . content ) };
});
// prompt vars: the inputs the prompts themselves declare ($TOKENS
// found in any prompt file). Values live in the run's settings vars.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/vars' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
2026-11-14 09:04:13 +00:00
const vars = body . vars ;
if ( typeof vars !== 'object' || vars === null || Array . isArray ( vars )) throw new HttpError ( 400 , 'vars (an object of token -> value) is required' );
for ( const [ k , v ] of Object . entries ( vars )) {
if ( ! /^[A-Za-z][A-Za-z0-9_]*$/ . test ( k )) throw new HttpError ( 400 , `bad var name: ${ JSON . stringify ( k ) } ` );
if ( typeof v !== 'string' ) throw new HttpError ( 400 , `var ${ k } must be a string` );
}
const settings = bundle . readSettings ( params . id );
settings . vars = { ...( settings . vars ?? {}), ... vars };
fs . writeFileSync ( path . join ( dir , 'settings.json' ), JSON . stringify ( settings , null , 2 ) + '\n' );
return { ok : true , vars : settings . vars };
});
2026-11-14 21:15:32 +00:00
// the run's models: per-run overrides of the deployment defaults
// (server.json), selected from the upstream listing (GET /api/models).
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
2026-11-15 14:35:00 +00:00
// Owner-only, changeable at any time -- every call resolves fresh, so a
2026-11-14 23:48:27 +00:00
// mid-session switch simply takes the next turn. null clears a role
2026-11-14 21:15:32 +00:00
// back to its deployment default.
route ( 'POST' , '/api/runs/:id/model' , async ({ params , body , user }) => {
const id = params . id ;
bundle . requireRun ( id );
requireOwner ( user , id );
for ( const k of Object . keys ( body )) {
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
2026-11-15 14:35:00 +00:00
if ( k !== 'player' && k !== 'housekeeper' ) throw new HttpError ( 400 , `unknown model role: ${ k } -- player and housekeeper` );
2026-11-14 21:15:32 +00:00
}
const meta = bundle . runMeta ( id ) ?? {};
const models = meta . models ?? {};
for ( const role of [ 'player' , 'housekeeper' ]) {
if ( body [ role ] === undefined ) continue ;
if ( body [ role ] === null ) { delete models [ role ]; continue ; }
const m = String ( body [ role ]). trim ();
if ( ! m ) throw new HttpError ( 400 , ` ${ role } : a model name, or null to fall back to the deployment default` );
models [ role ] = m ;
}
if ( Object . keys ( models ). length ) meta . models = models ;
else delete meta . models ;
fs . writeFileSync ( path . join ( bundle . runDir ( id ), 'run.json' ), JSON . stringify ( meta , null , 2 ) + '\n' );
return { ok : true , models : meta . models ?? {}, defaults : ctx . cfg . models ?? {} };
});
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
2026-11-15 14:35:00 +00:00
// the GM's notepad: the run's gm.md -- always editable in the SPA,
2026-11-14 09:04:13 +00:00
// never in any bundle, never sent to any model (no assembly path
// reads it). Seeded from the package at creation, the GM's to keep.
route ( 'GET' , '/api/runs/:id/notes' , async ({ params }) => {
const dir = bundle . requireRun ( params . id );
const file = path . join ( dir , 'gm.md' );
return { content : fs . existsSync ( file ) ? fs . readFileSync ( file , 'utf8' ) : '' };
});
2026-11-14 20:01:15 +00:00
route ( 'PUT' , '/api/runs/:id/notes' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id ); // spectators read the pad, the owner writes it
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
2026-11-15 14:35:00 +00:00
if ( typeof body . content !== 'string' ) throw new HttpError ( 400 , 'content (a string) is required -- empty clears the pad' );
2026-11-14 09:04:13 +00:00
fs . writeFileSync ( path . join ( dir , 'gm.md' ), body . content );
return { ok : true };
});
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
2026-11-15 14:35:00 +00:00
// delete a DRAFT: a run whose sessions were never started holds
// nothing but its copy, so the directory is the whole run and removal
// is complete. A played run is a story -- deleting one is a
// deliberate act that stays by hand (Remove-Item runs/<id>), not a
// button.
2026-11-14 20:01:15 +00:00
route ( 'DELETE' , '/api/runs/:id' , async ({ params , user }) => {
2026-11-14 09:04:13 +00:00
const dir = bundle . requireRun ( params . id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
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
2026-11-15 14:35:00 +00:00
const played = session . listSessions ( params . id ). some (( n ) => fs . existsSync ( path . join ( session . sessionDir ( params . id , n ), 'log.jsonl' )));
if ( played ) {
throw new HttpError ( 409 , `this run has been played -- its sessions and memory stay until deleted by hand: Remove-Item -Recurse ${ path . join ( 'runs' , params . id ) } ` );
2026-11-14 09:04:13 +00:00
}
fs . rmSync ( dir , { recursive : true , force : true });
return { ok : true , deleted : params . id };
});
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
2026-11-15 14:35:00 +00:00
// start: the dormant session goes live -- lint the carryover, freeze
// the bundle, consume the carryover into the log. If the carryover
// ends on a GM turn, that turn is her cue: the first request of the
// assembled contwin fires automatically. Everything rides the run's
// activity lock (serialized with turns and the housekeeping job).
2026-11-14 23:48:27 +00:00
route ( 'POST' , '/api/runs/:id/sessions' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const id = params . id ;
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
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
2026-11-15 14:35:00 +00:00
if ( ctx . sessions . has ( id )) throw new HttpError ( 409 , `session ${ ctx . sessions . get ( id ). n } is already live -- one active session per run` );
return ctx . enqueue ( id , async () => {
const { session : s , autoSend } = session . startSession ( id , { override : body . override === true });
ctx . sessions . set ( id , s );
const out = { ok : true , session : s . n , autoSend };
if ( autoSend ) return { ... out , ...( await openingCall ( ctx , id , user )) };
return out ;
});
2026-11-14 03:15:53 +00:00
});
route ( 'GET' , '/api/runs/:id/session' , async ({ params }) => {
const s = ctx . sessions . get ( params . id );
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
2026-11-15 14:35:00 +00:00
if ( ! s ) throw new HttpError ( 404 , `no live session for ' ${ params . id } '` );
2026-11-14 03:15:53 +00:00
return {
run : params . id ,
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
2026-11-15 14:35:00 +00:00
session : s . n ,
2026-11-14 03:15:53 +00:00
entries : s . lines ,
pendingAsk : s . pendingAsk ? . question ?? null ,
usage : s . usage ,
};
});
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
2026-11-15 14:35:00 +00:00
// the carryover: the dormant session's opening material, raw and
// read-only -- the review window's preview of the next contwin. Same
// projection as the table (the picked variant only, thinking stays in
// the raw log), plus the ending that decides the opening flow.
route ( 'GET' , '/api/runs/:id/carryover' , async ({ params }) => {
bundle . requireRun ( params . id );
const live = ctx . sessions . get ( params . id );
if ( live ) throw new HttpError ( 409 , `session ${ live . n } is live -- the table is the surface` );
const latest = session . latestSession ( params . id );
if ( latest == null ) throw new HttpError ( 404 , 'no sessions' );
const meta = session . sessionMeta ( params . id , latest );
if ( meta . phase !== 'dormant' ) throw new HttpError ( 409 , `session ${ latest } is ${ meta . phase || 'unmarked' } ` );
const p = path . join ( session . sessionDir ( params . id , latest ), 'carryover.jsonl' );
const lines = [];
if ( fs . existsSync ( p )) {
for ( const l of fs . readFileSync ( p , 'utf8' ). split ( '\n' )) {
if ( ! l . trim ()) continue ;
try {
lines . push ( JSON . parse ( l ));
} catch {
throw new HttpError ( 422 , 'the carryover is not valid JSONL -- fix it before start' );
}
}
}
const eff = effectiveContents ( lines );
const entries = lines . map (( e , i ) => {
if ( e . t === 'msg' && e . m . role === 'assistant' ) {
const m = { role : 'assistant' , content : eff . has ( i ) ? eff . get ( i ) : ( e . m . content ?? null ) };
if ( e . m . tool_calls ? . length ) m . tool_calls = e . m . tool_calls ;
return { ... e , m };
}
return e ;
});
const lastMsg = [... lines ]. reverse (). find (( e ) => e . t === 'msg' && ! e . reminder );
return {
run : params . id ,
session : latest ,
ready : meta . ready === true ,
entries ,
ends : lastMsg == null ? null : ( lastMsg . m . role === 'user' ? 'gm' : 'player' ),
};
});
// the table: the play surface's projection of the live session --
// what the GM needs at the table. Same envelope as /session,
// different policy over the same log: thinking never crosses the
// wire, variant turns carry only the picked variant. The raw
// /session stays whole as the audit surface; during dormancy the
// /carryover endpoint is the table's stand-in.
route ( 'GET' , '/api/runs/:id/table' , async ({ params }) => {
const s = ctx . sessions . get ( params . id );
if ( ! s ) throw new HttpError ( 404 , `no live session for ' ${ params . id } '` );
const eff = effectiveContents ( s . lines );
const entries = s . lines . map (( e , i ) => {
if ( e . t === 'msg' && e . m . role === 'assistant' ) {
const m = { role : 'assistant' , content : eff . has ( i ) ? eff . get ( i ) : ( e . m . content ?? null ) };
if ( e . m . tool_calls ? . length ) m . tool_calls = e . m . tool_calls ;
return { ... e , m };
}
return e ;
});
// the variantary metric: how variant she tends to be, straight off
// the pick notes (counted, never content)
const picks = s . lines . filter (( e ) => e . t === 'note' && e . kind === 'pick' );
return {
run : params . id ,
session : s . n ,
entries ,
pendingAsk : s . pendingAsk ? . question ?? null ,
usage : s . usage ,
variance : {
picks : picks . length ,
offered : picks . reduce (( a , p ) => a + ( p . count ?? 0 ), 0 ),
maxVariants : picks . reduce (( a , p ) => Math . max ( a , p . count ?? 0 ), 0 ),
},
};
});
// the story: the whole deliverable, read-only -- every non-dropped
// literature turn from the opening to the last recorded, across all
// sessions in order. OOC, tool calls, substrate verbs, thinking,
// rings, machinery: all out; load-bearing prose living inside OOC
// only is a GM protocol violation, and the story enforces that by
// omission. A dormant session's carryover is the story's live edge:
// its raw lines project like any log's, at the chronological end --
// GM edits during dormancy show, because the carryover is the current
// truth of where the story stands.
route ( 'GET' , '/api/runs/:id/story' , async ({ params }) => {
bundle . requireRun ( params . id );
const rides = /<(status|agenda|conflict)>[\s\S]*?<\/\1>/g ;
const verbs = /<(lost|gained|add|drop)>[\s\S]*?<\/\1>/g ;
const project = ( lines ) => {
const eff = effectiveContents ( lines );
const turns = [];
for ( let i = 0 ; i < lines . length ; i ++ ) {
const e = lines [ i ];
if ( e . t !== 'msg' || e . reminder ) continue ;
if ( e . m . role === 'user' && ! e . conflictOnly ) {
const text = String ( e . m . content ?? '' ). replace ( rides , '' ). trim ();
if ( text ) turns . push ({ who : 'gm' , text });
} else if ( e . m . role === 'assistant' && ! e . m . tool_calls ? . length ) {
// tool prose is for the tool result turn, not the story
const text = String ( eff . has ( i ) ? eff . get ( i ) : ( e . m . content ?? '' )). replace ( verbs , '' ). trim ();
if ( text ) turns . push ({ who : 'player' , text });
}
}
return turns ;
};
const readJsonl = ( p ) => {
const out = [];
if ( ! fs . existsSync ( p )) return out ;
for ( const l of fs . readFileSync ( p , 'utf8' ). split ( '\n' )) {
if ( ! l . trim ()) continue ;
try {
out . push ( JSON . parse ( l ));
} catch {
// a malformed line fails loud at start; the story skips it
}
}
return out ;
};
const sessions = [];
for ( const n of session . listSessions ( params . id )) {
const dir = session . sessionDir ( params . id , n );
const meta = session . sessionMeta ( params . id , n );
const lines = readJsonl ( path . join ( dir , 'log.jsonl' ));
const turns = project ( lines );
if ( meta . phase === 'dormant' ) {
turns . push (... project ( readJsonl ( path . join ( dir , 'carryover.jsonl' ))));
}
if ( turns . length ) sessions . push ({ session : n , turns });
}
return { run : params . id , sessions };
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/turn' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const line = String ( body . line ?? '' ). trim ();
if ( ! line ) throw new HttpError ( 400 , 'line is required' );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
return { ok : true , ...( await ctx . enqueue ( params . id , () => gmTurn ( ctx , params . id , line , user ))) };
2026-11-14 03:15:53 +00:00
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/ask' , async ({ params , body , user }) => {
2026-11-14 03:15:53 +00:00
const answer = String ( body . answer ?? '' ). trim ();
if ( ! answer ) throw new HttpError ( 400 , 'answer is required' );
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
return { ok : true , ...( await ctx . enqueue ( params . id , () => answerAsk ( ctx , params . id , answer , user ))) };
});
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
2026-11-15 14:35:00 +00:00
// fork: any user, any run -- a mechanical atomic copy with the owner
2026-11-14 20:01:15 +00:00
// replaced (server/fork.mjs). The source's activity lock is held, so
// the copy is never taken mid-turn.
route ( 'POST' , '/api/runs/:id/fork' , async ({ params , user }) => {
bundle . requireRun ( params . id );
return ctx . enqueue ( params . id , () => forkRun ( ctx , params . id , user ));
2026-11-14 03:15:53 +00:00
});
route ( 'GET' , '/api/runs/:id/status' , async ({ params }) => {
bundle . requireRun ( params . id );
2026-11-14 23:48:27 +00:00
return { status : clerkJson ( params . id , 'status' ), agenda : clerkJson ( params . id , 'agenda' ) };
2026-11-14 03:15:53 +00:00
});
2026-11-14 23:48:27 +00:00
// the GM's out-of-band status override: whole-status replace via the
2026-11-14 09:04:13 +00:00
// clerk (which journals the prior state). Descriptions never contain
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
2026-11-15 14:35:00 +00:00
// commas -- the transport is comma-separated -- so a comma inside an
2026-11-14 09:04:13 +00:00
// item is a 400, not a silent corruption later.
2026-11-14 23:48:27 +00:00
route ( 'POST' , '/api/runs/:id/status' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
2026-11-14 09:04:13 +00:00
const items = body . items ;
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
2026-11-15 14:35:00 +00:00
if ( ! Array . isArray ( items )) throw new HttpError ( 400 , 'items (an array of descriptions) is required -- an empty array clears the status' );
2026-11-14 09:04:13 +00:00
for ( const it of items ) {
if ( typeof it !== 'string' || ! it . trim ()) throw new HttpError ( 400 , 'every item must be a non-empty string' );
if ( it . includes ( ',' )) throw new HttpError ( 400 , `descriptions never contain commas (the transport is comma-separated): ${ JSON . stringify ( it ) } ` );
}
2026-11-14 23:48:27 +00:00
const status = clerkJson ( id , '--gm' , 'status-set' , ... items );
return { ok : true , status };
2026-11-14 09:04:13 +00:00
});
2026-11-14 21:15:32 +00:00
// the GM's out-of-band agenda override: whole-queue replace via the
// clerk (journaled). Items land in written order, first = top; an
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
2026-11-15 14:35:00 +00:00
// empty array clears it. Commas are the add transport's separator --
2026-11-14 21:15:32 +00:00
// an item containing one is a 400, not a silent split later.
route ( 'POST' , '/api/runs/:id/agenda' , async ({ params , body , user }) => {
const id = params . id ;
bundle . requireRun ( id );
requireOwner ( user , id );
const items = body . items ;
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
2026-11-15 14:35:00 +00:00
if ( ! Array . isArray ( items )) throw new HttpError ( 400 , 'items (an array of descriptions) is required -- an empty array clears the agenda' );
2026-11-14 21:15:32 +00:00
for ( const it of items ) {
if ( typeof it !== 'string' || ! it . trim ()) throw new HttpError ( 400 , 'every item must be a non-empty string' );
if ( it . includes ( ',' )) throw new HttpError ( 400 , `items never contain commas (the add transport is comma-separated): ${ JSON . stringify ( it ) } ` );
}
const agenda = clerkJson ( id , '--gm' , 'agenda-set' , ... items );
return { ok : true , agenda };
});
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping' , async ({ params , user }) => {
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
2026-11-15 14:35:00 +00:00
// with a live session this is STOP (close, move the tail, freeze,
// then the pass); with a dormant latest it is the RE-RUN. Poll GET
// for the outcome.
2026-11-14 20:01:15 +00:00
requireOwner ( user , params . id );
const job = housekeeping . trigger ( ctx , params . id , user );
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
2026-11-15 14:35:00 +00:00
return { state : job . state , phase : job . phase , session : job . session , target : job . target ?? null };
2026-11-14 03:15:53 +00:00
});
2026-11-14 09:04:13 +00:00
// dry-run the housekeeper over a session log: the same transcript
2026-11-14 23:48:27 +00:00
// assembly the real housekeeping uses, a real housekeeper call, the manifest
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
2026-11-15 14:35:00 +00:00
// saved for review -- but nothing applied, no state touched. The way
// to iterate on housekeeper.md against real data without playing
// more; works on the live session and on finished ones alike.
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping/replay' , async ({ params , body , user }) => {
2026-11-14 09:04:13 +00:00
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id ); // a replay spends a model call on the shared key
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
2026-11-15 14:35:00 +00:00
const latest = session . latestSession ( id );
if ( latest == null ) throw new HttpError ( 409 , 'no session to replay -- this run has none' );
// default: the newest session that has a log -- the live one, else
// the finished predecessor of a dormant latest
const n = body ? . session != null ? Number ( body . session ) : ( ctx . sessions . get ( id ) ? . n ?? latest - 1 );
if ( ! Number . isInteger ( n ) || n < 1 ) throw new HttpError ( 409 , 'no session log to replay yet' );
2026-11-14 09:04:13 +00:00
let lines ;
try {
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
2026-11-15 14:35:00 +00:00
lines = session . loadSession ( id , n ). lines ;
2026-11-14 09:04:13 +00:00
} catch {
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
2026-11-15 14:35:00 +00:00
throw new HttpError ( 404 , `no such session log: ${ n } ` );
2026-11-14 09:04:13 +00:00
}
if ( ! lines . some (( e ) => e . t === 'msg' )) throw new HttpError ( 409 , 'that session has no exchange to review' );
const dir = path . join ( bundle . runDir ( id ), 'manifests' );
fs . mkdirSync ( dir , { recursive : true });
const text = ctx . mock
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
2026-11-15 14:35:00 +00:00
? housekeeping . mockManifest ( n )
: await housekeeping . callHousekeeper ( ctx , id , housekeeping . buildMessages ( id , n , lines ), user );
2026-11-14 09:04:13 +00:00
let mf ;
try {
mf = housekeeping . parseManifest ( text );
} catch ( e ) {
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
2026-11-15 14:35:00 +00:00
const raw = path . join ( dir , ` ${ n } .replay.raw.md` );
2026-11-14 09:04:13 +00:00
fs . writeFileSync ( raw , String ( text ));
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
2026-11-15 14:35:00 +00:00
return { ok : true , parsed : false , session : n , file : `manifests/ ${ n } .replay.raw.md` , reason : e . message };
2026-11-14 09:04:13 +00:00
}
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
2026-11-15 14:35:00 +00:00
const file = path . join ( dir , ` ${ n } .replay.json` );
2026-11-14 09:04:13 +00:00
fs . writeFileSync ( file , JSON . stringify ( mf , null , 2 ) + '\n' );
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
2026-11-15 14:35:00 +00:00
return { ok : true , parsed : true , session : n , file : `manifests/ ${ n } .replay.json` , manifest : mf };
2026-11-14 09:04:13 +00:00
});
2026-11-14 03:15:53 +00:00
route ( 'GET' , '/api/runs/:id/housekeeping' , async ({ params }) => housekeeping . jobState ( ctx , params . id ));
route ( 'GET' , '/api/runs/:id/housekeeping/log' , async ({ params }) => housekeeping . latestLog ( params . id ));
2026-11-14 20:01:15 +00:00
route ( 'POST' , '/api/runs/:id/housekeeping/apply' , async ({ params , body , user }) => {
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
2026-11-15 14:35:00 +00:00
// the recovery path: apply a (hand-edited) manifest directly -- the
// rebase + apply + ready, into the dormant continuation session
2026-11-14 03:15:53 +00:00
const id = params . id ;
bundle . requireRun ( id );
2026-11-14 20:01:15 +00:00
requireOwner ( user , id );
2026-11-14 03:15:53 +00:00
const file = String ( body . file ?? '' ). trim ();
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
2026-11-15 14:35:00 +00:00
if ( ! file ) throw new HttpError ( 400 , 'file is required -- a manifest path relative to the run dir, e.g. manifests/<session>.json' );
2026-11-14 03:15:53 +00:00
const manifestPath = path . resolve ( path . join ( ROOT , 'runs' , id ), file );
if ( ! manifestPath . startsWith ( path . join ( ROOT , 'runs' , id ))) throw new HttpError ( 400 , 'file must stay inside the run dir' );
if ( ! fs . existsSync ( manifestPath )) throw new HttpError ( 404 , `no such manifest: ${ file } ` );
const latest = session . latestSession ( id );
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
2026-11-15 14:35:00 +00:00
if ( latest == null || latest < 2 ) throw new HttpError ( 409 , 'no dormant continuation session to apply into' );
if ( session . sessionMeta ( id , latest ). phase !== 'dormant' ) throw new HttpError ( 409 , `session ${ latest } is not dormant` );
return ctx . enqueue ( id , () => {
try {
housekeeping . applyToDormant ( id , manifestPath , latest - 1 );
return { ok : true , housekept : latest - 1 , target : latest };
} catch ( e ) {
ctx . jobs . set ( id , { state : 'rejected' , session : latest - 1 , reason : e . message });
throw new HttpError ( 422 , e . message );
}
});
2026-11-14 03:15:53 +00:00
});
// --- dispatch -------------------------------------------------------------------
2026-11-14 20:01:15 +00:00
// bearer-token identity (users.mjs); null when absent or unknown
function authenticate ( req ) {
const m = /^Bearer\s+(.+)$/i . exec ( req . headers . authorization ?? '' );
return m ? users . getUserByToken ( m [ 1 ]. trim ()) : null ;
}
2026-11-14 03:15:53 +00:00
const server = http . createServer ( async ( req , res ) => {
2026-11-14 09:04:13 +00:00
const started = Date . now ();
2026-11-14 20:01:15 +00:00
let user = null ;
2026-11-14 03:15:53 +00:00
try {
const url = new URL ( req . url , 'http://localhost' );
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
2026-11-15 14:35:00 +00:00
// the request log: one line per API call -- reconstruct any session
2026-11-14 20:01:15 +00:00
// from the console output after the fact; the acting user rides
// every line (attribution, #22)
2026-11-14 09:04:13 +00:00
res . on ( 'finish' , () => {
if ( url . pathname . startsWith ( '/api' )) {
2026-11-14 20:01:15 +00:00
console . log ( ` ${ new Date (). toISOString (). slice ( 11 , 19 ) } ${ req . method } ${ url . pathname } ${ res . statusCode } ${ Date . now () - started } ms ${ user ? ` u: ${ user . id } ` : '' } ` );
2026-11-14 09:04:13 +00:00
}
});
2026-11-14 03:15:53 +00:00
if ( ! url . pathname . startsWith ( '/api' )) {
if ( req . method !== 'GET' ) throw new HttpError ( 405 , 'static files are GET-only' );
serveStatic ( url . pathname , res );
return ;
}
const m = match ( req . method , url . pathname );
if ( ! m ) throw new HttpError ( 404 , `no such route: ${ req . method } ${ url . pathname } ` );
const body = ( req . method === 'POST' || req . method === 'PUT' ) ? await readBody ( req ) : {};
2026-11-14 20:01:15 +00:00
user = authenticate ( req );
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
2026-11-15 14:35:00 +00:00
if ( ! m . publicRoute && ! user ) throw new HttpError ( 401 , 'not signed in -- claim an invite first (POST /api/claim)' );
2026-11-14 20:01:15 +00:00
send ( res , 200 , await m . handler ({ params : m . params , body , req , user }));
2026-11-14 03:15:53 +00:00
} catch ( e ) {
const status = e . status ?? 500 ;
if ( status >= 500 ) console . error ( `server: ${ e . stack ?? e . message } ` );
send ( res , status , { error : e . message , ...( e . detail ? { detail : e . detail } : {}) });
}
});
const [ host , port ] = String ( cfg . bind ?? '127.0.0.1:7350' ). split ( ':' );
server . listen ( Number ( port ), host , () => {
2026-11-15 14:46:00 +00:00
console . log ( `Tiny Worlds server: http:// ${ host } : ${ port } | ${ MOCK ? 'MOCK model' : cfg . models ? . player } | ${ ctx . sessions . size } session(s) rebuilt` );
2026-11-14 03:15:53 +00:00
});