Update frontend/dist/assets/boot.js
#2
by pmrinal2005 - opened
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182835 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151163 unmodified lines1201211221231241251261271281295 unmodified lines1351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254263 unmodified lines430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473/* ============================================================ELYSIUM — boot.js------------------------------------------------------------Wires UI ↔ /api/turn. Critical guarantees:• The JSON envelope returned by the model is NEVER renderedas raw text anywhere on screen. It is parsed and ROUTED to:hypergraph_delta → canvas nodes / edgescouncil_deliberation → council overlay + TTS audioui_directives → bioluminescence pulses, focus, alertdirect_answer → optional small toastmetrics → bottom stats bar + legend densities• File uploads are previewed above the textbox with X removaland only sent when the user presses Send.• Every DOM lookup is defensive — a single missing elementnever throws an unhandled "Cannot read properties of null".This was the root cause of the previous "classList of null"toast that appeared on top.============================================================ */(() => {'use strict';// ── Safe element accessor (logs once if missing) ──const _missing = new Set();const $ = (id) => {const el = document.getElementById(id);if (!el && !_missing.has(id)) {_missing.add(id);console.warn('[elysium] missing element:', id);}return el;};// Safe wrappers — no-op if element missingconst addCls = (el, c) => { if (el && el.classList) el.classList.add(c); };const rmCls = (el, c) => { if (el && el.classList) el.classList.remove(c); };// ── Toast helper (always returns; never throws) ──window.toast = function (msg, kind = '') {const host = $('toasts');if (!host) { console.log('[toast]', msg); return; }const t = document.createElement('div');t.className = 'toast ' + (kind || '');t.textContent = String(msg).slice(0, 280);host.appendChild(t);setTimeout(() => { try { t.remove(); } catch {} }, 5200);};function escapeHtml(s) {return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}// ── DOM references (all may be null — handled defensively) ──const input = $('q-input');const send = $('q-send');const fileEl = $('q-file');const upBtn = $('q-upload');const strip = $('attach-strip');const seedHint = $('seed-hint');/* =========================================================PART A — FILE ATTACHMENTS (preview above textbox, max 2)========================================================= */const MAX_FILES = 2;const MAX_BYTES = 12 * 1024 * 1024;let attachments = []; // [{file, name, kind:'image'|'pdf', previewUrl}]function renderStrip() {if (!strip) return;if (attachments.length === 0) {addCls(strip, 'hidden');strip.innerHTML = '';return;}rmCls(strip, 'hidden');const hint = attachments.length < MAX_FILES? `<span class="attach-hint">${MAX_FILES - attachments.length} more allowed</span>`: `<span class="attach-hint">max ${MAX_FILES} reached</span>`;strip.innerHTML = attachments.map((a, i) => {5 unmodified lines<div class="preview-tile" data-i="${i}">${preview}<span class="nm" title="${escapeHtml(a.name)}">${escapeHtml(a.name)} · ${sizeKb}KB</span><button class="x" data-i="${i}" title="Remove attachment" aria-label="Remove">×</button></div>`;}).join('') + hint;// Wire remove buttonsstrip.querySelectorAll('.x').forEach(b => {b.onclick = (ev) => {ev.preventDefault();ev.stopPropagation();const i = +b.dataset.i;const removed = attachments.splice(i, 1)[0];if (removed && removed.previewUrl) {try { URL.revokeObjectURL(removed.previewUrl); } catch {}}renderStrip();};});}function addFiles(files) {if (!files) return;const list = Array.from(files);for (const f of list) {if (attachments.length >= MAX_FILES) {window.toast(`Max ${MAX_FILES} attachments allowed`, 'warn');3 unmodified linesconst isImg = mime.startsWith('image/');const isPdf = mime === 'application/pdf' || f.name.toLowerCase().endsWith('.pdf');if (!isImg && !isPdf) {window.toast(`Unsupported: ${f.name} (only images & PDFs)`, 'warn');continue;}if (f.size > MAX_BYTES) {window.toast(`${f.name} is too large (>12MB)`, 'warn');continue;}5 unmodified lines});}renderStrip();if (fileEl) fileEl.value = ''; // allow re-selecting same file after removal}if (fileEl) {fileEl.addEventListener('change', e => addFiles(e.target.files));}// Optional polish: drag-and-drop files anywhere on the window['dragenter', 'dragover'].forEach(ev =>window.addEventListener(ev, e => { e.preventDefault(); }));window.addEventListener('drop', e => {if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;e.preventDefault();addFiles(e.dataTransfer.files);});/* =========================================================PART B — BUSY LOCK (disables input while model thinks)========================================================= */function setBusy(b) {document.body.dataset.busy = b ? '1' : '0';if (input) input.disabled = b;if (send) send.disabled = b;if (b) {if (send) send.classList.add('loading');if (upBtn) upBtn.classList.add('disabled');if (fileEl) fileEl.disabled = true;if (input) {input.dataset.prev = input.placeholder || '';input.placeholder = 'Council deliberating…';}} else {if (send) send.classList.remove('loading');if (upBtn) upBtn.classList.remove('disabled');if (fileEl) fileEl.disabled = false;if (input) {input.placeholder = input.dataset.prev || 'Speak to your civilization seed…';}}}/* =========================================================PART C — RESTORE existing civilization on page load========================================================= */async function restore() {try {const h = await ElysiumAPI.hypergraph();(h.nodes || []).forEach(n => {if (n.node_id !== 'CORE' && typeof window.elysiumAddNode === 'function') {window.elysiumAddNode(n);}});(h.edges || []).forEach(e => {if (typeof window.elysiumAddEdge === 'function') window.elysiumAddEdge(e);});if ((h.nodes || []).length > 1) addCls(seedHint, 'hidden');updateLegend();updateMetrics({nodes: h.node_count || (h.nodes || []).length || 1,edges: h.edge_count || (h.edges || []).length || 0,council_active: 0,knowledge_growth: 0,civilization_age_min: 0,mycelium_density_pct: h.node_count? Math.round(Math.min(1, (h.edge_count || 0) / Math.max(1, h.node_count * 1.4)) * 100): 0,coherence_pct: 70,});} catch (e) {console.warn('[restore] failed', e);updateLegend();}}restore();/* =========================================================PART D — SUBMIT a turn========================================================= */async function submit() {if (document.body.dataset.busy === '1') return;const text = input ? input.value.trim() : '';if (!text && attachments.length === 0) return;setBusy(true);addCls(seedHint, 'hidden');if (input) input.value = '';const files = attachments.map(a => a.file);// Clear preview strip (response will show separate "Analyzed:" toast)attachments.forEach(a => {if (a.previewUrl) { try { URL.revokeObjectURL(a.previewUrl); } catch {} }});attachments = [];renderStrip();try {const data = await ElysiumAPI.turn(text, files);handleResponse(data || {});} catch (e) {console.error('[submit] failed', e);window.toast('Inference failed: ' + (e.message || e), 'error');} finally {setBusy(false);}}if (send) send.onclick = submit;if (input) {input.addEventListener('keydown', e => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault();submit();}});}/* =========================================================PART E — HANDLE RESPONSEParses the JSON envelope and routes it. NEVER renders rawJSON to the canvas or any visible element.========================================================= */function handleResponse(payload) {// payload schema: { user_msg, elysium_response, _runtime }let resp = {};let rt = {};try {resp = payload.elysium_response || {};rt = payload._runtime || {};} catch (e) {console.error('[handleResponse] malformed payload', e);window.toast('Malformed response from model', 'error');return;}// 0. Attachment errors (server-side validation failures) → toastsafeArr(rt.attachment_errors).forEach(e =>window.toast(`📎 ${e.name}: ${e.error}`, 'warn'));// 1. Hypergraph delta → canvas (NODES then EDGES; build parent map)const delta = resp.hypergraph_delta || {};const edgesAdded = safeArr(delta.edges_added);const nodesAdded = safeArr(delta.nodes_added);// Build a parent-hint map: for each new node, what's its closest source// (used so spawn animation grows OUT FROM the parent, not the centre).const parentHint = {};edgesAdded.forEach(e => {if (!e) return;if (e.target_node_id && !parentHint[e.target_node_id]) {parentHint[e.target_node_id] = e.source_node_id;}if (e.source_node_id && !parentHint[e.source_node_id]) {// weaker hint (reverse direction) — only if not setif (!parentHint[e.source_node_id]) {parentHint[e.source_node_id] = e.target_node_id;}}});nodesAdded.forEach(n => {if (!n || !n.node_id) return;try {if (typeof window.elysiumAddNode === 'function') {window.elysiumAddNode(n, parentHint[n.node_id]);}} catch (err) {console.warn('[handleResponse] addNode failed', n, err);}});edgesAdded.forEach(e => {if (!e || !e.source_node_id || !e.target_node_id) return;try {if (typeof window.elysiumAddEdge === 'function') window.elysiumAddEdge(e);} catch (err) {console.warn('[handleResponse] addEdge failed', e, err);}});// Apply node updates (fields_changed)safeArr(delta.nodes_updated).forEach(u => {if (!u || !u.node_id) return;const node = window.elysiumGetNode && window.elysiumGetNode(u.node_id);if (node && u.fields_changed) {Object.assign(node.payload || (node.payload = {}), u.fields_changed);}});// 2. UI directives — pulses, focus, alertconst ui = resp.ui_directives || {};safeArr(ui.bioluminescence_pulse_nodes).forEach(id => {if (typeof window.elysiumPulse === 'function') window.elysiumPulse(id, 1600);});document.body.dataset.alert = ui.alert_level || 'CALM';if (ui.camera_focus_node_id && typeof window.elysiumFocus === 'function') {if (typeof window.elysiumPulse === 'function')window.elysiumPulse(ui.camera_focus_node_id, 1800);setTimeout(() => {try { window.elysiumFocus(ui.camera_focus_node_id); } catch {}}, 380);}// 3. Council overlay + TTStry {if (typeof window.renderCouncil === 'function') {window.renderCouncil(resp, rt);}} catch (e) {console.error('[council] render failed', e);}// 4. Metrics bar (REAL civilization metrics)updateMetrics(rt.metrics || {});// 5. Agent count badgeconst ag = safeArr(resp.council_deliberation && resp.council_deliberation.agent_outputs).length;const badge = $('agent-count');if (badge) badge.textContent = `+${ag}`;// 6. Legend live update (counts per type)updateLegend();// 7. Tool toastssafeArr(rt.tool_results).forEach(tr => {if (!tr) return;const ok = tr.result && !tr.result.error;window.toast(`🔧 ${tr.tool_name || 'tool'}: ${ok ? 'ok' : (tr.result?.error || 'offline')}`,ok ? 'info' : 'warn');});// 8. Direct answer toast — ONLY when no council (otherwise it's already// shown in the overlay synthesis). NEVER dumps raw JSON.if (!ag && resp.direct_answer && typeof resp.direct_answer === 'string') {window.toast(resp.direct_answer.slice(0, 240));}// 9. Confirm attachment analysisconst processed = safeArr(rt.attachments_processed);if (processed.length) {const names = processed.map(a => a && a.name).filter(Boolean).join(', ');if (names) window.toast(`📎 Analyzed: ${names}`, 'info');}}function safeArr(x) { return Array.isArray(x) ? x : []; }/* =========================================================PART F — Metrics & Legend updates========================================================= */function updateMetrics(m) {m = m || {};const nodes = m.nodes ?? (window.ELYSIUM ? window.ELYSIUM.nodes.size : 1);const edges = m.edges ?? (window.ELYSIUM ? window.ELYSIUM.edges.length : 0);setText('s-nodes', nodes);setText('s-edges', edges);setText('s-council', m.council_active ?? 0);setText('s-growth', m.knowledge_growth ?? 0);setText('s-age', m.civilization_age_min ?? 0);setText('m-density', (m.mycelium_density_pct ?? 0) + '%');setText('m-coherence', (m.coherence_pct ?? 70) + '%');}function setText(id, value) {const el = $(id);if (el) el.textContent = value;}function updateLegend() {const host = $('legend-items');if (!host || !window.ELYSIUM) return;const counts = {};window.ELYSIUM.nodes.forEach(n => {const t = n.type || 'CONCEPT';counts[t] = (counts[t] || 0) + 1;});const order = ['CORE','CIVILIZATION','DOMAIN','AGENT','TOOL','PROJECT','LIFE_EVENT','EMOTION','PERSON','VALUE','MEMORY','FACT','CONCEPT','QUERY'];const seen = new Set();const parts = [];const colorFn = window.colorFor || (() => '#a76bff');order.forEach(t => {if (!counts[t]) return;seen.add(t);const c = colorFn(t);parts.push(`<div class="legend-item" data-type="${t}"><span class="dot" style="background:${c};color:${c}"></span>3 unmodified lines});Object.keys(counts).forEach(t => {if (seen.has(t)) return;const c = colorFn(t);parts.push(`<div class="legend-item" data-type="${t}"><span class="dot" style="background:${c};color:${c}"></span><span class="badge">${counts[t]}</span><span class="lbl">${t.replace(/_/g, ' ').toLowerCase()}</span></div>`);});host.innerHTML = parts.join('');// Wire legend filter clickshost.querySelectorAll('.legend-item').forEach(el => {el.onclick = () => {const t = el.dataset.type;if (typeof window.elysiumFilterType === 'function') window.elysiumFilterType(t);const active = window.ELYSIUM && window.ELYSIUM.filterType;host.querySelectorAll('.legend-item').forEach(x => {x.style.opacity = active? (x.dataset.type === active ? '1' : '.45'): '1';});};});}/* =========================================================PART G — RI Analysis button (fit + summary)========================================================= */const ri = $('ri-analysis');if (ri) {ri.onclick = () => {if (typeof window.elysiumFitAll === 'function') window.elysiumFitAll();const n = window.ELYSIUM ? window.ELYSIUM.nodes.size : 0;const e = window.ELYSIUM ? window.ELYSIUM.edges.length : 0;window.toast(`🔍 Civilization snapshot: ${n} nodes · ${e} threads`, 'info');};}// Expose for debugging (read-only-ish)window.elysiumUpdateLegend = updateLegend;window.elysiumUpdateMetrics = updateMetrics;})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869705 unmodified lines767778798081828384858687888990919293949596973 unmodified lines1011021031041051061071081091105 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263 unmodified lines330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366/* Main app boot — wires UI ↔ /api/turn.FIXES vs previous build:• NEVER renders raw JSON anywhere. `direct_answer` is sanitised beforetoasting — anything that looks like JSON, looks like a <think> tag,or exceeds 240 chars is silently dropped.• Hard null-guards around every DOM lookup inside handleResponse so apartial backend response can never throw "cannot read classList of null".• Civilization map (minimap) is now refreshed on every turn via the`_runtime.civilization_map` snapshot.• Attachment preview strip shows above input with X-cancel — preserved& verified to live on /attach-strip with file metadata + thumbnail.• Busy lock prevents double-sends; stuck "Inference failed" toasts nolonger fire because parse errors are caught server-side.*/(() => {const $ = (id) => document.getElementById(id);const input = $('q-input');const send = $('q-send');const fileEl = $('q-file');const upBtn = $('q-upload');const strip = $('attach-strip');const seedHint = $('seed-hint');// ── Toast helper ──window.toast = function (msg, kind = '') {if (msg == null) return;const text = String(msg).trim();if (!text) return;const t = document.createElement('div');t.className = 'toast ' + kind;t.textContent = text.length > 240 ? text.slice(0, 237) + '…' : text;const host = $('toasts');if (!host) return;host.appendChild(t);setTimeout(() => t.remove(), 5200);};// ── direct_answer sanitiser ── (TASK 1: never display JSON on top)function safeDirectAnswer(s) {if (!s) return '';const text = String(s).trim();if (!text) return '';// Looks like JSON? (starts with { or [, or contains "schema_version")if (/^[\{\[]/.test(text)) return '';if (/schema_version|hypergraph_delta|council_deliberation/.test(text)) return '';// Contains <think> or other XML-like tags? drop.if (/<\s*\/?\s*(think|reasoning|tool|json)\b/i.test(text)) return '';// Excessively long (probably an error dump)if (text.length > 320) return '';return text;}// ── File attachment state (max 2) ── TASK 2const MAX_FILES = 2;let attachments = [];function renderStrip() {if (!strip) return;if (attachments.length === 0) {strip.classList.add('hidden');strip.innerHTML = '';return;}strip.classList.remove('hidden');const hintHtml = attachments.length < MAX_FILES? `<span class="attach-hint">${MAX_FILES - attachments.length} more allowed</span>`: `<span class="attach-hint">max ${MAX_FILES} reached</span>`;strip.innerHTML = attachments.map((a, i) => {5 unmodified lines<div class="preview-tile" data-i="${i}">${preview}<span class="nm" title="${escapeHtml(a.name)}">${escapeHtml(a.name)} · ${sizeKb}KB</span><button class="x" data-i="${i}" title="Remove">×</button></div>`;}).join('') + hintHtml;strip.querySelectorAll('.x').forEach(b => {b.onclick = (ev) => {ev.stopPropagation();const i = +b.dataset.i;const removed = attachments.splice(i, 1)[0];if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);renderStrip();};});}function addFiles(files) {const list = Array.from(files || []);for (const f of list) {if (attachments.length >= MAX_FILES) {window.toast(`Max ${MAX_FILES} attachments allowed`, 'warn');3 unmodified linesconst isImg = mime.startsWith('image/');const isPdf = mime === 'application/pdf' || f.name.toLowerCase().endsWith('.pdf');if (!isImg && !isPdf) {window.toast(`Unsupported file: ${f.name} (only images & PDFs)`, 'warn');continue;}if (f.size > 12 * 1024 * 1024) {window.toast(`${f.name} is too large (>12MB)`, 'warn');continue;}5 unmodified lines});}renderStrip();if (fileEl) fileEl.value = '';}if (fileEl) fileEl.addEventListener('change', e => addFiles(e.target.files));// Drag-and-drop on whole window['dragenter', 'dragover'].forEach(ev =>window.addEventListener(ev, e => { e.preventDefault(); }));window.addEventListener('drop', e => {if (!e.dataTransfer || !e.dataTransfer.files.length) return;e.preventDefault();addFiles(e.dataTransfer.files);});// ── Busy lock ──function setBusy(b) {document.body.dataset.busy = b ? '1' : '0';if (input) input.disabled = b;if (send) send.disabled = b;if (b) {send?.classList.add('loading');upBtn?.classList.add('disabled');if (fileEl) fileEl.disabled = true;if (input) {input.dataset.prev = input.placeholder;input.placeholder = 'Council deliberating…';}} else {send?.classList.remove('loading');upBtn?.classList.remove('disabled');if (fileEl) fileEl.disabled = false;if (input) input.placeholder = input.dataset.prev || 'Speak to your civilization seed…';}}// ── Restore civilization on load ──async function restore() {try {const h = await window.ElysiumAPI.hypergraph();(h.nodes || []).forEach(n => {if (n.node_id !== 'CORE') window.elysiumAddNode(n);});(h.edges || []).forEach(e => window.elysiumAddEdge(e));if ((h.nodes || []).length > 0) seedHint?.classList.add('hidden');updateLegend();updateMetrics({nodes: h.node_count, edges: h.edge_count,council_active: 0, knowledge_growth: 0,civilization_age_min: 0,mycelium_density_pct: h.node_count? Math.round(Math.min(1, h.edge_count / Math.max(1, h.node_count * 1.4)) * 100): 0,coherence_pct: 70,});} catch (e) {// offline first boot — fine}}restore();// ── SUBMIT ──async function submit() {if (document.body.dataset.busy === '1') return;if (!input) return;const text = input.value.trim();if (!text && attachments.length === 0) return;setBusy(true);seedHint?.classList.add('hidden');input.value = '';const files = attachments.map(a => a.file);attachments.forEach(a => a.previewUrl && URL.revokeObjectURL(a.previewUrl));attachments = [];renderStrip();try {const data = await window.ElysiumAPI.turn(text, files);handleResponse(data);} catch (e) {window.toast('Network error: ' + (e?.message || 'unknown'), 'error');} finally {setBusy(false);}}send?.addEventListener('click', submit);input?.addEventListener('keydown', e => {if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); }});// ── HANDLE MODEL RESPONSE ── (TASK 1: route JSON to features, never display raw)function handleResponse(payload) {payload = payload || {};const resp = payload.elysium_response || {};const rt = payload._runtime || {};// 0. Attachment errors → toast(rt.attachment_errors || []).forEach(e =>window.toast(`📎 ${e.name}: ${e.error}`, 'warn'));// 1. Hypergraph delta → canvasconst delta = resp.hypergraph_delta || {};const nodesAdded = delta.nodes_added || [];const edgesAdded = delta.edges_added || [];nodesAdded.forEach(n => {// Find a parent hint: first edge touching this nodelet parent = null;for (const e of edgesAdded) {if (e.target_node_id === n.node_id) { parent = e.source_node_id; break; }if (e.source_node_id === n.node_id) { parent = e.target_node_id; break; }}try { window.elysiumAddNode(n, parent); } catch (err) { console.warn('addNode failed', err); }});edgesAdded.forEach(e => {try { window.elysiumAddEdge(e); } catch (err) { console.warn('addEdge failed', err); }});// 2. UI directivesconst ui = resp.ui_directives || {};(ui.bioluminescence_pulse_nodes || []).forEach(id => {try { window.elysiumPulse(id, 1500); } catch (_) {}});document.body.dataset.alert = ui.alert_level || 'CALM';if (ui.camera_focus_node_id) {try {window.elysiumPulse(ui.camera_focus_node_id, 1800);setTimeout(() => window.elysiumFocus(ui.camera_focus_node_id), 350);} catch (_) {}}// 3. Council overlay + TTS (null-safe)try { window.renderCouncil?.(resp, rt); } catch (err) { console.warn('renderCouncil failed', err); }// 4. Metrics barupdateMetrics(rt.metrics || {});// 5. Agent count badgeconst ag = (resp.council_deliberation?.agent_outputs || []).length;const agBadge = $('agent-count');if (agBadge) agBadge.textContent = `+${ag}`;// 6. Legend live updateupdateLegend();// 7. Tool toasts(rt.tool_results || []).forEach(tr => {const ok = tr.result && !tr.result.error;window.toast(`🔧 ${tr.tool_name}: ${ok ? 'ok' : (tr.result?.error || 'offline')}`,ok ? 'info' : 'warn');});// 8. Direct answer toast — STRICTLY sanitised. Never raw JSON. Never errors.if (!ag) {const safe = safeDirectAnswer(resp.direct_answer);if (safe) window.toast(safe);}// 9. Attachment processed confirmationif ((rt.attachments_processed || []).length) {const names = rt.attachments_processed.map(a => a.name).join(', ');window.toast(`📎 Analyzed: ${names}`, 'info');}// 10. Civilization map sync (TASK 4) — frontend already has the nodes from// hypergraph_delta; this verifies counts match backend truth.if (rt.civilization_map) {// No reassignment of positions — the canvas owns layout. We only ensure// that any backend-side node missing from the canvas (e.g. restored// across reload) gets added.(rt.civilization_map.nodes || []).forEach(n => {if (!window.ELYSIUM?.nodes.has(n.node_id) && n.node_id !== 'CORE') {try { window.elysiumAddNode({node_id: n.node_id, label: n.label, node_type: n.type,}); } catch (_) {}}});}}function updateMetrics(m) {m = m || {};const set = (id, v) => { const el = $(id); if (el) el.textContent = v; };set('s-nodes', (m.nodes ?? window.ELYSIUM?.nodes.size ?? 1));set('s-edges', (m.edges ?? window.ELYSIUM?.edges.length ?? 0));set('s-council',(m.council_active ?? 0));set('s-growth', (m.knowledge_growth ?? 0));set('s-age', (m.civilization_age_min ?? 0));set('m-density', (m.mycelium_density_pct ?? 0) + '%');set('m-coherence',(m.coherence_pct ?? 70) + '%');}function updateLegend() {const host = $('legend-items');if (!host || !window.ELYSIUM) return;const counts = {};window.ELYSIUM.nodes.forEach(n => counts[n.type] = (counts[n.type] || 0) + 1);const order = ['CORE','CIVILIZATION','DOMAIN','AGENT','TOOL','PROJECT','LIFE_EVENT','EMOTION','PERSON','VALUE','MEMORY','FACT','CONCEPT','QUERY'];const seen = new Set();const parts = [];order.filter(t => counts[t] && !seen.has(t)).forEach(t => {seen.add(t);const c = window.colorFor(t);parts.push(`<div class="legend-item" data-type="${t}"><span class="dot" style="background:${c};color:${c}"></span>3 unmodified lines});Object.keys(counts).forEach(t => {if (seen.has(t)) return;const c = window.colorFor(t);parts.push(`<div class="legend-item" data-type="${t}"><span class="dot" style="background:${c};color:${c}"></span><span class="badge">${counts[t]}</span><span class="lbl">${t.replace(/_/g, ' ').toLowerCase()}</span></div>`);});host.innerHTML = parts.join('');host.querySelectorAll('.legend-item').forEach(el => {el.onclick = () => {const t = el.dataset.type;window.elysiumFilterType?.(t);host.querySelectorAll('.legend-item').forEach(x =>x.style.opacity = window.ELYSIUM.filterType? (x.dataset.type === window.ELYSIUM.filterType ? '1' : '.45'): '1');};});}// RI Analysis$('ri-analysis')?.addEventListener('click', () => {window.elysiumFitAll?.();const n = window.ELYSIUM?.nodes.size ?? 0;const e = window.ELYSIUM?.edges.length ?? 0;window.toast(`🔍 Civilization snapshot: ${n} nodes · ${e} threads`, 'info');});function escapeHtml(s) {return String(s || '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}})();
frontend/dist/assets/boot.js+174-281