feat(admin): live tuning revisions adopted at recorded ticks (schema 66)
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m47s
Foundation / postgres-tools (push) Successful in 29s
Foundation / server-image (push) Successful in 4m42s
Foundation / image (push) Successful in 5m55s

ADR-0182 section 13. The admin portal's Tuning page edits the world's
rules-13 tuning (the Git revamp file format); the admin API checks it,
stores an append-only revision and queues an adopt_tuning admin command
(kind 7: revision and rules digest) for every region of the world.

- Lifecycle: adopt_tuning replaces the region's rules after births when
  a resolver names the rules for that revision and digest; the safety
  revision cannot change live. At most one adoption per batch.
- Host: fetches the revision text, rebuilds and digests the rules before
  appending the command; publication and recovery name the rules from
  the successor state, checked against the recorded digest.
- Schema 66: tuning_revisions, admin_set_tuning_v1, load_tuning_revision_v1
  (runtime), admin_tuning_revisions_v1, admin_tuning_text_v1.
- OpsServer: optional bounded request bodies (Content-Length, 413).
- Region view: rules_sha256, so the portal shows each region's revision.
- Portal: Tuning page; baseline from the mounted cellular-revamp.tuning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-27 19:35:09 -04:00
co-authored by Claude Opus 5.5
parent 7041c947a9
commit 7273b157d6
33 changed files with 1241 additions and 97 deletions
+144 -9
View File
@@ -1,4 +1,4 @@
// ADR-0182 read-only admin portal. Keycloak sign-in (authorization code with PKCE), then the
// 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.
@@ -151,17 +151,20 @@ function signOut() {
}
class ApiError extends Error {
constructor(status, code) { super(code || `HTTP ${status}`); this.status = status; this.code = code; }
constructor(status, code, detail = {}) { super(code || `HTTP ${status}`); this.status = status; this.code = code; this.detail = detail; }
}
async function api(path, retry = true, method = 'GET') {
// `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 res = await fetch(path, { method, headers: { Authorization: `Bearer ${t}` }, cache: 'no-store' });
if (res.status === 401 && retry) { access = null; return api(path, false, method); }
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 code = null;
try { code = (await res.json()).error; } catch { /* plain text */ }
throw new ApiError(res.status, code);
let detail = {};
try { detail = await res.json(); } catch { /* plain text */ }
throw new ApiError(res.status, detail.error || (res.status === 413 ? 'too_large' : null), detail);
}
return res.json();
}
@@ -423,6 +426,7 @@ function amountInputs() {
const kindLabels = {
remove_cell: 'remove cell', grant_reserve: 'grant reserve', add_bubbles: 'add bubbles',
add_pool: 'add to pool', release_pool: 'release pool', spawn_wildlife: 'spawn wildlife',
adopt_tuning: 'adopt tuning',
};
// Admin commands (ADR-0182): queued now, applied by the region at its next ticks.
@@ -460,7 +464,8 @@ function commandsCard(region) {
const data = await api(`/api/regions/${region}/commands`);
history.replaceChildren(data.commands.length ? h('table', { class: 'compact' }, h('tbody', {}, data.commands.slice(0, 10).map((c) =>
h('tr', {}, h('td', { class: 'mono' }, `#${c.id}`), h('td', {}, kindLabels[c.kind] || c.kind,
c.count ? ` ×${c.count}` : '', c.kind === 'remove_cell' || c.kind === 'grant_reserve' ? ` ${c.target}` : ''),
c.count ? ` ×${c.count}` : '', c.kind === 'remove_cell' || c.kind === 'grant_reserve' ? ` ${c.target}` : '',
c.kind === 'adopt_tuning' ? ` revision ${c.target}` : ''),
h('td', {}, c.applied_tick ? h('span', { class: 'badge alive' }, `tick ${c.applied_tick}`) : h('span', { class: 'badge warn' }, 'pending')),
h('td', { class: 'muted', title: c.author || '' }, (c.author || '').split(' (')[0]))))) : h('p', { class: 'muted' }, 'No commands yet.'));
} catch (e) {
@@ -777,6 +782,135 @@ async function regionPage(region, params) {
stopPage = () => { clearTimeout(timer); window.removeEventListener('resize', onResize); };
}
// ---------- Tuning (schema 66) ----------
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.line ? `Line ${d.line}: ` : ''}${tuningErrors[d.kind] || d.kind}${d.key ? ` (${d.key})` : ''}`;
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_text') return 'The text must be plain ASCII.';
if (e.code === 'too_large') return 'The text is over 64 KiB.';
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);
}
async function tuningPage() {
const data = await api('/api/tuning');
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: 'small' });
const regionsBox = h('div', { class: 'muted' }, 'Loading…');
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');
let loadedText = '';
const load = (text, label) => { area.value = text; loadedText = text; source.textContent = label; note.textContent = ''; };
if (data.newest) load(data.newest.text, `Editing a copy of revision ${data.newest.revision}`);
else if (data.baseline) load(data.baseline.text, 'Editing a copy of the baseline file (no revisions yet)');
else load('', 'No baseline file and no revisions');
const say = (text, cls = 'muted') => { note.className = `small ${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 () => {
const ok = await check();
if (!ok) 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');
}
};
const revert = () => load(loadedText, source.textContent);
// Which rules each region runs now, from its live view.
(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('tr', {}, h('td', {}, h('a', { href: `#/regions/${region}` }, `Region ${region}`)),
h('td', {}, 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('td', { class: 'muted' }, `tick ${fmtInt(v.tick)}`));
} catch (e) {
return h('tr', {}, h('td', {}, `Region ${region}`), h('td', { class: 'muted', colspan: 2 }, `unavailable: ${e.code || e.message}`));
}
}));
regionsBox.replaceChildren(rows.length ? h('table', { class: 'compact' }, h('tbody', {}, rows)) : 'No regions configured.');
})();
const revisions = data.revisions.length ? h('table', { class: 'compact' }, h('tbody', {}, data.revisions.map((r) =>
h('tr', {},
h('td', { class: 'mono' }, `#${r.revision}`),
h('td', {}, h('div', {}, r.reason || h('span', { class: 'muted' }, 'no reason')),
h('div', { class: 'muted', title: r.author || '' }, `${(r.author || '').split(' (')[0]} · ${fmtAgo(r.created_at)}`)),
h('td', {}, 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('td', {}, h('button', {
onclick: async () => {
try { const t = await api(`/api/tuning/${r.revision}`); load(t.text, `Editing a copy of revision ${t.revision}`); } catch (e) { say(`Could not load: ${e.code || e.message}`, 'error'); }
},
}, 'Load')))))) : h('p', { class: 'muted' }, 'No revisions yet: regions run the rules they opened with.');
show(
h('div', { class: 'head' },
h('div', {}, h('h1', {}, 'Cellular tuning'), h('span', { class: 'muted' }, `World ${data.world} · rules 13 · every region adopts the same revision`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
h('div', { class: 'tuning-layout' },
h('div', { class: 'card' },
h('div', { class: 'head' }, source,
h('div', { class: 'tools' },
data.baseline ? h('button', { class: 'ghost', onclick: () => load(data.baseline.text, 'Editing a copy of the baseline file') }, 'Load baseline') : null,
h('button', { class: 'ghost', onclick: revert }, 'Revert'))),
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' },
h('div', { class: 'card' }, h('h2', {}, 'Regions'), regionsBox),
h('div', { class: 'card' }, h('h2', {}, 'Revisions'), revisions),
h('div', { class: 'card muted small' },
'The file format is the Git revamp tuning file (key = value, integers). A region adopts a revision at a tick recorded in its trace, so replay and recovery reproduce it. ',
'reproduction.safety_version cannot change live, and playtest.* keys only matter when a region opens.'))));
}
// ---------- Routing ----------
async function route() {
stopPage();
@@ -789,6 +923,7 @@ async function route() {
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) {