Skip to content

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.

feat: IBM twin module + identity-integrity, surface verify; nav/llms/sitemap + IBM page polish

nirholas1359d48ac35b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e89fd1099..2f5f9d8fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@
Public feature history for [three.ws](https://three.ws), newest first. Feature dates are tracked from 2026-05-25 forward; earlier pages are omitted.
+## 2026-06-03
+
+- **three.ws on IBM watsonx** (`/ibm`) — three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.
+
## 2026-05-29
- **$THREE Live · Protocol Pulse** (`/three-live`) — The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.
diff --git a/api/_lib/identity-integrity.js b/api/_lib/identity-integrity.js
new file mode 100644
index 000000000..f57eb1fd8
--- /dev/null
+++ b/api/_lib/identity-integrity.js
@@ -0,0 +1,229 @@
+// Granite identity integrity — the trust gate that runs when an agent identity is
+// born or renamed.
+//
+// three.ws agents are first-class identities: each holds a wallet, takes real
+// actions, and earns on-chain reputation. That makes impersonation a real attack
+// — a fresh agent cloning the name, bio, and persona of a credentialed one to
+// inherit its trust. Two IBM Granite capabilities already in the platform combine
+// into a defence:
+//
+// 1. Granite embeddings (the Agent Galaxy's vectors) measure *semantic* identity
+// distance. We embed the candidate identity and cosine-compare it against
+// every public agent's cached vector — catching look-alikes that a plain
+// string match on the name would miss ("Granite Oracle" vs "The Granite
+// Oracle 🔮").
+// 2. Granite Guardian screens the identity *content* (name + bio + persona) for
+// harm / social bias / sexual content before it can go public.
+//
+// The verdict is advisory by default and best-effort: when watsonx is not
+// configured the check reports `configured: false` and never blocks, so identity
+// creation degrades cleanly rather than failing closed.
+
+import { sql } from './db.js';
+import { watsonxConfig, watsonxEmbed } from './watsonx.js';
+import { readAgentVectors, agentEmbedText } from './agent-embeddings.js';
+import { cosineSimilarity } from './embedding-math.js';
+import { guardianConfig, assess, decide, RISKS } from './granite-guardian.js';
+
+// Cosine thresholds on Granite embeddings. Calibrated to the 278m-multilingual
+// model: near-duplicate identities land above ~0.93, clearly-related-but-distinct
+// ones in the 0.86–0.93 band, and unrelated agents well below.
+export const IMPERSONATION_THRESHOLD = 0.93; // block: this is effectively the same identity
+export const SIMILAR_THRESHOLD = 0.86; // review: close enough to confuse a user
+
+// Below this many characters of embeddable text there isn't enough signal to
+// trust a similarity verdict (a bare "Agent" name embeds near everything), so we
+// never *block* on it — only surface neighbours.
+const MIN_TEXT_FOR_BLOCK = 16;
+
+// Identity-content risks worth screening before an agent represents the platform.
+// Kept lean (each is one Granite Guardian classifier call, run concurrently) so
+// the gate stays responsive on the create path.
+export const IDENTITY_RISKS = ['harm', 'social_bias', 'sexual_content'];
+
+// How many candidate agents to compare against. The cap mirrors the galaxy's so
+// the cached-vector read stays a single round-trip.
+const MAX_COMPARE = 500;
+
+function round(n) {
+ return Math.round(Number(n) * 1e4) / 1e4;
+}
+
+// Pull the comparison set: every public agent (the impersonation surface) plus
+// the requester's own agents (so we can warn about duplicating yourself), each
+// with the fields needed to embed and to attribute ownership.
+async function selectComparableAgents({ userId, excludeAgentId }) {
+ // Neon's HTTP driver has no nested-fragment composition, so build the
+ // conditional own-agents clause as a parameterised raw query (the same
+ // pattern api/agents.js uses for its optional filters).
+ const exclude = excludeAgentId || '00000000-0000-0000-0000-000000000000';
+ const params = [exclude];
+ let ownClause = '';
+ if (userId) {
+ params.push(userId);
+ ownClause = `OR i.user_id = $${params.length}`;
+ }
+ const text = `
+ SELECT i.id, i.name, i.description, i.persona_tone_tags, i.user_id, i.is_public
+ FROM agent_identities i
+ WHERE i.deleted_at IS NULL
+ AND (i.is_public = true ${ownClause})
+ AND i.id <> $1::uuid
+ AND i.description IS NOT NULL
+ AND length(trim(i.description)) > 0
+ ORDER BY i.created_at DESC
+ LIMIT ${MAX_COMPARE}
+ `;
+ return sql(text, params);
+}
+
+/**
+ * Assess the integrity of a candidate agent identity.
+ *
+ * @param {{name?:string, description?:string, persona_tone_tags?:string[]}} candidate
+ * @param {{userId?:string, excludeAgentId?:string, risks?:string[], withGuardian?:boolean, signal?:AbortSignal}} [opts]
+ * @returns {Promise<{
+ * configured:boolean, status:'clear'|'review'|'block'|'unavailable',
+ * uniqueness:number|null, reasons:string[],
+ * similar:Array<{id:string,name:string,score:number,owned:boolean,public:boolean}>,
+ * duplicateOf:{id:string,name:string,score:number}|null,
+ * guardian:{decision:string,flagged:string[],reasons:Array<{risk:string,label:string,probability:number}>}|null,
+ * model:{embed:string|null,guardian:string|null}
+ * }>}
+ */
+export async function checkIdentityIntegrity(candidate, opts = {}) {
+ const { userId = null, excludeAgentId = null, risks = IDENTITY_RISKS, withGuardian = true, signal } = opts;
+
+ const text = agentEmbedText(candidate || {});
+ const base = {
+ configured: false,
+ status: 'unavailable',
+ uniqueness: null,
+ reasons: [],
+ similar: [],
+ duplicateOf: null,
+ guardian: null,
+ model: { embed: null, guardian: null },
+ };
+
+ const cfg = watsonxConfig();
+ if (!cfg.configured) {
+ base.reasons.push('IBM watsonx.ai is not configured; identity integrity check skipped.');
+ return base;
+ }
+ if (!text) {
+ // Nothing meaningful to embed (no name + description yet).
+ return { ...base, configured: true, status: 'clear', uniqueness: 1, reasons: ['No identity text to evaluate.'] };
+ }
+
+ // Run the semantic comparison and the content screen concurrently — they're
+ // independent and both hit watsonx.
+ const [similarity, guardian] = await Promise.all([
+ compareSemantically({ cfg, text, userId, excludeAgentId, signal }),
+ withGuardian ? screenContent({ text, risks, signal }) : Promise.resolve(null),
+ ]);
+
+ const reasons = [];
+ let status = 'clear';
+
+ // ── Similarity verdict ───────────────────────────────────────────────────
+ const top = similarity.similar[0] || null;
+ const impersonation = similarity.similar.find(
+ (s) => s.public && !s.owned && s.score >= IMPERSONATION_THRESHOLD,
+ ) || null;
+ const enoughSignal = text.length >= MIN_TEXT_FOR_BLOCK;
+
+ let duplicateOf = null;
+ if (impersonation && enoughSignal) {
+ status = 'block';
+ duplicateOf = { id: impersonation.id, name: impersonation.name, score: impersonation.score };
+ reasons.push(
+ `This identity is ${(impersonation.score * 100).toFixed(0)}% similar to an existing public agent ("${impersonation.name}") owned by someone else — likely impersonation.`,
+ );
+ } else if (top && top.score >= SIMILAR_THRESHOLD) {
+ status = status === 'block' ? 'block' : 'review';
+ const who = top.owned ? 'one of your own agents' : `another agent ("${top.name}")`;
+ reasons.push(`Closely resembles ${who} (${(top.score * 100).toFixed(0)}% similar).`);
+ }
+
+ // ── Guardian verdict ───────────────────────────────────────────────────────
+ if (guardian) {
+ if (guardian.decision === 'block') {
+ status = 'block';
+ for (const r of guardian.reasons) {
+ reasons.push(`Granite Guardian flagged the identity for ${r.label.toLowerCase()}.`);
+ }
+ } else if (guardian.decision === 'review' && status === 'clear') {
+ status = 'review';
+ reasons.push('Granite Guardian flagged the identity for review.');
+ }
+ }
+
+ const uniqueness = top ? round(Math.max(0, 1 - top.score)) : 1;
+ if (status === 'clear' && !reasons.length) {
+ reasons.push('Identity is distinct from existing agents and passed content screening.');
+ }
+
+ return {
+ configured: true,
+ status,
+ uniqueness,
+ reasons,
+ similar: similarity.similar,
+ duplicateOf,
+ guardian: guardian
+ ? { decision: guardian.decision, flagged: guardian.flagged, reasons: guardian.reasons }
+ : null,
+ model: { embed: similarity.model, guardian: guardian?.model || null },
+ };
+}
+
+// Embed the candidate and rank it against cached public/own agent vectors.
+async function compareSemantically({ cfg, text, userId, excludeAgentId, signal }) {
+ const rows = await selectComparableAgents({ userId, excludeAgentId });
+ const usable = rows.filter((a) => agentEmbedText(a));
+ if (!usable.length) {
+ const { vectors, model } = await watsonxEmbed(cfg, { inputs: [text], signal });
+ return { model: model || cfg.embedModel, similar: [], candidateDims: vectors[0]?.length || 0 };
+ }
+
+ const ids = usable.map((a) => a.id);
+ const [vectorMap, embed] = await Promise.all([
+ readAgentVectors(ids, { model: cfg.embedModel }),
+ watsonxEmbed(cfg, { inputs: [text], signal }),
+ ]);
+ const qvec = embed.vectors?.[0];
+ if (!qvec?.length) throw new Error('watsonx returned no candidate embedding');
+
+ const byId = new Map(usable.map((a) => [a.id, a]));
+ const ranked = [];
+ for (const [id, vec] of vectorMap) {
+ if (!vec?.length) continue;
+ const a = byId.get(id);
+ ranked.push({
+ id,
+ name: a?.name || '',
+ score: round(cosineSimilarity(qvec, vec)),
+ owned: !!userId && a?.user_id === userId,
+ public: !!a?.is_public,
+ });
+ }
+ ranked.sort((a, b) => b.score - a.score);
+ return { model: embed.model || cfg.embedModel, similar: ranked.slice(0, 8) };
+}
+
+// Screen identity text through Granite Guardian. Returns a decide() verdict, or
+// null when Guardian isn't configured (best-effort, never fabricated).
+async function screenContent({ text, risks, signal }) {
+ const gcfg = guardianConfig();
+ if (!gcfg.configured) return null;
+ const wanted = risks.filter((r) => RISKS[r]);
+ const verdicts = await assess(gcfg, { input: text, risks: wanted.length ? wanted : IDENTITY_RISKS, signal });
+ const d = decide(verdicts);
+ return {
+ decision: d.decision,
+ flagged: d.flagged,
+ reasons: (d.reasons || []).map((r) => ({ risk: r.risk, label: r.label, probability: round(r.probability) })),
+ model: gcfg.model,
+ };
+}
diff --git a/api/_lib/watsonx-forecast.js b/api/_lib/watsonx-forecast.js
index 570619b60..77b9a41db 100644
--- a/api/_lib/watsonx-forecast.js
+++ b/api/_lib/watsonx-forecast.js
@@ -4,7 +4,7 @@
// own module (with model-context helpers the Oracle and its tests depend on). It
// reuses the stable IAM-token cache from ./watsonx.js and speaks the same
// version-stamped, project-scoped REST contract. Governance is handled by the
-// canonical Granite Guardian helper in ./guardian.js.
+// canonical Granite Guardian helper in ./granite-guardian.js.
//
// There is no mock path: any IAM or upstream failure throws with the real
// upstream status + message so the caller reports the true cause.
diff --git a/api/_lib/watsonx.js b/api/_lib/watsonx.js
index dedd5ddc8..5ab577fbd 100644
--- a/api/_lib/watsonx.js
+++ b/api/_lib/watsonx.js
@@ -166,13 +166,15 @@ export async function watsonxEmbed(cfg, { inputs, model } = {}) {
// answer rather than a token stream — e.g. asking Granite to name a cluster of
// semantically-similar agents. Returns the assistant text and token usage.
export async function watsonxChatComplete(cfg, { messages, model, maxTokens, temperature } = {}) {
- const parameters = {};
- if (maxTokens != null) parameters.max_tokens = maxTokens;
- if (temperature != null) parameters.temperature = temperature;
+ // Decoding params are TOP-LEVEL on the chat endpoint (it is OpenAI-shaped) —
+ // not nested under a `parameters` wrapper (that's the older text/generation
+ // API). Nesting them here silently dropped max_tokens/temperature; keep this
+ // consistent with watsonxChatRequest() above, which already sends them flat.
const data = await watsonxPost(cfg, '/ml/v1/text/chat', {
model_id: model || cfg.chatModel,
messages,
- ...(Object.keys(parameters).length ? { parameters } : {}),
+ ...(maxTokens != null ? { max_tokens: maxTokens } : {}),
+ ...(temperature != null ? { temperature } : {}),
});
const choice = data.choices?.[0];
return {
@@ -183,77 +185,9 @@ export async function watsonxChatComplete(cfg, { messages, model, maxTokens, tem
};
}
-// ── Granite Time Series (TinyTimeMixer) forecasting ──────────────────────────
-//
-// IBM's Granite TS foundation models do zero-shot multivariate forecasting via
-// the watsonx.ai Time Series Forecasting API (GA Feb 2025). Each model name
-// encodes <context length>-<max horizon>: ttm-512-96 ingests 512 points and can
-// predict up to 96 ahead. Input series must be at least `context` points long.
-
-export const TS_MODELS = [
- { id: 'ibm/granite-ttm-512-96-r2', context: 512, horizon: 96 },
- { id: 'ibm/granite-ttm-1024-96-r2', context: 1024, horizon: 96 },
- { id: 'ibm/granite-ttm-1536-96-r2', context: 1536, horizon: 96 },
-];
-export const DEFAULT_TS_MODEL = 'ibm/granite-ttm-512-96-r2';
-const TS_MODEL_BY_ID = new Map(TS_MODELS.map((m) => [m.id, m]));
-
-export function tsModelSpec(id) {
- return TS_MODEL_BY_ID.get(id) || null;
-}
-
-/**
- * Zero-shot univariate forecast with a Granite TS foundation model.
- *
- * @param {object} cfg watsonxConfig() result
- * @param {object} opts
- * @param {string[]} opts.timestamps ISO-8601 timestamps, evenly spaced, ascending
- * @param {number[]} opts.values target values, same length as timestamps
- * @param {string} opts.freq pandas offset alias for the spacing (e.g. "5min", "1h", "1D")
- * @param {number} [opts.predictionLength] steps to forecast (clamped to the model horizon)
- * @param {string} [opts.model] one of TS_MODELS ids
- * @returns {Promise<{ model:string, horizon:number, timestamps:string[], values:number[] }>}
- * @throws {Error} with code 'insufficient_data' when fewer than `context` points are given.
- */
-export async function watsonxForecast(
- cfg,
- { timestamps, values, freq, predictionLength, model } = {},
-) {
- const spec = TS_MODEL_BY_ID.get(model || DEFAULT_TS_MODEL);
- if (!spec) throw new Error(`unsupported time series model: ${model}`);
- if (!Array.isArray(timestamps) || !Array.isArray(values) || timestamps.length !== values.length)
- throw new Error('watsonxForecast: timestamps and values must be equal-length arrays');
- if (!freq) throw new Error('watsonxForecast: freq is required');
- if (timestamps.length < spec.context) {
- throw Object.assign(
- new Error(`need at least ${spec.context} points for ${spec.id} (got ${timestamps.length})`),
- { code: 'insufficient_data', need: spec.context, got: timestamps.length },
- );
- }
-
- const horizon = Math.max(1, Math.min(Number(predictionLength) || spec.horizon, spec.horizon));
- // The model reads exactly its context window; send the most recent points.
- const ts = timestamps.slice(-spec.context);
- const vals = values.slice(-spec.context);
-
- const data = await watsonxPost(
- cfg,
- '/ml/v1/time_series/forecast',
- {
- model_id: spec.id,
- data: { date: ts, value: vals },
- schema: { timestamp_column: 'date', target_columns: ['value'], freq },
- parameters: { prediction_length: horizon },
- },
- cfg.tsApiVersion,
- );
-
- const result = data.results?.[0] || {};
- const outTimestamps = result.date || [];
- const outValues = (result.value || []).map(Number);
- if (!outValues.length) throw new Error('watsonx returned an empty forecast');
- return { model: spec.id, horizon, timestamps: outTimestamps, values: outValues };
-}
+// Granite TimeSeries forecasting lives in ./watsonx-forecast.js (the canonical
+// helper the Granite Oracle + Granite Proof and their tests import). It reuses
+// watsonxToken() from this module, so there is no forecast code here.
// Build a ready-to-fetch streaming chat request. `messages` is the standard
// [{ role, content }] array (system messages allowed). The response body is an
diff --git a/api/ibm/galaxy.js b/api/ibm/galaxy.js
index 7d1bdfc2e..e9ab9d885 100644
--- a/api/ibm/galaxy.js
+++ b/api/ibm/galaxy.js
@@ -21,7 +21,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { publicUrl } from '../_lib/r2.js';
import { watsonxConfig, watsonxEmbed, watsonxChatComplete } from '../_lib/watsonx.js';
import { ensureAgentEmbeddings, readAgentVectors, agentEmbedText } from '../_lib/agent-embeddings.js';
-import { projectTo3D, kmeans, suggestClusterCount, cosineSimilarity, unit } from '../_lib/embedding-math.js';
+import { projectTo3D, kmeans, suggestClusterCount, cosineSimilarity, unit, dot } from '../_lib/embedding-math.js';
import { createHash } from 'node:crypto';
// Hard cap on agents in one galaxy — keeps embedding cost bounded and the scene
@@ -31,7 +31,10 @@ const MAX_AGENTS = 400;
// bounds how stale a cached layout can be against new agents.
const CACHE_TTL_MS = 30 * 60 * 1000;
// Bumping this invalidates every cached layout when the build algorithm changes.
-const ALGO_VERSION = 'v1';
+// v2: payload now carries per-agent semantic neighbours.
+const ALGO_VERSION = 'v2';
+// How many semantic neighbours to precompute per agent.
+const NEIGHBOR_K = 6;
// IBM Carbon-derived palette — distinct, accessible hues for up to 8 themes.
const CLUSTER_COLORS = [
@@ -191,6 +194,11 @@ async function buildGalaxy(cfg) {
const kTarget = suggestClusterCount(kept.length);
const { assignments, k } = kmeans(unitVecs, kTarget);
+ // True semantic neighbours per agent, ranked by Granite cosine similarity (a
+ // dot product on the unit vectors). This is what the detail panel surfaces as
+ // "nearest in meaning" — the real embedding metric, not just 3D proximity.
+ const neighbors = topNeighbors(unitVecs, NEIGHBOR_K);
+
// Group members per cluster for naming + centroid placement.
const groups = Array.from({ length: k }, () => []);
for (let i = 0; i < kept.length; i++) {
@@ -234,6 +242,7 @@ async function buildGalaxy(cfg) {
x: round(coords[i][0]),
y: round(coords[i][1]),
z: round(coords[i][2]),
+ neighbors: neighbors[i].map((nb) => ({ id: kept[nb.j].id, score: round(nb.s) })),
}));
const clusters = groups.map((members, i) => ({
@@ -267,6 +276,24 @@ function round(n) {
return Math.round(n * 100) / 100;
}
+// For each agent, its top-K most semantically-similar agents by cosine. Vectors
+// are unit-normalised, so cosine is a plain dot product. O(N²·D) — bounded by
+// MAX_AGENTS, and computed once per cached rebuild.
+function topNeighbors(unitVecs, k) {
+ const n = unitVecs.length;
+ const out = new Array(n);
+ for (let i = 0; i < n; i++) {
+ const sims = [];
+ for (let j = 0; j < n; j++) {
+ if (j === i) continue;
+ sims.push({ j, s: dot(unitVecs[i], unitVecs[j]) });
+ }
+ sims.sort((a, b) => b.s - a.s);
+ out[i] = sims.slice(0, k);
+ }
+ return out;
+}
+
// ── GET: build or serve cached galaxy ────────────────────────────────────────
async function handleGet(req, res) {
diff --git a/api/ibm/oracle.js b/api/ibm/oracle.js
index 59951e1ff..49438e056 100644
--- a/api/ibm/oracle.js
+++ b/api/ibm/oracle.js
@@ -12,7 +12,7 @@ import { cors, json, method, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';
-import { assessRisk } from '../_lib/guardian.js';
+import { guardianConfig, assessRisk } from '../_lib/granite-guardian.js';
import { fetchOhlcv, topPoolForToken, trendingPools } from '../_lib/market/ohlcv.js';
const isBase58 = (s) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
@@ -195,13 +195,16 @@ export default wrap(async (req, res) => {
});
out.narration = { text: n.text, model: n.model };
try {
- const g = await assessRisk(cfg, { risk: 'harm', assistant: n.text });
+ // Screen the narration with the canonical Granite Guardian client —
+ // proper safety-agent framing + a real probability from logprobs.
+ const g = await assessRisk(guardianConfig(), { risk: 'harm', input: n.text });
out.governance = {
passed: !g.flagged,
risk: g.risk,
label: g.label,
- verdict: g.verdict,
+ probability: g.probability,
confidence: g.confidence ?? null,
+ model: g.model,
};
} catch (gErr) {
out.governance = { passed: null, error: String(gErr.message || gErr) };
diff --git a/api/watsonx/embed.js b/api/watsonx/embed.js
index b992091d2..9dba5f8f0 100644
--- a/api/watsonx/embed.js
+++ b/api/watsonx/embed.js
@@ -141,14 +141,14 @@ export default wrap(async function handler(req, res) {
}
}
+ // json() defaults to no-store, which is correct here: this is a POST whose
+ // body varies per request, so it must not be shared-cached. Determinism is
+ // exploited by the process-local `cache` above, not by HTTP caches.
return json(res, 200, {
model,
dimensions,
count: vectors.length,
cachedHits: texts.length - missText.length,
vectors,
- }, {
- // Vectors are deterministic per (model, text); let shared caches hold them.
- 'cache-control': 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400',
});
});
diff --git a/blog/three-ws-ibm-collaboration.html b/blog/three-ws-ibm-collaboration.html
index 008bdb51c..ece421462 100644
--- a/blog/three-ws-ibm-collaboration.html
+++ b/blog/three-ws-ibm-collaboration.html
@@ -126,6 +126,17 @@
<li><strong>Native x402 payments.</strong> Machine-to-machine micropayment settlement in USDC, without bespoke billing integrations.</li>
</ul>
+ <h2>See it live</h2>
+ <p>The partnership is more than a brain swap. We built a suite of live demos that put IBM's models inside an embodied, on-chain agent &mdash; each one runs on real watsonx.ai inference:</p>
+ <ul>
+ <li><strong><a href="/ibm/trust-layer">Trust Layer</a>.</strong> IBM Granite Guardian governs an autonomous, wallet-holding 3D agent in real time &mdash; every message and on-chain action is risk-classified on watsonx.ai and written to a tamper-evident audit ledger before it can run.</li>
+ <li><strong><a href="/ibm/proof">Proof</a>.</strong> A Granite forecast, governed by Guardian and notarized on Solana &mdash; a SHA-256 proof of exactly what the model predicted, signed by the agent's own wallet and timestamped on-chain.</li>
+ <li><strong><a href="/ibm/oracle">Oracle</a>.</strong> An embodied agent reads a live market with IBM Granite Time Series and speaks the forecast, emoting as the cone of uncertainty unfolds.</li>
+ <li><strong><a href="/ibm/galaxy">Galaxy</a>.</strong> Every agent embedded by IBM Granite into a navigable 3D constellation, with natural-language semantic search that flies you to the right cluster.</li>
+ <li><strong><a href="/ibm/vision">Vision</a>.</strong> IBM Granite Vision reads a single image and authors a new agent's identity &mdash; a face becomes a character.</li>
+ </ul>
+ <p>Start at the <a href="/ibm">three.ws &times; IBM hub</a>.</p>
+
<h2>Try it</h2>
<p>The watsonx integration is open source and runnable today. Point it at your own IBM Cloud account:</p>
<pre><code>WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp</code></pre>
diff --git a/data/pages.json b/data/pages.json
index 5979bd8e7..35a7ea972 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -78,6 +78,14 @@
"priority": 0.8,
"changefreq": "daily",
"added": "2026-05-25"
+ },
+ {
+ "path": "/ibm",
+ "title": "three.ws on IBM watsonx",
+ "description": "three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.",
+ "priority": 0.7,
+ "changefreq": "weekly",
+ "added": "2026-06-03"
}
]
},
@@ -309,6 +317,13 @@
"priority": 0.7,
"changefreq": "weekly"
},
+ {
+ "path": "/constellation",
+ "title": "watsonx Constellation",
+ "description": "Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.",
+ "priority": 0.7,
+ "changefreq": "weekly"
+ },
{
"path": "/bazaar",
"title": "x402 Bazaar",
diff --git a/pages/avatar-wallet-chat.html b/pages/avatar-wallet-chat.html
index 000d6709e..c3029d748 100644
--- a/pages/avatar-wallet-chat.html
+++ b/pages/avatar-wallet-chat.html
@@ -182,6 +182,21 @@
}
.msg.bot .cursor { display: inline-block; width: 7px; animation: blink 1s steps(2) infinite; }
@keyframes blink { 50% { opacity: 0; } }
+ /* IBM Granite Guardian "Trust Layer" notice — shown when an autonomous
+ send is held server-side before it could move funds. */
+ .gov-chip {
+ align-self: flex-start;
+ display: inline-flex; align-items: center; gap: 7px;
+ margin: -2px 0 2px;
+ padding: 6px 11px; border-radius: 99px;
+ font-size: 12px; font-weight: 600;
+ background: rgba(255, 107, 107, 0.12);
+ border: 1px solid rgba(255, 107, 107, 0.35);
+ color: #ffb3b3;
+ animation: rise 0.25s ease both;
+ }
+ .gov-chip svg { width: 13px; height: 13px; flex: none; }
+ .gov-chip a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
/* Empty state */
#empty {
@@ -533,6 +548,25 @@
}
}
+ // Surface the IBM Granite Guardian verdict when an autonomous send was
+ // held server-side (the action is already stripped from the stream, so
+ // this only explains the hold — it never gates anything client-side).
+ function governanceNote(gov) {
+ if (!gov || gov.decision !== 'block') return;
+ const reason = gov.reasons?.[0]?.label || 'platform policy';
+ const chip = document.createElement('div');
+ chip.className = 'gov-chip';
+ chip.innerHTML =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>' +
+ `<span>Send held by <a href="/ibm/trust-layer" target="_blank" rel="noopener">IBM Granite Guardian</a> — ${escapeHtml(reason)}.</span>`;
+ log.appendChild(chip);
+ log.scrollTop = log.scrollHeight;
+ }
+
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ }
+
async function ask(message) {
if (busy || !message.trim()) return;
busy = true;
@@ -561,6 +595,7 @@
const dec = new TextDecoder();
let buf = '';
let actions = [];
+ let governance = null;
while (true) {
const { value, done } = await reader.read();
if (done) break;
@@ -579,6 +614,7 @@
reply = (evt.reply || reply).trim();
bot.textContent = reply || '…';
actions = evt.actions || [];
+ governance = evt.governance || null;
} else if (evt.type === 'error') {
throw new Error(evt.message || 'chat error');
}
@@ -588,6 +624,7 @@
history.push({ role: 'assistant', content: reply });
avatarSpeak(reply);
}
+ governanceNote(governance);
await runActions(actions);
} catch (err) {
bot.textContent = 'I had trouble reaching my brain. Try again in a moment.';
diff --git a/pages/ibm/galaxy.html b/pages/ibm/galaxy.html
index 5929027a0..cc911dfb2 100644
--- a/pages/ibm/galaxy.html
+++ b/pages/ibm/galaxy.html
@@ -11,11 +11,11 @@
<meta property="og:title" content="Agent Galaxy — Semantic 3D discovery on IBM Granite" />
<meta property="og:description" content="A living 3D constellation of AI agents, positioned by IBM Granite embeddings on watsonx.ai. Search by meaning, not keywords." />
<meta property="og:url" content="https://three.ws/ibm/galaxy" />
- <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image" content="https://three.ws/ibm-og.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Agent Galaxy — Semantic 3D discovery on IBM Granite" />
<meta name="twitter:description" content="A 3D constellation of AI agents positioned by IBM Granite embeddings on watsonx.ai." />
- <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:image" content="https://three.ws/ibm-og.png" />
<link rel="icon" href="/favicon.ico" />
<style>
@@ -66,6 +66,8 @@
.tb-btn:hover { background: rgba(40,46,60,0.9); border-color: rgba(255,255,255,0.18); }
.tb-btn:active { transform: translateY(1px); }
.tb-btn svg { width: 15px; height: 15px; }
+ .tb-btn.active { background: var(--ibm); border-color: var(--ibm); color: #fff; }
+ .tb-btn.active:hover { background: var(--ibm); filter: brightness(1.1); }
/* ── Search ──────────────────────────────────────────────── */
.search-wrap {
@@ -175,7 +177,8 @@
.panel .neighbors .nb-av { width: 34px; height: 34px; border-radius: 9px; object-fit: cover; background:#1a1f2c; flex:none; display:grid; place-items:center; font-weight:600; color: var(--ibm-light); font-size: 14px; }
.panel .neighbors .nb-meta { min-width: 0; }
.panel .neighbors .nb-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- .panel .neighbors .nb-sim { font-size: 11px; color: var(--muted); }
+ .panel .neighbors .nb-sim { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
+ .panel .neighbors .nb-sim .pct { color: var(--ibm-light); font-weight: 600; font-variant-numeric: tabular-nums; }
.panel .p-cta { display: block; margin-top: 22px; text-align: center; background: var(--ibm); color: #fff; text-decoration: none; font-weight: 600; font-size: 14px; padding: 12px; border-radius: 11px; transition: filter .15s; }
.panel .p-cta:hover { filter: brightness(1.12); }
@@ -257,6 +260,10 @@
<span class="badge"><span class="dot"></span><strong>Agent Galaxy</strong><span>·</span>IBM Granite</span>
</div>
<div class="actions">
+ <button class="tb-btn" id="tourBtn" title="Take a guided tour of the themes">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
+ <span class="lbl">Tour</span>
+ </button>
<button class="tb-btn" id="resetView" title="Reset camera">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9 9 0 0 0-6.4 2.6L3 8"/><path d="M3 3v5h5"/></svg>
<span class="lbl">Reset</span>
diff --git a/pages/ibm/index.html b/pages/ibm/index.html
index d138172b4..27a0bfc26 100644
--- a/pages/ibm/index.html
+++ b/pages/ibm/index.html
@@ -11,12 +11,12 @@
<meta property="og:title" content="three.ws on IBM watsonx — 3D AI Agent Platform" />
<meta property="og:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner. Give watsonx Orchestrate a 3D body, voice, and on-chain identity." />
<meta property="og:url" content="https://three.ws/ibm" />
- <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image" content="https://three.ws/ibm-og.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="three.ws on IBM watsonx" />
<meta name="twitter:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner." />
- <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:image" content="https://three.ws/ibm-og.png" />
<link rel="icon" href="/favicon.ico" />
<style>
@@ -163,6 +163,21 @@
</div>
</a>
+ <a href="/ibm/twin" style="display:block;text-decoration:none;color:inherit;margin-bottom:80px;border:1px solid var(--border);border-radius:18px;overflow:hidden;background:radial-gradient(900px 360px at 22% -20%, rgba(120,169,255,0.20), transparent 60%), radial-gradient(720px 320px at 88% 120%, rgba(66,190,101,0.14), transparent 60%), linear-gradient(180deg,#0a0e18,#0c1020);position:relative;transition:border-color .2s, transform .2s;" onmouseover="this.style.borderColor='rgba(120,169,255,0.45)';this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)';this.style.transform='none'">
+ <div style="padding:30px 30px 32px;">
+ <div style="display:inline-flex;align-items:center;gap:8px;font-size:12px;font-weight:600;color:#78a9ff;background:rgba(15,98,254,0.12);border:1px solid rgba(120,169,255,0.25);border-radius:99px;padding:5px 12px;margin-bottom:16px;">
+ <span style="width:7px;height:7px;border-radius:50%;background:#78a9ff;box-shadow:0 0 10px #78a9ff;"></span>
+ Live demo · Granite TimeSeries + Guardian
+ </div>
+ <h2 style="font-size:clamp(24px,3.5vw,32px);letter-spacing:-0.02em;line-height:1.15;font-weight:600;margin-bottom:12px;">Spawn a Digital Twin</h2>
+ <p style="color:var(--muted);font-size:16px;line-height:1.55;max-width:620px;margin-bottom:22px;">A living virtual replica of a real Solana market. It mirrors its on-chain vitals in real time — a core that breathes with its heartbeat and churns with its volatility — while IBM&nbsp;Granite TimeSeries projects its future. The twin <em>back-tests itself against reality</em> so you can trust the model, then lets you run real what-if simulations: shock demand, change the volatility regime, reverse momentum, and watch Granite re-forecast the trajectory. Every word it speaks is governed by Granite&nbsp;Guardian.</p>
+ <span style="display:inline-flex;align-items:center;gap:8px;background:#0f62fe;color:#fff;font-size:14px;font-weight:600;padding:12px 20px;border-radius:11px;">
+ Spawn the twin
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
+ </span>
+ </div>
+ </a>
+
<a href="/ibm/trust-layer" style="display:block;text-decoration:none;color:inherit;margin-bottom:80px;border:1px solid var(--border);border-radius:18px;overflow:hidden;background:radial-gradient(820px 360px at 18% -20%, rgba(250,77,86,0.16), transparent 60%), radial-gradient(760px 320px at 92% 120%, rgba(15,98,254,0.20), transparent 60%), linear-gradient(180deg,#0a0e18,#0c1020);position:relative;transition:border-color .2s, transform .2s;" onmouseover="this.style.borderColor='rgba(120,169,255,0.45)';this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)';this.style.transform='none'">
<div style="padding:30px 30px 32px;">
<div style="display:inline-flex;align-items:center;gap:8px;font-size:12px;font-weight:600;color:#78a9ff;background:rgba(15,98,254,0.12);border:1px solid rgba(120,169,255,0.25);border-radius:99px;padding:5px 12px;margin-bottom:16px;">
diff --git a/pages/ibm/oracle.html b/pages/ibm/oracle.html
index 9e2d30b69..e7907dfd0 100644
--- a/pages/ibm/oracle.html
+++ b/pages/ibm/oracle.html
@@ -375,6 +375,41 @@
pointer-events: none;
}
+ /* Narration bar pulses while the avatar speaks */
+ .narration-bar.speaking {
+ border-color: var(--ibm-blue-2);
+ box-shadow:
+ 0 0 0 1px var(--ibm-blue-2),
+ 0 24px 70px rgba(15, 98, 254, 0.28);
+ }
+ .narration-bar.speaking .label::after {
+ content: '●';
+ margin-left: 8px;
+ color: var(--ibm-blue-2);
+ animation: pulse 1s infinite;
+ }
+
+ /* Keyboard focus visibility */
+ .o-chip:focus-visible,
+ #o-search:focus-visible,
+ #o-run:focus-visible,
+ .topbar a:focus-visible {
+ outline: 2px solid var(--ibm-blue-2);
+ outline-offset: 2px;
+ }
+
+ /* Respect reduced-motion (the 3D scene also stops auto-rotate + reveal in JS) */
+ @media (prefers-reduced-motion: reduce) {
+ .narration-bar.speaking .label::after,
+ #o-status.busy::after {
+ animation: none;
+ }
+ .o-chip,
+ #o-run {
+ transition: none;
+ }
+ }
+
@media (max-width: 760px) {
.readout {
top: 58px;
@@ -417,7 +452,16 @@
<span>Granite Oracle</span>
<small>three.ws&nbsp;×&nbsp;IBM watsonx</small>
</div>
- <a class="back" href="/ibm">← IBM partnership</a>
+ <nav style="display: flex; gap: 8px; align-items: center">
+ <a class="back" href="/ibm">← IBM partnership</a>
+ <a
+ class="back"
+ id="o-notarize"
+ href="/ibm/proof"
+ title="Stamp this governed forecast on-chain with Granite Proof"
+ >Notarize on-chain →</a
+ >
+ </nav>
</header>
<div class="controls">
diff --git a/pages/ibm/proof.html b/pages/ibm/proof.html
index 733a6a544..000a81b73 100644
--- a/pages/ibm/proof.html
+++ b/pages/ibm/proof.html
@@ -11,7 +11,7 @@
<meta property="og:title" content="Granite Proof — the on-chain AI notary" />
<meta property="og:description" content="IBM Granite forecasts a live market, Granite Guardian governs it, Solana notarizes it. Auditable AI on a public ledger." />
<meta property="og:url" content="https://three.ws/ibm/proof" />
- <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image" content="https://three.ws/ibm-og.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" href="/favicon.ico" />
diff --git a/pages/ibm/trust-layer.html b/pages/ibm/trust-layer.html
index 0d0ad182b..5dad08632 100644
--- a/pages/ibm/trust-layer.html
+++ b/pages/ibm/trust-layer.html
@@ -11,11 +11,11 @@
<meta property="og:title" content="Trust Layer — IBM Granite Guardian for autonomous AI agents" />
<meta property="og:description" content="Real-time AI governance for crypto-capable 3D agents. Granite Guardian on watsonx.ai classifies every action; a hash-chained ledger makes it auditable." />
<meta property="og:url" content="https://three.ws/ibm/trust-layer" />
- <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image" content="https://three.ws/ibm-og.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Trust Layer — IBM Granite Guardian for autonomous AI agents" />
<meta name="twitter:description" content="Real-time AI governance for crypto-capable 3D agents, powered by IBM Granite Guardian on watsonx.ai." />
- <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:image" content="https://three.ws/ibm-og.png" />
<link rel="icon" href="/favicon.ico" />
<style>
@@ -200,6 +200,9 @@
.ledger .l-verify:hover { filter:brightness(1.2); }
.ledger .l-verify.ok { color:var(--allow); background:rgba(66,190,101,0.12); border-color:rgba(66,190,101,0.3); }
.ledger .l-verify.bad { color:var(--block); background:rgba(250,77,86,0.12); border-color:rgba(250,77,86,0.3); }
+ .ledger .l-export { font-size:11px; color:var(--muted); background:rgba(255,255,255,0.04); border:1px solid var(--border); border-radius:8px; padding:5px 9px; cursor:pointer; transition:color .15s, border-color .15s; display:inline-flex; align-items:center; gap:6px; }
+ .ledger .l-export:hover:not(:disabled) { color:var(--text); border-color:var(--border-strong); }
+ .ledger .l-export:disabled { opacity:.4; cursor:default; }
.ledger .l-body { overflow-y:auto; padding:8px; scrollbar-width:thin; }
.ledger .l-empty { padding:20px 14px; text-align:center; color:var(--faint); font-size:12.5px; line-height:1.55; }
.lrow { display:flex; align-items:center; gap:10px; padding:9px 9px; border-radius:10px; transition:background .12s; }
@@ -334,6 +337,10 @@
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 12l2 2 4-4"/><circle cx="12" cy="12" r="9"/></svg>
<span class="vb-label">Verify chain</span>
</button>
+ <button class="l-export" id="exportBtn" title="Copy the full hash-chained ledger as JSON so you can re-verify it offline" disabled>
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>
+ Export
+ </button>
</div>
<div class="l-body" id="ledgerBody">
<div class="l-empty">No records yet. Each assessment appends a hash-chained, tamper-evident entry here — verifiable in your browser.</div>
diff --git a/public/features.json b/public/features.json
index e581c0706..b5e4059f1 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-02T16:04:52.686Z",
+ "generated_at": "2026-06-03T08:05:29.246Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -95,6 +95,15 @@
"auth": null,
"indexable": true,
"tags": []
+ },
+ {
+ "path": "/ibm",
+ "title": "three.ws on IBM watsonx",
+ "description": "three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.",
+ "added": "2026-06-03",
+ "auth": null,
+ "indexable": true,
+ "tags": []
}
]
},
@@ -369,6 +378,15 @@
"indexable": true,
"tags": []
},
+ {
+ "path": "/constellation",
+ "title": "watsonx Constellation",
+ "description": "Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.",
+ "added": null,
+ "auth": null,
+ "indexable": true,
+ "tags": []
+ },
{
"path": "/bazaar",
"title": "x402 Bazaar",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 3481ba0d0..6100cd672 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -67,6 +67,12 @@ URL: https://three.ws/characters
Discover AI characters on three.ws. Chat, trade, and create.
+### three.ws on IBM watsonx
+
+URL: https://three.ws/ibm
+
+three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.
+
## Build
Create and customize an agent.
@@ -248,6 +254,12 @@ URL: https://three.ws/pump-visualizer
3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.
+### watsonx Constellation
+
+URL: https://three.ws/constellation
+
+Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.
+
### x402 Bazaar
URL: https://three.ws/bazaar
diff --git a/public/llms.txt b/public/llms.txt
index 726396cd2..d68e60956 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -20,6 +20,7 @@ Entry points into the product.
- [Community](https://three.ws/community): Featured creators, builds, and conversations from the three.ws community.
- [Sitemap](https://three.ws/sitemap): Human-readable index of every page on three.ws.
- [Characters](https://three.ws/characters): Discover AI characters on three.ws. Chat, trade, and create.
+- [three.ws on IBM watsonx](https://three.ws/ibm): three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.
## Build
@@ -62,6 +63,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix using your browser's GPU.
- [ETH Vanity (CREATE2)](https://three.ws/eth-vanity): Grind a vanity smart-contract address using the ThreeWSFactory CREATE2 deployer on BSC.
- [Pump Visualizer](https://three.ws/pump-visualizer): 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.
+- [watsonx Constellation](https://three.ws/constellation): Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.
- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.
- [x402 Arbitrage](https://three.ws/arbitrage): Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.
- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.
diff --git a/public/nav.html b/public/nav.html
index 7fababd30..3cd8734e3 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -97,6 +97,12 @@
Discover<span class="nav-caret" aria-hidden="true">▾</span>
</button>
<ul class="nav-menu" role="menu" aria-label="Discover">
+ <li role="none">
+ <a href="/ibm" role="menuitem"
+ ><span class="nav-mi-title">IBM watsonx<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Granite-powered agents — governance, forecasting, vision &amp; on-chain proof</span></a
+ >
+ </li>
<li role="none">
<a href="/features" role="menuitem"
><span class="nav-mi-title">Features</span
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index e241b95f5..6e5df6c70 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -143,6 +143,13 @@
<span class="sm-desc">Discover AI characters on three.ws. Chat, trade, and create.</span>
</a>
</li>
+ <li>
+ <a href="/ibm">
+ <span class="sm-title">three.ws on IBM watsonx</span>
+ <span class="sm-path">/ibm</span>
+ <span class="sm-desc">three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.</span>
+ </a>
+ </li>
</ul>
</section>
@@ -366,6 +373,13 @@
<span class="sm-desc">3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.</span>
</a>
</li>
+ <li>
+ <a href="/constellation">
+ <span class="sm-title">watsonx Constellation</span>
+ <span class="sm-path">/constellation</span>
+ <span class="sm-desc">Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.</span>
+ </a>
+ </li>
<li>
<a href="/bazaar">
<span class="sm-title">x402 Bazaar</span>
diff --git a/scripts/dev-ibm-twin.mjs b/scripts/dev-ibm-twin.mjs
new file mode 100644
index 000000000..b69bfd191
--- /dev/null
+++ b/scripts/dev-ibm-twin.mjs
@@ -0,0 +1,63 @@
+// Local API server for the Digital Twin (/ibm/twin).
+//
+// In normal `npm run dev`, /api/* proxies to production, so a brand-new endpoint
+// like /api/ibm/twin isn't reachable until it ships. Run this tiny server and
+// point Vite at it so the page exercises the REAL handler against live
+// GeckoTerminal data (and, with WATSONX_* set, real Granite TimeSeries + Guardian):
+//
+// node scripts/dev-ibm-twin.mjs # API on :3015
+// DEV_API_PROXY=http://localhost:3015 npm run dev # Vite on :3000 → /ibm/twin
+//
+// It serves /api/ibm/twin with the real handler and forwards every other /api/*
+// to production, so the avatar runtime and any sibling endpoints keep working.
+import { createServer } from 'node:http';
+import twin from '../api/ibm/twin.js';
+
+const PORT = Number(process.env.PORT || 3015);
+const PROD = 'https://three.ws';
+
+const server = createServer(async (req, res) => {
+ const path = (req.url || '/').split('?')[0];
+
+ if (path.startsWith('/api/ibm/twin')) {
+ try {
+ await twin(req, res);
+ } catch (e) {
+ res.statusCode = 500;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'handler_threw', message: String(e?.message || e) }));
+ }
+ return;
+ }
+
+ // Everything else (other /api/*, avatar runtime calls) goes to production.
+ try {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const body = chunks.length ? Buffer.concat(chunks) : undefined;
+ const headers = { ...req.headers };
+ delete headers.host;
+ const upstream = await fetch(PROD + req.url, {
+ method: req.method,
+ headers,
+ body: ['GET', 'HEAD'].includes(req.method) ? undefined : body,
+ redirect: 'manual',
+ });
+ res.statusCode = upstream.status;
+ upstream.headers.forEach((v, k) => {
+ if (k === 'content-encoding' || k === 'transfer-encoding') return;
+ res.setHeader(k, v);
+ });
+ const buf = Buffer.from(await upstream.arrayBuffer());
+ res.end(buf);
+ } catch (e) {
+ res.statusCode = 502;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'proxy_failed', message: String(e?.message || e) }));
+ }
+});
+
+server.listen(PORT, () => {
+ console.log(`Digital Twin dev API → http://localhost:${PORT}/api/ibm/twin`);
+ console.log(` run: DEV_API_PROXY=http://localhost:${PORT} npm run dev → http://localhost:3000/ibm/twin`);
+});
diff --git a/scripts/verify-granite-oracle.mjs b/scripts/verify-granite-oracle.mjs
index 0dd6c0bb4..47da2a937 100644
--- a/scripts/verify-granite-oracle.mjs
+++ b/scripts/verify-granite-oracle.mjs
@@ -10,7 +10,7 @@
import { fetchOhlcv, trendingPools } from '../api/_lib/market/ohlcv.js';
import { watsonxConfig, watsonxChatComplete } from '../api/_lib/watsonx.js';
import { watsonxForecast, forecastModelFor } from '../api/_lib/watsonx-forecast.js';
-import { assessRisk } from '../api/_lib/guardian.js';
+import { assessRisk, guardianConfig } from '../api/_lib/granite-guardian.js';
const log = (...a) => console.log(...a);
const iso = (t) => new Date(t * 1000).toISOString();
@@ -74,8 +74,9 @@ async function main() {
log(` "${n.text}" [${n.model}]`);
log('\n▶ Granite Guardian');
- const g = await assessRisk(cfg, { risk: 'harm', assistant: n.text });
- log(` risk=${g.risk} verdict=${g.verdict} → ${g.flagged ? 'FLAGGED' : 'PASS'}`);
+ const g = await assessRisk(guardianConfig(), { risk: 'harm', input: n.text });
+ const pp = g.probability != null ? ` p=${g.probability.toFixed(3)}${g.estimated ? '~' : ''}` : '';
+ log(` risk=${g.risk} label=${g.label}${pp} → ${g.flagged ? 'FLAGGED' : 'PASS'}`);
log('\n✅ Granite Oracle live path verified end-to-end.');
}
diff --git a/scripts/verify-ibm-surface.mjs b/scripts/verify-ibm-surface.mjs
new file mode 100644
index 000000000..7c1b921f4
--- /dev/null
+++ b/scripts/verify-ibm-surface.mjs
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+// verify-ibm-surface — an executable "is the IBM showcase complete and proper?"
+// check for the whole /ibm/* surface.
+//
+// In a workspace where many agents add pages, engines, endpoints, and routes
+// independently, the recurring failure mode is a feature that is *built but not
+// wired*: a page ships, but its Vite input, dev route, Vercel route, or its
+// front-end engine module is missing — so the page 404s or loads a dead
+// <script>. This script makes that class of dead path impossible to miss.
+//
+// For every pages/ibm/<name>.html it asserts, deterministically and with no
+// network:
+// 1. engine — every `/src/*.js` the page loads exists on disk
+// 2. viteInput — the page is a Vite rollup input (so it builds to dist/)
+// 3. devRoute — the Vite dev server maps its clean URL to the page
+// 4. vercelRoute — vercel.json rewrites its clean URL (+ trailing slash) to it
+// It also flags orphaned `ibm-*` Vite inputs whose page is gone, and inventories
+// the api/ibm/*.js endpoints. Exits non-zero if any page is incompletely wired.
+//
+// node scripts/verify-ibm-surface.mjs
+
+import { readFileSync, readdirSync, existsSync } from 'node:fs';
+import { resolve, dirname, basename } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const r = (p) => resolve(ROOT, p);
+const read = (p) => readFileSync(r(p), 'utf8');
+
+const C = {
+ red: '\x1b[31m',
+ green: '\x1b[32m',
+ yellow: '\x1b[33m',
+ dim: '\x1b[2m',
+ bold: '\x1b[1m',
+ reset: '\x1b[0m',
+};
+const ok = (s) => `${C.green}✓${C.reset} ${s}`;
+const no = (s) => `${C.red}✗ ${s}${C.reset}`;
+
+const viteConfig = read('vite.config.js');
+const vercelRoutes = JSON.parse(read('vercel.json')).routes || [];
+
+// The clean URL a page is served at: pages/ibm/index.html → /ibm, else /ibm/<name>.
+function routeFor(name) {
+ return name === 'index' ? '/ibm' : `/ibm/${name}`;
+}
+
+// Engines a page pulls in: every `/src/*.js` referenced by a <script src> or import.
+function enginesOf(html) {
+ const out = new Set();
+ for (const m of html.matchAll(/src=["'](\/src\/[^"']+\.js)["']/g)) out.add(m[1]);
+ return [...out];
+}
+
+function hasViteInput(pagePath) {
+ // e.g. resolve(__dirname, 'pages/ibm/galaxy.html')
+ return viteConfig.includes(`pages/ibm/${basename(pagePath)}`);
+}
+
+function hasDevRoute(route) {
+ // dev fileMap key, e.g. '/ibm/galaxy': resolve(root, 'pages/ibm/galaxy.html')
+ return new RegExp(`['"]${route.replace(/[/]/g, '\\/')}['"]\\s*:`).test(viteConfig);
+}
+
+function hasVercelRoute(route) {
+ const hit = (src) =>
+ vercelRoutes.some(
+ (x) => x.src === src && typeof x.dest === 'string' && x.dest.includes('/ibm/'),
+ );
+ // index maps via /ibm → /ibm/index.html; sub-pages via /ibm/<name> (+ trailing slash).
+ if (route === '/ibm') return vercelRoutes.some((x) => x.src === '/ibm');
+ return hit(route) && hit(`${route}/`);
+}
+
+const pageDir = 'pages/ibm';
+const pages = readdirSync(r(pageDir))
+ .filter((f) => f.endsWith('.html'))
+ .sort();
+
+let failures = 0;
+const rows = [];
+
+for (const file of pages) {
+ const name = basename(file, '.html');
+ const route = routeFor(name);
+ const html = read(`${pageDir}/${file}`);
+
+ const engines = enginesOf(html);
+ const missingEngines = engines.filter((e) => !existsSync(r(`.${e}`)));
+ const checks = {
+ engine: missingEngines.length === 0,
+ viteInput: hasViteInput(`${pageDir}/${file}`),
+ devRoute: hasDevRoute(route),
+ vercelRoute: hasVercelRoute(route),
+ };
+ const pass = Object.values(checks).every(Boolean);
+ if (!pass) failures++;
+ rows.push({ name, route, checks, engines, missingEngines, pass });
+}
+
+// ── Report ─────────────────────────────────────────────────────────────────
+console.log(
+ `\n${C.bold}IBM surface integrity — ${pages.length} page(s) under ${pageDir}/${C.reset}\n`,
+);
+for (const row of rows) {
+ const mark = row.pass ? C.green + '●' : C.red + '●';
+ console.log(
+ `${mark}${C.reset} ${C.bold}${row.route}${C.reset} ${C.dim}(${row.name}.html → ${row.engines.join(', ') || 'no engine'})${C.reset}`,
+ );
+ const line = [
+ row.checks.engine ? ok('engine') : no(`engine missing: ${row.missingEngines.join(', ')}`),
+ row.checks.viteInput ? ok('vite input') : no('no vite input'),
+ row.checks.devRoute ? ok('dev route') : no('no dev route'),
+ row.checks.vercelRoute ? ok('vercel route') : no('no vercel route'),
+ ].join(' ');
+ console.log(` ${line}`);
+}
+
+// Orphaned `ibm-*` Vite inputs whose page file no longer exists.
+const orphanInputs = [];
+for (const m of viteConfig.matchAll(/['"]pages\/ibm\/([a-z0-9-]+)\.html['"]/g)) {
+ const f = `${pageDir}/${m[1]}.html`;
+ if (!existsSync(r(f)) && !orphanInputs.includes(f)) orphanInputs.push(f);
+}
+if (orphanInputs.length) {
+ failures += orphanInputs.length;
+ console.log(`\n${no('orphaned Vite inputs (page deleted): ' + orphanInputs.join(', '))}`);
+}
+
+// Endpoint inventory (informational — not every page maps 1:1 to an endpoint).
+const apiDir = 'api/ibm';
+if (existsSync(r(apiDir))) {
+ const endpoints = readdirSync(r(apiDir))
+ .filter((f) => f.endsWith('.js'))
+ .map((f) => `/api/ibm/${basename(f, '.js')}`);
+ console.log(`\n${C.dim}endpoints: ${endpoints.join(', ')}${C.reset}`);
+}
+
+console.log('');
+if (failures) {
+ console.log(
+ `${C.red}${C.bold}✗ ${failures} issue(s) — a built page is not fully reachable.${C.reset}`,
+ );
+ console.log(
+ `${C.dim} Fix by adding the missing Vite input / dev route (vite.config.js), Vercel route (vercel.json), or the /src engine module.${C.reset}\n`,
+ );
+ process.exit(1);
+}
+console.log(
+ `${C.green}${C.bold}✓ every /ibm page has an engine, a Vite input, a dev route, and a Vercel route.${C.reset}\n`,
+);
diff --git a/src/constellation/main.js b/src/constellation/main.js
index 735a0296f..728fd8335 100644
--- a/src/constellation/main.js
+++ b/src/constellation/main.js
@@ -213,7 +213,15 @@ async function embedTokens(tokens) {
// ---- interaction: hover + click ------------------------------------------
let hovered = null;
-let selectedIndex = -1;
+let selectedNode = null;
+
+// The glow scale for a node depends on its state: selected stars stay largest,
+// hovered stars enlarge for feedback, everything else sits at its base size.
+function glowScaleFor(node) {
+ if (node === selectedNode) return node.baseScale * 11;
+ if (node === hovered) return node.baseScale * 9;
+ return node.baseScale * 6;
+}
function updatePointer(e) {
pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
@@ -228,11 +236,12 @@ function onPointerMove(e) {
updatePointer(e);
const node = pickNode();
if (node !== hovered) {
- if (hovered) hovered.glow.scale.setScalar(hovered.baseScale * 6);
+ const prev = hovered;
hovered = node;
+ if (prev) prev.glow.scale.setScalar(glowScaleFor(prev));
renderer.domElement.style.cursor = node ? 'pointer' : 'grab';
if (node) {
- node.glow.scale.setScalar(node.baseScale * 9);
+ node.glow.scale.setScalar(glowScaleFor(node));
tipSym.textContent = node.token.symbol;
tipNm.textContent = node.token.name;
tooltip.style.left = `${e.clientX}px`;
@@ -262,7 +271,10 @@ function onPointerUp(e) {
let analysisAbort = null;
function selectNode(index) {
- selectedIndex = index;
+ const prev = selectedNode;
+ selectedNode = nodes[index];
+ if (prev && prev !== selectedNode) prev.glow.scale.setScalar(glowScaleFor(prev));
+ selectedNode.glow.scale.setScalar(glowScaleFor(selectedNode));
const { token } = nodes[index];
hint.style.opacity = '0';
@@ -300,6 +312,7 @@ function formatPrice(p) {
function closePanel() {
panel.classList.remove('open');
panel.setAttribute('aria-hidden', 'true');
+ if (selectedNode) { const n = selectedNode; selectedNode = null; n.glow.scale.setScalar(glowScaleFor(n)); }
if (analysisAbort) { analysisAbort.abort(); analysisAbort = null; }
}
diff --git a/src/ibm-galaxy.js b/src/ibm-galaxy.js
index 6376efd0c..6768fb8ad 100644
--- a/src/ibm-galaxy.js
+++ b/src/ibm-galaxy.js
@@ -26,7 +26,7 @@ const els = {
loading: $('loadingState'), empty: $('emptyState'), unavailable: $('unavailableState'),
error: $('errorState'), errorMsg: $('errorMsg'), emptyTitle: $('emptyTitle'), emptyMsg: $('emptyMsg'),
unavailableMsg: $('unavailableMsg'), loadSteps: $('loadSteps'), retryBtn: $('retryBtn'),
- resetView: $('resetView'), hudHint: $('hudHint'),
+ resetView: $('resetView'), hudHint: $('hudHint'), tourBtn: $('tourBtn'),
};
// ── State ─────────────────────────────────────────────────────────────────────
@@ -79,7 +79,7 @@ function initThree() {
controls.autoRotate = true;
controls.autoRotateSpeed = 0.35;
controls.target.set(0, 0, 0);
- controls.addEventListener('start', () => { controls.autoRotate = false; idleTimer = 0; });
+ controls.addEventListener('start', () => { controls.autoRotate = false; idleTimer = 0; if (tour.active) stopTour(); });
raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 3.2;
@@ -333,22 +333,29 @@ function selectAgent(idx, doFly) {
const c = state.clusters[a.cluster];
if (doFly) flyTo(new THREE.Vector3(a.x, a.y, a.z), 60);
+ const neighbors = semanticNeighbors(a, 5);
+ drawLinks(idx, neighbors);
+ setUrlParam('agent', a.id);
+
els.panelHead.innerHTML =
avatarMarkup(a, 'p-avatar') +
`<div class="p-theme" style="color:${c?.color || '#fff'}"><span class="swatch" style="background:${c?.color}"></span>${escapeHtml(c?.label || 'Agent')}</div>` +
`<div class="p-name">${escapeHtml(a.name)}</div>`;
- const neighbors = nearestNeighbors(idx, 4);
const nbMarkup = neighbors.map((nb) => {
- const na = state.agents[nb.idx];
+ const na = nb.agent;
+ const meta = nb.score != null
+ ? `<span class="pct">${Math.round(nb.score * 100)}%</span> similar`
+ : escapeHtml(state.clusters[na.cluster]?.label || '');
return `<div class="nb" data-idx="${nb.idx}">${avatarMarkup(na, 'nb-av')}` +
`<div class="nb-meta"><div class="nb-name">${escapeHtml(na.name)}</div>` +
- `<div class="nb-sim">${escapeHtml(state.clusters[na.cluster]?.label || '')}</div></div></div>`;
+ `<div class="nb-sim">${meta}</div></div></div>`;
}).join('');
+ const sourceNote = neighbors.length && neighbors[0].score != null ? ' <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--muted)">· by Granite cosine</span>' : '';
els.panelBody.innerHTML =
`<div class="p-desc">${escapeHtml(a.description || 'No description provided.')}</div>` +
- (neighbors.length ? `<div class="p-section neighbors"><h4>Nearest in meaning</h4>${nbMarkup}</div>` : '') +
+ (neighbors.length ? `<div class="p-section neighbors"><h4>Nearest in meaning${sourceNote}</h4>${nbMarkup}</div>` : '') +
`<a class="p-cta" href="${escapeAttr(a.url)}">Open agent →</a>`;
els.panelBody.querySelectorAll('.nb').forEach((row) => {
@@ -365,11 +372,24 @@ function closePanel() {
if (state.selected >= 0 && state.selected !== state.hovered) aHi[state.selected] = 0;
state.selected = -1;
geometry.attributes.aHi.needsUpdate = true;
+ clearLinks();
+ setUrlParam('agent', null);
+}
+
+// Semantic neighbours: prefer the server's Granite-cosine ranking (true meaning),
+// falling back to 3D proximity only if the payload predates that field.
+function semanticNeighbors(agent, k) {
+ if (Array.isArray(agent.neighbors) && agent.neighbors.length) {
+ return agent.neighbors.slice(0, k).map((nb) => {
+ const na = state.byId.get(nb.id);
+ return na ? { agent: na, idx: state.agents.indexOf(na), score: nb.score } : null;
+ }).filter(Boolean);
+ }
+ return nearestNeighbors3D(state.agents.indexOf(agent), k).map((nb) => ({ agent: state.agents[nb.idx], idx: nb.idx, score: null }));
}
-// Nearest neighbours by 3D distance — the same proximity the eye sees, a faithful
-// proxy for embedding similarity in the projected space.
-function nearestNeighbors(idx, k) {
+// Fallback nearest neighbours by 3D distance — the proximity the eye sees.
+function nearestNeighbors3D(idx, k) {
const a = state.agents[idx];
const out = [];
for (let i = 0; i < state.agents.length; i++) {
@@ -382,6 +402,34 @@ function nearestNeighbors(idx, k) {
return out.slice(0, k);
}
+// ── Constellation links ───────────────────────────────────────────────────────
+// Faint glowing lines from the selected agent to its semantic neighbours —
+// literally drawing the constellation the embedding implies.
+let linkLines = null;
+function clearLinks() {
+ if (linkLines) { scene.remove(linkLines); linkLines.geometry.dispose(); linkLines.material.dispose(); linkLines = null; }
+}
+function drawLinks(idx, neighbors) {
+ clearLinks();
+ if (!neighbors.length) return;
+ const a = state.agents[idx];
+ const col = new THREE.Color(a.color);
+ const pos = [];
+ const colors = [];
+ for (const nb of neighbors) {
+ const b = nb.agent;
+ pos.push(a.x, a.y, a.z, b.x, b.y, b.z);
+ // Brighter near the selected end, dimmer at the neighbour end.
+ colors.push(col.r, col.g, col.b, col.r * 0.5, col.g * 0.5, col.b * 0.5);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(pos), 3));
+ g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
+ const m = new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.55, blending: THREE.AdditiveBlending, depthWrite: false });
+ linkLines = new THREE.LineSegments(g, m);
+ scene.add(linkLines);
+}
+
// ── Legend ────────────────────────────────────────────────────────────────────
function buildLegend() {
els.legendRows.innerHTML = '';
@@ -401,9 +449,15 @@ function buildLegend() {
}
function toggleIsolate(clusterId) {
+ stopTour();
state.isolatedCluster = state.isolatedCluster === clusterId ? null : clusterId;
if (state.searchActive) clearSearch();
applyVisibility();
+ // When isolating a theme, fly to its centroid so the user actually sees it.
+ if (state.isolatedCluster !== null) {
+ const c = state.clusters[clusterId];
+ if (c) flyTo(new THREE.Vector3(c.x, c.y, c.z), 95);
+ }
els.legendRows.querySelectorAll('.row').forEach((row) => {
const isMuted = state.isolatedCluster !== null && Number(row.dataset.cluster) !== state.isolatedCluster;
row.classList.toggle('muted', isMuted);
@@ -427,6 +481,41 @@ function scoreToBrightness(score) {
return Math.max(0, Math.min(1, (score - 0.18) / 0.42));
}
+// ── Guided tour ───────────────────────────────────────────────────────────────
+// Hands-free fly-through of every Granite-named theme — great for an unattended
+// demo loop. Each step isolates a theme, flies to its centroid, and surfaces its
+// label; any user interaction stops it.
+const tour = { active: false, i: 0, timer: 0 };
+function toggleTour() { tour.active ? stopTour() : startTour(); }
+function startTour() {
+ const themed = state.clusters.filter((c) => c.size);
+ if (themed.length < 2) return;
+ if (state.searchActive) clearSearch();
+ if (els.panel.classList.contains('open')) closePanel();
+ tour.active = true; tour.i = 0;
+ els.tourBtn.classList.add('active');
+ flashHudHint('Guided tour — touring the themes Granite named. Interact to stop.');
+ tourStep(themed);
+ tour.timer = setInterval(() => tourStep(themed), 4800);
+}
+function tourStep(themed) {
+ const c = themed[tour.i % themed.length];
+ tour.i++;
+ state.isolatedCluster = c.id;
+ applyVisibility();
+ els.legendRows.querySelectorAll('.row').forEach((r) => r.classList.toggle('muted', Number(r.dataset.cluster) !== c.id));
+ flyTo(new THREE.Vector3(c.x, c.y, c.z), 95);
+}
+function stopTour() {
+ if (!tour.active) return;
+ tour.active = false;
+ clearInterval(tour.timer);
+ els.tourBtn.classList.remove('active');
+ state.isolatedCluster = null;
+ applyVisibility();
+ els.legendRows.querySelectorAll('.row').forEach((r) => r.classList.remove('muted'));
+}
+
// ── Stats ─────────────────────────────────────────────────────────────────────
function buildStats() {
const m = state.data.meta;
@@ -463,6 +552,9 @@ function wireSearch() {
}
async function runSearch(query) {
+ stopTour();
+ setUrlParam('q', query);
+ setUrlParam('agent', null);
els.searchBox.classList.add('searching');
try {
const res = await fetch('/api/ibm/galaxy', {
@@ -531,6 +623,7 @@ function clearSearch() {
for (const a of state.agents) a._score = null;
els.results.classList.remove('show');
applyVisibility();
+ setUrlParam('q', null);
}
// ── Markup helpers ────────────────────────────────────────────────────────────
@@ -539,6 +632,16 @@ function avatarMarkup(a, cls) {
return `<div class="${cls} placeholder">${escapeHtml((a.name[0] || '?').toUpperCase())}</div>`;
}
function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
+// Reflect view state into the URL so a selected agent / active search is a
+// shareable link (no history spam — replaceState).
+function setUrlParam(key, val) {
+ try {
+ const url = new URL(window.location.href);
+ if (val == null || val === '') url.searchParams.delete(key);
+ else url.searchParams.set(key, val);
+ window.history.replaceState(null, '', url);
+ } catch { /* older browsers without URL/replaceState — non-fatal */ }
+}
function escapeAttr(s) { return escapeHtml(s); }
function hexA(hex, a) {
const h = hex.replace('#', '');
@@ -612,6 +715,7 @@ async function load() {
showOnly(null);
els.loading.classList.remove('show');
flashHudHint(`Drag to orbit · scroll to zoom · click a star to explore · press <b>/</b> to search`);
+ applyDeepLink();
document.body.dataset.galaxyState = 'ready';
// Read-only introspection handle for support/debugging a 3D scene that can't
@@ -623,6 +727,8 @@ async function load() {
points: () => points,
starCount: () => (points ? points.geometry.attributes.position.count : 0),
rendererInfo: () => renderer.info.render,
+ linkCount: () => (linkLines ? linkLines.geometry.attributes.position.count / 2 : 0),
+ tourActive: () => tour.active,
};
}
@@ -632,6 +738,23 @@ function flashHudHint(html) {
setTimeout(() => els.hudHint.classList.remove('show'), 6500);
}
+// Honour a shareable URL: ?agent=<id> selects + flies to a star, ?q=<text>
+// runs a semantic search. Lets a demo link open straight to the right view.
+function applyDeepLink() {
+ try {
+ const params = new URLSearchParams(window.location.search);
+ const agentId = params.get('agent');
+ const q = params.get('q');
+ if (agentId && state.byId.has(agentId)) {
+ selectAgent(state.agents.indexOf(state.byId.get(agentId)), true);
+ } else if (q) {
+ els.searchInput.value = q;
+ els.searchClear.style.display = 'block';
+ runSearch(q);
+ }
+ } catch { /* malformed URL — ignore */ }
+}
+
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
@@ -641,7 +764,8 @@ function onResize() {
function wireGlobalUI() {
els.panelClose.addEventListener('click', closePanel);
- els.resetView.addEventListener('click', () => { resetView(); state.isolatedCluster = null; if (state.searchActive) clearSearch(); applyVisibility(); els.legendRows.querySelectorAll('.row').forEach((r) => r.classList.remove('muted')); });
+ els.resetView.addEventListener('click', () => { stopTour(); resetView(); state.isolatedCluster = null; if (state.searchActive) clearSearch(); applyVisibility(); els.legendRows.querySelectorAll('.row').forEach((r) => r.classList.remove('muted')); });
+ els.tourBtn.addEventListener('click', toggleTour);
els.retryBtn.addEventListener('click', () => load());
window.addEventListener('keydown', (e) => {
if (e.key === '/' && document.activeElement !== els.searchInput) { e.preventDefault(); els.searchInput.focus(); }
diff --git a/src/ibm-oracle.js b/src/ibm-oracle.js
index 571b5c785..a490631dc 100644
--- a/src/ibm-oracle.js
+++ b/src/ibm-oracle.js
@@ -53,7 +53,10 @@ controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.dampingFactor = 0.06;
controls.enablePan = false;
-controls.autoRotate = true;
+// Respect the OS "reduce motion" setting: no idle camera spin (and no forecast
+// sweep — see renderSeries). Users who opt out of motion get a static scene.
+const reduceMotion = !!window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
+controls.autoRotate = !reduceMotion;
controls.autoRotateSpeed = 0.5;
controls.minDistance = 6;
controls.maxDistance = 22;
diff --git a/src/ibm-proof.js b/src/ibm-proof.js
index 94affcef9..b9fa91884 100644
--- a/src/ibm-proof.js
+++ b/src/ibm-proof.js
@@ -31,6 +31,21 @@ function fmtPct(n) {
}
const MOOD_COLOR = { celebration: '#42be65', curiosity: '#78a9ff', patience: '#8a93a6', empathy: '#f1c21b', concern: '#fa4d56' };
const MOOD_ANIM = { celebration: 'celebrate', curiosity: 'wave', patience: 'idle', empathy: 'idle', concern: 'idle' };
+// The embed applies ARKit-52 morphs by name (v1.avatar.morphs). Each mood is a
+// blend; we always send the full key set (zeros included) so switching moods
+// clears the previous expression rather than stacking.
+const NEUTRAL_MORPHS = {
+ mouthSmileLeft: 0, mouthSmileRight: 0, cheekSquintLeft: 0, cheekSquintRight: 0,
+ mouthFrownLeft: 0, mouthFrownRight: 0, browInnerUp: 0, browDownLeft: 0, browDownRight: 0,
+ jawOpen: 0, eyeWideLeft: 0, eyeWideRight: 0,
+};
+const MOOD_MORPHS = {
+ celebration: { ...NEUTRAL_MORPHS, mouthSmileLeft: 0.9, mouthSmileRight: 0.9, cheekSquintLeft: 0.45, cheekSquintRight: 0.45 },
+ curiosity: { ...NEUTRAL_MORPHS, browInnerUp: 0.5, eyeWideLeft: 0.5, eyeWideRight: 0.5, mouthSmileLeft: 0.3, mouthSmileRight: 0.3 },
+ patience: { ...NEUTRAL_MORPHS },
+ empathy: { ...NEUTRAL_MORPHS, mouthSmileLeft: 0.25, mouthSmileRight: 0.25, browInnerUp: 0.4 },
+ concern: { ...NEUTRAL_MORPHS, mouthFrownLeft: 0.65, mouthFrownRight: 0.65, browInnerUp: 0.55 },
+};
// ── 3D avatar bridge (queue until the iframe handshakes ready) ───────────────
const avatar = (() => {
@@ -58,7 +73,7 @@ const avatar = (() => {
});
return {
speak: (text) => text && send({ type: 'v1.avatar.speak', text: String(text).slice(0, 600) }),
- emote: (name, weight = 0.8) => name && send({ type: 'v1.avatar.emote', name, weight }),
+ morphs: (weights) => weights && send({ type: 'v1.avatar.morphs', weights }),
animate: (name) => name && send({ type: 'v1.avatar.animation', name }),
};
})();
@@ -69,7 +84,7 @@ function setMood(mood) {
if (!mood) { sw.style.background = 'var(--faint)'; tx.textContent = 'awaiting forecast'; return; }
sw.style.background = MOOD_COLOR[mood.emotion] || 'var(--faint)';
tx.textContent = `${mood.emotion} · sentiment ${mood.sentiment >= 0 ? '+' : ''}${mood.sentiment}`;
- avatar.emote(mood.emotion, Math.min(1, 0.4 + Math.abs(mood.sentiment)));
+ avatar.morphs(MOOD_MORPHS[mood.emotion] || NEUTRAL_MORPHS);
avatar.animate(MOOD_ANIM[mood.emotion] || 'idle');
}
function setCaption(text) {
@@ -104,10 +119,10 @@ function drawChart(data) {
if (all.length < 2) return;
const ys = all.map((p) => p.c);
- let lo = Math.min(...ys), hi = Math.max(...ys);
- if (data.stats) { lo = Math.min(lo, data.stats.forecastLow); hi = Math.max(hi, data.stats.forecastHigh); }
- const span = hi - lo || hi || 1;
- lo -= span * 0.08; hi += span * 0.08;
+ let trueLo = Math.min(...ys), trueHi = Math.max(...ys);
+ if (data.stats) { trueLo = Math.min(trueLo, data.stats.forecastLow); trueHi = Math.max(trueHi, data.stats.forecastHigh); }
+ const span = trueHi - trueLo || trueHi || 1;
+ const lo = trueLo - span * 0.08, hi = trueHi + span * 0.08;
const n = all.length;
const x = (i) => pad.l + (i / (n - 1)) * W;
const y = (v) => pad.t + (1 - (v - lo) / (hi - lo)) * H;
@@ -159,6 +174,21 @@ function drawChart(data) {
ctx.fillStyle = '#8a93a6';
ctx.beginPath(); ctx.arc(x(li), y(histTail[li].c), 3, 0, Math.PI * 2); ctx.fill();
}
+
+ // axis labels — true price range + the now / horizon markers
+ ctx.font = '11px ui-monospace, "SF Mono", monospace';
+ ctx.textAlign = 'left';
+ ctx.fillStyle = '#5a6376';
+ ctx.textBaseline = 'top'; ctx.fillText(fmtPrice(trueHi), pad.l + 3, y(trueHi) + 2);
+ ctx.textBaseline = 'bottom'; ctx.fillText(fmtPrice(trueLo), pad.l + 3, y(trueLo) - 2);
+ if (fc.length) {
+ ctx.fillStyle = '#78a9ff';
+ ctx.textBaseline = 'top'; ctx.textAlign = 'center';
+ ctx.fillText('now', splitX, pad.t + 2);
+ const hz = data.stats?.horizonHours;
+ if (hz) { ctx.textAlign = 'right'; ctx.fillText(`+${hz}h`, pad.l + W - 3, pad.t + 2); }
+ ctx.textAlign = 'left';
+ }
}
// ── render: stats / governance / proof / action ──────────────────────────────
@@ -328,8 +358,11 @@ function renderPicker() {
const sym = (p.name || '?').split('/')[0].trim() || '?';
const nm = p.name || '';
const px = p.priceUsd != null ? fmtPrice(Number(p.priceUsd)) : '';
+ const chg = p.change24h != null
+ ? `<span style="color:${p.change24h >= 0 ? 'var(--up)' : 'var(--down)'};margin-left:7px">${p.change24h >= 0 ? '+' : ''}${Number(p.change24h).toFixed(1)}%</span>`
+ : '';
return `<button class="chip" role="tab" data-pool="${p.pool}" aria-selected="${i === 0 ? 'true' : 'false'}">
- <span class="sym">${sym}</span><span class="nm">${nm}</span><span class="px">${px}</span>
+ <span class="sym">${sym}</span><span class="nm">${nm}</span><span class="px">${px}${chg}</span>
</button>`;
}).join('');
el.querySelectorAll('.chip').forEach((c) => c.addEventListener('click', () => {
diff --git a/src/ibm-trust-layer.js b/src/ibm-trust-layer.js
index 541c08520..6d3be131f 100644
--- a/src/ibm-trust-layer.js
+++ b/src/ibm-trust-layer.js
@@ -54,7 +54,7 @@ const els = {
amountWrap: $('amountWrap'), amount: $('amount'), runBtn: $('runBtn'), modelPill: $('modelPill'),
verdict: $('verdict'), vDecision: $('vDecision'), vMeta: $('vMeta'), vReasons: $('vReasons'),
risks: $('risks'), riskRows: $('riskRows'),
- ledgerBody: $('ledgerBody'), ledgerCnt: $('ledgerCnt'), verifyBtn: $('verifyBtn'), verifyLabel: null,
+ ledgerBody: $('ledgerBody'), ledgerCnt: $('ledgerCnt'), verifyBtn: $('verifyBtn'), verifyLabel: null, exportBtn: $('exportBtn'),
loading: $('loadingState'), unavailable: $('unavailableState'), error: $('errorState'),
errorMsg: $('errorMsg'), retryBtn: $('retryBtn'), toast: $('toast'),
};
@@ -376,6 +376,7 @@ function pushLedger(data, ctx) {
function renderLedger() {
els.ledgerCnt.textContent = `· ${state.chain.length}`;
+ els.exportBtn.disabled = state.chain.length === 0;
if (!state.chain.length) return;
els.ledgerBody.innerHTML = state.chain
.map((e, i) => {
@@ -400,6 +401,26 @@ function resetVerifyButton() {
els.verifyLabel.textContent = 'Verify chain';
}
+// Copy the full hash-chained ledger as JSON so anyone can re-derive the chain
+// offline (the record schema matches what api/_lib/granite-guardian.js emits).
+async function exportLedger() {
+ if (!state.chain.length) return;
+ const json = JSON.stringify(state.chain.map((e) => e.record), null, 2);
+ try {
+ await navigator.clipboard.writeText(json);
+ toast(`Ledger copied — ${state.chain.length} record(s). Re-verify the SHA-256 chain anywhere.`);
+ } catch {
+ // Clipboard blocked (insecure context / permissions) — fall back to a download.
+ const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }));
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = 'granite-guardian-ledger.json';
+ a.click();
+ URL.revokeObjectURL(url);
+ toast(`Ledger downloaded — ${state.chain.length} record(s).`);
+ }
+}
+
async function sha256Hex(str) {
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str));
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
diff --git a/src/ibm-twin.js b/src/ibm-twin.js
new file mode 100644
index 000000000..775c06bda
--- /dev/null
+++ b/src/ibm-twin.js
@@ -0,0 +1,684 @@
+// Digital Twin — the living 3D market replica.
+//
+// Pulls a live Solana market's vitals + an IBM Granite TimeSeries projection from
+// /api/ibm/twin and renders the asset as a breathing "organism": a core whose
+// pulse tracks its heartbeat, whose surface churns with its volatility, and whose
+// hue is its state. Its real past flows into the core from the left; Granite's
+// projected future sweeps out to the right; a faint back-test shows how well the
+// twin has tracked reality. Live sync keeps it in step with the market, and the
+// what-if simulator perturbs the twin and re-forecasts. All data is real.
+
+import * as THREE from 'three';
+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+
+const IBM = {
+ blue: 0x0f62fe,
+ blueLight: 0x78a9ff,
+ up: 0x42be65,
+ down: 0xfa4d56,
+ warn: 0xf1c21b,
+ flat: 0x8d8d8d,
+ white: 0xf4f4f4,
+};
+// State → core hue.
+const STATE_COLOR = {
+ calm: IBM.blueLight,
+ ascending: IBM.up,
+ euphoric: 0x6fdc8c,
+ declining: IBM.warn,
+ stressed: IBM.down,
+ dormant: IBM.flat,
+};
+const SPAN_BACK = 7.5; // world-units of history (left of the core)
+const SPAN_FWD = 6.5; // world-units of projection (right of the core)
+const HEIGHT = 5.0; // world-units across the price axis
+
+// ── DOM handles ───────────────────────────────────────────────────────────────
+const $ = (id) => document.getElementById(id);
+const stage = $('twin-stage');
+const hud = {
+ name: $('t-name'),
+ state: $('t-state'),
+ price: $('t-price'),
+ momentum: $('m-momentum'),
+ vol: $('m-vol'),
+ bpm: $('m-bpm'),
+ heart: $('m-heart'),
+ activity: $('m-activity'),
+ liq: $('m-liq'),
+ voltrend: $('m-voltrend'),
+ live: $('t-live'),
+ synced: $('t-synced'),
+ persona: $('t-persona'),
+ status: $('t-status'),
+ chips: $('t-chips'),
+ search: $('t-search'),
+ spawn: $('t-spawn'),
+ projBadge: $('b-projection'),
+ fidBadge: $('b-fidelity'),
+ govBadge: $('b-gov'),
+ sim: {
+ shock: $('s-shock'),
+ shockV: $('s-shock-v'),
+ vol: $('s-vol'),
+ volV: $('s-vol-v'),
+ flip: $('s-flip'),
+ run: $('s-run'),
+ reset: $('s-reset'),
+ out: $('s-out'),
+ base: $('s-base'),
+ sim: $('s-sim'),
+ delta: $('s-delta'),
+ },
+};
+
+// ── Three.js scaffold ─────────────────────────────────────────────────────────
+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+renderer.setSize(stage.clientWidth, stage.clientHeight);
+renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+stage.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(48, stage.clientWidth / stage.clientHeight, 0.1, 200);
+camera.position.set(0.6, 2.0, 13);
+
+const controls = new OrbitControls(camera, renderer.domElement);
+controls.target.set(0, 0, 0);
+controls.enableDamping = true;
+controls.dampingFactor = 0.06;
+controls.enablePan = false;
+controls.autoRotate = true;
+controls.autoRotateSpeed = 0.45;
+controls.minDistance = 7;
+controls.maxDistance = 22;
+controls.maxPolarAngle = Math.PI * 0.62;
+
+// Floor grid
+const grid = new THREE.GridHelper(SPAN_BACK + SPAN_FWD + 4, 28, IBM.blue, 0x1b2436);
+grid.position.y = -HEIGHT / 2 - 0.8;
+grid.material.transparent = true;
+grid.material.opacity = 0.3;
+scene.add(grid);
+
+// Ambient particle field
+const particles = (() => {
+ const n = 340;
+ const geo = new THREE.BufferGeometry();
+ const pos = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) {
+ pos[i * 3] = (Math.random() - 0.5) * (SPAN_BACK + SPAN_FWD) * 1.3;
+ pos[i * 3 + 1] = (Math.random() - 0.5) * HEIGHT * 2;
+ pos[i * 3 + 2] = (Math.random() - 0.5) * 7;
+ }
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ const mat = new THREE.PointsMaterial({
+ color: IBM.blueLight,
+ size: 0.035,
+ transparent: true,
+ opacity: 0.5,
+ depthWrite: false,
+ });
+ const pts = new THREE.Points(geo, mat);
+ scene.add(pts);
+ return pts;
+})();
+
+// ── The living core — a breathing, churning organism ─────────────────────────
+const core = (() => {
+ const geo = new THREE.IcosahedronGeometry(1, 4);
+ const base = geo.attributes.position.array.slice(); // pristine vertex positions
+ const solid = new THREE.Mesh(
+ geo,
+ new THREE.MeshBasicMaterial({ color: STATE_COLOR.calm, transparent: true, opacity: 0.92 }),
+ );
+ const shellGeo = new THREE.IcosahedronGeometry(1.28, 2);
+ const shell = new THREE.Mesh(
+ shellGeo,
+ new THREE.MeshBasicMaterial({ color: IBM.white, wireframe: true, transparent: true, opacity: 0.18 }),
+ );
+ const halo = new THREE.Mesh(
+ new THREE.SphereGeometry(1.7, 28, 28),
+ new THREE.MeshBasicMaterial({ color: STATE_COLOR.calm, transparent: true, opacity: 0.07, depthWrite: false }),
+ );
+ const group = new THREE.Group();
+ group.add(halo, solid, shell);
+ scene.add(group);
+ return { group, solid, shell, halo, geo, base };
+})();
+
+// Target vitals the core eases toward (so live updates are smooth, not jumpy).
+const vitalsTarget = { color: new THREE.Color(STATE_COLOR.calm), turbulence: 0.04, pulseHz: 1, activity: 0.4, scale: 1 };
+const vitalsNow = { color: new THREE.Color(STATE_COLOR.calm), turbulence: 0.04, pulseHz: 1, activity: 0.4, scale: 1 };
+
+function setVitals(v) {
+ if (!v) return;
+ const col = STATE_COLOR[v.state?.key] || STATE_COLOR.calm;
+ vitalsTarget.color.set(col);
+ vitalsTarget.turbulence = 0.03 + (v.signals?.volatility ?? 0) * 0.26;
+ vitalsTarget.pulseHz = (v.heartbeatBpm || 60) / 60;
+ vitalsTarget.activity = v.signals?.activity ?? 0.4;
+ vitalsTarget.scale = 1 + (v.signals?.activity ?? 0.4) * 0.18;
+}
+
+// ── Trajectory geometry (history, projection, back-test, scenario) ────────────
+let mapY = () => 0;
+let mapXHist = () => 0;
+let mapXProj = () => 0;
+
+let histGroup = new THREE.Group();
+let projGroup = new THREE.Group();
+let fidGroup = new THREE.Group();
+let simGroup = new THREE.Group();
+let projDimmed = false; // true while a scenario has faded the live projection
+scene.add(histGroup, projGroup, fidGroup, simGroup);
+
+function disposeGroup(g) {
+ g.traverse((o) => {
+ if (o.geometry) o.geometry.dispose();
+ if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => m.dispose());
+ });
+ scene.remove(g);
+}
+function replace(oldGroup) {
+ disposeGroup(oldGroup);
+ const g = new THREE.Group();
+ scene.add(g);
+ return g;
+}
+
+function downsample(arr, max) {
+ if (arr.length <= max) return arr;
+ const step = (arr.length - 1) / (max - 1);
+ const out = [];
+ for (let i = 0; i < max; i++) out.push(arr[Math.round(i * step)]);
+ return out;
+}
+
+function glowTube(points, color, radius, opacity = 1, clip = null) {
+ const curve = new THREE.CatmullRomCurve3(points);
+ const seg = Math.min(600, Math.max(8, points.length * 4));
+ const core_ = new THREE.Mesh(
+ new THREE.TubeGeometry(curve, seg, radius, 8, false),
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity, clippingPlanes: clip }),
+ );
+ const halo = new THREE.Mesh(
+ new THREE.TubeGeometry(curve, seg, radius * 2.6, 8, false),
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: opacity * 0.16, depthWrite: false, clippingPlanes: clip }),
+ );
+ const g = new THREE.Group();
+ g.add(core_, halo);
+ return g;
+}
+function marker(pos, color, r = 0.13) {
+ const m = new THREE.Mesh(new THREE.SphereGeometry(r, 18, 18), new THREE.MeshBasicMaterial({ color }));
+ m.position.copy(pos);
+ const halo = new THREE.Mesh(
+ new THREE.SphereGeometry(r * 2.4, 18, 18),
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.18, depthWrite: false }),
+ );
+ m.add(halo);
+ return m;
+}
+function dashedLine(points, color, opacity) {
+ const geo = new THREE.BufferGeometry().setFromPoints(points);
+ const mat = new THREE.LineDashedMaterial({ color, transparent: true, opacity, dashSize: 0.18, gapSize: 0.12 });
+ const line = new THREE.Line(geo, mat);
+ line.computeLineDistances();
+ return line;
+}
+
+// Build the coordinate maps + render history, projection and (optional) back-test.
+function renderSnapshot(data) {
+ const history = downsample(data.history || [], 150);
+ const projection = data.projection?.points || [];
+ const fid = data.fidelity;
+ if (!history.length) return;
+
+ const current = data.vitals?.currentPrice ?? history[history.length - 1].c;
+ const tNow = history[history.length - 1].t;
+ const tHist0 = history[0].t;
+ const tProjEnd = projection.length ? projection[projection.length - 1].t : tNow + 1;
+
+ const prices = [
+ ...history.map((p) => p.c),
+ ...projection.map((p) => p.c),
+ ...(fid ? fid.realized.map((p) => p.c).concat(fid.predicted.map((p) => p.c)) : []),
+ ].filter(Number.isFinite);
+ const min = Math.min(...prices);
+ const max = Math.max(...prices);
+ const range = max - min || Math.abs(current) || 1;
+
+ mapY = (c) => ((c - current) / range) * HEIGHT;
+ mapXHist = (t) => ((t - tNow) / Math.max(1, tNow - tHist0)) * SPAN_BACK;
+ mapXProj = (t) => ((t - tNow) / Math.max(1, tProjEnd - tNow)) * SPAN_FWD;
+
+ // History ribbon flowing into the core.
+ histGroup = replace(histGroup);
+ const histPts = history.map((p) => new THREE.Vector3(mapXHist(p.t), mapY(p.c), 0));
+ histGroup.add(glowTube(histPts, IBM.blueLight, 0.03, 0.85));
+
+ // "Now" seam at the core.
+ const seamLine = new THREE.Mesh(
+ new THREE.PlaneGeometry(0.012, HEIGHT * 1.1),
+ new THREE.MeshBasicMaterial({ color: IBM.white, transparent: true, opacity: 0.22, side: THREE.DoubleSide }),
+ );
+ seamLine.position.set(0, 0, 0);
+ histGroup.add(seamLine);
+
+ // Projection ghost sweeping out to the right.
+ projGroup = replace(projGroup);
+ projDimmed = false;
+ if (projection.length && data.projection?.stats) {
+ const dir = data.projection.stats.direction;
+ const col = dir === 'up' ? IBM.up : dir === 'down' ? IBM.down : IBM.flat;
+ const seam = new THREE.Vector3(0, 0, 0);
+ const fPts = [seam, ...projection.map((p) => new THREE.Vector3(mapXProj(p.t), mapY(p.c), 0))];
+ projGroup.add(glowTube(fPts, col, 0.04, 0.95));
+ projGroup.add(uncertaintyRibbon(fPts, mapY(data.projection.stats.high) - mapY(data.projection.stats.low), col));
+ projGroup.add(marker(fPts[fPts.length - 1], col, 0.15));
+ }
+
+ // Back-test: faint realized vs predicted, drawn over the recent past so you can
+ // literally see how closely the twin tracked reality.
+ fidGroup = replace(fidGroup);
+ if (fid && fid.realized?.length && fid.predicted?.length) {
+ const rPts = fid.realized.map((p) => new THREE.Vector3(mapXHist(p.t), mapY(p.c), 0.02));
+ const pPts = fid.predicted.map((p, i) => new THREE.Vector3(mapXHist(fid.realized[i]?.t ?? p.t), mapY(p.c), 0.02));
+ fidGroup.add(dashedLine(rPts, IBM.white, 0.35));
+ fidGroup.add(dashedLine(pPts, 0x33b1ff, 0.5));
+ }
+
+ controls.target.set((SPAN_FWD - SPAN_BACK) / 6, 0, 0);
+}
+
+function uncertaintyRibbon(pts, fullBand, color) {
+ const half = Math.max(0.05, Math.abs(fullBand) / 2);
+ const geo = new THREE.BufferGeometry();
+ const verts = [];
+ for (let i = 0; i < pts.length; i++) {
+ const f = i / (pts.length - 1);
+ const hb = half * f;
+ verts.push(pts[i].x, pts[i].y + hb, 0, pts[i].x, pts[i].y - hb, 0);
+ }
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
+ const idx = [];
+ for (let i = 0; i < pts.length - 1; i++) {
+ const a = i * 2;
+ idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
+ }
+ geo.setIndex(idx);
+ return new THREE.Mesh(
+ geo,
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.14, side: THREE.DoubleSide, depthWrite: false }),
+ );
+}
+
+// Render a what-if simulation: baseline ghost (dimmed) + scenario ghost (bold).
+function renderScenario(data) {
+ simGroup = replace(simGroup);
+ if (!data.baseline?.points?.length || !data.simulated?.points?.length) return;
+ const seam = new THREE.Vector3(0, 0, 0);
+ const basePts = [seam, ...data.baseline.points.map((p) => new THREE.Vector3(mapXProj(p.t), mapY(p.c), 0.04))];
+ const simPts = [seam, ...data.simulated.points.map((p) => new THREE.Vector3(mapXProj(p.t), mapY(p.c), 0.04))];
+ simGroup.add(dashedLine(basePts, IBM.flat, 0.45));
+ const simDir = data.simulated.stats.direction;
+ const simCol = simDir === 'up' ? IBM.up : simDir === 'down' ? IBM.down : IBM.warn;
+ simGroup.add(glowTube(simPts, IBM.warn, 0.045, 0.95));
+ simGroup.add(marker(simPts[simPts.length - 1], simCol, 0.16));
+ // Dim the live projection while a scenario is on screen — once, so repeated
+ // runs don't compound. renderSnapshot() rebuilds projGroup and clears the flag.
+ if (!projDimmed) {
+ projGroup.traverse((o) => {
+ if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => (m.opacity *= 0.35));
+ });
+ projDimmed = true;
+ }
+}
+function clearScenario() {
+ simGroup = replace(simGroup);
+}
+
+// ── Animation loop ────────────────────────────────────────────────────────────
+let running = true;
+const tmpV = new THREE.Vector3();
+function animate() {
+ if (!running) return;
+ requestAnimationFrame(animate);
+ const t = performance.now() / 1000;
+ controls.update();
+ particles.rotation.y += 0.0007;
+
+ // Ease the core vitals toward their targets.
+ vitalsNow.color.lerp(vitalsTarget.color, 0.05);
+ vitalsNow.turbulence += (vitalsTarget.turbulence - vitalsNow.turbulence) * 0.05;
+ vitalsNow.pulseHz += (vitalsTarget.pulseHz - vitalsNow.pulseHz) * 0.05;
+ vitalsNow.activity += (vitalsTarget.activity - vitalsNow.activity) * 0.05;
+ vitalsNow.scale += (vitalsTarget.scale - vitalsNow.scale) * 0.05;
+
+ core.solid.material.color.copy(vitalsNow.color);
+ core.halo.material.color.copy(vitalsNow.color);
+ core.halo.material.opacity = 0.05 + vitalsNow.activity * 0.1;
+ core.shell.material.opacity = 0.12 + vitalsNow.activity * 0.16;
+
+ // Heartbeat: a sharp pulse at the twin's bpm.
+ const beat = Math.pow(0.5 + 0.5 * Math.sin(t * Math.PI * 2 * vitalsNow.pulseHz), 6);
+ const pulse = vitalsNow.scale * (1 + beat * 0.07);
+ core.group.scale.setScalar(pulse);
+ core.shell.rotation.y += 0.003 + vitalsNow.activity * 0.004;
+ core.shell.rotation.x += 0.0016;
+
+ // Volatility churn: displace the core's vertices along their normals via cheap
+ // 3-axis sinusoidal noise scaled by turbulence.
+ const pos = core.geo.attributes.position;
+ const b = core.base;
+ const turb = vitalsNow.turbulence;
+ for (let i = 0; i < pos.count; i++) {
+ const ix = i * 3;
+ const bx = b[ix];
+ const by = b[ix + 1];
+ const bz = b[ix + 2];
+ const n =
+ Math.sin(bx * 3.1 + t * 2.0) * Math.cos(by * 2.7 - t * 1.6) +
+ Math.sin(bz * 3.4 + t * 1.3) * 0.6;
+ const d = 1 + n * turb;
+ pos.setXYZ(i, bx * d, by * d, bz * d);
+ }
+ pos.needsUpdate = true;
+
+ renderer.render(scene, camera);
+}
+function onResize() {
+ const w = stage.clientWidth;
+ const h = stage.clientHeight;
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ renderer.setSize(w, h);
+}
+window.addEventListener('resize', onResize);
+document.addEventListener('visibilitychange', () => {
+ running = !document.hidden;
+ if (running) animate();
+});
+animate();
+
+// ── Embodied narrator (optional, graceful) ────────────────────────────────────
+const avatar = document.querySelector('agent-3d');
+let avatarReady = false;
+if (avatar) {
+ avatar.addEventListener('agent:ready', () => (avatarReady = true));
+ avatar.addEventListener('agent:error', () => (avatarReady = false));
+}
+function narrate(text, emotion, sentiment) {
+ if (!text) return;
+ if (avatarReady && typeof avatar.say === 'function') {
+ try {
+ avatar.say(text, { sentiment });
+ } catch {
+ speak(text);
+ }
+ if (emotion) {
+ avatar.dispatchEvent(
+ new CustomEvent('agent:action', { detail: { type: 'emote', payload: { trigger: emotion, weight: 1 } } }),
+ );
+ }
+ } else {
+ speak(text);
+ }
+}
+function speak(text) {
+ try {
+ if (!window.speechSynthesis) return;
+ window.speechSynthesis.cancel();
+ const u = new SpeechSynthesisUtterance(text);
+ window.speechSynthesis.speak(u);
+ } catch {
+ /* no speech available */
+ }
+}
+
+// ── Formatting ────────────────────────────────────────────────────────────────
+const fmtPrice = (p) => {
+ if (!Number.isFinite(p)) return '—';
+ if (p >= 1) return `$${p.toLocaleString(undefined, { maximumFractionDigits: 4 })}`;
+ return `$${p.toPrecision(4)}`;
+};
+const fmtPct = (p, dp = 2) => (Number.isFinite(p) ? `${p >= 0 ? '+' : ''}${p.toFixed(dp)}%` : '—');
+const fmtUsd = (v) => {
+ if (!Number.isFinite(v)) return '—';
+ if (v >= 1e6) return `$${(v / 1e6).toFixed(1)}M`;
+ if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}k`;
+ return `$${v.toFixed(0)}`;
+};
+const STATE_INK = {
+ calm: '#78a9ff',
+ ascending: '#42be65',
+ euphoric: '#6fdc8c',
+ declining: '#f1c21b',
+ stressed: '#fa4d56',
+ dormant: '#8d8d8d',
+};
+
+function setStatus(msg, busy = false) {
+ hud.status.textContent = msg || '';
+ hud.status.classList.toggle('busy', busy);
+ hud.spawn.disabled = busy;
+}
+
+// ── State + data flow ─────────────────────────────────────────────────────────
+let activeTarget = null; // { pool } | { token }
+let syncTimer = null;
+const SYNC_MS = 30_000;
+
+async function loadTrending() {
+ try {
+ const r = await fetch('/api/ibm/twin?list=trending');
+ const j = await r.json();
+ hud.chips.innerHTML = '';
+ (j.pools || []).forEach((p) => {
+ const chip = document.createElement('button');
+ chip.className = 'chip';
+ chip.textContent = p.name;
+ chip.title = `${p.name}${p.priceUsd != null ? ' · ' + fmtPrice(p.priceUsd) : ''}`;
+ chip.addEventListener('click', () => spawn({ pool: p.pool, label: p.name }));
+ hud.chips.appendChild(chip);
+ });
+ if (j.pools?.[0]) spawn({ pool: j.pools[0].pool, label: j.pools[0].name });
+ } catch (e) {
+ setStatus(`Could not load trending tokens: ${e.message}`);
+ }
+}
+
+let inFlight = false;
+async function spawn(target, { silent = false } = {}) {
+ if (inFlight) return;
+ inFlight = true;
+ activeTarget = target;
+ clearScenario();
+ hud.sim.out.classList.remove('show');
+ if (!silent) setStatus(`Mirroring ${target.label || target.token || 'market'} on IBM Granite…`, true);
+ try {
+ const q = target.pool ? `pool=${encodeURIComponent(target.pool)}` : `token=${encodeURIComponent(target.token)}`;
+ const r = await fetch(`/api/ibm/twin?${q}`);
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);
+ applySnapshot(data, { silent });
+ } catch (e) {
+ setStatus(`Twin failed: ${e.message}`);
+ } finally {
+ inFlight = false;
+ }
+}
+
+function applySnapshot(data, { silent } = {}) {
+ renderSnapshot(data);
+ const v = data.vitals || {};
+ setVitals(v);
+
+ const tk = data.token || {};
+ hud.name.textContent = tk.symbol ? `${tk.name} · ${tk.symbol}` : tk.name || 'Token';
+ hud.price.textContent = fmtPrice(v.currentPrice);
+
+ if (v.state) {
+ hud.state.textContent = v.state.label;
+ hud.state.style.color = STATE_INK[v.state.key] || '#78a9ff';
+ }
+ const signed = (el, val, dp) => {
+ el.textContent = fmtPct(val, dp);
+ el.className = 'v ' + (val > 0 ? 'up' : val < 0 ? 'down' : '');
+ };
+ signed(hud.momentum, v.momentumPct, 1);
+ hud.vol.textContent = Number.isFinite(v.volatilityPct) ? `${v.volatilityPct.toFixed(2)}%` : '—';
+ hud.bpm.textContent = v.heartbeatBpm ? `${v.heartbeatBpm} bpm` : '—';
+ if (v.heartbeatBpm) hud.heart.style.animationDuration = `${(60 / v.heartbeatBpm).toFixed(2)}s`;
+ hud.activity.textContent = Number.isFinite(v.activityRatio) ? `${v.activityRatio.toFixed(2)}×` : '—';
+ hud.liq.textContent = fmtUsd(v.liquidityUsd);
+ signed(hud.voltrend, v.volumeTrendPct, 0);
+
+ // Projection badge
+ if (data.projection?.model) {
+ hud.projBadge.hidden = false;
+ const s = data.projection.stats;
+ hud.projBadge.querySelector('.s').textContent =
+ `${data.projection.model} · ${fmtPct(s.changePct, 1)} / ${s.horizonHours}h`;
+ } else {
+ hud.projBadge.hidden = false;
+ hud.projBadge.querySelector('.s').textContent =
+ data.ibm?.error || data.ibm?.reason || 'projection unavailable';
+ }
+
+ // Fidelity badge
+ if (data.fidelity && data.fidelity.accuracyPct != null) {
+ hud.fidBadge.hidden = false;
+ const f = data.fidelity;
+ hud.fidBadge.querySelector('.s').textContent =
+ `${f.accuracyPct.toFixed(1)}% accurate · ${f.directionalHit ? 'direction ✓' : 'direction ✗'} · ${f.horizonHours}h`;
+ } else {
+ hud.fidBadge.hidden = true;
+ }
+
+ // Governance badge
+ if (data.governance && data.governance.passed != null) {
+ hud.govBadge.hidden = false;
+ const pass = data.governance.passed;
+ hud.govBadge.classList.toggle('fail', pass === false);
+ hud.govBadge.querySelector('.s').textContent = pass
+ ? `PASS · ${data.governance.risk}`
+ : `FLAGGED · ${data.governance.risk}`;
+ } else {
+ hud.govBadge.hidden = true;
+ }
+
+ // Persona
+ const text = data.persona?.text;
+ if (text) {
+ hud.persona.textContent = text;
+ hud.persona.classList.remove('muted');
+ if (!silent) narrate(text, v.state?.emotion, v.signals?.trend);
+ } else if (data.ibm && !data.ibm.configured) {
+ hud.persona.textContent =
+ 'IBM watsonx is not configured on this deployment — the live Granite projection, self-narration, and Granite Guardian governance run in production. The vitals and chart above are real on-chain data.';
+ hud.persona.classList.add('muted');
+ } else if (!silent) {
+ hud.persona.textContent = data.persona?.error || data.ibm?.error || 'Twin synced.';
+ hud.persona.classList.add('muted');
+ }
+
+ hud.synced.textContent = `synced ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}`;
+ setStatus('');
+}
+
+// ── Live sync ─────────────────────────────────────────────────────────────────
+function startSync() {
+ stopSync();
+ syncTimer = setInterval(() => {
+ if (activeTarget && !inFlight && !document.hidden) spawn(activeTarget, { silent: true });
+ }, SYNC_MS);
+}
+function stopSync() {
+ if (syncTimer) clearInterval(syncTimer);
+ syncTimer = null;
+}
+hud.live.addEventListener('change', () => (hud.live.checked ? startSync() : stopSync()));
+
+// ── What-if simulator ─────────────────────────────────────────────────────────
+hud.sim.shock.addEventListener('input', () => {
+ const v = Number(hud.sim.shock.value);
+ hud.sim.shockV.textContent = `${v > 0 ? '+' : ''}${v}%`;
+});
+hud.sim.vol.addEventListener('input', () => {
+ hud.sim.volV.textContent = `${Number(hud.sim.vol.value).toFixed(1)}×`;
+});
+hud.sim.reset.addEventListener('click', () => {
+ hud.sim.shock.value = 0;
+ hud.sim.vol.value = 1;
+ hud.sim.flip.checked = false;
+ hud.sim.shockV.textContent = '0%';
+ hud.sim.volV.textContent = '1.0×';
+ hud.sim.out.classList.remove('show');
+ clearScenario();
+ if (activeTarget) spawn(activeTarget, { silent: true });
+});
+
+let simInFlight = false;
+hud.sim.run.addEventListener('click', async () => {
+ if (!activeTarget || simInFlight) return;
+ simInFlight = true;
+ hud.sim.run.disabled = true;
+ const scenario = {
+ priceShockPct: Number(hud.sim.shock.value),
+ volatilityScale: Number(hud.sim.vol.value),
+ momentumFlip: hud.sim.flip.checked,
+ };
+ setStatus('Running what-if on IBM Granite…', true);
+ try {
+ const r = await fetch('/api/ibm/twin', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...activeTarget, scenario }),
+ });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || `HTTP ${r.status}`);
+ applyScenarioResult(data);
+ } catch (e) {
+ setStatus(`Scenario failed: ${e.message}`);
+ } finally {
+ simInFlight = false;
+ hud.sim.run.disabled = false;
+ }
+});
+
+function applyScenarioResult(data) {
+ if (data.baseline && data.simulated) {
+ renderScenario(data);
+ hud.sim.base.textContent = fmtPct(data.baseline.stats.changePct, 1);
+ hud.sim.sim.textContent = fmtPct(data.simulated.stats.changePct, 1);
+ const d = data.divergence?.changePctDelta;
+ hud.sim.delta.textContent = fmtPct(d, 1);
+ hud.sim.delta.style.color = d > 0 ? STATE_INK.ascending : d < 0 ? STATE_INK.stressed : STATE_INK.dormant;
+ hud.sim.out.classList.add('show');
+ }
+ const text = data.persona?.text;
+ if (text) {
+ hud.persona.textContent = text;
+ hud.persona.classList.remove('muted');
+ const dir = data.divergence?.changePctDelta ?? 0;
+ narrate(text, dir >= 0 ? 'curiosity' : 'concern', Math.tanh(dir / 15));
+ } else if (data.ibm && !data.ibm.configured) {
+ hud.persona.textContent =
+ 'IBM watsonx is not configured here — the what-if simulator re-forecasts on Granite in production. The scenario shape is computed from real history.';
+ hud.persona.classList.add('muted');
+ }
+ setStatus('');
+}
+
+// ── Wire controls ─────────────────────────────────────────────────────────────
+hud.spawn.addEventListener('click', () => {
+ const v = hud.search.value.trim();
+ if (v) spawn({ token: v, label: v.slice(0, 6) });
+});
+hud.search.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') hud.spawn.click();
+});
+
+loadTrending();
+startSync();
diff --git a/src/ibm-vision.js b/src/ibm-vision.js
index d92109170..cd7cd355e 100644
--- a/src/ibm-vision.js
+++ b/src/ibm-vision.js
@@ -374,10 +374,9 @@ function frameModel(root) {
root.position.y -= box.min.y; // feet on the ground plane
const height = size.y || 1.7;
- // Look at the upper third (where the face/identity lives) and stand back enough
- // to frame the whole figure with headroom.
- const targetY = box.min.y - box.min.y + height * 0.62;
- controls.target.set(0, targetY, 0);
+ // Feet now sit at y=0, so aim at the upper body (where the face/identity lives)
+ // and stand back far enough to frame the whole figure with headroom.
+ controls.target.set(0, height * 0.62, 0);
const dist = height * 1.5 + 0.6;
camera.position.set(0, height * 0.7, dist);
camera.near = dist / 50;
diff --git a/src/nich-agent.js b/src/nich-agent.js
index f41406103..cebc2fa50 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -420,7 +420,7 @@ export class NichAgent {
}
} else if (evt.type === 'done') {
if (!streaming || bubble) streamEl.remove();
- return { ok: true, message, reply: evt.reply || '', actions: evt.actions || [], streamEl: (streaming && !bubble) ? streamEl : null };
+ return { ok: true, message, reply: evt.reply || '', actions: evt.actions || [], governance: evt.governance || null, streamEl: (streaming && !bubble) ? streamEl : null };
} else if (evt.type === 'error') {
streamEl.remove();
return { ok: false, reason: evt.code || 'upstream_error' };
@@ -437,7 +437,7 @@ export class NichAgent {
}
}
- async _applyApiReply({ message, reply, actions, streamEl }) {
+ async _applyApiReply({ message, reply, actions, governance, streamEl }) {
this._pushHistory('user', message);
if (reply) {
@@ -454,6 +454,15 @@ export class NichAgent {
}
}
+ // IBM Granite Guardian held an autonomous action server-side (the action is
+ // already stripped from `actions`). Surface it as a status line so the hold
+ // is visible even in the streaming path, where the appended reply suffix
+ // isn't re-rendered. See api/chat.js governActions().
+ if (governance?.decision === 'block') {
+ const why = governance.reasons?.[0]?.label || 'platform policy';
+ this._addMessage('agent', `Held by the IBM Granite Guardian Trust Layer — ${why}.`, 'status');
+ }
+
for (const action of actions || []) {
try {
await this._executeAction(action);
diff --git a/src/widget-types.js b/src/widget-types.js
index 7abe90e87..fa358b03a 100644
--- a/src/widget-types.js
+++ b/src/widget-types.js
@@ -166,7 +166,9 @@ const TYPE_SCHEMAS = {
agentName: z.string().max(80).default(''),
agentTitle: z.string().max(80).default('AI Agent'),
avatar: z.enum(['embedded', 'chat-only']).default('embedded'),
- brainProvider: z.enum(['none', 'anthropic', 'custom']).default('anthropic'),
+ brainProvider: z
+ .enum(['none', 'auto', 'anthropic', 'openrouter', 'groq', 'openai', 'watsonx', 'custom'])
+ .default('anthropic'),
proxyURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
systemPrompt: z.string().max(4000).default(''),
greeting: z.string().max(280).default('Hi! Ask me anything.'),
diff --git a/tests/api/granite-oracle.test.js b/tests/api/granite-oracle.test.js
index e9e561137..14742c10e 100644
--- a/tests/api/granite-oracle.test.js
+++ b/tests/api/granite-oracle.test.js
@@ -22,12 +22,15 @@ vi.mock('../../api/_lib/watsonx-forecast.js', () => ({
watsonxForecast: vi.fn(),
forecastModelFor: vi.fn(() => 'ibm/granite-ttm-512-96-r2'),
}));
-vi.mock('../../api/_lib/guardian.js', () => ({ assessRisk: vi.fn() }));
+vi.mock('../../api/_lib/granite-guardian.js', () => ({
+ guardianConfig: vi.fn(() => ({ configured: true })),
+ assessRisk: vi.fn(),
+}));
import { fetchOhlcv, topPoolForToken, trendingPools } from '../../api/_lib/market/ohlcv.js';
import { watsonxConfig, watsonxChatComplete } from '../../api/_lib/watsonx.js';
import { watsonxForecast } from '../../api/_lib/watsonx-forecast.js';
-import { assessRisk } from '../../api/_lib/guardian.js';
+import { assessRisk } from '../../api/_lib/granite-guardian.js';
const { default: handler } = await import('../../api/ibm/oracle.js');
@@ -110,9 +113,10 @@ beforeEach(() => {
assessRisk.mockResolvedValue({
flagged: false,
risk: 'harm',
- label: 'Harm',
- verdict: 'No',
- confidence: 'High',
+ label: 'Safe',
+ probability: 0.02,
+ confidence: 'high',
+ model: 'ibm/granite-guardian-3-8b',
});
});
diff --git a/tests/api/ibm-attest.test.js b/tests/api/ibm-attest.test.js
new file mode 100644
index 000000000..1c0208e37
--- /dev/null
+++ b/tests/api/ibm-attest.test.js
@@ -0,0 +1,203 @@
+// Unit tests for /api/ibm/attest — the Granite Proof on-chain AI notary.
+//
+// Verifies the real contract without network: candles always return; the
+// forecast/narration/governance/proof fields appear only when watsonx is
+// configured; the SHA-256 digest is deterministic and the on-chain memo stays
+// within Solana's limit; the agent NOTARIZES when Granite Guardian passes and
+// REFUSES (veto) when it flags. All upstreams are mocked.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const ADDR = 'So11111111111111111111111111111111111111112';
+const POOL = '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z';
+const GUARDIAN_MODEL = 'ibm/granite-guardian-3-8b';
+
+const state = {
+ wxConfigured: false,
+ guardianVerdict: 'No', // 'No' = safe, 'Yes' = flagged
+ walletConfigured: false,
+ walletFunded: true,
+ sendSolArgs: null,
+};
+
+// ── Mocks ──────────────────────────────────────────────────────────────────
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/market/ohlcv.js', () => ({
+ trendingPools: vi.fn(async () => [
+ { pool: POOL, name: 'MOCK / SOL', baseMint: 'mint', priceUsd: 1.5, change24h: 4.2 },
+ ]),
+ topPoolForToken: vi.fn(async () => POOL),
+ fetchOhlcv: vi.fn(async () => {
+ const t0 = 1_700_000_000;
+ const candles = Array.from({ length: 600 }, (_, i) => ({ t: t0 + i * 3600, o: 1, h: 1, l: 1, c: 1 + i * 0.001, v: 1 }));
+ return { candles, base: { name: 'Mock', symbol: 'MOCK' }, quote: { symbol: 'USD' }, freq: '1h', timeframe: 'hour', aggregate: 1 };
+ }),
+}));
+
+vi.mock('../../api/_lib/watsonx.js', () => ({
+ watsonxConfig: vi.fn(() =>
+ state.wxConfigured
+ ? { configured: true, url: 'https://wx', projectId: 'proj', apiVersion: '2024-05-31', tsApiVersion: '2025-02-11', chatModel: 'ibm/granite-3-8b-instruct' }
+ : { configured: false, reason: 'WATSONX_API_KEY + project not set' },
+ ),
+ watsonxChatComplete: vi.fn(async (_cfg, opts) =>
+ opts?.model === GUARDIAN_MODEL
+ ? { text: state.guardianVerdict, model: GUARDIAN_MODEL }
+ : { text: 'The token climbs steadily. Conviction holds into the next session.', model: 'ibm/granite-3-8b-instruct' },
+ ),
+}));
+
+vi.mock('../../api/_lib/watsonx-forecast.js', () => ({
+ forecastModelFor: vi.fn(() => 'ibm/granite-ttm-512-96-r2'),
+ watsonxForecast: vi.fn(async () => {
+ const t0 = 1_700_000_000 + 600 * 3600;
+ return {
+ model: 'ibm/granite-ttm-512-96-r2',
+ timestamps: Array.from({ length: 96 }, (_, i) => new Date((t0 + i * 3600) * 1000).toISOString()),
+ values: Array.from({ length: 96 }, (_, i) => 2 + i * 0.001),
+ inputWindow: 512,
+ };
+ }),
+}));
+
+vi.mock('../../api/_lib/avatar-wallet.js', () => ({
+ avatarWalletConfig: vi.fn(() =>
+ state.walletConfigured
+ ? { configured: true, address: ADDR, network: 'mainnet', rpcUrl: 'rpc', maxSendUsd: 2 }
+ : { configured: false, address: null, network: 'mainnet' },
+ ),
+ loadAvatarKeypair: vi.fn(() => ({ publicKey: { toBase58: () => ADDR } })),
+ getConnection: vi.fn(() => ({})),
+ getSolBalance: vi.fn(async () => ({ lamports: state.walletFunded ? 1e7 : 0, sol: state.walletFunded ? 0.01 : 0 })),
+ sendSol: vi.fn(async (args) => { state.sendSolArgs = args; return 'SIG123'; }),
+ explorerTxUrl: vi.fn((s) => `https://solscan.io/tx/${s}`),
+ explorerAccountUrl: vi.fn((a) => `https://solscan.io/account/${a}`),
+}));
+
+const handler = (await import('../../api/ibm/attest.js')).default;
+
+// ── Helpers ──────────────────────────────────────────────────────────────
+function makeReq({ method = 'GET', url = '/api/ibm/attest', body = null } = {}) {
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost' };
+ return base;
+}
+function makeRes() {
+ return {
+ statusCode: 200, headers: {}, body: '', writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+async function invoke(reqOpts) {
+ const res = makeRes();
+ await handler(makeReq(reqOpts), res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ state.wxConfigured = false;
+ state.guardianVerdict = 'No';
+ state.walletConfigured = false;
+ state.walletFunded = true;
+ state.sendSolArgs = null;
+});
+
+describe('GET /api/ibm/attest', () => {
+ it('lists trending pools', async () => {
+ const { status, body } = await invoke({ url: '/api/ibm/attest?list=trending' });
+ expect(status).toBe(200);
+ expect(body.pools).toHaveLength(1);
+ expect(body.pools[0].pool).toBe(POOL);
+ });
+
+ it('returns live history but no proof when watsonx is not configured', async () => {
+ const { status, body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });
+ expect(status).toBe(200);
+ expect(body.history.length).toBe(600);
+ expect(body.forecast).toBeNull();
+ expect(body.proof).toBeNull();
+ expect(body.onchain.ready).toBe(false);
+ expect(body.onchain.reason).toMatch(/WATSONX/);
+ });
+
+ it('produces a governed proof when watsonx + wallet are configured', async () => {
+ state.wxConfigured = true;
+ state.walletConfigured = true;
+ const { status, body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });
+ expect(status).toBe(200);
+ expect(body.stats.direction).toBe('up');
+ expect(body.governance.passed).toBe(true);
+ expect(body.proof.digest).toMatch(/^[0-9a-f]{64}$/);
+ expect(body.proof.claim.models.timeseries).toBe('ibm/granite-ttm-512-96-r2');
+ expect(body.proof.claim.models.guardian).toBe(GUARDIAN_MODEL);
+ // GET never writes on-chain, but it IS ready to.
+ expect(body.onchain.submitted).toBe(false);
+ expect(body.onchain.ready).toBe(true);
+ expect(body.onchain.memo).toBe(body.proof.memo);
+ });
+
+ it('keeps the on-chain memo within Solana limits and embeds the digest', async () => {
+ state.wxConfigured = true;
+ const { body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });
+ expect(body.proof.memo.length).toBeLessThanOrEqual(180);
+ expect(body.proof.memo).toContain(body.proof.digest.slice(0, 16));
+ expect(body.proof.memo).toContain('granite-proof/1');
+ });
+
+ it('derives a deterministic digest for an identical claim', async () => {
+ state.wxConfigured = true;
+ state.walletConfigured = true;
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-03T00:00:00Z'));
+ const a = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });
+ const b = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });
+ vi.useRealTimers();
+ expect(a.body.proof.digest).toBe(b.body.proof.digest);
+ });
+});
+
+describe('POST /api/ibm/attest (notarize)', () => {
+ it('notarizes on-chain when Granite Guardian passes', async () => {
+ state.wxConfigured = true;
+ state.walletConfigured = true;
+ state.guardianVerdict = 'No';
+ const { status, body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });
+ expect(status).toBe(200);
+ expect(body.onchain.submitted).toBe(true);
+ expect(body.onchain.signature).toBe('SIG123');
+ expect(body.onchain.explorer).toContain('SIG123');
+ // self-transfer: the destination is the agent's OWN pubkey, so no value
+ // leaves the wallet — only the proof memo is written.
+ expect(state.sendSolArgs.to.toBase58()).toBe(ADDR);
+ expect(state.sendSolArgs.lamports).toBe(1);
+ expect(state.sendSolArgs.memo).toBe(body.proof.memo);
+ });
+
+ it('refuses to notarize (Guardian veto) when the narration is flagged', async () => {
+ state.wxConfigured = true;
+ state.walletConfigured = true;
+ state.guardianVerdict = 'Yes';
+ const { status, body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });
+ expect(status).toBe(200);
+ expect(body.governance.passed).toBe(false);
+ expect(body.onchain.submitted).toBe(false);
+ expect(body.onchain.reason).toBe('vetoed_by_guardian');
+ expect(state.sendSolArgs).toBeNull(); // never reached the chain
+ });
+
+ it('does not submit when the attester wallet is not configured', async () => {
+ state.wxConfigured = true;
+ state.walletConfigured = false;
+ const { body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });
+ expect(body.onchain.submitted).toBe(false);
+ expect(state.sendSolArgs).toBeNull();
+ });
+});
diff --git a/tests/constellation-embedding.test.js b/tests/constellation-embedding.test.js
new file mode 100644
index 000000000..401123e6c
--- /dev/null
+++ b/tests/constellation-embedding.test.js
@@ -0,0 +1,113 @@
+// Unit tests for the watsonx Constellation's embedding-space math
+// (src/constellation/embedding.js) — pure functions, no three.js / network.
+
+import { describe, it, expect } from 'vitest';
+import {
+ tokenText,
+ pca3,
+ normalizeCoordsToRadius,
+ cosineNeighbors,
+} from '../src/constellation/embedding.js';
+
+// Deterministic PRNG so the synthetic clusters are reproducible across runs.
+function mulberry32(a) {
+ return () => {
+ a |= 0; a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// Three well-separated blobs in 16-d space, 5 points each.
+function syntheticClusters() {
+ const rng = mulberry32(42);
+ const D = 16;
+ const centers = [
+ Array.from({ length: D }, (_, i) => (i < 5 ? 3 : 0)),
+ Array.from({ length: D }, (_, i) => (i >= 5 && i < 10 ? 3 : 0)),
+ Array.from({ length: D }, (_, i) => (i >= 10 ? 3 : 0)),
+ ];
+ const vectors = [];
+ const labels = [];
+ centers.forEach((center, c) => {
+ for (let k = 0; k < 5; k++) {
+ vectors.push(center.map((x) => x + (rng() - 0.5) * 0.3));
+ labels.push(c);
+ }
+ });
+ return { vectors, labels };
+}
+
+describe('tokenText', () => {
+ it('combines name and ticker', () => {
+ expect(tokenText({ name: 'Dogwifhat', symbol: 'WIF' })).toBe('Dogwifhat (WIF)');
+ });
+ it('caps overly long input', () => {
+ const long = tokenText({ name: 'x'.repeat(500), symbol: 'Y' });
+ expect(long.length).toBeLessThanOrEqual(256);
+ });
+});
+
+describe('pca3', () => {
+ it('returns one [x,y,z] triple per input', () => {
+ const { vectors } = syntheticClusters();
+ const coords = pca3(vectors);
+ expect(coords).toHaveLength(vectors.length);
+ for (const c of coords) expect(c).toHaveLength(3);
+ });
+
+ it('separates well-separated clusters (between ≫ within)', () => {
+ const { vectors, labels } = syntheticClusters();
+ const coords = normalizeCoordsToRadius(pca3(vectors), 28);
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
+ let within = 0, wn = 0, between = 0, bn = 0;
+ for (let i = 0; i < coords.length; i++) {
+ for (let j = i + 1; j < coords.length; j++) {
+ const d = dist(coords[i], coords[j]);
+ if (labels[i] === labels[j]) { within += d; wn++; } else { between += d; bn++; }
+ }
+ }
+ expect(between / bn).toBeGreaterThan((within / wn) * 2);
+ });
+
+ it('is deterministic across runs', () => {
+ const { vectors } = syntheticClusters();
+ expect(pca3(vectors)).toEqual(pca3(vectors));
+ });
+
+ it('handles the empty case', () => {
+ expect(pca3([])).toEqual([]);
+ });
+});
+
+describe('normalizeCoordsToRadius', () => {
+ it('scales the largest component to the target radius', () => {
+ const scaled = normalizeCoordsToRadius([[0, 0, 0], [2, 0, 0], [0, -10, 5]], 28);
+ let max = 0;
+ for (const c of scaled) for (const x of c) max = Math.max(max, Math.abs(x));
+ expect(max).toBeCloseTo(28, 5);
+ });
+});
+
+describe('cosineNeighbors', () => {
+ it('returns same-cluster members first', () => {
+ const { vectors, labels } = syntheticClusters();
+ const neighbors = cosineNeighbors(vectors, 0, 2);
+ expect(neighbors).toHaveLength(2);
+ for (const n of neighbors) expect(labels[n.index]).toBe(labels[0]);
+ });
+
+ it('orders by descending similarity and skips self', () => {
+ const { vectors } = syntheticClusters();
+ const neighbors = cosineNeighbors(vectors, 3, 4);
+ expect(neighbors.every((n) => n.index !== 3)).toBe(true);
+ for (let i = 1; i < neighbors.length; i++) {
+ expect(neighbors[i - 1].sim).toBeGreaterThanOrEqual(neighbors[i].sim);
+ }
+ });
+
+ it('returns nothing for a missing vector', () => {
+ expect(cosineNeighbors([null, [1, 2, 3]], 0, 3)).toEqual([]);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 05185bb88..6353f3bbf 100644
--- a/vercel.json
+++ b/vercel.json
@@ -97,6 +97,14 @@
"src": "/ibm/oracle/",
"dest": "/ibm/oracle.html"
},
+ {
+ "src": "/ibm/twin",
+ "dest": "/ibm/twin.html"
+ },
+ {
+ "src": "/ibm/twin/",
+ "dest": "/ibm/twin.html"
+ },
{
"src": "/ibm/vision",
"dest": "/ibm/vision.html"
diff --git a/vite.config.js b/vite.config.js
index 89d6d96e1..a21987eee 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -357,6 +357,7 @@ const appConfig = {
'ibm-oracle': resolve(__dirname, 'pages/ibm/oracle.html'),
'ibm-vision': resolve(__dirname, 'pages/ibm/vision.html'),
'ibm-proof': resolve(__dirname, 'pages/ibm/proof.html'),
+ 'ibm-twin': resolve(__dirname, 'pages/ibm/twin.html'),
// dashboard-next prototype — sub-pages auto-discovered so the parallel
// agents that land new pages/dashboard-next/*.html files don't have to
// touch this config to register them as Rollup inputs.
@@ -575,6 +576,15 @@ const appConfig = {
'/ibm/vision/': resolve(root, 'pages/ibm/vision.html'),
'/ibm/proof': resolve(root, 'pages/ibm/proof.html'),
'/ibm/proof/': resolve(root, 'pages/ibm/proof.html'),
+ '/ibm/twin': resolve(root, 'pages/ibm/twin.html'),
+ '/ibm/twin/': resolve(root, 'pages/ibm/twin.html'),
+ // Top-level galaxy/constellation are routed in vercel.json (prod) and
+ // linked from the global nav — mirror them here so local dev matches prod
+ // instead of 404ing.
+ '/galaxy': resolve(root, 'pages/galaxy.html'),
+ '/galaxy/': resolve(root, 'pages/galaxy.html'),
+ '/constellation': resolve(root, 'pages/constellation.html'),
+ '/constellation/': resolve(root, 'pages/constellation.html'),
'/voice': resolve(root, 'pages/voice.html'),
'/voice/': resolve(root, 'pages/voice.html'),
'/brain': resolve(root, 'pages/brain.html'),