feat(admin): guided tuning editor that sends only the changes
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 28s
Foundation / server-image (push) Successful in 4m48s
Foundation / image (push) Successful in 5m37s

DEV's ingress refuses request bodies over about 1 KB, so adopting a whole
revamp file (5 KB) failed with a 413 the portal misreported as the API's 64 KiB
limit. POST /api/tuning?base=baseline|REV now takes only changed `key = value`
lines, applies them to the baseline file or the newest revision (409 stale_base
for an older one), keeping its comments, then checks and stores as before.

The Tuning page becomes a guided editor: sections, a field per setting with its
unit, plain reading and comment, a changes list with Check and Apply (or Adopt
as is), and loading a past revision or the baseline as changes. The full-text
editor stays as Text mode and names a proxy refusal plainly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-28 12:09:54 -04:00
co-authored by Claude Opus 5.5
parent 8dedde454d
commit 23ea24080e
7 changed files with 464 additions and 71 deletions
+285 -71
View File
@@ -182,8 +182,12 @@ async function api(path, retry = true, method = 'GET', body = undefined) {
if (res.status === 401 && retry) { access = null; return api(path, false, method, body); }
if (!res.ok) {
let detail = {};
try { detail = await res.json(); } catch { /* plain text */ }
throw new ApiError(res.status, detail.error || (res.status === 413 ? 'too_large' : null), 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();
}
@@ -544,7 +548,8 @@ function schedulesBlock(region) {
// ---------- 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 key's note its trailing comment. tuning.version (the format) is left out.
// 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 = [];
@@ -556,8 +561,9 @@ function parseTuning(text) {
if (!m) continue;
const name = m[1].split('.')[0];
if (m[1] === 'tuning.version') { comments = []; continue; }
if (!groups.has(name)) groups.set(name, { name, about: comments.join(' '), settings: [] });
groups.get(name).settings.push({ key: m[1], value: m[2], note: m[3] || '' });
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()];
@@ -1340,7 +1346,7 @@ async function regionPage(region, params) {
};
}
// ---------- Tuning (schema 66) ----------
// ---------- 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',
@@ -1350,11 +1356,15 @@ const tuningErrors = {
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})` : ''}`;
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 text is over 64 KiB.';
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.
@@ -1368,23 +1378,272 @@ function selectLine(area, n) {
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 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 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');
// 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'; } })();
const say = (text, cls = 'muted') => { note.className = `small ${cls}`; note.textContent = text; };
// ----- 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);
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);
@@ -1398,8 +1657,7 @@ async function tuningPage() {
}
};
const adopt = async () => {
const ok = await check();
if (!ok) return;
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 {
@@ -1413,63 +1671,19 @@ async function tuningPage() {
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('div', { class: 'subtitle' }, `World ${data.world} · rules 13 · every region adopts the same revision`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
show(head,
h('div', { class: 'tuning-layout' },
h('div', { class: 'card' },
h('div', { class: 'head' }, source,
h('div', { class: 'card-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'))),
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' },
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,
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.'))));
h('div', { class: 'side' }, ...sideCards)));
}
// ---------- Routing ----------
+33
View File
@@ -588,3 +588,36 @@ textarea.tuning {
textarea.tuning:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
.action { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 12px; }
.action .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
/* Guided tuning editor: sections, fields, changes. */
.tuning-guided { display: grid; grid-template-columns: 230px minmax(0, 1fr) 380px; gap: 16px; align-items: start; }
@media (max-width: 1250px) { .tuning-guided { grid-template-columns: 210px minmax(0, 1fr); } .tuning-guided > .side { grid-column: 1 / -1; } }
@media (max-width: 800px) { .tuning-guided { grid-template-columns: minmax(0, 1fr); } }
.tuning-guided .side { display: flex; flex-direction: column; gap: 14px; }
.tuning-guided .side .card + .card { margin-top: 0; }
.nav-card { position: sticky; top: 72px; padding: 12px; }
.section-nav { display: flex; flex-direction: column; gap: 2px; margin-top: 10px; }
.section-link { display: flex; align-items: center; gap: 8px; text-align: left; border: 0; background: transparent; color: var(--text); padding: 7px 10px; border-radius: var(--radius-sm); font-weight: 500; }
.section-link .grow { flex: 1; }
.section-link:hover { background: var(--panel-3); color: var(--text); }
.section-link.on { background: var(--accent-soft); color: var(--accent); }
.tuning-section + .tuning-section { margin-top: 14px; }
.field-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(220px, 300px); gap: 8px 20px; padding: 12px 0; border-top: 1px solid var(--line); align-items: start; }
.field-row.changed .field-label { color: var(--accent); }
.field-row.changed .input-unit input, .field-row.changed .input-unit select { border-color: var(--accent); }
.field-row.bad .input-unit input { border-color: var(--bad); }
.field-label { font-weight: 600; }
.field-key { color: var(--faint); font-size: 11.5px; margin-top: 1px; overflow-wrap: anywhere; }
.field-note { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
.field-input { display: flex; flex-direction: column; gap: 3px; }
.input-unit { display: flex; align-items: center; gap: 6px; }
.input-unit input, .input-unit select { flex: 1; min-width: 0; font-family: var(--mono); font-size: 13px; text-align: right; }
.input-unit select { text-align: left; font-family: inherit; }
.input-unit .unit { color: var(--muted); font-size: 12px; white-space: nowrap; min-width: 48px; }
.gloss { color: var(--muted); font-size: 12px; text-align: right; padding-right: 86px; min-height: 0; }
.gloss:empty, .field-problem:empty { display: none; }
.field-problem { font-size: 12px; text-align: right; padding-right: 86px; color: var(--accent); }
.field-row.bad .field-problem { color: var(--bad); }
.changes-card { position: sticky; top: 72px; }
.changes-card .wide { margin-top: 10px; }
@media (max-width: 1250px) { .changes-card, .nav-card { position: static; } }
+7
View File
@@ -1,5 +1,12 @@
# Project status and next steps
## Guided tuning editor - 2026-10-28
The Tuning page is a guided editor: pick a section, edit a setting's value (units and plain
readings shown), review the changes and apply. Only the changed values are sent and applied to
the newest revision on the server, which keeps the file's comments and refuses a stale base;
the whole-file text editor remains as Text mode.
## Energy cycle - 2026-10-28
Energy now cycles like matter: the heat cells produce (upkeep, motion, growth, feeding and
@@ -263,6 +263,13 @@ Sections 1-2 are delivered without a new owner format or opening, so running rul
the line, key and kind of a problem, Adopt stores the revision with a reason, the revision
list shows how many regions adopted each, and each region shows which revision its live
rules match (`rules_sha256` in the region view).
- **Guided editor (2026-10-28).** The Tuning page edits by section: each setting as a field
with its unit, a reading in plain units and its comment, changed values listed against the
base. `POST /api/tuning?base=baseline|REV` takes only the changed `key = value` lines and
applies them to the baseline file or to revision REV, which must be the newest (409
`stale_base` otherwise), keeping the base's comments; the result is checked and stored as
any full text. DEV's ingress admits request bodies of about 1 KB, below a whole revamp
file, so the full-text editor (kept as Text mode) reports that proxy refusal plainly.
- **Region page (2026-10-28).** The region view also carries the rules-13 drip
(`drip`: interval, energy and matter bubble caps) and, over every life and deposit whatever
the listing limits, `counts` (players, wildlife, patches, pools, bubbles) and `totals`
+4
View File
@@ -51,6 +51,10 @@
// revamp file format): checked, then stored as a new
// revision that every region of the world adopts at its
// next tick (check=1: checked only, nothing stored)
// POST /api/tuning?base=baseline|REV[&check=1][&reason=R] the body holds only changed
// `key = value` lines, applied to the baseline file or to
// revision REV (which must be the newest: 409 stale_base),
// keeping its comments; then as above
namespace evo::server::admin {
struct AdminAsset {
std::string path; // "/index.html", ...; "/" serves "/index.html".
+99
View File
@@ -618,6 +618,70 @@ std::expected<CheckedTuning, OpsResponse> check_tuning(std::string_view text) {
return std::unexpected{error(503, "unavailable")};
return CheckedTuning{rules, *digest};
}
std::string_view trim_blank(std::string_view text) {
while (!text.empty() && (text.front() == ' ' || text.front() == '\t'))
text.remove_prefix(1);
while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r'))
text.remove_suffix(1);
return text;
}
// The guided editor's changes applied to a base text: each `key = value` line (blank and `#`
// lines ignored) replaces the value on that key's line in `base`, keeping its spacing and
// comment, or is appended when the base has no such line. The parser checks the result.
std::expected<std::string, OpsResponse> apply_tuning_changes(std::string_view base,
std::string_view changes) {
const auto key_char = [](char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '.';
};
const auto value_char = [](char ch) {
return (ch >= '0' && ch <= '9') || ch == '_' || ch == '-';
};
std::string text(base);
std::vector<std::string_view> seen;
std::size_t line_number = 0;
for (std::size_t from = 0; from < changes.size();) {
const auto end = std::min(changes.find('\n', from), changes.size());
const auto line = trim_blank(changes.substr(from, end - from));
from = end + 1;
++line_number;
if (line.empty() || line.front() == '#')
continue;
const auto equals = line.find('=');
const auto key = trim_blank(line.substr(0, equals));
const auto value = equals == std::string_view::npos ? std::string_view{}
: trim_blank(line.substr(equals + 1));
if (key.empty() || value.empty() || !std::ranges::all_of(key, key_char) ||
!std::ranges::all_of(value, value_char) || std::ranges::contains(seen, key))
return std::unexpected{json(400, "{\"error\":\"invalid_change\",\"line\":" +
std::to_string(line_number) + "}\n")};
seen.push_back(key);
bool replaced = false;
for (std::size_t at = 0; at < text.size() && !replaced;) {
const auto stop = std::min(text.find('\n', at), text.size());
const std::string_view current{text.data() + at, stop - at};
const auto eq = current.find('=');
const auto name = trim_blank(current.substr(0, eq));
if (eq != std::string_view::npos && !name.starts_with('#') && name == key) {
auto first = eq + 1;
while (first < current.size() && (current[first] == ' ' || current[first] == '\t'))
++first;
auto last = std::min(current.find('#', first), current.size());
while (last > first && (current[last - 1] == ' ' || current[last - 1] == '\t' ||
current[last - 1] == '\r'))
--last;
text.replace(at + first, last - first, value);
replaced = true;
}
at = stop + 1;
}
if (!replaced) {
if (!text.empty() && text.back() != '\n')
text.push_back('\n');
text.append(key).append(" = ").append(value).push_back('\n');
}
}
return text;
}
} // namespace
OpsResponse AdminApi::commands(std::uint64_t region) {
@@ -845,6 +909,41 @@ OpsResponse AdminApi::tuning_text(std::uint64_t revision) {
OpsResponse AdminApi::set_tuning(std::string_view query_text, std::string_view text,
const broker::AccessTokenClaims& admin) {
// With `base`, the body holds only changed lines (the guided editor), applied to the
// baseline file or to the newest revision, so the whole file never travels (a proxy in
// front may bound request bodies far below max_api_body_bytes). A base revision that is no
// longer the newest is refused rather than silently overwriting a later revision.
std::string merged;
if (const auto base = query_value(query_text, "base")) {
std::string base_text;
if (*base == "baseline") {
if (config_.baseline_tuning.empty())
return error(400, "no_baseline");
base_text = config_.baseline_tuning;
} else {
const auto wanted = number(*base);
if (!wanted || *wanted == 0)
return error(400, "bad_base");
const auto newest =
query("SELECT revision, text FROM evolution.admin_tuning_text_v1($1, 0)",
{std::to_string(config_.world)});
if (!newest)
return error(503, "unavailable");
if (newest->empty() || at(newest->front(), 0) != std::to_string(*wanted))
return json(409, "{\"error\":\"stale_base\",\"newest\":" +
(newest->empty() ? std::string{"null"}
: text_value(at(newest->front(), 0))) +
"}\n");
base_text = at(newest->front(), 1).value_or("");
}
auto applied = apply_tuning_changes(base_text, text);
if (!applied)
return applied.error();
merged = std::move(*applied);
text = merged;
} else if (query_text.find("base=") != std::string_view::npos) {
return error(400, "bad_base");
}
const auto checked = check_tuning(text);
if (!checked)
return checked.error();
+29
View File
@@ -748,6 +748,35 @@ void admin_api_tests(const Realm& realm) {
CHECK(
must(JsonValue::parse(read("/api/tuning").body)).member("revisions")->array()->size() ==
1);
// The guided editor sends only changes against a base: the newest revision or the
// baseline file. Values are replaced in place (comments kept), absent keys appended,
// and a base that is no longer the newest is refused.
const auto back = must(JsonValue::parse(
send("/api/tuning?check=1&base=" + revision, "spent.drip_interval_ticks = 20\n").body));
CHECK(back.member("rules_sha256")->string() == digest);
CHECK(send("/api/tuning?check=1&base=baseline", "").status == 200);
CHECK(send("/api/tuning?check=1&base=999999", "").status == 409);
CHECK(send("/api/tuning?check=1&base=x", "").status == 400);
CHECK(send("/api/tuning?check=1&base=baseline", "spent.drip_interval_ticks = 1 # x\n")
.status == 400);
CHECK(send("/api/tuning?check=1&base=baseline",
"spent.drip_absorb = 1\nspent.drip_absorb = 0\n")
.status == 400);
const auto appended = must(
JsonValue::parse(send("/api/tuning?check=1&base=baseline", "no.such_key = 1\n").body));
CHECK(appended.member("kind")->string() == "unknown_key");
const auto guided = must(JsonValue::parse(
send("/api/tuning?reason=guided&base=" + revision, "spent.drip_interval_ticks = 30\n")
.body));
const auto guided_revision = std::string(must(guided.member("revision")->string()));
auto expected = changed;
expected.replace(expected.find("spent.drip_interval_ticks = 40"), 30,
"spent.drip_interval_ticks = 30");
CHECK(must(JsonValue::parse(read("/api/tuning/" + guided_revision).body))
.member("text")
->string() == expected);
CHECK(send("/api/tuning?check=1&base=" + revision, "").status == 409);
}
// Accounts (schema 64): control claims recorded alice's sessions; a ban refuses grants