the debug round: server.json deleted, the bind hardcoded to loopback (RP_PORT for the port), the debug superuser token-gated behind a printed, persisted token, and the context meter reading the discovered per-model contwin

The rulings (developer, 2026-11-19, in conversation): a deployment basically always needs a fronting proxy, so the listen address is code -- loopback, no override (an op who wants otherwise owns their own socat); the port rides the RP_PORT env var (the RP_BASE twin the test scripts use, default 7350, garbage refused loud); server.json is deleted entirely, file and reader both, because it held no meaningful configuration once the bind died -- only the dead bind and the declared contwin; and contwin is provider/model dependent, never a deployment global, so the meter must DISCOVER it, not read a declaration.

The meter: the run detail's context block now derives its window from the registry -- modelState's resolved player spec, findModel, the model's input ceiling -- null when the provider states none or no pick stands, pct computed against that. A dividend named in review: pct is uncapped, so a mid-run re-pick onto a smaller model shows the meter over 100% BEFORE the first send refuses (the endpoint's own context-length 400 is the designed refusal -- no pre-request check, nothing truncates, the failed call lands its req event, the composer keeps the line per the standing rule).

Debug mode reworked around its real purpose (skip the invite dance on a fresh server, mocks in particular): the old shape -- every request the superuser, no auth at all -- left any debug server that somehow reached a network fully open. Now one fixed superuser behind a real bearer token: minted into state/debug-token.txt (the bootstrap-invite precedent -- a raw secret on disk so a restart never invalidates what the tester already pasted; the developer ruled persist), printed at every boot, and the claim screen gains the paste path ("or paste a token": store it, verify through the public /session, land or banner). The paste path is generic surface, not debug-only: tokens are returned once and never listed, so a pasted saved token is the only browser-migration path that existed to build. The public /session carries a debug flag so the claim hint says "paste the token the server printed at boot" instead of pointing at the bootstrap file debug never mints. Debug browser passes now exercise the real auth path (the 401, the u: attribution line) instead of bypassing it.

En-route mock fidelity fix the smoke earned: the mock path never set s.usage (no provider call happens), so every usage and context surface was null under the smoke -- the first cut of the new gauge assertion failed on exactly that. The mock now carries a synthetic usage (the assembled view's chars over 4), riding the msg events like the real path's, so the detail's usage and the context gauge are smoke-assertable: contwin 524288 straight from the mock's registry input ceiling, pct computed.

Verified: typecheck green both programs; smoke ALL PASS (+1, the discovered-gauge assertion); restart + reminder checks green (5 runs again); a browser pass on --mock --debug end to end -- the wrong token banners "token rejected" and stays on claim, the printed token lands as Debug the op, the stored token survives a server restart (the persistence proof), zero console errors; check-repo clean (it caught the round's own "window" in the new README passage -- contwin is the word); the dev machine's server.json deleted and the debug server restarted on the real state (Chloe and Irene rebuilt, the token minted into the real state/). Docs: README's deployment and debug passages, the config passage, and the layout tree (the server.example.json lines gone with the file); DICTIONARY's meter and contwin entries (the config key died with the file -- the dated rename record keeps its day's words); AGENTS's server entry and the two server.json gotchas; HANDOFF's round record and the push-queue count (now eight). The developer's operator-queue line ("revisit the debug mode, hardcode loopback") is struck by them in the same commit. packages/detention stays untracked WIP, untouched.
This commit is contained in:
2026-11-19 10:31:03 +00:00
parent ccdd9ea129
commit 4b8fbd7471
16 changed files with 214 additions and 87 deletions
+14 -9
View File
@@ -127,8 +127,11 @@ noun -- a registry entry, never a seat.
- `node:sqlite` prints an ExperimentalWarning on every clerk call -- - `node:sqlite` prints an ExperimentalWarning on every clerk call --
harmless, filtered in bridge context. harmless, filtered in bridge context.
- Session logs, dumps, and views are generated; never hand-edit them. - Session logs, dumps, and views are generated; never hand-edit them.
- `server.json` (gitignored) holds the real key; it mirrors opencode's - There is no server.json (deleted 2026-11-19 -- it held only the
`dv` provider (config at `~/.config/opencode/opencode.jsonc`, auth at dead bind and the declared contwin): the provider entities live in
state/config.json, and the op's real key for the `dv` provider is
whatever the config carries (opencode's own config sits at
`~/.config/opencode/opencode.jsonc`, auth at
`~/.local/share/opencode/auth.json`). `~/.local/share/opencode/auth.json`).
- The repo lives at `C:\data\opencode\tiny-worlds` (renamed from - The repo lives at `C:\data\opencode\tiny-worlds` (renamed from
`rp-test` with the project name, 2026-11-15). The rename could not `rp-test` with the project name, 2026-11-15). The rename could not
@@ -166,10 +169,10 @@ noun -- a registry entry, never a seat.
browser timers resolve to node's overloads, so annotate them browser timers resolve to node's overloads, so annotate them
`?ReturnType<typeof setTimeout>` and `clearTimeout(x ?? `?ReturnType<typeof setTimeout>` and `clearTimeout(x ??
undefined)`. undefined)`.
- A fresh git worktree has neither server.json (gitignored) nor - A fresh git worktree has no node_modules: run npm.cmd
node_modules: copy server.json in from the main repo before the install before typecheck (2026-11-15, this worktree). No config
mock server starts (it exits without one), and run npm.cmd file is needed to boot -- the server comes up on loopback:7350
install before typecheck (2026-11-15, this worktree). (RP_PORT overrides) with whatever state/ holds.
- The remote (2026-11-15, developer): origin at - The remote (2026-11-15, developer): origin at
`ssh://code@code.fleshless.org:2290/hackmaster/tiny-worlds.git`, `ssh://code@code.fleshless.org:2290/hackmaster/tiny-worlds.git`,
branch mistress tracks origin/mistress. The ssh key takes a branch mistress tracks origin/mistress. The ssh key takes a
@@ -742,9 +745,11 @@ noun -- a registry entry, never a seat.
inspector, book export, service step) plus whatever the first real inspector, book export, service step) plus whatever the first real
story surfaces. story surfaces.
Server entry: `node server/main.mjs [--mock] [--debug]` (--debug: Server entry: `node server/main.mjs [--mock] [--debug]` (--debug:
every request is a fixed superuser, the users db bypassed, no one fixed superuser behind the printed token -- minted into
invite dance, loopback-bound regardless of config -- testing state/debug-token.txt, printed every boot, pasted on the claim
only); SPA at screen's token field; the users db bypassed, no invite dance --
testing only); the bind is loopback always, the port rides RP_PORT
(default 7350); SPA at
http://127.0.0.1:7350/; POST bodies from PowerShell need http://127.0.0.1:7350/; POST bodies from PowerShell need
Invoke-RestMethod (curl.exe mangles quotes); background start/stop Invoke-RestMethod (curl.exe mangles quotes); background start/stop
via Start-Process -PassThru with a PID file in $env:TEMP. via Start-Process -PassThru with a PID file in $env:TEMP.
+5 -3
View File
@@ -347,11 +347,13 @@ e
## Instrumentation ## Instrumentation
- **the meter** -- the context meter: prompt-token usage of the last - **the meter** -- the context meter: prompt-token usage of the last
call against the contwin; loud past 85%. call against the discovered contwin (the run's player model's input
ceiling from the registry); loud past 85%.
- **contwin** -- the context window, under its own name (coined - **contwin** -- the context window, under its own name (coined
2026-11-14, developer: the word "window" is beyond overloaded, so even 2026-11-14, developer: the word "window" is beyond overloaded, so even
this use got renamed). The config key in server.json is `contwin` this use got renamed). Model-dependent, read from the registry's
(`contextWindow` is still accepted). per-model input ceiling -- never deployment-declared (the
server.json config key died with the file, 2026-11-19).
- **mock mode** -- `--mock`: the scripted fake model that proves the - **mock mode** -- `--mock`: the scripted fake model that proves the
loop without a key. The smoke (`test/`) runs against it. loop without a key. The smoke (`test/`) runs against it.
- **the dump** -- `dumps/memory.sql`: the canonical id-ordered SQL - **the dump** -- `dumps/memory.sql`: the canonical id-ordered SQL
+52 -2
View File
@@ -9,6 +9,56 @@ file is the "where did we leave off" map.
## Where we are ## Where we are
- **The debug round is BUILT and verified (2026-11-19, developer-designed
in conversation): server.json is deleted, the bind is code, the
debug superuser is token-gated, and the context meter reads the
discovered contwin.** The rulings: a deployment always fronts the
server with a proxy, so the listen address is hardcoded loopback
with no override (an op who wants otherwise owns their own socat);
the port rides the RP_PORT env var (the RP_BASE twin the test
scripts use, default 7350, garbage refused loud); server.json is
gone entirely -- it held only the dead bind and the declared
contwin, no meaningful configuration (the developer's call,
striking their own operator-queue line); and contwin is
provider/model dependent, never global -- the meter derives it
from the registry: the run's player model's input ceiling, null
when the provider states none or no pick stands. Debug mode
reworked around its real purpose (skip the invite dance on a fresh
server, mocks in particular): the old shape -- every request the
superuser, no auth at all -- left any debug server that reached a
network fully open; now one fixed superuser behind a real bearer
token, minted into state/debug-token.txt (the bootstrap-invite
precedent: a raw secret on disk so a restart never invalidates
what the tester pasted -- the developer ruled persist), printed at
every boot, and the claim screen gains the paste path (store the
token, verify through the public /session, land or banner) --
generic surface, not debug-only: tokens are returned once and
never listed, so a pasted saved token is the only
browser-migration path that existed to build. The public /session
carries a debug flag so the claim hint says "paste the token the
server printed at boot" instead of pointing at the bootstrap file
debug never mints. Debug browser passes now exercise the real
auth path (the 401, the u: attribution line) instead of bypassing
it. En-route mock fidelity fix the smoke earned: the mock path
never set s.usage (no provider call happens), so every
usage/context surface was null under the smoke -- the mock now
carries a synthetic usage (the assembled view's chars over 4),
riding the msg events like the real path's, so the detail's usage
and the context gauge are smoke-assertable (+1: contwin 524288
from the registry, pct computed). Verified: typecheck green both
programs, smoke ALL PASS, restart + reminder checks green, a
browser pass on --mock --debug (the wrong token banners and stays
on claim, the printed token lands as Debug the op, the stored
token survives a server restart, zero console errors), check-repo
clean (it caught the round's own "window" in README -- contwin is
the word), and the debug server restarted on the real state (2
sessions rebuilt, the token minted into the real state/). Docs:
README's deployment and debug passages, the config passage, the
layout tree (the server.example.json lines gone); DICTIONARY's
meter and contwin entries (the config key died with the file);
AGENTS's server entry and the two server.json gotchas;
server.example.json and the dev machine's server.json deleted.
- **The roles inventory is BUILT (2026-11-19, GM-designed in - **The roles inventory is BUILT (2026-11-19, GM-designed in
conversation): every human and LLM seat named, the repo swept to conversation): every human and LLM seat named, the repo swept to
it.** DICTIONARY's "The people and the models" section is now the it.** DICTIONARY's "The people and the models" section is now the
@@ -377,9 +427,9 @@ makes the parked short-list rule suddenly relevant).
temp pid file; sessions rebuilt for Chloe and Irene at boot). temp pid file; sessions rebuilt for Chloe and Irene at boot).
state/ holds the refined registry (per-provider shape on disk, state/ holds the refined registry (per-provider shape on disk,
migrated in the no-legacy pass) and the provider config migrated in the no-legacy pass) and the provider config
('llm-exan-tech', default glm-5.3 at max). Seven commits await ('llm-exan-tech', default glm-5.3 at max). Eight commits await
the developer's push (`bbaf336`, `5279dd3`, `eefb721`, `53f992a`, the developer's push (`bbaf336`, `5279dd3`, `eefb721`, `53f992a`,
`14b9b01`, `e60fd63`, and this round -- the ssh key takes a `14b9b01`, `e60fd63`, `ccdd9ea`, and this round -- the ssh key takes a
passphrase, pushes are the developer's). passphrase, pushes are the developer's).
## Immediate next steps, in order ## Immediate next steps, in order
+18 -15
View File
@@ -63,9 +63,8 @@ or otherwise PC ever needs support, this is the line to revisit.
## The deployment (multiuser) ## The deployment (multiuser)
A deployment is one clone plus `state/` and `runs/` (all gitignored A deployment is one clone plus `state/` and `runs/` (all gitignored
state) and an optional `server.json` -- bind and contwin only; the state); the provider entities live in `state/config.json`,
provider entities live in `state/config.json`, server-written, server-written, SPA-managed, zero manual file edits. The inference key lives on the backend
SPA-managed, zero manual file edits. The inference key lives on the backend
need neither the key nor a local clone. Identity is a token, nothing need neither the key nor a local clone. Identity is a token, nothing
else: no usernames, no passwords, no external IDPs. A single-use else: no usernames, no passwords, no external IDPs. A single-use
invite code -- spent codes are recorded forever and rejected loudly on invite code -- spent codes are recorded forever and rejected loudly on
@@ -119,13 +118,15 @@ forking makes that cheap -- stories outlive identities by design.
an extension point, not built. an extension point, not built.
- All dates and times are UTC everywhere. No time zones, ever. - All dates and times are UTC everywhere. No time zones, ever.
Debug mode (`--debug`) is for testing: every request becomes one Debug mode (`--debug`) is for testing: one fixed superuser ("debug")
fixed superuser ("debug") that bypasses the user database entirely -- that bypasses the user database entirely -- no invite to claim. The
no invite to claim, no token to keep, the SPA opens straight in as bearer token that signs it in is minted into
the op, and the server binds loopback whatever the config says. It `state/debug-token.txt` and printed at every boot; paste it into the
reads normal state (runs, packages) unchanged, so it can inspect a sign-in box on the claim screen. It reads normal state (runs,
real deployment; it must simply never run on one that faces a packages) unchanged, so it can inspect a real deployment -- and with
network. every request token-gated, a debug server that somehow faces a
network is not an open door. It stays testing-only regardless: the
debug user is an unlimited superuser.
## Runs ## Runs
@@ -616,9 +617,13 @@ reached mock-parity (2026-11-14).
Config is self-healing state, not a hand-edited file (developer, 2026-11-18): Config is self-healing state, not a hand-edited file (developer, 2026-11-18):
the provider entities -- slug, baseUrl, optional key, the op's the provider entities -- slug, baseUrl, optional key, the op's
default model spec -- live in `state/config.json`, written only by default model spec -- live in `state/config.json`, written only by
the server, managed from the SPA's admin block. `server.json` the server, managed from the SPA's admin block. There is no
(gitignored, optional) is the static remainder: `bind` and `contwin` `server.json` (developer, 2026-11-19: it held no meaningful
(the context budget in tokens). No legacy config shapes are read: configuration once the bind died): the listen address is code --
loopback always, a deployment fronts the server with a proxy -- the
port rides the `RP_PORT` env var (default 7350), and the context
meter reads the discovered per-model contwin from the registry, never
a declared one. No legacy config shapes are read:
shape changes come with one-time migrations, not permanent tolerance shape changes come with one-time migrations, not permanent tolerance
(the no-legacy rule, developer, 2026-11-18). Boot always succeeds: a fresh clone with nothing comes (the no-legacy rule, developer, 2026-11-18). Boot always succeeds: a fresh clone with nothing comes
up serving and mints the superuser invite, and -- the self-heal up serving and mints the superuser invite, and -- the self-heal
@@ -882,8 +887,6 @@ test/ the mock smoke, kept next to the code
prose, zero-dependency imports, utc discipline, web/ prose, zero-dependency imports, utc discipline, web/
static naming (never "api"), the bundle boundary, static naming (never "api"), the bundle boundary,
dateless memory dateless memory
server.example.json copy to server.json (gitignored, optional) --
bind, contwin; the providers are SPA-managed state
db/ db/
schema.sql entries, records, events journal (shared; the status schema.sql entries, records, events journal (shared; the status
and agenda tables are retired -- the log is their and agenda tables are retired -- the log is their
+2 -2
View File
@@ -4,10 +4,10 @@ Reviewed 2026-11-11 via web survey: consumer companion apps, power
frontends, agent RP frameworks, memory research. Items below are meant to frontends, agent RP frameworks, memory research. Items below are meant to
be worked through one by one; statuses in caps, decisions dated. be worked through one by one; statuses in caps, decisions dated.
## Operator's queue (don't edit, don't work on) ## Developer's queue (don't edit, don't work on)
- revisit the debug mode, hardcode loopback
- "create new package" in SPA - "create new package" in SPA
- calibration package: classic dungeon (pve, minimal npcs)
- external sec review - external sec review
- refactor to add first-class GM agent - refactor to add first-class GM agent
- entirely safe-for-work package. space? vault? - entirely safe-for-work package. space? vault?
-4
View File
@@ -1,4 +0,0 @@
{
"bind": "127.0.0.1:7350",
"contwin": 262144
}
+6 -1
View File
@@ -174,9 +174,14 @@ async function runLoop(ctx, runId, user) {
if (ctx.mock) { if (ctx.mock) {
// the synthetic marker: no provider call happens, but the spec // the synthetic marker: no provider call happens, but the spec
// and the knobs resolve for real, so the smoke can assert the // and the knobs resolve for real, so the smoke can assert the
// recording // recording. Usage rides too (developer round, 2026-11-19): a
// rough chars-over-4 token count of the assembled view, so the
// detail's usage and the context gauge exercise against the
// mock exactly as they do against a real endpoint
msg = mockModel(s, view); msg = mockModel(s, view);
via = { model: spec.model, provider: spec.provider, params }; via = { model: spec.model, provider: spec.provider, params };
const chars = view.reduce((a, m) => a + String(m.content ?? '').length, 0);
s.usage = { promptTokens: Math.round(chars / 4), completionTokens: Math.round(String(msg.content ?? '').length / 4) };
} else { } else {
via = { model: spec.model, provider: spec.provider, params }; via = { model: spec.model, provider: spec.provider, params };
// attribution (#22): every inferencer call names the acting user // attribution (#22): every inferencer call names the acting user
+50 -37
View File
@@ -8,10 +8,11 @@
// session back from the jsonl -- the log is the truth, the context is a // session back from the jsonl -- the log is the truth, the context is a
// view. // view.
// //
// Debug mode (--debug): every request is one fixed superuser that // Debug mode (--debug): one fixed superuser ("debug") that bypasses
// bypasses the user database entirely -- no invite dance, no tokens. // the user database entirely -- no invite dance. The bearer token
// Loopback-bound whatever the config says. Testing only, never a real // that signs it in is minted into state/debug-token.txt and printed
// deployment. // at every boot. Loopback-bound by code, debug or not. Testing only,
// never a real deployment.
// //
// usage: node server/main.mjs [--mock] [--debug] // usage: node server/main.mjs [--mock] [--debug]
/** @typedef {import('./shapes.mjs').Ctx} Ctx */ /** @typedef {import('./shapes.mjs').Ctx} Ctx */
@@ -41,24 +42,14 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MOCK = process.argv.includes('--mock'); const MOCK = process.argv.includes('--mock');
const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser const DEBUG = process.argv.includes('--debug'); // identity bypass: everyone is the superuser
// server.json is the static, non-secret remainder: bind and contwin. // There is no server.json (developer, 2026-11-19: it held no
// Optional (developer, 2026-11-18) -- the provider entities live in // meaningful configuration once the bind died) -- the bind is code
// state/config.json (server-written, SPA-managed). Nothing here gates // (loopback always) and the port rides the RP_PORT env var. The
// the boot: a fresh deployment with no config at all comes up // provider entities live in state/config.json (server-written,
// serving, mints the superuser invite, and shows the global // SPA-managed). Nothing gates the boot: a fresh deployment with no
// no-providers banner -- every consumer of providers treats "none" // config at all comes up serving, mints the superuser invite, and
// as a loud 409, never a crash. // shows the global no-providers banner -- every consumer of
/** @type {import('./shapes.mjs').ServerCfg} */ // providers treats "none" as a loud 409, never a crash.
let cfg = {};
const SERVER_JSON = path.join(ROOT, 'server.json');
if (fs.existsSync(SERVER_JSON)) {
try {
cfg = JSON.parse(fs.readFileSync(SERVER_JSON, 'utf8'));
} catch {
console.error('server.json does not parse -- fix it or remove it (the provider entities live in state/config.json)');
process.exit(1);
}
}
let providerCfg = providers.readConfig(); let providerCfg = providers.readConfig();
// the self-heal rule (developer, 2026-11-18), stated broadly: an error that // the self-heal rule (developer, 2026-11-18), stated broadly: an error that
// can be mechanically fixed to a reasonable degree without requiring // can be mechanically fixed to a reasonable degree without requiring
@@ -86,7 +77,7 @@ if (!providerCfg.providers.length) {
const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)])); const providersMap = new Map(providerCfg.providers.map((p) => [p.slug, makeProvider(p)]));
// locks/enqueue are attached just below; the cast is the two-step that // locks/enqueue are attached just below; the cast is the two-step that
// lets the literal precede them // lets the literal precede them
const ctxBase = { mock: MOCK, cfg, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta }; const ctxBase = { mock: MOCK, providerCfg, providers: providersMap, sessions: new Map(), jobs: new Map(), runMeta: bundle.runMeta };
/** @type {Ctx} */ /** @type {Ctx} */
const ctx = /** @type {Ctx} */ (ctxBase); const ctx = /** @type {Ctx} */ (ctxBase);
@@ -119,7 +110,7 @@ ctx.enqueue = (runId, fn) => {
// --- bootstrap: the fresh-deployment superuser invite --------------------------- // --- bootstrap: the fresh-deployment superuser invite ---------------------------
if (DEBUG) { if (DEBUG) {
console.warn('debug mode: every request is the superuser -- no invites, no tokens; testing only, never a real deployment'); console.warn('debug mode: one fixed superuser behind the printed token -- no invites, no users db; testing only, never a real deployment');
} }
const boot = DEBUG ? null : users.bootstrap(); // debug skips the invite dance entirely const boot = DEBUG ? null : users.bootstrap(); // debug skips the invite dance entirely
if (boot?.code) { if (boot?.code) {
@@ -256,6 +247,7 @@ route('GET', '/api/session', async ({ user }) => ({
// the public shape only -- the stored row (token hash) never leaves // the public shape only -- the stored row (token hash) never leaves
user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null, user: user ? { id: user.id, name: user.name, superuser: user.superuser === 1 } : null,
fresh: users.userCount() === 0, fresh: users.userCount() === 0,
debug: DEBUG, // the claim screen's hint: no invite exists here
}), { public: true }); }), { public: true });
route('POST', '/api/claim', async ({ body }) => { route('POST', '/api/claim', async ({ body }) => {
@@ -762,6 +754,7 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
const latest = session.latestSession(id); const latest = session.latestSession(id);
const sm = latest == null ? {} : session.sessionMeta(id, latest); const sm = latest == null ? {} : session.sessionMeta(id, latest);
const phase = s ? 'live' : (sm.phase ?? null); const phase = s ? 'live' : (sm.phase ?? null);
const rh = roleHealth(id);
return { return {
run: { run: {
id, id,
@@ -773,7 +766,7 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
models: meta?.models ?? {}, models: meta?.models ?? {},
// the invalidation surface: each resolved spec's health, so the // the invalidation surface: each resolved spec's health, so the
// table can carry the note before a send ever 409s // table can carry the note before a send ever 409s
modelState: roleHealth(id), modelState: rh,
// the providers' default specs -- the create flow's pre-select, // the providers' default specs -- the create flow's pre-select,
// and the fallback a pick-less role would inherit // and the fallback a pick-less role would inherit
providerDefaults: providerDefaults(), providerDefaults: providerDefaults(),
@@ -793,11 +786,16 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
events: st.events, events: st.events,
pendingAsk: s?.pendingAsk?.question ?? null, pendingAsk: s?.pendingAsk?.question ?? null,
usage: s?.usage ?? null, usage: s?.usage ?? null,
context: s?.usage ? { // the discovered window (developer, 2026-11-19): contwin is
used: s.usage.promptTokens, // model-dependent, never deployment-declared -- the run's player
contwin: cfg.contwin ?? null, // model's input ceiling from the registry, null when the provider
pct: cfg.contwin ? Math.round((100 * s.usage.promptTokens) / cfg.contwin) : null, // states none or no pick stands
} : null, context: (() => {
if (!s?.usage) return null;
const spec = rh.player.spec;
const win = spec ? discovery.findModel(spec.provider, spec.model)?.input ?? null : null;
return { used: s.usage.promptTokens, contwin: win, pct: win ? Math.round((100 * s.usage.promptTokens) / win) : null };
})(),
}; };
}); });
@@ -1418,8 +1416,12 @@ route('POST', '/api/runs/:id/housekeeping/apply', async ({ params, body, user })
// bearer-token identity (users.mjs); null when absent or unknown // bearer-token identity (users.mjs); null when absent or unknown
/** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */ /** @param {import('node:http').IncomingMessage} req @returns {?UserRow} */
function authenticate(req) { function authenticate(req) {
if (DEBUG) return DEBUG_USER; // debug: everyone is the superuser
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? ''); const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
if (DEBUG) {
// debug: the one fixed superuser, token-gated -- the token lives
// in state/debug-token.txt and is printed at every boot
return m && m[1].trim() === users.debugToken() ? DEBUG_USER : null;
}
return m ? users.getUserByToken(m[1].trim()) : null; return m ? users.getUserByToken(m[1].trim()) : null;
} }
@@ -1455,12 +1457,23 @@ const server = http.createServer(async (req, res) => {
} }
}); });
// debug never leaves this machine: whatever the config binds, the // the bind is code, not config (developer, 2026-11-19): loopback
// debug host is loopback (the port stays configurable) // always -- a deployment fronts the server with a proxy, and anything
const [cfgHost, port] = String(cfg.bind ?? '127.0.0.1:7350').split(':'); // else is the op's socat. The port rides RP_PORT (the RP_BASE twin
const host = DEBUG ? '127.0.0.1' : cfgHost; // the test scripts use), default 7350, garbage refused loud.
server.listen(Number(port ?? 7350), host, () => { const PORT = (() => {
const raw = process.env.RP_PORT;
if (raw == null || raw === '') return 7350;
const n = Number(raw);
if (!Number.isInteger(n) || n < 1 || n > 65535) {
console.error(`RP_PORT '${raw}' is not a port -- fix or unset it`);
process.exit(1);
}
return n;
})();
server.listen(PORT, '127.0.0.1', () => {
const providerCount = ctx.providerCfg.providers.length; const providerCount = ctx.providerCfg.providers.length;
const discovered = Object.keys(discovery.registry()?.providers ?? {}).length; const discovered = Object.keys(discovery.registry()?.providers ?? {}).length;
console.log(`Tiny Worlds server: http://${host}:${port} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG: auth bypassed' : ''}`); console.log(`Tiny Worlds server: http://127.0.0.1:${PORT} | ${MOCK ? 'MOCK model' : `${providerCount} provider(s), ${discovered} discovered`} | ${ctx.sessions.size} session(s) rebuilt${DEBUG ? ' | DEBUG' : ''}`);
if (DEBUG) console.log(`debug token (paste it into the sign-in box): ${users.debugToken()}`);
}); });
+1 -5
View File
@@ -196,13 +196,9 @@ export {};
* written only (the SPA is the surface, zero hand edits). */ * written only (the SPA is the surface, zero hand edits). */
/** @typedef {{ providers: ProviderCfg[] }} DeployCfg */ /** @typedef {{ providers: ProviderCfg[] }} DeployCfg */
/** server.json as parsed -- the static, non-secret remainder of the
* old config: bind and contwin. */
/** @typedef {{ bind?: string, port?: number, contwin?: number }} ServerCfg */
/** The server context: the one object threaded through every module. /** The server context: the one object threaded through every module.
* locks/enqueue are the per-run activity lock (main.mjs). providers * locks/enqueue are the per-run activity lock (main.mjs). providers
* is the provider clients keyed by slug (the config's truth, * is the provider clients keyed by slug (the config's truth,
* rebuilt on every config mutation); providerCfg is the config * rebuilt on every config mutation); providerCfg is the config
* itself. */ * itself. */
/** @typedef {{ mock: boolean, cfg: ServerCfg, providerCfg: DeployCfg, providers: Map<string, Provider>, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */ /** @typedef {{ mock: boolean, providerCfg: DeployCfg, providers: Map<string, Provider>, sessions: Map<string, LiveSession>, jobs: Map<string, JobState>, runMeta: (runId: string) => ?RunMeta, locks: Map<string, Promise<void>>, enqueue: <T>(runId: string, fn: () => Promise<T>) => Promise<T> }} Ctx */
+20
View File
@@ -179,3 +179,23 @@ export function bootstrap() {
} }
export const bootstrapFile = BOOTSTRAP_FILE; export const bootstrapFile = BOOTSTRAP_FILE;
// --- the debug token -------------------------------------------------------------
//
// Debug mode's sign-in (developer, 2026-11-19): one bearer token,
// minted into state/debug-token.txt and printed by the server at
// every boot. The bootstrap-invite precedent -- a raw secret on disk
// so a restart never invalidates what the tester already pasted.
// Never a db row: the debug user stays out of the deployment's
// people, the token dies with the file.
const DEBUG_TOKEN_FILE = path.join(STATE_DIR, 'debug-token.txt');
/** @returns {string} */
export function debugToken() {
const existing = fs.existsSync(DEBUG_TOKEN_FILE) ? fs.readFileSync(DEBUG_TOKEN_FILE, 'utf8').trim() : '';
if (existing) return existing;
const t = hex(16); // 32 hex chars -- the user-token shape
fs.writeFileSync(DEBUG_TOKEN_FILE, `${t}\n`);
return t;
}
+1 -1
View File
@@ -3,7 +3,7 @@
// node test/check-repo.mjs // node test/check-repo.mjs
// //
// 1. ASCII bytes everywhere (developer, 2026-11-15). No unicode in any // 1. ASCII bytes everywhere (developer, 2026-11-15). No unicode in any
// tracked file; gitignored state (runs/, state/, server.json) is // tracked file; gitignored state (runs/, state/) is
// per-deployment and exempt. The ENCODING is the problem, never // per-deployment and exempt. The ENCODING is the problem, never
// the visual: rendered glyphs travel ASCII-safe (\u escapes in // the visual: rendered glyphs travel ASCII-safe (\u escapes in
// JS, entities in HTML), never verbatim bytes. // JS, entities in HTML), never verbatim bytes.
+3
View File
@@ -363,6 +363,9 @@ ok('gm turn -> variant literature', r.status === 200 && r.data.variants?.count =
const pickedStatus = r.data.variants.chosen === 0 ? 'determined' : 'cautious'; const pickedStatus = r.data.variants.chosen === 0 ? 'determined' : 'cautious';
r = await call(`/runs/${runId}`, { token: op }); r = await call(`/runs/${runId}`, { token: op });
ok("the picked variant's status applied", r.data.status.includes(pickedStatus), JSON.stringify(r.data.status)); ok("the picked variant's status applied", r.data.status.includes(pickedStatus), JSON.stringify(r.data.status));
ok('the context gauge reads the discovered window (the registry input ceiling, never a declared config)',
r.data.context?.contwin === 524288 && r.data.context?.pct === Math.round((100 * r.data.context.used) / 524288),
JSON.stringify(r.data.context ?? null));
r = await call(`/runs/${runId}/session`, { token: op }); r = await call(`/runs/${runId}/session`, { token: op });
ok('raw session keeps the whole block', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /<variants>/.test(e.m.content ?? '')), 'no <variants> in the raw log'); ok('raw session keeps the whole block', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /<variants>/.test(e.m.content ?? '')), 'no <variants> in the raw log');
const pickNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'pick'); const pickNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'pick');
+1 -1
View File
@@ -25,7 +25,7 @@ export function setSessionInfo(text) {
/** The run detail (GET /runs/:id) carries the meter's numbers; null /** The run detail (GET /runs/:id) carries the meter's numbers; null
* is the router's "no run addressed" reset. * is the router's "no run addressed" reset.
* @param {?{ context?: ?{ used?: ?number, pct?: ?number, contwin?: ?boolean } }} [detail] */ * @param {?{ context?: ?{ used?: ?number, pct?: ?number, contwin?: ?number } }} [detail] */
export function renderMeter(detail) { export function renderMeter(detail) {
const fill = $('context-fill'); const fill = $('context-fill');
const label = $('context-label'); const label = $('context-label');
+6
View File
@@ -29,6 +29,12 @@
<button type="submit" class="primary">claim</button> <button type="submit" class="primary">claim</button>
</div> </div>
</form> </form>
<form id="token-form">
<label class="field">or paste a token <input id="token-paste" autocomplete="off"></label>
<div class="form-actions">
<button type="submit">sign in</button>
</div>
</form>
</section> </section>
<section id="view-home" hidden> <section id="view-home" hidden>
+1 -1
View File
@@ -25,7 +25,7 @@ export {};
* her two blocks, the fill, the context meter's numbers. models is * her two blocks, the fill, the context meter's numbers. models is
* run.json verbatim (the spec picks); modelState is the resolved * run.json verbatim (the spec picks); modelState is the resolved
* truth. */ * truth. */
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, modelState: { player: RoleHealth, housekeeper: RoleHealth }, providerDefaults: { slug: string, default: ?{ model: string, effort: string } }[] }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */ /** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, modelState: { player: RoleHealth, housekeeper: RoleHealth }, providerDefaults: { slug: string, default: ?{ model: string, effort: string } }[] }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], sheet: ?Record<string, unknown>, records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?number, pct: ?number } }} RunDetail */
/** One provider's /api/models payload: its registry section (phase /** One provider's /api/models payload: its registry section (phase
* 'none' when never discovered), the op's default spec, the * 'none' when never discovered), the op's default spec, the
+34 -6
View File
@@ -1,9 +1,12 @@
// web/view-claim.mjs -- the invite claim: the only public screen. // web/view-claim.mjs -- the invite claim and the token paste: the
// A single-use invite code is exchanged for a persistent token; the // only public screen. A single-use invite code is exchanged for a
// display name is a freeform label, collisions allowed. // persistent token; the display name is a freeform label, collisions
// allowed. The paste path takes a token straight into the store --
// the debug token's way in, and the only browser-migration path for
// a saved token (tokens are returned once, never listed).
import { $ } from './dom.mjs'; import { $ } from './dom.mjs';
import { api, setToken } from './client.mjs'; import { api, setToken, clearToken } from './client.mjs';
import { state } from './state.mjs'; import { state } from './state.mjs';
import { banner } from './chrome.mjs'; import { banner } from './chrome.mjs';
import { logEvent } from './log.mjs'; import { logEvent } from './log.mjs';
@@ -13,12 +16,18 @@ import { navigate } from './router.mjs';
export async function enter(arg, seq) { export async function enter(arg, seq) {
/** @type {HTMLInputElement} */ ($('claim-code')).value = ''; /** @type {HTMLInputElement} */ ($('claim-code')).value = '';
/** @type {HTMLInputElement} */ ($('claim-name')).value = ''; /** @type {HTMLInputElement} */ ($('claim-name')).value = '';
/** @type {HTMLInputElement} */ ($('token-paste')).value = '';
let fresh = false; let fresh = false;
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ } let debug = false;
try { ({ fresh = false, debug = false } = await api('/session')); } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return; if (seq !== state.seq) return;
$('claim-hint').textContent = fresh /** @type {string} */
let hint;
if (debug) hint = 'debug server -- paste the token the server printed at boot';
else hint = fresh
? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server' ? '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'; : 'a single-use invite code, from the operator';
$('claim-hint').textContent = hint;
/** @type {HTMLInputElement} */ ($('claim-code')).focus(); /** @type {HTMLInputElement} */ ($('claim-code')).focus();
} }
@@ -34,3 +43,22 @@ $('claim-form').addEventListener('submit', async (e) => {
banner(err.message); banner(err.message);
} }
}); });
// the paste path: store the token, then verify it the same way the
// app boot does -- the public /session resolves it to a user or null
$('token-form').addEventListener('submit', async (e) => {
e.preventDefault();
const t = /** @type {HTMLInputElement} */ ($('token-paste')).value.trim();
if (!t) return;
try {
setToken(t);
const r = await api('/session');
if (!r.user) { clearToken(); banner('token rejected'); return; }
state.me = r.user;
logEvent('nav', `signed in: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
clearToken();
banner(err.message);
}
});