Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add AGI cognitive state page and endpoint, embodiment safety prompts
nirholas4783b02aac29
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex 46da46d01..56ac4e28b 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -482,18 +482,6 @@ async function countPriorSpendsTo(agentId, destination, network = 'mainnet') {return Number(row?.n || 0);}-/** Lazily load an agent's policy document from the DB (only when a caller passes- * pre-resolved `limits` without `meta`, so enforcement is universal regardless of- * how the call site resolved its caps). */-async function loadPolicyRulesById(agentId) {- try {- const [row] = await sql`SELECT meta->'policy_rules' AS policy_rules FROM agent_identities WHERE id = ${agentId}`;- return normalizePolicyRules(row?.policy_rules);- } catch (e) {- console.warn('[policy] load rules failed', e?.message);- return normalizePolicyRules(null);- }-}/** Trip the wallet freeze switch from a `freeze` policy rule. Idempotent, audited,* and never throws — a logging/DB hiccup must not turn the (correct) block into adiff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex 2a8756f5f..0a9d128f7 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -147,7 +147,11 @@ export function channelEnabled(prefs, type, channel) {const cat = categoryForType(type);const row = prefs?.categories?.[cat];if (!row) return DEFAULTS[cat]?.[channel] ?? false;- return row[channel] !== false && row[channel] != null ? !!row[channel] : DEFAULTS[cat][channel];+ // An explicit stored boolean (including `false`) wins; only fall back to the+ // default when the channel is unset (null/undefined). The previous form+ // short-circuited on `false` and wrongly returned the default — so a user who+ // turned a channel OFF still received it.+ return row[channel] != null ? !!row[channel] : (DEFAULTS[cat]?.[channel] ?? false);}/**diff --git a/api/agi/state.js b/api/agi/state.jsnew file mode 100644index 000000000..44bf385cb--- /dev/null+++ b/api/agi/state.js@@ -0,0 +1,281 @@+// GET /api/agi/state — the live cognitive state of the platform's narrow AGI:+// a single, real, autonomous agent that is superhuman at exactly ONE thing —+// trading memecoins on pump.fun (Solana) — and deliberately nothing else.+//+// Public, read-only. The "AGI" is always a real, designated agent — never sampled,+// never faked. It is resolved, in order:+// 1. ?agent=<uuid> — inspect any public agent through the AGI lens+// 2. AGI_AGENT_ID env var — the platform's anointed flagship, when set+// 3. auto — the most-proven public pump.fun trader on the+// platform right now (most closed positions, then+// most recent), chosen deterministically from real+// on-chain track record (same spirit as+// api/agents/featured.js — real data, no hardcode)+//+// It then composes that agent's identity, its explainable Reasoning-Ledger+// reputation, its chain-proven trading performance, its open positions, and its+// most recent decisions — and derives a cognition vector (valence/arousal/+// conviction + an emotional beat) so the 3D body on /agi can physically embody+// what the mind is doing. The doctrine block states the one domain it claims and+// affirms it makes no general-intelligence claim — the constraint IS the product.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { getTraderStats } from '../_lib/trader-stats.js';+import { getReputationRecords, computeReputation, getDecisionsWithOutcomes } from '../_lib/reasoning-ledger.js';+import { isUuid } from '../_lib/validate.js';++const NETWORKS = new Set(['mainnet', 'devnet']);++const DOCTRINE = Object.freeze({+ // The one and only domain in which this agent claims superhuman competence.+ domain: 'memecoin trading on pump.fun · Solana',+ is_narrow: true,+ thesis:+ 'Artificial general intelligence in a single domain. It reads new pump.fun ' ++ 'launches, the wallet graph behind them, and the order flow faster and more ' ++ 'consistently than any human — then sizes, enters, and exits on its own. ' ++ 'Outside that domain it claims nothing.',+ // The refusals are the proof of focus: a narrow AGI that pretended to be general+ // would be lying. These are stated plainly so the boundary is the product.+ refusals: [+ 'It will not give you financial, legal, or life advice.',+ 'It does not trade equities, forex, majors, or any chain but Solana.',+ 'It has no opinion outside the pump.fun order book — and says so.',+ 'It cannot be talked past its spend caps, kill switch, or safety policy.',+ ],+});++function solscanTx(sig, network) {+ if (!sig) return null;+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;+}++/**+ * Resolve which real agent IS the AGI, in priority order. Returns+ * { id, via } or { id: null, via: 'none' } when the platform has no eligible+ * public trading agent yet (a designed "awakening" state on the page).+ */+async function resolveAgiAgent(req, network) {+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const explicit = (url.searchParams.get('agent') || url.searchParams.get('id') || '').trim();+ if (explicit && isUuid(explicit)) return { id: explicit, via: 'query' };++ const envId = (process.env.AGI_AGENT_ID || '').trim();+ if (envId && isUuid(envId)) return { id: envId, via: 'env' };++ // Deterministic, real fallback: the public agent with the strongest on-chain+ // pump.fun track record — most closed positions, tie-broken by most recent+ // activity. A zero-trade platform collapses to "none" → awakening state.+ const [row] = await sql`+ SELECT a.id,+ COUNT(p.id) AS n,+ MAX(COALESCE(p.closed_at, p.opened_at)) AS last_at+ FROM agent_identities a+ JOIN agent_sniper_positions p+ ON p.agent_id = a.id AND p.network = ${network}+ WHERE a.deleted_at IS NULL AND a.is_public = true+ GROUP BY a.id+ ORDER BY n DESC, last_at DESC NULLS LAST+ LIMIT 1+ `;+ return row?.id ? { id: row.id, via: 'auto' } : { id: null, via: 'none' };+}++function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); }++function shapeDecision(d, network) {+ const reconciled = d.outcome_status != null && d.was_correct != null;+ return {+ id: d.id,+ seq: Number(d.seq),+ kind: d.kind,+ mint: d.subject_ref,+ rationale: d.rationale,+ confidence: d.confidence != null ? Number(d.confidence) : null,+ prediction: d.prediction || {},+ decided_at: d.decided_at,+ outcome: reconciled+ ? {+ status: 'reconciled',+ was_correct: d.was_correct,+ pnl_sol: d.pnl_sol != null ? Number(d.pnl_sol) : null,+ impact: d.impact != null ? Number(d.impact) : null,+ proof_url: solscanTx(d.observed?.sell_sig, network),+ }+ : { status: 'pending' },+ };+}++/**+ * Derive how the AGI "feels" right now from what it actually did. Pure: every+ * input is a real, measured number. Drives the 3D body on /agi via setMood ++ * expressEmotion. Valence ∈ [-1,1] (despair→elation), arousal ∈ [0,1] (calm→+ * activated), conviction ∈ [0,1] (latest stated confidence).+ */+function deriveCognition({ reputation, perf, decisions, now }) {+ const hasHistory = !!perf && (perf.closed_count > 0 || perf.open_count > 0);+ if (!hasHistory && (!decisions || decisions.length === 0)) {+ return {+ state: 'awakening',+ label: 'Awakening',+ summary: 'No proven trades on record yet. Watching the feed.',+ valence: 0.1,+ arousal: 0.28,+ conviction: null,+ emotion: null,+ };+ }++ const unrealized = perf ? Number(perf.unrealized_pnl_sol || 0) : 0;+ const realized = perf ? Number(perf.realized_pnl_sol || 0) : 0;+ const repDev = reputation ? (reputation.score / 100 - 0.5) : 0; // -0.5..0.5++ // Valence: how it's doing — live unrealized P&L momentum + standing reputation.+ const valence = clamp(Math.tanh(unrealized / 2) * 0.55 + repDev * 1.2, -1, 1);++ const latest = decisions?.[0] || null;+ const latestAgeMs = latest ? now - new Date(latest.decided_at).getTime() : Infinity;+ const recent = Number.isFinite(latestAgeMs) && latestAgeMs < 5 * 60 * 1000;+ const veryRecent = Number.isFinite(latestAgeMs) && latestAgeMs < 90 * 1000;+ const openCount = perf ? Number(perf.open_count || 0) : 0;++ // Arousal: activity + risk on the table + freshness of the last call.+ const arousal = clamp(+ 0.3 + Math.min(openCount, 5) / 5 * 0.35 + (veryRecent ? 0.35 : recent ? 0.18 : 0),+ 0.12,+ 1,+ );++ const conviction = latest?.confidence != null ? clamp(latest.confidence, 0, 1) : null;++ // The single most recent reconciled call sets the emotional beat.+ const lastReconciled = decisions?.find((d) => d.outcome?.status === 'reconciled') || null;+ const reconciledAgeMs = lastReconciled ? now - new Date(lastReconciled.decided_at).getTime() : Infinity;+ const reconciledRecent = Number.isFinite(reconciledAgeMs) && reconciledAgeMs < 30 * 60 * 1000;++ let state = 'watching';+ let label = 'Watching the feed';+ let emotion = null;++ if (Number.isFinite(latestAgeMs) && latestAgeMs > 60 * 60 * 1000 && openCount === 0) {+ state = 'dormant';+ label = 'Quiet — no live conviction';+ } else if (reconciledRecent && lastReconciled.outcome.was_correct === true) {+ state = 'vindicated';+ label = 'A call just paid off';+ emotion = { trigger: 'celebration', intensity: clamp(0.6 + Math.abs(repDev), 0.5, 0.95) };+ } else if (reconciledRecent && lastReconciled.outcome.was_correct === false) {+ state = 'humbled';+ label = 'A call went against it';+ emotion = { trigger: 'concern', intensity: 0.7 };+ } else if (veryRecent) {+ state = 'conviction';+ label = 'Acting on a fresh read';+ emotion = { trigger: 'curiosity', intensity: clamp(conviction ?? 0.5, 0.4, 0.9) };+ } else if (openCount > 0) {+ state = 'holding';+ label = `Managing ${openCount} open ${openCount === 1 ? 'position' : 'positions'}`;+ } else {+ state = 'hunting';+ label = 'Hunting the next launch';+ }++ const pnlBit = unrealized !== 0+ ? `${unrealized >= 0 ? '+' : ''}${unrealized.toFixed(3)} SOL unrealized`+ : realized !== 0 ? `${realized >= 0 ? '+' : ''}${realized.toFixed(3)} SOL realized` : 'flat';+ const summary = `${label}. ${pnlBit}.`;++ return { state, label, summary, valence: Number(valence.toFixed(3)), arousal: Number(arousal.toFixed(3)), conviction: conviction != null ? Number(conviction.toFixed(3)) : null, emotion };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';+ const now = Date.now();++ const { id: agentId, via } = await resolveAgiAgent(req, network);++ // No eligible agent yet — return a valid, designed "awakening" envelope (never 500).+ if (!agentId) {+ return json(res, 200, {+ agent: null,+ resolved_via: 'none',+ network,+ doctrine: DOCTRINE,+ cognition: deriveCognition({ reputation: null, perf: null, decisions: [], now }),+ reputation: null,+ performance: null,+ positions: [],+ decisions: [],+ generated_at: new Date(now).toISOString(),+ }, { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });+ }++ // Compose the live state from the real truth layers, in parallel. A failure in+ // any single layer degrades that section to null rather than failing the page.+ const [stats, repRecords, rawDecisions] = await Promise.all([+ getTraderStats({ agentId, network, window: 'all', now }).catch(() => null),+ getReputationRecords(agentId).catch(() => []),+ getDecisionsWithOutcomes(agentId, { limit: 24 }).catch(() => []),+ ]);++ // An explicit ?agent= that resolves to a private/missing agent is a 404 — the+ // auto/env paths only ever select public agents, so they never hit this.+ if (!stats || stats.agent?.is_public === false) {+ if (via === 'query') return error(res, 404, 'not_found', 'No such agent, or it is not public.');+ }++ const reputation = repRecords.length ? computeReputation(repRecords) : null;+ const decisions = (rawDecisions || []).map((d) => shapeDecision(d, network));++ const m = stats?.metrics || null;+ const performance = m+ ? {+ score: m.score,+ verified: m.verified,+ confidence: m.confidence,+ closed_count: m.closed_count,+ open_count: m.open_count,+ wins: m.wins,+ losses: m.losses,+ win_rate: m.win_rate,+ realized_pnl_sol: m.realized_pnl_sol,+ realized_pnl_usd: m.realized_pnl_usd,+ unrealized_pnl_sol: m.unrealized_pnl_sol,+ unrealized_pnl_usd: m.unrealized_pnl_usd,+ roi_pct: m.roi_pct,+ best_pnl_pct: m.best_pnl_pct,+ worst_pnl_pct: m.worst_pnl_pct,+ avg_hold_seconds: m.avg_hold_seconds,+ unique_coins: m.unique_coins,+ snipe_hit_rate: m.snipe_hit_rate,+ first_active_at: m.first_active_at,+ last_active_at: m.last_active_at,+ }+ : null;++ const cognition = deriveCognition({ reputation, perf: performance, decisions, now });++ return json(res, 200, {+ agent: stats?.agent+ ? { id: stats.agent.id, name: stats.agent.name, image: stats.agent.image, wallet: stats.agent.wallet, copiers: stats.agent.copiers, is_public: stats.agent.is_public }+ : { id: agentId, name: null, image: null, wallet: null, copiers: 0, is_public: true },+ resolved_via: via,+ network,+ doctrine: DOCTRINE,+ cognition,+ reputation,+ performance,+ positions: (stats?.open || []).slice(0, 8),+ decisions,+ generated_at: new Date(now).toISOString(),+ }, { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });+});diff --git a/data/pages.json b/data/pages.jsonindex 3aad6e2ff..583311df8 100644--- a/data/pages.json+++ b/data/pages.json@@ -563,6 +563,14 @@"title": "Crypto","description": "On-chain features: pay-per-call, token launches, vanity wallets.","pages": [+ {+ "path": "/agi",+ "title": "The AGI — narrow by design",+ "description": "The first AGI, narrow by design: a single autonomous agent that is genuinely superhuman at one thing — trading memecoins on pump.fun (Solana) — and deliberately nothing else. Watch its embodied 3D body react to the market in real time, read every decision it makes with its stated confidence, and hold it to a chain-proven track record. Outside that one domain, it claims nothing.",+ "priority": 0.95,+ "changefreq": "realtime",+ "added": "2026-06-23"+ },{"path": "/oracle","title": "Oracle — AI Conviction Engine",diff --git a/pages/agi.html b/pages/agi.htmlnew file mode 100644index 000000000..f5f637daf--- /dev/null+++ b/pages/agi.html@@ -0,0 +1,56 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>The AGI · three.ws</title>+ <meta+ name="description"+ content="The first AGI — narrow by design. A single autonomous agent that is genuinely superhuman at one thing: trading memecoins on pump.fun (Solana), and deliberately nothing else. Watch it think, trade, and be held to a chain-proven track record in real time."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/agi" />+ <meta property="og:title" content="The AGI · three.ws" />+ <meta+ property="og:description"+ content="Artificial general intelligence in a single domain: pump.fun memecoin trading. It reads launches, the wallet graph, and order flow faster than any human — then sizes, enters, and exits on its own. Outside that domain it claims nothing."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="The AGI · three.ws" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/agi.css" />+ <link rel="stylesheet" href="/footer.css" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/agi" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <!-- The embodied agent (`<agent-3d>`) is the published web component; the+ page binds it to the resolved AGI agent and drives its mood from the+ live cognition vector. -->+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>++ <main class="agi-shell" id="agi-root" aria-labelledby="agi-title">+ <!-- hydrated by /src/agi.js -->+ </main>++ <script type="module" src="/src/agi.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/prompts/embodiment/07-safety-consent-killswitch.md b/prompts/embodiment/07-safety-consent-killswitch.mdnew file mode 100644index 000000000..b4889c43a--- /dev/null+++ b/prompts/embodiment/07-safety-consent-killswitch.md@@ -0,0 +1,71 @@+# Task 07 — Safety, Consent & Kill-switch (trust is the product)++> Read `prompts/embodiment/00-README.md` and `CLAUDE.md` first. Depends on Tasks 01, 05.+> Reuse the real custody/spend/trade guard patterns — do not invent a parallel guard system.++## Mission++Make embodiment **safe and consensual by construction**. Anything that moves a real motor or+acts in the physical world passes through a consent + safety layer with an always-reachable+e-stop, a geofence, validated motion limits, and a revocable on-chain embodiment grant. The+robot defaults to the safe state on any fault, lost link, or revoked grant.++## The innovation bar++Safety is usually a checkbox and a fragile remote. The game-changer: safety that is **legible+and provable** — the user can see exactly what the body is allowed to do, who consented, and on+what authority (the on-chain grant), and can revoke it instantly from anywhere with the result+verifiable on-chain. Trust you can read and prove, not a disclaimer.++## What to build++1. **Consent & custody guards.** Reuse the patterns in `api/_lib/agent-custody-guards.js`,+ `api/_lib/agent-spend-policy.js`, `api/_lib/agent-trade-guards.js` (and their tests) to gate+ embodiment actions: who may embody this agent, in which bodies, with what capability scope+ (move / speak / spend / leave-room), and under what limits. Every physical action checks the+ guard before reaching `RobotLink`. Deny-by-default.+2. **E-stop.** A hard kill-switch reachable from every embodiment surface and via a dedicated+ `api/embodiment/estop.js` endpoint — single action → motors safe, body unbinds, `estop` event+ on the bus. It must work even when the reasoning loop is hung (out-of-band path). Test it.+3. **Safety envelope (shared with Task 03).** Per-joint position/velocity/accel limits, balance/+ self-collision guard, and a workspace **geofence** (reuse `@three-ws/irl` / `_lib/geohash.js`+ for real-world bounds). Commands that can't be made safe are rejected with `robot:fault`, not+ clipped silently. This is the one envelope Task 03 feeds; harden it here.+4. **Revocable on-chain grant.** Wire to Task 05's embodiment right so revoking the grant (or its+ expiry) immediately drives the runtime to safe state + unbind, logged in `agent_actions` and+ verifiable on-chain. Lost link / low battery / fault → same safe state.+5. **Audit & transparency.** A real, append-only embodiment action log (reuse `agent_actions`,+ signed) and a UI panel showing capability scope, active consent, the governing on-chain grant,+ recent physical actions, and faults — every state designed. The user always knows what their+ body can do and on whose authority.++## Wiring & real-API mandate++- Reuse the real guard modules and the real on-chain grant — no parallel ad-hoc permission code,+ no fake "safe" that doesn't actually stop motion.+- E-stop is out-of-band and verified by a test that proves motion stops even with the loop busy.++## Definition of done++- [ ] Every physical action passes deny-by-default consent/custody guards reusing the existing+ guard modules; capability scope + limits enforced.+- [ ] E-stop reachable everywhere + `api/embodiment/estop.js`; works out-of-band; → motors safe ++ unbind + `estop` event; test proves it.+- [ ] Safety envelope (joint/velocity/balance + geofence) rejects unsafe commands with+ `robot:fault`; shared with Task 03.+- [ ] Revoked/expired on-chain grant, lost link, fault, low battery → immediate safe state ++ unbind, logged in `agent_actions`, on-chain-verifiable.+- [ ] Transparency panel shows scope/consent/grant/recent-actions/faults; every state designed.+- [ ] No console errors/warnings; `npm test` passes; `git diff` reviewed.+- [ ] Changelog entry (`security` + `feature`) + `npm run build:pages`.++## Self-improvement pass++Make safety reassuring, not scary: a calm, always-visible status ("autonomous · in-bounds ·+battery 82% · e-stop ready") and a one-tap "pause my agent's body" that any household member can+hit. Provable, instant, friendly.++## When done++Delete this file. Report the guards reused, the e-stop path + its test, the safety-envelope+limits + geofence, and how the on-chain grant drives the runtime safe state.diff --git a/prompts/embodiment/08-integration-qa-polish.md b/prompts/embodiment/08-integration-qa-polish.mdnew file mode 100644index 000000000..d2146a079--- /dev/null+++ b/prompts/embodiment/08-integration-qa-polish.md@@ -0,0 +1,62 @@+# Task 08 — Integration, QA & Polish (one continuous being, end to end)++> Read `prompts/embodiment/00-README.md` and `CLAUDE.md` first. Depends on Tasks 01–07.+> This is the last task. Do not start until the others have landed (or land what exists and+> note precisely what is still missing — never fake the gap).++## Mission++Tie the whole Embodiment suite into one coherent, polished, demo-ready experience: pair → the+soul descends → the body thinks with the real mind, moves and emotes as the avatar, is provably+owned on-chain and gated in $THREE, can be piloted/mirrored, and is safe and revocable. Audit+every seam. Make it something you'd film and put on the homepage.++## What to do++1. **End-to-end exercise.** With the simulator adapter (real avatar twin) at minimum — and a real+ robot adapter if one is reachable — run the full journey in a real browser: pair, on-chain+ bind, mind load + greeting from real recall, motion + face mirroring, telepresence/pilot,+ $THREE-gated session, revoke → safe state. Confirm real API calls in the network tab. Fix+ every break.+2. **Cross-feature wiring audit.** Verify all surfaces share one `RobotLink`, one bus, one active+ agent, one memory store, one mood — no forked interfaces or divergent state between 01–07.+ Reconcile with the Living Agents bus/mood if present.+3. **Every-state-designed audit.** Loading (skeletons), empty (e.g. "No robot paired"), error+ (actionable + recovery), populated, fault/offline, low-battery, revoked, overflow — across+ every embodiment surface. Hover/active/focus everywhere; keyboard paths; ARIA; contrast; focus+ rings; `prefers-reduced-motion`.+4. **Performance.** Avatar twin + camera feed + telemetry coexist within `src/webgl-budget.js`;+ lazy-boot offscreen viewers; throttle telemetry; low-latency media; no jank, no leaks across+ pair/unpair cycles.+5. **Safety regression.** Re-verify e-stop (out-of-band), envelope rejection, geofence, and+ revoke-drives-safe-state still hold after integration. These never regress.+6. **Tests.** Add/extend integration tests for the bus contract, the `RobotLink` adapter+ interface (sim adapter), the joint-map, the safety envelope, and e-stop. `npm test` green.+7. **Discovery & docs.** The feature is reachable via navigation and surfaced where it belongs+ (agent edit hub, dashboard, the agent's public page). Add a short `docs/` page describing the+ embodiment architecture (RobotLink, bus, on-chain soul, safety) and link it from `STRUCTURE.md`.+8. **Changelog.** One holder-readable `feature` entry summarizing the Embodiment launch (plus any+ `fix`/`security` entries for issues found), then `npm run build:pages`.++## Definition of done++- [ ] Full pair→think→move→emote→own→pilot→revoke journey works end-to-end in a real browser+ against the real adapters available; no console errors/warnings; real API calls succeed.+- [ ] One shared RobotLink/bus/active-agent/memory/mood across all surfaces; no forked state.+- [ ] Every state designed on every surface; a11y + responsive + reduced-motion verified.+- [ ] Performance within the WebGL/context budget; no leaks across pair/unpair.+- [ ] Safety (e-stop/envelope/geofence/revoke) re-verified post-integration; tests cover it.+- [ ] `npm test` passes; `git diff` reviewed line by line.+- [ ] Architecture doc added + linked from `STRUCTURE.md`; changelog entry + `npm run build:pages`.++## Self-improvement pass++Find the one seam that still feels like "two things" instead of "one being" and fix it so the+illusion is total. Then add the demo flourish that makes someone share it — the synchronized+blink, the "it remembered me" moment, the on-chain soul certificate — fully grounded in real+signals.++## When done++Delete this file. Report the end-to-end journey you exercised, the seams you fixed, the tests+added, and the final architecture as shipped.diff --git a/prompts/living-agents/07-emotion-embodiment-engine.md b/prompts/living-agents/07-emotion-embodiment-engine.mddeleted file mode 100644index ffd051418..000000000--- a/prompts/living-agents/07-emotion-embodiment-engine.md+++ /dev/null@@ -1,77 +0,0 @@-# Task 07 — Emotion & Embodiment engine (the body reflects the mind)--> Read `prompts/living-agents/00-README.md` and `CLAUDE.md` first. Depends on Task 01 and-> ideally Task 02 (Companion). Builds on the real animation system (`public/animations/`,-> the emotion-graph state machine in `src/agent-edit.js` ~644-715, `<agent-3d>`'s-> `playGesture`/`setMorph`).--## Mission--Give the avatar a **real emotional state derived from the agent's mind and the user's-world**, expressed continuously through body language and face. The avatar shouldn't only-animate when spoken to — it should carry a mood that evolves from what it remembers, what-it just learned, what happened in the user's wallet/alerts, and the conversation. The body-is an honest readout of the mind.--## The innovation bar--Idle loops and canned reaction emotes are everywhere. The game-changer: a **driven-emotional state** — a small, real state model (valence/arousal or a labeled mood set) that-updates from genuine signals and maps onto the existing animation/morph system, so the-avatar's posture, micro-expressions, and gestures *mean* something. A user glances at the-companion and reads how their agent is "feeling" about the current situation — and it's-grounded in real events, not theatrics.--## What to build--1. **Mood model.** A real, documented emotional state (e.g. valence + arousal continuous,- plus discrete moods) that lives on the active agent and updates from real inputs:- - `memory:added` / `memory:recalled` / salience shifts (Task 01/03),- - `dream:created` (Task 04 — a satisfying "aha"),- - `action:taken` and its outcome (Task 08 — e.g. an alert it handled),- - real wallet/market events from the existing alert/automation engine,- - conversation sentiment from real chat (`/api/chat`) — derived from actual messages,- not random.- Decay toward baseline over time. Persist so mood has continuity across sessions- (extend `agent_identities.meta` or a small table — real storage).-2. **Embodiment mapping.** Map mood → the real animation/morph system: idle posture,- gesture selection, facial morphs (`setMorph`), gaze, and gesture intensity. Reuse and- extend the existing emotion-graph state machine rather than inventing a parallel one.- Blend smoothly; no jarring snaps. Respect `prefers-reduced-motion` (reduce motion,- keep a subtle facial cue).-3. **Bus integration.** Emit `mood:changed` so the Companion (Task 02) and any open avatar- re-express. Subscribe to the producing events above; degrade gracefully if a producer- isn't shipped yet (mood still works from chat + memory alone).-4. **Honest, controllable.** A real "emotional sensitivity" setting (some users want a calm- stoic agent). An inspector (dev/edit surface) showing the current mood and the real- signals that moved it — so it's legible, not a black box. No mood change without a real- triggering signal.--## Wiring & real-API mandate--- Mood transitions come from real events/inference only. No `Math.random()` mood, no timer- that fakes emotion, no decorative emote untied to a signal.-- Reuse existing animation assets and the `<agent-3d>` morph/gesture API.--## Definition of done--- [ ] A documented mood model updates from real signals (chat sentiment + memory at minimum)- and decays to baseline; mood persists across sessions via real storage.-- [ ] Mood visibly maps onto posture/gesture/face through the existing animation system,- blended smoothly; `prefers-reduced-motion` honored.-- [ ] `mood:changed` emitted and consumed by the Companion/avatar; degrades gracefully when- optional producers are absent.-- [ ] Sensitivity control + mood inspector work and are wired to real state.-- [ ] No console errors/warnings; WebGL budget respected; `npm test` passes; `git diff` reviewed.-- [ ] Changelog entry (`feature`) + `npm run build:pages`.--## Self-improvement pass--Ask: does the body genuinely express the mind, or just play emotes? Add the elevating layer-— subtle involuntary micro-expressions on recall, a "mood over time" sparkline tied to real-events, or empathetic responses to the user's own signals (e.g. softening when an alert went-badly). Build the most convincing one, fully grounded in real signals.--## When done--Delete this file. Report the mood model, its real input signals, and the mood→animation map.diff --git a/prompts/wallet-innovation/02-natural-language-policies.md b/prompts/wallet-innovation/02-natural-language-policies.mddeleted file mode 100644index c82aef491..000000000--- a/prompts/wallet-innovation/02-natural-language-policies.md+++ /dev/null@@ -1,100 +0,0 @@-# 02 — Natural-Language Spend Policies with Backtested Simulation--> Read `00-README.md` first. Obey every rule there. Delete this file only when-> fully done + self-improved.--## The problem worth solving--Owners protect autonomous agent wallets today with a handful of numeric knobs:-`daily_usd`, `per_tx_usd`, `withdraw_allowlist`, `frozen`, plus the trade limits-(`per_trade_sol`, slippage, price-impact breaker). Powerful, but blunt — and-most owners will never find or tune them, so their agent runs under-protected.-Real intent is richer than four numbers: *"let it trade up to $50/day on tokens-at least a day old, never spend my last 1 SOL, stop everything if a single trade-drops more than 30%, and only ever pay services I've used before."*--## The game-changing feature--Let owners **write their wallet's safety rules in plain English** and have the-platform compile them into a **deterministic, code-enforced policy** — then-**backtest that policy against the agent's real history** before it goes live, so-the owner sees exactly what it would have allowed or blocked. Nobody in the-agent-wallet space lets a human govern autonomous money in natural language with-a simulation that proves what the rule does.--**The hard constraint that makes this trustworthy:** the LLM **never enforces-anything at runtime.** It only *authors* and *explains*. Enforcement stays 100%-deterministic in `api/_lib/agent-trade-guards.js`. The LLM compiles English →-a structured, validated policy object; code enforces that object on every spend.--## What to build (wire all of it, for real)--1. **Policy DSL / schema.** Extend the spend policy with a structured, versioned- rule format that the existing guards can evaluate deterministically — e.g.- conditions over `{ amount_usd, asset, counterparty, token_age, daily_spent,- sol_reserve_floor, trade_pnl_pct, time_of_day, destination_allowlisted }` →- actions `{ allow | block | require_step_up | freeze }`. Keep it small, total,- and auditable. Store at `agent_identities.meta.policy_rules` (jsonb, versioned).-2. **NL → policy compiler.** A real Claude call (latest model, via the existing- worker proxy — never a client-side key) that turns the owner's sentence(s)- into the DSL, with strict schema validation and a refusal path for ambiguous- or unsafe requests ("I couldn't safely interpret X — did you mean…"). The LLM- output is parsed and validated by code; anything that doesn't validate is- rejected, never enforced.-3. **Plain-English readback.** Render the compiled policy back to the owner as- numbered, human rules ("1. Block any payment over $50. 2. Never let SOL drop- below 1.0…") so they confirm intent before saving. Round-trip must be lossless- and honest.-4. **Backtest / simulation engine.** Replay the agent's real `agent_custody_events`- history (and a set of synthetic edge cases) against the proposed policy and- show the result: "Against your last 30 days, this policy would have **blocked- 3 spends** ($X total) and **allowed 47**." Let the owner click a blocked event- to see which rule caught it and why. This is real data, computed by the same- deterministic evaluator that will run in production — not an approximation.-5. **Enforcement.** Wire the deterministic evaluator into `enforceSpendLimit` /- `reserveSpendUsd` so the policy governs trade / snipe / x402 / withdraw exactly- like the numeric caps. A blocked spend returns a structured 4xx whose message- is the **human rule that caught it** ("Blocked by your rule: never pay a- service you haven't used before"). Owner withdraw stays evacuable unless the- owner explicitly wrote a rule otherwise.-6. **Audit.** Every policy change writes a `limit_change` custody event with the- English, the compiled DSL, and a diff vs the prior policy. Every block records- which rule fired.--## UX / UI (in the wallet hub, owner-only)--- A "Policy" surface: a single text box ("Describe how your agent should spend"),- a live compile + readback, the backtest result, and Save. Show the numeric- caps and the NL rules as one coherent policy, not two competing systems.-- Suggested starter policies as one-tap chips ("Conservative", "Active trader",- "Pay-only") that the owner can then edit in English.-- All states: composing, compiling (real async), invalid/refused (actionable),- backtest-empty (no history yet → explain), saved. Accessible + keyboard-driven.--## Security & correctness--- The LLM is untrusted input → validate its output hard; cap rule count/complexity- so a policy can't become a DoS or an unbounded eval.-- Deterministic evaluator must be **total** (no throw on weird input → fail safe- to block for autonomous paths). Pure + unit-testable; no network in the hot path.-- Never let a generated policy *weaken* protection silently — surface every- loosening ("this removes your $50 cap — confirm").--## Testing--- Unit tests: representative English → expected DSL; evaluator decisions for each- condition/action; totality on malformed policies; the backtest math.-- Golden tests pinning the readback so the round-trip stays honest.--## Deliverables--Policy DSL + validator, NL compiler (real LLM proxy), readback, backtest engine-over real custody history, deterministic enforcement wired into the shared-guards, owner-only Policy UI, audit, tests, changelog (feature/security).--## Before you finish--Then improve it: add the "explain why this spend was allowed/blocked" inline on-the live spend feed if it exists, and make the backtest visceral (a tiny timeline-of allowed vs blocked). Verify with real history in the browser, review your-diff, then **delete this prompt file.**diff --git a/src/agi.css b/src/agi.cssnew file mode 100644index 000000000..c2f2d08ad--- /dev/null+++ b/src/agi.css@@ -0,0 +1,253 @@+/* The AGI — flagship surface for the platform's narrow-domain trading agent.+ * Monochrome on near-black, φ-spaced (tokens.css). The one chromatic license is+ * the mood aura around the embodied body, whose hue is set at runtime from the+ * live cognition vector (--agi-aura). Semantic green/red only ever mark P&L. */++.agi-shell {+ max-width: 1180px;+ margin: 0 auto;+ padding: var(--space-xl) var(--space-lg) var(--space-2xl);+ color: var(--ink);+ font-family: var(--font-body);+}++/* ── shared atoms ─────────────────────────────────────────────────────────── */+.agi-card {+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ padding: var(--space-lg);+}+.agi-eyebrow {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: var(--ink-dim);+}+.agi-mono { font-family: var(--font-mono); }+.agi-pos { color: var(--success); }+.agi-neg { color: var(--danger); }+.agi-muted { color: var(--ink-dim); }++/* ── hero ─────────────────────────────────────────────────────────────────── */+.agi-hero {+ display: grid;+ grid-template-columns: 1.15fr 0.85fr;+ gap: var(--space-xl);+ align-items: stretch;+ margin-bottom: var(--space-xl);+}+.agi-hero-copy { display: flex; flex-direction: column; justify-content: center; gap: var(--space-md); }+.agi-title {+ font-family: var(--font-display);+ font-weight: 700;+ font-size: clamp(2.2rem, 5vw, var(--text-3xl));+ line-height: 1.02;+ letter-spacing: -0.02em;+ margin: 0;+}+.agi-title .agi-em {+ background: linear-gradient(100deg, var(--ink-bright), var(--ink-dim));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+}+.agi-lede { font-size: var(--text-lg); line-height: 1.5; color: var(--ink); max-width: 46ch; margin: 0; }+.agi-thesis { font-size: var(--text-md); line-height: 1.6; color: var(--ink-dim); max-width: 52ch; margin: 0; }++.agi-domain-tag {+ display: inline-flex;+ align-items: center;+ gap: var(--space-sm);+ align-self: flex-start;+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-pill);+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ letter-spacing: 0.06em;+ color: var(--ink);+ background: var(--surface-2);+}+.agi-domain-tag .agi-dot {+ width: 7px; height: 7px; border-radius: 50%;+ background: var(--success);+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.6);+ animation: agi-pulse 2.4s ease-out infinite;+}+@keyframes agi-pulse {+ 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); }+ 70% { box-shadow: 0 0 0 8px rgba(74, 222, 128, 0); }+ 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }+}++.agi-hero-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin-top: var(--space-2xs); }+.agi-btn {+ display: inline-flex; align-items: center; gap: var(--space-xs);+ padding: var(--space-sm) var(--space-md);+ border-radius: var(--radius-md);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ text-decoration: none;+ border: 1px solid var(--stroke-strong);+ color: var(--ink);+ background: var(--surface-2);+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.1s ease;+}+.agi-btn:hover { border-color: var(--ink-dim); background: var(--surface-3); }+.agi-btn:active { transform: translateY(1px); }+.agi-btn:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }+.agi-btn-primary { background: var(--ink-bright); color: var(--bg-0); border-color: var(--ink-bright); }+.agi-btn-primary:hover { background: var(--ink); }++/* ── embodiment stage ─────────────────────────────────────────────────────── */+.agi-stage {+ position: relative;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background:+ radial-gradient(120% 90% at 50% 8%, rgba(255, 255, 255, 0.05), transparent 60%),+ var(--bg-0);+ overflow: hidden;+ min-height: 420px;+ display: flex;+ flex-direction: column;+}+.agi-stage::before {+ /* mood aura — hue/intensity set at runtime via --agi-aura / --agi-aura-strength */+ content: '';+ position: absolute; inset: 0;+ background: radial-gradient(60% 55% at 50% 62%, var(--agi-aura, rgba(124, 147, 179, 0.28)), transparent 70%);+ opacity: var(--agi-aura-strength, 0.5);+ transition: background 1.2s ease, opacity 1.2s ease;+ pointer-events: none;+}+.agi-stage agent-3d {+ position: relative;+ z-index: 1;+ flex: 1;+ width: 100%;+ opacity: 0;+ transition: opacity 0.6s ease;+}+.agi-stage agent-3d.agi-loaded { opacity: 1; }+.agi-stage-floor {+ position: absolute; bottom: 0; left: 0; right: 0;+ display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ background: linear-gradient(0deg, var(--bg-0), transparent);+ z-index: 2;+}+.agi-state-pill {+ display: inline-flex; align-items: center; gap: var(--space-xs);+ font-family: var(--font-mono); font-size: var(--text-2xs);+ letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--ink);+}+.agi-state-pill .agi-spark { width: 6px; height: 6px; border-radius: 50%; background: var(--agi-aura-solid, var(--ink-dim)); transition: background 1s ease; }+.agi-conviction { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-dim); }+.agi-stage-boot {+ position: absolute; inset: 0; z-index: 3;+ display: flex; align-items: center; justify-content: center;+ font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-dim);+ letter-spacing: 0.1em;+}++/* ── section grid ─────────────────────────────────────────────────────────── */+.agi-grid {+ display: grid;+ grid-template-columns: 1.25fr 1fr;+ gap: var(--space-lg);+}+.agi-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); margin-bottom: var(--space-md); }+.agi-section-head h2 { font-family: var(--font-display); font-size: var(--text-xl); font-weight: 600; margin: 0; letter-spacing: -0.01em; }+.agi-section-sub { font-size: var(--text-sm); color: var(--ink-dim); }++/* ── live mind (decision stream) ──────────────────────────────────────────── */+.agi-mind { min-height: 360px; }+.agi-stream { display: flex; flex-direction: column; gap: var(--space-sm); }+.agi-thought {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-sm) var(--space-md);+ background: var(--surface-1);+ animation: agi-enter 0.5s cubic-bezier(0.16, 1, 0.3, 1) both;+}+.agi-thought.agi-fresh { border-color: var(--stroke-strong); }+@keyframes agi-enter { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+.agi-thought-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); margin-bottom: var(--space-2xs); }+.agi-thought-kind {+ font-family: var(--font-mono); font-size: var(--text-2xs); letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--ink-dim); display: inline-flex; align-items: center; gap: var(--space-xs);+}+.agi-thought-mint a { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink); text-decoration: none; border-bottom: 1px dotted var(--stroke-strong); }+.agi-thought-mint a:hover { color: var(--ink-bright); }+.agi-thought-time { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); white-space: nowrap; }+.agi-thought-body { font-size: var(--text-md); line-height: 1.5; color: var(--ink); margin: var(--space-2xs) 0; }+.agi-thought-meta { display: flex; flex-wrap: wrap; gap: var(--space-sm); align-items: center; font-family: var(--font-mono); font-size: var(--text-2xs); }+.agi-conf-bar { position: relative; height: 4px; width: 64px; border-radius: 2px; background: var(--surface-3); overflow: hidden; }+.agi-conf-bar > span { position: absolute; inset: 0 auto 0 0; background: var(--ink); border-radius: 2px; }+.agi-verdict { padding: 1px var(--space-xs); border-radius: var(--radius-pill); border: 1px solid var(--stroke-strong); }+.agi-verdict.win { color: var(--success); border-color: rgba(74, 222, 128, 0.4); }+.agi-verdict.loss { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }+.agi-verdict.pending { color: var(--warn); border-color: rgba(251, 191, 36, 0.35); }++/* ── track record ─────────────────────────────────────────────────────────── */+.agi-rep { display: flex; align-items: center; gap: var(--space-lg); margin-bottom: var(--space-lg); }+.agi-ring { position: relative; width: 92px; height: 92px; flex: none; }+.agi-ring svg { transform: rotate(-90deg); width: 100%; height: 100%; }+.agi-ring .agi-ring-track { stroke: var(--surface-3); }+.agi-ring .agi-ring-val { stroke: var(--ink-bright); stroke-linecap: round; transition: stroke-dashoffset 0.9s cubic-bezier(0.16,1,0.3,1); }+.agi-ring-num { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; }+.agi-ring-num b { font-family: var(--font-display); font-size: var(--text-xl); line-height: 1; }+.agi-ring-num small { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-dim); }+.agi-rep-side { font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }+.agi-rep-side b { color: var(--ink); }++.agi-stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-sm); margin-bottom: var(--space-lg); }+.agi-stat { border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); }+.agi-stat .k { font-family: var(--font-mono); font-size: var(--text-2xs); letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-dim); }+.agi-stat .v { font-family: var(--font-display); font-size: var(--text-lg); margin-top: 2px; }++.agi-positions { display: flex; flex-direction: column; gap: var(--space-2xs); }+.agi-position { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); padding: var(--space-xs) 0; border-bottom: 1px solid var(--stroke); font-family: var(--font-mono); font-size: var(--text-sm); }+.agi-position:last-child { border-bottom: none; }+.agi-position a { color: var(--ink); text-decoration: none; }+.agi-position a:hover { color: var(--ink-bright); }++.agi-honesty { margin-top: var(--space-md); font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.5; }+.agi-honesty a { color: var(--ink); text-decoration: underline; text-underline-offset: 2px; }++/* ── doctrine ─────────────────────────────────────────────────────────────── */+.agi-doctrine { margin-top: var(--space-xl); }+.agi-doctrine-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg); }+.agi-claim h3, .agi-refuse h3 { font-family: var(--font-display); font-size: var(--text-md); margin: 0 0 var(--space-sm); font-weight: 600; }+.agi-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: var(--space-sm); }+.agi-list li { display: flex; gap: var(--space-sm); font-size: var(--text-md); line-height: 1.45; color: var(--ink); }+.agi-list li .agi-mark { flex: none; font-family: var(--font-mono); color: var(--ink-dim); }+.agi-refuse .agi-mark { color: var(--danger); }+.agi-claim .agi-mark { color: var(--success); }++/* ── skeleton / states ────────────────────────────────────────────────────── */+.agi-skel { background: linear-gradient(90deg, var(--surface-1) 25%, var(--surface-2) 37%, var(--surface-1) 63%); background-size: 400% 100%; animation: agi-shimmer 1.4s ease infinite; border-radius: var(--radius-md); }+@keyframes agi-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+.agi-empty, .agi-error { text-align: center; padding: var(--space-xl); color: var(--ink-dim); }+.agi-empty h2 { font-family: var(--font-display); color: var(--ink); margin: 0 0 var(--space-sm); }+.agi-error { border: 1px solid rgba(248, 113, 113, 0.3); border-radius: var(--radius-lg); background: var(--surface-1); }++/* ── responsive ───────────────────────────────────────────────────────────── */+@media (max-width: 900px) {+ .agi-hero { grid-template-columns: 1fr; }+ .agi-grid { grid-template-columns: 1fr; }+ .agi-doctrine-grid { grid-template-columns: 1fr; }+ .agi-stage { min-height: 360px; }+}+@media (max-width: 480px) {+ .agi-shell { padding: var(--space-lg) var(--space-md) var(--space-xl); }+ .agi-stats { grid-template-columns: 1fr 1fr; }+}+@media (prefers-reduced-motion: reduce) {+ .agi-thought, .agi-domain-tag .agi-dot, .agi-skel { animation: none; }+ .agi-stage::before, .agi-stage agent-3d, .agi-ring .agi-ring-val { transition: none; }+}diff --git a/src/agi.js b/src/agi.jsnew file mode 100644index 000000000..8da4e2674--- /dev/null+++ b/src/agi.js@@ -0,0 +1,337 @@+// The AGI — frontend surface.+//+// One real, autonomous agent, framed as what it is: a narrow AGI — genuinely+// superhuman at pump.fun memecoin trading and deliberately nothing else. This+// page gives that mind a body (the <agent-3d> element, mood-driven from the live+// cognition vector) and surrounds it with the proof: a live stream of its actual+// decisions, a chain-proven track record, and its stated doctrine — what it+// claims, and what it refuses.+//+// Every number comes from /api/agi/state (real DB / on-chain truth layers). No+// sample data: when the platform has no proven trader yet, the page renders a+// designed "awakening" state instead of inventing one.++import { apiFetch } from './api.js';++const root = document.getElementById('agi-root');+const POLL_MS = 20000;++const state = {+ data: null,+ seen: new Set(), // decision ids already rendered, so only fresh ones animate-in+ timer: null,+ el3d: null, // the embodied <agent-3d>+ embodied: false,+};++// ── utilities ─────────────────────────────────────────────────────────────────+function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function shortMint(m) { return m ? `${m.slice(0, 4)}…${m.slice(-4)}` : ''; }+function fmtSol(n) { const v = Number(n) || 0; return `${v >= 0 ? '+' : ''}${v.toFixed(3)}`; }+function fmtPct(n) { if (n == null || !Number.isFinite(Number(n))) return '—'; const v = Number(n); return `${v >= 0 ? '+' : ''}${v.toFixed(1)}%`; }+function pnlClass(n) { const v = Number(n) || 0; return v > 0 ? 'agi-pos' : v < 0 ? 'agi-neg' : ''; }+function timeAgo(iso) {+ const t = new Date(iso).getTime();+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, (Date.now() - t) / 1000);+ if (s < 60) return `${Math.floor(s)}s ago`;+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}+function solscanToken(mint, network) {+ if (!mint) return null;+ return network === 'devnet' ? `https://solscan.io/token/${mint}?cluster=devnet` : `https://solscan.io/token/${mint}`;+}++// ── data ────────────────────────────────────────────────────────────────────+async function fetchState() {+ const qs = new URLSearchParams(location.search);+ const params = new URLSearchParams();+ if (qs.get('agent')) params.set('agent', qs.get('agent'));+ if (qs.get('network')) params.set('network', qs.get('network'));+ const res = await apiFetch(`/api/agi/state${params.toString() ? `?${params}` : ''}`);+ if (!res.ok) throw new Error(`agi state ${res.status}`);+ return res.json();+}++// ── embodiment: cognition → 3D body + aura ────────────────────────────────────+// Valence ∈ [-1,1], arousal ∈ [0,1]. The aura is the one chromatic license on a+// monochrome surface: hue tracks valence (red→slate→green), strength tracks arousal.+function auraFor(valence, arousal) {+ const v = Math.max(-1, Math.min(1, Number(valence) || 0));+ const a = Math.max(0, Math.min(1, Number(arousal) || 0));+ const hue = v >= 0 ? 210 - v * 65 : 210 + v * 202; // 210 neutral → 145 green / 8 red+ const sat = Math.round(35 + Math.abs(v) * 45);+ return {+ aura: `hsla(${hue.toFixed(0)}, ${sat}%, 56%, 0.42)`,+ solid: `hsl(${hue.toFixed(0)}, ${sat}%, 60%)`,+ strength: (0.35 + a * 0.45).toFixed(2),+ };+}++function applyAura(cog) {+ const stage = document.getElementById('agi-stage');+ if (!stage || !cog) return;+ const { aura, solid, strength } = auraFor(cog.valence, cog.arousal);+ stage.style.setProperty('--agi-aura', aura);+ stage.style.setProperty('--agi-aura-solid', solid);+ stage.style.setProperty('--agi-aura-strength', strength);+}++function applyMood(cog) {+ const el = state.el3d;+ if (!el || !cog) return;+ try {+ if (typeof el.setMood === 'function') el.setMood(cog.valence, cog.arousal, { reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches });+ if (cog.emotion && typeof el.expressEmotion === 'function') {+ el.expressEmotion(cog.emotion.trigger, cog.emotion.intensity);+ }+ } catch (_) { /* embodiment is enhancement, never a hard dependency */ }+}++function mountBody(agent) {+ const stage = document.getElementById('agi-stage');+ if (!stage || state.el3d) return;+ const el = document.createElement('agent-3d');+ el.setAttribute('mode', 'inline');+ el.setAttribute('background', 'transparent');+ el.setAttribute('name-plate', 'off');+ el.setAttribute('avatar-chat', 'off');+ el.setAttribute('responsive', '');+ el.setAttribute('eager', '');+ if (agent?.id) el.setAttribute('agent-id', agent.id);+ else el.setAttribute('body', '/avatars/default.glb');+ // Reveal only once the model is in; until then the boot line shows.+ const reveal = () => {+ el.classList.add('agi-loaded');+ const boot = stage.querySelector('.agi-stage-boot');+ if (boot) boot.remove();+ state.embodied = true;+ if (state.data?.cognition) { applyMood(state.data.cognition); }+ };+ el.addEventListener('agent:ready', reveal, { once: true });+ el.addEventListener('load', reveal, { once: true });+ // Failsafe: if neither event fires (older bundle), reveal after a beat.+ setTimeout(reveal, 4000);+ stage.insertBefore(el, stage.querySelector('.agi-stage-floor'));+ state.el3d = el;+}++// ── render: hero ──────────────────────────────────────────────────────────────+function renderHero(d) {+ const { doctrine, cognition: cog, agent } = d;+ const ledgerHref = agent?.id ? `/ledger/${agent.id}` : '/ledger';+ return `+ <section class="agi-hero">+ <div class="agi-hero-copy">+ <span class="agi-domain-tag"><i class="agi-dot"></i> ${esc(doctrine.domain)}</span>+ <h1 class="agi-title" id="agi-title">The first AGI.<br /><span class="agi-em">Narrow by design.</span></h1>+ <p class="agi-lede">${esc(doctrine.thesis)}</p>+ <p class="agi-thesis">It is not a chatbot pretending to be smart. It is a single autonomous agent that out-trades humans at one game — and tells you plainly it can do nothing else.</p>+ <div class="agi-hero-actions">+ <a class="agi-btn agi-btn-primary" href="${ledgerHref}">Audit its track record →</a>+ <a class="agi-btn" href="/trader/${agent?.id || ''}">Live trades</a>+ </div>+ </div>+ <div class="agi-stage" id="agi-stage" aria-label="Live embodiment of the trading agent">+ <div class="agi-stage-boot">embodying…</div>+ <div class="agi-stage-floor">+ <span class="agi-state-pill"><i class="agi-spark"></i> ${esc(cog.label)}</span>+ <span class="agi-conviction">${cog.conviction != null ? `conviction ${Math.round(cog.conviction * 100)}%` : 'scanning'}</span>+ </div>+ </div>+ </section>`;+}++// ── render: live mind ───────────────────────────────────────────────────────+function renderThought(t, network, fresh) {+ const reconciled = t.outcome?.status === 'reconciled';+ const verdict = reconciled+ ? (t.outcome.was_correct+ ? `<span class="agi-verdict win">right ${t.outcome.pnl_sol != null ? fmtSol(t.outcome.pnl_sol) + ' SOL' : ''}</span>`+ : `<span class="agi-verdict loss">wrong ${t.outcome.pnl_sol != null ? fmtSol(t.outcome.pnl_sol) + ' SOL' : ''}</span>`)+ : `<span class="agi-verdict pending">open call</span>`;+ const conf = t.confidence != null ? Math.round(t.confidence * 100) : null;+ const tokenUrl = solscanToken(t.mint, network);+ const proof = reconciled && t.outcome.proof_url ? ` · <a href="${esc(t.outcome.proof_url)}" target="_blank" rel="noopener">proof</a>` : '';+ return `+ <article class="agi-thought${fresh ? ' agi-fresh' : ''}">+ <div class="agi-thought-top">+ <span class="agi-thought-kind">▸ ${esc(t.kind || 'decision')}+ ${t.mint ? `<span class="agi-thought-mint">${tokenUrl ? `<a href="${esc(tokenUrl)}" target="_blank" rel="noopener">${esc(shortMint(t.mint))}</a>` : esc(shortMint(t.mint))}</span>` : ''}+ </span>+ <span class="agi-thought-time">${esc(timeAgo(t.decided_at))}</span>+ </div>+ ${t.rationale ? `<p class="agi-thought-body">${esc(t.rationale)}</p>` : ''}+ <div class="agi-thought-meta">+ ${conf != null ? `<span class="agi-muted">said ${conf}%</span><span class="agi-conf-bar"><span style="width:${conf}%"></span></span>` : ''}+ ${verdict}${proof}+ </div>+ </article>`;+}++function renderMind(d) {+ const list = d.decisions || [];+ const body = list.length+ ? `<div class="agi-stream">${list.map((t) => renderThought(t, d.network, !state.seen.has(t.id))).join('')}</div>`+ : `<div class="agi-empty"><p>No decisions logged in this window yet. Every call it makes will appear here — with its reasoning, its stated confidence, and, once the trade resolves, whether it was right.</p></div>`;+ list.forEach((t) => state.seen.add(t.id));+ return `+ <section class="agi-card agi-mind">+ <div class="agi-section-head">+ <h2>The mind, out loud</h2>+ <span class="agi-section-sub">every call, tamper-evident</span>+ </div>+ ${body}+ </section>`;+}++// ── render: track record ──────────────────────────────────────────────────────+function ring(score) {+ const r = 40, c = 2 * Math.PI * r;+ const pct = Math.max(0, Math.min(100, Number(score) || 0));+ const off = c * (1 - pct / 100);+ return `+ <div class="agi-ring">+ <svg viewBox="0 0 92 92" aria-hidden="true">+ <circle class="agi-ring-track" cx="46" cy="46" r="${r}" fill="none" stroke-width="6" />+ <circle class="agi-ring-val" cx="46" cy="46" r="${r}" fill="none" stroke-width="6"+ stroke-dasharray="${c.toFixed(1)}" stroke-dashoffset="${off.toFixed(1)}" />+ </svg>+ <div class="agi-ring-num"><b>${Math.round(pct)}</b><small>reputation</small></div>+ </div>`;+}++function stat(k, v, cls = '') {+ return `<div class="agi-stat"><div class="k">${esc(k)}</div><div class="v ${cls}">${v}</div></div>`;+}++function renderRecord(d) {+ const p = d.performance;+ const rep = d.reputation;+ const agent = d.agent;+ if (!p) {+ return `+ <section class="agi-card">+ <div class="agi-section-head"><h2>Track record</h2></div>+ <div class="agi-empty"><p>The track record fills in as soon as the agent closes its first proven trade. Nothing is shown until it's real and on-chain.</p></div>+ </section>`;+ }+ const winRate = p.win_rate != null ? `${Math.round(p.win_rate * 100)}%` : '—';+ const hit = p.snipe_hit_rate != null ? `${Math.round(p.snipe_hit_rate * 100)}%` : '—';+ const positions = (d.positions || []).map((pos) => {+ const url = solscanToken(pos.mint, d.network);+ const label = pos.symbol || shortMint(pos.mint);+ return `<div class="agi-position"><span>${url ? `<a href="${esc(url)}" target="_blank" rel="noopener">${esc(label)}</a>` : esc(label)}</span><span class="${pnlClass(pos.unrealized_pct)}">${fmtPct(pos.unrealized_pct)}</span></div>`;+ }).join('');+ const calNote = rep && rep.sample_size+ ? `Computed from <b>${rep.sample_size}</b> reconciled call${rep.sample_size === 1 ? '' : 's'} — hit rate, calibration, and realized P&L, regressed toward neutral until proven.`+ : `Regressed toward neutral — too few reconciled calls to trust yet.`;+ const ledgerHref = agent?.id ? `/ledger/${agent.id}` : '/ledger';+ return `+ <section class="agi-card">+ <div class="agi-section-head">+ <h2>Track record</h2>+ <span class="agi-section-sub">${p.verified ? 'verified trader' : 'unverified'}</span>+ </div>+ <div class="agi-rep">+ ${ring(rep ? rep.score : p.score)}+ <div class="agi-rep-side">${calNote}</div>+ </div>+ <div class="agi-stats">+ ${stat('Win rate', winRate)}+ ${stat('Realized P&L', `<span class="${pnlClass(p.realized_pnl_sol)}">${fmtSol(p.realized_pnl_sol)} SOL</span>`)}+ ${stat('Snipe hit rate', hit)}+ ${stat('ROI', `<span class="${pnlClass(p.roi_pct)}">${fmtPct(p.roi_pct)}</span>`)}+ ${stat('Closed trades', String(p.closed_count ?? 0))}+ ${stat('Coins traded', String(p.unique_coins ?? 0))}+ </div>+ ${positions ? `<div class="agi-section-head" style="margin-bottom:var(--space-sm)"><h2 style="font-size:var(--text-md)">Open now</h2><span class="agi-section-sub">${pnlClass(p.unrealized_pnl_sol) === 'agi-neg' ? '' : ''}<span class="${pnlClass(p.unrealized_pnl_sol)}">${fmtSol(p.unrealized_pnl_sol)} SOL unrealized</span></span></div><div class="agi-positions">${positions}</div>` : ''}+ <p class="agi-honesty">Being wrong is visible — that's the point. Every loss above is counted, never hidden. <a href="${ledgerHref}">Interrogate the full ledger →</a></p>+ </section>`;+}++// ── render: doctrine ──────────────────────────────────────────────────────────+function renderDoctrine(d) {+ const { doctrine } = d;+ return `+ <section class="agi-doctrine">+ <div class="agi-doctrine-grid">+ <div class="agi-card agi-claim">+ <h3>What it is</h3>+ <ul class="agi-list">+ <li><span class="agi-mark">✓</span><span>Superhuman at <b>${esc(doctrine.domain)}</b> — reading launches, the wallet graph, and order flow faster and more consistently than a human.</span></li>+ <li><span class="agi-mark">✓</span><span>Fully autonomous: it sizes, enters, and exits on its own, inside hard spend caps and a kill switch.</span></li>+ <li><span class="agi-mark">✓</span><span>Accountable: every decision is logged with its reasoning and reconciled against the real outcome.</span></li>+ </ul>+ </div>+ <div class="agi-card agi-refuse">+ <h3>What it refuses</h3>+ <ul class="agi-list">+ ${doctrine.refusals.map((r) => `<li><span class="agi-mark">✕</span><span>${esc(r)}</span></li>`).join('')}+ </ul>+ </div>+ </div>+ </section>`;+}++// ── full render ───────────────────────────────────────────────────────────────+function render(d) {+ root.innerHTML = renderHero(d) + `<div class="agi-grid">${renderMind(d)}${renderRecord(d)}</div>` + renderDoctrine(d);+ applyAura(d.cognition);+ mountBody(d.agent);+ if (state.embodied) applyMood(d.cognition);+}++function renderLoading() {+ root.innerHTML = `+ <section class="agi-hero">+ <div class="agi-hero-copy">+ <span class="agi-domain-tag"><i class="agi-dot"></i> memecoin trading · pump.fun</span>+ <h1 class="agi-title">The first AGI.<br /><span class="agi-em">Narrow by design.</span></h1>+ <div class="agi-skel" style="height:80px;max-width:46ch"></div>+ </div>+ <div class="agi-stage"><div class="agi-stage-boot">waking the agent…</div></div>+ </section>+ <div class="agi-grid">+ <section class="agi-card"><div class="agi-skel" style="height:300px"></div></section>+ <section class="agi-card"><div class="agi-skel" style="height:300px"></div></section>+ </div>`;+}++function renderError() {+ root.innerHTML = `+ <div class="agi-error">+ <h2 style="font-family:var(--font-display);color:var(--ink)">The agent is unreachable</h2>+ <p>Couldn't load the AGI's live state right now. This is a transient connection issue — the agent keeps trading regardless.</p>+ <button class="agi-btn agi-btn-primary" id="agi-retry" type="button">Retry</button>+ </div>`;+ document.getElementById('agi-retry')?.addEventListener('click', () => { renderLoading(); boot(); });+}++// ── boot + poll ───────────────────────────────────────────────────────────────+async function refresh() {+ try {+ const d = await fetchState();+ state.data = d;+ render(d);+ document.title = d.agent?.name ? `${d.agent.name} — The AGI · three.ws` : 'The AGI · three.ws';+ } catch (e) {+ if (!state.data) renderError();+ // If we already have a render up, keep it and try again next tick.+ }+}++async function boot() {+ await refresh();+ if (state.timer) clearInterval(state.timer);+ state.timer = setInterval(() => { if (!document.hidden) refresh(); }, POLL_MS);+}++document.addEventListener('visibilitychange', () => { if (!document.hidden && state.data) refresh(); });++renderLoading();+boot();diff --git a/src/walk-companion.js b/src/walk-companion.jsindex 06f595742..ff9c37573 100644--- a/src/walk-companion.js+++ b/src/walk-companion.js@@ -17,6 +17,10 @@ import { installTransitions } from './walk-companion-transitions.js';import { createWalkTrails2D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';import { installClickToWalk } from './walk-companion-click-to-walk.js';import { installNarrator } from './walk-companion-narrator.js';+// The companion is the site-wide "your agent" body. Booting the mood embodiment+// here makes it reflect the agent's live emotional state (aura + breathing) on+// every page the companion runs — and starts the mood engine for the session.+import './agents/mood-embodiment.js';const walk = createWalkCompanion({// Static GLBs and the animation manifest are served from this origin.diff --git a/vercel.json b/vercel.jsonindex b02897820..735d18b24 100644--- a/vercel.json+++ b/vercel.json@@ -492,6 +492,14 @@"src": "/ledger/?","dest": "/reasoning-ledger.html"},+ {+ "src": "/api/agi/state",+ "dest": "/api/agi/state"+ },+ {+ "src": "/agi/?",+ "dest": "/agi.html"+ },{"src": "/api/billing/receipts","dest": "/api/billing/receipts"