Files
dingoandClaude Opus 5.5 6de2b7b1ca
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 5m17s
Foundation / image (push) Successful in 6m23s
Foundation / server-image (push) Successful in 8m26s
feat(admin): end a stranded life from the portal (schema 69)
ADR-0182 section 18. Region 16 refused every birth for an account with
"Existing cell is already bound to this account" although no cell in it
held the account: a published reservation was never ended, and the only
remedy was tools/ops/end-account-life.sql as the database owner.

- Account action POST /api/accounts/<uuid>/end-life?request=N. The admin
  API reads the life's region from the account's lives and refuses while
  that region's live view lists a cell holding the account (also a bud,
  split offspring or organism control moved to), a region it cannot view,
  an incomplete view, an unpublished request or a life no longer open.
- Schema 69: admin_end_account_life_v1 (admin role only) ends it at the
  region's latest commit and appends who and why to admin_life_endings.
- The account page shows End life for each published life not ended.
- A region refusing a birth because the account holds a cell (life_exists)
  could never record it: reject_primitive_life accepted reasons 1..3 only.
  The reservation stayed open and unpublished and refused every later
  birth. Schema 69 and the C++ wrapper accept existing_life (4).
- A region with no ticking cells ignored queued admin commands (such as a
  spawn) until something else woke it; a queued command now keeps it
  ticking until applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 07:32:08 -04:00

1994 lines
114 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ADR-0182 admin portal. Keycloak sign-in (authorization code with PKCE), then the
// admin API on this origin. Tokens stay in this tab: the access token in memory, the refresh
// and ID tokens in sessionStorage so a reload keeps the session. No third-party code.
const store = {
get: (k) => { try { return sessionStorage.getItem(k); } catch { return null; } },
set: (k, v) => { try { sessionStorage.setItem(k, v); } catch { /* private mode */ } },
drop: (...ks) => { try { ks.forEach((k) => sessionStorage.removeItem(k)); } catch { /* */ } },
};
let config = null;
let access = null; // { token, expires (ms) }
let refreshing = null; // In-flight refresh promise.
// ---------- DOM helpers (textContent only: nothing from the API is parsed as HTML) ----------
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'style') Object.assign(el.style, v); // CSSOM: the CSP refuses style attributes.
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
for (const c of children.flat()) {
if (c === null || c === undefined || c === false) continue;
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
return el;
}
const main = () => document.getElementById('main');
function show(...nodes) { main().replaceChildren(...nodes); }
// ---------- Theme: the system's, or light or dark as chosen (kept in this browser) ----------
function savedTheme() { try { return localStorage.getItem('theme') || 'system'; } catch { return 'system'; } }
function applyTheme(choice) {
const root = document.documentElement;
if (choice === 'light' || choice === 'dark') root.dataset.theme = choice;
else delete root.dataset.theme;
for (const b of document.querySelectorAll('[data-theme-choice]')) b.classList.toggle('on', b.dataset.themeChoice === choice);
window.dispatchEvent(new Event('themechange'));
}
applyTheme(savedTheme());
for (const b of document.querySelectorAll('[data-theme-choice]')) {
b.addEventListener('click', () => {
try { localStorage.setItem('theme', b.dataset.themeChoice); } catch { /* private mode */ }
applyTheme(b.dataset.themeChoice);
});
}
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => window.dispatchEvent(new Event('themechange')));
// ---------- Formatting ----------
const fmtInt = (n) => (n === null || n === undefined ? '—' : Number(n).toLocaleString());
function fmtUnit(value, units) {
if (value === null || value === undefined) return '—';
let v = Number(value), i = 0;
while (Math.abs(v) >= 1000 && i < units.length - 1) { v /= 1000; i++; }
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(v >= 10 ? 1 : 2)} ${units[i]}`;
}
const fmtEnergy = (pj) => fmtUnit(pj, ['pJ', 'nJ', 'µJ', 'mJ', 'J']);
const fmtMass = (fg) => fmtUnit(fg, ['fg', 'pg', 'ng', 'µg', 'mg']);
const fmtLength = (um) => fmtUnit(um, ['µm', 'mm', 'm']);
function fmtTime(seconds) {
if (!seconds) return '—';
return new Date(seconds * 1000).toLocaleString();
}
function fmtAgo(seconds) {
if (!seconds) return '—';
const d = Math.round(Date.now() / 1000 - seconds);
if (Math.abs(d) < 60) return d >= 0 ? `${d}s ago` : `in ${-d}s`;
const m = Math.round(d / 60);
if (Math.abs(m) < 60) return m >= 0 ? `${m}m ago` : `in ${-m}m`;
const hr = Math.round(m / 60);
if (Math.abs(hr) < 48) return hr >= 0 ? `${hr}h ago` : `in ${-hr}h`;
return `${Math.round(hr / 24)}d ago`;
}
const short = (id) => (id ? `${id.slice(0, 8)}…` : '—');
function fmtDuration(seconds) {
const s = Math.max(0, Math.round(seconds || 0));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m ${s % 60}s`;
const hr = Math.floor(m / 60);
return hr < 48 ? `${hr}h ${m % 60}m` : `${Math.floor(hr / 24)}d ${hr % 24}h`;
}
// ---------- Sign-in ----------
function b64url(bytes) {
let s = '';
bytes.forEach((b) => { s += String.fromCharCode(b); });
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function randomText(n) {
const a = new Uint8Array(n);
crypto.getRandomValues(a);
return b64url(a);
}
const endpoint = (name) => `${config.issuer}/protocol/openid-connect/${name}`;
const redirectUri = () => `${location.origin}/`;
async function signIn() {
const verifier = randomText(48);
const state = randomText(16);
const challenge = b64url(new Uint8Array(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
store.set('pkce_verifier', verifier);
store.set('pkce_state', state);
store.set('return_to', location.hash || '#/accounts');
const url = new URL(endpoint('auth'));
url.search = new URLSearchParams({
client_id: config.client_id, redirect_uri: redirectUri(), response_type: 'code',
response_mode: 'query', scope: 'openid email', state, code_challenge: challenge,
code_challenge_method: 'S256',
});
location.assign(url);
}
async function tokenRequest(body) {
const res = await fetch(endpoint('token'), {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ client_id: config.client_id, ...body }),
});
if (!res.ok) throw new Error(`token endpoint ${res.status}`);
const t = await res.json();
access = { token: t.access_token, expires: Date.now() + (t.expires_in || 60) * 1000 };
if (t.refresh_token) store.set('refresh_token', t.refresh_token);
if (t.id_token) store.set('id_token', t.id_token);
return access.token;
}
async function finishSignIn() {
const params = new URLSearchParams(location.search);
const code = params.get('code');
if (!code && !params.get('error')) return false;
const expected = store.get('pkce_state');
const verifier = store.get('pkce_verifier');
const returnTo = store.get('return_to') || '#/accounts';
store.drop('pkce_state', 'pkce_verifier', 'return_to');
history.replaceState(null, '', `/${returnTo}`);
if (params.get('error') || !expected || params.get('state') !== expected || !verifier) {
throw new Error(`sign-in was not completed (${params.get('error') || 'state mismatch'})`);
}
await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri(),
code_verifier: verifier });
return true;
}
async function token() {
if (access && access.expires - Date.now() > 30000) return access.token;
const refresh = store.get('refresh_token');
if (!refresh) return null;
refreshing = refreshing || tokenRequest({ grant_type: 'refresh_token', refresh_token: refresh })
.catch(() => { store.drop('refresh_token'); access = null; return null; })
.finally(() => { refreshing = null; });
return refreshing;
}
function signOut() {
const idToken = store.get('id_token');
store.drop('refresh_token', 'id_token');
access = null;
const url = new URL(endpoint('logout'));
url.search = new URLSearchParams({
client_id: config.client_id, post_logout_redirect_uri: redirectUri(),
...(idToken ? { id_token_hint: idToken } : {}),
});
location.assign(url);
}
class ApiError extends Error {
constructor(status, code, detail = {}) { super(code || `HTTP ${status}`); this.status = status; this.code = code; this.detail = detail; }
}
// `body` is sent as plain text (only tuning revisions take one).
async function api(path, retry = true, method = 'GET', body = undefined) {
const t = await token();
if (!t) throw new ApiError(401, 'signed_out');
const headers = { Authorization: `Bearer ${t}` };
if (body !== undefined) headers['Content-Type'] = 'text/plain; charset=utf-8';
const res = await fetch(path, { method, headers, body, cache: 'no-store' });
if (res.status === 401 && retry) { access = null; return api(path, false, method, body); }
if (!res.ok) {
let detail = {};
const raw = await res.text();
try { detail = JSON.parse(raw); } catch { /* plain text or a proxy's page */ }
// A 413 page in HTML is the web proxy's limit; the admin API's own answer is plain text.
const tooLarge = raw.includes('<html') ? 'proxy_too_large' : 'too_large';
if (res.status === 413) detail = { ...detail, bytes: body === undefined ? 0 : new Blob([body]).size };
throw new ApiError(res.status, detail.error || (res.status === 413 ? tooLarge : null), detail);
}
return res.json();
}
// ---------- Sortable tables ----------
function table(columns, rows, { onRow, sortKey, sortUp = false } = {}) {
let key = sortKey, up = sortUp;
const wrap = h('div', { class: 'table-wrap' });
const draw = () => {
const col = columns.find((c) => c.key === key);
const sorted = col ? [...rows].sort((a, b) => {
const va = col.sort ? col.sort(a) : a[col.key];
const vb = col.sort ? col.sort(b) : b[col.key];
const r = va === vb ? 0 : va === null || va === undefined ? 1 : vb === null || vb === undefined ? -1 : va < vb ? -1 : 1;
return up ? r : -r;
}) : rows;
const head = h('tr', {}, columns.map((c) => h('th', {
class: [c.num ? 'num' : '', c.key === key ? `sorted${up ? ' up' : ''}` : ''].join(' ').trim() || null,
onclick: () => { if (key === c.key) up = !up; else { key = c.key; up = !c.num; } draw(); },
}, c.label)));
const body = sorted.map((r) => h('tr', { class: onRow ? 'clickable' : null, onclick: onRow ? () => onRow(r) : null },
columns.map((c) => h('td', { class: c.num ? 'num' : null }, c.render ? c.render(r) : (r[c.key] ?? '—')))));
wrap.replaceChildren(h('table', {}, h('thead', {}, head), h('tbody', {}, body.length ? body
: h('tr', {}, h('td', { colspan: columns.length, class: 'muted' }, 'Nothing to show.')))));
};
draw();
return wrap;
}
function statusBadge(a) {
const life = h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` },
a.status === 'no_life' ? 'no life' : a.status);
return a.banned ? h('span', {}, life, ' ', h('span', { class: 'badge dead' }, 'banned')) : life;
}
function sessionBadge(a) {
return a.logged_in ? h('span', { class: 'badge online' }, `online · region ${a.control_region}`)
: h('span', { class: 'muted' }, 'offline');
}
// ---------- Pages ----------
let stopPage = () => {};
async function accountsPage() {
const data = await api('/api/accounts');
const search = h('input', { type: 'search', placeholder: 'Filter by account, subject or status' });
const holder = h('div');
const columns = [
{ key: 'account', label: 'Account', render: (a) => h('span', { class: 'mono', title: a.account }, short(a.account)) },
{ key: 'subject', label: 'Keycloak subject', render: (a) => h('span', { class: 'mono muted', title: a.subject || '' }, a.subject ? short(a.subject) : '—') },
{ key: 'status', label: 'Status', render: statusBadge },
{ key: 'logged_in', label: 'Session', render: sessionBadge, sort: (a) => (a.logged_in ? 1 : 0) },
{ key: 'active_region', label: 'Region', render: (a) => a.active_region ?? '—', sort: (a) => Number(a.active_region ?? -1) },
{ key: 'lives', label: 'Lives', num: true },
{ key: 'deaths', label: 'Deaths', num: true },
{ key: 'resets', label: 'Resets', num: true },
{ key: 'mutation_choices', label: 'Mutation choices', num: true },
{ key: 'played_seconds', label: 'Time played', num: true, render: (a) => fmtDuration(a.played_seconds) },
{ key: 'created_at', label: 'Created', render: (a) => (a.created_at ? fmtAgo(a.created_at) : '—'), sort: (a) => a.created_at ?? 0 },
];
const draw = () => {
const q = search.value.trim().toLowerCase();
const rows = data.accounts.filter((a) => !q || [a.account, a.subject, a.status].some((v) => (v || '').toLowerCase().includes(q)));
holder.replaceChildren(table(columns, rows, { sortKey: 'created_at', onRow: (a) => { location.hash = `#/accounts/${a.account}`; } }));
};
search.addEventListener('input', draw);
const n = data.accounts.length;
const online = data.accounts.filter((a) => a.logged_in).length;
const alive = data.accounts.filter((a) => a.status === 'alive').length;
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Accounts'), h('div', { class: 'subtitle' }, `World ${data.world}`)),
h('div', { class: 'tools' }, search, h('button', { onclick: () => route() }, 'Refresh'))),
h('div', { class: 'stats' },
stat('Accounts', fmtInt(n)), stat('Online', fmtInt(online)), stat('Alive', fmtInt(alive)),
stat('Deaths', fmtInt(data.accounts.reduce((s, a) => s + (a.deaths || 0), 0)))),
holder);
draw();
}
function stat(label, value, sub) {
return h('div', { class: 'stat' }, h('div', { class: 'label' }, label),
h('div', { class: 'value' }, value, sub ? h('small', {}, ` ${sub}`) : null));
}
// persistence::LifeRefusal.
const rejections = ['accepted', 'refused: not enough funding', 'refused: no placement', 'cancelled', 'refused: already alive'];
async function livingOffspring(identities) {
// Living wildlife whose lineage root is one of the account's lives, in every viewable region.
const roots = new Set(identities);
let count = 0;
try {
const regions = await api('/api/regions');
for (const r of regions.regions.filter((x) => x.viewable)) {
try {
const view = await api(`/api/regions/${r.region}/view`);
count += view.cells.filter((c) => (c[6] & 1) && roots.has(c[14])).length;
} catch { /* region not ready */ }
}
} catch { return null; }
return count;
}
async function accountPage(id) {
const data = await api(`/api/accounts/${id}`);
const a = data.account;
const offspring = h('span', { class: 'muted' }, '…');
livingOffspring(data.lives.filter((l) => l.born !== null).map((l) => l.identity))
.then((n) => { offspring.textContent = n === null ? '—' : fmtInt(n); });
const note = h('span', { class: 'muted small' });
const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' });
const act = async (path, label, ask) => {
if (ask && !confirm(ask)) return;
try {
const q = new URLSearchParams(path.includes('?') ? path.split('?')[1] : '');
if (reason.value.trim()) q.set('reason', reason.value.trim());
await api(`/api/accounts/${a.account}/${path.split('?')[0]}?${q}`, true, 'POST');
route();
} catch (e) { note.textContent = `Could not ${label}: ${e.code || e.message}`; }
};
const actions = h('div', { class: 'card' }, h('h2', {}, 'Account actions'),
h('div', { class: 'window-controls' },
h('button', { onclick: () => act('logout', 'log out', `Log out ${short(a.account)} now? Its session closes within seconds.`) }, 'Log out'),
a.banned
? h('button', { onclick: () => act('ban?banned=0', 'lift the ban') }, 'Lift ban')
: h('button', { class: 'danger', onclick: () => act('ban?banned=1', 'ban', `Ban ${short(a.account)}? It is logged out and cannot sign in to play.`) }, 'Ban'),
// A published life never ended refuses every new birth ("Existing cell is already bound").
data.lives.filter((l) => !l.rejection && l.born !== null && !l.ended_tick).map((l) =>
h('button', { class: 'danger', onclick: () => act(`end-life?request=${l.request}`, 'end the life',
`End life ${l.identity} in region ${l.region}? Use this only when the account has no cell left there. The region refuses while one still holds the account.`) },
`End life ${l.identity}`))),
reason, note,
data.bans.length ? h('table', { class: 'compact' }, h('tbody', {}, data.bans.slice(0, 8).map((b) =>
h('tr', {}, h('td', {}, fmtTime(b.at)), h('td', {}, b.banned ? h('span', { class: 'badge dead' }, 'banned') : 'lifted'),
h('td', { class: 'muted' }, (b.author || '').split(' (')[0]), h('td', { class: 'muted' }, b.reason || ''))))) : null);
const facts = h('dl', { class: 'facts' },
h('dt', {}, 'Account'), h('dd', { class: 'mono' }, a.account),
h('dt', {}, 'Keycloak subject'), h('dd', { class: 'mono' }, a.subject || '—'),
h('dt', {}, 'Issuer'), h('dd', { class: 'mono' }, a.issuer || '—'),
h('dt', {}, 'Status'), h('dd', {}, statusBadge(a)),
h('dt', {}, 'Session'), h('dd', {}, sessionBadge(a),
a.control_expires ? h('span', { class: 'muted' }, ` control ${a.logged_in ? 'until' : 'ended'} ${fmtTime(a.control_expires)}`) : null),
h('dt', {}, 'Active life'), h('dd', { class: 'mono' }, a.active_life ?? '—',
a.active_region ? h('span', {}, ' ', h('a', { href: `#/regions/${a.active_region}?account=${a.account}` }, `show in region ${a.active_region}`)) : null),
h('dt', {}, 'Created'), h('dd', {}, fmtTime(a.created_at)),
h('dt', {}, 'Last seen'), h('dd', {}, a.last_seen ? `${fmtTime(a.last_seen)} (${fmtAgo(a.last_seen)})` : '—'),
h('dt', {}, 'Living offspring'), h('dd', {}, offspring, h('span', { class: 'muted' }, ' wildlife descended from its lives')));
const lives = table([
{ key: 'request', label: 'Request', sort: (l) => Number(l.request) },
{ key: 'identity', label: 'Life', render: (l) => h('span', { class: 'mono' }, l.identity) },
{ key: 'region', label: 'Region' },
{ key: 'rejection', label: 'Outcome', render: (l) => (l.rejection ? h('span', { class: 'badge warn' }, rejections[l.rejection] || `refused ${l.rejection}`)
: l.born === null ? h('span', { class: 'muted' }, 'reserved') : l.ended_tick ? h('span', { class: 'badge dead' }, 'died') : h('span', { class: 'badge alive' }, 'alive')) },
{ key: 'born', label: 'Born (tick)', num: true, sort: (l) => Number(l.born ?? -1) },
{ key: 'ended_tick', label: 'Ended (tick)', num: true, sort: (l) => Number(l.ended_tick ?? -1) },
{ key: 'ended_at', label: 'Ended', render: (l) => fmtTime(l.ended_at), sort: (l) => l.ended_at ?? 0 },
], data.lives, { sortKey: 'request' });
show(
h('div', { class: 'head' }, h('div', {}, h('a', { class: 'crumb', href: '#/accounts' }, '← Accounts'), h('h1', {}, `Account ${short(a.account)}`))),
h('div', { class: 'stats' },
stat('Lives', fmtInt(a.lives)), stat('Deaths', fmtInt(a.deaths)), stat('Resets', fmtInt(a.resets)),
stat('Mutation choices', fmtInt(a.mutation_choices)),
stat('Time played', fmtDuration(a.played_seconds), `${fmtInt(a.sessions)} sessions`)),
h('div', { class: 'card' }, facts),
actions,
h('h2', { style: { marginTop: '24px' } }, 'Lives'), lives,
h('p', { class: 'muted' }, 'Time played counts sessions from schema 64 on; earlier play is not recorded.'));
}
// ---------- Region building blocks ----------
// Energy in pJ, matter in fg; the five channels in the view's order.
const channels = [
{ key: 'energy', label: 'Energy', short: 'Energy', fmt: (v) => fmtEnergy(v) },
{ key: 'carbon', label: 'Carbon', short: 'C', fmt: (v) => fmtMass(v) },
{ key: 'nitrogen', label: 'Nitrogen', short: 'N', fmt: (v) => fmtMass(v) },
{ key: 'phosphorus', label: 'Phosphorus', short: 'P', fmt: (v) => fmtMass(v) },
{ key: 'other', label: 'Other', short: 'Other', fmt: (v) => fmtMass(v) },
];
const channelNames = channels.map((c) => c.key);
const fmtChannel = (i, v) => channels[i].fmt(v);
const sum = (a) => a.reduce((s, v) => s + Number(v || 0), 0);
const addTo = (into, a) => { a.forEach((v, i) => { into[i] += Number(v || 0); }); return into; };
const tickSeconds = 0.05; // One 50 ms tick.
const depositLimit = 8192; // biology::max_cellular_liquid_deposits.
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
const swatch = (cls) => h('span', { class: `swatch ${cls}` });
const reasonInput = () => h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional, recorded)', class: 'grow' });
// replaceChildren without the nulls h() skips (the DOM would print them).
const fill = (el, ...nodes) => el.replaceChildren(...nodes.flat().filter((n) => n !== null && n !== undefined && n !== false));
const block = (title, aside, ...body) => h('div', { class: 'block' },
h('div', { class: 'block-head' }, h('h3', {}, title), aside || null), ...body);
// Amounts typed in friendly units: energy in µJ (10^6 pJ), matter in ng (10^6 fg).
function amountInputs() {
const fields = channels.map((c) => {
const input = h('input', { type: 'number', min: 0, step: 'any', placeholder: '0' });
return { c, input, node: h('div', { class: 'field' }, h('label', {}, swatch(c.key), `${c.label} ${c.key === 'energy' ? 'µJ' : 'ng'}`), input) };
});
const read = () => {
const out = {};
for (const { c, input } of fields) {
const v = Number(input.value || 0);
if (!Number.isFinite(v) || v < 0) throw new Error(`${c.label} must be a positive number`);
out[c.key] = String(Math.round(v * 1e6));
}
if (Object.values(out).every((v) => v === '0')) throw new Error('Enter at least one amount.');
return out;
};
const clear = () => fields.forEach(({ input }) => { input.value = ''; });
return { node: h('div', { class: 'field-grid' }, fields.map((f) => f.node)), read, clear };
}
// Five channel tiles: a main amount and an optional line under it.
function channelTiles(values, subs = []) {
return h('div', { class: 'channels' }, channels.map((c, i) =>
h('div', { class: `channel${Number(values[i]) ? '' : ' empty-ch'}` },
h('div', { class: 'name' }, swatch(c.key), c.label),
h('div', { class: 'amt' }, c.fmt(values[i])),
subs[i] ? h('div', { class: 'sub', title: subs[i] }, subs[i]) : null)));
}
const kindLabels = {
remove_cell: 'remove cell', grant_reserve: 'grant reserve', add_bubbles: 'add bubbles',
add_pool: 'add to spent pool', release_pool: 'release spent pool', spawn_wildlife: 'spawn wildlife',
adopt_tuning: 'adopt tuning', take_reserve: 'take reserve', remove_wildlife: 'remove all wildlife',
};
// Admin commands (ADR-0182): queued now, applied by the region at its next ticks.
function commandSender(region, onQueued) {
return async (params, label, note, reason) => {
try {
const q = new URLSearchParams(params);
if (reason && reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/regions/${region}/commands?${q}`, true, 'POST');
if (note) { note.className = 'note good'; note.textContent = `Queued #${r.id} (${label}). The region applies it within a few seconds.`; }
if (reason) reason.value = '';
onQueued();
return true;
} catch (e) {
if (note) { note.className = 'note error'; note.textContent = `Could not queue ${label}: ${e.code || e.message}`; }
return false;
}
};
}
// The region's session window (ADR-0087): who may connect, until when. Writes go through the
// admin API as the signed-in admin; the region applies a change within about 5 seconds.
function sessionWindowBlock(region) {
const minutes = h('select', {}, [[30, '30 minutes'], [60, '1 hour'], [120, '2 hours'], [240, '4 hours']]
.map(([m, label]) => h('option', { value: m, selected: m === 240 }, label)));
const reason = reasonInput();
const note = h('div', { class: 'note' });
let busy = false;
const send = async (m) => {
if (busy) return;
if (m === 0 && !confirm(`Close sessions in region ${region}? Connected players are disconnected.`)) return;
busy = true;
try {
const q = new URLSearchParams({ minutes: String(m) });
if (reason.value.trim()) q.set('reason', reason.value.trim());
await api(`/api/regions/${region}/session-window?${q}`, true, 'POST');
reason.value = '';
note.className = 'note good';
note.textContent = 'Saved. The region applies it within about 5 seconds.';
} catch (e) {
note.className = 'note error';
note.textContent = `Could not change the window: ${e.message}`;
} finally {
busy = false;
load();
}
};
const openButton = h('button', { class: 'primary', onclick: () => send(Number(minutes.value)) }, 'Open');
const closeButton = h('button', { class: 'danger', onclick: () => send(0) }, 'Close sessions');
const status = h('div');
const history = h('div');
const badge = h('span', { class: 'badge' }, '…');
async function load() {
try {
const w = await api(`/api/regions/${region}/session-window`);
const current = w.history[0];
openButton.textContent = w.open ? 'Extend' : 'Open';
closeButton.disabled = !w.open;
badge.className = `badge ${w.open ? 'alive' : ''}`;
badge.replaceChildren(w.open ? h('span', { class: 'dot pulse' }) : '', w.open ? 'open' : 'closed');
status.replaceChildren(h('p', { class: 'hint' }, w.open
? `Players may connect until ${fmtTime(current.expires_at)} (closes ${fmtAgo(current.expires_at)}).`
: current && current.expires_at ? `Closed: the last window expired ${fmtAgo(current.expires_at)}.` : 'Closed: no window has been opened yet.'));
history.replaceChildren(w.history.length ? h('div', { class: 'list' }, w.history.slice(0, 8).map((x) =>
h('div', { class: 'list-item' },
h('div', { class: 'grow' }, x.expires_at ? `Opened until ${new Date(x.expires_at * 1000).toLocaleTimeString()}` : 'Closed',
h('div', { class: 'sub', title: x.author || '' }, `${(x.author || '').split(' (')[0]}${x.reason ? ` · ${x.reason}` : ''}`)),
h('span', { class: 'muted small' }, fmtAgo(x.created_at))))) : null);
} catch (e) {
status.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`));
}
}
const node = h('div', {},
block('Session window', badge, status,
h('div', { class: 'form-row' }, minutes, openButton, closeButton),
h('div', { class: 'form-row' }, reason), note),
block('History', null, history));
load();
return { node, load };
}
// Resource schedules (schema 65): a command repeated every N seconds while enabled. The game
// source for bubbles, a steady release of the spent pool, or a wildlife population top-up.
function schedulesBlock(region) {
const list = h('div');
const note = h('div', { class: 'note' });
const kind = h('select', {}, [['add_bubbles', 'Add bubbles'], ['release_pool', 'Release spent pool'], ['spawn_wildlife', 'Spawn wildlife']]
.map(([v, label]) => h('option', { value: v }, label)));
const count = h('input', { type: 'number', min: 1, max: 256, value: 10, class: 'count', title: 'bubbles or cells each time' });
const every = h('input', { type: 'number', min: 1, max: 86400, value: 30, class: 'count', title: 'seconds between runs' });
const amount = amountInputs();
kind.addEventListener('change', () => { amount.node.hidden = kind.value === 'spawn_wildlife'; });
const reason = reasonInput();
const fromSchedule = (x) => ({
id: x.id, kind: x.kind, count: String(x.count), interval: String(x.interval),
energy: x.amount[0], carbon: x.amount[1], nitrogen: x.amount[2], phosphorus: x.amount[3], other: x.amount[4],
});
const save = async (params, label) => {
try {
const q = new URLSearchParams(params);
if (reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/regions/${region}/schedules?${q}`, true, 'POST');
note.className = 'note good';
note.textContent = `Saved schedule #${r.id} (${label}).`;
reason.value = '';
load();
return true;
} catch (e) { note.className = 'note error'; note.textContent = `Could not save: ${e.code || e.message}`; return false; }
};
const add = () => {
let values;
try { values = kind.value === 'spawn_wildlife' ? {} : amount.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
save({ kind: kind.value, count: count.value, interval: every.value, enabled: '1', ...values }, 'new')
.then((ok) => { if (ok) amount.clear(); });
};
async function load() {
try {
const data = await api(`/api/regions/${region}/schedules`);
list.replaceChildren(data.schedules.length ? h('div', { class: 'list' }, data.schedules.map((x) =>
h('div', { class: 'list-item' },
h('span', { class: 'mono faint' }, `#${x.id}`),
h('div', { class: 'grow' }, `${kindLabels[x.kind] || x.kind} ×${x.count} every ${fmtDuration(x.interval)}`,
x.kind !== 'spawn_wildlife' ? h('div', { class: 'sub' }, `each: ${x.amount.map((v, i) => (Number(v) ? fmtChannel(i, v) : null)).filter(Boolean).join(' · ') || 'nothing'}`) : null),
x.enabled ? h('span', { class: 'badge alive' }, `on · ${fmtInt(x.runs)} runs`) : h('span', { class: 'badge' }, 'off'),
h('button', { onclick: () => save({ ...fromSchedule(x), enabled: x.enabled ? '0' : '1' }, x.enabled ? 'stopped' : 'started') }, x.enabled ? 'Stop' : 'Start'))))
: h('p', { class: 'hint' }, 'No schedules. A schedule repeats a command while it is on.'));
} catch (e) { list.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`)); }
}
const node = block('Resource schedules', null, list,
h('div', { class: 'action' },
h('div', { class: 'form-row' }, h('div', { class: 'field grow' }, h('label', {}, 'Repeat'), kind),
h('div', { class: 'field' }, h('label', {}, 'Count'), count),
h('div', { class: 'field' }, h('label', {}, 'Every (s)'), every)),
h('div', { class: 'form-row' }, amount.node),
h('div', { class: 'form-row' }, reason, h('button', { onclick: add }, 'Add schedule')), note));
load();
return { node, load };
}
// ---------- Tuning text (the Git `key = value` format) ----------
// Groups by the key's first part; a group's description is the comment block before its first
// key, a later key's `lead` the comment block just above it, and its note its trailing comment.
// tuning.version (the format) is left out.
function parseTuning(text) {
const groups = new Map();
let comments = [];
for (const raw of (text || '').split('\n')) {
const line = raw.trim();
if (!line) { comments = []; continue; }
if (line.startsWith('#')) { comments.push(line.replace(/^#\s?/, '')); continue; }
const m = /^([A-Za-z0-9_.]+)\s*=\s*([^#]*?)\s*(?:#\s*(.*))?$/.exec(line);
if (!m) continue;
const name = m[1].split('.')[0];
if (m[1] === 'tuning.version') { comments = []; continue; }
const fresh = !groups.has(name);
if (fresh) groups.set(name, { name, about: comments.join(' '), settings: [] });
groups.get(name).settings.push({ key: m[1], value: m[2], note: m[3] || '', lead: fresh ? '' : comments.join(' ') });
comments = [];
}
return [...groups.values()];
}
// A readable gloss of a raw value from its key's unit suffix.
function gloss(key, value) {
const n = Number(String(value).replace(/_/g, ''));
if (!Number.isFinite(n)) return '';
if (/_pj$|_e_pj$/.test(key)) return fmtEnergy(n);
if (/_fg$/.test(key)) return fmtMass(n);
if (/_ticks$/.test(key)) return `${(n * tickSeconds).toLocaleString(undefined, { maximumFractionDigits: 2 })} s`;
if (/_ms$/.test(key)) return fmtDuration(n / 1000);
if (/_um$/.test(key)) return fmtLength(n);
if (/_mk$/.test(key)) return `${((n - 273150) / 1000).toLocaleString(undefined, { maximumFractionDigits: 1 })} °C`;
if (/per_mille$/.test(key) && !/per_point|per_k$/.test(key)) return `${(n / 10).toLocaleString()}%`;
if (/_ppm$/.test(key)) return `${(n / 10000).toLocaleString()}%`;
return '';
}
// The settings as collapsible groups, filtered by `query`; values differing from `compare`
// (a key → value map) are marked.
function settingsView(text, { query = '', compare = null, open = true } = {}) {
const q = query.trim().toLowerCase();
const groups = parseTuning(text).map((g) => ({
...g, settings: g.settings.filter((s) => !q || s.key.toLowerCase().includes(q) || s.note.toLowerCase().includes(q)),
})).filter((g) => g.settings.length);
if (!groups.length) return h('p', { class: 'hint' }, q ? 'No setting matches.' : 'No settings.');
return h('div', {}, groups.map((g) => h('details', { class: 'settings-group', open: open || !!q },
h('summary', {}, h('span', { class: 'label' }, g.name), h('span', { class: 'badge' }, g.settings.length)),
g.about ? h('p', { class: 'hint', style: { margin: '8px 0 4px 16px' } }, g.about) : null,
g.settings.map((s) => {
const before = compare ? compare.get(s.key) : undefined;
const changed = compare && before !== undefined && before !== s.value;
const added = compare && before === undefined;
const extra = gloss(s.key, s.value);
return h('div', { class: `setting${changed || added ? ' changed' : ''}`, title: changed ? `baseline: ${before}` : added ? 'not in the baseline' : '' },
h('span', { class: 'key' }, s.key.slice(g.name.length + 1) || s.key),
h('span', { class: 'val' }, s.value.replace(/_/g, ','), extra ? h('span', { class: 'muted', style: { fontWeight: 400 } }, ` ${extra}`) : null),
s.note || changed ? h('span', { class: 'why' }, [s.note, changed ? `baseline ${before.replace(/_/g, ',')}` : ''].filter(Boolean).join(' · ')) : null);
}))));
}
const tuningMap = (text) => new Map(parseTuning(text).flatMap((g) => g.settings.map((s) => [s.key, s.value])));
// ---------- Region list ----------
async function regionsPage() {
const data = await api('/api/regions');
const opener = h('div', { class: 'card', style: { marginTop: '18px' } }, h('p', { class: 'hint' }, 'Loading…'));
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Regions'), h('div', { class: 'subtitle' }, `World ${data.world}`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
table([
{ key: 'region', label: 'Region', sort: (r) => Number(r.region) },
{ key: 'frame', label: 'Frame' },
{ key: 'lease_held', label: 'Lease', render: (r) => (r.lease_held ? h('span', { class: 'badge alive' }, `held · epoch ${r.lease_epoch}`) : h('span', { class: 'muted' }, 'free')) },
{ key: 'lease_expires', label: 'Lease expires', render: (r) => fmtAgo(r.lease_expires) },
{ key: 'tick', label: 'Head tick', num: true, render: (r) => fmtInt(r.tick), sort: (r) => Number(r.tick ?? -1) },
{ key: 'sequence', label: 'Commits', num: true, render: (r) => fmtInt(r.sequence), sort: (r) => Number(r.sequence ?? -1) },
{ key: 'committed_at', label: 'Last commit', render: (r) => fmtAgo(r.committed_at), sort: (r) => r.committed_at ?? 0 },
{ key: 'build', label: 'Build', render: (r) => h('span', { class: 'mono', title: r.build || '' }, r.build ? r.build.slice(0, 12) : '—') },
{ key: 'window_open', label: 'Sessions', render: windowBadge, sort: (r) => (r.window_open ? r.window_expires : 0) },
{ key: 'viewable', label: '', render: (r) => (r.viewable ? h('a', { href: `#/regions/${r.region}` }, 'Open view →') : h('span', { class: 'muted' }, 'no view')) },
], data.regions, { sortKey: 'region', onRow: (r) => { if (r.viewable) location.hash = `#/regions/${r.region}`; } }),
opener);
openRegionCard(opener);
}
// ADR-0182 section 15: open a fresh region in place of the one DEV serves (one Git commit,
// then a full Argo sync). The progress survives this tab reloading while the portal restarts.
function argoBadges(argo) {
if (!argo || argo.error) return h('span', { class: 'badge warn' }, `Argo unavailable${argo && argo.error ? `: ${argo.error}` : ''}`);
const tone = (v, good) => (v === good ? 'alive' : v ? 'warn' : '');
return h('span', {},
h('span', { class: `badge ${tone(argo.phase, 'Succeeded')}`, title: argo.message || '' }, argo.phase || 'no operation'), ' ',
h('span', { class: `badge ${tone(argo.sync, 'Synced')}` }, argo.sync || 'sync ?'), ' ',
h('span', { class: `badge ${tone(argo.health, 'Healthy')}` }, argo.health || 'health ?'));
}
async function openRegionCard(card) {
const progressKey = 'deploy-progress';
const saved = (() => { try { return JSON.parse(sessionStorage.getItem(progressKey) || 'null'); } catch { return null; } })();
if (saved && Date.now() - saved.at < 20 * 60 * 1000) return followOpening(card, saved, progressKey);
let status;
try { status = await api('/api/deploy'); } catch (e) { fill(card, h('h2', {}, 'Open a new region'), h('p', { class: 'error' }, `Unavailable: ${e.code || e.message}`)); return; }
if (!status.configured) {
fill(card, h('h2', {}, 'Open a new region'),
h('p', { class: 'hint' }, 'Not configured: the admin API needs Secret aevolution-admin (Gitea and Argo CD settings and tokens) mounted at /run/deploy.'));
return;
}
const problem = status.git && status.git.error ? `Git: ${status.git.error}` : status.layout_error ? `The region files changed shape (${status.layout_error}); edit them by hand.`
: status.world_mismatch ? 'Git serves another world than this portal.' : !status.next ? 'The next region number is unavailable.' : '';
const running = status.argo && status.argo.phase === 'Running';
const reason = reasonInput();
const confirmBox = h('input', { type: 'text', placeholder: status.next ? `Type ${status.next.region} to confirm` : '', class: 'count', style: { width: '170px' } });
const note = h('div', { class: 'note' });
const go = h('button', { class: 'primary', disabled: true }, status.next ? `Open region ${status.next.region}` : 'Open region');
const ready = () => { go.disabled = !!problem || running || !status.next || confirmBox.value.trim() !== status.next.region; };
confirmBox.addEventListener('input', ready);
go.addEventListener('click', async () => {
go.disabled = true;
try {
const q = new URLSearchParams({ region: status.next.region });
if (reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/deploy/region?${q}`, true, 'POST');
const progress = { region: r.region, from: r.from, commit: r.commit, synced: r.sync_started, at: Date.now() };
try { sessionStorage.setItem(progressKey, JSON.stringify(progress)); } catch { /* private mode */ }
followOpening(card, progress, progressKey);
} catch (e) {
note.className = 'note error';
const d = e.detail || {};
note.textContent = {
sync_running: 'An Argo sync is already running; try again when it finishes.',
region_changed: `The next region is now ${d.expected}: reload.`,
layout_changed: `The region files changed shape (${d.detail}).`,
commit_refused: `Gitea refused the commit (HTTP ${d.status}); someone may have changed these files. Reload.`,
gitea_unavailable: `Gitea is unreachable (${d.detail}).`,
argo_unavailable: `Argo CD is unreachable (${d.detail}).`,
}[e.code] || `Could not open the region: ${e.code || e.message}`;
ready();
}
});
const c = status.current || {}, n = status.next || {};
const last = n.wildlife_count ? String(BigInt(n.wildlife_first) + BigInt(n.wildlife_count) - 1n) : '';
fill(card,
h('div', { class: 'card-head' }, h('h2', {}, 'Open a new region'), argoBadges(status.argo)),
h('p', { class: 'hint' }, `Opens a fresh region in world ${c.world || '?'} and serves it in place of region ${c.region || '?'}. `,
'The portal commits the change to Git (region values, grant broker and portal) and runs a full Argo sync: the provision hook opens the region first, then the region host, broker and this portal restart. ',
'The current region stays in the stores but is no longer served.'),
h('dl', { class: 'facts' },
h('dt', {}, 'Serving now'), h('dd', {}, c.region ? `region ${c.region}` : '—'),
h('dt', {}, 'Opens'), h('dd', {}, n.region ? h('strong', {}, `region ${n.region}`) : '—'),
h('dt', {}, 'Seeded wildlife'), h('dd', { class: 'mono' }, n.wildlife_count ? `${n.wildlife_count} cells, ids ${n.wildlife_first}–${last}` : 'none'),
h('dt', {}, 'Rules'), h('dd', {}, 'the Git baseline tuning files; adopt a revision afterwards to change them'),
h('dt', {}, 'Repository'), h('dd', { class: 'mono' }, `${status.repository} @ ${status.branch}${status.git && status.git.head ? ` (${status.git.head.slice(0, 8)})` : ''}`),
h('dt', {}, 'Application'), h('dd', { class: 'mono' }, status.application)),
problem ? h('div', { class: 'callout', style: { marginTop: '12px' } }, problem) : null,
running ? h('div', { class: 'callout', style: { marginTop: '12px' } }, 'An Argo sync is running; wait for it to finish.') : null,
h('div', { class: 'form-row' }, reason, confirmBox, go), note);
ready();
}
async function followOpening(card, progress, progressKey) {
const steps = h('div', { class: 'list' });
const step = (done, text, sub) => h('div', { class: 'list-item' },
h('span', { class: `badge ${done === true ? 'alive' : done === false ? 'warn' : ''}` }, done === true ? 'done' : done === false ? 'waiting' : '…'),
h('div', { class: 'grow' }, text, sub ? h('div', { class: 'sub' }, sub) : null));
const finish = h('div', { class: 'form-row' });
fill(card, h('div', { class: 'card-head' }, h('h2', {}, `Opening region ${progress.region}`), h('span', { class: 'muted small' }, `from region ${progress.from}`)), steps, finish);
let stopped = false;
const previous = stopPage;
stopPage = () => { stopped = true; previous(); };
const clear = () => { try { sessionStorage.removeItem(progressKey); } catch { /* */ } };
for (;;) {
if (stopped) return;
let argo = null, regions = null, restarting = false;
try { argo = (await api('/api/deploy?argo=1')).argo; } catch { restarting = true; }
try { regions = await api('/api/regions'); } catch { restarting = true; }
const target = regions && regions.regions.find((r) => String(r.region) === String(progress.region));
const synced = argo && !argo.error && argo.revision === progress.commit && argo.phase === 'Succeeded';
const live = target && target.lease_held && target.viewable;
fill(steps,
step(true, `Committed to Git`, h('span', { class: 'mono' }, progress.commit.slice(0, 12))),
step(progress.synced ? (synced ? true : false) : false, progress.synced ? 'Full Argo sync of that commit' : 'Argo did not accept the sync request: start a full sync of the commit by hand',
argo && !argo.error ? `${argo.phase || 'no operation'} · ${argo.sync} · ${argo.health}${argo.message ? ` · ${argo.message}` : ''}` : restarting ? 'the admin portal is restarting with the new region…' : ''),
step(live ? true : false, `Region ${progress.region} provisioned and running`, target ? (target.lease_held ? `lease held · tick ${fmtInt(target.tick)}` : 'provisioned, waiting for the region host') : 'not provisioned yet'));
if (live) {
clear();
fill(finish,
h('a', { href: `#/regions/${progress.region}` }, h('button', { class: 'primary' }, `Open region ${progress.region} →`)),
h('span', { class: 'hint', style: { margin: 0 } }, 'Players can join once a session window is open (region page, Access tab).'));
return;
}
if (Date.now() - progress.at > 20 * 60 * 1000) {
clear();
fill(finish, h('div', { class: 'callout' }, 'Still not live after 20 minutes: check the Argo Application and the provision job.'));
return;
}
await new Promise((resolve) => setTimeout(resolve, 3000));
}
}
function windowBadge(r) {
return r.window_open ? h('span', { class: 'badge alive', title: fmtTime(r.window_expires) }, `open · closes ${fmtAgo(r.window_expires)}`)
: h('span', { class: 'badge' }, 'closed');
}
// ---------- Region view ----------
// Where a region's stock sits: the server's complete totals, or (an older server) sums over the
// listed cells and deposits.
function regionLedger(view) {
const zero = () => [0, 0, 0, 0, 0];
// Heat: energy the cells used that has not (yet) returned to the spent pool.
const heat = view.heat === undefined ? null : [Number(view.heat), 0, 0, 0, 0];
if (view.totals) {
const t = view.totals;
return { complete: true, reserve: t.reserve, body: t.body, bubbles: t.bubbles, pools: t.pools, patches: t.patches, spent: view.spent, heat };
}
const reserve = zero(), bubbles = zero(), pools = zero(), patches = zero();
for (const c of view.cells) addTo(reserve, c.reserve);
for (const d of view.deps) addTo(d.kind === 2 ? bubbles : d.kind === 1 ? pools : patches, d.stock);
return { complete: false, reserve, body: null, bubbles, pools, patches, spent: view.spent, heat };
}
// The rules-13 drip: every `interval` ticks, one bubble per non-empty channel of at most the cap;
// the energy cycle (ADR-0182 section 14): heat recycled per mille each tick, absorbing drip.
function dripPlan(view) {
if (!view.drip) return null;
const [interval, capE, capM, recycle = 0, absorb = 0] = view.drip.map(Number);
const caps = [capE, capM, capM, capM, capM];
const spent = view.spent.map(Number);
return {
interval, caps, recycle, absorb: absorb === 1,
next: spent.map((v, i) => Math.min(v, caps[i])),
drips: spent.map((v, i) => (caps[i] ? Math.ceil(v / caps[i]) : 0)),
};
}
async function regionPage(region, params) {
const highlight = params.get('account') || '';
const send = commandSender(region, () => commands.load());
let view = null, selected = null, timer = null, frame = 0, beats = 0;
let zoom = 1, panX = 0, panY = 0, drag = null;
// Cells marked for a bulk removal (shift+click toggles, shift+drag adds a box of them).
const marked = new Set();
let box = null;
// Tick pace: the last ticks seen and when the tick last moved.
const pace = { samples: [], movedAt: performance.now(), lastTick: null, fetchedAt: 0 };
const layers = { players: true, online: true, wildlife: true, pools: true, patches: true, energy: true, carbon: true, nitrogen: true, phosphorus: true, other: true };
// ----- Header and KPIs -----
const titleBadges = h('div', { class: 'title-row' });
const subtitle = h('div', { class: 'subtitle' }, 'Loading…');
const live = h('input', { type: 'checkbox', checked: true });
const kpi = (label) => {
const value = h('div', { class: 'value' }, '—'), sub = h('div', { class: 'sub' }), meter = h('div', { class: 'meter', hidden: true }, h('span'));
const node = h('div', { class: 'kpi' }, h('div', { class: 'label' }, label), value, sub, meter);
return {
node, meter,
set(v, s, cls = '', fill = null, meterCls = '') {
value.textContent = v; sub.textContent = s || ''; node.className = `kpi ${cls}`.trim();
meter.hidden = fill === null;
if (fill !== null) { meter.className = `meter ${meterCls}`.trim(); meter.firstChild.style.width = `${Math.max(0, Math.min(100, fill * 100))}%`; }
},
};
};
const k = {
tick: kpi('Tick'), cells: kpi('Population'), deposits: kpi('Deposit capacity'), energy: kpi('Region energy'),
matter: kpi('Region matter'), spent: kpi('Spent pool'), drip: kpi('Next drip'),
};
k.drip.meter.classList.add('smooth');
// ----- Map -----
const canvas = h('canvas');
const tip = h('div', { class: 'tooltip glass', hidden: true });
const banner = h('div', { class: 'map-banner glass', hidden: true });
const scaleLabel = h('div'), scaleRule = h('div', { class: 'rule' });
const chipRow = h('div', { class: 'map-layers' });
const chips = {};
const chip = (key, cls, label) => {
const count = h('span', { class: 'count' });
const node = h('label', { class: 'chip', title: `Show or hide ${label.toLowerCase()}` }, swatch(cls), label, count);
node.addEventListener('click', (e) => { e.preventDefault(); layers[key] = !layers[key]; node.classList.toggle('off', !layers[key]); paint(); });
chips[key] = { node, count };
return node;
};
chipRow.append(chip('players', 'player', 'Players'), chip('online', 'online', 'Connected'), chip('wildlife', 'wildlife', 'Wildlife'),
chip('pools', 'pool', 'Pools'), chip('patches', 'patch', 'Patches'),
...channels.map((c) => chip(c.key, c.key, `${c.label} bubbles`)));
const zoomBy = (factor) => { setZoom(zoom * factor, 0, 0); };
const markCount = h('span');
const markNote = h('span', { class: 'muted small' });
const markBar = h('div', { class: 'mark-bar glass', hidden: true }, markCount,
h('button', { class: 'danger', onclick: () => removeMarked() }, 'Remove'),
h('button', { class: 'ghost', onclick: () => { marked.clear(); drawMarks(); paint(); } }, 'Clear'), markNote);
const mapCard = h('div', { class: 'map-card' },
h('div', { class: 'map-toolbar' }, chipRow,
h('div', { class: 'map-zoom' },
h('button', { title: 'Zoom in', onclick: () => zoomBy(1.6) }, '+'),
h('button', { title: 'Zoom out', onclick: () => zoomBy(1 / 1.6) }, '−'),
h('button', { title: 'Fit the region', onclick: () => { zoom = 1; panX = 0; panY = 0; paint(); } }, '⤢'))),
h('div', { class: 'map-stage' }, canvas, banner, markBar,
h('div', { class: 'map-foot' },
h('div', { class: 'map-hint glass' }, 'Click to inspect · shift+click or shift+drag to mark cells · scroll to zoom · drag to pan'),
h('div', { class: 'scale glass' }, scaleLabel, scaleRule)),
tip));
// ----- Side panel: tabs -----
const tabNames = [['inspect', 'Inspect'], ['resources', 'Resources'], ['actions', 'Actions'], ['tuning', 'Tuning'], ['access', 'Access']];
let tab = (() => { try { return localStorage.getItem('region-tab') || 'resources'; } catch { return 'resources'; } })();
const tabButtons = {}, tabBodies = {};
const actionsBadge = h('span', { class: 'tab-badge', hidden: true });
for (const [key, label] of tabNames) {
tabButtons[key] = h('button', { role: 'tab', onclick: () => openTab(key) }, label, key === 'actions' ? actionsBadge : null);
tabBodies[key] = h('div', { hidden: true });
}
const panelBody = h('div', { class: 'panel-body' }, Object.values(tabBodies));
function openTab(key) {
tab = key;
try { localStorage.setItem('region-tab', key); } catch { /* private mode */ }
for (const [name] of tabNames) { tabButtons[name].classList.toggle('on', name === key); tabBodies[name].hidden = name !== key; }
if (key === 'tuning') tuning.load();
}
// Inspect: the selected cell or deposit, else the region's player cells.
const inspect = h('div');
tabBodies.inspect.append(inspect);
let inspectFacts = null, inspectKey = null, goneText = '';
// Resources: the ledger, the spent pool and its drip, and pool actions.
const ledgerBox = h('div');
const dripBox = h('div');
const dripCountdown = h('span', { class: 'drip-count' }, '—');
const dripMeter = h('div', { class: 'meter smooth', style: { marginTop: '8px' } }, h('span'));
const dripEvery = h('span', { class: 'muted small' });
const poolAmount = amountInputs(), poolReason = reasonInput(), poolNote = h('div', { class: 'note' });
const releaseAmount = amountInputs(), releaseReason = reasonInput(), releaseNote = h('div', { class: 'note' });
const releaseCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' });
const withAmount = (amount, extra, label, note, reason) => {
let values;
try { values = amount.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
send({ ...extra, ...values }, label, note, reason).then((ok) => { if (ok) amount.clear(); });
};
tabBodies.resources.append(
block('Where the resources are', h('span', { class: 'muted' }, 'everything in the region'), ledgerBox),
block('Spent pool and drip', dripEvery,
h('div', { class: 'drip-card' },
h('div', { class: 'drip-top' }, h('span', { class: 'muted small' }, 'Next drip'), dripCountdown),
dripMeter, dripBox)),
block('Add to the spent pool', null,
h('p', { class: 'hint' }, 'The spent pool is the region\'s single reserve of dead and spent matter. It has no place on the map: the drip returns it as bubbles at random spots.'),
poolAmount.node,
h('div', { class: 'form-row' }, poolReason, h('button', { onclick: () => withAmount(poolAmount, { kind: 'add_pool' }, 'add to spent pool', poolNote, poolReason) }, 'Add to pool')),
poolNote),
block('Release the spent pool now', null,
h('p', { class: 'hint' }, 'Takes these amounts from the spent pool at once, as bubbles at random spots.'),
releaseAmount.node,
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Bubbles'), releaseCount), releaseReason,
h('button', { onclick: () => withAmount(releaseAmount, { kind: 'release_pool', count: releaseCount.value }, 'release spent pool', releaseNote, releaseReason) }, 'Release')),
releaseNote));
// Actions: wildlife, bubbles, schedules and the command log.
const spawnCount = h('input', { type: 'number', min: 1, max: 256, value: 10, class: 'count' });
const spawnReason = reasonInput(), spawnNote = h('div', { class: 'note' });
const bubbleCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' });
const bubbleAmount = amountInputs(), bubbleReason = reasonInput(), bubbleNote = h('div', { class: 'note' });
const commandLog = h('div');
const commands = {
async load() {
try {
const data = await api(`/api/regions/${region}/commands`);
const pending = data.commands.filter((c) => !c.applied_tick).length;
actionsBadge.hidden = !pending;
actionsBadge.textContent = `${pending}`;
commandLog.replaceChildren(data.commands.length ? h('div', { class: 'list' }, data.commands.slice(0, 12).map((c) =>
h('div', { class: 'list-item' },
h('span', { class: 'mono faint' }, `#${c.id}`),
h('div', { class: 'grow' }, kindLabels[c.kind] || c.kind, c.count ? ` ×${c.count}` : '',
['remove_cell', 'grant_reserve', 'take_reserve'].includes(c.kind) ? h('span', { class: 'mono muted' }, ` ${c.target}`) : '',
c.kind === 'adopt_tuning' ? ` revision ${c.target}` : '',
h('div', { class: 'sub', title: c.author || '' }, (c.author || '').split(' (')[0])),
c.applied_tick ? h('span', { class: 'badge alive' }, `tick ${fmtInt(c.applied_tick)}`) : h('span', { class: 'badge warn' }, 'pending'))))
: h('p', { class: 'hint' }, 'No commands yet.'));
} catch (e) { commandLog.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`)); }
},
};
const schedules = schedulesBlock(region);
const cullReason = reasonInput(), cullNote = h('div', { class: 'note' });
const cull = () => {
const wild = view ? view.cells.filter((c) => c.flags & 1).length : 0;
if (!confirm(`Remove all ${fmtInt(wild)} wildlife cells? Their bodies and reserves go to the spent pool.`)) return;
send({ kind: 'remove_wildlife' }, 'remove all wildlife', cullNote, cullReason);
};
tabBodies.actions.append(
block('Remove wildlife', null,
h('p', { class: 'hint' }, 'Every wildlife cell at once, in one command; bodies and reserves go to the spent pool. To remove some, shift+click or shift+drag them on the map.'),
h('div', { class: 'form-row' }, cullReason, h('button', { class: 'danger', onclick: cull }, 'Remove all wildlife')),
cullNote),
block('Spawn wildlife', null,
h('p', { class: 'hint' }, 'Founder wildlife at random spots, funded like any birth.'),
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Cells'), spawnCount), spawnReason,
h('button', { onclick: () => send({ kind: 'spawn_wildlife', count: spawnCount.value }, 'spawn wildlife', spawnNote, spawnReason) }, 'Spawn')),
spawnNote),
block('Add bubbles', null,
h('p', { class: 'hint' }, 'New stock from outside the region, split evenly over the bubbles.'),
bubbleAmount.node,
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Bubbles'), bubbleCount), bubbleReason,
h('button', { onclick: () => withAmount(bubbleAmount, { kind: 'add_bubbles', count: bubbleCount.value }, 'add bubbles', bubbleNote, bubbleReason) }, 'Add')),
bubbleNote),
schedules.node,
block('Recent commands', null, commandLog));
// Tuning: what the region runs now.
const tuning = (() => {
const search = h('input', { type: 'search', placeholder: 'Filter settings', class: 'wide' });
const head = h('div');
const live_ = h('div');
const file = h('div');
let data = null, runningText = null, loadedAt = 0, running = null, tried = false;
const texts = new Map();
const draw = () => {
if (!data) return;
const baseline = data.baseline ? tuningMap(data.baseline.text) : null;
live_.replaceChildren(runningText ? settingsView(runningText, { query: search.value, compare: running && running.revision ? baseline : null })
: h('p', { class: 'hint' }, view && view.rules_sha256 ? 'This region runs rules that match neither the baseline file nor a stored revision, so their text is not available here.' : 'Live tuning applies to rules-13 regions only.'));
file.replaceChildren(data.region_file ? settingsView(data.region_file, { query: search.value, open: !!search.value.trim() })
: h('p', { class: 'hint' }, 'The admin API was started without the region tuning file.'));
};
search.addEventListener('input', draw);
async function load(force = false) {
tried = true;
try {
if (force || !data || performance.now() - loadedAt > 30000) { data = await api('/api/tuning'); loadedAt = performance.now(); }
const digest = view && view.rules_sha256;
const rev = digest ? data.revisions.find((r) => r.rules_sha256 === digest) : null;
running = rev ? { revision: rev.revision, label: `Revision #${rev.revision}`, about: rev.reason }
: digest && data.baseline && data.baseline.rules_sha256 === digest ? { revision: 0, label: 'Baseline file', about: 'the revamp file the region opened with' }
: digest ? { revision: null, label: `Unknown rules ${digest.slice(0, 8)}…` } : null;
if (rev) {
if (!texts.has(rev.revision)) texts.set(rev.revision, data.newest && data.newest.revision === rev.revision ? data.newest.text : (await api(`/api/tuning/${rev.revision}`)).text);
runningText = texts.get(rev.revision);
} else runningText = running && running.revision === 0 ? data.baseline.text : null;
head.replaceChildren(h('div', { class: 'block-head' },
h('div', {}, running ? h('span', { class: `badge ${running.revision === null ? 'warn' : 'alive'}` }, running.label) : h('span', { class: 'badge' }, `rules ${view ? view.rules : '—'}`),
running && running.about ? h('div', { class: 'hint', style: { margin: '6px 0 0' } }, running.about) : null),
h('a', { href: '#/tuning' }, 'Open the editor →')));
draw();
return running;
} catch (e) {
head.replaceChildren(h('p', { class: 'error' }, `Tuning unavailable: ${e.code || e.message}`));
return null;
}
}
tabBodies.tuning.append(
h('div', { class: 'block' }, head, search),
block('Live rules', h('span', { class: 'muted' }, 'rules 13 · adopt changes in the editor'), live_),
block('Region file', h('span', { class: 'muted' }, 'read at restart · shape at opening'), file));
return { load, get running() { return running; }, get tried() { return tried; } };
})();
const sessions = sessionWindowBlock(region);
tabBodies.access.append(sessions.node);
show(
h('div', { class: 'head' },
h('div', {}, h('a', { class: 'crumb', href: '#/regions' }, '← Regions'),
h('div', { class: 'title-row' }, h('h1', {}, `Region ${region}`), titleBadges), subtitle),
h('div', { class: 'tools' }, h('label', { class: 'chip glass', title: 'Refresh every second' }, live, 'Live'),
h('button', { onclick: () => load() }, 'Refresh'))),
h('div', { class: 'kpis' }, Object.values(k).map((x) => x.node)),
h('div', { class: 'region-grid' }, mapCard,
h('div', { class: 'panel' }, h('div', { class: 'tabs', role: 'tablist' }, Object.values(tabButtons)), panelBody)));
openTab(tab);
// ----- Map drawing -----
const cellObj = (c) => ({
life: c[0], organism: c[1], account: c[2], x: c[3], y: c[4], extent: c[5], flags: c[6], members: c[7],
reserve: c.slice(8, 13), bodyMass: c[13], root: c[14],
});
const depObj = (d) => {
// Energy counts in pJ, matter in fg; ~17 pJ per fg of food, so compare on that scale.
const stock = d.slice(5, 10);
const weights = [stock[0] / 17, stock[1], stock[2], stock[3], stock[4]];
return { id: d[0], kind: d[1], x: d[2], y: d[3], r: d[4], stock, top: weights.indexOf(Math.max(...weights)) };
};
const cellLayer = (c) => (c.flags & 1 ? 'wildlife' : c.flags & 2 ? 'online' : 'players');
const depLayer = (d) => (d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pools' : 'patches');
function geometry() {
// The backing store follows the laid-out size (the canvas is absolutely placed, so its own
// size never feeds back into the layout), at most 2x and 4,096 pixels a side.
const rect = canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2, 4096 / Math.max(1, rect.width, rect.height));
const w = Math.max(1, Math.round(rect.width * dpr)), hgt = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== w || canvas.height !== hgt) { canvas.width = w; canvas.height = hgt; }
const [aw, ah] = view ? view.area : [1, 1];
const base = Math.min(w / aw, hgt / ah) * 0.94;
const s = base * zoom;
const ox = (w - aw * s) / 2 + panX * dpr, oy = (hgt - ah * s) / 2 + panY * dpr;
// World y grows upward; the canvas grows downward.
return { dpr, s, w, hgt, toX: (x) => ox + x * s, toY: (y) => oy + (ah - y) * s, fromX: (px) => (px - ox) / s, fromY: (py) => ah - (py - oy) / s };
}
function setZoom(next, mx, my) {
next = Math.min(96, Math.max(1, next));
const kz = next / zoom;
panX = mx - (mx - panX) * kz; panY = my - (my - panY) * kz;
zoom = next;
if (zoom === 1) { panX = 0; panY = 0; }
paint();
}
function centerOn(x, y) {
if (!view) return;
zoom = Math.max(zoom, 8);
const g = geometry();
panX = (view.area[0] / 2 - x) * g.s / g.dpr;
panY = (y - view.area[1] / 2) * g.s / g.dpr;
paint();
}
const niceLength = (um) => {
const p = 10 ** Math.floor(Math.log10(um));
return [5, 2, 1].map((m) => m * p).find((v) => v <= um) || p;
};
function paint() {
const g = geometry();
const ctx = canvas.getContext('2d');
if (!ctx) return; // The browser refused a context (lost or out of memory).
ctx.fillStyle = css('map-bg');
ctx.fillRect(0, 0, g.w, g.hgt);
if (!view) return;
const [aw, ah] = view.area;
// Grid lines at a round spacing at least ~60 px apart, then the region's edge.
const step = niceLength(Math.max(1, (60 * g.dpr) / g.s) * 2.2);
ctx.strokeStyle = css('map-grid');
ctx.lineWidth = g.dpr;
ctx.beginPath();
for (let x = step; x < aw; x += step) { ctx.moveTo(g.toX(x), g.toY(0)); ctx.lineTo(g.toX(x), g.toY(ah)); }
for (let y = step; y < ah; y += step) { ctx.moveTo(g.toX(0), g.toY(y)); ctx.lineTo(g.toX(aw), g.toY(y)); }
ctx.stroke();
ctx.strokeStyle = css('map-edge');
ctx.lineWidth = 1.5 * g.dpr;
ctx.strokeRect(g.toX(0), g.toY(ah), aw * g.s, ah * g.s);
const ring = (x, y, r) => {
ctx.strokeStyle = css('select'); ctx.lineWidth = 2 * g.dpr;
ctx.beginPath(); ctx.arc(x, y, r + 4 * g.dpr, 0, Math.PI * 2); ctx.stroke();
};
const poolFill = css('pool'), poolEdge = css('pool-edge'), patchFill = css('patch');
for (const d of view.deps) {
if (d.kind === 2 || !layers[depLayer(d)]) continue;
ctx.fillStyle = d.kind === 1 ? poolFill : patchFill;
ctx.strokeStyle = poolEdge; ctx.lineWidth = g.dpr;
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 3 * g.dpr), 0, Math.PI * 2); ctx.fill();
if (d.kind === 1) ctx.stroke();
}
const colors = channelNames.map(css);
for (const d of view.deps) {
if (d.kind !== 2 || !layers[channelNames[d.top]]) continue;
ctx.fillStyle = colors[d.top];
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 1.6 * g.dpr), 0, Math.PI * 2); ctx.fill();
}
if (selected && selected.dep) {
const d = selected.dep;
ring(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 2 * g.dpr));
}
const fills = { wildlife: css('wildlife'), online: css('online'), players: css('player') };
for (const c of view.cells) {
const layer = cellLayer(c);
if (!layers[layer]) continue;
const faded = (c.flags & 12) !== 0;
const size = Math.max(c.extent * g.s, 4 * g.dpr);
const x = g.toX(c.x + c.extent / 2), y = g.toY(c.y + c.extent / 2);
ctx.globalAlpha = faded ? 0.4 : 0.95;
ctx.fillStyle = fills[layer];
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1;
if ((highlight && c.account === highlight) || (selected && selected.cell && selected.cell.life === c.life)) ring(x, y, size / 2);
if (marked.has(c.life)) {
ctx.strokeStyle = css('bad'); ctx.lineWidth = 2 * g.dpr;
ctx.beginPath(); ctx.arc(x, y, size / 2 + 2 * g.dpr, 0, Math.PI * 2); ctx.stroke();
}
}
if (box) {
ctx.strokeStyle = css('bad'); ctx.lineWidth = g.dpr; ctx.setLineDash([5 * g.dpr, 4 * g.dpr]);
ctx.strokeRect(box.x0 * g.dpr, box.y0 * g.dpr, (box.x1 - box.x0) * g.dpr, (box.y1 - box.y0) * g.dpr);
ctx.setLineDash([]);
}
// Scale bar: a round length about 90 px long.
const len = niceLength((90 * g.dpr) / g.s);
scaleLabel.textContent = fmtLength(len);
scaleRule.style.width = `${(len * g.s) / g.dpr}px`;
}
function hit(px, py) {
if (!view) return null;
const g = geometry();
const wx = g.fromX(px * g.dpr), wy = g.fromY(py * g.dpr);
const slack = (5 * g.dpr) / g.s;
for (const c of view.cells) {
if (!layers[cellLayer(c)]) continue;
if (wx >= c.x - slack && wx <= c.x + c.extent + slack && wy >= c.y - slack && wy <= c.y + c.extent + slack) return { cell: c };
}
// Bubbles before pools: a pool is large and would hide the bubbles over it.
let best = null, bestD = Infinity;
for (const d of view.deps) {
if (!layers[depLayer(d)]) continue;
const r = Math.max(d.kind === 2 ? d.r : 0, slack);
const dist = (wx - d.x) ** 2 + (wy - d.y) ** 2;
if (d.kind === 2 && dist <= r * r && dist < bestD) { best = d; bestD = dist; }
}
if (best) return { dep: best };
for (const d of view.deps) {
if (d.kind === 2 || !layers[depLayer(d)]) continue;
const r = Math.max(d.r, slack);
if ((wx - d.x) ** 2 + (wy - d.y) ** 2 <= r * r) return { dep: d };
}
return null;
}
const depName = (d) => (d.kind === 2 ? 'Bubble' : d.kind === 1 ? 'Liquid pool' : 'Patch');
const cellName = (c) => (c.flags & 1 ? 'Wildlife cell' : c.flags & 2 ? 'Player cell (connected)' : 'Player cell');
function tipFor(found) {
if (found.cell) {
const c = found.cell;
return [h('div', { class: 'tip-title' }, swatch(cellLayer(c) === 'players' ? 'player' : cellLayer(c)), cellName(c)),
...[['Life', c.life], ['Members', c.members], ['Size', fmtLength(c.extent)], ['Reserve energy', fmtEnergy(c.reserve[0])],
['Reserve matter', fmtMass(sum(c.reserve.slice(1)))], ['Body mass', fmtMass(c.bodyMass)]]
.map(([a, b]) => h('div', { class: 'tip-row' }, h('span', {}, a), h('span', {}, String(b))))];
}
const d = found.dep;
return [h('div', { class: 'tip-title' }, swatch(d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pool' : 'patch'), `${depName(d)} #${d.id}`),
...channels.map((c, i) => (Number(d.stock[i]) ? h('div', { class: 'tip-row' }, h('span', {}, c.label), h('span', {}, c.fmt(d.stock[i]))) : null)),
h('div', { class: 'tip-row' }, h('span', {}, 'Radius'), h('span', {}, fmtLength(d.r)))];
}
// ----- Marked cells -----
function drawMarks() {
markBar.hidden = marked.size === 0;
if (!view) return;
const wild = view.cells.filter((c) => marked.has(c.life) && c.flags & 1).length;
markCount.textContent = `${fmtInt(marked.size)} marked`;
markNote.textContent = wild === marked.size ? 'wildlife' : `${fmtInt(marked.size - wild)} player${marked.size - wild === 1 ? '' : 's'}`;
}
// One remove_cell command each, queued in turn; the region applies them over its next ticks.
async function removeMarked() {
const lives = [...marked];
if (!lives.length || !confirm(`Remove ${fmtInt(lives.length)} marked cells? Their bodies and reserves go to the spent pool.`)) return;
let queued = 0, failed = '';
for (const life of lives) {
markNote.textContent = `queuing ${queued + 1} of ${lives.length}…`;
try {
await api(`/api/regions/${region}/commands?${new URLSearchParams({ kind: 'remove_cell', target: life, reason: 'bulk removal from the map' })}`, true, 'POST');
marked.delete(life);
++queued;
} catch (e) { failed = e.code || e.message; break; }
}
commands.load();
drawMarks();
paint();
markNote.textContent = failed ? `queued ${queued}; stopped: ${failed}` : `queued ${queued}`;
markBar.hidden = false;
}
// ----- Inspector -----
function select(found) {
selected = found;
inspectKey = null;
goneText = '';
drawInspector();
openTab('inspect');
paint();
}
function drawInspector() {
if (!view) return;
if (!selected) {
inspectKey = 'none';
const players = view.cells.filter((c) => !(c.flags & 1));
inspect.replaceChildren(
h('div', { class: 'empty' }, h('div', { class: 'big' }, goneText ? '∅' : '◎'), goneText || 'Click a cell, bubble or pool on the map to inspect it.'),
block(`Player cells`, h('span', { class: 'muted' }, fmtInt(players.length)),
players.length ? h('div', { class: 'list' }, players.map((c) => h('div', {
class: 'list-item clickable',
onclick: () => { select({ cell: c }); centerOn(c.x + c.extent / 2, c.y + c.extent / 2); },
}, swatch(c.flags & 2 ? 'online' : 'player'),
h('div', { class: 'grow' }, h('span', { class: 'mono' }, short(c.account)), h('div', { class: 'sub' }, `life ${c.life} · ${fmtLength(c.extent)}`)),
h('span', { class: 'muted small' }, fmtEnergy(c.reserve[0])))))
: h('p', { class: 'hint' }, 'No player cells are alive in this region.')));
return;
}
const key = selected.cell ? `c${selected.cell.life}` : `d${selected.dep.id}`;
if (inspectKey !== key) {
// Built once per selection so typed amounts survive the live refresh.
inspectKey = key;
inspectFacts = h('div');
const close = h('button', { class: 'ghost icon', title: 'Clear the selection', onclick: () => { selected = null; drawInspector(); paint(); } }, '✕');
const locate = h('button', { title: 'Center the map on it', onclick: () => {
const it = selected && (selected.cell || selected.dep);
if (it) centerOn(selected.cell ? it.x + it.extent / 2 : it.x, selected.cell ? it.y + it.extent / 2 : it.y);
} }, 'Locate');
if (selected.cell) {
const c = selected.cell;
const grant = amountInputs(), reason = reasonInput(), note = h('div', { class: 'note' });
const give = () => {
let values;
try { values = grant.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
send({ kind: 'grant_reserve', target: c.life, ...values }, `grant reserve to ${c.life}`, note, reason).then((ok) => { if (ok) grant.clear(); });
};
const takeAmount = amountInputs(), takeReason = reasonInput(), takeNote = h('div', { class: 'note' });
const take = () => {
let values;
try { values = takeAmount.read(); } catch (e) { takeNote.className = 'note error'; takeNote.textContent = e.message; return; }
send({ kind: 'take_reserve', target: c.life, ...values }, `take reserve from ${c.life}`, takeNote, takeReason).then((ok) => { if (ok) takeAmount.clear(); });
};
const remove = () => {
if (!confirm(`Remove ${c.flags & 1 ? 'wildlife' : 'player'} cell ${c.life}? Its body and reserve go to the spent pool.`)) return;
send({ kind: 'remove_cell', target: c.life }, `remove cell ${c.life}`, note, reason);
};
inspect.replaceChildren(
h('div', { class: 'inspect-head' }, swatch(cellLayer(c) === 'players' ? 'player' : cellLayer(c)), h('h2', { class: 'grow' }, cellName(c)), locate, close),
inspectFacts,
block('Grant reserve', null, grant.node, h('div', { class: 'form-row' }, reason, h('button', { onclick: give }, 'Grant')), note),
block('Take reserve', null, h('p', { class: 'hint' }, 'Moves up to these amounts from the cell\'s reserve to the spent pool (never more than it holds).'),
takeAmount.node, h('div', { class: 'form-row' }, takeReason, h('button', { onclick: take }, 'Take')), takeNote),
block('Remove', null, h('p', { class: 'hint' }, 'Kills the cell now; its body and reserve go to the spent pool.'),
h('button', { class: 'danger', onclick: remove }, 'Remove cell')));
} else {
const d = selected.dep;
inspect.replaceChildren(
h('div', { class: 'inspect-head' }, swatch(d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pool' : 'patch'), h('h2', { class: 'grow' }, `${depName(d)} #${d.id}`), locate, close),
inspectFacts,
h('div', { class: 'callout info', style: { marginTop: '14px' } },
h('div', {}, d.kind === 2 ? 'Cells collect bubbles by touching them.' : 'Pools and patches are fixed food sources cells collect from.',
' Admin commands do not target a single deposit: add stock with Add bubbles, or to the spent pool on the Resources tab.')));
}
}
if (selected.cell) {
const c = selected.cell;
inspectFacts.replaceChildren(
h('dl', { class: 'facts' },
h('dt', {}, 'Life'), h('dd', { class: 'mono' }, c.life),
h('dt', {}, 'Organism'), h('dd', { class: 'mono' }, c.organism, c.members > 1 ? h('span', { class: 'muted' }, ` ${c.members} cells`) : null),
h('dt', {}, 'Account'), h('dd', {}, c.account ? h('a', { class: 'mono', href: `#/accounts/${c.account}` }, c.account) : h('span', { class: 'muted' }, 'wildlife')),
h('dt', {}, 'Lineage root'), h('dd', { class: 'mono' }, c.root || '—'),
h('dt', {}, 'Size'), h('dd', {}, fmtLength(c.extent)),
h('dt', {}, 'Body mass'), h('dd', {}, fmtMass(c.bodyMass)),
h('dt', {}, 'Position'), h('dd', {}, `${fmtLength(c.x)}, ${fmtLength(c.y)}`),
h('dt', {}, 'State'), h('dd', {}, c.flags & 4 ? h('span', { class: 'badge warn' }, 'lingering') : c.flags & 8 ? h('span', { class: 'badge warn' }, 'suspended') : h('span', { class: 'badge alive' }, 'active'))),
h('h3', { style: { margin: '16px 0 0' } }, 'Reserve'), channelTiles(c.reserve));
} else {
const d = selected.dep;
inspectFacts.replaceChildren(
h('dl', { class: 'facts' },
h('dt', {}, 'Kind'), h('dd', {}, depName(d)),
h('dt', {}, 'Radius'), h('dd', {}, fmtLength(d.r)),
h('dt', {}, 'Position'), h('dd', {}, `${fmtLength(d.x)}, ${fmtLength(d.y)}`)),
h('h3', { style: { margin: '16px 0 0' } }, 'Contents'), channelTiles(d.stock));
}
}
// ----- Resources -----
function drawResources() {
const L = regionLedger(view);
const rows = [
['Cell reserves', L.reserve], ['Cell bodies', L.body], ['Bubbles', L.bubbles], ['Liquid pools', L.pools],
...(sum(L.patches) ? [['Patches', L.patches]] : []), ['Spent pool', L.spent],
...(L.heat ? [['Heat (used energy)', L.heat]] : []),
];
const total = rows.reduce((t, [, v]) => (v ? addTo(t, v) : t), [0, 0, 0, 0, 0]);
const held = [0, 0, 0, 0, 0], free = [0, 0, 0, 0, 0];
if (L.reserve) addTo(held, L.reserve);
if (L.body) addTo(held, L.body);
for (const v of [L.bubbles, L.pools, L.patches]) addTo(free, v);
const parts = [['In cells', held, 'var(--wildlife)'], ['Bubbles and pools', free, 'var(--accent)'], ['Spent pool', L.spent.map(Number), 'var(--warn)'],
...(L.heat ? [['Heat', L.heat, 'var(--bad)']] : [])];
fill(ledgerBox,
h('table', { class: 'ledger' },
h('thead', {}, h('tr', {}, h('th', {}, ''), channels.map((c) => h('th', { class: 'num' }, swatch(c.key), c.short)))),
h('tbody', {},
rows.map(([label, v]) => h('tr', {}, h('td', {}, label), channels.map((c, i) => h('td', { class: 'num' }, v ? c.fmt(v[i]) : '—')))),
h('tr', { class: 'total' }, h('td', {}, 'Total'), channels.map((c, i) => h('td', { class: 'num' }, c.fmt(total[i])))))),
h('div', { style: { marginTop: '12px' } }, channels.map((c, i) => h('div', { class: 'split-row' },
h('span', { class: 'muted' }, c.label),
h('div', { class: 'split', title: parts.map(([n, v]) => `${n}: ${c.fmt(v[i])}`).join('\n') },
parts.map(([, v, color]) => h('span', { style: { width: `${total[i] ? (100 * v[i]) / total[i] : 0}%`, background: color } })))))),
h('div', { class: 'split-legend' }, parts.map(([n, , color]) => h('span', {}, h('span', { class: 'swatch', style: { background: color } }), n))),
L.complete ? null : h('p', { class: 'hint', style: { marginTop: '8px' } }, 'Sums over the listed cells and deposits only (this region server predates complete totals).'));
const plan = dripPlan(view);
const notes = [];
const deposits = Number(view.deposits_total);
const absorbing = plan && plan.absorb;
if (deposits >= depositLimit) {
notes.push(absorbing
? `The region holds ${fmtInt(deposits)} deposits, its limit: drips join existing bubbles, and Add bubbles is refused until cells eat some.`
: `The region holds ${fmtInt(deposits)} deposits, its limit: the drip waits and new bubbles are refused until cells eat some.`);
}
else if (deposits >= depositLimit * 0.95) notes.push(`${fmtInt(depositLimit - deposits)} deposit places left before the limit of ${fmtInt(depositLimit)}.`);
if (pace.stalled) notes.push('The tick is not advancing, so nothing drips until the region ticks again.');
if (!plan) {
dripEvery.textContent = '';
fill(dripBox, h('p', { class: 'hint', style: { marginTop: '8px' } }, 'Only rules-13 regions drip their spent pool (this server does not report the drip).'));
return;
}
dripEvery.textContent = plan.interval ? `every ${(plan.interval * tickSeconds).toLocaleString()} s (${plan.interval} ticks)` : 'off';
if (!sum(plan.next)) notes.push('The spent pool is empty: drips release nothing.');
if (!plan.recycle && L.heat && L.heat[0]) notes.push(`Energy cells use is lost as heat (${fmtEnergy(L.heat[0])} so far): set spent.heat_recycle_per_mille to return it through the drip.`);
const dryIn = (i) => (!Number(view.spent[i]) ? h('span', { class: 'faint' }, 'empty') : plan.interval ? fmtDuration(plan.drips[i] * plan.interval * tickSeconds) : '—');
fill(dripBox,
h('table', { class: 'ledger', style: { marginTop: '12px' } },
h('thead', {}, h('tr', {}, h('th', {}, 'Channel'), h('th', { class: 'num' }, 'In the pool'), h('th', { class: 'num' }, 'Per drip'), h('th', { class: 'num' }, 'Empty in'))),
h('tbody', {}, channels.map((c, i) => h('tr', {},
h('td', {}, swatch(c.key), ' ', c.label),
h('td', { class: 'num' }, c.fmt(view.spent[i])),
h('td', { class: 'num' }, Number(plan.next[i]) ? c.fmt(plan.next[i]) : h('span', { class: 'faint' }, '—')),
h('td', { class: 'num' }, dryIn(i)))))),
h('div', { class: 'muted small', style: { marginTop: '8px' } }, `Each drip makes one bubble per non-empty channel, at most ${fmtEnergy(plan.caps[0])} of energy or ${fmtMass(plan.caps[1])} of one matter, at random spots${plan.absorb ? '; at the deposit limit it joins an existing bubble instead' : ''}.`),
h('div', { class: 'muted small', style: { marginTop: '4px' } }, plan.recycle
? `Energy cycle: ${(plan.recycle / 10).toLocaleString()}% of the region's heat returns to the spent pool every tick.`
: 'Energy cycle: off. Energy cells use stays as heat.'),
notes.length ? h('div', { style: { marginTop: '12px' } }, notes.map((n) => h('div', { class: 'callout' }, n))) : null);
}
// Estimated tick now, between fetches, from the measured pace.
const rate = () => {
const s = pace.samples;
if (s.length < 2) return 1 / tickSeconds;
const dt = (s[s.length - 1].t - s[0].t) / 1000;
return dt > 0 ? (s[s.length - 1].tick - s[0].tick) / dt : 1 / tickSeconds;
};
function animate() {
frame = requestAnimationFrame(animate);
if (!view) return;
const plan = dripPlan(view);
if (!plan || !plan.interval) { k.drip.set(plan ? 'off' : '—', plan ? 'drip interval 0' : 'rules 13 only'); dripCountdown.textContent = plan ? 'off' : '—'; return; }
const r = pace.stalled ? 0 : rate();
const est = Number(view.tick) + Math.min(5, (performance.now() - pace.fetchedAt) / 1000) * r;
const into = ((est % plan.interval) + plan.interval) % plan.interval;
const left = (plan.interval - into) / Math.max(r, 1e-9);
const text = pace.stalled ? 'paused' : `in ${left < 10 ? left.toFixed(1) : Math.round(left)} s`;
const fill = into / plan.interval;
const empty = !sum(plan.next);
k.drip.set(text, empty ? 'spent pool empty' : `${fmtEnergy(plan.next[0])} · ${fmtMass(sum(plan.next.slice(1)))}`, pace.stalled ? 'warn' : '', fill, empty ? 'warn' : '');
dripCountdown.textContent = text;
dripMeter.firstChild.style.width = `${fill * 100}%`;
}
// ----- Pointer -----
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
if (box) {
box.x1 = e.clientX - rect.left; box.y1 = e.clientY - rect.top;
tip.hidden = true;
paint(); return;
}
if (drag) {
if (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3) { drag.moved = true; canvas.classList.add('dragging'); }
panX = drag.panX + (e.clientX - drag.x); panY = drag.panY + (e.clientY - drag.y);
tip.hidden = true;
paint(); return;
}
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (!found) { tip.hidden = true; return; }
tip.replaceChildren(...tipFor(found));
tip.hidden = false;
const x = e.clientX - rect.left + 16, y = e.clientY - rect.top + 16;
tip.style.left = `${Math.min(x, rect.width - tip.offsetWidth - 8)}px`;
tip.style.top = `${Math.min(y, rect.height - tip.offsetHeight - 8)}px`;
});
canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; box = null; canvas.classList.remove('dragging'); paint(); });
canvas.addEventListener('mousedown', (e) => {
if (e.shiftKey) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left, y = e.clientY - rect.top;
box = { x0: x, y0: y, x1: x, y1: y };
return;
}
drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false };
});
canvas.addEventListener('mouseup', (e) => {
if (box) {
const b = box;
box = null;
if (Math.abs(b.x1 - b.x0) < 4 && Math.abs(b.y1 - b.y0) < 4) {
const found = hit(b.x0, b.y0);
if (found && found.cell) {
if (marked.has(found.cell.life)) marked.delete(found.cell.life); else marked.add(found.cell.life);
}
} else if (view) {
// Every shown cell whose centre is inside the box.
const g = geometry();
const xs = [b.x0, b.x1].map((v) => g.fromX(v * g.dpr)), ys = [b.y0, b.y1].map((v) => g.fromY(v * g.dpr));
const [x0, x1] = [Math.min(...xs), Math.max(...xs)], [y0, y1] = [Math.min(...ys), Math.max(...ys)];
for (const c of view.cells) {
const cx = c.x + c.extent / 2, cy = c.y + c.extent / 2;
if (layers[cellLayer(c)] && cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1) marked.add(c.life);
}
}
drawMarks();
paint();
return;
}
const moved = drag && drag.moved;
drag = null;
canvas.classList.remove('dragging');
if (moved) return;
const rect = canvas.getBoundingClientRect();
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (found) select(found);
});
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
setZoom(zoom * Math.exp(-e.deltaY * 0.0015), e.clientX - rect.left - rect.width / 2, e.clientY - rect.top - rect.height / 2);
}, { passive: false });
canvas.addEventListener('dblclick', () => { zoom = 1; panX = 0; panY = 0; paint(); });
const onResize = () => paint();
window.addEventListener('resize', onResize);
window.addEventListener('themechange', onResize);
// ----- Loading -----
async function load() {
try {
const raw = await api(`/api/regions/${region}/view`);
const now = performance.now();
const tick = Number(raw.tick);
if (pace.lastTick === null || tick !== pace.lastTick) pace.movedAt = now;
pace.lastTick = tick;
pace.fetchedAt = now;
pace.samples.push({ t: now, tick });
while (pace.samples.length > 2 && now - pace.samples[0].t > 10000) pace.samples.shift();
pace.stalled = now - pace.movedAt > 3000 && pace.samples.length > 2;
const digestChanged = view && view.rules_sha256 !== raw.rules_sha256;
view = { ...raw, cells: raw.cells.map(cellObj), deps: raw.deposits.map(depObj) };
const counts = raw.counts ? raw.counts.map(Number) : null;
const players = counts ? counts[0] : view.cells.filter((c) => !(c.flags & 1)).length;
const wild = counts ? counts[1] : view.cells.length - players;
const online = view.cells.filter((c) => !(c.flags & 1) && c.flags & 2).length;
const kinds = counts ? counts.slice(2) : [0, 1, 2].map((kd) => view.deps.filter((d) => d.kind === kd).length);
const byChannel = [0, 0, 0, 0, 0];
for (const d of view.deps) if (d.kind === 2) byChannel[d.top] += 1;
chips.players.count.textContent = fmtInt(players - online);
chips.online.count.textContent = fmtInt(online);
chips.wildlife.count.textContent = fmtInt(wild);
chips.pools.count.textContent = fmtInt(kinds[1]);
chips.patches.count.textContent = fmtInt(kinds[0]);
chips.patches.node.hidden = !kinds[0];
channels.forEach((c, i) => { chips[c.key].count.textContent = fmtInt(byChannel[i]); });
const L = regionLedger(view);
const totalOf = (i) => [L.reserve, L.body, L.bubbles, L.pools, L.patches, L.spent, L.heat].reduce((s, v) => s + (v ? Number(v[i]) : 0), 0);
const freeOf = (i) => [L.bubbles, L.pools, L.patches].reduce((s, v) => s + Number(v[i]), 0);
const energy = totalOf(0), matter = [1, 2, 3, 4].reduce((s, i) => s + totalOf(i), 0);
const freeMatter = [1, 2, 3, 4].reduce((s, i) => s + freeOf(i), 0);
const deposits = Number(raw.deposits_total);
const r = rate();
k.tick.set(fmtInt(tick), pace.stalled ? `not advancing for ${fmtDuration((now - pace.movedAt) / 1000)}` : `${r.toFixed(1)} ticks/s`, pace.stalled ? 'warn' : '');
// The lineage archive never forgets: at its limits the region stops ticking.
const archive = raw.archive ? Math.max(Number(raw.archive[0]) / Number(raw.archive[1]), Number(raw.archive[2]) / Number(raw.archive[3])) : 0;
const archiveText = raw.archive ? ` · archive ${Math.floor(archive * 100)}% (${fmtInt(raw.archive[0])} births, ${fmtInt(raw.archive[2])} genomes)` : '';
if (raw.caps) {
// Births stop at the organism cap; wildlife buds stop at the wildlife cap.
const cap = Number(raw.caps[0]), wildCap = Number(raw.caps[1]) || cap, lives = players + wild;
const full = lives >= cap || archive >= 0.95 ? 'bad' : lives >= wildCap || archive >= 0.8 ? 'warn' : '';
k.cells.set(`${fmtInt(lives)} / ${fmtInt(cap)}`,
`${fmtInt(players)} players · ${fmtInt(wild)} wildlife${wildCap < cap ? ` · wildlife stop at ${fmtInt(wildCap)}` : ''}${archiveText}`,
lives ? full : 'warn', lives / cap, full);
} else {
k.cells.set(fmtInt(players + wild), `${fmtInt(players)} players · ${fmtInt(wild)} wildlife`, players + wild ? '' : 'warn');
}
k.deposits.set(`${fmtInt(deposits)} / ${fmtInt(depositLimit)}`, `${fmtInt(kinds[2])} bubbles · ${fmtInt(kinds[1])} pools`,
deposits >= depositLimit ? 'bad' : '', deposits / depositLimit, deposits >= depositLimit ? 'bad' : deposits >= depositLimit * 0.9 ? 'warn' : '');
k.energy.set(fmtEnergy(energy), `${fmtEnergy(freeOf(0))} free to eat`, energy ? '' : 'bad');
k.matter.set(fmtMass(matter), `${fmtMass(freeMatter)} free to eat`);
k.spent.set(fmtEnergy(raw.spent[0]), `${fmtMass(sum(raw.spent.slice(1)))} matter`);
const truncated = raw.cells_total > raw.cells.length || raw.deposits_total > raw.deposits.length;
fill(titleBadges,
pace.stalled ? h('span', { class: 'badge warn', title: 'The tick has not moved in the last few seconds' }, h('span', { class: 'dot' }), 'not ticking')
: h('span', { class: 'badge alive' }, h('span', { class: 'dot pulse' }), 'running'),
h('span', { class: 'badge' }, `rules ${raw.rules}`),
tuning.running ? h('span', { class: `badge ${tuning.running.revision === null ? 'warn' : ''}` }, tuning.running.label) : null,
truncated ? h('span', { class: 'badge warn', title: 'More cells or deposits than the view lists' }, 'view truncated') : null);
subtitle.textContent = `World ${raw.world} · ${fmtLength(raw.area[0])} × ${fmtLength(raw.area[1])} · updated ${new Date().toLocaleTimeString()}`;
subtitle.className = 'subtitle';
banner.hidden = !pace.stalled;
banner.textContent = pace.stalled ? `Tick ${fmtInt(tick)} has not advanced for ${fmtDuration((now - pace.movedAt) / 1000)}` : '';
if (marked.size) {
const alive = new Set(view.cells.map((c) => c.life));
for (const life of marked) if (!alive.has(life)) marked.delete(life);
drawMarks();
}
if (selected) {
if (selected.cell) {
const again = view.cells.find((c) => c.life === selected.cell.life);
if (again) selected = { cell: again };
else { selected = null; goneText = 'The selected cell is gone (died or left).'; }
} else {
const again = view.deps.find((d) => d.id === selected.dep.id);
if (again) selected = { dep: again };
else { selected = null; goneText = 'The selected deposit is gone (eaten or merged).'; }
}
}
drawInspector();
drawResources();
if (digestChanged || !tuning.tried) tuning.load(digestChanged);
paint();
} catch (e) {
subtitle.textContent = e.status === 503 ? 'The region is not ready or cannot be reached.' : `Could not load the view: ${e.message}`;
subtitle.className = 'subtitle error';
titleBadges.replaceChildren(h('span', { class: 'badge dead' }, 'unreachable'));
}
}
const tick = () => {
timer = setTimeout(async () => {
if (live.checked && !document.hidden) {
await load();
beats += 1;
if (beats % 10 === 0) sessions.load();
if (beats % 5 === 0) commands.load();
if (beats % 15 === 0) schedules.load();
}
tick();
}, 1000);
};
await load();
commands.load();
tick();
animate();
stopPage = () => {
clearTimeout(timer);
cancelAnimationFrame(frame);
window.removeEventListener('resize', onResize);
window.removeEventListener('themechange', onResize);
};
}
// ---------- Tuning (schema 66): guided editor and text editor ----------
const tuningErrors = {
too_large: 'the text is too large', syntax: 'not a `key = value` line', unknown_key: 'unknown key',
duplicate_key: 'key given twice', invalid_value: 'not an integer', out_of_range: 'value out of range',
missing_key: 'required key missing', inconsistent: 'values contradict each other',
unsupported_version: 'unsupported tuning.version',
};
function tuningProblem(e) {
const d = e.detail || {};
if (e.code === 'invalid_tuning')
return `${d.key ? `${d.key}: ` : d.line ? `Line ${d.line}: ` : ''}${tuningErrors[d.kind] || d.kind}`;
if (e.code === 'invalid_rules') return 'The values parse but do not make valid rules (a bound or gate is out of range).';
if (e.code === 'safety_version_changed') return `reproduction.safety_version must stay ${d.expected}: it is fixed when a region opens.`;
if (e.code === 'invalid_change') return `Change ${d.line} is not a whole number.`;
if (e.code === 'stale_base') return `Revision ${d.newest} was adopted after this page loaded. Reload to edit it.`;
if (e.code === 'invalid_text') return 'The text must be plain ASCII.';
if (e.code === 'too_large') return 'The admin API refused the text as over 64 KiB.';
if (e.code === 'proxy_too_large')
return `The web proxy in front of the portal refused ${fmtInt(d.bytes)} bytes (HTTP 413). Use the guided editor, which sends only the changes, or raise the srs Ingress's nginx.ingress.kubernetes.io/proxy-body-size.`;
return `Refused: ${e.code || e.message}`;
}
// Selects line `n` (1-based) of a textarea so the problem is in view.
function selectLine(area, n) {
const lines = area.value.split('\n');
if (!n || n > lines.length) return;
const start = lines.slice(0, n - 1).reduce((s, l) => s + l.length + 1, 0);
area.focus();
area.setSelectionRange(start, start + lines[n - 1].length);
const lineHeight = parseFloat(getComputedStyle(area).lineHeight) || 18;
area.scrollTop = Math.max(0, (n - 5) * lineHeight);
}
const tuningSectionNames = {
playtest: 'Playtest opening', body: 'Body', energy: 'Energy burn', feeding: 'Feeding',
predation: 'Predation', spent: 'Spent pool and energy cycle', mutation: 'Mutation offers',
reproduction: 'Reproduction', organism: 'Organisms',
};
// Unit suffixes: stripped from the label and shown beside the input (longest first).
const tuningUnits = [
[/_per_mille_per_point$/, '‰ per point'], [/_pj_per_kfg$/, 'pJ per 1,000 fg'], [/_centi_mille$/, '1/100 ‰'],
[/_per_mille$/, '‰'], [/_um_per_s$/, 'µm/s'], [/_percent$/, '%'], [/_ppm$/, 'ppm'], [/_milli$/, '1/1000'],
[/_pj$/, 'pJ'], [/_fg$/, 'fg'], [/_ticks$/, 'ticks'], [/_ms$/, 'ms'], [/_um$/, 'µm'], [/_seconds$/, 's'], [/_mk$/, 'mK'],
];
const tuningSwitches = new Set(['feeding.split_evenly', 'spent.drip_absorb']);
const tuningOptional = [
['spent.heat_recycle_per_mille', '0', 'share of the heat returned to the spent pool each tick'],
['spent.drip_absorb', '0', 'a drip at the deposit limit joins an existing bubble'],
['reproduction.wildlife_cap', '0', 'wildlife buds refused at this many lives (0: the organism cap); the rest are for players'],
];
const isSwitch = (key) => tuningSwitches.has(key) || key.endsWith('.enabled');
function tuningLabel(key, section) {
let name = key.slice(section.length + 1);
let unit = '';
for (const [pattern, u] of tuningUnits) {
if (pattern.test(name)) { unit = u; name = name.replace(pattern, ''); break; }
}
name = name.replace(/[._]+/g, ' ').trim();
// Energy and matter amounts of the same thing otherwise share a label.
const kind = unit === 'pJ' ? ' (energy)' : unit === 'fg' ? ' (matter)' : '';
return { label: name.charAt(0).toUpperCase() + name.slice(1) + kind, unit };
}
const tuningNorm = (v) => String(v).replace(/[_,\s]/g, '');
const tuningValid = (v) => /^-?\d+$/.test(v);
async function tuningPage() {
const data = await api('/api/tuning');
const byDigest = new Map(data.revisions.map((r) => [r.rules_sha256, `revision ${r.revision}`]));
if (data.baseline && data.baseline.rules_sha256 && !byDigest.has(data.baseline.rules_sha256))
byDigest.set(data.baseline.rules_sha256, 'the baseline file');
// The base every change applies to: the newest revision, else the baseline file.
const base = data.newest
? { query: String(data.newest.revision), label: `revision #${data.newest.revision}`, text: data.newest.text }
: data.baseline ? { query: 'baseline', label: 'the baseline file', text: data.baseline.text } : null;
let mode = (() => { try { return localStorage.getItem('tuning-mode') || 'guided'; } catch { return 'guided'; } })();
// ----- Region status and revisions (shared by both modes) -----
const regionsBox = h('div', { class: 'muted' }, 'Loading…');
(async () => {
const rows = await Promise.all(data.regions.map(async (region) => {
try {
const v = await api(`/api/regions/${region}/view`);
const running = v.rules_sha256 ? byDigest.get(v.rules_sha256) : null;
return h('div', { class: 'list-item' }, h('a', { class: 'grow', href: `#/regions/${region}` }, `Region ${region}`),
v.rules_sha256
? (running ? h('span', { class: 'badge alive' }, running) : h('span', { class: 'badge warn', title: v.rules_sha256 }, `other rules ${v.rules_sha256.slice(0, 8)}…`))
: h('span', { class: 'muted' }, `rules ${v.rules}`),
h('span', { class: 'muted small' }, `tick ${fmtInt(v.tick)}`));
} catch (e) {
return h('div', { class: 'list-item' }, h('span', { class: 'grow' }, `Region ${region}`), h('span', { class: 'muted small' }, `unavailable: ${e.code || e.message}`));
}
}));
fill(regionsBox, rows.length ? h('div', { class: 'list' }, rows) : 'No regions configured.');
})();
const loadInto = { fn: null }; // Set by the active mode: loads another text's values.
const revisions = data.revisions.length ? h('div', { class: 'list' }, data.revisions.map((r) =>
h('div', { class: 'list-item' },
h('span', { class: 'mono faint' }, `#${r.revision}`),
h('div', { class: 'grow' }, r.reason || h('span', { class: 'muted' }, 'no reason'),
h('div', { class: 'sub', title: r.author || '' }, `${(r.author || '').split(' (')[0]} · ${fmtAgo(r.created_at)}`)),
r.adopted >= r.regions && r.regions > 0
? h('span', { class: 'badge alive', title: r.last_tick ? `last at tick ${r.last_tick}` : '' }, `adopted ${r.adopted}/${r.regions}`)
: h('span', { class: 'badge warn' }, `pending ${r.adopted}/${r.regions}`),
h('button', {
title: 'Load its values into the editor',
onclick: async () => {
try { const t = await api(`/api/tuning/${r.revision}`); if (loadInto.fn) loadInto.fn(t.text, `revision #${t.revision}`); } catch (e) { alert(`Could not load: ${e.code || e.message}`); }
},
}, 'Load')))) : h('p', { class: 'hint' }, 'No revisions yet: regions run the rules they opened with.');
const sideCards = [
h('div', { class: 'card' }, h('h2', {}, 'Regions'), regionsBox),
h('div', { class: 'card' }, h('h2', {}, 'Revisions'), revisions),
data.region_file ? h('div', { class: 'card' }, h('h2', {}, 'Region file'),
h('p', { class: 'hint' }, 'cellular.tuning from Git, read only: read when a region starts (shape and currents when it opens). Changing it takes a commit and a sync.'),
settingsView(data.region_file, { open: false })) : null,
];
const modeSwitch = h('div', { class: 'segmented' },
['guided', 'text'].map((m) => h('button', { class: m === mode ? 'on' : null, onclick: () => { try { localStorage.setItem('tuning-mode', m); } catch { /* */ } route(); } },
m === 'guided' ? 'Guided' : 'Text')));
const head = h('div', { class: 'head' },
h('div', {}, h('h1', {}, 'Cellular tuning'), h('div', { class: 'subtitle' }, `World ${data.world} · rules 13 · every region adopts the same revision · editing ${base ? base.label : 'nothing (no baseline, no revisions)'}`)),
h('div', { class: 'tools' }, modeSwitch, h('button', { onclick: () => route() }, 'Reload')));
if (!base) { show(head, h('p', { class: 'hint' }, 'No baseline file and no revisions to start from.')); return; }
if (mode === 'text') { textTuning(data, base, byDigest, head, sideCards, loadInto); return; }
// ----- Guided editor -----
const groups = parseTuning(base.text);
// Optional keys a revision may lack, shown at the value that keeps the historical law.
for (const [key, value, note] of tuningOptional) {
const name = key.split('.')[0];
let group = groups.find((g) => g.name === name);
if (!group) { group = { name, about: '', settings: [] }; groups.push(group); }
if (!group.settings.some((s) => s.key === key)) group.settings.push({ key, value, note, lead: '' });
}
const baseValues = new Map(groups.flatMap((g) => g.settings.map((s) => [s.key, s.value])));
const edits = new Map(); // key -> normalized new value (only where it differs)
const problems = new Map(); // key -> message (bad input or the server's refusal)
let section = groups.length ? groups[0].name : '';
const nav = h('div', { class: 'section-nav' });
const search = h('input', { type: 'search', placeholder: 'Find a setting', class: 'wide' });
const form = h('div');
const changesBox = h('div');
const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (recorded with the revision)', class: 'wide' });
const note = h('div', { class: 'note' });
const say = (text, cls = 'muted') => { note.className = `note ${cls}`; note.textContent = text; };
const changeText = () => [...edits].map(([k, v]) => `${k} = ${v}\n`).join('');
function setValue(key, raw) {
const n = tuningNorm(raw);
problems.delete(key);
if (!tuningValid(n)) { problems.set(key, 'Enter a whole number.'); edits.delete(key); } else if (baseValues.has(key) && n === tuningNorm(baseValues.get(key))) edits.delete(key);
else edits.set(key, n);
drawNav(); drawChanges();
}
function loadText(text, label) {
const other = new Map(parseTuning(text).flatMap((g) => g.settings.map((s) => [s.key, s.value])));
edits.clear(); problems.clear();
for (const [k, v] of other) if (!baseValues.has(k) || tuningNorm(v) !== tuningNorm(baseValues.get(k))) edits.set(k, tuningNorm(v));
const dropped = [...baseValues.keys()].filter((k) => !other.has(k));
say(`Loaded ${label}: ${edits.size} value${edits.size === 1 ? '' : 's'} differ from ${base.label}.${dropped.length ? ` Keys it lacks stay as they are: ${dropped.join(', ')}.` : ''}`);
drawNav(); drawForm(); drawChanges();
}
loadInto.fn = loadText;
function fieldRow(s, group) {
const { label, unit } = tuningLabel(s.key, group.name);
const current = edits.has(s.key) ? edits.get(s.key) : s.value;
const locked = s.key === 'reproduction.safety_version';
const gl = h('span', { class: 'gloss' });
const problem = h('div', { class: 'field-problem' });
const row = h('div', { class: 'field-row' });
const refresh = (value) => {
const n = tuningNorm(value);
gl.textContent = tuningValid(n) ? gloss(s.key, n) : '';
const changed = edits.has(s.key);
row.classList.toggle('changed', changed);
row.classList.toggle('bad', problems.has(s.key));
problem.textContent = problems.get(s.key) || (changed ? `was ${s.value.replace(/_/g, ',')}` : '');
reset.hidden = !changed && !problems.has(s.key);
};
let input;
if (isSwitch(s.key)) {
input = h('select', { disabled: locked }, [['1', 'On'], ['0', 'Off']].map(([v, t]) => h('option', { value: v, selected: tuningNorm(current) === v }, t)));
input.addEventListener('change', () => { setValue(s.key, input.value); refresh(input.value); });
} else {
input = h('input', { type: 'text', inputmode: 'numeric', value: current, disabled: locked, spellcheck: 'false' });
input.addEventListener('input', () => { setValue(s.key, input.value); refresh(input.value); });
}
const reset = h('button', {
class: 'ghost icon', title: `Back to ${s.value}`,
onclick: () => { edits.delete(s.key); problems.delete(s.key); input.value = isSwitch(s.key) ? tuningNorm(s.value) : s.value; refresh(s.value); drawNav(); drawChanges(); },
}, '↺');
row.append(
h('div', { class: 'field-text' },
h('div', { class: 'field-label' }, label, locked ? h('span', { class: 'badge', style: { marginLeft: '8px' } }, 'fixed at opening') : null),
h('div', { class: 'field-key mono' }, s.key),
s.lead ? h('div', { class: 'field-note' }, s.lead) : null,
s.note ? h('div', { class: 'field-note' }, s.note) : null),
h('div', { class: 'field-input' },
h('div', { class: 'input-unit' }, input, unit ? h('span', { class: 'unit' }, unit) : null, reset),
gl, problem));
refresh(current);
return row;
}
function drawForm() {
const q = search.value.trim().toLowerCase();
const shown = q
? groups.map((g) => ({ ...g, settings: g.settings.filter((s) => s.key.toLowerCase().includes(q) || s.note.toLowerCase().includes(q)) })).filter((g) => g.settings.length)
: groups.filter((g) => g.name === section);
fill(form, shown.length ? shown.map((g) => h('div', { class: 'card tuning-section' },
h('div', { class: 'card-head' }, h('h2', {}, tuningSectionNames[g.name] || g.name), h('span', { class: 'badge' }, `${g.settings.length} settings`)),
g.about ? h('p', { class: 'hint' }, g.about) : null,
g.name === 'playtest' ? h('div', { class: 'callout info' }, 'Only used when a region opens; a live change has no effect on running regions.') : null,
g.settings.map((s) => fieldRow(s, g)))) : h('div', { class: 'card' }, h('p', { class: 'hint' }, 'No setting matches.')));
}
function drawNav() {
fill(nav, groups.map((g) => {
const changed = g.settings.filter((s) => edits.has(s.key) || problems.has(s.key)).length;
return h('button', {
class: `section-link${g.name === section && !search.value.trim() ? ' on' : ''}`,
onclick: () => { section = g.name; search.value = ''; drawNav(); drawForm(); },
}, h('span', { class: 'grow' }, tuningSectionNames[g.name] || g.name),
changed ? h('span', { class: 'badge warn' }, `${changed}`) : h('span', { class: 'faint small' }, g.settings.length));
}), (() => {
const extra = [...edits.keys()].filter((k) => !baseValues.has(k));
return extra.length ? h('div', { class: 'hint', style: { marginTop: '10px' } }, `New keys: ${extra.join(', ')}`) : null;
})());
}
function drawChanges() {
const bytes = new Blob([changeText()]).size;
fill(changesBox,
edits.size ? h('div', { class: 'list' }, [...edits].map(([k, v]) => h('div', { class: 'list-item' },
h('div', { class: 'grow' }, h('div', { class: 'mono small' }, k),
h('div', { class: 'sub' }, `${baseValues.has(k) ? baseValues.get(k).replace(/_/g, ',') : 'not set'} → ${v.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}${gloss(k, v) ? ` (${gloss(k, v)})` : ''}`)),
h('button', { class: 'ghost icon', title: 'Drop this change', onclick: () => { edits.delete(k); drawNav(); drawForm(); drawChanges(); } }, '✕'))))
: h('p', { class: 'hint' }, `No changes. Apply adopts ${base.label} as it is.`),
problems.size ? h('div', { class: 'callout' }, `${problems.size} value${problems.size === 1 ? ' needs' : 's need'} fixing first.`) : null,
bytes > 950 ? h('div', { class: 'callout' }, `These changes are ${fmtInt(bytes)} bytes; the web proxy may refuse more than about 1 KB. Apply them in two parts if it does.`) : null);
applyButton.textContent = edits.size ? `Apply ${edits.size} change${edits.size === 1 ? '' : 's'}` : 'Adopt as is';
applyButton.disabled = problems.size > 0;
checkButton.disabled = problems.size > 0;
}
const showServerProblem = (e) => {
const key = e.detail && e.detail.key;
if (key && baseValues.has(key)) {
problems.set(key, tuningProblem(e));
section = groups.find((g) => g.settings.some((s) => s.key === key))?.name || section;
search.value = '';
drawNav(); drawForm(); drawChanges();
}
say(tuningProblem(e), 'error');
};
const post = (extra) => {
const q = new URLSearchParams({ base: base.query, ...extra });
return api(`/api/tuning?${q}`, true, 'POST', changeText());
};
const checkButton = h('button', {
onclick: async () => {
try {
const r = await post({ check: '1' });
const known = byDigest.get(r.rules_sha256);
say(known ? `Valid. These are the same rules as ${known}.` : `Valid. New rules ${r.rules_sha256.slice(0, 12)}…`, 'good');
} catch (e) { showServerProblem(e); }
},
}, 'Check');
const applyButton = h('button', {
class: 'primary',
onclick: async () => {
try { await post({ check: '1' }); } catch (e) { showServerProblem(e); return; }
const regions = data.regions.length === 1 ? `region ${data.regions[0]}` : `all ${data.regions.length} regions`;
const what = edits.size ? `${edits.size} change${edits.size === 1 ? '' : 's'} to ${base.label}` : `${base.label} as it is`;
if (!window.confirm(`Adopt ${what} in ${regions} of world ${data.world}?\n\nEach region switches at its next tick (a region with no living cell waits until it ticks). The revision is recorded and can only be undone by adopting another.`)) return;
try {
const extra = {};
if (reason.value.trim()) extra.reason = reason.value.trim();
const r = await post(extra);
say(`Stored revision ${r.revision}; queued for ${r.regions} region(s).`, 'good');
setTimeout(() => route(), 1500);
} catch (e) { showServerProblem(e); }
},
}, 'Adopt as is');
search.addEventListener('input', () => { drawNav(); drawForm(); });
show(head,
h('div', { class: 'tuning-guided' },
h('div', { class: 'card nav-card' }, search, nav,
data.baseline && base.query !== 'baseline' ? h('button', { class: 'ghost', style: { marginTop: '10px' }, onclick: () => loadText(data.baseline.text, 'the baseline file') }, 'Load baseline values') : null),
form,
h('div', { class: 'side' },
h('div', { class: 'card changes-card' },
h('div', { class: 'card-head' }, h('h2', {}, 'Changes'), h('button', { class: 'ghost', onclick: () => { edits.clear(); problems.clear(); drawNav(); drawForm(); drawChanges(); say(''); } }, 'Discard')),
h('p', { class: 'hint' }, `Applied to ${base.label}; only the changed values are sent.`),
changesBox, reason,
h('div', { class: 'form-row' }, checkButton, applyButton), note),
...sideCards)));
drawNav(); drawForm(); drawChanges();
}
// The whole tuning text, edited directly. Sending it needs the proxy to admit the full file.
function textTuning(data, base, byDigest, head, sideCards, loadInto) {
const area = h('textarea', { class: 'tuning', spellcheck: 'false', 'aria-label': 'Tuning text' });
const source = h('span', { class: 'muted' });
const reason = h('input', { type: 'text', class: 'wide', maxlength: 200, placeholder: 'Reason (recorded with the revision)' });
const note = h('div', { class: 'note' });
let loadedText = '';
const load = (text, label) => { area.value = text; loadedText = text; source.textContent = `Editing a copy of ${label}`; note.textContent = ''; };
load(base.text, base.label);
loadInto.fn = load;
const say = (text, cls = 'muted') => { note.className = `note ${cls}`; note.textContent = text; };
const check = async () => {
try {
const r = await api('/api/tuning?check=1', true, 'POST', area.value);
const known = byDigest.get(r.rules_sha256);
say(known ? `Valid. These are the same rules as ${known}.` : `Valid. New rules ${r.rules_sha256.slice(0, 12)}…`, 'good');
return r;
} catch (e) {
say(tuningProblem(e), 'error');
if (e.detail && e.detail.line) selectLine(area, e.detail.line);
return null;
}
};
const adopt = async () => {
if (!(await check())) return;
const regions = data.regions.length === 1 ? `region ${data.regions[0]}` : `all ${data.regions.length} regions`;
if (!window.confirm(`Adopt this tuning in ${regions} of world ${data.world}?\n\nEach region switches at its next tick; the change is recorded in its history and cannot be undone except by adopting another revision.`)) return;
try {
const q = new URLSearchParams();
if (reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/tuning?${q}`, true, 'POST', area.value);
say(`Stored revision ${r.revision}; queued for ${r.regions} region(s).`, 'good');
reason.value = '';
setTimeout(() => route(), 1500);
} catch (e) {
say(tuningProblem(e), 'error');
}
};
show(head,
h('div', { class: 'tuning-layout' },
h('div', { class: 'card' },
h('div', { class: 'card-head' }, source,
h('div', { class: 'tools' },
data.baseline ? h('button', { class: 'ghost', onclick: () => load(data.baseline.text, 'the baseline file') }, 'Load baseline') : null,
h('button', { class: 'ghost', onclick: () => load(loadedText, source.textContent.replace('Editing a copy of ', '')) }, 'Revert'))),
h('div', { class: 'callout info' }, 'The text editor sends the whole file. If the web proxy refuses it (HTTP 413), use the guided editor, which sends only the changes.'),
area,
h('div', { class: 'action' }, reason,
h('div', { class: 'row' }, h('button', { onclick: check }, 'Check'), h('button', { class: 'primary', onclick: adopt }, 'Adopt')),
note)),
h('div', { class: 'side' }, ...sideCards)));
}
// ---------- Routing ----------
async function route() {
stopPage();
stopPage = () => {};
const [path, query] = (location.hash.slice(1) || '/accounts').split('?');
const parts = path.split('/').filter(Boolean);
const params = new URLSearchParams(query || '');
for (const a of document.querySelectorAll('[data-route]')) a.classList.toggle('active', a.dataset.route === parts[0]);
try {
if (parts[0] === 'accounts' && parts[1]) await accountPage(parts[1]);
else if (parts[0] === 'regions' && parts[1]) await regionPage(parts[1], params);
else if (parts[0] === 'regions') await regionsPage();
else if (parts[0] === 'tuning') await tuningPage();
else await accountsPage();
main().focus({ preventScroll: true });
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
if (e instanceof ApiError && e.status === 403) {
return show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'Not an administrator'),
h('p', { class: 'muted' }, 'Your account does not have the aevolution-admin role.'),
h('button', { onclick: signOut }, 'Sign out'))));
}
show(h('p', { class: 'error' }, `Could not load this page: ${e.message}`), h('button', { onclick: () => route() }, 'Try again'));
}
}
function signedOut() {
document.getElementById('who').textContent = '';
document.getElementById('sign-out').hidden = true;
show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'AEvolution admin'),
h('p', { class: 'muted' }, 'Sign in with an account that has the aevolution-admin role.'),
h('button', { class: 'primary', onclick: signIn }, 'Sign in'))));
}
async function start() {
config = await (await fetch('/config.json', { cache: 'no-store' })).json();
document.getElementById('sign-out').addEventListener('click', signOut);
try {
await finishSignIn();
} catch (e) {
show(h('p', { class: 'error' }, e.message), h('button', { class: 'primary', onclick: signIn }, 'Sign in again'));
return;
}
if (!(await token())) return signedOut();
const env = document.getElementById('env');
if (env) { env.textContent = `World ${config.world}`; env.hidden = !config.world; }
try {
const me = await api('/api/me');
document.getElementById('who').textContent = me.email || me.subject;
document.getElementById('sign-out').hidden = false;
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
}
window.addEventListener('hashchange', route);
await route();
}
start();