From 23ea24080e725ed99643e2c3bf2e5dbc7c1217c6 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 28 Oct 2026 12:09:54 -0400 Subject: [PATCH] feat(admin): guided tuning editor that sends only the changes 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 --- apps/evo-admin-api/portal/app.js | 356 ++++++++++++++---- apps/evo-admin-api/portal/style.css | 33 ++ docs/STATUS.md | 7 + .../adr/0182-admin-portal-and-world-tuning.md | 7 + include/evo/server/admin/admin_api.hpp | 4 + src/server/admin/admin_api.cpp | 99 +++++ tests/grant_broker_tests.cpp | 29 ++ 7 files changed, 464 insertions(+), 71 deletions(-) diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js index c087223..7605af5 100644 --- a/apps/evo-admin-api/portal/app.js +++ b/apps/evo-admin-api/portal/app.js @@ -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(' 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 ---------- diff --git a/apps/evo-admin-api/portal/style.css b/apps/evo-admin-api/portal/style.css index 3e15065..1fea817 100644 --- a/apps/evo-admin-api/portal/style.css +++ b/apps/evo-admin-api/portal/style.css @@ -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; } } diff --git a/docs/STATUS.md b/docs/STATUS.md index 268a0c0..418dae8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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 diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index cd99571..ade2b64 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -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` diff --git a/include/evo/server/admin/admin_api.hpp b/include/evo/server/admin/admin_api.hpp index c15e5d8..65ea0f5 100644 --- a/include/evo/server/admin/admin_api.hpp +++ b/include/evo/server/admin/admin_api.hpp @@ -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". diff --git a/src/server/admin/admin_api.cpp b/src/server/admin/admin_api.cpp index 8957377..2e62a8e 100644 --- a/src/server/admin/admin_api.cpp +++ b/src/server/admin/admin_api.cpp @@ -618,6 +618,70 @@ std::expected 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 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 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(); diff --git a/tests/grant_broker_tests.cpp b/tests/grant_broker_tests.cpp index 90c3ee3..502add5 100644 --- a/tests/grant_broker_tests.cpp +++ b/tests/grant_broker_tests.cpp @@ -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