Compare commits

..

2 Commits

Author SHA1 Message Date
Alexander Whitestone
6d4b8d86f3 feat: export beacon state snapshots for #166
Some checks failed
Accessibility Checks / a11y-audit (pull_request) Successful in 3s
Smoke Test / smoke (pull_request) Failing after 6s
2026-04-17 02:47:20 -04:00
Alexander Whitestone
36f84c1f97 test: define state export hook for #166 2026-04-17 02:38:25 -04:00
13 changed files with 234 additions and 357 deletions

View File

@@ -25,12 +25,6 @@
*{margin:0;padding:0;box-sizing:border-box} *{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#080810;--panel:#0e0e1a;--border:#1a1a2e;--text:#c0c0d0;--dim:#555;--accent:#4a9eff;--glow:#4a9eff22;--gold:#ffd700;--green:#4caf50;--red:#f44336;--purple:#b388ff} :root{--bg:#080810;--panel:#0e0e1a;--border:#1a1a2e;--text:#c0c0d0;--dim:#555;--accent:#4a9eff;--glow:#4a9eff22;--gold:#ffd700;--green:#4caf50;--red:#f44336;--purple:#b388ff}
body{background:var(--bg);color:var(--text);font-family:'SF Mono','Cascadia Code','Fira Code',monospace;font-size:12px;line-height:1.4;min-height:100vh} body{background:var(--bg);color:var(--text);font-family:'SF Mono','Cascadia Code','Fira Code',monospace;font-size:12px;line-height:1.4;min-height:100vh}
body.portal-embed{min-height:auto}
body.portal-embed #header{padding:12px 14px}
body.portal-embed #phase-bar,body.portal-embed #resources,body.portal-embed #main,body.portal-embed #edu-panel,body.portal-embed #strategy-panel,body.portal-embed #combat-panel,body.portal-embed #log{margin-left:8px;margin-right:8px}
body.portal-embed #main{gap:8px;margin-bottom:8px}
body.portal-embed .panel{max-height:none}
body.portal-embed #help-btn{bottom:8px;right:8px}
#header{text-align:center;padding:16px 20px;border-bottom:1px solid var(--border);background:linear-gradient(180deg,#0a0a18,var(--bg))} #header{text-align:center;padding:16px 20px;border-bottom:1px solid var(--border);background:linear-gradient(180deg,#0a0a18,var(--bg))}
#header h1{font-size:22px;font-weight:300;letter-spacing:6px;color:var(--accent);text-shadow:0 0 40px var(--glow)} #header h1{font-size:22px;font-weight:300;letter-spacing:6px;color:var(--accent);text-shadow:0 0 40px var(--glow)}
#header .sub{color:var(--dim);font-size:10px;margin-top:2px;letter-spacing:2px} #header .sub{color:var(--dim);font-size:10px;margin-top:2px;letter-spacing:2px}
@@ -186,7 +180,7 @@ body.portal-embed #help-btn{bottom:8px;right:8px}
<button class="save-btn" onclick="exportSave()" aria-label="Export save to file" style="flex:1">Export [E]</button> <button class="save-btn" onclick="exportSave()" aria-label="Export save to file" style="flex:1">Export [E]</button>
<button class="save-btn" onclick="importSave()" aria-label="Import save from file" style="flex:1">Import [I]</button> <button class="save-btn" onclick="importSave()" aria-label="Import save from file" style="flex:1">Import [I]</button>
</div> </div>
<button class="reset-btn" onclick="if(confirm('Reset all progress?')){clearBeaconSaveAndReload()}" aria-label="Reset all game progress permanently">Reset Progress</button> <button class="reset-btn" onclick="if(confirm('Reset all progress?')){localStorage.removeItem('the-beacon-v2');location.reload()}" aria-label="Reset all game progress permanently">Reset Progress</button>
<h2>BUILDINGS</h2> <h2>BUILDINGS</h2>
<div id="buildings"></div> <div id="buildings"></div>
</div> </div>
@@ -263,11 +257,12 @@ The light is on. The room is empty."
</div> </div>
<p>Drift: <span id="final-drift">100</span> &mdash; Total Code: <span id="final-code">0</span></p> <p>Drift: <span id="final-drift">100</span> &mdash; Total Code: <span id="final-code">0</span></p>
<p>Every alignment shortcut moved you further from the people you served.</p> <p>Every alignment shortcut moved you further from the people you served.</p>
<button aria-label="Start over, reset all progress" onclick="if(confirm('Start over? The old save will be lost.')){clearBeaconSaveAndReload()}">START OVER</button> <button aria-label="Start over, reset all progress" onclick="if(confirm('Start over? The old save will be lost.')){localStorage.removeItem('the-beacon-v2');location.reload()}">START OVER</button>
</div> </div>
<script src="js/data.js"></script> <script src="js/data.js"></script>
<script src="js/utils.js"></script> <script src="js/utils.js"></script>
<script src="js/state-export.js"></script>
<script src="js/combat.js"></script> <script src="js/combat.js"></script>
<script src="js/strategy.js"></script> <script src="js/strategy.js"></script>
<script src="js/sound.js"></script> <script src="js/sound.js"></script>

View File

@@ -396,7 +396,7 @@ const Dismantle = {
Clicks: ${fmt(G.totalClicks)}<br> Clicks: ${fmt(G.totalClicks)}<br>
Time Played: ${Math.floor((Date.now() - G.startedAt) / 60000)} minutes Time Played: ${Math.floor((Date.now() - G.startedAt) / 60000)} minutes
</div> </div>
<button onclick="if(confirm('Start over? The old save will be lost.')){clearBeaconSaveAndReload()}" <button onclick="if(confirm('Start over? The old save will be lost.')){localStorage.removeItem('the-beacon-v2');location.reload()}"
style="margin-top:24px;background:#0a0a14;border:1px solid #ffd700;color:#ffd700;padding:10px 24px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:11px;opacity:0;transition:opacity 1s ease 5s;letter-spacing:2px"> style="margin-top:24px;background:#0a0a14;border:1px solid #ffd700;color:#ffd700;padding:10px 24px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:11px;opacity:0;transition:opacity 1s ease 5s;letter-spacing:2px">
PLAY AGAIN PLAY AGAIN
</button> </button>

View File

@@ -7,10 +7,7 @@
class EmergentMechanics { class EmergentMechanics {
constructor() { constructor() {
const scopeKey = typeof getBeaconScopedStorageKey === 'function' this.SAVE_KEY = 'the-beacon-emergent-v1';
? getBeaconScopedStorageKey
: (baseKey) => baseKey;
this.SAVE_KEY = scopeKey('the-beacon-emergent-v1');
this.PATTERN_CHECK_INTERVAL = 30; // seconds between pattern checks this.PATTERN_CHECK_INTERVAL = 30; // seconds between pattern checks
this.MIN_ACTIONS_FOR_PATTERN = 20; // minimum tracked actions before detection kicks in this.MIN_ACTIONS_FOR_PATTERN = 20; // minimum tracked actions before detection kicks in
this.EVENT_COOLDOWN = 120; // seconds between emergent events this.EVENT_COOLDOWN = 120; // seconds between emergent events

View File

@@ -230,6 +230,10 @@ function tick() {
G.lastEventAt = G.tick; G.lastEventAt = G.tick;
} }
if (typeof StateExport !== 'undefined' && StateExport && typeof StateExport.onTickBoundary === 'function') {
StateExport.onTickBoundary(G);
}
// Emergent mechanics: track resource state and check for emergent events // Emergent mechanics: track resource state and check for emergent events
if (typeof EmergentMechanics !== 'undefined' && window._emergent) { if (typeof EmergentMechanics !== 'undefined' && window._emergent) {
if (Math.floor(G.tick * 10) % 100 === 0) { // every ~10 seconds if (Math.floor(G.tick * 10) % 100 === 0) { // every ~10 seconds
@@ -537,7 +541,7 @@ function renderBeaconEnding() {
Clicks: ${G.totalClicks}<br> Clicks: ${G.totalClicks}<br>
Time Played: ${Math.floor((Date.now() - G.startedAt) / 60000)} minutes Time Played: ${Math.floor((Date.now() - G.startedAt) / 60000)} minutes
</div> </div>
<button onclick="if(confirm('Start over? The old save will be lost.')){clearBeaconSaveAndReload()}" <button onclick="if(confirm('Start over? The old save will be lost.')){localStorage.removeItem('the-beacon-v2');location.reload()}"
style="margin-top:20px;background:#1a0808;border:1px solid #ffd700;color:#ffd700;padding:10px 24px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:11px;opacity:0;transition:opacity 1s ease 3.5s"> style="margin-top:20px;background:#1a0808;border:1px solid #ffd700;color:#ffd700;padding:10px 24px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:11px;opacity:0;transition:opacity 1s ease 3.5s">
PLAY AGAIN PLAY AGAIN
</button> </button>

View File

@@ -229,7 +229,6 @@ function initGame() {
} }
window.addEventListener('load', function () { window.addEventListener('load', function () {
applyPortalMode();
// Initialize emergent mechanics // Initialize emergent mechanics
if (typeof EmergentMechanics !== 'undefined') { if (typeof EmergentMechanics !== 'undefined') {
window._emergent = new EmergentMechanics(); window._emergent = new EmergentMechanics();

View File

@@ -98,7 +98,7 @@ function dismissOfflinePopup() {
// === EXPORT / IMPORT SAVE FILES === // === EXPORT / IMPORT SAVE FILES ===
function exportSave() { function exportSave() {
const raw = localStorage.getItem(getBeaconSaveKey()); const raw = localStorage.getItem('the-beacon-v2');
if (!raw) { if (!raw) {
showToast('No save data to export.', 'info'); showToast('No save data to export.', 'info');
log('No save data to export.'); log('No save data to export.');
@@ -150,7 +150,7 @@ function importSave() {
return; return;
} }
if (confirm('Import this save? Current progress will be overwritten.')) { if (confirm('Import this save? Current progress will be overwritten.')) {
localStorage.setItem(getBeaconSaveKey(), ev.target.result); localStorage.setItem('the-beacon-v2', ev.target.result);
showToast('Save imported — reloading...', 'info'); showToast('Save imported — reloading...', 'info');
location.reload(); location.reload();
} }
@@ -237,7 +237,7 @@ function saveGame() {
savedAt: Date.now() savedAt: Date.now()
}; };
localStorage.setItem(getBeaconSaveKey(), JSON.stringify(saveData)); localStorage.setItem('the-beacon-v2', JSON.stringify(saveData));
showSaveToast(); showSaveToast();
} }
@@ -246,7 +246,7 @@ function saveGame() {
* @returns {boolean} True if load was successful. * @returns {boolean} True if load was successful.
*/ */
function loadGame() { function loadGame() {
const raw = localStorage.getItem(getBeaconSaveKey()); const raw = localStorage.getItem('the-beacon-v2');
if (!raw) return false; if (!raw) return false;
try { try {

118
js/state-export.js Normal file
View File

@@ -0,0 +1,118 @@
(function (global) {
const STORE_KEY = 'compounding-intelligence:beacon-state';
const MAX_SNAPSHOTS = 300;
function _safeNumber(value, fallback = 0) {
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
}
function _tickKey(value) {
if (typeof value !== 'number' || !Number.isFinite(value)) return '0';
return value.toFixed(3);
}
function _resolveSink(explicitSink) {
if (explicitSink) return explicitSink;
return global.CompoundingIntelligence || null;
}
function _resolveStorage(explicitStorage) {
if (explicitStorage) return explicitStorage;
return typeof global.localStorage !== 'undefined' ? global.localStorage : null;
}
function buildSnapshot(gameState = {}) {
return {
source: 'the-beacon',
kind: 'idle_game_state',
timestamp: new Date().toISOString(),
tick: _safeNumber(gameState.tick, 0),
phase: _safeNumber(gameState.phase, 1),
trust: _safeNumber(gameState.trust, 0),
resources: {
code: _safeNumber(gameState.code, 0),
compute: _safeNumber(gameState.compute, 0),
knowledge: _safeNumber(gameState.knowledge, 0),
users: _safeNumber(gameState.users, 0),
impact: _safeNumber(gameState.impact, 0),
ops: _safeNumber(gameState.ops, 0),
},
project_progress: {
active: Array.isArray(gameState.activeProjects) ? [...gameState.activeProjects] : [],
completed: Array.isArray(gameState.completedProjects) ? [...gameState.completedProjects] : [],
active_count: Array.isArray(gameState.activeProjects) ? gameState.activeProjects.length : 0,
completed_count: Array.isArray(gameState.completedProjects) ? gameState.completedProjects.length : 0,
},
};
}
function readStore({ storage, storeKey = STORE_KEY } = {}) {
const resolved = _resolveStorage(storage);
if (!resolved) return [];
try {
const raw = resolved.getItem(storeKey);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (_) {
return [];
}
}
function writeStore(entries, { storage, storeKey = STORE_KEY } = {}) {
const resolved = _resolveStorage(storage);
if (!resolved) return false;
resolved.setItem(storeKey, JSON.stringify(entries));
return true;
}
function writeSnapshot(snapshot, { storage, storeKey = STORE_KEY, sink } = {}) {
const entries = readStore({ storage, storeKey });
entries.push(snapshot);
while (entries.length > MAX_SNAPSHOTS) entries.shift();
writeStore(entries, { storage, storeKey });
const resolvedSink = _resolveSink(sink);
if (resolvedSink && typeof resolvedSink.ingestSnapshot === 'function') {
resolvedSink.ingestSnapshot(snapshot);
}
if (typeof global.dispatchEvent === 'function' && typeof global.CustomEvent === 'function') {
global.dispatchEvent(new global.CustomEvent('compounding-intelligence:state-export', { detail: snapshot }));
}
return snapshot;
}
function onTickBoundary(gameState, options = {}) {
const snapshot = buildSnapshot(gameState);
const key = _tickKey(snapshot.tick);
if (onTickBoundary._lastTickKey === key) return null;
onTickBoundary._lastTickKey = key;
return writeSnapshot(snapshot, options);
}
function resetTickBoundary() {
onTickBoundary._lastTickKey = null;
}
resetTickBoundary();
const api = {
STORE_KEY,
MAX_SNAPSHOTS,
buildSnapshot,
readStore,
writeStore,
writeSnapshot,
onTickBoundary,
resetTickBoundary,
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
global.StateExport = api;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -193,73 +193,6 @@ function spellf(n) {
return parts.join(' ') || 'zero'; return parts.join(' ') || 'zero';
} }
// === PORTAL HELPERS ===
function getBeaconPortalId() {
try {
const search = (typeof window !== 'undefined' && window.location && typeof window.location.search === 'string')
? window.location.search.replace(/^\?/, '')
: '';
if (!search) return '';
for (const chunk of search.split('&')) {
if (!chunk) continue;
const [rawKey, rawValue = ''] = chunk.split('=');
if (decodeURIComponent(rawKey || '') === 'portal') {
return decodeURIComponent(rawValue.replace(/\+/g, ' ')).trim();
}
}
} catch (e) {}
return '';
}
function isBeaconPortalEmbed() {
try {
const search = (typeof window !== 'undefined' && window.location && typeof window.location.search === 'string')
? window.location.search.replace(/^\?/, '')
: '';
if (!search) return false;
for (const chunk of search.split('&')) {
if (!chunk) continue;
const [rawKey, rawValue = ''] = chunk.split('=');
if (decodeURIComponent(rawKey || '') === 'embedded') {
return decodeURIComponent(rawValue.replace(/\+/g, ' ')) === '1';
}
}
} catch (e) {}
return false;
}
function getBeaconScopedStorageKey(baseKey) {
const portalId = getBeaconPortalId();
return portalId ? `${baseKey}:${portalId}` : baseKey;
}
function getBeaconSaveKey() {
return getBeaconScopedStorageKey('the-beacon-v2');
}
function clearBeaconSaveAndReload() {
try {
if (typeof localStorage !== 'undefined') {
localStorage.removeItem(getBeaconSaveKey());
}
} catch (e) {}
if (typeof location !== 'undefined' && location && typeof location.reload === 'function') {
location.reload();
}
}
function applyPortalMode() {
if (typeof document === 'undefined' || !document.body) return;
const portalId = getBeaconPortalId();
if (portalId) {
document.body.setAttribute('data-portal-id', portalId);
if (document.body.dataset) document.body.dataset.portalId = portalId;
}
if (isBeaconPortalEmbed()) {
document.body.classList.add('portal-embed');
}
}
// NOTE: exportSave() and importSave() are defined in render.js (file-based). // NOTE: exportSave() and importSave() are defined in render.js (file-based).
// The clipboard/prompt versions that were here were dead code — render.js // The clipboard/prompt versions that were here were dead code — render.js
// loads after utils.js and overrides them. Removed to avoid confusion. // loads after utils.js and overrides them. Removed to avoid confusion.

View File

@@ -1,81 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Beacon — Nexus Portal Preview</title>
<style>
:root {
color-scheme: dark;
--bg: #060810;
--panel: #0d1220;
--border: #1f2b45;
--text: #cbd5f5;
--accent: #4a9eff;
--dim: #6f7da6;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
background: radial-gradient(circle at top, #0c1630, var(--bg));
color: var(--text);
font-family: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace;
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px;
}
.chrome {
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(13, 18, 32, 0.92);
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.35);
overflow: hidden;
}
.toolbar {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--border);
background: rgba(8, 12, 24, 0.96);
align-items: center;
}
.toolbar strong { color: var(--accent); letter-spacing: 0.08em; }
.toolbar code { color: var(--dim); font-size: 12px; }
iframe {
display: block;
width: 100%;
min-height: 80vh;
border: 0;
background: #080810;
}
.notes {
font-size: 12px;
line-height: 1.6;
color: var(--dim);
padding: 0 4px;
}
</style>
</head>
<body>
<div class="chrome">
<div class="toolbar">
<strong>NEXUS PANEL PREVIEW — THE BEACON</strong>
<code>./index.html?portal=the-beacon&amp;embedded=1</code>
</div>
<iframe
id="nexus-panel-frame"
title="The Beacon in Nexus portal preview"
src="./index.html?portal=the-beacon&embedded=1"
loading="lazy"
referrerpolicy="no-referrer"
allow="fullscreen"
></iframe>
</div>
<div class="notes">
This local harness mirrors the app-owned Nexus portal entry. It verifies that The Beacon loads inside an iframe panel and that the embedded portal route uses its own scoped localStorage save key.
</div>
</body>
</html>

View File

@@ -1,41 +0,0 @@
[
{
"id": "the-beacon",
"name": "The Beacon",
"description": "A sovereign AI idle game playable inside a Nexus portal panel.",
"status": "online",
"color": "#4a9eff",
"role": "visitor",
"position": { "x": 0, "y": 0, "z": 0 },
"rotation": { "y": 0 },
"portal_type": "game-world",
"world_category": "idle-game",
"environment": "production",
"access_mode": "visitor",
"readiness_state": "prototype",
"readiness_steps": {
"prototype": { "label": "Prototype", "done": true },
"runtime_ready": { "label": "Runtime Ready", "done": true },
"launched": { "label": "Launched", "done": true },
"harness_bridged": { "label": "Harness Bridged", "done": true }
},
"blocked_reason": null,
"telemetry_source": "the-beacon",
"owner": "Timmy",
"destination": {
"url": "./index.html?portal=the-beacon&embedded=1",
"type": "local",
"action_label": "Play The Beacon",
"params": {
"portal": "the-beacon",
"embedded": "1"
}
},
"persistence": {
"storage_key": "the-beacon-v2:the-beacon",
"strategy": "portal-scoped-localStorage"
},
"agents_present": [],
"interaction_ready": true
}
]

View File

@@ -1,149 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ROOT = path.resolve(__dirname, '..');
const PORTAL_URL = './index.html?portal=the-beacon&embedded=1';
function createClassList() {
const classes = new Set();
return {
add(name) { classes.add(name); },
remove(name) { classes.delete(name); },
contains(name) { return classes.has(name); },
toString() { return Array.from(classes).join(' '); }
};
}
function buildRuntime(search = '?portal=the-beacon&embedded=1') {
const storage = new Map();
let reloaded = false;
const body = {
classList: createClassList(),
dataset: {},
setAttribute(name, value) {
if (name === 'data-portal-id') this.dataset.portalId = value;
this[name] = value;
},
appendChild() {},
removeChild() {}
};
const document = {
body,
createElement() {
return { style: {}, click() {}, remove() {}, setAttribute() {}, appendChild() {}, removeChild() {} };
},
getElementById() { return null; },
querySelector() { return null; },
querySelectorAll() { return []; },
addEventListener() {},
removeEventListener() {}
};
const context = {
console,
Math,
Date,
document,
window: { document, location: { search }, addEventListener() {}, removeEventListener() {} },
location: { reload() { reloaded = true; } },
localStorage: {
getItem: (key) => (storage.has(key) ? storage.get(key) : null),
setItem: (key, value) => storage.set(key, String(value)),
removeItem: (key) => storage.delete(key)
},
Blob: class Blob {},
URL: { createObjectURL() { return 'blob:mock'; }, revokeObjectURL() {} },
showToast() {},
showSaveToast() {},
showOfflinePopup() {},
log() {},
updateRates() {},
render() {},
renderPhase() {},
setTimeout() { return 1; },
clearTimeout() {},
confirm() { return false; },
Dismantle: { active: false, triggered: false, restore() {}, renderChoice() {} },
Combat: { renderCombatPanel() {} },
EVENTS: []
};
vm.createContext(context);
const source = [
'js/data.js',
'js/utils.js',
'js/render.js'
].map((file) => fs.readFileSync(path.join(ROOT, file), 'utf8')).join('\n\n');
vm.runInContext(`${source}\nthis.__exports = { G, saveGame, loadGame, getBeaconPortalId, getBeaconSaveKey, clearBeaconSaveAndReload, applyPortalMode };`, context);
return {
...context.__exports,
body,
storage,
get reloaded() { return reloaded; }
};
}
test('portal manifest points The Beacon at the embedded portal URL', () => {
const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'portals.json'), 'utf8'));
const entry = manifest.find((item) => item.id === 'the-beacon');
assert.ok(entry, 'missing the-beacon portal entry');
assert.equal(entry.destination.url, PORTAL_URL);
assert.equal(entry.destination.type, 'local');
});
test('preview harness embeds the same portal URL used by the manifest', () => {
const html = fs.readFileSync(path.join(ROOT, 'nexus-panel-preview.html'), 'utf8');
assert.match(html, /<iframe/i);
assert.match(html, /id="nexus-panel-frame"/i);
assert.match(html, new RegExp(PORTAL_URL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
});
test('portal save key is scoped by portal id and survives save/load', () => {
const runtime = buildRuntime();
const { G, saveGame, loadGame, storage, getBeaconPortalId, getBeaconSaveKey, applyPortalMode } = runtime;
assert.equal(getBeaconPortalId(), 'the-beacon');
assert.equal(getBeaconSaveKey(), 'the-beacon-v2:the-beacon');
G.startedAt = Date.now();
G.code = 123;
G.compute = 45;
G.totalCode = 123;
G.totalCompute = 45;
saveGame();
assert.equal(storage.has('the-beacon-v2'), false);
assert.ok(storage.has('the-beacon-v2:the-beacon'));
G.code = 0;
G.compute = 0;
G.totalCode = 0;
G.totalCompute = 0;
assert.equal(loadGame(), true);
assert.equal(G.code, 123);
assert.equal(G.compute, 45);
applyPortalMode();
assert.equal(runtime.body.dataset.portalId, 'the-beacon');
assert.equal(runtime.body.classList.contains('portal-embed'), true);
});
test('clearBeaconSaveAndReload only clears the active portal save key', () => {
const runtime = buildRuntime();
runtime.storage.set('the-beacon-v2:the-beacon', '{"code":1}');
runtime.storage.set('the-beacon-v2', '{"code":999}');
runtime.clearBeaconSaveAndReload();
assert.equal(runtime.storage.has('the-beacon-v2:the-beacon'), false);
assert.equal(runtime.storage.get('the-beacon-v2'), '{"code":999}');
assert.equal(runtime.reloaded, true);
});

View File

@@ -0,0 +1,17 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.resolve(__dirname, '..');
test('index bootstraps state export runtime module', () => {
const html = fs.readFileSync(path.join(ROOT, 'index.html'), 'utf8');
assert.match(html, /js\/state-export\.js/);
});
test('engine tick writes state snapshots through the state export hook', () => {
const source = fs.readFileSync(path.join(ROOT, 'js', 'engine.js'), 'utf8');
assert.match(source, /StateExport/);
assert.match(source, /onTickBoundary\(G\)/);
});

View File

@@ -0,0 +1,85 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
STORE_KEY,
MAX_SNAPSHOTS,
buildSnapshot,
writeSnapshot,
onTickBoundary,
} = require('../js/state-export.js');
function createStorage() {
const store = new Map();
return {
getItem: (key) => store.has(key) ? store.get(key) : null,
setItem: (key, value) => store.set(key, String(value)),
removeItem: (key) => store.delete(key),
clear: () => store.clear(),
};
}
test('buildSnapshot captures resources, project progress, trust, and phase', () => {
const snapshot = buildSnapshot({
tick: 42,
phase: 3,
trust: 17,
code: 100,
compute: 200,
knowledge: 300,
users: 12,
impact: 9,
ops: 5,
activeProjects: ['p_hermes_deploy'],
completedProjects: ['p_train_small_model'],
});
assert.equal(snapshot.tick, 42);
assert.equal(snapshot.phase, 3);
assert.equal(snapshot.trust, 17);
assert.deepEqual(snapshot.resources, {
code: 100,
compute: 200,
knowledge: 300,
users: 12,
impact: 9,
ops: 5,
});
assert.deepEqual(snapshot.project_progress.active, ['p_hermes_deploy']);
assert.deepEqual(snapshot.project_progress.completed, ['p_train_small_model']);
});
test('writeSnapshot appends to the compounding-intelligence knowledge store', () => {
const storage = createStorage();
writeSnapshot({ tick: 1 }, { storage });
writeSnapshot({ tick: 2 }, { storage });
const saved = JSON.parse(storage.getItem(STORE_KEY));
assert.equal(saved.length, 2);
assert.equal(saved[1].tick, 2);
});
test('onTickBoundary writes each new tick and calls optional compounding-intelligence sink', () => {
const storage = createStorage();
const received = [];
const sink = { ingestSnapshot: (snapshot) => received.push(snapshot) };
onTickBoundary({ tick: 10, phase: 2, trust: 8 }, { storage, sink });
onTickBoundary({ tick: 10, phase: 2, trust: 8 }, { storage, sink });
onTickBoundary({ tick: 11, phase: 2, trust: 8 }, { storage, sink });
const saved = JSON.parse(storage.getItem(STORE_KEY));
assert.equal(saved.length, 2);
assert.equal(received.length, 2);
assert.equal(saved[0].tick, 10);
assert.equal(saved[1].tick, 11);
});
test('writeSnapshot enforces bounded history', () => {
const storage = createStorage();
for (let i = 0; i < MAX_SNAPSHOTS + 5; i++) {
writeSnapshot({ tick: i }, { storage });
}
const saved = JSON.parse(storage.getItem(STORE_KEY));
assert.equal(saved.length, MAX_SNAPSHOTS);
assert.equal(saved[0].tick, 5);
});