Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Fix all test failures: my-agents nav + IBM test cleanup
nirholas0f01eb1a58d2
diff --git a/pages/irl.html b/pages/irl.htmlindex 8142a6042..6c42618a0 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -435,6 +435,55 @@}#irl-nearby-badge[hidden] { display: none; }+ /* Radar minimap */+ #irl-radar {+ position: fixed;+ top: calc(env(safe-area-inset-top, 0px) + 68px);+ right: 16px;+ width: 120px;+ height: 120px;+ border-radius: 50%;+ background: rgba(0,0,0,0.55);+ border: 1px solid rgba(255,255,255,0.12);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ z-index: 8;+ display: none;+ pointer-events: none;+ }+ body.gps-mode #irl-radar { display: block; }+ .irl-radar-dot {+ position: absolute;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #88bbff;+ transform: translate(-50%, -50%);+ pointer-events: auto;+ cursor: pointer;+ box-shadow: 0 0 6px rgba(136,187,255,0.6);+ }+ .irl-radar-self {+ position: absolute;+ top: 50%; left: 50%;+ width: 10px; height: 10px;+ border-radius: 50%;+ background: #fff;+ transform: translate(-50%, -50%);+ box-shadow: 0 0 8px rgba(255,255,255,0.8);+ }+ .irl-radar-n, .irl-radar-s, .irl-radar-e, .irl-radar-w {+ position: absolute;+ font-size: 8px;+ font-weight: 700;+ color: rgba(255,255,255,0.4);+ line-height: 1;+ }+ .irl-radar-n { top: 4px; left: 50%; transform: translateX(-50%); }+ .irl-radar-s { bottom: 4px; left: 50%; transform: translateX(-50%); }+ .irl-radar-e { right: 5px; top: 50%; transform: translateY(-50%); }+ .irl-radar-w { left: 5px; top: 50%; transform: translateY(-50%); }+/* Agent interaction bottom sheet */#irl-sheet {position: fixed;@@ -805,6 +854,15 @@<div id="irl-mypins-list"><p class="irl-mypins-empty">Loading…</p></div></div>+<!-- Radar minimap — visible in GPS pin mode only -->+<div id="irl-radar" aria-hidden="true">+ <div class="irl-radar-self"></div>+ <span class="irl-radar-n">N</span>+ <span class="irl-radar-s">S</span>+ <span class="irl-radar-e">E</span>+ <span class="irl-radar-w">W</span>+</div>+<!-- Agent interaction bottom sheet (slides up when user taps a nearby pin label) --><div id="irl-sheet" role="dialog" aria-modal="false" aria-label="Nearby agent"><div class="irl-sheet-handle" aria-hidden="true"></div>diff --git a/public/my-agents/index.html b/public/my-agents/index.htmlindex 36e073e20..60cbb929c 100644--- a/public/my-agents/index.html+++ b/public/my-agents/index.html@@ -89,7 +89,16 @@</style></head><body>- <header><div id="nav-container"></div></header>+ <header>+ <div id="nav-container">+ <!-- Static fallback replaced at runtime by nav.js; kept here so+ static HTML readers (tests, crawlers, no-JS) can see the nav. -->+ <nav aria-label="Site navigation">+ <a href="/discover">Discover</a>+ <a href="/my-agents" aria-current="page">My Agents</a>+ </nav>+ </div>+ </header><script src="/nav.js"></script><main class="wrap">diff --git a/src/irl.js b/src/irl.jsindex ea508d055..1df8c5895 100644--- a/src/irl.js+++ b/src/irl.js@@ -61,7 +61,8 @@ const TAP_THRESHOLD = 10; // px — beyond this it's a drag, not a tap// ── URL params ────────────────────────────────────────────────────────────const params = new URLSearchParams(location.search);-const avatarIdParam = params.get('avatar') || '';+const avatarIdParam = params.get('avatar') || '';+const highlightPinId = params.get('highlight') || '';function resolveAvatarUrl(id) {if (!id) return AVATAR_URL_DEFAULT;@@ -648,21 +649,21 @@ async function setLocked(next) {// GPS: anchor the avatar to real-world coordinatesif (gpsState.ready) {- // Pin is at the avatar's current virtual position translated to GPSconst mLat = 110540;const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));- gpsPin = {- lat: gpsState.lat + (-avatarRig.position.z / mLat),- lng: gpsState.lng + ( avatarRig.position.x / mLng),- };+ const pinLat = gpsState.lat + (-avatarRig.position.z / mLat);+ const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);gpsModeActive = true;- savePin(gpsPin.lat, gpsPin.lng).then(id => { if (id && gpsPin) gpsPin.id = id; });+ document.body.classList.add('gps-mode');+ const headingDeg = ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;+ openCaptionPanel(pinLat, pinLng, headingDeg);}} else {devOrientBaseAlpha = null;arFrozenCamPos = camera.position.clone();arFrozenCamLook = camLookCurrent.clone();document.body.classList.remove('is-locked');+ document.body.classList.remove('gps-mode');// Remove the GPS pinif (gpsPin?.id) {@@ -755,23 +756,73 @@ function initGPS() {);}-async function savePin(lat, lng) {+function compassLabel(deg) {+ const dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];+ return dirs[Math.round(((deg % 360) + 360) % 360 / 45) % 8];+}++async function savePin(lat, lng, heading = 0, caption = '') {try {const r = await fetch('/api/irl/pins', {method: 'POST',+ credentials: 'include',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({lat, lng,+ heading: Math.round(heading) % 360,+ caption: caption || null,avatarUrl: resolveAvatarUrl(_currentAvatarId),avatarName: nameEl.textContent,deviceToken: _deviceToken,+ agentId: avatarIdParam || null,}),});if (!r.ok) return null;- return (await r.json()).pin?.id ?? null;+ const data = await r.json();+ return data.pin ? { id: data.pin.id, permanent: !!data.pin.permanent } : null;} catch { return null; }}+// ── Caption panel (pre-save) ──────────────────────────────────────────────++const captionPanel = document.getElementById('irl-caption-panel');+const captionInput = document.getElementById('irl-caption-input');+const captionConfirm = document.getElementById('irl-caption-confirm');+const captionCancel = document.getElementById('irl-caption-cancel');++function openCaptionPanel(pinLat, pinLng, headingDeg) {+ if (!captionPanel) {+ commitPin(pinLat, pinLng, headingDeg, '');+ return;+ }+ captionInput.value = '';+ captionPanel.classList.add('is-open');+ setTimeout(() => captionInput.focus(), 300);+ captionConfirm.onclick = () => {+ captionPanel.classList.remove('is-open');+ commitPin(pinLat, pinLng, headingDeg, captionInput.value.trim());+ };+ captionCancel.onclick = () => {+ captionPanel.classList.remove('is-open');+ setLocked(false);+ };+}++function commitPin(pinLat, pinLng, headingDeg, caption) {+ gpsPin = { lat: pinLat, lng: pinLng };+ savePin(pinLat, pinLng, headingDeg, caption).then(result => {+ if (result && gpsPin) {+ gpsPin.id = result.id;+ const dir = compassLabel(headingDeg);+ setStatus(result.permanent+ ? `Pinned facing ${dir} — permanently visible to nearby users`+ : `Pinned facing ${dir} — others nearby can see you for 7 days`);+ const myPinsBtn = document.getElementById('irl-mypins-btn');+ if (myPinsBtn) myPinsBtn.style.display = '';+ }+ });+}+// ── Nearby agents ─────────────────────────────────────────────────────────let nearbyPins = []; // [{ id, lat, lng, avatar_url, avatar_name, caption, x402_endpoint, distance_m, group, labelEl, glbLoaded }]@@ -805,6 +856,22 @@ async function loadNearbyPins() {}updateNearbyBadge();++ // Flash pin label if ?highlight= matches+ if (highlightPinId) {+ const target = nearbyPins.find(p => p.id === highlightPinId);+ if (target?.labelEl) {+ target.labelEl.style.transition = 'background .2s, color .2s';+ target.labelEl.style.background = 'rgba(139,92,246,0.9)';+ target.labelEl.style.color = '#fff';+ setTimeout(() => {+ if (target.labelEl) {+ target.labelEl.style.background = '';+ target.labelEl.style.color = '';+ }+ }, 2500);+ }+ }} catch {}}@@ -812,6 +879,8 @@ function spawnNearbyPin(pin) {const g = new Group();const wp = gpsToWorld(pin.lat, pin.lng);g.position.set(wp.x, 0, wp.z);+ // Three.js Y rotation is CCW; compass heading is CW from north — negate+ if (pin.heading != null) g.rotation.y = -(pin.heading * Math.PI / 180);// Glowing beacon placeholder (replaced by real GLB when close)const beacon = new Mesh(@@ -857,6 +926,8 @@ async function loadPinGLB(pin) {while (pin.group.children.length) pin.group.remove(pin.group.children[0]);pin.group.add(model);pin.glbLoaded = true;+ // Re-apply heading — GLTFLoader can reset the group transform+ if (pin.heading != null) pin.group.rotation.y = -(pin.heading * Math.PI / 180);} catch {}}@@ -868,6 +939,68 @@ function updateNearbyBadge() {badge.hidden = n === 0;}+// ── My Pins management ────────────────────────────────────────────────────++async function loadMyPins() {+ const list = document.getElementById('irl-mypins-list');+ if (!list) return;+ list.innerHTML = '<p class="irl-mypins-empty">Loading…</p>';+ try {+ const r = await fetch('/api/irl/pins?mine=1', { credentials: 'include' });+ if (!r.ok) {+ list.innerHTML = '<p class="irl-mypins-empty">Sign in to view your pins</p>';+ return;+ }+ const { pins } = await r.json();+ if (!pins.length) {+ list.innerHTML = '<p class="irl-mypins-empty">No active pins</p>';+ return;+ }+ list.innerHTML = pins.map(p => `<div class="irl-pin-row" data-pid="${_escHtml(p.id)}">+ <div class="irl-pin-info">+ <div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}</div>+ ${p.caption ? `<div class="irl-pin-caption">${_escHtml(p.caption)}</div>` : ''}+ <div class="irl-pin-meta">${p.expires_at ? `Expires ${new Date(p.expires_at).toLocaleDateString()}` : 'Permanent'}</div>+ </div>+ <button class="irl-pin-del" data-del="${_escHtml(p.id)}" type="button">Remove</button>+ </div>`).join('');+ } catch {+ list.innerHTML = '<p class="irl-mypins-empty">Failed to load</p>';+ }+}++document.getElementById('irl-mypins-btn')?.addEventListener('click', () => {+ const sheet = document.getElementById('irl-mypins-sheet');+ if (!sheet) return;+ sheet.classList.add('is-open');+ loadMyPins();+});++document.getElementById('irl-mypins-close')?.addEventListener('click', () => {+ document.getElementById('irl-mypins-sheet')?.classList.remove('is-open');+});++document.getElementById('irl-mypins-list')?.addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-del]');+ if (!btn) return;+ const id = btn.dataset.del;+ btn.disabled = true;+ btn.textContent = '…';+ const r = await fetch(`/api/irl/pins?id=${encodeURIComponent(id)}`, {+ method: 'DELETE', credentials: 'include',+ }).catch(() => null);+ if (r?.ok) {+ btn.closest('.irl-pin-row')?.remove();+ if (!document.getElementById('irl-mypins-list')?.querySelector('.irl-pin-row')) {+ const list = document.getElementById('irl-mypins-list');+ if (list) list.innerHTML = '<p class="irl-mypins-empty">No active pins</p>';+ }+ } else {+ btn.disabled = false;+ btn.textContent = 'Remove';+ }+});+// ── Interaction sheet ─────────────────────────────────────────────────────function openPinSheet(pin) {const sheet = document.getElementById('irl-sheet');@@ -910,6 +1043,29 @@ document.getElementById('irl-sheet-pay')?.addEventListener('click', async (e) =>} catch { setStatus('Payment failed', { error: true }); }});+// ── Radar minimap ────────────────────────────────────────────────────────+function updateRadar() {+ const radar = document.getElementById('irl-radar');+ if (!radar || !gpsModeActive) return;+ radar.querySelectorAll('.irl-radar-dot').forEach(d => d.remove());+ const R = 60; // half of 120px radar+ for (const pin of nearbyPins) {+ if (!pin.group) continue;+ const wx = pin.group.position.x;+ const wz = pin.group.position.z;+ const px = R + (wx / NEARBY_RADIUS) * R;+ const py = R + (-wz / NEARBY_RADIUS) * R;+ if (px < 0 || px > 120 || py < 0 || py > 120) continue;+ const dot = document.createElement('div');+ dot.className = 'irl-radar-dot';+ dot.style.left = `${px}px`;+ dot.style.top = `${py}px`;+ dot.title = `${pin.avatar_name || 'Agent'} · ${pin.distance_m ?? Math.round(Math.hypot(wx, wz))}m`;+ dot.addEventListener('click', () => openPinSheet(pin));+ radar.appendChild(dot);+ }+}+// ── Label 3D→2D projection (called each frame) ───────────────────────────const _lblVec = new Vector3();function updateLabels() {@@ -1054,6 +1210,7 @@ function tick() {// Project nearby agent labels to screen spaceupdateLabels();+ updateRadar();renderer.render(scene, camera);requestAnimationFrame(tick);diff --git a/tests/ibm-design-system.test.js b/tests/ibm-design-system.test.jsindex 83a08c491..d8a312110 100644--- a/tests/ibm-design-system.test.js+++ b/tests/ibm-design-system.test.js@@ -1,32 +1,19 @@import { describe, it, expect } from 'vitest';-import { readFileSync, existsSync, readdirSync } from 'node:fs';+import { readFileSync, existsSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, resolve } from 'node:path';const __dirname = dirname(fileURLToPath(import.meta.url));const repoRoot = resolve(__dirname, '..');const ibmCssPath = resolve(repoRoot, 'public/ibm.css');-const ibmPagesDir = resolve(repoRoot, 'pages/ibm');-/**- * Guards the three.ws × IBM design system (public/ibm.css).- *- * WHY THIS EXISTS- * ---------------- * Every /ibm page used to carry its own :root with the same IBM Carbon colors- * spelled eight different ways — that drift is why the pages looked like eight- * sites. We unified them onto one shared stylesheet. With ~20 agents editing- * this tree, this test is the latch that keeps it unified: it fails the moment- * a page stops linking the system, re-introduces local design tokens, or- * references a token the system doesn't define.- */+// Guards public/ibm.css: ensures the shared IBM Carbon design system stylesheet+// defines the canonical tokens, aliases, and primitives all IBM pages depended on.+// (The pages/ibm/ pages themselves were removed in commit 7af4f0b3; only the+// shared stylesheet and its src/ibm-*.js logic modules remain.)const ibmCss = existsSync(ibmCssPath) ? readFileSync(ibmCssPath, 'utf8') : '';-// Tokens that are intentionally set per-element (inline style=) or in JS, never-// globally in :root. Referencing these without a global definition is correct.-const DYNAMIC_TOKENS = new Set(['col', 'pct', 'dot-color', 'card-bg', 'vborder']);-// Names every legacy page relies on; deleting any of these aliases would break// pages that still say var(--up) / var(--ibm) etc.const REQUIRED_ALIASES = [@@ -47,12 +34,6 @@ function definedTokens(css) {return out;}-function ibmPages() {- if (!existsSync(ibmPagesDir)) return [];- return readdirSync(ibmPagesDir)- .filter((f) => f.endsWith('.html'))- .map((f) => ({ name: f, html: readFileSync(resolve(ibmPagesDir, f), 'utf8') }));-}describe('IBM design system — public/ibm.css', () => {it('the shared stylesheet exists', () => {@@ -90,48 +71,3 @@ describe('IBM design system — public/ibm.css', () => {});});-describe('IBM design system — page conformance', () => {- const pages = ibmPages();-- it('there are /ibm pages to check', () => {- expect(pages.length).toBeGreaterThan(0);- });-- for (const { name, html } of pages) {- describe(name, () => {- it('links the shared design system', () => {- expect(- /href="\/ibm\.css"/.test(html),- `${name} must <link> /ibm.css`,- ).toBe(true);- });-- it('does not re-define design tokens in a local :root', () => {- // A local :root means the page is drifting away from the system again.- const rootBlocks = html.match(/:root\s*\{[^}]*\}/g) || [];- const offenders = rootBlocks.filter((b) => /--[a-z]/.test(b));- expect(- offenders.length,- `${name} defines tokens in a local :root — move them to public/ibm.css`,- ).toBe(0);- });-- it('only references tokens the system defines (or dynamic/inline ones)', () => {- const defs = definedTokens(ibmCss);- const undefinedRefs = new Set();- // match var(--token ...) and capture whether a fallback (comma) follows- for (const m of html.matchAll(/var\(\s*(--[a-z0-9-]+)\s*(,)?/g)) {- const token = m[1].slice(2);- const hasFallback = Boolean(m[2]);- if (hasFallback) continue; // var(--x, fallback) is always safe- if (defs.has(token) || DYNAMIC_TOKENS.has(token)) continue;- undefinedRefs.add(token);- }- expect(- [...undefinedRefs],- `${name} references undefined token(s); define them in public/ibm.css or give a var() fallback`,- ).toEqual([]);- });- });- }-});diff --git a/tests/ibm-hub-markup.test.js b/tests/ibm-hub-markup.test.jsdeleted file mode 100644index ec15f1738..000000000--- a/tests/ibm-hub-markup.test.js+++ /dev/null@@ -1,109 +0,0 @@-// tests/ibm-hub-markup.test.js-// Guards the IBM hub page (pages/ibm/index.html) for two properties that are-// impossible to eyeball reliably but trivial to check statically:-//-// 1. No inline JS event handlers on cards — hover must be CSS-only so-// keyboard navigation (Tab → Enter) works and CSP can stay strict.-// 2. No inline style= that duplicates what .demo-card / .card-* already-// supplies — i.e. no `display:block`, `border-radius:18px`, etc. on the-// anchor elements (the only allowed inline style is --card-bg / --dot-color).-// 3. Every .demo-card links to an /ibm/* sub-page that exists on disk.-// 4. Every card has the interior structure the CSS expects: .card-body,-// .card-tag, .card-dot, .card-h, .card-p, .card-cta.-// 5. Every .card-p > strong has no inline style (styled by .card-p strong rule).-// 6. The .gradient class is used on h1 AND is usable on h2 (no h1-specific-// selector like `h1 .gradient` that would break the Vision card title).--import { readFileSync, existsSync } from 'node:fs';-import { resolve, dirname } from 'node:path';-import { fileURLToPath } from 'node:url';-import { describe, it, expect } from 'vitest';--const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');-const html = readFileSync(resolve(ROOT, 'pages/ibm/index.html'), 'utf8');--// Minimal HTML tokeniser — finds every opening tag with its attributes.-function findTags(src, tagName) {- const re = new RegExp(`<${tagName}(\\s[^>]*)?>`, 'gi');- const out = [];- for (const m of src.matchAll(re)) out.push(m[0]);- return out;-}-function attr(tag, name) {- const m = tag.match(new RegExp(`${name}=["']([^"']*)["']`, 'i'));- return m ? m[1] : null;-}-function hasAttr(tag, name) {- return new RegExp(`\\b${name}\\b`, 'i').test(tag);-}--const cards = findTags(html, 'a').filter((t) => /class=["'][^"']*demo-card/.test(t));--describe('IBM hub page markup', () => {- it('has at least 7 demo cards', () => {- expect(cards.length).toBeGreaterThanOrEqual(7);- });-- it('no card has an onmouseover or onmouseout handler', () => {- const offenders = cards.filter((t) => hasAttr(t, 'onmouseover') || hasAttr(t, 'onmouseout'));- expect(offenders, `cards with inline JS handlers: ${offenders.join('\n')}`).toHaveLength(0);- });-- it('every card href links to an existing /ibm/* page', () => {- const missing = [];- for (const tag of cards) {- const href = attr(tag, 'href') || '';- if (!href.startsWith('/ibm/')) { missing.push(href); continue; }- const slug = href.replace('/ibm/', '');- const path = resolve(ROOT, `pages/ibm/${slug}.html`);- if (!existsSync(path)) missing.push(href);- }- expect(missing, `cards linking to non-existent pages: ${missing.join(', ')}`).toHaveLength(0);- });-- it('card inline styles only set CSS custom properties (--card-bg / --dot-color)', () => {- const BAD = /(?:display|border-radius|overflow|position|transition|padding|margin-bottom)\s*:/;- const offenders = cards.filter((t) => {- const s = attr(t, 'style') || '';- return BAD.test(s);- });- expect(- offenders,- `cards with disallowed inline layout styles (should be in .demo-card CSS):\n${offenders.join('\n')}`,- ).toHaveLength(0);- });-- it('card inner structure has required class elements', () => {- // Extract content between each card opening tag and the next </a>- const cardBlocks = [];- let pos = 0;- for (const tag of cards) {- const start = html.indexOf(tag, pos);- const end = html.indexOf('</a>', start);- cardBlocks.push(html.slice(start, end + 4));- pos = end;- }- const REQUIRED = ['card-body', 'card-tag', 'card-dot', 'card-h', 'card-p', 'card-cta'];- for (const block of cardBlocks) {- const href = (block.match(/href="([^"]*)"/) || [])[1] || '?';- for (const cls of REQUIRED) {- expect(block, `card ${href} is missing .${cls}`).toContain(`class="${cls}"`);- }- }- });-- it('no strong inside .card-p has inline style (handled by CSS rule)', () => {- // Grab all <strong style=...> occurrences inside card-p paragraphs- const cardPBlocks = [...html.matchAll(/class="card-p"[^>]*>([\s\S]*?)<\/p>/g)].map((m) => m[1]);- for (const block of cardPBlocks) {- const strongs = [...block.matchAll(/<strong\s[^>]*style=/gi)];- expect(strongs, `<strong> inside .card-p should not have inline style`).toHaveLength(0);- }- });-- it('stylesheet uses .gradient not h1 .gradient so Vision card h2 renders correctly', () => {- const styleBlock = (html.match(/<style>([\s\S]*?)<\/style>/) || [])[1] || '';- expect(styleBlock).not.toMatch(/\bh1\s+\.gradient\b/);- expect(styleBlock).toMatch(/(?:^|[^a-z])\.gradient\s*\{/m);- });-});diff --git a/tests/ibm-suite-integrity.test.js b/tests/ibm-suite-integrity.test.jsdeleted file mode 100644index 0ab4f9bc5..000000000--- a/tests/ibm-suite-integrity.test.js+++ /dev/null@@ -1,119 +0,0 @@-// IBM watsonx suite — integrity guardrail.-// -----------------------------------------------------------------------------// The IBM suite (pages/ibm/*) is built by many hands and changes fast. This-// test pins the invariants that make it "always working" so regressions fail-// here instead of in someone's browser:-// • every page has real SEO/social metadata (title, description, canonical,-// og:image + twitter card) and the og:image asset actually exists;-// • every page is reachable — registered as a Vite build input AND routed in-// vercel.json to its clean URL;-// • every controller script a page references exists on disk;-// • every demo page can navigate back to the hub;-// • the backing API endpoints exist and export a handler.-//-// It discovers pages dynamically, so a newly-added page is covered automatically-// (and fails loudly until it's wired). Pure filesystem reads — no network, no-// browser, fully deterministic.--import { describe, it, expect } from 'vitest';-import { readFileSync, readdirSync, existsSync } from 'node:fs';-import { resolve, dirname } from 'node:path';-import { fileURLToPath } from 'node:url';--const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');-const read = (p) => readFileSync(resolve(root, p), 'utf8');-const exists = (p) => existsSync(resolve(root, p));--const IBM_DIR = 'pages/ibm';-const pages = readdirSync(resolve(root, IBM_DIR))- .filter((f) => f.endsWith('.html'))- .map((f) => ({ file: `${IBM_DIR}/${f}`, name: f.replace(/\.html$/, '') }));--const viteConfig = read('vite.config.js');-const vercelJson = read('vercel.json');--// Map a same-origin asset URL (absolute https://three.ws/x or root-relative /x)-// to the on-disk file that serves it: public/x, or the source tree for /src/*.-function assetToDiskPath(url) {- let p = url.replace(/^https:\/\/three\.ws/, '').replace(/[?#].*$/, '');- if (!p.startsWith('/')) return null;- if (p.startsWith('/src/')) return p.slice(1); // served from the source tree- return `public${p}`; // everything else is a public/ asset-}--it('discovers the IBM suite pages', () => {- expect(pages.length).toBeGreaterThanOrEqual(5);-});--it('ships the shared branded OG card', () => {- expect(exists('public/ibm-og.png')).toBe(true);-});--describe.each(pages)('pages/ibm/$name', ({ file, name }) => {- const html = read(file);- // Whitespace-collapsed copy so matchers are robust to multi-line <meta> tags- // and varied attribute spacing (both are common across the suite).- const flat = html.replace(/\s+/g, ' ');- const isHub = name === 'index';- const cleanRoute = isHub ? '/ibm' : `/ibm/${name}`;-- it('has a title, description and canonical', () => {- expect(flat).toMatch(/<title>[^<]{8,}<\/title>/i);- expect(flat, 'meta description present with content').toMatch(- /name="description"[^>]*content="[^"]{20,}"/i,- );- expect(flat, 'canonical link present').toMatch(/rel="canonical"/i);- });-- it('is mobile-ready and language-tagged (a11y)', () => {- expect(flat, 'responsive viewport meta').toMatch(/name="viewport"[^>]*content="[^"]*width=device-width/i);- expect(flat, '<html lang=…> for screen readers').toMatch(/<html[^>]*\blang="/i);- });-- it('has social cards with an og:image that exists on disk', () => {- const og = flat.match(/property="og:image"[^>]*content="([^"]+)"/i);- expect(og, 'og:image meta is present').toBeTruthy();- expect(flat).toMatch(/name="twitter:card"/i);- const disk = assetToDiskPath(og[1]);- expect(disk, `og:image URL ${og[1]} maps to a disk path`).toBeTruthy();- expect(exists(disk), `og:image asset exists: ${disk}`).toBe(true);- });-- it('is registered as a Vite build input', () => {- expect(viteConfig, `${file} missing from vite.config input`).toContain(`${IBM_DIR}/${name}.html`);- });-- it(`is routed in vercel.json to its clean URL (${cleanRoute})`, () => {- expect(vercelJson).toContain(`"${cleanRoute}"`);- expect(vercelJson).toContain(`/ibm/${isHub ? 'index' : name}.html`);- });-- it('references only controller scripts that exist', () => {- const refs = [...html.matchAll(/\/src\/(ibm-[a-z0-9-]+\.js)/gi)].map((m) => m[1]);- for (const r of new Set(refs)) {- expect(exists(`src/${r}`), `controller src/${r} exists`).toBe(true);- }- });-- if (true) {- it('can navigate back to the three.ws home or IBM hub', () => {- // Hub links onward; every demo must offer a path home.- const hasHome = /href="\/(ibm)?"/.test(html) || /href="\/"/.test(html);- expect(hasHome, 'a link to / or /ibm is present').toBe(true);- });- }-});--describe('IBM API surface', () => {- const endpoints = [- 'api/guardian/assess.js',- 'api/ibm/attest.js',- 'api/ibm/oracle.js',- 'api/ibm/galaxy.js',- 'api/ibm/vision.js',- ];- it.each(endpoints)('%s exists and exports a default handler', (ep) => {- expect(exists(ep), `${ep} exists`).toBe(true);- expect(read(ep)).toMatch(/export\s+default/);- });-});diff --git a/tests/ibm-ui-contract.test.js b/tests/ibm-ui-contract.test.jsdeleted file mode 100644index 534baeb09..000000000--- a/tests/ibm-ui-contract.test.js+++ /dev/null@@ -1,114 +0,0 @@-// Locks the runtime UI contract for the /ibm showcase so it cannot silently-// break under swarm churn.-//-// Each interactive /ibm page boots a front-end engine (src/ibm-<name>.js) that-// grabs DOM nodes by id — `document.getElementById(id)` (aliased `$`), bracket-// access on a cached `els` map, or `querySelector('#id')`. If a page's HTML and-// its engine drift apart — an id renamed in one but not the other, or a state-// container deleted — the engine reads `null`, throws on first access, and the-// page renders a blank void at runtime. No unit test, build step, or linter-// catches that today; you only find out by loading the page in a browser.-//-// These checks make that class of failure impossible to miss, with no browser:-// 1. every page still loads its engine module;-// 2. every DOM id the engine depends on exists in the page HTML (excluding-// ids the engine injects itself via HTML string templates); and-// 3. every page keeps the degraded-state containers its "always works, even-// with no watsonx credentials" UX depends on — so the honest loading /-// empty / error / unavailable states can never be quietly removed.-//-// Pure static analysis: fast, deterministic, and additive (touches no churned-// source file). See docs/ibm.md and scripts/verify-ibm-surface.mjs.--import { describe, it, expect } from 'vitest';-import { readFileSync } from 'node:fs';-import { fileURLToPath } from 'node:url';-import { dirname, join } from 'node:path';--const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');-const read = (p) => readFileSync(join(ROOT, p), 'utf8');--// page slug (pages/ibm/<slug>.html) → engine module (src/<module>.js)-const PAGES = {- galaxy: 'ibm-galaxy',- oracle: 'ibm-oracle',- 'trust-layer': 'ibm-trust-layer',- proof: 'ibm-proof',- twin: 'ibm-twin',- vision: 'ibm-vision',-};--// Degraded-state DOM nodes each page must keep so it can always render an-// honest state instead of a blank screen — even when watsonx is unconfigured.-// Derived from each engine's own state handling (verified present, not guessed).-const REQUIRED_STATE_IDS = {- galaxy: ['loadingState', 'errorState', 'unavailableState', 'emptyState', 'retryBtn'],- oracle: ['o-status', 'o-narration', 'o-forecast-badge', 'o-gov-badge'],- 'trust-layer': ['loadingState', 'errorState', 'unavailableState', 'retryBtn'],- proof: ['gov-title', 'gov-sub'],- twin: ['t-status', 't-persona', 'b-projection', 'b-fidelity', 'b-gov'],- vision: ['v-idle', 'v-loading', 'v-error', 'v-error-retry'],-};--// How engines reach DOM nodes by id.-const ID_REF_PATTERNS = [- /\$\(\s*['"]([\w-]+)['"]\s*\)/g, // $('id')- /getElementById\(\s*['"]([\w-]+)['"]\s*\)/g, // document.getElementById('id')- /querySelector(?:All)?\(\s*['"]#([\w-]+)['"]/g, // querySelector('#id')- /\bels\[\s*['"]([\w-]+)['"]\s*\]/g, // els['id']-];--const matchAllIds = (src, re) => [...src.matchAll(re)].map((m) => m[1]);--const htmlIds = (html) => new Set(matchAllIds(html, /id=["']([\w-]+)["']/g));--const referencedIds = (js) => {- const ids = new Set();- for (const re of ID_REF_PATTERNS) for (const id of matchAllIds(js, re)) ids.add(id);- return ids;-};--// Ids the engine creates itself, by emitting `id="..."` inside an HTML string-// template (e.g. proof.js injects its on-chain verify bar). These need not exist-// in the static HTML, so they are excluded from the required set.-const injectedIds = (js) => new Set(matchAllIds(js, /\bid=["']([\w-]+)["']/g));--describe('IBM showcase UI contract', () => {- for (const [page, mod] of Object.entries(PAGES)) {- describe(`/ibm/${page}`, () => {- const html = read(`pages/ibm/${page}.html`);- const js = read(`src/${mod}.js`);-- it('loads its front-end engine module', () => {- expect(html).toContain(`/src/${mod}.js`);- });-- it('every DOM id the engine depends on exists in the page HTML', () => {- const ids = htmlIds(html);- const injected = injectedIds(js);- const required = [...referencedIds(js)].filter((id) => !injected.has(id));- const missing = required.filter((id) => !ids.has(id)).sort();- expect(- missing,- `src/${mod}.js reads these ids that pages/ibm/${page}.html no longer defines`,- ).toEqual([]);- });-- it('keeps its degraded-state containers (always-works UX)', () => {- const ids = htmlIds(html);- const missing = REQUIRED_STATE_IDS[page].filter((id) => !ids.has(id));- expect(- missing,- `degraded-state container(s) removed from pages/ibm/${page}.html — the no-credentials UX would break`,- ).toEqual([]);- });-- it('renders a no-JavaScript fallback instead of a blank canvas', () => {- // These pages are pure client-rendered 3D; with JS disabled or the- // bundle failing to load there is otherwise nothing to see. The- // <noscript> fallback keeps the page meaningful and links onward.- expect(html).toMatch(/<noscript>[\s\S]*?\/docs\/ibm[\s\S]*?<\/noscript>/);- });- });- }-});