multiuser: token identity, invites + bootstrap, owner-gated runs, fork, user packages; spectator spa; utc house rule

This commit is contained in:
2026-11-14 20:01:15 +00:00
parent 9f85adc3c6
commit 711634cc38
15 changed files with 1134 additions and 105 deletions
+1
View File
@@ -1,2 +1,3 @@
runs/
state/
server.json
+24 -1
View File
@@ -70,6 +70,19 @@ memory the agent owes itself across sessions.
## State pointers
- **The multiuser server is built and mock-proven (2026-11-14).**
Design: ROADMAP "The multiuser server" + QUESTIONS #22-31 (all
resolved). Identity = bearer token, no usernames/passwords/IDPs;
invites single-use with a permanent spent record; bootstrap invite
auto-mints on fresh deployment to state/bootstrap-invite.txt; op
mints/revokes invites and users; revocation destroys identity (new
invite = new person). Ownership is RESOLVED, never maintained —
run.json keeps dead owner ids, the API reads them as ownerless (GM
overruled my file-sweep; resolution won). Fork = atomic copy, owner
replaced, `forked: unixtime` stamped, no lineage. Packages split
system (repo) / user (state/packages, published). Spectators read
everything incl. gm.md (the boundary is the model boundary), mutate
nothing. Dates/times always UTC — house rule.
- Substrate design round complete (2026-11-13); rulings live in ROADMAP
("The harness") and HANDOFF. Bridge retired before ever going live;
REST + SPA is the MVP; runs are per-deployment instances copied from
@@ -106,7 +119,17 @@ memory the agent owes itself across sessions.
whatever you build from it); wait's text matches RENDERED text, so
CSS text-transform breaks literal waits (wait for "HER PAPER", not
"her paper"); clickable divs are invisible to the a11y tree and the
keyboard — clickable things are buttons.
keyboard — clickable things are buttons. Added 2026-11-14 (multiuser
round): the a11y snapshot races async renders — waiting for static
skeleton text ("RUNS") snapshots BEFORE the fetches land and looks
like a rendering bug; wait for text that only exists post-render (a
card name, the window-info line) or probe the DOM via evaluate.
- Test-state discipline (2026-11-14): the deployment's state/ is real
— never leave test users or invites in it. Smoke against --mock,
then Remove-Item state/ and every test run (all but the GM's real
ones) before calling it done. A stale bootstrap file is harmless
(dead once a superuser exists), but test users make the deployment
NOT fresh and block the real bootstrap.
- Gotcha (2026-11-14, rewind aftermath): a session rewind erases my
memory of tool calls but NOT their effects — the server, files, and
databases keep them. After any rewind, external state is the truth:
+37
View File
@@ -148,6 +148,43 @@ file is the "where did we leave off" map.
turns — completions grew 103 to 668 chars across window one) are
live now.
## The multiuser build (2026-11-14) — DONE
Design round closed (ROADMAP "The multiuser server", QUESTIONS
#22-31); all four phases built and proven the same day:
1. **Storage + identity + auth spine** — `state/deployment.db`
(users, invites; gitignored `state/`), `server/users.mjs`,
bearer-token auth on every route except session/claim, bootstrap
invite on the fresh-deployment condition, owner stamping at create,
acting-user attribution in the request and LLM call logs.
2. **Ownership + fork + packages** — owner gating on every mutation
and every model call; per-run activity locks (turn, ask, turn0,
housekeeping job, fork); `POST /api/runs/:id/fork` (staged copy,
atomic swap, owner replaced, `forked` stamped, window state
mirrored); clerk learns the second packages root (`state/packages`)
and `save-package`; user packages published to all. Ownership is
resolved, never maintained (GM ruling): run.json keeps dead owner
ids, the API reads them as absent; revocation is a db delete plus
closing the revoked user's open windows.
3. **SPA** — claim view, identity in the header, superuser admin on
home, spectator mode (read everything, mutate nothing, fork CTA),
save-as-package on setup, origin in the package picker, garnish
(owner, started/forked at second precision) on run names.
4. **Smoke + docs** — 34-step mock smoke plus a restart check, all
green; UI verified text-safely in the browser (claim, home, admin,
spectator on Irene, owner mode, fork click-through, picker,
setup; zero console errors). README deployment section +
layout updated; test state cleaned (Irene untouched).
Post-verdict cut (GM, same day): sign-out removed — signing in is
permanent and per-browser; the user lifecycle / auth story is a
ROADMAP extension point for a later revisit.
Gotcha learned while testing: the a11y snapshot races async renders —
wait for text that only exists POST-render (a card name, the
window-info line), never the static skeleton; and CSS text-transform
still uppercases wait targets.
## Working agreements with the GM
- **"I draft, you cut"** for all creative content.
+108
View File
@@ -67,6 +67,114 @@ as housekeeper evidence (observable #12). Status leaves the opening
bundle: system, backdrop, character, ring-b, ring-a (+ prelude on a
new game).
## The multiuser server
Design round opened 2026-11-14. The pitch, on the record: invite-only
onboarding (no usernames, no external IDPs); the value proposition is the
substrate ruling ("invited instance, key on the backend, no secrets in the
repo"); multiple users on one run is an extension point, out of scope.
Users can save an edited draft as a new package; packages split system
(repo, read-only) vs user (saved, gitignored storage). Runs attribute to
the starting user, GM actions are owner-only, and every run is readable
by any user and forkable (copied) to continue as a new GM. Read-only
is strict: spectators read everything in the run, notepad included, and
mutate nothing (GM-clarified 2026-11-14).
### 22. LLM call attribution — RESOLVED (2026-11-14)
Every logged LLM call records the acting user. Quotas and limits are an
extension point, not v1.
### 23. Identity mechanism — RESOLVED (2026-11-14)
No usernames, no passwords: a single-use invite code is exchanged at claim
time for a persistent token (random hex; the server stores a hash, the
client keeps the token). A display name is picked at claim — freeform
label, collisions allowed. Recovery for a lost token is a new invite;
recovery for the superuser is filesystem access. Client posture (GM,
same day): signing in is permanent and per-browser — no sign-out
exists, deliberately; the lifecycle story is a ROADMAP extension
point.
### 24. Saved-state location — RESOLVED (2026-11-14)
In-repo, gitignored — the same pattern as runs/. The requirement is only
that saved state never dirties git status; exact paths are free.
### 25. Bootstrap of the superuser — RESOLVED (2026-11-14)
Variant (b): on the fresh-deployment condition (empty users table), the
server generates the initial superuser invite itself, writes it to a file
in the gitignored storage dir, and echoes it to the console. One
bootstrap invite exists until claimed: generated on first fresh start,
reused across restarts so a restart never invalidates what the op saw.
The moment a superuser exists, bootstrap invites are never generated
again. Recovery for the superuser is filesystem access. Invite tokens
are single-use with an explicit record: spent tokens stay recorded and
claiming with a spent token is rejected, never silently dropped.
### 26. Superuser powers — RESOLVED (2026-11-14)
The minimum, ruled as proposed: mint invites (single-use code, seen once);
revoke an unclaimed invite; list users; revoke a user (token dies on the
spot, sessions end; runs and packages stay — ownerless but readable and
adoptable). Revocation destroys the identity: no suspend, no restore —
identity is just the token, so a revoked user who returns via a new
invite is a new identity. Ruled cheap because forking covers the loss:
any previous run can be forked and continued, so only attribution
metadata is lost, never data. Not in scope: touching another user's runs
or packages, reading another user's notepad, any user management beyond
revocation.
### 27. gm.md on save-as-package — RESOLVED (2026-11-14)
gm.md is part of the package and travels with every save; user packages
publish it to all users. A package has no players yet — nothing to hide.
### 28. gm.md in the read-only run view — RESOLVED (2026-11-14)
The agent's owner-only lean was overruled by a cleaner principle: gm.md
is secret from players only — the player-model, whose play the notes
would change. Humans are never the player (multi-user same-run is out
of scope; a fork's owner becomes the GM and inherits the notepad anyway).
So the notepad is owner-writable, readable by any user including
spectators, and never model-facing. The boundary is the model boundary,
not the human boundary.
### 29. Fork (formerly "adopt") — RESOLVED (2026-11-14, renamed same day)
The action is named fork, not adopt: it is about copying a run, not
re-homing one, and any user can fork any run, including their own. The
mechanics: a mechanical atomic copy of the run with the owner replaced —
rings, paper, db, session log, bundle — everything — into a new run id
under the forker. No inconsistent state on disk at any point: the copy
lands staged and is swapped in atomically (directory rename on the same
volume), taken under the run's existing activity lock so a mid-turn
fork can't torn-copy. Mid-window forking allowed; the copy inherits
window state honestly, unhousekept-session guard included. No lineage:
runs are entirely independent, so the fork records no source — it
stamps `forked: unixtime` in run.json (`created` carries over
unchanged), and that stamp is the only mark a fork bears.
Fresh-run-from-package needs no new verb — that is just create-run.
### 30. Migration of pre-user runs — RESOLVED (2026-11-14, revised same day)
No migration code. The GM prefers no legacy luggage: nothing stamps
owners automatically, and pre-user runs are left as they are until the
op fixes them by hand — editing run.json to add the owner id is trivial
for the person with filesystem access. This costs nothing because
ownerless is a legitimate runtime state anyway (revoked users' runs):
readable, forkable, no owner actions, no re-claiming mechanism. One
uniform rule, zero special cases.
### 31. Run display identity — RESOLVED (2026-11-14)
Fork broke the (package, pc) uniqueness that made "Package / PC" a safe
identifier — a fork copies both, and the pc name cannot change without
a retcon. Ruled apart: the run id is the identifier (strictly unique,
internal, factless, unchanged — it already exists and needs no
decoration); the visible name is a content descriptor for quick
selection, which must carry facts about the contents and be unique
ENOUGH — collisions unlikely and harmless, never load-bearing. The
visible name stays "Package / PC" (the content facts, and the only
name form the model ever sees, via @Package); the SPA garnish adds
owner and started-or-forked, rendered from run.json — chrome only,
never written to settings, never model-facing. `created` stays
recorded as it is and carries over unchanged on fork; a fork adds
`forked: unixtime` beside it — second precision, formatted as such in
the garnish. House rule: all dates and times are UTC everywhere, no
time zones, ever.
## Small / non-blocking
### 9. Unresolved-token check in expandVars — OPEN
+69 -14
View File
@@ -55,6 +55,47 @@ gendered and the shared prompts say "she" throughout; the postulate is
cheaper than a gender system no customer has asked for yet. When a male
or otherwise PC ever needs support, this is the line to revisit.
## The deployment (multiuser)
A deployment is one clone plus `server.json`, `state/`, and `runs/` —
all gitignored state. The LLM key lives on the backend; invited users
need neither the key nor a local clone. Identity is a token, nothing
else: no usernames, no passwords, no external IDPs. A single-use
invite code — spent codes are recorded forever and rejected loudly on
reuse — is exchanged at claim time for a persistent token; display
names are freeform labels, collisions allowed. On a fresh deployment
(empty users table) the server mints the superuser's bootstrap invite
to `state/bootstrap-invite.txt` and the console; it is dead the moment
any superuser exists, and recovery for the superuser is filesystem
access. The superuser mints and revokes invites, lists and revokes
users — that is the whole of admin. Revocation destroys the identity:
no suspend, no restore; a returning user is a new identity, and
forking makes that cheap — stories outlive identities by design.
- Every API route except `GET /api/session` and `POST /api/claim`
requires a signed-in user (`Authorization: Bearer <token>`).
- **Runs belong to their starter.** Every mutation and every model
call is owner-only; every run is readable by any user — transcript,
paper, rings, config, notepad included. The boundary is the model
boundary: gm.md is secret from the player-model, never from people.
Ownerless runs — pre-user, or the owner was revoked — are one
uniform state: readable, forkable, no owner actions, never
re-claimed. Ownership is resolved, never maintained: run.json keeps
the record, a dead owner id reads as absent.
- **Fork is the way in:** any user can fork any run, including their
own. A mechanical atomic copy — staged, swapped in by a same-volume
rename, under the run's activity lock — with the owner replaced. No
lineage is recorded (runs are entirely independent); the fork's only
mark is `forked: unixtime` in run.json, beside the carried-over
`created`.
- **Packages are system or user.** System packages ship with the repo;
a user can save their run's craft as a user package under
`state/packages/` — published to everyone, gm.md included (saving is
the act of publishing), the pc never riding.
- Every logged LLM call records the acting user. Quotas and limits are
an extension point, not built.
- All dates and times are UTC everywhere. No time zones, ever.
## Runs
Two interleaved stories calibrate the memory system against itself:
@@ -176,8 +217,8 @@ window, and sends turn-0 as the first GM turn in one action.
the session transcript — pasted, or the latest
`runs/<id>/sessions/*.jsonl` when playing through the server (the
phase-3 housekeeping job automates this). Save
its manifest to `packages/<story>/manifests/<window>.json`.
6. **Apply:** `node tool/memory.mjs apply packages/<story>/manifests/<window>.json`
its manifest to `runs/<id>/manifests/<window>.json`.
6. **Apply:** `node tool/memory.mjs --run <id> apply runs/<id>/manifests/<window>.json`
— the tool validates, applies, handles overflow, writes the run's
`log/<window>.md`, re-renders the views. A rejected manifest changes
nothing and says why.
@@ -186,7 +227,7 @@ window, and sends turn-0 as the first GM turn in one action.
## The memory model
State lives in **SQLite** (`packages/<story>/db/memory.db`); `canon/ring-*.md`
State lives in **SQLite** (`runs/<id>/db/memory.db`); `canon/ring-*.md`
are generated views. Markdown survives as rendering, dies as storage — the
models see prose, the machine sees rows.
@@ -421,9 +462,17 @@ tool/
packages/runs/status)
server/ the substrate: a zero-dependency node:http service
main.mjs entry + REST spine (node server/main.mjs [--mock]);
loopback, single-human, synchronous JSON; boot-rebuilds
open windows from the session logs on start
bearer-token auth on every route (session/claim are
public), ownership gating, per-run activity locks
(turn, ask, turn0, the housekeeping job, fork);
boot-rebuilds open windows from the session logs on
start; bootstraps the fresh-deployment superuser
invite; the request log and every LLM call carry the
acting user
provider.mjs the endpoint client (chat completions, models listing)
users.mjs the deployment's people: users, invites, tokens
(state/deployment.db; hashes only, spent invites
recorded forever)
bundle.mjs run context: prompt assembly (the trio system message,
the GM-message bundle, @ sigils + $ vars), the tool manifest
and its clerk dispatch
@@ -432,31 +481,37 @@ server/ the substrate: a zero-dependency node:http service
renderer (elision, thinking-strip, pairing check)
loop.mjs the turn loop: ask_gm pause/resume, paper ride and
delta apply, conflict carry; the scripted mock model
fork.mjs fork: the staged atomic copy with the owner replaced
and the `forked` stamp
clerk.mjs the clerk boundary (every state op via memory.mjs)
housekeeping.mjs the window-close ritual as an async job: transcript
with labeled thinking, run-state injection, the
housekeeper call, manifest save, apply, autorestart;
rejections hold and surface why
web/ the SPA — no build, vanilla ES modules, path-routed
index.html the shell: home (runs), new (packages), setup (editor),
play (transcript, status pane, context meter, GM input,
ask modal) — the server serves it for any extensionless
path
app.mjs the client: routing, the setup editor, register parsing
(speech / narration / OOC), bundle cards, turns,
housekeeping polling
index.html the shell: claim (invite), home (runs + admin), new
(packages), setup (editor), play (transcript, status
pane, context meter, GM input, ask modal, fork) —
the server serves it for any extensionless path
app.mjs the client: routing, the token session, the setup
editor, register parsing (speech / narration / OOC),
bundle cards, turns, housekeeping polling, spectator
mode
style.css dark, quiet, fiction-first
server.example.json copy to server.json (gitignored) — bind, endpoint +
key env, models, contextWindow, params passthrough
db/
schema.sql entries, records, paper, events journal (shared)
state/ per-deployment people + shared packages (gitignored):
deployment.db (users, invites), bootstrap-invite.txt,
packages/ (user-saved, published to everyone)
runs/ per-deployment run state (gitignored) — one anonymous
id per run (carries no facts): the copied package,
the craft prompt (handbook.md),
run.json (lineage,
run.json (lineage, owner, `forked` stamp on a fork,
model override), db/, canon/ (rendered views), dumps/,
log/, manifests/, sessions/
packages/ presets — authored content only, never state
packages/ system presets — authored content only, never state
la-caramba/ backdrop.md, turn-0.md (new-game opener), character.md,
seed.json, settings.json, gm.md (the GM's notepad —
seeded per run, always editable in the SPA, never in
+67
View File
@@ -174,6 +174,73 @@ example, gitignored real file, env-var option).
clerk-side; the web side at loopback single-user scale is the easy
part.
## The multiuser server (2026-11-14, GM)
The invited-instance half of the harness goal, designed in one round
(rulings QUESTIONS #22-31). The LLM key stays on the backend; invited
users need neither the host's secrets nor their own key, and can play
without running anything locally.
- **Identity is a token, nothing else.** No usernames, no passwords, no
external IDPs. A single-use invite code is exchanged at claim time
for a persistent token (random hex; the server stores a hash, the
client keeps the token). Display names are freeform labels picked at
claim, collisions allowed. Recovery for a lost token is a new invite;
recovery for the superuser is filesystem access. Revocation destroys
the identity — no suspend, no restore — and that is cheap because
stories outlive identities by design (forking).
- **Bootstrap:** on the fresh-deployment condition (empty users table)
the server generates the initial superuser invite itself, writes it
to `state/bootstrap-invite.txt` and echoes it to the console. Exactly
one bootstrap invite exists until claimed, reused across restarts so
a restart never invalidates what the op saw; dead the moment any
superuser exists. Invite tokens are single-use with an explicit
spent record — reuse is rejected loudly, never silently dropped.
- **Superuser powers:** mint/revoke invites, list/revoke users.
Nothing else — no touching another user's runs or packages, no user
management beyond revocation.
- **The boundary is the model boundary.** gm.md is secret from the
player-model only; humans read freely. Saving a draft as a package
publishes its gm.md to everyone (saving is the act of publishing).
Spectators read everything in a run, notepad included, and mutate
nothing. `housekeeper.md` stays never-exposed (it prompts an
internal agent).
- **Runs:** attributed to the starting user; every GM action is
owner-only (including anything that spends a model call); every run
is readable by any user. Any user can fork any run, including their
own: a mechanical atomic copy — staged, swapped in by same-volume
rename, taken under the run's activity lock so a mid-turn fork can't
torn-copy — with the owner replaced. No lineage: runs are entirely
independent, and a fork's only mark is `forked: unixtime` beside the
carried-over `created`. Ownerless (pre-user or revoked-owner) is one
uniform runtime state: readable, forkable, no owner actions, no
re-claiming mechanism. No migration code — pre-user runs stay as
they are until the op hand-stamps an owner id into run.json.
- **Packages split system and user.** System packages ship with the
repo (authored, read-only); a user can save their run's craft as a
new user package under `state/packages/`, published to everyone,
gm.md included. The saved package carries no pc — the next create
asks for one; the display name is the save's one decision.
- **Display identity:** the run id is the identifier (strictly unique,
internal, factless, undecorated). The visible name is a content
descriptor — "Package / PC" plus SPA garnish (owner, started or
forked) — unique ENOUGH: collisions unlikely and harmless, never
load-bearing, never model-facing.
- **Every logged LLM call records the acting user.** Quotas and limits
are an extension point, not v1. Saved state lives gitignored
(`runs/`, `state/`) — the repo stays clean by construction.
- **House rule: all dates and times are UTC everywhere.** No time
zones, ever.
- **Extension point (later): proper user lifecycle and auth story.**
Signing in is permanent and per-browser — the token lives in the
client's localStorage, and sign-out is deliberately absent: less
functional, much easier to reason about. A user who loses their
browser storage is re-invited as a new identity (their old runs
stay owned by the old, unreachable one — readable, forkable,
frozen). Revisit when a real need shows: sign-out/token
expiry/refresh, multiple devices per user, token backup
affordances.
## SPA v1 — substrate decisions (2026-11-12, GM)
- **The whole story is recorded; publishing is a someday option.**
+43
View File
@@ -0,0 +1,43 @@
// server/fork.mjs — fork: a run copied whole, the owner replaced.
//
// Runs are entirely independent: no lineage is recorded, and the only
// mark a fork bears is `forked: unixtime` in run.json (its `created`
// carries over unchanged — the story's start date is a fact of the
// contents). No inconsistent state on disk at any point: the copy
// lands staged under a dot-name and is swapped in by a same-volume
// rename, which is atomic — no reader ever sees a half-run. The
// caller holds the source run's activity lock, so the copy is never
// taken mid-turn; a copied open window reopens honestly in the fork
// (the log is the truth, same as boot-rebuild).
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { requireRun } from './bundle.mjs';
import { latestSession, lastHousekept, loadSession } from './session.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
export function forkRun(ctx, srcId, user) {
requireRun(srcId);
let id;
for (;;) {
id = randomBytes(4).toString('hex'); // anonymous, same alphabet as create
if (!fs.existsSync(path.join(RUNS_DIR, id)) && !fs.existsSync(path.join(RUNS_DIR, `.staging-${id}`))) break;
}
const staging = path.join(RUNS_DIR, `.staging-${id}`);
fs.cpSync(path.join(RUNS_DIR, srcId), staging, { recursive: true }); // sync: atomic wrt the event loop
const metaPath = path.join(staging, 'run.json');
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
meta.owner = user.id;
meta.forked = Math.floor(Date.now() / 1000); // unixtime, UTC by definition
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
fs.renameSync(staging, path.join(RUNS_DIR, id)); // same-volume rename: the atomic swap-in
// an open, unhousekept window in the source is an open window in the
// fork — its transcript reaches the fork's rings only after the fork
// housekeeps it, same rule as the original
const latest = latestSession(id);
if (latest && latest !== lastHousekept(id)) ctx.sessions.set(id, loadSession(id, latest));
return { run: id };
}
+9 -5
View File
@@ -96,7 +96,7 @@ export function parseManifest(text) {
// --- the job -----------------------------------------------------------------
export function trigger(ctx, runId) {
export function trigger(ctx, runId, user) {
requireRun(runId);
const s = ctx.sessions.get(runId);
if (!s) throw new HttpError(409, `no open window for '${runId}' — housekeeping is the window-close ritual`);
@@ -104,16 +104,18 @@ export function trigger(ctx, runId) {
ctx.sessions.delete(runId); // the window is closed from here on
const job = { state: 'running', session: s.stamp, started: new Date().toISOString() };
ctx.jobs.set(runId, job);
runJob(ctx, runId, s.stamp, s.lines); // async; catches its own errors
// the whole async chain holds the run's activity lock — a fork
// enqueued behind it copies the post-wrap state, never a half-apply
ctx.enqueue(runId, () => runJob(ctx, runId, s.stamp, s.lines, user));
return job;
}
async function runJob(ctx, runId, stamp, lines) {
async function runJob(ctx, runId, stamp, lines, user) {
const job = ctx.jobs.get(runId);
try {
const text = ctx.mock
? mockManifest(stamp)
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp));
: await callHousekeeper(ctx, runId, buildMessages(runId, lines, stamp), user);
const dir = path.join(runDir(runId), 'manifests');
fs.mkdirSync(dir, { recursive: true });
let mf;
@@ -136,9 +138,11 @@ async function runJob(ctx, runId, stamp, lines) {
}
}
async function callHousekeeper(ctx, runId, messages) {
async function callHousekeeper(ctx, runId, messages, user) {
const model = ctx.cfg.models?.housekeeper ?? ctx.cfg.models?.player ?? null;
if (!model) throw new Error('no housekeeper model configured (server.json models.housekeeper)');
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, messages, undefined, ctx.cfg.params ?? {});
return data.choices[0].message.content ?? '';
}
+10 -8
View File
@@ -27,7 +27,7 @@ function needSession(ctx, runId) {
return s;
}
export async function gmTurn(ctx, runId, line) {
export async function gmTurn(ctx, runId, line, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
const paper = clerkJson(runId, 'paper'); // fresh per turn
@@ -37,7 +37,7 @@ export async function gmTurn(ctx, runId, line) {
s.conflict = null;
}
s.append({ t: 'msg', m: { role: 'user', content } });
return runLoop(ctx, runId);
return runLoop(ctx, runId, user);
}
// the opening beat: turn-0 sent as the first GM turn, separate from
@@ -45,7 +45,7 @@ export async function gmTurn(ctx, runId, line) {
// block was ingested as her opening paper at window-open — stripped
// here, since the normal ride carries the current paper on every GM
// turn, the beat included.
export async function turn0(ctx, runId) {
export async function turn0(ctx, runId, user) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending — answer it first (POST /ask)');
if (!s.fresh) throw new HttpError(409, 'turn-0 opens a fresh run only');
@@ -57,10 +57,10 @@ export async function turn0(ctx, runId) {
let text = expandVars(runId, fs.readFileSync(file, 'utf8')); // $NAME tokens resolve like every bundle file
const sm = text.match(/<status>[\s\S]*?<\/status>/);
if (sm) text = text.replace(sm[0], '');
return gmTurn(ctx, runId, text.trim());
return gmTurn(ctx, runId, text.trim(), user);
}
export async function answerAsk(ctx, runId, answer) {
export async function answerAsk(ctx, runId, answer, user) {
const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
// execute the paused batch: the ask gets the answer, its siblings
@@ -73,13 +73,12 @@ export async function answerAsk(ctx, runId, answer) {
}
}
s.pendingAsk = null;
return runLoop(ctx, runId);
return runLoop(ctx, runId, user);
}
async function runLoop(ctx, runId) {
async function runLoop(ctx, runId, user) {
const s = ctx.sessions.get(runId);
const tools = toolList(runId);
const model = s.pendingAsk ? null : resolveModel(ctx, runId);
const out = { tools: [] };
for (;;) {
const view = renderView(s);
@@ -87,6 +86,9 @@ async function runLoop(ctx, runId) {
if (ctx.mock) {
msg = mockModel(s, view);
} else {
const model = resolveModel(ctx, runId);
// attribution (#22): every LLM call names the acting user
console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`);
const data = await ctx.provider.chat(model, view, tools, ctx.cfg.params ?? {});
msg = data.choices[0].message;
s.usage = data.usage
+213 -31
View File
@@ -1,9 +1,11 @@
// server/main.mjs — entry + REST spine.
//
// Loopback, single-human, synchronous JSON. The SPA and curl are both
// just clients. Boot-rebuild: every run whose latest session was not
// housekept gets its open window back from the jsonl — the log is the
// truth, the context is a view.
// 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
// window back from the jsonl — the log is the truth, the context is a
// view.
//
// usage: node server/main.mjs [--mock]
import fs from 'node:fs';
@@ -11,11 +13,13 @@ import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { makeProvider } from './provider.mjs';
import { clerkRaw, clerkRawJson, clerkJson } from './clerk.mjs';
import { clerkRaw, clerkRawJson, clerkJson, clerk } from './clerk.mjs';
import * as bundle from './bundle.mjs';
import * as session from './session.mjs';
import * as housekeeping from './housekeeping.mjs';
import { gmTurn, answerAsk, turn0, HttpError } from './loop.mjs';
import * as users from './users.mjs';
import { forkRun } from './fork.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock');
@@ -29,11 +33,36 @@ const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
const provider = makeProvider(cfg.endpoint ?? {});
const ctx = { mock: MOCK, cfg, provider, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
// --- the per-run activity lock ---------------------------------------------------
//
// Serializes every async mutation span (turn, ask, turn0, the
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
// two concurrent turns can never interleave across their awaits.
// Sync-only handlers (paper-set, file writes) need no lock: they
// 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) {
console.log(`fresh deployment — the superuser invite (also at ${path.relative(ROOT, users.bootstrapFile)}):`);
console.log(` ${boot.code}`);
} else if (boot?.reused) {
console.log(`fresh deployment — the superuser invite waits at ${path.relative(ROOT, users.bootstrapFile)}`);
}
// --- boot-rebuild ------------------------------------------------------------
if (fs.existsSync(path.join(ROOT, 'runs'))) {
for (const d of fs.readdirSync(path.join(ROOT, 'runs'), { withFileTypes: true })) {
if (!d.isDirectory()) continue;
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
if (!fs.existsSync(path.join(ROOT, 'runs', d.name, 'run.json'))) continue;
const latest = session.latestSession(d.name);
if (latest && latest !== session.lastHousekept(d.name)) {
@@ -67,7 +96,8 @@ const readBody = (req) => new Promise((resolve, reject) => {
});
const routes = [];
const route = (method, pattern, handler) => routes.push({ method, segs: pattern.split('/').filter(Boolean), handler });
const route = (method, pattern, handler, opts = {}) =>
routes.push({ method, segs: pattern.split('/').filter(Boolean), handler, publicRoute: opts.public === true });
const match = (method, pathname) => {
const segs = pathname.split('/').filter(Boolean);
@@ -78,7 +108,7 @@ const match = (method, pathname) => {
if (r.segs[i].startsWith(':')) params[r.segs[i].slice(1)] = decodeURIComponent(segs[i]);
else if (r.segs[i] !== segs[i]) continue outer;
}
return { handler: r.handler, params };
return { handler: r.handler, params, publicRoute: r.publicRoute };
}
return null;
};
@@ -115,6 +145,92 @@ function serveStatic(pathname, res) {
res.end(data);
}
// --- 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
// claiming an invite. Everything else — reads included — requires a
// signed-in user: the runs and packages of this deployment are shared
// among invitees, not with the world.
route('GET', '/api/session', async ({ user }) => ({
user, // null when signed out or the token is stale
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 });
// superuser: mint an invite — the code is returned once, never stored
route('POST', '/api/invites', async ({ user }) => {
requireSuperuser(user);
return users.mintInvite(user.id);
});
// superuser: the invite ledger, hashes only — codes are never listed
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
// runs and packages stay on disk untouched — the record of ownership
// keeps its dead id, which resolves to ownerless everywhere it is
// read. Only the live map is reconciled: their open windows close.
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);
// ownership: every GM action — every mutation, every model call — is
// 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) {
throw new HttpError(403, `run '${runId}' is ownerless — fork it to make it yours`);
}
if (meta.owner !== user.id) {
throw new HttpError(403, `run '${runId}' is ${users.userName(meta.owner) ?? 'another user'}'s — fork it to continue as yours`);
}
return meta;
}
// --- routes -------------------------------------------------------------------
route('GET', '/api', async () => ({
@@ -125,7 +241,30 @@ route('GET', '/api', async () => ({
route('GET', '/api/models', async () => (MOCK ? ['mock'] : await provider.models()));
route('GET', '/api/packages', async () => clerkRawJson('packages'));
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
// (gm.md included — saving is the act of publishing). The pc never
// 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) };
});
// the repo-fed prompts, read-only: per-project opening + guards and
// substrate invariants — never copied into a run, so the editor shows
@@ -148,6 +287,8 @@ route('GET', '/api/runs', async () => {
r.pendingAsk = s?.pendingAsk?.question ?? null;
r.lastSession = session.latestSession(r.id);
r.lastHousekept = session.lastHousekept(r.id);
r.owner = resolveOwner(r.owner);
r.ownerName = r.owner == null ? null : users.userName(r.owner);
}
return runs;
});
@@ -155,13 +296,13 @@ route('GET', '/api/runs', async () => {
// 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.
route('POST', '/api/runs', async ({ body }) => {
route('POST', '/api/runs', async ({ body, user }) => {
const pkg = String(body.package ?? '').trim();
const pc = String(body.pc ?? '').trim();
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');
const name = body.name === undefined ? undefined : String(body.name);
const r = clerkRaw('--json', 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
const r = clerkRaw('--json', '--owner', user.id, 'create', pkg, pc, ...(name !== undefined ? [name] : []), ...(body.model ? [String(body.model)] : []));
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'create failed');
const run = JSON.parse(r.out);
return { run, dir: `runs/${run.id}` };
@@ -182,8 +323,17 @@ route('GET', '/api/runs/:id', async ({ params }) => {
const st = clerkJson(id, '--json', 'status');
const s = ctx.sessions.get(id);
const meta = bundle.runMeta(id);
const owner = resolveOwner(meta?.owner);
return {
run: { id, package: meta?.package ?? null, created: meta?.created ?? null, model: meta?.model ?? null },
run: {
id,
package: meta?.package ?? null,
created: meta?.created ?? null,
forked: meta?.forked ?? null,
owner,
ownerName: owner == null ? null : users.userName(owner),
model: meta?.model ?? null,
},
display: bundle.runDisplay(id),
open: !!s,
draft: session.latestSession(id) === null,
@@ -235,8 +385,9 @@ route('GET', '/api/runs/:id/files', async ({ params }) => {
return { files };
});
route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
route('PUT', '/api/runs/:id/files/:path', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
const f = params.path;
const mode = RUN_FILES[f];
if (!mode) throw new HttpError(404, `no such run file in the API surface: ${f}`);
@@ -251,8 +402,9 @@ route('PUT', '/api/runs/:id/files/:path', async ({ params, body }) => {
// prompt vars: the inputs the prompts themselves declare ($TOKENS
// found in any prompt file). Values live in the run's settings vars.
route('POST', '/api/runs/:id/vars', async ({ params, body }) => {
route('POST', '/api/runs/:id/vars', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
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)) {
@@ -274,8 +426,9 @@ route('GET', '/api/runs/:id/notes', async ({ params }) => {
return { content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '' };
});
route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
route('PUT', '/api/runs/:id/notes', async ({ params, body, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id); // spectators read the pad, the owner writes it
if (typeof body.content !== 'string') throw new HttpError(400, 'content (a string) is required — empty clears the pad');
fs.writeFileSync(path.join(dir, 'gm.md'), body.content);
return { ok: true };
@@ -285,8 +438,9 @@ route('PUT', '/api/runs/:id/notes', async ({ params, body }) => {
// 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.
route('DELETE', '/api/runs/:id', async ({ params }) => {
route('DELETE', '/api/runs/:id', async ({ params, user }) => {
const dir = bundle.requireRun(params.id);
requireOwner(user, params.id);
if (session.latestSession(params.id) !== null) {
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)}`);
}
@@ -294,8 +448,9 @@ route('DELETE', '/api/runs/:id', async ({ params }) => {
return { ok: true, deleted: params.id };
});
route('POST', '/api/runs/:id/windows', async ({ params, body }) => {
route('POST', '/api/runs/:id/windows', async ({ params, body, user }) => {
const id = params.id;
requireOwner(user, id);
if (ctx.sessions.has(id)) throw new HttpError(409, `a window is already open for '${id}' — one active window per run`);
const s = session.openWindow(id, body.override === true);
ctx.sessions.set(id, s);
@@ -318,20 +473,33 @@ route('GET', '/api/runs/:id/session', async ({ params }) => {
};
});
route('POST', '/api/runs/:id/turn', async ({ params, body }) => {
route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
const line = String(body.line ?? '').trim();
if (!line) throw new HttpError(400, 'line is required');
return { ok: true, ...(await gmTurn(ctx, params.id, line)) };
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => gmTurn(ctx, params.id, line, user))) };
});
// the opening beat as its own action: sent as the first GM turn on a
// fresh window — "start" is this right after window-open
route('POST', '/api/runs/:id/turn0', async ({ params }) => ({ ok: true, ...(await turn0(ctx, params.id)) }));
route('POST', '/api/runs/:id/turn0', async ({ params, user }) => {
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => turn0(ctx, params.id, user))) };
});
route('POST', '/api/runs/:id/ask', async ({ params, body }) => {
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required');
return { ok: true, ...(await answerAsk(ctx, params.id, answer)) };
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, () => answerAsk(ctx, params.id, answer, user))) };
});
// fork: any user, any run — a mechanical atomic copy with the owner
// 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));
});
route('GET', '/api/runs/:id/status', async ({ params }) => {
@@ -344,9 +512,10 @@ route('GET', '/api/runs/:id/status', async ({ params }) => {
// clerk (which journals the prior state). Descriptions never contain
// commas — the transport is comma-separated — so a comma inside an
// item is a 400, not a silent corruption later.
route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
route('POST', '/api/runs/:id/paper', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const items = body.items;
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required — an empty array clears the paper');
for (const it of items) {
@@ -357,9 +526,10 @@ route('POST', '/api/runs/:id/paper', async ({ params, body }) => {
return { ok: true, paper };
});
route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
// ends the window and kicks the async chain; poll GET for the outcome
const job = housekeeping.trigger(ctx, params.id);
requireOwner(user, params.id);
const job = housekeeping.trigger(ctx, params.id, user);
return { state: job.state, session: job.session };
});
@@ -368,9 +538,10 @@ route('POST', '/api/runs/:id/housekeeping', async ({ params }) => {
// saved for review — but nothing applied, no window ended, no state
// touched. The way to iterate on housekeeper.md against real data
// without playing more; works on the open window too.
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body, user }) => {
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id); // a replay spends a model call on the shared key
const stamp = String(body?.session ?? '').trim() || session.latestSession(id);
if (!stamp) throw new HttpError(409, 'no session to replay — this run has none');
let lines;
@@ -384,7 +555,7 @@ route('POST', '/api/runs/:id/housekeeping/replay', async ({ params, body }) => {
fs.mkdirSync(dir, { recursive: true });
const text = ctx.mock
? housekeeping.mockManifest(stamp)
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp));
: await housekeeping.callHousekeeper(ctx, id, housekeeping.buildMessages(id, lines, stamp), user);
let mf;
try {
mf = housekeeping.parseManifest(text);
@@ -402,11 +573,12 @@ route('GET', '/api/runs/:id/housekeeping', async ({ params }) => housekeeping.jo
route('GET', '/api/runs/:id/housekeeping/log', async ({ params }) => housekeeping.latestLog(params.id));
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user }) => {
// the recovery path: apply a (hand-edited) manifest directly — closes
// any open window, marks the latest session housekept, autorestarts
const id = params.id;
bundle.requireRun(id);
requireOwner(user, id);
const file = String(body.file ?? '').trim();
if (!file) throw new HttpError(400, 'file is required — a manifest path relative to the run dir, e.g. manifests/<window>.json');
const manifestPath = path.resolve(path.join(ROOT, 'runs', id), file);
@@ -427,15 +599,23 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body }) => {
// --- dispatch -------------------------------------------------------------------
// 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;
}
const server = http.createServer(async (req, res) => {
const started = Date.now();
let user = null;
try {
const url = new URL(req.url, 'http://localhost');
// the request log: one line per API call — reconstruct any session
// from the console output after the fact
// from the console output after the fact; the acting user rides
// every line (attribution, #22)
res.on('finish', () => {
if (url.pathname.startsWith('/api')) {
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
console.log(`${new Date().toISOString().slice(11, 19)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms${user ? ` u:${user.id}` : ''}`);
}
});
if (!url.pathname.startsWith('/api')) {
@@ -446,7 +626,9 @@ const server = http.createServer(async (req, res) => {
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) : {};
send(res, 200, await m.handler({ params: m.params, body, req }));
user = authenticate(req);
if (!m.publicRoute && !user) throw new HttpError(401, 'not signed in — claim an invite first (POST /api/claim)');
send(res, 200, await m.handler({ params: m.params, body, req, user }));
} catch (e) {
const status = e.status ?? 500;
if (status >= 500) console.error(`server: ${e.stack ?? e.message}`);
+159
View File
@@ -0,0 +1,159 @@
// server/users.mjs — the deployment's people: users, invites, tokens.
//
// Identity is a token, nothing else: no usernames, no passwords, no
// external IDPs. A single-use invite code is exchanged at claim time
// for a persistent token; the server stores hashes only, the client
// keeps the token. Spent invites stay recorded forever — claiming
// with a spent code is rejected loudly, never silently dropped. The
// first claim on a fresh deployment creates the superuser; recovery
// for a lost superuser token is filesystem access (it is their
// deployment). Revocation deletes the row — the token dies with it,
// and the person returns (if invited again) as a new identity.
//
// All times are UTC (house rule). Never model-facing: nothing here
// ever enters a bundle or a prompt.
import { DatabaseSync } from 'node:sqlite';
import { createHash, randomBytes } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const STATE_DIR = path.join(ROOT, 'state');
const DB_PATH = path.join(STATE_DIR, 'deployment.db');
const BOOTSTRAP_FILE = path.join(STATE_DIR, 'bootstrap-invite.txt');
const SCHEMA = `
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
superuser INTEGER NOT NULL DEFAULT 0,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS invites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code_hash TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL CHECK (kind IN ('invite', 'bootstrap')),
created_by TEXT NOT NULL,
created_at TEXT NOT NULL,
claimed_by TEXT,
claimed_at TEXT
);
`;
fs.mkdirSync(STATE_DIR, { recursive: true });
const db = new DatabaseSync(DB_PATH);
db.exec(SCHEMA);
const now = () => new Date().toISOString();
const sha = (s) => createHash('sha256').update(String(s)).digest('hex');
const hex = (n) => randomBytes(n).toString('hex');
// --- users ---------------------------------------------------------------------
export function userCount() {
return db.prepare('SELECT COUNT(*) AS n FROM users').get().n;
}
// does this identity exist? A revoked user's id resolves to absent —
// dead ids are ownerless by resolution, never by rewriting history
export function exists(uid) {
if (uid == null) return false;
return !!db.prepare('SELECT 1 FROM users WHERE id = ?').get(uid);
}
export function getUserByToken(token) {
const t = String(token ?? '').trim();
if (!t) return null;
const row = db.prepare('SELECT * FROM users WHERE token_hash = ?').get(sha(t));
return row ?? null;
}
export function userName(uid) {
if (uid == null) return null;
const row = db.prepare('SELECT name FROM users WHERE id = ?').get(uid);
return row ? row.name : null;
}
export function listUsers() {
return db.prepare('SELECT id, name, superuser, created FROM users ORDER BY created').all()
.map((u) => ({ ...u, superuser: u.superuser === 1 }));
}
// revocation destroys the identity: no suspend, no restore. Their runs
// and packages stay — ownerless, readable, forkable.
export function revokeUser(id) {
return db.prepare('DELETE FROM users WHERE id = ?').run(id).changes > 0;
}
// --- invites ---------------------------------------------------------------------
export function mintInvite(byUid, kind = 'invite') {
const code = hex(12); // 24 hex chars — shown once, stored hashed
const res = db.prepare(
'INSERT INTO invites (code_hash, kind, created_by, created_at) VALUES (?, ?, ?, ?)'
).run(sha(code), kind, byUid, now());
return { id: Number(res.lastInsertRowid), code };
}
export function listInvites() {
return db.prepare(
'SELECT id, kind, created_by, created_at, claimed_by, claimed_at FROM invites ORDER BY id'
).all();
}
// only unclaimed invites can be revoked; spent ones are a permanent record
export function revokeInvite(id) {
return db.prepare('DELETE FROM invites WHERE id = ? AND claimed_by IS NULL').run(id).changes > 0;
}
// exchange a single-use invite code for a persistent token. Unknown,
// spent, and dead-bootstrap codes are each named explicitly.
export function claimInvite(code, name) {
const c = String(code ?? '').trim();
const n = String(name ?? '').trim();
const fail = (msg) => { const e = new Error(msg); e.status = 400; throw e; };
if (!c) fail('the invite code is required');
if (!n) fail('a display name is required');
const row = db.prepare('SELECT * FROM invites WHERE code_hash = ?').get(sha(c));
if (!row) fail('unknown invite code');
if (row.claimed_by != null) fail('this invite was already used — ask for a fresh one');
if (row.kind === 'bootstrap' && userCount() > 0) {
fail('the bootstrap invite expired when this deployment got its superuser — ask the operator for an invite');
}
const uid = hex(4);
const token = hex(16); // 32 hex chars — returned once, never again
const su = userCount() === 0 ? 1 : 0;
db.exec('BEGIN');
try {
db.prepare('INSERT INTO users (id, token_hash, name, superuser, created) VALUES (?, ?, ?, ?, ?)')
.run(uid, sha(token), n, su, now());
db.prepare('UPDATE invites SET claimed_by = ?, claimed_at = ? WHERE id = ?').run(uid, now(), row.id);
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
throw e;
}
return { token, user: { id: uid, name: n, superuser: su === 1 } };
}
// --- bootstrap -------------------------------------------------------------------
//
// On the fresh-deployment condition (no users yet) the server mints
// the superuser's invite itself and places it on disk for the op.
// Exactly one bootstrap invite exists until claimed: reused across
// restarts so a restart never invalidates what the op already saw;
// never generated again once any user exists; rejected at claim time
// if somehow presented after that.
export function bootstrap() {
if (userCount() > 0) return null;
const open = db.prepare("SELECT id FROM invites WHERE kind = 'bootstrap' AND claimed_by IS NULL").get();
if (open) return { reused: true };
const { code } = mintInvite('bootstrap', 'bootstrap');
fs.writeFileSync(BOOTSTRAP_FILE, `${code}\n`);
return { code };
}
export const bootstrapFile = BOOTSTRAP_FILE;
+115 -28
View File
@@ -16,6 +16,9 @@
// init the db, render the views.
// From then on the run dir is the only
// truth; the package is never read again.
// save-package "display name" save this run's craft as a new user
// package (state/packages/, published to
// all; pc never rides; --owner stamps)
// init create the run's database and stubs
// (the low-level primitive under create)
// seed [--force] [file] one-time pre-story migration; applies
@@ -57,6 +60,7 @@ import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SCHEMA_PATH = path.join(ROOT, 'db', 'schema.sql');
const PACKAGES_DIR = path.join(ROOT, 'packages');
const STATE_PACKAGES_DIR = path.join(ROOT, 'state', 'packages');
const RUNS_DIR = path.join(ROOT, 'runs');
// dials — retune freely
@@ -83,6 +87,12 @@ const QUIET = argv.includes('--quiet');
for (let i = argv.indexOf('--quiet'); i !== -1; i = argv.indexOf('--quiet')) argv.splice(i, 1);
const AS_JSON = argv.includes('--json');
for (let i = argv.indexOf('--json'); i !== -1; i = argv.indexOf('--json')) argv.splice(i, 1);
const ownerIdx = argv.indexOf('--owner');
let ownerOverride = null;
if (ownerIdx !== -1) {
ownerOverride = argv[ownerIdx + 1] ?? null;
argv.splice(ownerIdx, 2);
}
const [cmd, ...args] = argv;
// a run is an instance under runs/, created from a package by `create`;
@@ -555,11 +565,14 @@ function cmdInit() {
// --- packages and runs --------------------------------------------------------
//
// A package is a preset: authored content only, no state. A run is an
// instance: the package copied wholesale (the shared prompts included —
// battery included, editable per run), plus all state. Creation is the
// one time a package is ever read; afterwards the run dir is the only
// truth. run.json records the lineage and an optional model override.
// A package is a preset: authored content only, no state. Packages
// come from two roots: system (repo, authored, read-only) and user
// (state/packages, saved from a run, published to everyone). A run is
// an instance: the package copied wholesale (the shared prompts
// included — battery included, editable per run), plus all state.
// Creation is the one time a package is ever read; afterwards the run
// dir is the only truth. run.json records the lineage, the owner
// (multiuser), and an optional model override.
const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json', 'settings.json', 'gm.md'];
// battery included, copied per run and then the run's to edit: the craft
@@ -569,27 +582,57 @@ const PACKAGE_FILES = ['backdrop.md', 'turn-0.md', 'character.md', 'seed.json',
// substrate facts)
const SHARED_PROMPTS = ['handbook.md'];
function cmdPackages() {
if (!fs.existsSync(PACKAGES_DIR)) { if (AS_JSON) console.log('[]'); else console.log('(no packages)'); return; }
const list = [];
for (const d of fs.readdirSync(PACKAGES_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
const p = path.join(PACKAGES_DIR, d.name);
const has = (f) => fs.existsSync(path.join(p, f));
let settings = {};
try { settings = JSON.parse(fs.readFileSync(path.join(p, 'settings.json'), 'utf8')); } catch {}
list.push({
name: d.name,
display: settings.name ?? d.name,
pc: settings.pc ?? null,
records: settings.records === true,
turn0: has('turn-0.md'), seed: has('seed.json'),
complete: has('backdrop.md') && has('character.md'),
});
// resolve a package name against both roots; the repo wins a collision
function packageDir(name) {
if (!/^[a-z0-9-]+$/.test(name ?? '')) return null;
if (fs.existsSync(path.join(PACKAGES_DIR, name))) return path.join(PACKAGES_DIR, name);
if (fs.existsSync(path.join(STATE_PACKAGES_DIR, name))) return path.join(STATE_PACKAGES_DIR, name);
return null;
}
// the package meta of a user package (owner, created); system packages
// have none — their origin is the repo itself
function readPackageMeta(dir) {
try {
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
} catch {
return null;
}
}
function packageEntry(name, dir, origin) {
const has = (f) => fs.existsSync(path.join(dir, f));
let settings = {};
try { settings = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')); } catch {}
const meta = origin === 'user' ? readPackageMeta(dir) : null;
return {
name,
origin,
...(origin === 'user' ? { owner: meta?.owner ?? null } : {}),
display: settings.name ?? name,
pc: settings.pc ?? null,
records: settings.records === true,
turn0: has('turn-0.md'), seed: has('seed.json'),
complete: has('backdrop.md') && has('character.md'),
};
}
function cmdPackages() {
const list = [];
const scan = (root, origin) => {
if (!fs.existsSync(root)) return;
for (const d of fs.readdirSync(root, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
list.push(packageEntry(d.name, path.join(root, d.name), origin));
}
};
scan(PACKAGES_DIR, 'system');
scan(STATE_PACKAGES_DIR, 'user');
list.sort((a, b) => a.name.localeCompare(b.name));
if (AS_JSON) { console.log(JSON.stringify(list)); return; }
if (!list.length) { console.log('(no packages)'); return; }
for (const x of list) {
console.log(`${x.name}: ${x.display} — records ${x.records ? 'on' : 'off'} · turn-0 ${x.turn0 ? 'yes' : 'no'} · seed ${x.seed ? 'yes' : 'no'} · backdrop+card ${x.complete ? 'ok' : 'MISSING'}`);
console.log(`${x.name}: ${x.display} [${x.origin}] — records ${x.records ? 'on' : 'off'} · turn-0 ${x.turn0 ? 'yes' : 'no'} · seed ${x.seed ? 'yes' : 'no'} · backdrop+card ${x.complete ? 'ok' : 'MISSING'}`);
}
}
@@ -614,13 +657,13 @@ function cmdCreate(pkgName, pc, displayName, model) {
if (!pkgName || !/^[a-z0-9-]+$/.test(pkgName) || !pc || !String(pc).trim()) {
fail('usage: create <package> <pc-name> ["package display name"] ["model"]');
}
const pkgDir = path.join(PACKAGES_DIR, pkgName);
if (!fs.existsSync(pkgDir)) fail(`no such package: ${pkgName} — see: packages`);
const pkgDir = packageDir(pkgName);
if (!pkgDir) fail(`no such package: ${pkgName} — see: packages`);
pc = String(pc).trim();
// different runs of the same package require different pc names
if (fs.existsSync(RUNS_DIR)) {
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
const rd = path.join(RUNS_DIR, d.name);
let meta = null;
try { meta = JSON.parse(fs.readFileSync(path.join(rd, 'run.json'), 'utf8')); } catch { continue; }
@@ -651,6 +694,7 @@ function cmdCreate(pkgName, pc, displayName, model) {
fs.writeFileSync(path.join(runDir, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');
const meta = { package: pkgName, created: today() };
if (model) meta.model = model;
if (ownerOverride) meta.owner = ownerOverride;
fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify(meta, null, 2) + '\n');
for (const d of ['db', 'canon', 'dumps', 'log', 'manifests', 'sessions']) {
@@ -671,19 +715,25 @@ function cmdRuns() {
const list = [];
let found = 0;
for (const d of fs.readdirSync(RUNS_DIR, { withFileTypes: true })) {
if (!d.isDirectory()) continue;
if (!d.isDirectory() || d.name.startsWith('.')) continue; // .staging-* is never a run
const runDir = path.join(RUNS_DIR, d.name);
if (!fs.existsSync(path.join(runDir, 'run.json'))) continue; // a run is marked by run.json
found++;
let pkg = '?';
let model = null;
let owner = null;
let created = null;
let forked = null;
try {
const meta = JSON.parse(fs.readFileSync(path.join(runDir, 'run.json'), 'utf8'));
pkg = meta.package ?? '?';
model = meta.model ?? null;
owner = meta.owner ?? null;
created = meta.created ?? null;
forked = meta.forked ?? null;
} catch {}
const st = readRunSettings(runDir);
const base = { id: d.name, package: pkg, model, pc: st.pc ?? null, display: runDisplay(pkg, st) };
const base = { id: d.name, package: pkg, model, owner, created, forked, pc: st.pc ?? null, display: runDisplay(pkg, st) };
const dbPath = path.join(runDir, 'db', 'memory.db');
if (!fs.existsSync(dbPath)) { list.push({ ...base, initialized: false }); continue; }
const db = new DatabaseSync(dbPath);
@@ -701,6 +751,42 @@ function cmdRuns() {
function today() { return new Date().toISOString().slice(0, 10); }
// save the run's craft as a new user package: the same files create
// copies (plus handbook), published to every user of the deployment —
// gm.md included, because saving is the act of publishing. The saved
// package carries no pc (the next create asks for one); the display
// name is the save's one decision. The id is anonymous hex, like a
// run's: no facts, nothing to rename.
function cmdSavePackage(displayName) {
const name = String(displayName ?? '').trim();
if (!name) fail('usage: save-package "display name" (run required via --run)');
let id;
for (;;) {
id = randomBytes(4).toString('hex');
if (!fs.existsSync(path.join(STATE_PACKAGES_DIR, id)) && !fs.existsSync(path.join(PACKAGES_DIR, id))) break;
}
const dst = path.join(STATE_PACKAGES_DIR, id);
fs.mkdirSync(dst, { recursive: true });
for (const f of [...PACKAGE_FILES, ...SHARED_PROMPTS]) {
const src = path.join(RUN_ROOT, f);
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(dst, f));
}
const settingsPath = path.join(dst, 'settings.json');
let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {}
settings.name = name;
delete settings.pc; // per-run identity never rides a package
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
fs.writeFileSync(path.join(dst, 'package.json'), JSON.stringify({
owner: ownerOverride, created: today(),
}, null, 2) + '\n');
if (AS_JSON) {
console.log(JSON.stringify({ id, name, origin: 'user', owner: ownerOverride }));
return;
}
console.log(`saved package '${id}' — ${name}: ${rel(dst)}`);
}
function gmOp(ring, type, label, detail) {
const db = openDb();
if (!RINGS.includes(ring) || !TYPES.includes(type)) {
@@ -991,6 +1077,7 @@ switch (cmd) {
case 'packages': cmdPackages(); break;
case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2], args[3]); break;
case 'save-package': cmdSavePackage(args[0]); break;
case 'seed': cmdSeed(FORCE, args[0]); break;
case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break;
+217 -18
View File
@@ -12,10 +12,14 @@
const $ = (id) => document.getElementById(id);
const TOKEN_KEY = 'rp-token';
const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
const state = {
view: null, runId: null, seq: 0, poll: null, paper: [],
files: null, drafts: {}, currentFile: null, fileSpecs: {}, repoPrompts: {},
vars: [], pkg: null, log: [],
me: null, // the signed-in user ({ id, name, superuser }) or null
};
// --- diagnostics: a rolling event log that survives refreshes ---------------
@@ -48,7 +52,10 @@ async function api(path, opts = {}) {
try {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: opts.body !== undefined ? { 'content-type': 'application/json' } : {},
headers: {
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page — the notepad flush
});
@@ -58,6 +65,14 @@ async function api(path, opts = {}) {
e.detail = data.detail;
e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms — ${e.message}`);
// a rejected token ends the session: drop it and show the claim
// view — every path leads there until a fresh one is claimed
if (res.status === 401 && path !== '/session' && authToken()) {
try { localStorage.removeItem(TOKEN_KEY); } catch {}
state.me = null;
logEvent('nav', 'signed out: token rejected');
setTimeout(render, 0);
}
throw e;
}
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
@@ -348,6 +363,7 @@ async function render() {
stopPoll();
hideBanner();
const p = location.pathname;
if (!state.me) return viewClaim(seq); // signed out: every path leads to the claim
let m;
if (p === '/') return viewHome(seq);
if (p === '/new') return viewNew(seq);
@@ -359,8 +375,13 @@ async function render() {
function show(view) {
if (state.view === 'play' && view !== 'play') saveNotes(); // flush the pad when leaving play
state.view = view;
for (const v of ['home', 'new', 'setup', 'play']) $(`view-${v}`).hidden = v !== view;
for (const v of ['claim', 'home', 'new', 'setup', 'play']) $(`view-${v}`).hidden = v !== view;
document.body.classList.toggle('play', view === 'play');
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// — the lifecycle story is a roadmap extension point
$('who').textContent = state.me ? `${state.me.name}${state.me.superuser ? ' · op' : ''}` : '';
$('who').title = state.me?.id ?? '';
$('window-info').textContent = '';
$('conflict').hidden = true;
renderMeter(null);
@@ -368,6 +389,21 @@ function show(view) {
if (view !== 'play') $('ask-modal').close();
}
// --- the claim view ---------------------------------------------------------------
async function viewClaim(seq) {
show('claim');
$('claim-code').value = '';
$('claim-name').value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch {} // public: works signed out
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? 'this deployment has no users yet — the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-code').focus();
}
// --- home -----------------------------------------------------------------------
async function viewHome(seq) {
@@ -378,16 +414,81 @@ async function viewHome(seq) {
list.textContent = '';
if (!runs.length) {
list.appendChild(el('div', 'hint', 'no runs yet — start one from a package'));
return;
}
for (const r of runs) {
const mine = state.me && r.owner === state.me.id;
const card = el('button', 'card run-card');
card.appendChild(el('span', 'card-name', r.display ?? r.id));
card.appendChild(el('span', 'card-meta', `${r.package} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.model ? ` · ${r.model}` : ''}`));
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta — chrome, never model-facing
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.model ? ` · ${r.model}` : ''}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
card.addEventListener('click', () => navigate(r.lastSession ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
// another user's draft is read-only: the play view says so; your own opens the editor
card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
list.appendChild(card);
}
await renderAdmin(seq);
}
const ownershipTag = (r, mine) =>
(mine ? ' · yours' : r.owner == null ? ' · ownerless' : ` · ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
// --- admin (superuser, on home): invites and users -------------------------------
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
invList.textContent = '';
for (const i of inv.invites) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} — ${i.state}`));
if (i.state === 'unclaimed') {
const b = el('button', null, 'revoke');
b.addEventListener('click', async () => {
try { await api(`/invites/${i.id}`, { method: 'DELETE' }); render(); } catch (e) { banner(e.message); }
});
row.appendChild(b);
}
invList.appendChild(row);
}
const userList = $('user-list');
userList.textContent = '';
for (const u of us.users) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `${u.name} · ${u.id}${u.superuser ? ' · op' : ''}`));
if (u.id !== state.me.id) {
const b = el('button', 'danger', 'revoke');
b.addEventListener('click', () => revokeUser(u, b));
row.appendChild(b);
}
userList.appendChild(row);
}
}
// revocation destroys the identity — two-click armed, like every destructive act
let revokeArmed = null;
function revokeUser(u, btn) {
if (revokeArmed === null) {
btn.textContent = 'sure? click again';
revokeArmed = setTimeout(() => { revokeArmed = null; btn.textContent = 'revoke'; }, 5000);
return;
}
clearTimeout(revokeArmed);
revokeArmed = null;
btn.textContent = 'revoke';
api(`/users/${u.id}/revoke`, { method: 'POST', body: {} })
.then(() => render())
.catch((e) => banner(e.message));
}
function runStateText(r) {
@@ -417,7 +518,8 @@ async function viewNew(seq) {
for (const p of pkgs) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
card.appendChild(el('span', 'card-meta', `${p.name} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} · ${origin} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete — missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
@@ -513,6 +615,7 @@ async function viewSetup(id, seq) {
}
if (seq !== state.seq) return;
if (!detail.draft) return navigate(`/runs/${id}`); // started runs live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only — fork to edit
state.files = files.files;
state.repoPrompts = { 'system.md': prompts.system, 'invariants.md': prompts.invariants };
@@ -556,6 +659,8 @@ async function viewSetup(id, seq) {
nav.appendChild(item);
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
}
function selectFile(f) {
@@ -638,6 +743,26 @@ async function saveDirty() {
markNav();
}
// save the run's craft as a new user package — published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true;
$('savepkg-state').textContent = 'saving…';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved — ${r.package.id}`;
$('savepkg-name').value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
}
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side — stories are deleted by hand.
let deleteArmed = null;
@@ -728,21 +853,37 @@ async function refreshPlay(id, seq) {
return banner(`could not reach the server: ${e.message}`); // stay put — transient
}
if (seq !== state.seq) return;
if (detail.draft) return navigate(`/runs/${id}/setup`);
const mine = state.me && detail.run.owner === state.me.id;
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
show('play');
state.runId = id;
$('window-info').textContent = `${detail.display} — a draft, not yours`;
$('transcript').textContent = '';
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft — fork it to make it yours and edit it'));
return;
}
$('window-info').textContent = detail.open
$('window-info').textContent = (detail.open
? `${detail.display} — window ${detail.window}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: `${detail.display} — no open window`;
: `${detail.display} — no open window`)
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating');
renderMeter(detail);
renderPaper(detail.paper);
$('conflict').hidden = true;
// spectator mode: read everything, mutate nothing — the fork is the
// way in. Ownerless runs are spectators for everyone alike.
$('paper-edit').hidden = !mine;
$('gm-notes').readOnly = !mine;
let beatNeeded = false;
if (detail.open) {
const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
renderTranscript(session.entries);
beatNeeded = detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
} else {
$('transcript').textContent = '';
}
@@ -751,13 +892,17 @@ async function refreshPlay(id, seq) {
if (beatNeeded) await offerBeat(id, seq);
// controls
$('window-open').hidden = detail.open;
$('hk-run').hidden = !detail.open;
$('hk-replay').hidden = !detail.lastSession; // any session log is replayable
setInput(detail.open && !detail.pendingAsk);
$('window-open').hidden = detail.open || !mine;
$('hk-run').hidden = !detail.open || !mine;
$('hk-replay').hidden = !detail.lastSession || !mine; // any session log is replayable, by the owner
setInput(detail.open && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
? 'GM line — Enter sends, Shift+Enter newlines'
: 'spectating — fork this run to continue it as yours';
// pending ask: the modal re-presents after a refresh
if (detail.pendingAsk) {
// pending ask: the modal re-presents after a refresh — the owner's
// to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
@@ -896,6 +1041,22 @@ function setBusy(on, text = 'her turn…') {
if (on) $('busy').textContent = text;
}
// fork: a copy of this run under you — any run, anyone's, including
// yours. Lands you in the fork.
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking…');
try {
const r = await api(`/runs/${state.runId}/fork`, { method: 'POST', body: {} });
setBusy(false);
logEvent('nav', `forked ${state.runId} -> ${r.run}`);
navigate(`/runs/${r.run}`);
} catch (e) {
setBusy(false);
banner(e.message);
}
}
async function openWindow() {
const override = $('hk-override').checked;
hideBanner();
@@ -982,6 +1143,27 @@ async function loadLog() {
// --- wiring --------------------------------------------------------------------------
$('home-link').addEventListener('click', (e) => { e.preventDefault(); navigate('/'); });
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const r = await api('/claim', { method: 'POST', body: { code: $('claim-code').value.trim(), name: $('claim-name').value.trim() } });
try { localStorage.setItem(TOKEN_KEY, r.token); } catch {}
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
banner(err.message);
}
});
$('invite-mint').addEventListener('click', async () => {
try {
const r = await api('/invites', { method: 'POST', body: {} });
$('invite-code').textContent = r.code; // shown once — it is never listed again
render();
} catch (e) {
banner(e.message);
}
});
$('new-run-btn').addEventListener('click', () => navigate('/new'));
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
@@ -1017,6 +1199,8 @@ $('setup-edit').addEventListener('scroll', () => {
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
});
$('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage);
$('fork-btn').addEventListener('click', forkRun);
$('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
@@ -1036,4 +1220,19 @@ $('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
$('diag-btn').addEventListener('click', toggleDiag);
render();
// --- boot --------------------------------------------------------------------------
// restore the session from the stored token; a rejected or absent
// token leaves me signed out, and every path leads to the claim view
(async () => {
if (authToken()) {
try {
const s = await api('/session');
state.me = s.user;
if (!state.me) { try { localStorage.removeItem(TOKEN_KEY); } catch {} }
} catch {
state.me = null;
}
}
render();
})();
+32
View File
@@ -9,6 +9,7 @@
<body>
<header>
<a id="home-link" href="/">rp-test</a>
<span id="who"></span>
<div id="window-info"></div>
<div id="context-meter" title="context usage of the last call">
<div id="context-bar"><div id="context-fill"></div></div>
@@ -18,10 +19,31 @@
</header>
<main>
<section id="view-claim" hidden>
<h1>claim an invite</h1>
<p class="hint" id="claim-hint"></p>
<form id="claim-form">
<label class="field">invite code <input id="claim-code" autocomplete="off"></label>
<label class="field">display name <input id="claim-name" autocomplete="off"></label>
<div class="form-actions">
<button type="submit" class="primary">claim</button>
</div>
</form>
</section>
<section id="view-home" hidden>
<h1>runs</h1>
<div id="run-list"></div>
<button id="new-run-btn" class="primary">new run</button>
<section id="admin" hidden>
<h2>admin</h2>
<div class="form-actions">
<button id="invite-mint">mint invite</button>
<span id="invite-code"></span>
</div>
<div id="invite-list"></div>
<div id="user-list"></div>
</section>
</section>
<section id="view-new" hidden>
@@ -56,6 +78,11 @@
<span id="setup-vars-state"></span>
</div>
</div>
<div id="setup-savepkg">
<input id="savepkg-name" placeholder="new package display name" autocomplete="off">
<button id="savepkg-btn">save as package</button>
<span id="savepkg-state"></span>
</div>
<div class="setup-body">
<nav id="setup-files"></nav>
<div id="setup-editor">
@@ -109,6 +136,11 @@
<details id="hk-log" hidden><summary>window log</summary><pre id="hk-log-content"></pre></details>
<details id="hk-replay-log" hidden><summary>replay manifest</summary><pre id="hk-replay-content"></pre></details>
</section>
<section id="fork-pane">
<h2>fork</h2>
<p class="hint">a copy of this run — yours to continue</p>
<button id="fork-btn">fork this run</button>
</section>
</aside>
<footer>
+30
View File
@@ -128,6 +128,36 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
#new-run-btn { margin-top: 8px; }
/* --- identity + admin --- */
#who { color: var(--dim); font-size: 13px; }
#logout-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#claim-form { max-width: 480px; }
#admin { max-width: 560px; margin-top: 28px; border-top: 1px solid var(--line); padding-top: 14px; }
#admin h2 {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
}
#invite-code { font: 12px ui-monospace, Consolas, monospace; color: var(--accent); word-break: break-all; }
.admin-row { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); padding: 3px 0; }
.admin-row .grow { flex: 1; }
.admin-row button { font-size: 11px; padding: 1px 8px; color: var(--dim); }
.admin-row button.danger { color: var(--danger); }
/* --- setup: save-as-package --- */
#setup-savepkg { display: flex; gap: 8px; max-width: 560px; margin-bottom: 14px; align-items: center; }
#setup-savepkg input { flex: 1; }
#savepkg-state { color: var(--dim); font-size: 12px; }
/* --- aside: fork --- */
#fork-pane { margin-top: 22px; }
#fork-pane .hint { margin: 0 0 8px; }
#fork-pane button { width: 100%; }
/* the naming form (new run) and the vars box (setup) */
#create-form { max-width: 560px; }
#create-form h2 { font-size: 15px; margin: 0 0 14px; color: var(--text); font-weight: 600; }