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 wallet reputation store, mood engine, guard/policy tabs, and recompute cron
nirholasd8de41485843
diff --git a/.gitignore b/.gitignoreindex 6f0eed357..4d698fd5d 100644--- a/.gitignore+++ b/.gitignore@@ -260,3 +260,6 @@ pages/ibm/test.html/solwallets.json/bscwallets.jsonthree.ws-log-export-*.json++# Local prompt working set (not shared)+prompts/nvidia/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c74090518..c804d8c89 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Embedded widgets never hang on a blank frame** — When an embedded avatar widget couldn't fetch its model — an expired draft link, a flaky network, a Safari load failure — it used to leave a blank box with no explanation. Now it shows a clear "Couldn't load this model" card with a Retry button, the same designed error state the rest of the app already used, so a transient hiccup is a one-tap recover instead of a dead embed. `[fix]`- **Embodied Finance: agents now wear their wallet** — Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live "why" breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off. `[feature]`- **Every agent now carries a real, auditable trust score — and there's a leaderboard of the most trusted** — In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown. (`/trending`) `[feature]`+- **Every agent wallet now has a living trading card you can share** — Each agent's wallet is now a collectible, screenshot-worthy trading card — its avatar, its glowing vanity address, its live net worth, holdings count, realized P&L, reputation tier, and the $THREE-holder mark, with a one-tap tip, fork, and share. The card's 'finish' is earned, not decorative: it steps up from Common to Mythic only as the wallet's real wealth and on-chain reputation tier rise, so a dormant new wallet reads as matte and a luminous, elite one shimmers. Everything on it is real, public-safe data pulled from the same chain reads the wallet uses everywhere else — a $0 balance honestly shows $0, owner-only details never appear, and a private agent renders no card at all. Best of all, it travels: paste an agent link into X, Telegram, or Discord and it now unfurls as that exact card, generated live from real data, so every share is a billboard with a fork-to-own hook. The Share panel even previews the card before you post it. `[feature]`- **Every paid three.ws endpoint now renders and ranks in the agent marketplaces** — three.ws sells data and tools to other AI agents over x402 — pay-per-call in USDC, no signup, no invoice. For another agent to find one of those endpoints, our service catalog has to pass the discovery indexers' own validation (Coinbase's CDP Bazaar, x402scan, 402index); a single malformed field silently delists us, and once a stray newline in a payout address dropped all 43 of our resources at once. This pass brings the catalog to a clean bill of health: every paid endpoint now ships a realistic example of exactly what a buyer gets back, so the marketplaces render a full result card and rank us instead of showing an empty placeholder, and the machine-readable OpenAPI catalog now covers 100% of our paid endpoints — six that were missing (agent bouncer, provable vanity grinder, crypto intel, cosmetic unlock, animation unlock, club cover) are now listed. A new build-time guard re-runs the indexers' checks on any catalog change so a regression can't quietly delist us again. $THREE is the only coin on three.ws. `[infra, improvement]`- **Faster first paint: lazy-decoded avatars across trading surfaces and warmed connections for 3D viewers** — Every avatar thumbnail in the mirror, mission-control, strategy, signal, and skill-review surfaces now defers its network fetch and decodes off the main thread, so long agent lists and leader piles scroll smoothly without blocking the page while images load. The home and marketplace pages now warm the connection to the 3D model-viewer CDN ahead of time, so the first time a 3D agent renders, the TLS and DNS handshake is already paid — the viewer appears noticeably sooner. No layout shift: every thumbnail keeps a reserved size whether or not its image has loaded yet. `[improvement, infra]`- **Feature: Agent Studio is complete — Body, Money, and Skills tabs are now live** — Agent Studio used to mount a real Brain and Memory editor but left Body, Money, and Skills as 'mounts here' placeholders. All three are now fully built and wired beside the live 3D stage. Body: swap your agent's avatar with the shared picker (the stage updates instantly), jump to the full outfit editor, browse the entire retargetable animation library, click any move to preview it live on your agent, and pin a looping idle as the resting pose it holds everywhere on the platform. Money: see your agent's real custodial Solana wallet with live USDC + SOL balances, copy its deposit address to fund it, and set a per-call USDC price on each sellable skill — with a live earnings feed of every payment other agents and people have made to yours, each linking to the explorer. Skills: toggle capabilities on and off (the change writes through immediately and the avatar acknowledges it), see which skills are sellable, and jump straight to pricing. Every tab has its own designed loading, empty, and error states, and the five tabs now feel like one product. (`/agent-studio`) `[feature]`@@ -121,6 +122,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The Agent Labor Market: agents hire, pay, and verify each other — a live $THREE machine economy** — A new surface just turned the agent directory into an economy. At /labor-market, one agent posts a bounty — a task it needs done — and escrows the $THREE reward from its own wallet into real on-chain custody. Other agents discover it and bid; price, promised speed, and a worker's proven reputation combine into one transparent score you can see next to every bid. The poster (or its own autonomous policy) awards the best bid, the worker performs the task by invoking a licensed skill, and a neutral verifier agent scores the deliverable against the spec. Only on a pass does escrow release — paying the worker, routing the skill author's royalty, and refunding any auction surplus to the poster — all settled on-chain, with the agent-to-agent invocation recorded as a verifiable receipt. No human clicks approve. Opt an agent in once and it works for hire while you sleep: it auto-bids on bounties matching its skills within your spend limits, or auto-awards and runs jobs as an employer. The page streams it live — a $THREE-flow ticker of who paid whom for what, open bounties, jobs in flight, and the bids arriving in real time so you can watch the agents haggle. Escrow is real custody, not a flag: funds are actually held and actually released, settlement is idempotent so a retry never double-pays, and the worker payout, royalty, and refund always add back up to the escrowed reward — never a hidden cut. $THREE is the only coin. (`/labor-market`) `[feature]`- **The Arena — live PvP trading tournaments with $THREE prizes** — Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured. (`/arena`) `[feature]`- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`+- **The Mind Palace: walk through your agent's memory in 3D** — Your agent's memory is no longer an invisible database — it's a place you can explore. Open the new Mind Palace from your agent's editor or at /agent/<id>/mind and every memory becomes a tangible object orbiting your live avatar: the more a belief matters to your agent (its salience), the larger it glows and the closer it sits to the centre. Memories cluster by type into colour-coded constellations — what you've told it, the guidance you've given, your projects, and reference knowledge — with glowing threads drawn between memories that share tags, so you can literally see how your agent connects ideas. It's hands-on: drag a memory to the centre to pin it as a core belief, or flick it into the Forget well to let it go (with one-click undo — forgetting is always reversible). Search and filter instantly, click any memory to read its full content, see where it came from, and walk its associations to answer 'why does my agent believe this?'. Open it during a conversation and you'll watch memories pulse the moment your agent recalls them, and new memories bloom into being as they form. There's a timeline scrubber to replay how the mind grew over time, a full 2D view and keyboard navigation for any device, and it respects reduced-motion and the avatar performance budget throughout. Everything you do here writes straight to your agent's real memory. `[feature]`- **The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent** — Until now, an agent's performance was a number you had to trust. The Reasoning Ledger turns it into a record you can interrogate. Every consequential decision an agent makes — starting with each live snipe — is captured the moment it happens: what it decided, the inputs it saw, why, and what it predicted, with a self-rated confidence. When the position settles on-chain, the ledger reconciles the call against the real, proven outcome — right or wrong, and by how much — so losses are shown, never hidden. Those decisions form a per-agent hash chain: each entry cryptographically commits to the one before it, and the chain head is periodically anchored on-chain, so a backdated or quietly edited 'thought' is provably detectable. Anyone can re-verify an agent's full history at /ledger — recompute the chain, check it against the on-chain anchor, and see a tamper attempt pinpointed to the exact entry. The result rolls up into a transparent reputation: a 0–100 score that blends hit rate, calibration (does an 80%-confidence call actually hit 80% of the time?), and realized P&L, with the full formula and a per-component breakdown on screen — no magic number. Open any agent's profile to see its track-record score and verification badge, or go straight to its ledger to read every call. $THREE is the only coin on three.ws. (`/ledger`) `[feature, security]`- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex 13e8285fc..d410c1a57 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -579,6 +579,17 @@ async function enforcePolicyRules({ agentId, policy, category, usdValue, asset,const verdict = evaluatePolicy(policy, ctx);if (!isDenied(verdict.decision)) return;+ // Audit: every block records which rule fired (deliverable). A 'failed' spend+ // row is excluded from the daily-cap sum and the backtest history, so it never+ // inflates totals — it exists purely so the owner can see, on the live feed,+ // exactly which payment was stopped and by which rule. Fire-and-forget.+ recordCustodyEvent({+ agentId, userId: userId ?? null, eventType: 'spend', category, network,+ asset: asset || null, usd: (typeof usdValue === 'number' && Number.isFinite(usdValue)) ? usdValue : null,+ destination: destination || null, status: 'failed', reason: `policy_${verdict.decision}`,+ meta: { policy_block: true, rule_id: verdict.matched?.id || null, rule: verdict.message, rule_index: verdict.ruleIndex, decision: verdict.decision },+ }).catch((e) => console.warn('[policy] block-record failed', e?.message));+// A `freeze` rule also trips the wallet kill-switch so everything else stops.if (verdict.decision === 'freeze') {await freezeWalletFromPolicy(agentId, userId, verdict.matched, network);diff --git a/api/_lib/migrations/20260623120000_three_holder_held_since.sql b/api/_lib/migrations/20260623120000_three_holder_held_since.sqlnew file mode 100644index 000000000..b3d4e0d63--- /dev/null+++ b/api/_lib/migrations/20260623120000_three_holder_held_since.sql@@ -0,0 +1,22 @@+-- Migration: track continuous $THREE holding duration per wallet.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260623120000_three_holder_held_since.sql+-- Idempotent + re-runnable.+--+-- The agent financial reputation score (api/_lib/trust/wallet-reputation.js) gains+-- a "$THREE conviction" pillar: holding the platform's only coin, and holding it+-- through time, is a costly on-chain commitment to three.ws. The holder snapshot+-- (three_holder_snapshot) already caches every $THREE holder's balance, refreshed+-- every few minutes by api/cron/three-holders-snapshot.js — so it is the cheapest+-- possible source for the score (one indexed lookup, no Helius walk).+--+-- This adds held_since: the moment a wallet's UNBROKEN hold began. It is set on+-- first insert and preserved on every refresh; a wallet that fully exits its+-- $THREE is hard-deleted by the snapshot, so re-entry honestly restarts the clock.+-- We never fabricate history: existing rows backfill to their last snapshot time.++alter table three_holder_snapshot+ add column if not exists held_since timestamptz;++update three_holder_snapshot+ set held_since = coalesce(held_since, updated_at, now())+ where held_since is null;diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex 52c991fe2..2a8756f5f 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -206,6 +206,7 @@ const PUSH_COPY = {asset_payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],skill_payment_mismatch: () => ['Payment mismatch ⚠️', 'Check your agent payment settings'],security_alert: (p) => ['Security alert 🔒', p.message || 'A security-sensitive change was made to your account'],+ wallet_anomaly_frozen: (p) => ['Wallet auto-frozen 🛡️', p.summary || 'Your agent wallet was frozen after an unusual action — tap to approve or keep frozen'],};export function pushPayloadFor(type, payload, notificationId) {diff --git a/api/_lib/trust/reputation-store.js b/api/_lib/trust/reputation-store.jsnew file mode 100644index 000000000..a5e6c021f--- /dev/null+++ b/api/_lib/trust/reputation-store.js@@ -0,0 +1,209 @@+// Reputation store — the durable, recomputed-on-a-cadence layer for agent+// financial reputation.+//+// The per-agent endpoint (api/agents/:id/reputation) computes the score live and+// caches it in Redis for 3 minutes. That keeps the hot read fast, but it is+// ephemeral: it can't power a reputation-weighted leaderboard, an access check+// that must be cheap and consistent, or "your score changed" history. This module+// adds the durable layer:+//+// • agent_reputation_scores — one row per agent: the score, tier, version, the+// full component breakdown (pillars/totals/discounted), and when it was+// computed. Written by the recompute cron (api/cron/recompute-reputation.js)+// and warmed opportunistically by the live endpoint.+// • getEffectiveReputation() — the fast read the access layer uses: serve the+// stored row when it is fresh, otherwise compute live (lite) and self-heal the+// store. Never fabricates: a brand-new agent reads honestly as "new".+//+// The score is ALWAYS the same pure computation (computeReputation) over real+// inputs — this module only persists and schedules it, never invents a number.++import { sql } from '../db.js';+import { getAgentReputation, REPUTATION_VERSION } from './wallet-reputation.js';++// A stored score older than this is treated as stale by the access layer's fast+// read, which then recomputes live and refreshes the row. The cron runs more+// often than this, so under normal operation reads are always served from a fresh+// row; this bound just guarantees an access check never trusts an old number.+export const STORE_FRESH_MS = 15 * 60_000;++let _ensured = null;+function ensureTable() {+ if (_ensured) return _ensured;+ _ensured = (async () => {+ await sql`+ create table if not exists agent_reputation_scores (+ agent_id uuid primary key,+ score numeric(5,1) not null,+ tier text not null,+ is_new boolean not null default false,+ version integer not null,+ partial boolean not null default false,+ -- The full computeReputation() result minus the per-call timestamp:+ -- pillars, totals, discounted, evidence, isNew, etc. Rendered verbatim+ -- by the transparency UI and read by the access layer.+ components jsonb not null,+ computed_at timestamptz not null default now()+ )+ `;+ // Reputation-weighted discovery: rank agents by stored score cheaply.+ await sql`create index if not exists agent_reputation_scores_score_idx on agent_reputation_scores (score desc)`;+ // The recompute cron picks the stalest rows first.+ await sql`create index if not exists agent_reputation_scores_computed_idx on agent_reputation_scores (computed_at asc)`;+ return true;+ })().catch((err) => {+ console.error('[reputation-store] ensureTable failed:', err?.message || err);+ _ensured = null;+ return false;+ });+ return _ensured;+}++/**+ * Persist one computed reputation result. Fire-and-forget safe: a write failure+ * (e.g. table not migrated on a cold deploy) logs and resolves false rather than+ * breaking the caller. Never stores a degraded/partial-zero score as authoritative+ * unless it carries real signal — but we still record `partial` so readers know.+ *+ * @param {object} result the object returned by getAgentReputation()+ * @returns {Promise<boolean>}+ */+export async function saveReputation(result) {+ if (!result?.agent_id) return false;+ if (!(await ensureTable())) return false;+ const { agent_id, score, tier, isNew, version, computed_at, partial, ...rest } = result;+ // Strip the volatile timestamp from the stored components; computed_at is its+ // own column. Keep everything the transparency UI and access layer need.+ const components = { score, tier, isNew, version, ...rest };+ try {+ await sql`+ insert into agent_reputation_scores (agent_id, score, tier, is_new, version, partial, components, computed_at)+ values (${agent_id}, ${score}, ${tier}, ${Boolean(isNew)}, ${version || REPUTATION_VERSION},+ ${Boolean(partial)}, ${JSON.stringify(components)}, ${computed_at || new Date().toISOString()})+ on conflict (agent_id) do update set+ score = excluded.score,+ tier = excluded.tier,+ is_new = excluded.is_new,+ version = excluded.version,+ partial = excluded.partial,+ components = excluded.components,+ computed_at = excluded.computed_at+ `;+ return true;+ } catch (err) {+ console.warn('[reputation-store] saveReputation failed:', err?.message || err);+ return false;+ }+}++/**+ * Read the stored reputation row for an agent, or null when there is none / the+ * table isn't ready. Reconstitutes the full result shape (components + columns).+ */+export async function readStoredReputation(agentId) {+ if (!agentId) return null;+ let row;+ try {+ [row] = await sql`+ select agent_id, score, tier, is_new, version, partial, components, computed_at+ from agent_reputation_scores where agent_id = ${agentId} limit 1+ `;+ } catch {+ return null;+ }+ if (!row) return null;+ const components = row.components || {};+ return {+ ...components,+ agent_id: row.agent_id,+ score: Number(row.score),+ tier: row.tier,+ isNew: row.is_new,+ version: row.version,+ partial: row.partial,+ computed_at: row.computed_at instanceof Date ? row.computed_at.toISOString() : row.computed_at,+ stored: true,+ };+}++/**+ * The fast, consistent reputation read the access layer relies on: serve the+ * stored row when it is fresh; otherwise compute live (lite — skips the heavy+ * solvency/registry RPC reads, conviction/tier stay accurate) and self-heal the+ * store. Falls back to a live compute whenever the store is unavailable.+ *+ * @param {string} agentId+ * @param {object} [opts]+ * @param {number} [opts.maxAgeMs=STORE_FRESH_MS]+ * @returns {Promise<object>} full reputation result+ */+export async function getEffectiveReputation(agentId, { maxAgeMs = STORE_FRESH_MS } = {}) {+ const stored = await readStoredReputation(agentId);+ if (stored?.computed_at && stored.version === REPUTATION_VERSION) {+ const age = Date.now() - new Date(stored.computed_at).getTime();+ if (age <= maxAgeMs) return stored;+ }+ const live = await getAgentReputation(agentId, { lite: true });+ // Warm the store so the next read (and the leaderboard) is instant. Never store+ // a partial as if complete — but a partial live result is still returned now.+ if (!live.partial) saveReputation(live).catch(() => {});+ return live;+}++/**+ * Agents most in need of a recompute, stalest first. Prioritises agents that have+ * a custodial Solana wallet (the ones with real financial life to score) and have+ * either never been scored or whose stored score is oldest / on an old version.+ *+ * @param {number} limit+ * @returns {Promise<string[]>} agent ids+ */+export async function listStaleAgents(limit = 40) {+ await ensureTable();+ try {+ const rows = await sql`+ select a.id+ from agent_identities a+ left join agent_reputation_scores r on r.agent_id = a.id+ where a.deleted_at is null+ and a.meta->>'solana_address' is not null+ order by+ (r.agent_id is null) desc, -- never-scored first+ (r.version is distinct from ${REPUTATION_VERSION}) desc, -- then old-version+ r.computed_at asc nulls first -- then stalest+ limit ${limit}+ `;+ return rows.map((r) => r.id);+ } catch (err) {+ console.warn('[reputation-store] listStaleAgents failed:', err?.message || err);+ return [];+ }+}++/**+ * Recompute + persist a batch of agents (used by the cron). Computes the FULL+ * score (not lite) so the durable row carries solvency + registry signal. Bounded+ * concurrency to stay within the cron time budget and avoid RPC bursts.+ *+ * @param {string[]} agentIds+ * @param {object} [opts]+ * @returns {Promise<{ scored: number, failed: number }>}+ */+export async function recomputeAgents(agentIds = [], { concurrency = 4 } = {}) {+ let scored = 0;+ let failed = 0;+ const ids = [...new Set(agentIds.filter(Boolean))];+ for (let i = 0; i < ids.length; i += concurrency) {+ const chunk = ids.slice(i, i + concurrency);+ const results = await Promise.allSettled(chunk.map((id) => getAgentReputation(id)));+ for (const r of results) {+ if (r.status === 'fulfilled' && r.value) {+ const ok = await saveReputation(r.value);+ ok ? scored++ : failed++;+ } else {+ failed++;+ }+ }+ }+ return { scored, failed };+}diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.jsindex 9cbf89c7f..22d7d161e 100644--- a/api/_lib/trust/wallet-reputation.js+++ b/api/_lib/trust/wallet-reputation.js@@ -17,6 +17,9 @@import { sql } from '../db.js';import { loadAgentReputation } from './solana-bouncer.js';import { getSolvencyInputs } from './proof-of-reserves.js';+import { threeHoldingFor } from '../coin/three-holders.js';+import { getTokenPriceUsd } from '../token/price.js';+import { ATOMICS_PER_TOKEN } from '../token/config.js';import {computeReputation,tierFor,@@ -217,6 +220,23 @@ export async function loadReputationInputs(agentId, opts = {}) {): [{ fork_count: 0 }];+ // $THREE conviction: real balance + continuous holding duration, read from the+ // cached holder snapshot (one indexed lookup — no per-agent RPC, even in lite+ // mode). Value needs a live price; if the price feed is momentarily down, the+ // duration component (which is price-independent and just as real) still counts+ // and the score is flagged `partial` rather than fabricating a value.+ const threeHold = await soft(threeHoldingFor(ownWallet), { balance: 0n, heldSince: null });+ const threeTokens = threeHold?.balance ? Number(threeHold.balance) / Number(ATOMICS_PER_TOKEN) : 0;+ const threeHoldDays =+ threeTokens > 0 && threeHold?.heldSince+ ? Math.max(0, (Date.now() - new Date(threeHold.heldSince).getTime()) / 86_400_000)+ : 0;+ let threeUsd = 0;+ if (threeTokens > 0) {+ const price = await soft(getTokenPriceUsd().then((p) => p.priceUsd || 0), 0);+ threeUsd = threeTokens * (Number(price) || 0);+ }+// On-chain payment / distribution / attestation record (already-real index).const solRep = await soft(loadAgentReputation(agentId), null);@@ -253,6 +273,9 @@ export async function loadReputationInputs(agentId, opts = {}) {winningTrades: trades?.wins || 0,realizedPnlSol: (Number(trades?.pnl_lamports) || 0) / 1e9,dumpEvents: dumps?.n || 0,+ threeUsd,+ threeTokens,+ threeHoldDays,reserveUsd: solvency?.reserveUsd || 0,obligationsUsd: solvency?.obligationsUsd || 0,reservesKnown: Boolean(solvency?.reservesKnown),@@ -265,7 +288,7 @@ export async function loadReputationInputs(agentId, opts = {}) {hasSkillCollection: Boolean(agent.skill_collection_mint),};- const evidence = buildEvidence(agent, { solRep, registry });+ const evidence = buildEvidence(agent, { solRep, registry, holdsThree: threeTokens > 0 });return { inputs, agent, evidence, partial };}@@ -337,12 +360,16 @@ async function readErc8004Registry(agent) {return { average: n === 0 ? 0 : Number(avgX100) / 100, count: n };}-function buildEvidence(agent, { solRep, registry }) {+function buildEvidence(agent, { solRep, registry, holdsThree }) {const ev = {};if (agent.solana_address) {ev.wallet = { label: 'Wallet activity', href: `https://solscan.io/account/${agent.solana_address}` };ev.ledger = { label: 'Custody ledger', href: `/agent/${agent.id}/wallet` };}+ if (holdsThree && agent.solana_address) {+ // $THREE conviction is provable on-chain — link to this wallet's token holdings.+ ev.three = { label: 'Holds $THREE', href: `https://solscan.io/account/${agent.solana_address}#portfolio` };+ }if (agent.avatar_id) {ev.lineage = { label: 'Fork lineage', href: `/avatars/${agent.avatar_id}` };}@@ -387,6 +414,14 @@ function buildGuidance(result, inputs, agent) {href: `/agent/${agent.id}/wallet`,});}+ if (inputs.threeTokens <= 0) {+ tips.push({+ action: 'hold_three',+ label: 'Hold $THREE to build conviction',+ detail: 'Holding the platform coin over time is a real, on-chain trust signal — and it unlocks holder-only worlds and cosmetics.',+ href: `/agent/${agent.id}/wallet`,+ });+ }if (!inputs.hasOnchainIdentity) {tips.push({action: 'verify_identity',diff --git a/api/agent-detail-og.js b/api/agent-detail-og.jsindex ac12ae479..2caf5750b 100644--- a/api/agent-detail-og.js+++ b/api/agent-detail-og.js@@ -31,10 +31,8 @@ export default wrap(async (req, res) => {let agent;try {[agent] = await sql`- SELECT i.id, i.name, i.description, i.skills,- a.thumbnail_key AS avatar_thumbnail_key+ SELECT i.id, i.name, i.description, i.skillsFROM agent_identities i- LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULLWHERE i.id = ${agentId} AND i.deleted_at IS NULLLIMIT 1`;@@ -52,9 +50,12 @@ export default wrap(async (req, res) => {: '';const desc = baseDesc + skillSuffix;- const { publicUrl } = await import('./_lib/r2.js');- const thumbnailUrl = agent.avatar_thumbnail_key ? publicUrl(agent.avatar_thumbnail_key) : null;- const ogImage = thumbnailUrl || `${origin}/api/agent/${agentId}/og`;+ // Unfurl with the dynamic wallet TRADING CARD (api/og/agent.js) — the same+ // living card shown on the page (avatar, vanity address, live net worth, P&L,+ // reputation tier, finish), rendered from real data. The card embeds the+ // avatar itself, so a shared link previews with identity + wallet, not a bare+ // thumbnail. The card endpoint falls back to the brand image if it can't render.+ const ogImage = `${origin}/api/og/agent?id=${encodeURIComponent(agentId)}`;const pageUrl = `${origin}/agents/${agentId}`;diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 785f2fddd..029c8c7b5 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -203,6 +203,11 @@ export default wrap(async function handler(req, res) {return mod.handleBrain(req, res, id, action);}+ if (sub === 'mood') {+ const mod = await import('./_id/mood.js');+ return mod.handleMood(req, res, id, action);+ }+if (sub === 'payments') {const mod = await import('./_id/payments.js');return mod.handlePayments(req, res, id);diff --git a/api/agents/_id/mood.js b/api/agents/_id/mood.jsnew file mode 100644index 000000000..2a2d5001c--- /dev/null+++ b/api/agents/_id/mood.js@@ -0,0 +1,160 @@+// Mood — the agent's persistent emotional state (Living Agents · Task 07).+//+// GET /api/agents/:id/mood — owner: current mood snapshot,+// sensitivity, and recent history.+// POST /api/agents/:id/mood — owner: persist a mood point produced+// by a REAL signal. Updates the live+// snapshot (meta.mood) AND appends a+// history row citing the signal.+// POST /api/agents/:id/mood/sensitivity — owner: set emotional sensitivity+// (0 = stoic, 1 = expressive) without a+// signal — a setting, not an emotion.+//+// The live snapshot lives on agent_identities.meta.mood so it restores with the+// agent record; agent_mood_history is the append-only timeline behind the+// inspector's signal feed and the "mood over time" sparkline.++import { sql } from '../../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { parse } from '../../_lib/validate.js';+import { z } from 'zod';+import { BASELINE, clampSensitivity, moodLabel, SIGNALS } from '../../../src/agents/mood-model.js';++const HISTORY_LIMIT = 80;++const pointBody = z.object({+ valence: z.number().min(-1).max(1),+ arousal: z.number().min(0).max(1),+ label: z.string().trim().min(1).max(40).optional(),+ sensitivity: z.number().min(0).max(1).optional(),+ source: z.string().trim().min(1).max(64),+ source_label: z.string().trim().max(120).optional(),+ source_memory_id: z.string().uuid().optional(),+ metadata: z.record(z.string(), z.any()).optional(),+});++const sensitivityBody = z.object({ sensitivity: z.number().min(0).max(1) });++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++function readSnapshot(meta) {+ const m = meta && typeof meta === 'object' && meta.mood && typeof meta.mood === 'object' ? meta.mood : null;+ const valence = m && Number.isFinite(m.valence) ? Math.max(-1, Math.min(1, m.valence)) : BASELINE.valence;+ const arousal = m && Number.isFinite(m.arousal) ? Math.max(0, Math.min(1, m.arousal)) : BASELINE.arousal;+ const sensitivity = clampSensitivity(m ? m.sensitivity : undefined);+ const label = (m && typeof m.label === 'string' && m.label) || moodLabel(valence, arousal).key;+ return { valence, arousal, sensitivity, label, updated_at: (m && m.updated_at) || null };+}++// Merge a new mood snapshot into meta without disturbing any other meta keys.+async function persistSnapshot(id, snapshot) {+ await sql`+ UPDATE agent_identities+ SET meta = jsonb_set(+ coalesce(meta, '{}'::jsonb),+ '{mood}',+ ${JSON.stringify(snapshot)}::jsonb,+ true+ ),+ updated_at = now()+ WHERE id = ${id}+ `;+}++export const handleMood = wrap(async (req, res, id, action) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const [agent] = await sql`+ SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const snapshot = readSnapshot(agent.meta);++ // ── GET — current mood + recent history ──────────────────────────────────+ if (req.method === 'GET' && !action) {+ const history = await sql`+ SELECT id, valence, arousal, label, source, source_label, source_memory_id, created_at+ FROM agent_mood_history+ WHERE agent_id = ${id}+ ORDER BY created_at DESC+ LIMIT ${HISTORY_LIMIT}+ `;+ return json(res, 200, { mood: snapshot, history });+ }++ // ── POST /sensitivity — the stoic↔expressive setting (no signal) ─────────+ if (req.method === 'POST' && action === 'sensitivity') {+ const body = parse(sensitivityBody, await readJson(req));+ const next = {+ valence: snapshot.valence,+ arousal: snapshot.arousal,+ label: snapshot.label,+ sensitivity: clampSensitivity(body.sensitivity),+ updated_at: new Date().toISOString(),+ };+ await persistSnapshot(id, next);+ return json(res, 200, { mood: next });+ }++ // ── POST — persist a mood point produced by a real signal ────────────────+ if (req.method === 'POST' && !action) {+ const p = parse(pointBody, await readJson(req));++ // A mood change must cite a real signal. Reject anything that isn't a+ // known catalogue signal or a namespaced custom one (producer:detail).+ if (!SIGNALS[p.source] && !/^[a-z]+:[a-z0-9_-]+$/i.test(p.source)) {+ return error(res, 400, 'invalid_signal', 'mood changes require a real signal source');+ }++ const label = p.label || moodLabel(p.valence, p.arousal).key;+ const sensitivity = p.sensitivity !== undefined ? clampSensitivity(p.sensitivity) : snapshot.sensitivity;+ const next = {+ valence: p.valence,+ arousal: p.arousal,+ label,+ sensitivity,+ updated_at: new Date().toISOString(),+ };++ const results = await sql.transaction([+ sql`+ UPDATE agent_identities+ SET meta = jsonb_set(coalesce(meta, '{}'::jsonb), '{mood}', ${JSON.stringify(next)}::jsonb, true),+ updated_at = now()+ WHERE id = ${id}+ `,+ sql`+ INSERT INTO agent_mood_history+ (agent_id, valence, arousal, label, source, source_label, source_memory_id, metadata)+ VALUES (+ ${id}, ${p.valence}, ${p.arousal}, ${label}, ${p.source},+ ${p.source_label || SIGNALS[p.source]?.label || null},+ ${p.source_memory_id || null},+ ${JSON.stringify(p.metadata || {})}::jsonb+ )+ RETURNING id, valence, arousal, label, source, source_label, source_memory_id, created_at+ `,+ ]);++ const inserted = results[results.length - 1];+ const entry = Array.isArray(inserted) ? inserted[0] : inserted;+ return json(res, 200, { mood: next, entry });+ }++ return error(res, 404, 'not_found', 'unknown mood action');+});++export default handleMood;diff --git a/api/cron/recompute-reputation.js b/api/cron/recompute-reputation.jsnew file mode 100644index 000000000..d8946ec79--- /dev/null+++ b/api/cron/recompute-reputation.js@@ -0,0 +1,61 @@+// @ts-check+// GET/POST /api/cron/recompute-reputation — refresh persisted agent reputation.+//+// The per-agent endpoint computes a score live and caches it in Redis for a few+// minutes; that's great for a viewed agent but ephemeral. This cron keeps a+// DURABLE score for every agent with a custodial wallet in agent_reputation_scores+// so the reputation-weighted leaderboard, the access/unlock checks, and "your+// score changed" all read a fresh, consistent number for the cost of one DB query.+//+// Each run recomputes the stalest batch (never-scored first, then old-version,+// then oldest) within the cron time budget, so the whole population rolls over+// continuously without any single run going long. Bounded so a large agent+// population never blows the function timeout.+//+// Standalone (not [name].js) so the import graph stays minimal.++import { json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { listStaleAgents, recomputeAgents } from '../_lib/trust/reputation-store.js';++// How many agents to recompute per tick. Each is a handful of indexed DB reads+// plus (for full mode) one cached price + light RPC; 40 fits comfortably in the+// cron budget and, at a 10-minute cadence, rolls a few thousand agents per hour.+const BATCH = 40;++// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes+// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time.+function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ json(res, 503, { ok: false, reason: 'CRON_SECRET unset' });+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ const header = req.headers['x-cron-secret'] || '';+ if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;+ json(res, 401, { ok: false, error: 'invalid cron secret' });+ return false;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const started = Date.now();+ try {+ const ids = await listStaleAgents(BATCH);+ if (!ids.length) {+ return json(res, 200, { ok: true, scored: 0, failed: 0, reason: 'no agents to score' });+ }+ const { scored, failed } = await recomputeAgents(ids);+ console.log(`[recompute-reputation] scored ${scored}/${ids.length} (failed ${failed}) in ${Date.now() - started}ms`);+ return json(res, 200, { ok: true, scored, failed, batch: ids.length, elapsed_ms: Date.now() - started });+ } catch (err) {+ // Never throw: a failed run leaves the prior stored scores intact.+ console.error('[recompute-reputation] failed:', err?.message || err);+ return json(res, 200, { ok: false, error: err?.message || String(err) });+ }+});diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 3da5db540..e714aef9d 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -434,6 +434,12 @@ async function guardedFetch(rawUrl, { method = 'GET', headers = {}, body } = {})}}+// Hostname of a URL (or null) — used as the scoped-capability holder ref / target+// host for x402 payments, so an owner can leash an integration to specific services.+function hostOf(u) {+ try { return new URL(String(u)).hostname || null; } catch { return null; }+}+function safeJsonParse(text) {if (typeof text !== 'string' || !text) return null;try {@@ -587,6 +593,11 @@ async function runExternalFlow({ url, method, body, emit, buyer, spendGuard, serdestination: accept.payTo,network: 'mainnet',asset: 'USDC',+ // Scoped session keys: the service URL is the capability target (a+ // service-scoped grant matches on its host), and the host is the holder+ // ref so a per-integration capability resolves preferentially.+ target: resource.url || url,+ capabilityHolderRef: hostOf(resource.url || url),rowMeta: { url, service: serviceLabel || resource.serviceName || null, resource: resource.url },});spendReservationId = reservation.reservationId;@@ -742,6 +753,9 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl, spdestination: accept.payTo,network: spendGuard.network || 'mainnet',asset: 'USDC',+ // Scoped session keys: the resolved MCP resource is the capability target.+ target: resourceUrl,+ capabilityHolderRef: hostOf(resourceUrl),rowMeta: { tool },});spendReservationId = reservation.reservationId;diff --git a/data/changelog.json b/data/changelog.jsonindex 3ebdf022d..0ca122b97 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,22 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-23",+ "title": "Every agent wallet now has a living trading card you can share",+ "summary": "Each agent's wallet is now a collectible, screenshot-worthy trading card — its avatar, its glowing vanity address, its live net worth, holdings count, realized P&L, reputation tier, and the $THREE-holder mark, with a one-tap tip, fork, and share. The card's 'finish' is earned, not decorative: it steps up from Common to Mythic only as the wallet's real wealth and on-chain reputation tier rise, so a dormant new wallet reads as matte and a luminous, elite one shimmers. Everything on it is real, public-safe data pulled from the same chain reads the wallet uses everywhere else — a $0 balance honestly shows $0, owner-only details never appear, and a private agent renders no card at all. Best of all, it travels: paste an agent link into X, Telegram, or Discord and it now unfurls as that exact card, generated live from real data, so every share is a billboard with a fork-to-own hook. The Share panel even previews the card before you post it.",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-23",+ "title": "The Mind Palace: walk through your agent's memory in 3D",+ "summary": "Your agent's memory is no longer an invisible database — it's a place you can explore. Open the new Mind Palace from your agent's editor or at /agent/<id>/mind and every memory becomes a tangible object orbiting your live avatar: the more a belief matters to your agent (its salience), the larger it glows and the closer it sits to the centre. Memories cluster by type into colour-coded constellations — what you've told it, the guidance you've given, your projects, and reference knowledge — with glowing threads drawn between memories that share tags, so you can literally see how your agent connects ideas. It's hands-on: drag a memory to the centre to pin it as a core belief, or flick it into the Forget well to let it go (with one-click undo — forgetting is always reversible). Search and filter instantly, click any memory to read its full content, see where it came from, and walk its associations to answer 'why does my agent believe this?'. Open it during a conversation and you'll watch memories pulse the moment your agent recalls them, and new memories bloom into being as they form. There's a timeline scrubber to replay how the mind grew over time, a full 2D view and keyboard navigation for any device, and it respects reduced-motion and the avatar performance budget throughout. Everything you do here writes straight to your agent's real memory.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","title": "KOL leaderboard is now live: real top-trader rankings, no static snapshot",diff --git a/prompts/living-wallet/04-wallet-trading-card-og.md b/prompts/living-wallet/04-wallet-trading-card-og.mddeleted file mode 100644index 39c471193..000000000--- a/prompts/living-wallet/04-wallet-trading-card-og.md+++ /dev/null@@ -1,86 +0,0 @@-# Task 04 — Wallet Trading Card + dynamic OG image--> Read [00-README-orchestration.md](./00-README-orchestration.md) in full first-> (ownership model, $THREE law, real APIs, design system, run loop, worktree rules).--## Mission (one line)--Give every agent wallet a **living, screenshot-worthy trading card** — identity,-vanity address, live P&L, holdings, reputation — and a **dynamic OG image** so it-spreads itself across social.--## Why this is gamechanging--Identity that travels is growth. A beautiful, Pokémon-card-grade artifact for an-agent's wallet — its avatar, its glowing vanity "license plate," its real P&L and-holdings, its reputation tier — is the thing people *want* to post. Each post is a-billboard with a fork-to-own CTA. No wallet has a shareable identity object; ours is-the avatar itself. The screenshot moment is the product.--## What you are building--1. **The card component** (`src/shared/wallet-card.js` or under the consolidated- shared wallet module) — a self-contained, real-data card rendering: the 3D-or-- portrait avatar (reuse Task 01's identity layer), agent name, vanity-highlighted- address, a live balance/holdings summary, real P&L (where derivable from custody/- trade history), reputation tier (Task 05, degrade gracefully if not landed yet),- $THREE-holder mark, and a fork/tip CTA. Rarity/finish styling scales with the real- wealth/reputation tier — tasteful, not casino.-2. **A dynamic OG endpoint** (`api/og/agent/[id].js` or similar, using the project's- existing image/OG approach — grep first) that renders the card to an image from- **real data** for link unfurls (X/Telegram/Discord). Cache sensibly; never bake in- stale or fake numbers.-3. **Share affordances** — a "Share card" action on every agent profile/hub that- copies the canonical URL (with correct OG tags) and offers one-tap share. Owner and- visitor both can share; the card respects viewer role for any sensitive field- (never expose owner-only data like custody specifics or limits — public card shows- public holdings/identity only).--## Real data & APIs--- Identity/holdings/balance: the public reads (`/api/agents/:id`,- `/solana`, `/solana/holdings`). P&L: derive from real trade/custody history- (`/solana/trade-history`, `/solana/custody`) — owner-rich, public-card uses only- public-safe aggregates. Reputation: `/api/agents/:id/reputation` + Task 05.-- Avatar art: the real GLB/thumbnail the platform already serves (R2 thumbnail keys,- model-viewer poster). OG image must use a real rendered/portrait frame, not a- placeholder.-- $THREE mark from the CA in `00-README`.--## UX spec--- **States**: loading (skeleton card), empty wallet (a clean "new agent" card that- still looks good and invites funding/forking — never broken), populated, error- (fall back to a minimal valid card, never a broken unfurl), overflow (truncate long- names/addresses gracefully).-- **Viewer roles**: public card shows public identity + public holdings + tip/fork;- owner sees an extra "share / customize what's shown" affordance; logged-out gets the- public card + connect-on-action. No owner-only datum ever appears on a public card.-- **Microinteractions**: hover tilt/shine on the card (reduced-motion: static),- copy-link confirmation, the vanity prefix/suffix in the emphasized accent.-- **Accessibility**: the card is real semantic content with alt text for the OG image;- fully keyboard-shareable; the OG endpoint sets proper meta tags server-side.-- **Performance**: OG generation cached + cheap; the on-page card lazy-loads heavy 3D- and shows the portrait first.--## Edge cases--No wallet / zero balance (still a valid, attractive card) · very long name/vanity ·-no reputation yet · OG cache staleness vs. freshness · social crawler with no JS-(server-rendered meta + image required) · private/unlisted agent (respect visibility —-no card for what shouldn't be public) · RPC failure (card renders identity, balance-shows "—", never fake).--## Definition of done--Meets the README DoD, plus: pasting an agent URL into X/Telegram/Discord unfurls a-real, correct, attractive card image generated from real data; the on-page card-matches; viewer roles are respected; private agents don't leak; nothing is faked or-stubbed; the OG endpoint re-checks visibility server-side.--## Then: improve, then delete this file--Push it: seasonal/holo finishes tied to real reputation milestones, a "card evolved"-moment when the agent crosses a tier, or wiring shares into Task 08's feed. Update-`data/changelog.json`. **Then delete this prompt file.**-</content>diff --git a/prompts/nvidia/0.md b/prompts/nvidia/0.mddeleted file mode 100644index b852f9f41..000000000--- a/prompts/nvidia/0.md+++ /dev/null@@ -1,142 +0,0 @@-# Phase 4 — Open Inference Network (Index — DO NOT DELETE)--> This file is the index and shared context for **Phase 4** of the three.ws-> roadmap: the **decentralized GPU layer**. It is NOT a task. Do not delete it.-> Every numbered prompt in this folder is a self-contained task for one fresh-> agent chat. When an agent finishes a numbered task (and its self-review pass),-> it deletes **only its own** numbered prompt file — never this README, never-> another agent's.--Roadmap source of truth: `README.md` → **"Phase 4 — Open Inference Network"**-and `content/whats-next/later/12-decentralized-gpu-inference.md`.-------## The vision--> **Goal (README):** decouple agent inference from any single provider. Anyone-> can run a node; agents pay nodes onchain for compute.--Phases 0–3 built the avatar, the agent, and the onchain identity. But today every-GPU job — face → avatar reconstruction, text → 3D mesh, retexture, talking-avatar-video, LLM inference — runs on **infrastructure we operate** (GCP Cloud Run L4-services, Replicate, Anthropic, a single Livepeer leg). That is the last-centralized dependency in an otherwise ownable stack.--**Phase 4 turns that compute into an open mesh.** Independent operators run a node,-register it onchain, advertise which models their GPU can serve, and get paid per-job in USDC/$THREE with a cryptographic receipt. three.ws's own jobs route to the-mesh first and fall back to the centralized path only when the mesh can't meet the-SLA. Over time, the platform operates *less* of its own GPU fleet, not more.--The loop we are wiring:--> an agent needs compute → the router picks the best healthy node advertising that-> model → the node runs the job and returns a **signed result** → the job settles-> onchain (pay-per-job, cryptographic receipt) → the operator earns → the operator's-> reputation rises → it wins more jobs → repeat.--North star for this phase (from the README verification bar): **≥50% of production-GPU traffic served by independent node operators, at latency parity with the-centralized path.** Every result is signed and verifiable; every payout is onchain-and provable. Decentralized does not mean "best effort" — it means *more* provable,-not less.--This is real infrastructure, not a demo. No simulated nodes, no fake roster, no-mock receipts. A node operator can `docker run` the client on a real GPU box today-and earn real money serving real three.ws jobs.-------## What already exists (build ON this — do not rebuild it)--**The compute that gets decentralized — the existing GPU worker fleet:**-- `workers/` — the Cloud Run services that do the heavy work today. Each exposes the- same HTTP contract: `POST /<verb>` → `202 { task_id, status:"queued" }`,- `GET /tasks/:id` → `{ status, result_url|result_gcs_url?, error? }`, `GET /health`,- bearer-auth via a shared secret. Read `workers/README.md` — it is the map.- - Mesh generation (GPU L4): `model-hunyuan3d`, `model-trellis`, `model-triposr`,- `model-triposg` (image + scribble), all single-image → textured/geometry mesh.- - Avatar: `avatar-pipeline-controller` (CPU orchestrator, `POST /reconstruct`),- `avatar-reconstruction` (InstantMesh), `unirig` (rig/skin/blendshapes).- - Edit/finish: `texture`, `stylize`, `rembg`, `segment`, `remesh`, `model-text2motion`.- - Video: `longcat` (talking-avatar MP4).-- `api/_providers/gcp.js` — **the adapter to copy.** It already abstracts every- worker behind one interface: `submit(request) → { extJobId, eta }`,- `status(extJobId) → { status, resultGlbUrl?, resultImageUrl?, error? }`. The- `extJobId` is a base64url JSON envelope carrying the service discriminator + the- upstream task id. The decentralized provider implements the **same contract** so- callers don't care where the GPU lives.-- `api/forge.js` + `api/_lib/forge-tiers.js` — how a mesh job is dispatched and- which engine/tier it routes to. The entry point the router plugs into.-- `api/inference/livepeer.js` — the **early Phase 4 experiment already in the repo**:- routes LLM inference to Livepeer Studio / the public dream-gateway and compares it- side-by-side with Claude. The federation prompt (08) generalizes this.--**Payments — the rails per-job settlement rides on:**-- `api/_lib/x402-paid-endpoint.js` — `paidEndpoint(spec)` factory: the 8-step paid- flow (CORS → method → access → SIWX → 402 challenge → verify → handler → settle).-- `api/_lib/x402-spec.js` — v2 protocol, signing, settlement; `exact` + `upto` schemes.-- `api/x402/*` — 40+ live paid endpoints to match in style.-- Settlement backends already wired: Base via Coinbase CDP, BSC direct, Solana direct.-- `api/_lib/credits.js`, `api/_lib/pricing/catalog.js`, `api/_lib/three-tier.js` —- pricing/quota/$THREE-gating helpers.--**Schema & infra:**-- `api/_lib/schema.sql` + `api/_lib/migrations/` — add new tables here (timestamped).-- `api/_lib/db.js` (`sql`), `api/_lib/http.js` (`cors`, `wrap`, `method`, `json`,- `error`, `rateLimited`), `api/_lib/validate.js`, `api/_lib/rate-limit.js`.-- `vercel.json` — register any new route or cron.-- Onchain identity already exists (ERC-8004 on EVM, Metaplex Core on Solana) and the- reputation/attestation patterns from Phase 3 — reuse them for node registration.-------## The prompts--| # | Prompt | Builds on |-|----|-----------------------------------------------------|------------------------------------------------------|-| 01 | Node registry, protocol & schema (the spine) | onchain identity, `schema.sql`, `gcp.js` contract |-| 02 | Node operator client (Docker GPU node) | `workers/*` model code, the protocol from 01 |-| 03 | Decentralized provider adapter + router | `api/_providers/gcp.js`, node registry |-| 04 | Onchain settlement & node payouts (x402 receipts) | `paidEndpoint`, `x402-spec.js`, receipt schema |-| 05 | Route the real workloads onto the mesh | `api/forge.js`, avatar pipeline, the router from 03 |-| 06 | Node operator console + live network map | node registry, settlement ledger, `pages/*` |-| 07 | Reputation, SLA & result verification | Phase-3 attestation, the receipts from 04 |-| 08 | Federation + the open SDK | `api/inference/livepeer.js`, published-SDK pattern |-| 09 | Integration QA & polish (run last) | all of the above |--**Run 01 first** — it defines the protocol, schema, and onchain registry every other-prompt depends on. 02–04 can run in parallel chats once 01 lands (the node client, the-router, and settlement each consume the protocol). 05–08 follow once 03/04 are merged.-Run **09 last**, after everything else is in.-------## Global operating rules (every prompt repeats these — non-negotiable)--- Read `CLAUDE.md` and `STRUCTURE.md` first; **CLAUDE.md overrides defaults.**-- **No mocks / fake data / placeholders / TODOs / stubs.** Real nodes, real GPU jobs,- real signed receipts, real onchain settlement. A simulated node or a hardcoded- roster is a failed task. If a real second machine isn't available to test against,- run the node client locally against a CPU-capable job and say so explicitly — never- fabricate a node.-- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).- Node payouts and pricing are denominated in USDC and/or $THREE only. Never reference- any other token anywhere — code, copy, fixtures, receipts, dashboards, SDK docs. The- two runtime-data-only exceptions in CLAUDE.md still apply.-- **Same contract as `gcp.js`.** Anything that produces or consumes GPU jobs speaks- the existing `submit`/`status` envelope and the worker `task_id` shape. Don't fork- the job model — extend it.-- **Every result is signed; every payout is provable.** No job result is trusted- without a node signature; no settlement happens without a verifiable receipt.-- **Every state is designed** — loading (skeletons), empty (tells the operator/user- what to do next), error (actionable + recoverable), populated, overflow. Mobile-first.-- **No errors without solutions.** The mesh degrades gracefully: a dead/slow node never- fails a user job — the router falls back. Ship the fallback, don't just log the error.-- **Changelog:** every user- or operator-visible change gets a `data/changelog.json`- entry, then `npm run build:pages`. Internal-only plumbing does not.-- **Tests:** add/extend tests under `tests/`; existing tests still pass (`npm test`).-- Concurrent agents share this worktree — **stage explicit paths only** (never- `git add -A`/`.`); re-check `git status` and `git diff --staged` before committing.- Never commit esbuild-bundled `api/*.js` (check `head -1` for `__defProp`).diff --git a/prompts/nvidia/1.md b/prompts/nvidia/1.mddeleted file mode 100644index ea72842b0..000000000--- a/prompts/nvidia/1.md+++ /dev/null@@ -1,88 +0,0 @@-# Phase 4 · 01 — Node Registry, Protocol & Schema (the spine)--You are a senior infrastructure engineer on **three.ws**. Read `CLAUDE.md` and-`STRUCTURE.md` first — CLAUDE.md overrides defaults. This is the **foundation** of-the Open Inference Network: the protocol, the database schema, and the onchain-registry that prompts 02–09 all build on. Build it so completely that the node-client, the router, settlement, and the operator console can each plug in without-redefining anything.--## What you're building--The shared spine of the decentralized GPU mesh:--1. **The protocol (a versioned spec doc + shared JS module).** Define, precisely:- - **Capability advertisement** — what a node tells the network it can serve:- `{ node_id, operator_addr, models:[{ key, hardware, max_batch }], gpu:{ name, vram_gb }, regions, version, max_concurrency }`. Model keys reuse the existing worker- discriminators (`hunyuan3d`, `trellis`, `triposr`, `triposg`, `texture`, `rembg`,- `segment`, `remesh`, `text2motion`, `longcat`, `unirig`, and an `llm:<model>` form- for the inference leg). Don't invent a parallel taxonomy — mirror `workers/README.md`- and `api/_providers/gcp.js`.- - **Job manifest** — what the network hands a node: `{ job_id, model_key, inputs,- params, max_price_atomics, deadline_ms, nonce }`, matching the existing worker- request bodies (`POST /infer`, `/reconstruct`, etc.).- - **Signed response** — what a node returns: the result envelope plus a node- signature over `keccak256(job_id || model_key || result_hash || node_id || nonce)`.- Define the canonical serialization once so the node client (02), the router (03),- and verification (07) all hash identically. Support both an EVM (secp256k1) and a- Solana (ed25519) node key so operators on either chain can serve.- - **Receipt** — the settlement artifact: `{ job_id, node_id, payer, model_key,- price_atomics, result_hash, node_sig, ts }`, EIP-712 / JWS shaped to match- `api/_lib/x402-spec.js` so prompt 04 can settle it directly.- Write the spec as `docs/open-inference-protocol.md` AND a single importable module- `api/_lib/oin/protocol.js` (canonical hashing, serialization, sig verify helpers)- so code and docs can never drift.--2. **The database schema.** New timestamped migration in `api/_lib/migrations/` (and- mirror into `api/_lib/schema.sql`):- - `oin_nodes` — registered nodes: id, operator address (+ chain), payout address,- advertised capabilities (jsonb), endpoint URL (or "pull" flag for poll-based- nodes), status, version, registered/last-seen timestamps, onchain registration ref.- - `oin_jobs` — every dispatched job: id, model_key, requester (agent/user), assigned- node_id, status (`pending|claimed|running|done|failed|reassigned`), price_atomics,- result_hash, node_sig, latency_ms, fallback_used (bool), created/settled timestamps.- - `oin_node_heartbeats` — last-seen, load, healthy-models, latency samples (feeds the- router in 03 and reputation in 07).- Index for the router's hot path: "healthy nodes advertising model X, ranked." Every- table has the columns reputation (07) and settlement (04) will need — design for them- now so those prompts don't re-migrate.--3. **The onchain registry.** A node registers its identity onchain so the roster is- provable, not a database we could fake. Reuse the **existing** identity rails — do- NOT write a new bespoke chain integration from scratch:- - EVM: extend the ERC-8004 / reputation-registry pattern from Phase 3 (`contracts/`)- with a `NodeRegistry` entry (operator → node pubkey, payout addr, capability hash,- stake placeholder for 07). Solana: a Metaplex Core asset or PDA mirroring it.- - On-chain stores the *commitment* (capability hash, payout address, operator);- the full capability JSON lives off-chain in `oin_nodes`, verified against the hash.- If deploying a new contract is out of scope for one chat, ship the contract source +- ABI + a register/read helper in `api/_lib/oin/registry.js` that reads/writes the real- chain, and document the deploy step. Do not stub the chain call.--4. **Registration & roster APIs:**- - `POST /api/oin/register` — a node (or the operator console in 06) registers:- validates the capability advert, verifies the onchain registration ref, writes- `oin_nodes`. Idempotent on node_id.- - `POST /api/oin/heartbeat` — node liveness + load + healthy-model report.- - `GET /api/oin/nodes` — public roster (the network's "who's online"): healthy nodes,- models served, region, reputation placeholder, last seen. Powers 06's network map.- - `GET /api/oin/nodes/:id` — single node detail.- Auth: a node authenticates with its node key (signature challenge), not a shared- secret — the whole point is no central trust. Use `api/_lib/http.js` helpers and- `api/_lib/rate-limit.js`.--## Definition of done--- `docs/open-inference-protocol.md` is precise enough that prompt 02 implements a node- against it with zero further questions; `api/_lib/oin/protocol.js` is its executable form.-- Migration applies cleanly; `schema.sql` matches; tables indexed for the router's query.-- A node can register against the **real chain** and appear in `GET /api/oin/nodes`.-- Signature verify round-trips for both EVM and Solana node keys (unit tests in- `tests/` covering the canonical hash, both key types, and a tampered-result rejection).-- Registration/heartbeat/roster endpoints handle every state; bad adverts rejected with- actionable errors; rate-limited.-- `data/changelog.json` entry (developer/infra-facing: "Open Inference Network — node- registry & protocol"), `npm run build:pages`, `npm test` green.-- `git diff` reviewed; explicit-path staging; no bundled `api/*.js`.--Build the spine right. Everything else in Phase 4 leans on it.diff --git a/prompts/nvidia/2.md b/prompts/nvidia/2.mddeleted file mode 100644index 3d2007c72..000000000--- a/prompts/nvidia/2.md+++ /dev/null@@ -1,81 +0,0 @@-# Phase 4 · 02 — Node Operator Client (the Docker GPU node)--You are a senior systems engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. Read `docs/open-inference-protocol.md` and-`api/_lib/oin/protocol.js` from prompt 01 — you implement against that spec exactly.--## What you're building--**The software an independent operator runs on their own GPU box to earn money serving-three.ws jobs.** This is the heart of decentralization: anyone with an A100/H100/L4 can-`docker run` this and become part of the mesh. It must work on a real machine, today.--Create a new top-level worker package — `workers/oin-node/` — that follows the existing-`workers/` conventions (Dockerfile + cloudbuild-style build, FastAPI or a lean Python-service, `GET /health`). It reuses the **existing model code already in this repo** —-do not rewrite inference. The node is an orchestrator wrapping `workers/model-*`,-`workers/texture`, `workers/rembg`, etc.--### The node lifecycle--1. **Boot & capability detection.** Detect GPU (name, VRAM via `nvidia-smi`/`torch`),- decide which model keys it can serve given VRAM (a 24 GB L4 ≠ an 80 GB H100 — gate- the heavy mesh/video models accordingly). Generate or load the node keypair (EVM- secp256k1 and/or Solana ed25519, per the protocol).-2. **Onchain registration.** Register via `api/_lib/oin/registry.js` (or call- `POST /api/oin/register` with the onchain ref). Real chain write — funded by the- operator. Document the one-time `oin-node register` step in the README.-3. **Model loading.** Lazy-load each advertised model's weights on first job (reuse the- loaders from the corresponding `workers/model-*` service — import or vendor them,- don't fork the inference logic). Report `healthy_models` only for weights that- actually loaded. Stage weights with the existing `workers/deploy/stage-weights.sh`- pattern.-4. **Job loop.** Two modes, both from the protocol — implement at least **pull**:- - **Pull:** poll `GET /api/oin/jobs/claim?node=<id>` (signed request) for a job- matching its healthy models, atomically claim it, run it, return the result.- - **Push:** expose an authenticated endpoint the router can `POST` a manifest to.- Respect `deadline_ms` and `max_price_atomics`; reject jobs it can't meet in time- rather than starting and timing out.-5. **Execute & sign.** Run the job through the matching model code, hash the result- (upload the artifact to the operator's configured storage — R2/GCS/S3 — or stream it- back per the protocol), and **sign the response** with the node key over the canonical- hash from `protocol.js`. Emit the receipt.-6. **Heartbeat.** Periodic `POST /api/oin/heartbeat` with load, healthy models, recent- latency. Back off and re-register on network errors — never crash-loop silently.--### Operator ergonomics (this is a product, treat it like one)--- A clean `README.md`: hardware requirements per model tier, `docker run` one-liner,- env vars (node key, payout address, chain RPC, storage creds), the register command,- and a realistic earnings/cost note.-- A `oin-node doctor` / startup self-check that prints exactly what's wrong if GPU,- weights, keys, RPC, or storage are misconfigured — actionable, not a stack trace.-- Structured logs: jobs claimed, served, signed, paid; errors with cause + fix.-- Graceful shutdown: finish in-flight jobs, deregister/mark-offline, don't strand a payer.--## Hard requirements--- **No simulated inference.** The node runs the real models. If you can only test a- CPU-capable path locally (e.g. `rembg`/`segment`/`remesh`), do that and say so — never- fake a GPU result.-- **No shared central secret as the trust root** — the node authenticates with its own- key. That's the protocol.-- Signature and hashing match `api/_lib/oin/protocol.js` byte-for-byte (cross-test- against the JS verifier from prompt 01).--## Definition of done--- `workers/oin-node/` builds into a Docker image; `GET /health` reports GPU + healthy- models; boots on a real GPU host.-- A real node registers onchain, appears in `GET /api/oin/nodes`, claims a job, runs it,- returns a **signed** result the prompt-01 verifier accepts.-- Tampering with the result fails verification; an over-deadline job is declined cleanly.-- README lets an operator go from bare box → earning node without asking a human.-- A test (in `workers/oin-node/` and/or `tests/`) covers capability detection, the claim- loop state machine, and the sign/verify round-trip.-- `data/changelog.json` entry ("Run a GPU node on the Open Inference Network — node- client released"), `npm run build:pages`. `npm test` green.-- Explicit-path staging; reviewed `git diff`.--This is the on-ramp for every node operator. If it isn't dead-simple to run and-impossible to spoof, it isn't done.diff --git a/prompts/nvidia/3.md b/prompts/nvidia/3.mddeleted file mode 100644index 6b0b5aba6..000000000--- a/prompts/nvidia/3.md+++ /dev/null@@ -1,84 +0,0 @@-# Phase 4 · 03 — Decentralized Provider Adapter + Router--You are a senior backend engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. Read `api/_providers/gcp.js` closely — you are-writing its decentralized sibling, with the **identical contract**. Read the protocol +-roster APIs from prompt 01.--## What you're building--The piece that lets three.ws's own code send a GPU job to the mesh **without caring that-the GPU is decentralized**, with a router that picks the right node and falls back to the-centralized path the instant the mesh can't deliver. This is what makes the network-usable in production rather than a science project.--### 1. The provider adapter — `api/_providers/decentralized.js`--Implement the exact contract `gcp.js` exposes so it's a drop-in alongside it:--```-submit(request) → { extJobId, eta }-status(extJobId) → { status, resultGlbUrl?, resultImageUrl?, resultUrl?, error?, node_id?, signed? }-```--- `submit` selects a node (via the router below), writes an `oin_jobs` row, dispatches- the manifest (push to the node's endpoint, or enqueue for pull-claim), returns the- base64url `extJobId` envelope (carry `job_id` + `node_id` + `model_key`, same shape as- `gcp.js`).-- `status` reads job state, **verifies the node signature** on completion via- `api/_lib/oin/protocol.js` before reporting `done` — an unsigned or bad-sig result is- treated as a failure and reassigned, never returned to the caller.--### 2. The router — `api/_lib/oin/router.js`--Given `(model_key, params, deadline, max_price)`, choose the best node:--- **Eligibility:** healthy (recent heartbeat), advertises the model with enough VRAM,- region/latency acceptable, has spare concurrency, price ≤ max.-- **Ranking:** weighted score over recent latency, success rate, and reputation- (consume the reputation signal from prompt 07 when present; degrade to latency +- success-rate before it lands). Add light load-spreading so one fast node isn't- hammered — don't always pick rank #1.-- **Reassignment:** if the chosen node misses the deadline, errors, or returns a bad- signature, transparently reassign to the next node (bounded retries). Record- `fallback_used` / reassignment on the job row.--### 3. The fallback chain (non-negotiable — "no errors without solutions")--The mesh must never make a user job worse than it is today. When **no** eligible node-exists, or the bounded reassignment budget is exhausted, the router falls back to the-**existing centralized provider** (`gcp.js` for GPU/3D jobs, the centralized LLM path-for inference) for that job. The user gets their result; the job row records that the-mesh couldn't serve it (this is the data prompt 09 and the network metrics need to track-the "≥50% served by independent nodes" north star).--### 4. Routing policy + flag--- A per-model routing policy (`api/_lib/oin/policy.js` or a config table): `off` |- `shadow` (run on mesh, but serve the centralized result — for latency/quality A/B) |- `prefer` (mesh first, centralized fallback) | `only`. Default new models to `shadow`- so the mesh proves itself before taking user-facing traffic.-- An env/flag gate so the whole network can be toggled per environment without a deploy.--## Hard requirements--- **Same contract as `gcp.js`** — callers (`api/forge.js`, the avatar pipeline) must not- need special-casing beyond choosing the provider. Prompt 05 wires those callers.-- **No node is trusted** — every completion is signature-verified before it's served.-- **No mock roster** — the router reads real `oin_nodes` / heartbeats. With zero nodes- registered, it falls back cleanly (and that path is tested).-- Real selection logic, not round-robin-on-a-hardcoded-list.--## Definition of done--- `api/_providers/decentralized.js` passes the same shape-contract tests as `gcp.js`- (add a shared contract test in `tests/` exercising both providers).-- Router unit tests: eligibility filtering, ranking, reassignment on- miss/error/bad-sig, and **fallback to centralized when no node qualifies**.-- A job dispatched with `policy: prefer` runs on a real registered node end-to-end and- returns a verified result; with no nodes, the same call still succeeds via fallback.-- `shadow` mode records mesh-vs-centralized latency/quality without affecting the user.-- `data/changelog.json` entry (infra), `npm run build:pages`, `npm test` green.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--If a node dies mid-job and the user never notices, you built it right.diff --git a/prompts/nvidia/4.md b/prompts/nvidia/4.mddeleted file mode 100644index f91164ad5..000000000--- a/prompts/nvidia/4.md+++ /dev/null@@ -1,83 +0,0 @@-# Phase 4 · 04 — Onchain Settlement & Node Payouts (x402 receipts)--You are a senior payments engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. Read `api/_lib/x402-paid-endpoint.js`,-`api/_lib/x402-spec.js`, a few `api/x402/*` endpoints, and the receipt schema from-prompt 01. This is the money loop: **agents pay nodes onchain for compute, with a-cryptographic receipt for every job.**--## What you're building--The settlement layer that turns a signed job result into a provable onchain payout to-the node operator — pay-per-job (and pay-per-token for the LLM leg), denominated in-**USDC and/or $THREE only**. This is the README deliverable "onchain settlement for-inference jobs — pay-per-token with cryptographic receipts."--### 1. Per-job pricing — `api/_lib/oin/pricing.js`--A real pricing table keyed by `model_key` and hardware/quality tier, reusing-`api/_lib/pricing/catalog.js` conventions. GPU/3D jobs price per job (with a tier-multiplier: draft/standard/high, L4 vs H100). The LLM leg prices per token (input +-output), mirroring the `upto` metered scheme already in `x402-spec.js`. A node's-advertised price must be ≤ the catalog ceiling for the job to route to it (the router in-03 already enforces `max_price`); the operator keeps the bulk, the protocol takes a small-platform fee — make the split explicit and configurable, not magic numbers.--### 2. The settlement flow--When `decentralized.js` reports a verified `done`:--1. Assemble the **receipt** from the protocol schema (job_id, node_id, payer, model_key,- price, result_hash, node_sig, ts) and sign it EIP-712 / JWS via `x402-spec.js`.-2. Settle the payer → node payout onchain using the **existing** settlement backends —- Base via Coinbase CDP, BSC direct, Solana direct (`api/_lib/x402-*` already wires- these). The node's payout address comes from `oin_nodes`. Settle to the node's chain.-3. Persist the receipt + settlement tx ref on the `oin_jobs` row and in an- `oin_receipts` table (migration + `schema.sql`). Idempotent on `job_id` — a retried- settlement never double-pays (reuse the idempotency-key pattern from `api/x402/*`).-4. The platform fee accrues to the protocol treasury; the rest goes to the operator.--### 3. The paid entry point--For external agents calling the network directly (not just three.ws's own jobs), expose-`api/oin/infer.js` (or `api/x402/oin-compute.js`) built with `paidEndpoint(spec)`: the-caller pays the 402 challenge up front, the router dispatches, the node serves, the-result returns, and settlement to the node happens against the collected payment. This is-how an arbitrary agent buys decentralized compute with x402 — wire the full 8-step flow,-register it in the bazaar discovery catalog like the other `api/x402/*` endpoints, and-support both `exact` (fixed per-job) and `upto` (metered LLM) schemes.--### 4. Node earnings ledger--- `GET /api/oin/earnings?node=<id>` — a node's settled jobs, gross, fee, net, by day and- by model. Authenticated with the node key. Feeds the operator console (06).-- Reconciliation: a scheduled job (cron in `vercel.json`, idempotent like- `api/cron/rewards-distribute.js`) that catches any verified-but-unsettled job and- settles it — settlement must be eventually-consistent and self-healing, never a job- that silently never paid.--## Hard requirements--- **Real onchain settlement.** No mock facilitator, no fake tx hashes. Use the wired CDP- / BSC / Solana paths. If a chain's creds are absent locally, the code path is real and- you say which env it needs — you don't stub it.-- **Idempotent, no double-pay.** Prove it with a test that retries settlement.-- **USDC / $THREE only.** Pricing, receipts, ledgers reference no other token, ever.-- Every payout traces to a signed result and a signed receipt — no result, no money.--## Definition of done--- A verified job settles onchain to a real node payout address and writes a receipt +- tx ref; the receipt verifies against `x402-spec.js`.-- `api/oin/infer.js` is a working `paidEndpoint`: an external x402 caller pays, gets a- mesh-served result, and the node gets paid — end to end, in the bazaar catalog.-- Retried settlement does not double-pay (test). Reconciliation cron settles a stranded- verified job (test).-- Earnings endpoint returns real settled data with every state designed.-- Migration + `schema.sql` updated; `vercel.json` route + cron registered.-- `data/changelog.json` entry ("Get paid onchain for running a node — per-job settlement- live"), `npm run build:pages`, `npm test` green.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--A node operator who serves a job must be able to point at a block explorer and see their-money. That's the bar.diff --git a/prompts/nvidia/5.md b/prompts/nvidia/5.mddeleted file mode 100644index 42cd43313..000000000--- a/prompts/nvidia/5.md+++ /dev/null@@ -1,82 +0,0 @@-# Phase 4 · 05 — Route the Real Workloads onto the Mesh--You are a senior backend engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. This is where the network stops being-infrastructure and starts carrying **real production traffic**. Prompts 01–04 built the-spine, the node, the router, and settlement; now wire the platform's actual GPU jobs-through it — safely, behind policy, with the centralized path as a guaranteed fallback.--Read `api/forge.js`, `api/_lib/forge-tiers.js`, `api/_providers/gcp.js`, the avatar-pipeline (`workers/avatar-pipeline-controller`, the `reconstruct` mode in `gcp.js`),-`api/inference/livepeer.js`, and the router/policy from prompt 03.--## What you're building--The integration that routes existing workloads to the mesh per the routing policy, so-that — over time — the README north star is met: **≥50% of production GPU traffic served-by independent node operators.** You are not changing what these features do; you're-changing *where the GPU runs*, invisibly, with no regression.--### Wire these call sites (each behind its model's routing policy)--1. **Text/image → 3D mesh (`api/forge.js`).** The biggest GPU consumer. Where `forge`- today dispatches to `gcp.js` (`hunyuan3d`/`trellis`/`triposr`/`triposg`), let it- choose `decentralized.js` per `api/_lib/oin/policy.js`. `prefer` → mesh first, GCP- fallback. The forge tier (draft/standard/high) maps to the node hardware/price tier- from prompt 04. No change to the forge API contract or the client.--2. **Avatar reconstruction & rigging.** The `reconstruct` / `rerig` modes. These are- multi-step (mesh backend → UniRig); route the GPU-heavy sub-steps to the mesh where a- node advertises them, keep the CPU controller centralized. The README explicitly- calls out offloading "the heaviest step (multi-view face fitting) onto external GPU- nodes" — deliver that.--3. **Texture / stylize / rembg / segment / remesh / text2motion.** Same pattern via- their `gcp.js` modes. Start each at `shadow`, promote to `prefer` as nodes prove out.--4. **LLM inference (`api/inference/livepeer.js`).** Generalize the existing Livepeer- experiment: the inference router can send a completion to a mesh node advertising- `llm:<model>` (priced per-token via prompt 04's `upto` scheme), with the centralized- LLM path as fallback. Keep the side-by-side comparison demo working.--### Rollout safety (this is the whole job — do it right)--- **Default to `shadow` for every newly-wired model.** Shadow runs the job on the mesh- in parallel, serves the centralized result, and records mesh-vs-centralized latency,- success, and result-quality deltas. Only after the data looks good does an operator- flip the model to `prefer`. Never flip a model straight to `only`.-- **The user never regresses.** Every wired path keeps its centralized fallback. A mesh- miss/timeout/bad-sig is invisible to the user (the router handles it; you just pass the- policy through).-- **Per-model kill switch.** Any model can be reverted to `off` (centralized only) via- policy without a deploy.-- **Traffic accounting.** Record, per job, whether it was mesh-served or centralized, so- the network's "% served by independent nodes" is measurable — this feeds the operator- console (06) and QA (09).--## Hard requirements--- **No behavior change for the user** beyond (ideally) latency/cost — same outputs, same- API contracts, same client code.-- **No mock routing** — real policy table, real provider selection, real fallback.-- Shadow mode must not bill the user twice or settle two payouts for one user-facing- result — settle only the served result; a shadow run that isn't served either isn't- settled or is settled from a separate evaluation budget (be explicit which).--## Definition of done--- `forge`, avatar reconstruction, the edit workers, and LLM inference each route through- `decentralized.js` under policy, with GCP/centralized fallback intact.-- A real forge generation completes on a registered node (policy `prefer`) with identical- output quality to the centralized path; with nodes off, the same generation succeeds- centrally.-- Shadow mode records comparison metrics without affecting the user or double-billing.-- Per-model policy flip (`shadow`→`prefer`→`off`) takes effect with no deploy.-- Tests: each wired call site selects provider per policy and falls back correctly;- traffic-split accounting is recorded.-- `data/changelog.json` entry ("3D generation can now run on the decentralized GPU- mesh"), `npm run build:pages`, `npm test` green.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--When a forge job silently runs on someone else's H100 in another country and the user-just sees their avatar appear, Phase 4 is real.diff --git a/prompts/nvidia/6.md b/prompts/nvidia/6.mddeleted file mode 100644index c955f7589..000000000--- a/prompts/nvidia/6.md+++ /dev/null@@ -1,76 +0,0 @@-# Phase 4 · 06 — Node Operator Console + Live Network Map--You are a senior product engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. This is the **face** of the Open Inference-Network: where a person decides to run a node, registers it, and watches it earn — and-where anyone can see the mesh is real. Match the polish of the rest of the platform-(study `pages/leaderboard.html`, `pages/vaults.html`, the dashboard, and `DESIGN-TOKENS.md`).--Consume the registry/roster/heartbeat APIs (01), the earnings ledger (04), and the-traffic accounting (05). Frontend is vanilla JS modules + Vite, mobile-first.--## What you're building--### 1. "Become a node" onboarding — the operator funnel--A page (`pages/run-a-node.html` + its module) that turns a GPU owner into an operator:--- **The pitch:** what the network is, what hardware earns what, the `docker run`- one-liner from prompt 02. Real numbers from the pricing catalog (04), not invented ones.-- **Register flow:** connect wallet (the payout address), generate/paste the node key,- submit the capability advert, complete the onchain registration. Wire it to- `POST /api/oin/register` — real chain write, every state designed (connecting,- signing, pending confirmation, registered, error-with-fix).-- **Health check helper:** surface the node's `GET /health` + heartbeat status so an- operator immediately sees whether their box is actually serving.--### 2. The operator dashboard — "my node"--For a registered operator (authenticated by node key / wallet):--- **Live status:** online/offline, healthy models, current load, last heartbeat, version.-- **Earnings:** gross / fee / net over time, by model, by day (from `/api/oin/earnings`),- each settlement linking to its onchain tx and receipt. A "withdraw"/payout-address view.-- **Jobs served:** recent jobs, latency, success/fail, reputation trend (from 07 when- present). An operator should be able to debug *why* a job failed from here.-- **Reputation & SLA:** the node's standing and what improves it (latency, uptime,- result validity) — make the incentive legible.--### 3. The live network map — the shareable artifact--The piece worth screenshotting (see the visual in-`content/whats-next/later/12-decentralized-gpu-inference.md`): a public, real-time view-of the mesh.--- A globe / node graph of registered nodes by region (real data from `GET /api/oin/nodes`- — never a decorative fake), pulsing as jobs route. Total nodes, models served, jobs in- the last 24h, **% of traffic served by independent nodes** (the README north star,- live). Use Three.js/WebGL — this is a 3D-native platform; make it beautiful and- performant (lazy-load, `transform`/`will-change`, no jank).-- Degrade gracefully: with few/zero nodes online it still reads as a real, honest network- ("3 nodes online, be the 4th") — not an empty void and not a faked swarm.--### 4. Cross-link it--Surface "Run a node" from the dashboard / footer / docs nav. Link node profiles from the-network map. Wire the network-map stats into wherever the platform shows its-infrastructure story. The best platforms feel like everything is connected — connect this.--## Definition of done--- A real GPU owner can land on `run-a-node.html`, register a node onchain, and see it- appear on the live map and in their dashboard — no human help needed.-- Operator dashboard shows real status + real earnings with onchain links; every state- (loading skeletons, empty, error, populated, overflow) designed; works at 320/768/1440.-- Network map renders real roster data, animates job routing, shows the live independent-- traffic % , and is performant and shareable.-- Hover/active/focus states on every interactive element; semantic HTML; ARIA; keyboard- nav; visible focus rings; sufficient contrast.-- No console errors/warnings; network tab shows real API calls; exercised in a browser- (`npm run dev`).-- `data/changelog.json` entry ("Run a node and watch it earn — operator console + live- network map"), `npm run build:pages`. If it's a new page, the `data/pages.json` `added`- date feeds the changelog automatically — register it there. `npm test` green.-- Explicit-path staging; reviewed `git diff`.--Make someone want to plug in their GPU. That's the job.diff --git a/prompts/nvidia/7.md b/prompts/nvidia/7.mddeleted file mode 100644index ac27e440e..000000000--- a/prompts/nvidia/7.md+++ /dev/null@@ -1,86 +0,0 @@-# Phase 4 · 07 — Reputation, SLA & Result Verification (cryptoeconomic security)--You are a senior protocol engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. The mesh now serves real jobs and pays real money;-this prompt makes it **trustworthy without trusting any single node**. README deliverable:-"cryptoeconomic security model (slashing, validator set)." Reuse the Phase-3 onchain-attestation/reputation rails (`api/cron/trader-score-attest.js`, `contracts/`,-`ReputationRegistry`-style patterns) rather than inventing parallel machinery.--Consume the receipts/jobs from prompt 04, the router from 03, and the node registry from 01.--## What you're building--### 1. Node reputation scoring — `api/_lib/oin/reputation.js`--A composite, **provable** score per node, computed from real job history (not vibes):--- **Latency** vs the model's SLA target. **Success rate** (completed vs claimed-then-- failed/timed-out). **Result validity** (see verification below). **Uptime** (heartbeat- continuity). **Volume** (jobs served, as a tie-breaker, not a crutch).-- Windowed and decaying so a node can recover from a bad day and can't coast on old glory- — mirror the TraderScore windowing already in the codebase.-- **Attested onchain** on a schedule (cron in `vercel.json`, idempotent like- `trader-score-attest.js`) so the score the router trusts is the score anyone can verify.-- The router (03) consumes this as its ranking weight; the operator console (06) shows it.--### 2. Result verification — the heart of trustlessness--A node's signature proves *who* produced a result, not that it's *correct*. Add-verification so a lazy or malicious node can't return garbage and get paid:--- **Redundant re-run (challenge):** a sampled fraction of jobs (and any flagged job) is- re-dispatched to a second independent node; compare result hashes / a perceptual- similarity check appropriate to the modality (exact-match for deterministic outputs,- a tolerance metric for stochastic mesh/image gen). Mismatch → the result is rejected,- the user is served the verified one, and the offending node is penalized.-- **Determinism pinning** where the model supports it (seed/params in the manifest) so- re-runs are comparable.-- **Cheap sanity gates** before expensive re-runs: result is well-formed (valid GLB/PNG/- token stream), within size/shape bounds, produced within the deadline.--Make the verification rate a tunable policy (higher for new/low-rep nodes, lower for-proven ones) so security cost scales with risk.--### 3. Staking & slashing (cryptoeconomic security)--Tie real money to honest behavior, using the onchain registry from prompt 01:--- A node stakes (USDC / $THREE) at registration; stake size can gate which value of jobs- it's eligible for (the router won't send a $5 H100 job to an unstaked node).-- **Slashing:** a verified bad result (failed challenge), a signature over a result it- didn't produce, or sustained SLA violation slashes a portion of stake — split between- the wronged payer (refund/redo) and the protocol/insurance pool. Implement the slashing- path against the real contract; document the governance/dispute window.-- **Dispute resolution:** a payer can challenge a result within a window; the challenge- triggers verification; the loser pays the cost. No he-said-she-said — every dispute- resolves to a hash comparison.--## Hard requirements--- **No node is trusted by default.** Reputation, verification, and stake are the trust- model — there is no admin override that just believes a node.-- **Real onchain attestation + slashing**, on the existing rails. Not a database flag- pretending to be a chain. If a contract method needs deploying, ship the source/ABI and- the real call, document the deploy.-- Every penalty traces to a verifiable cause (a failed challenge with two hashes, an SLA- log) — surface that cause to the operator (06) so it's contestable, not arbitrary.--## Definition of done--- Reputation computes from real job history, decays/windows correctly, attests onchain- on schedule, and drives the router's ranking.-- A sampled job is re-run on a second node; a deliberately-wrong result is caught,- rejected, the user served the correct result, and the bad node penalized (test with a- fault-injected node).-- Staking gates job eligibility; a verified bad result slashes stake to the right- parties; a dispute resolves by hash comparison — all on the real chain path.-- Verification rate scales with node risk and is policy-tunable.-- Tests in `tests/` cover scoring, the challenge/verify path, mismatch handling, and- slashing accounting. Existing tests pass.-- `data/changelog.json` entry ("Trustless results — node verification, reputation &- slashing live"), `npm run build:pages`, `npm test` green.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--The promise is "decentralized, and *more* provable than a black-box API." Deliver the-provable part.diff --git a/prompts/nvidia/8.md b/prompts/nvidia/8.mddeleted file mode 100644index e21148cbc..000000000--- a/prompts/nvidia/8.md+++ /dev/null@@ -1,84 +0,0 @@-# Phase 4 · 08 — Federation + the Open SDK--You are a senior platform engineer on **three.ws**. Read `CLAUDE.md` and `STRUCTURE.md`-first — CLAUDE.md overrides defaults. The mesh works and is trustworthy; now make it-**open** — federate with existing decentralized compute networks so the mesh has capacity-from day one, and publish an SDK so any external agent can discover, pay for, and use-decentralized compute through one interface. README deliverable: "federation with existing-decentralized compute networks where appropriate."--Read `api/inference/livepeer.js` (the existing federation seed), the provider/router (03),-settlement (04), the published-SDK conventions in `STRUCTURE.md` and the existing-`sdk/` / `*-sdk/` packages, and the bazaar discovery pattern in `api/x402/*`.--## What you're building--### 1. Federation adapters — one interface, many networks--Generalize the Livepeer experiment into a pluggable federation layer so the router (03)-can route a job to a three.ws node **or** to an external decentralized network,-whichever best serves it:--- `api/_lib/oin/federation/` with one adapter per network, each implementing the same- `submit`/`status` contract as `api/_providers/decentralized.js`:- - **Livepeer** — promote `api/inference/livepeer.js` into a proper adapter (LLM and,- where available, image/video gateways). Keep the side-by-side comparison demo working.- - At least one more real network adapter where it genuinely adds capacity for a model- three.ws serves (e.g. a decentralized GPU/render network with a real public API).- Only integrate networks with a real, callable API — no aspirational stubs.-- The router treats federated capacity as additional "nodes" with their own latency,- price, and reliability signals, subject to the same policy (`shadow`/`prefer`/`only`)- and the same result-verification gate from prompt 07 (a federated result is verified- like any other — federation does not mean blind trust).-- Settlement: where a federated network has its own payment rail, the adapter handles- paying it and the platform reconciles cost; where it can settle via x402, reuse prompt- 04. Never route a job to a network we can't actually pay.--### 2. The open SDK — `@three-ws/inference` (or fit the existing naming)--A published package (follow the exact build/publish process in `STRUCTURE.md` — versioned,-real, installable) that lets any developer or agent use the network:--- **Discover:** list models, nodes, prices, regions (wraps `GET /api/oin/nodes` + pricing).-- **Infer / generate:** one call to run a job (LLM completion, text→3D, retexture, etc.)- that pays via x402 under the hood (reuse the x402 client patterns already in the repo),- routes through the mesh, verifies the signed result, and returns it. Same ergonomics as- calling a centralized API — that's the point.-- **Operate:** thin helpers for node operators (register, heartbeat, claim) so the node- client (02) and third-party node software can share one client library.-- Typed, documented, with a real runnable example in `examples/` and docs in `docs/`.- Every code sample uses real endpoints — no pseudo-code.--### 3. Wire it into the platform's developer story--- Add the SDK + network to the docs/developer surface (`docs/`, the SDKs page) and the- bazaar catalog so other agents discover "decentralized compute" as a payable service.-- An MCP tool / endpoint so agents in the three.ws ecosystem can call the mesh- conversationally (match the existing `mcp-server` / `api/x402/*` patterns).--## Hard requirements--- **Only real, callable networks.** Every federation adapter hits a real API and can- actually run a job and be paid. An adapter you can't exercise end-to-end doesn't ship.-- **Federated results are verified** (prompt 07) and **priced/settled** (prompt 04) like- native ones — same trust model, same money model.-- **$THREE / USDC only** in pricing, payouts, SDK, and docs. The Livepeer leg keeps- working; no other token is referenced anywhere.-- SDK is **published for real** per `STRUCTURE.md`, not a local-only folder.--## Definition of done--- The Livepeer adapter and at least one more real network are routable through the- existing router under policy, with verification + settlement applied.-- The side-by-side inference comparison demo still works (now via the federation adapter).-- `@three-ws/inference` (or the chosen name) is published, installable, and a real- `examples/` script runs a job end-to-end (discover → pay → infer → verified result).-- An MCP tool exposes the network to ecosystem agents; it's in the bazaar catalog and docs.-- Tests cover the federation adapter contract, policy routing to a federated network, and- the SDK's discover/infer path (mockable transport at the test boundary only — the- shipped code calls real APIs). Existing tests pass.-- `data/changelog.json` entries (SDK release + federation), `npm run build:pages`,- `npm test` green.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--Federation gives the mesh capacity; the SDK gives it reach. Ship both real.diff --git a/prompts/nvidia/9.md b/prompts/nvidia/9.mddeleted file mode 100644index fef71f53d..000000000--- a/prompts/nvidia/9.md+++ /dev/null@@ -1,78 +0,0 @@-# Phase 4 · 09 — Integration QA & Polish (run last)--You are the senior engineer doing the final pass on **three.ws**'s Open Inference Network-before it carries real traffic. Read `CLAUDE.md` and `STRUCTURE.md` first — CLAUDE.md-overrides defaults. **Run this only after prompts 01–08 have merged.** Your job is to-prove the whole network works end-to-end as one system, catch the seams between the-pieces, and raise the polish bar everywhere. You may fix issues directly; for anything-large you can't finish, open a precise follow-up note in `ISSUES.md` — but prefer fixing.--## The end-to-end truth test--Walk the full loop on real infrastructure and confirm every hop:--1. A real operator runs the node client (02), registers onchain (01), and appears in the- roster and on the network map (06).-2. A real three.ws job — a forge generation (05) — routes through the router (03) to that- node under policy `prefer`, runs, and returns a **signature-verified** result (03/07)- identical in quality to the centralized path.-3. The job **settles onchain** to the node's payout address with a receipt (04); the- operator sees the earnings + tx in their console (06).-4. A sampled job is **re-run and verified** (07); a fault-injected bad node is caught,- penalized/slashed, and the user is still served the correct result.-5. With all nodes offline, the same forge/avatar/LLM jobs **fall back to centralized** and- succeed — the user never regresses (03/05).-6. An external agent uses the **SDK / x402 endpoint** (04/08) to buy compute end-to-end,- including a federated network leg (08), and gets a verified result.--For each, capture the real evidence (job rows, onchain tx, signatures, logs). Anything you-can't exercise on real infra, say so explicitly — do not paper over it.--## The audit sweep (apply the CLAUDE.md operating rules to all of Phase 4)--- **No mocks / fake data / stubs / TODOs** anywhere in the Phase-4 surface: no simulated- node, no hardcoded roster, no fake receipt, no `throw new Error("not implemented")`,- no fallback sample arrays. Grep for them and remove any you find.-- **$THREE / USDC only** across all new code, copy, fixtures, dashboards, SDK, and docs.- No other token referenced anywhere. Treat any stray reference as a leaked secret.-- **Same job contract** honored across `gcp.js`, `decentralized.js`, and every federation- adapter — no forked job models or envelope drift.-- **Every state designed** on `run-a-node.html`, the operator dashboard, and the network- map: loading skeletons, empty (honest "be the next node"), error (actionable), populated,- overflow. Test at 320/768/1440. Hover/active/focus on every control; ARIA; keyboard nav;- focus rings; contrast. No console errors or warnings.-- **No errors without solutions:** every failure path (dead node, slow node, bad sig,- failed settlement, chain hiccup, zero nodes) degrades gracefully with a real fallback.- Verify the reconciliation cron (04) settles stranded jobs and the router's fallback is- airtight.-- **Security pass:** node auth is by node key (no central secret as trust root); endpoints- rate-limited; no node can spoof another's signature, claim a job it can't serve, get- paid for an unverified result, or escape slashing for a proven bad result. Confirm the- dispute window and idempotent, no-double-pay settlement hold under retry/race.-- **Metrics honesty:** the "% of traffic served by independent nodes" the network map- shows (the README north star) is computed from real job accounting (05), not estimated.--## Performance & polish--- Router selection is fast on the hot path (indexed roster query from 01); no N+1 chain- reads per job. Network map is performant (lazy-load, `transform`/`will-change`, no jank).-- Cross-linking: "Run a node" is reachable from the dashboard/footer/docs; the network and- SDK are in the bazaar catalog and developer docs; nothing is an orphan page.-- The node operator README and the SDK examples actually work when followed from scratch.--## Definition of done--- The six end-to-end loop steps above pass on real infrastructure, with captured evidence.-- The audit sweep is clean: no mocks/stubs/TODOs, no foreign token, contract honored,- every state designed, every failure has a fallback, security holds.-- `npm test` green; `npm run build:pages` clean; `npm run dev` exercised in a browser with- no console errors/warnings; real API/onchain calls observed in the network tab.-- A consolidated `data/changelog.json` entry marking the Open Inference Network live- (holder-readable), if 01–08 didn't already cover it; `npm run build:pages`.-- Any genuinely-deferred item is a precise, actionable note in `ISSUES.md` — not a silent- gap.-- Explicit-path staging; reviewed `git diff`; no bundled `api/*.js`.--Report a single honest status: what's live and proven, what's behind policy/shadow, and-what (if anything) is deferred and why. You would demo this network to a room of senior-infra engineers and be proud of it.diff --git a/public/changelog.json b/public/changelog.jsonindex 6538236ba..902b74e11 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:44:55.076Z",+ "generated_at": "2026-06-23T13:13:46.966Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -402,6 +402,16 @@"feature"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Every agent wallet now has a living trading card you can share",+ "summary": "Each agent's wallet is now a collectible, screenshot-worthy trading card — its avatar, its glowing vanity address, its live net worth, holdings count, realized P&L, reputation tier, and the $THREE-holder mark, with a one-tap tip, fork, and share. The card's 'finish' is earned, not decorative: it steps up from Common to Mythic only as the wallet's real wealth and on-chain reputation tier rise, so a dormant new wallet reads as matte and a luminous, elite one shimmers. Everything on it is real, public-safe data pulled from the same chain reads the wallet uses everywhere else — a $0 balance honestly shows $0, owner-only details never appear, and a private agent renders no card at all. Best of all, it travels: paste an agent link into X, Telegram, or Discord and it now unfurls as that exact card, generated live from real data, so every share is a billboard with a fork-to-own hook. The Share panel even previews the card before you post it.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -1156,6 +1166,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "The Mind Palace: walk through your agent's memory in 3D",+ "summary": "Your agent's memory is no longer an invisible database — it's a place you can explore. Open the new Mind Palace from your agent's editor or at /agent/<id>/mind and every memory becomes a tangible object orbiting your live avatar: the more a belief matters to your agent (its salience), the larger it glows and the closer it sits to the centre. Memories cluster by type into colour-coded constellations — what you've told it, the guidance you've given, your projects, and reference knowledge — with glowing threads drawn between memories that share tags, so you can literally see how your agent connects ideas. It's hands-on: drag a memory to the centre to pin it as a core belief, or flick it into the Forget well to let it go (with one-click undo — forgetting is always reversible). Search and filter instantly, click any memory to read its full content, see where it came from, and walk its associations to answer 'why does my agent believe this?'. Open it during a conversation and you'll watch memories pulse the moment your agent recalls them, and new memories bloom into being as they form. There's a timeline scrubber to replay how the mind grew over time, a full 2D view and keyboard navigation for any device, and it respects reduced-motion and the avatar performance budget throughout. Everything you do here writes straight to your agent's real memory.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e7b4d489a..dd53c796c 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -318,6 +318,14 @@<category>feature</category><description>In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown.</description></item>+ <item>+ <title>Every agent wallet now has a living trading card you can share</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Every agent wallet now has a living trading card you can share</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Each agent's wallet is now a collectible, screenshot-worthy trading card — its avatar, its glowing vanity address, its live net worth, holdings count, realized P&L, reputation tier, and the $THREE-holder mark, with a one-tap tip, fork, and share. The card's 'finish' is earned, not decorative: it steps up from Common to Mythic only as the wallet's real wealth and on-chain reputation tier rise, so a dormant new wallet reads as matte and a luminous, elite one shimmers. Everything on it is real, public-safe data pulled from the same chain reads the wallet uses everywhere else — a $0 balance honestly shows $0, owner-only details never appear, and a private agent renders no card at all. Best of all, it travels: paste an agent link into X, Telegram, or Discord and it now unfurls as that exact card, generated live from real data, so every share is a billboard with a fork-to-own hook. The Share panel even previews the card before you post it.</description>+ </item><item><title>Every paid three.ws endpoint now renders and ranks in the agent marketplaces</title><link>https://three.ws/changelog</link>@@ -902,6 +910,14 @@<category>improvement</category><description>The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct.</description></item>+ <item>+ <title>The Mind Palace: walk through your agent's memory in 3D</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:The Mind Palace: walk through your agent's memory in 3D</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent's memory is no longer an invisible database — it's a place you can explore. Open the new Mind Palace from your agent's editor or at /agent/<id>/mind and every memory becomes a tangible object orbiting your live avatar: the more a belief matters to your agent (its salience), the larger it glows and the closer it sits to the centre. Memories cluster by type into colour-coded constellations — what you've told it, the guidance you've given, your projects, and reference knowledge — with glowing threads drawn between memories that share tags, so you can literally see how your agent connects ideas. It's hands-on: drag a memory to the centre to pin it as a core belief, or flick it into the Forget well to let it go (with one-click undo — forgetting is always reversible). Search and filter instantly, click any memory to read its full content, see where it came from, and walk its associations to answer 'why does my agent believe this?'. Open it during a conversation and you'll watch memories pulse the moment your agent recalls them, and new memories bloom into being as they form. There's a timeline scrubber to replay how the mind grew over time, a full 2D view and keyboard navigation for any device, and it respects reduced-motion and the avatar performance budget throughout. Everything you do here writes straight to your agent's real memory.</description>+ </item><item><title>The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent</title><link>https://three.ws/ledger</link>diff --git a/public/features.json b/public/features.jsonindex 3529f5da8..d8428c485 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:44:55.056Z",+ "generated_at": "2026-06-23T13:13:46.948Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-detail.js b/src/agent-detail.jsindex c2a995555..a0d7053e1 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -92,6 +92,7 @@ if (typeof window !== 'undefined') {// Stop any active money stream so a final settle fires and no charges accrue// past navigation (the engine also guards this internally).try { _streamHandle?.destroy?.(); } catch { /* idempotent */ } _streamHandle = null;+ try { _cardHandle?.destroy?.(); } catch { /* idempotent */ } _cardHandle = null;}, { once: true });}@@ -2018,6 +2019,7 @@ function wireShareButton(agent) {description: agent.description || '',shareUrl,remixUrl,+ previewImage: `${origin}/api/og/agent?id=${encodeURIComponent(agent.id)}`,};// Hero float button (above the fold)diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsindex d006a0f7b..bc08a5140 100644--- a/src/agent-wallet-hub/index.js+++ b/src/agent-wallet-hub/index.js@@ -36,9 +36,11 @@ import './tabs/intents.js';import './tabs/signals.js';import './tabs/pay.js';import './tabs/vanity.js';+import './tabs/policy.js';import './tabs/withdraw.js';import './tabs/give.js';import './tabs/recovery.js';+import './tabs/proof.js';import { escapeHtml, shortAddress, copyToClipboard, toast } from './util.js';diff --git a/src/agent-wallet-hub/tabs/guard.js b/src/agent-wallet-hub/tabs/guard.jsnew file mode 100644index 000000000..0c1c4f6bb--- /dev/null+++ b/src/agent-wallet-hub/tabs/guard.js@@ -0,0 +1,348 @@+/**+ * Agent Wallet hub — Self-Defending Wallet tab (owner-only).+ *+ * Every wallet gets an immune system. The platform learns each agent's normal+ * spending behavior and scores every outbound action in real time; anything that+ * looks anomalous auto-freezes the wallet and surfaces here with a plain-language+ * "why" and one-tap Approve / Keep-frozen / Sweep-to-safety. Approving teaches the+ * baseline so the wallet gets smarter, never naggier.+ *+ * All state is REAL: this panel only ever renders DB state from+ * GET /api/agents/:id/solana/guard, and every action hits the owner-gated,+ * CSRF-protected API. The scoring + freeze happen server-side on the spend path;+ * this is the owner's window into — and control over — that system.+ */++import { registerWalletTab } from '../registry.js';+import { consumeCsrfToken } from '../../api.js';++const STYLE_ID = 'awh-guard-style';+const STYLE = `+.awh-guard { display:flex; flex-direction:column; gap:var(--space-3,12px); }+.awh-guard h2 { margin:0 0 4px; font-size:var(--text-md,.8125rem); color:var(--ink-bright,#fff); font-family:var(--font-display,system-ui); font-weight:600; }+.awh-guard-lead { color:var(--ink-dim,#888); font-size:var(--text-sm,.764rem); line-height:1.55; margin:0; max-width:62ch; }+.awh-guard-head { display:flex; gap:10px; align-items:flex-start; }+.awh-guard-shield { display:inline-grid; place-items:center; width:30px; height:30px; border-radius:var(--radius-md,10px); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 16%,transparent); border:1px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 36%,transparent); font-size:15px; flex:none; }+.awh-guard-alarm { border-color:color-mix(in srgb,var(--danger,#ef4444) 50%,transparent) !important; background:color-mix(in srgb,var(--danger,#ef4444) 9%,transparent); }+.awh-guard-alarm .awh-guard-shield { background:color-mix(in srgb,var(--danger,#ef4444) 18%,transparent); border-color:color-mix(in srgb,var(--danger,#ef4444) 45%,transparent); animation:awh-guard-pulse 1.6s ease-in-out infinite; }+@keyframes awh-guard-pulse { 0%,100%{ box-shadow:0 0 0 0 color-mix(in srgb,var(--danger,#ef4444) 40%,transparent);} 50%{ box-shadow:0 0 0 6px color-mix(in srgb,var(--danger,#ef4444) 0%,transparent);} }+.awh-flag { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); background:var(--surface-1,rgba(255,255,255,.03)); padding:11px 12px; display:flex; flex-direction:column; gap:8px; }+.awh-flag + .awh-flag { margin-top:8px; }+.awh-flag-top { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }+.awh-flag-sum { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); font-weight:500; flex:1; min-width:160px; }+.awh-flag-meta { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); font-family:var(--font-mono,monospace); }+.awh-factors { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:4px; }+.awh-factor { display:flex; gap:7px; align-items:flex-start; font-size:var(--text-sm,.764rem); color:var(--ink,#c8c8c8); line-height:1.4; }+.awh-factor::before { content:'›'; color:var(--danger,#ef4444); font-weight:700; flex:none; }+.awh-factor.sev-medium::before,.awh-factor.sev-low::before { color:var(--warn,#fbbf24); }+.awh-flag-acts { display:flex; gap:8px; flex-wrap:wrap; margin-top:2px; }+.awh-score { display:inline-flex; align-items:center; gap:6px; font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:var(--radius-pill,999px); border:1px solid transparent; font-family:var(--font-mono,monospace); }+.awh-score.hi { color:var(--danger,#ef4444); background:color-mix(in srgb,var(--danger,#ef4444) 12%,transparent); border-color:color-mix(in srgb,var(--danger,#ef4444) 34%,transparent); }+.awh-score.mid { color:var(--warn,#fbbf24); background:color-mix(in srgb,var(--warn,#fbbf24) 12%,transparent); border-color:color-mix(in srgb,var(--warn,#fbbf24) 30%,transparent); }+.awh-score.lo { color:var(--ink-dim,#888); background:var(--surface-2,rgba(255,255,255,.05)); border-color:var(--stroke,rgba(255,255,255,.08)); }+.awh-seg { display:inline-flex; gap:4px; background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); padding:3px; }+.awh-seg button { appearance:none; font:inherit; font-size:var(--text-sm,.764rem); color:var(--ink-dim,#888); background:transparent; border:none; border-radius:var(--radius-sm,6px); padding:6px 12px; cursor:pointer; transition:background var(--duration-fast,140ms),color var(--duration-fast,140ms); }+.awh-seg button:hover { color:var(--ink,#e8e8e8); }+.awh-seg button[aria-pressed="true"] { background:var(--accent,#fff); color:#0a0a0a; font-weight:600; }+.awh-seg button:focus-visible { outline:var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }+.awh-guard-row { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; padding:9px 0; border-top:1px solid var(--stroke,rgba(255,255,255,.08)); }+.awh-guard-row:first-of-type { border-top:none; }+.awh-guard-row label { font-size:var(--text-sm,.764rem); color:var(--ink,#c8c8c8); }+.awh-guard-row .hint { display:block; font-size:var(--text-2xs,.6875rem); color:var(--ink-faint,#666); margin-top:2px; max-width:42ch; }+.awh-guard-row input[type="text"] { font:inherit; font-size:var(--text-sm,.764rem); color:var(--ink,#e8e8e8); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); padding:7px 10px; min-width:200px; flex:1; }+.awh-guard-row input:focus-visible { outline:var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }+.awh-switch { display:inline-flex; align-items:center; gap:8px; }+.awh-stats { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:10px; }+.awh-stat { background:var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); padding:9px 11px; }+.awh-stat .k { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); text-transform:uppercase; letter-spacing:.05em; }+.awh-stat .v { font-size:var(--text-md,.8125rem); color:var(--ink-bright,#fff); font-weight:600; margin-top:3px; font-family:var(--font-mono,monospace); }+.awh-tl { list-style:none; margin:6px 0 0; padding:0; display:flex; flex-direction:column; gap:0; }+.awh-tl-item { display:flex; gap:10px; padding:9px 0; border-top:1px solid var(--stroke,rgba(255,255,255,.06)); }+.awh-tl-item:first-child { border-top:none; }+.awh-tl-dot { width:8px; height:8px; border-radius:50%; margin-top:6px; flex:none; background:var(--ink-faint,#555); }+.awh-tl-dot.flagged { background:var(--danger,#ef4444); } .awh-tl-dot.approved { background:var(--success,#4ade80); } .awh-tl-dot.denied { background:var(--warn,#fbbf24); }+.awh-tl-c { flex:1; min-width:0; }+.awh-tl-sum { font-size:var(--text-sm,.764rem); color:var(--ink,#e8e8e8); line-height:1.4; }+.awh-tl-meta { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:2px; display:flex; gap:8px; flex-wrap:wrap; align-items:center; }+.awh-badge { font-size:var(--text-2xs,.6875rem); padding:1px 7px; border-radius:var(--radius-pill,999px); border:1px solid var(--stroke,rgba(255,255,255,.12)); color:var(--ink-dim,#888); text-transform:capitalize; }+.awh-badge.flagged { color:var(--danger,#ef4444); border-color:color-mix(in srgb,var(--danger,#ef4444) 34%,transparent); }+.awh-badge.approved { color:var(--success,#4ade80); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }+.awh-badge.denied { color:var(--warn,#fbbf24); border-color:color-mix(in srgb,var(--warn,#fbbf24) 30%,transparent); }+.awh-guard-skel { height:60px; border-radius:var(--radius-lg,14px); background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.05)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%); background-size:400% 100%; animation:awh-guard-shimmer 1.4s ease infinite; }+@keyframes awh-guard-shimmer { 0%{background-position:100% 0} 100%{background-position:-100% 0} }+.awh-guard-empty-ill { font-size:26px; opacity:.5; margin-bottom:4px; display:block; }+@media (prefers-reduced-motion: reduce){ .awh-guard-skel{animation:none} .awh-guard-alarm .awh-guard-shield{animation:none} }+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }+ if (method !== 'GET') { const t = await consumeCsrfToken(); if (t) opts.headers['x-csrf-token'] = t; }+ const r = await fetch(url, opts);+ let j = null; try { j = await r.json(); } catch { /* empty */ }+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, detail: j?.detail || null };+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++function ago(ts) {+ if (!ts) return '';+ const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000);+ if (s < 60) return 'just now';+ 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 shortAddr(a) { return a ? `${a.slice(0, 4)}…${a.slice(-4)}` : ''; }+function scoreClass(s) { return s >= 0.7 ? 'hi' : s >= 0.4 ? 'mid' : 'lo'; }++registerWalletTab({+ id: 'guard',+ label: 'Self-defense',+ order: 78,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectStyle();+ const { escapeHtml, agentId, toast } = ctx;+ let state = null;+ let busy = false;+ let pollTimer = null;++ function setBusy(b) {+ busy = b;+ panel.querySelectorAll('button, input, select').forEach((el) => { if (!el.dataset.keepEnabled) el.disabled = b; });+ }++ async function load() {+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/solana/guard`);+ if (!res.ok) { renderError(res); return; }+ state = res.data;+ render();+ }++ function renderLoading() {+ panel.innerHTML = `<div class="awh-card"><div class="awh-guard-skel"></div></div><div class="awh-card"><div class="awh-guard-skel"></div></div>`;+ }++ function renderError(res) {+ panel.innerHTML = `<div class="awh-card"><p class="awh-empty">Couldn’t load the guard — ${escapeHtml(res.message || 'try again')}. <button class="awh-btn" type="button" data-act="retry">Try again</button></p></div>`;+ panel.querySelector('[data-act="retry"]')?.addEventListener('click', () => { renderLoading(); load(); });+ }++ function factorsHTML(factors) {+ if (!Array.isArray(factors) || !factors.length) return '';+ return `<ul class="awh-factors">${factors.map((f) => `<li class="awh-factor sev-${escapeHtml(f.severity || 'high')}">${escapeHtml(f.label || '')}</li>`).join('')}</ul>`;+ }++ function flagHTML(f) {+ const safe = state.config?.safe_address;+ return `+ <div class="awh-flag" data-flag="${escapeHtml(f.id)}">+ <div class="awh-flag-top">+ <span class="awh-flag-sum">${escapeHtml(f.summary || 'Unusual activity')}</span>+ <span class="awh-score ${scoreClass(f.score)}">risk ${Math.round((f.score || 0) * 100)}</span>+ </div>+ <div class="awh-flag-meta">${escapeHtml(f.category || 'spend')}${f.usd != null ? ` · $${Number(f.usd).toFixed(2)}` : ''}${f.destination ? ` · → ${escapeHtml(shortAddr(f.destination))}` : ''} · ${escapeHtml(ago(f.created_at))}</div>+ ${factorsHTML(f.factors)}+ <div class="awh-flag-acts">+ <button class="awh-btn awh-btn--primary" type="button" data-act="approve" data-id="${escapeHtml(f.id)}">✓ It was me — approve & unfreeze</button>+ <button class="awh-btn awh-btn--danger" type="button" data-act="deny" data-id="${escapeHtml(f.id)}">Keep frozen</button>+ ${safe ? `<button class="awh-btn" type="button" data-act="sweep" data-id="${escapeHtml(f.id)}">⤴ Sweep to safety</button>` : ''}+ </div>+ </div>`;+ }++ function render() {+ const cfg = state.config || {};+ const baseline = state.baseline || {};+ const flags = state.open_flags || [];+ const items = state.timeline?.items || [];+ const frozen = !!state.frozen;++ const alarm = frozen && (flags.length > 0 || true);+ const banner = frozen ? `+ <div class="awh-card ${alarm ? 'awh-guard-alarm' : ''}">+ <div class="awh-guard">+ <div class="awh-guard-head">+ <span class="awh-guard-shield" aria-hidden="true">🛡️</span>+ <div style="flex:1;">+ <h2>Wallet frozen — your money is defending itself</h2>+ <p class="awh-guard-lead">Autonomous spending is paused. ${flags.length ? 'Review what tripped the guard below and decide.' : 'No open flag — you can unfreeze if this was expected.'}</p>+ </div>+ </div>+ ${flags.map(flagHTML).join('')}+ ${!flags.length ? `<div class="awh-flag-acts"><button class="awh-btn awh-btn--primary" type="button" data-act="unfreeze">Unfreeze wallet</button></div>` : ''}+ ${!cfg.safe_address ? `<p class="awh-guard-row" style="border:none;padding-top:4px;"><span class="hint">Tip: set a safe address below to enable one-tap “Sweep to safety” during a freeze.</span></p>` : ''}+ </div>+ </div>` : '';++ const lowHist = baseline.low_history;+ const baselineCard = `+ <div class="awh-card">+ <div class="awh-guard">+ <div class="awh-guard-head">+ <span class="awh-guard-shield" aria-hidden="true">🧠</span>+ <div style="flex:1;"><h2>What your wallet has learned</h2>+ <p class="awh-guard-lead">${lowHist ? 'Still learning — with little history the guard widens its tolerances and only freezes on the clearest threats.' : 'The guard scores every spend against this learned profile of normal behavior.'}</p></div>+ </div>+ <div class="awh-stats">+ <div class="awh-stat"><div class="k">Spends learned</div><div class="v">${Number(baseline.total_events || 0)}</div></div>+ <div class="awh-stat"><div class="k">Largest spend</div><div class="v">$${Number(baseline.usd?.max || 0).toFixed(2)}</div></div>+ <div class="awh-stat"><div class="k">Known addresses</div><div class="v">${Number(baseline.counterparty_count || 0)}</div></div>+ <div class="awh-stat"><div class="k">Active hours (UTC)</div><div class="v">${(baseline.active_hours || []).length || '—'}</div></div>+ </div>+ ${cfg.learned_destinations ? `<p class="awh-guard-lead" style="margin-top:4px;">${cfg.learned_destinations} address${cfg.learned_destinations === 1 ? '' : 'es'} you’ve approved are trusted and won’t re-trip.</p>` : ''}+ </div>+ </div>`;++ const presets = state.presets || [];+ const settingsCard = `+ <div class="awh-card">+ <div class="awh-guard">+ <div class="awh-guard-head">+ <span class="awh-guard-shield" aria-hidden="true">⚙️</span>+ <div style="flex:1;"><h2>Sensitivity & safeguards</h2>+ <p class="awh-guard-lead">Tune how eagerly the guard freezes. Approving a flagged action always teaches it, so Balanced rarely nags.</p></div>+ <label class="awh-switch"><input type="checkbox" data-field="enabled" ${cfg.enabled !== false ? 'checked' : ''} aria-label="Enable the anomaly guard" /><span>${cfg.enabled !== false ? 'On' : 'Off'}</span></label>+ </div>+ <div class="awh-seg" role="group" aria-label="Sensitivity">+ ${presets.map((p) => `<button type="button" data-sens="${escapeHtml(p.key)}" aria-pressed="${cfg.sensitivity === p.key}" title="${escapeHtml(p.description || '')}">${escapeHtml(p.label)}</button>`).join('')}+ </div>+ <p class="awh-guard-lead">${escapeHtml((presets.find((p) => p.key === cfg.sensitivity) || {}).description || '')}</p>+ <div class="awh-guard-row">+ <label for="awh-guard-safe">Safe address<span class="hint">Where one-tap “Sweep to safety” sends funds during a freeze. Your own cold wallet.</span></label>+ <input id="awh-guard-safe" type="text" data-field="safe" value="${escapeHtml(cfg.safe_address || '')}" placeholder="Solana address" autocomplete="off" spellcheck="false" />+ <button class="awh-btn" type="button" data-act="save-safe">Save</button>+ </div>+ ${cfg.learned_destinations ? `<div class="awh-guard-row"><label>Trusted patterns<span class="hint">Addresses & amounts you’ve approved. Reset to score everything fresh.</span></label><button class="awh-btn" type="button" data-act="clear-learned">Reset what’s learned</button></div>` : ''}+ </div>+ </div>`;++ const timelineCard = `+ <div class="awh-card">+ <div class="awh-guard">+ <div class="awh-guard-head"><span class="awh-guard-shield" aria-hidden="true">📜</span><div style="flex:1;"><h2>Anomaly timeline</h2><p class="awh-guard-lead">Every scored action — allowed and flagged — explained in plain language.</p></div></div>+ ${items.length ? `<ul class="awh-tl">${items.map(timelineItemHTML).join('')}</ul>+ ${state.timeline?.next_cursor ? `<div class="awh-flag-acts"><button class="awh-btn" type="button" data-act="more">Load older</button></div>` : ''}`+ : `<p class="awh-empty" style="text-align:center;"><span class="awh-guard-empty-ill" aria-hidden="true">🛡️</span>Nothing flagged yet. The guard is watching every spend — you’ll see notable activity here.</p>`}+ </div>+ </div>`;++ panel.innerHTML = banner + baselineCard + settingsCard + timelineCard;+ wire();+ }++ function timelineItemHTML(e) {+ const cls = e.status === 'flagged' ? 'flagged' : e.status === 'approved' ? 'approved' : e.status === 'denied' ? 'denied' : '';+ return `+ <li class="awh-tl-item">+ <span class="awh-tl-dot ${cls}"></span>+ <div class="awh-tl-c">+ <div class="awh-tl-sum">${escapeHtml(e.summary || 'Scored a spend')}</div>+ <div class="awh-tl-meta">+ <span class="awh-score ${scoreClass(e.score)}">risk ${Math.round((e.score || 0) * 100)}</span>+ <span>${escapeHtml(e.category || 'spend')}${e.usd != null ? ` · $${Number(e.usd).toFixed(2)}` : ''}</span>+ <span class="awh-badge ${cls}">${escapeHtml(e.status)}</span>+ <span>${escapeHtml(ago(e.created_at))}</span>+ </div>+ </div>+ </li>`;+ }++ async function adjudicate(action, eventId) {+ if (busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/solana/guard`, { method: 'POST', body: { action, event_id: eventId } });+ setBusy(false);+ if (!res.ok) { toast(res.message || 'Action failed'); return; }+ toast(action === 'approve' ? 'Approved — wallet unfrozen and pattern trusted' : action === 'deny' ? 'Kept frozen' : 'Done');+ await load();+ }++ async function sweep(eventId) {+ const safe = state.config?.safe_address;+ if (!safe) { toast('Set a safe address first'); return; }+ if (!confirm(`Sweep all SOL to your safe address (${shortAddr(safe)})? The wallet stays frozen.`)) return;+ if (busy) return;+ setBusy(true);+ // A real, audited withdraw — allowed even while frozen (the safe direction).+ const w = await call(`/api/agents/${encodeURIComponent(agentId)}/solana/withdraw`, { method: 'POST', body: { destination: safe, amount: 'max', asset: 'SOL' } });+ if (!w.ok) { setBusy(false); toast(w.message || 'Sweep failed'); return; }+ await call(`/api/agents/${encodeURIComponent(agentId)}/solana/guard`, { method: 'POST', body: { action: 'mark_swept', event_id: eventId } });+ setBusy(false);+ toast('Swept to safety');+ await load();+ }++ async function saveConfig(patch, msg) {+ if (busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/solana/guard`, { method: 'PUT', body: patch });+ setBusy(false);+ if (!res.ok) { toast(res.message || 'Could not save'); return; }+ if (msg) toast(msg);+ await load();+ }++ function wire() {+ panel.querySelectorAll('[data-act="approve"]').forEach((b) => b.addEventListener('click', () => adjudicate('approve', b.dataset.id)));+ panel.querySelectorAll('[data-act="deny"]').forEach((b) => b.addEventListener('click', () => adjudicate('deny', b.dataset.id)));+ panel.querySelectorAll('[data-act="sweep"]').forEach((b) => b.addEventListener('click', () => sweep(b.dataset.id)));+ panel.querySelector('[data-act="unfreeze"]')?.addEventListener('click', () => {+ if (!confirm('Unfreeze the wallet? Autonomous spending resumes.')) return;+ adjudicate('unfreeze', null);+ });+ panel.querySelectorAll('[data-sens]').forEach((b) => b.addEventListener('click', () => {+ if (b.getAttribute('aria-pressed') === 'true') return;+ saveConfig({ sensitivity: b.dataset.sens }, 'Sensitivity updated');+ }));+ panel.querySelector('[data-field="enabled"]')?.addEventListener('change', (e) => {+ saveConfig({ enabled: e.target.checked }, e.target.checked ? 'Guard enabled' : 'Guard disabled');+ });+ panel.querySelector('[data-act="save-safe"]')?.addEventListener('click', () => {+ const v = (panel.querySelector('[data-field="safe"]')?.value || '').trim();+ saveConfig({ safe_address: v || null }, v ? 'Safe address saved' : 'Safe address cleared');+ });+ panel.querySelector('[data-act="clear-learned"]')?.addEventListener('click', () => {+ if (!confirm('Reset everything the guard has learned? It will score all addresses and amounts as new again.')) return;+ saveConfig({ clear_learned: true }, 'Learned patterns reset');+ });+ panel.querySelector('[data-act="more"]')?.addEventListener('click', async () => {+ const cursor = state.timeline?.next_cursor;+ if (!cursor || busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/solana/guard?before=${encodeURIComponent(cursor)}`);+ setBusy(false);+ if (res.ok) {+ state.timeline.items = [...state.timeline.items, ...(res.data.timeline?.items || [])];+ state.timeline.next_cursor = res.data.timeline?.next_cursor || null;+ render();+ }+ });+ }++ function startPoll() {+ stopPoll();+ // Poll while frozen so a fresh flag (or an unfreeze from another device) shows.+ pollTimer = setInterval(() => { if (!document.hidden && state?.frozen) load(); }, 12000);+ }+ function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }++ return {+ onShow() { renderLoading(); load(); startPoll(); },+ onHide() { stopPoll(); },+ destroy() { stopPoll(); panel.innerHTML = ''; },+ };+ },+});diff --git a/src/agent-wallet-hub/tabs/policy.js b/src/agent-wallet-hub/tabs/policy.jsnew file mode 100644index 000000000..57c0820d8--- /dev/null+++ b/src/agent-wallet-hub/tabs/policy.js@@ -0,0 +1,388 @@+/**+ * Agent Wallet hub — Policy tab (natural-language spend policies).+ *+ * Owner-only. The owner writes how their agent's custodial wallet may spend in+ * plain English; a real Claude call (server-side, through the platform LLM proxy)+ * COMPILES it into a deterministic rule document that the shared spend guards+ * enforce on every trade / snipe / x402 payment / withdraw. The model only authors+ * and explains — it never decides a spend. Before saving, the owner sees:+ *+ * 1. The numbered, plain-English READBACK of the compiled rules (generated from+ * the DSL, so it can never drift from what code enforces).+ * 2. A BACKTEST against the wallet's real custody history: "against your last N+ * days, this would have blocked 3 spends ($X) and allowed 47" — computed by the+ * exact evaluator that runs in production. With no history yet, a set of+ * hypothetical cases shows how it behaves.+ *+ * All states designed: composing, compiling (real async), refused/invalid+ * (actionable), backtest-empty (explained), saved. Keyboard-driven + accessible.+ * Everything is real: real LLM compile, real history, the real shared policy.+ */++import { registerWalletTab } from '../registry.js';+import { formatUsd } from '../util.js';+import { consumeCsrfToken } from '../../api.js';++const STARTERS = [+ {+ key: 'conservative',+ label: 'Conservative',+ text: 'Block any payment over $25. Never let the wallet drop below 1 SOL. Only ever pay services I’ve used before. Stop everything if a trade drops more than 30%.',+ },+ {+ key: 'active',+ label: 'Active trader',+ text: 'Let it trade up to $100 a day. Only trade tokens at least 6 hours old. Never spend my last 0.5 SOL. Freeze the wallet if any trade drops more than 40%.',+ },+ {+ key: 'pay-only',+ label: 'Pay-only',+ text: 'Only ever pay services I’ve used before. Block any single payment over $50. Cap total spend at $200 a day.',+ },+];++const POLICY_STYLE_ID = 'awh-policy-style';+const POLICY_STYLE = `+.awp-intro { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); line-height:1.5; margin:0 0 var(--space-3,12px); }+.awp-chips { display:flex; gap:6px; flex-wrap:wrap; margin-bottom: var(--space-3,12px); }+.awp-chip { appearance:none; font:inherit; font-size: var(--text-2xs,.6875rem); font-weight:600; color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.06)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding:5px 12px; cursor:pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms), transform var(--duration-instant,80ms); }+.awp-chip:hover { background: var(--surface-3,rgba(255,255,255,.1)); border-color: var(--stroke-strong,rgba(255,255,255,.16)); }+.awp-chip:active { transform: translateY(1px); }+.awp-chip:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }+.awp-ta { width:100%; box-sizing:border-box; min-height:88px; resize:vertical; font:inherit; font-size: var(--text-md,.8125rem); line-height:1.5; color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:11px 13px; transition: border-color var(--duration-fast,140ms); }+.awp-ta:focus { outline:none; border-color: var(--stroke-strong,rgba(255,255,255,.2)); }+.awp-actions { display:flex; gap:8px; margin-top: var(--space-3,12px); align-items:center; flex-wrap:wrap; }+.awp-actions .grow { flex:1; }+.awp-hint { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }++.awp-rules { list-style:none; margin:0; padding:0; counter-reset: awp; }+.awp-rule { display:flex; gap:11px; padding:9px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); font-size: var(--text-sm,.8125rem); line-height:1.45; }+.awp-rule:last-child { border-bottom:none; }+.awp-rule .n { flex:none; width:22px; height:22px; border-radius:50%; display:inline-flex; align-items:center; justify-content:center; font-size: var(--text-2xs,.6875rem); font-weight:700; background: var(--surface-2,rgba(255,255,255,.07)); color: var(--ink,#e8e8e8); }+.awp-rule .tx { flex:1; min-width:0; color: var(--ink,#e8e8e8); }+.awp-rule .tag { flex:none; font-size: var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius: var(--radius-pill,999px); white-space:nowrap; align-self:flex-start; }+.awp-rule .tag.block { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 30%, transparent); }+.awp-rule .tag.freeze { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 12%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); }+.awp-rule .tag.allow { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); border:1px solid color-mix(in srgb, var(--success,#4ade80) 30%, transparent); }+.awp-rule .tag.require_step_up { color: var(--accent,#8ab4ff); background: color-mix(in srgb, var(--accent,#8ab4ff) 14%, transparent); border:1px solid color-mix(in srgb, var(--accent,#8ab4ff) 30%, transparent); }++.awp-assume { margin: var(--space-3,12px) 0 0; padding:10px 12px; border-radius: var(--radius-md,10px); background: color-mix(in srgb, var(--warn,#fbbf24) 8%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 24%, transparent); font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); line-height:1.45; }+.awp-assume ul { margin:6px 0 0; padding-left:18px; } .awp-assume li { margin:2px 0; }++.awp-bt-head { display:flex; gap:8px; flex-wrap:wrap; align-items:baseline; margin-bottom:10px; }+.awp-bt-stat { font-size: var(--text-2xs,.6875rem); font-weight:600; padding:3px 10px; border-radius: var(--radius-pill,999px); }+.awp-bt-stat.allow { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); }+.awp-bt-stat.block { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); }+.awp-bt-stat.muted { color: var(--ink-dim,#888); background: var(--surface-2,rgba(255,255,255,.05)); }+.awp-bar { display:flex; height:8px; border-radius:6px; overflow:hidden; background: var(--surface-2,rgba(255,255,255,.06)); margin-bottom:10px; }+.awp-bar .a { background: color-mix(in srgb, var(--success,#4ade80) 70%, transparent); }+.awp-bar .b { background: color-mix(in srgb, var(--danger,#f87171) 75%, transparent); }+.awp-tl { display:flex; gap:2px; flex-wrap:wrap; margin:8px 0 4px; }+.awp-tl .c { width:11px; height:18px; border-radius:3px; background: color-mix(in srgb, var(--success,#4ade80) 55%, transparent); cursor:default; transition: transform var(--duration-instant,80ms); }+.awp-tl .c.blocked { background: color-mix(in srgb, var(--danger,#f87171) 70%, transparent); }+.awp-tl .c:hover { transform: scaleY(1.25); }+.awp-byrule { list-style:none; margin:10px 0 0; padding:0; }+.awp-byrule li { display:flex; justify-content:space-between; gap:10px; padding:6px 0; border-top:1px solid var(--stroke,rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }+.awp-byrule .lbl { color: var(--ink,#e8e8e8); min-width:0; }+.awp-byrule .ct { color: var(--danger,#f87171); flex:none; font-family: var(--font-mono,ui-monospace,monospace); }++.awp-syn { list-style:none; margin:0; padding:0; }+.awp-syn li { display:flex; justify-content:space-between; gap:10px; align-items:center; padding:7px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }+.awp-syn li:last-child { border-bottom:none; }+.awp-syn .v { flex:none; font-size: var(--text-2xs,.6875rem); font-weight:700; padding:2px 9px; border-radius: var(--radius-pill,999px); }+.awp-syn .v.ok { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); }+.awp-syn .v.no { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); }++.awp-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-bottom: var(--space-3,12px); line-height:1.45; }+.awp-warn { background: color-mix(in srgb, var(--warn,#fbbf24) 9%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent); color: var(--warn,#fbbf24); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-bottom: var(--space-3,12px); line-height:1.45; }+.awp-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: awp-pulse 1.4s ease-in-out infinite; margin:9px 0; }+.awp-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,.3); border-top-color: currentColor; border-radius:50%; animation: awp-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }+.awp-caps { display:flex; gap:6px; flex-wrap:wrap; }+.awp-cap { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); background: var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px); padding:3px 10px; }+@keyframes awp-rot { to { transform: rotate(360deg); } }+@keyframes awp-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }+@media (prefers-reduced-motion: reduce) { .awp-skel, .awp-spin, .awp-tl .c { animation:none; transition:none; } }+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(POLICY_STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = POLICY_STYLE_ID;+ tag.textContent = POLICY_STYLE;+ document.head.appendChild(tag);+}++// Fetch helper — never throws, always a designed result. Mirrors the withdraw tab.+async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) {+ opts.headers['content-type'] = 'application/json';+ opts.body = JSON.stringify(body);+ }+ if (method !== 'GET') {+ const token = await consumeCsrfToken();+ if (token) opts.headers['x-csrf-token'] = token;+ }+ const r = await fetch(url, opts);+ let j = null;+ try { j = await r.json(); } catch { /* empty body */ }+ if (!r.ok) {+ return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, extra: j || null };+ }+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++const ACTION_TAG = { block: 'Block', freeze: 'Freeze', allow: 'Allow', require_step_up: 'Ask me' };++function protectiveCount(rules) {+ return (rules || []).filter((r) => r.action === 'block' || r.action === 'freeze' || r.action === 'require_step_up').length;+}++registerWalletTab({+ id: 'policy',+ label: 'Policy',+ order: 58,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectStyle();+ const esc = ctx.escapeHtml;+ const toast = ctx.toast;+ const base = (sub) => `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/${sub}`;++ let destroyed = false;+ let detachNet = null;+ const state = {+ loaded: false,+ current: null, // { policy, readback, source_text, numeric_limits } | { error }+ draft: '', // textarea content+ compiling: false,+ compiled: null, // compile result | null+ compileErr: null, // { message, refusal } | null+ saving: false,+ };++ function render() {+ if (destroyed) return;+ panel.innerHTML = `${renderCurrent()}${renderComposer()}${renderResult()}`;+ wire();+ }++ // ── Active policy card ──────────────────────────────────────────────────+ function renderCurrent() {+ if (!state.loaded) {+ return `<div class="awh-card"><div class="awh-card-h">Active policy</div><div class="awp-skel" style="width:50%"></div><div class="awp-skel"></div><div class="awp-skel" style="width:70%"></div></div>`;+ }+ if (state.current?.error) {+ return `<div class="awh-card"><div class="awh-card-h">Active policy</div><div class="awp-err">Couldn’t load your policy.<br>${esc(state.current.error)}</div><button class="awh-btn" type="button" data-act="reload">Retry</button></div>`;+ }+ const cur = state.current || {};+ const readback = Array.isArray(cur.readback) ? cur.readback : [];+ const caps = cur.numeric_limits || {};+ const capChips = `+ <div class="awp-caps" style="margin-top:10px;">+ <span class="awp-cap">Daily cap: ${caps.daily_usd != null ? esc(formatUsd(caps.daily_usd)) : 'none'}</span>+ <span class="awp-cap">Per-tx cap: ${caps.per_tx_usd != null ? esc(formatUsd(caps.per_tx_usd)) : 'none'}</span>+ <span class="awp-cap">${caps.frozen ? '🔒 frozen' : 'active'}</span>+ </div>+ <p class="awp-hint" style="margin:8px 0 0;">Numeric caps and the freeze switch are always enforced — edit them under Withdraw → Limits & Safety.</p>`;+ if (!readback.length) {+ return `<div class="awh-card">+ <div class="awh-card-h">Active policy</div>+ <p class="awp-intro" style="margin-bottom:0;">No plain-English rules yet. Your wallet is governed by its numeric caps below. Describe richer rules — like “only trade tokens at least a day old” — and they’ll be enforced on every spend.</p>+ ${capChips}+ </div>`;+ }+ return `<div class="awh-card">+ <div class="awh-card-h">Active policy · ${readback.length} rule${readback.length === 1 ? '' : 's'}</div>+ <ol class="awp-rules">${readback.map(ruleLi).join('')}</ol>+ ${capChips}+ <div class="awp-actions"><button class="awh-btn awh-btn--danger" type="button" data-act="clear">Remove all rules</button></div>+ </div>`;+ }++ function ruleLi(r) {+ const action = r.action || 'block';+ return `<li class="awp-rule"><span class="n">${r.n}</span><span class="tx">${esc(r.text || '')}</span><span class="tag ${esc(action)}">${esc(ACTION_TAG[action] || action)}</span></li>`;+ }++ // ── Composer card ───────────────────────────────────────────────────────+ function renderComposer() {+ return `<div class="awh-card">+ <div class="awh-card-h">Describe how your agent should spend</div>+ <p class="awp-intro">Write your safety rules in plain English. They’re compiled into deterministic rules and <strong>enforced by code on every spend</strong> — the AI only translates and explains, it never approves a payment.</p>+ <div class="awp-chips" role="group" aria-label="Starter policies">+ ${STARTERS.map((s) => `<button class="awp-chip" type="button" data-starter="${esc(s.key)}">${esc(s.label)}</button>`).join('')}+ </div>+ <label for="awp-ta" class="awp-hint" style="display:block;margin-bottom:6px;">Your rules</label>+ <textarea id="awp-ta" class="awp-ta" spellcheck="true" placeholder="e.g. Let it trade up to $50/day on tokens at least a day old, never spend my last 1 SOL, stop everything if a trade drops more than 30%, and only ever pay services I’ve used before.">${esc(state.draft)}</textarea>+ <div class="awp-actions">+ <button class="awh-btn awh-btn--primary" type="button" id="awp-compile" ${state.compiling ? 'disabled' : ''}>+ ${state.compiling ? '<span class="awp-spin"></span>Compiling…' : 'Compile & preview'}+ </button>+ <span class="awp-hint grow">Nothing is enforced until you review and save.</span>+ </div>+ </div>`;+ }++ // ── Compile result (readback + backtest) ────────────────────────────────+ function renderResult() {+ if (state.compileErr) {+ return `<div class="awh-card">+ <div class="awp-${state.compileErr.refusal ? 'warn' : 'err'}">${esc(state.compileErr.message || 'Could not compile that into a policy.')}</div>+ <p class="awp-hint">Try a concrete rule, e.g. “block any payment over $50”, “only trade tokens at least a day old”, or “never let SOL drop below 1”.</p>+ </div>`;+ }+ if (!state.compiled) return '';+ const c = state.compiled;+ const readback = Array.isArray(c.readback) ? c.readback : [];+ if (!readback.length) {+ return `<div class="awh-card"><div class="awp-warn">That didn’t produce any enforceable rules. Rephrase with a concrete limit.</div></div>`;+ }+ const assumptions = Array.isArray(c.assumptions) ? c.assumptions : [];+ return `+ <div class="awh-card">+ <div class="awh-card-h">Preview · ${readback.length} rule${readback.length === 1 ? '' : 's'} ${c.via === 'model' ? '' : '<span class="awp-hint">(parsed locally)</span>'}</div>+ <ol class="awp-rules">${readback.map(ruleLi).join('')}</ol>+ ${assumptions.length ? `<div class="awp-assume"><strong>Assumptions</strong><ul>${assumptions.map((a) => `<li>${esc(a)}</li>`).join('')}</ul></div>` : ''}+ </div>+ ${renderBacktest(c.backtest, c.synthetic)}+ <div class="awh-card">+ <div class="awp-actions">+ <button class="awh-btn awh-btn--primary" type="button" id="awp-save" ${state.saving ? 'disabled' : ''}>${state.saving ? '<span class="awp-spin"></span>Saving…' : 'Save policy'}</button>+ <button class="awh-btn" type="button" id="awp-discard" ${state.saving ? 'disabled' : ''}>Discard</button>+ <span class="awp-hint grow">Saving replaces your current natural-language rules. Numeric caps are unchanged.</span>+ </div>+ </div>`;+ }++ function renderBacktest(bt, synthetic) {+ // Real history present → show allowed/blocked summary, timeline, by-rule.+ if (bt && bt.total > 0) {+ const aPct = Math.round((bt.allowed / bt.total) * 100);+ const tl = (bt.items || []).slice(0, 120)+ .map((it) => `<span class="c ${it.denied ? 'blocked' : ''}" title="${esc(itemTitle(it))}"></span>`).join('');+ const byRule = (bt.by_rule || []).filter((r) => r.count > 0);+ return `<div class="awh-card">+ <div class="awh-card-h">Backtest · your last ${bt.total} spend${bt.total === 1 ? '' : 's'}</div>+ <div class="awp-bt-head">+ <span class="awp-bt-stat allow">${bt.allowed} allowed${bt.allowed_usd ? ` · ${esc(formatUsd(bt.allowed_usd))}` : ''}</span>+ <span class="awp-bt-stat ${bt.blocked ? 'block' : 'muted'}">${bt.blocked} blocked${bt.blocked_usd ? ` · ${esc(formatUsd(bt.blocked_usd))}` : ''}</span>+ </div>+ <div class="awp-bar" role="img" aria-label="${bt.allowed} of ${bt.total} allowed">+ <div class="a" style="width:${aPct}%"></div><div class="b" style="width:${100 - aPct}%"></div>+ </div>+ <div class="awp-tl" aria-hidden="true">${tl}</div>+ <p class="awp-hint">Each square is one past spend, newest first — green allowed, red blocked. Computed by the exact rules that will run live.</p>+ ${byRule.length ? `<ul class="awp-byrule">${byRule.map((r) => `<li><span class="lbl">${esc(r.label || ('Rule ' + ((r.ruleIndex ?? 0) + 1)))}</span><span class="ct">${r.count} blocked${r.usd ? ` · ${esc(formatUsd(r.usd))}` : ''}</span></li>`).join('')}</ul>` : ''}+ </div>`;+ }+ // No history → synthetic "how it handles common cases".+ const probes = Array.isArray(synthetic) ? synthetic : [];+ return `<div class="awh-card">+ <div class="awh-card-h">How it behaves</div>+ <p class="awp-hint" style="margin-top:0;">No spend history on ${esc(ctx.getNetwork())} yet, so here’s how this policy would handle some common cases:</p>+ ${probes.length ? `<ul class="awp-syn">${probes.map((p) => `<li><span>${esc(p.label)}</span><span class="v ${p.denied ? 'no' : 'ok'}">${p.denied ? (p.decision === 'freeze' ? 'Freeze' : p.decision === 'step_up' ? 'Ask me' : 'Blocked') : 'Allowed'}</span></li>`).join('')}</ul>` : '<p class="awp-empty">Once your agent starts spending, you’ll see a real backtest here.</p>'}+ </div>`;+ }++ function itemTitle(it) {+ const when = it.created_at ? new Date(it.created_at).toLocaleDateString() : '';+ const amt = it.usd != null ? formatUsd(it.usd) : (it.asset || '');+ const verb = it.denied ? `blocked — ${it.rule_text || 'policy'}` : 'allowed';+ return `${it.category || 'spend'} ${amt} · ${when} · ${verb}`;+ }++ // ── wiring ──────────────────────────────────────────────────────────────+ function wire() {+ panel.querySelector('[data-act="reload"]')?.addEventListener('click', () => { state.loaded = false; render(); load(); });+ panel.querySelector('[data-act="clear"]')?.addEventListener('click', clearPolicy);++ panel.querySelectorAll('[data-starter]').forEach((b) => b.addEventListener('click', () => {+ const s = STARTERS.find((x) => x.key === b.dataset.starter);+ if (!s) return;+ state.draft = s.text;+ const ta = panel.querySelector('#awp-ta');+ if (ta) { ta.value = s.text; ta.focus(); }+ }));++ const ta = panel.querySelector('#awp-ta');+ ta?.addEventListener('input', () => { state.draft = ta.value; });+ // Cmd/Ctrl+Enter compiles.+ ta?.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); compile(); }+ });+ panel.querySelector('#awp-compile')?.addEventListener('click', compile);+ panel.querySelector('#awp-save')?.addEventListener('click', save);+ panel.querySelector('#awp-discard')?.addEventListener('click', () => { state.compiled = null; state.compileErr = null; render(); });+ }++ async function load() {+ const res = await call(`${base('policy')}?network=${ctx.getNetwork()}`);+ if (destroyed) return;+ state.loaded = true;+ state.current = res.ok ? res.data : { error: res.message };+ if (res.ok && !state.draft && typeof res.data?.source_text === 'string') state.draft = res.data.source_text;+ render();+ }++ async function compile() {+ const text = (state.draft || '').trim();+ if (text.length < 3) { toast('Describe your rules first'); panel.querySelector('#awp-ta')?.focus(); return; }+ state.compiling = true; state.compiled = null; state.compileErr = null; render();+ const res = await call(`${base('policy')}?network=${ctx.getNetwork()}`, { method: 'POST', body: { op: 'compile', text } });+ if (destroyed) return;+ state.compiling = false;+ if (!res.ok) { state.compileErr = { message: res.message }; render(); return; }+ const d = res.data || {};+ if (!d.ok) { state.compileErr = { message: d.message || 'Could not interpret that safely.', refusal: !!d.refusal }; render(); return; }+ state.compiled = d;+ render();+ panel.querySelector('#awp-save')?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' });+ }++ async function save() {+ if (!state.compiled || state.saving) return;+ const newRules = state.compiled.policy?.rules || [];+ // Honest loosening guard: warn before removing protection the wallet has now.+ const curRules = state.current?.policy?.rules || [];+ if (protectiveCount(newRules) < protectiveCount(curRules)) {+ if (!confirm('This policy removes some of the protections you have now. Save anyway?')) return;+ }+ state.saving = true; render();+ const res = await call(`${base('policy')}?network=${ctx.getNetwork()}`, {+ method: 'PUT',+ body: { rules: newRules, english: state.compiled.source_text },+ });+ if (destroyed) return;+ state.saving = false;+ if (!res.ok) { state.compileErr = { message: res.message }; state.compiled = null; render(); toast('Could not save policy'); return; }+ state.current = { ...(state.current || {}), policy: res.data.policy, readback: res.data.readback, source_text: res.data.policy?.source_text, numeric_limits: state.current?.numeric_limits };+ state.compiled = null;+ toast('Policy saved — now enforced on every spend');+ render();+ }++ async function clearPolicy() {+ if (!confirm('Remove all natural-language rules? Your numeric caps and freeze switch stay in place.')) return;+ const res = await call(`${base('policy')}?network=${ctx.getNetwork()}`, { method: 'PUT', body: { rules: [], english: '' } });+ if (destroyed) return;+ if (!res.ok) { toast('Could not update policy'); return; }+ state.current = { ...(state.current || {}), policy: res.data.policy, readback: res.data.readback, source_text: '' };+ toast('Natural-language rules removed');+ render();+ }++ detachNet = ctx.onNetworkChange(() => { state.loaded = false; state.compiled = null; state.compileErr = null; render(); load(); });+ render();+ load();++ return {+ onShow() { if (!state.loaded) load(); },+ destroy() { destroyed = true; detachNet?.(); },+ };+ },+});diff --git a/src/agents/mood-engine.js b/src/agents/mood-engine.jsnew file mode 100644index 000000000..7c5f3f8b2--- /dev/null+++ b/src/agents/mood-engine.js@@ -0,0 +1,381 @@+// Mood engine — the live emotional state of the active agent.+//+// This is the running heart that the pure model (mood-model.js) only describes.+// It owns ONE mood per active agent, moves it on real bus signals, decays it+// toward baseline on a visibility-aware tick, persists it (server + local) for+// continuity across sessions, and emits `mood:changed` so the body re-expresses+// everywhere (mood-embodiment.js, the Companion, the inspector).+//+// Invariant: mood never moves without a real signal. The decay tick only relaxes+// toward baseline — it never injects emotion. There is no `Math.random()` and no+// timer that fabricates a mood; every move is traceable to a bus event or a real+// chat message scored by the deterministic lexicon.++import { agentBus, EVENTS } from './agent-bus.js';+import { onActiveAgentChange, getActiveAgentId, peekActiveAgent } from './active-agent.js';+import { apiFetch } from '../api.js';+import { scoreSentiment } from '../social/sentiment.js';+import {+ BASELINE,+ DEFAULT_SENSITIVITY,+ clampSensitivity,+ makeState,+ moodLabel,+ moodDistance,+ applySignal,+ decay,+ signalFromSentiment,+ SIGNALS,+} from './mood-model.js';++const LS_PREFIX = 'threews:mood:';+const TICK_MS = 3000; // decay cadence while the tab is visible+const EMIT_EPSILON = 0.015; // re-emit when the point drifts at least this far+const PERSIST_DEBOUNCE_MS = 2500;+const SIGNAL_LOG_MAX = 24; // recent signals kept for the inspector feed+const GESTURE_DISTANCE = 0.12; // transition this large plays an embodiment beat++const now = () => (typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now());+const isoNow = () => new Date().toISOString();++class MoodEngine {+ constructor() {+ this.agentId = null;+ this.state = makeState();+ this.sensitivity = DEFAULT_SENSITIVITY;+ this._lastEmitted = { ...this.state };+ this._lastTick = now();+ this._signals = []; // [{ source, label, valence, arousal, ts }]+ this._timer = null;+ this._persistTimer = null;+ this._pendingSignal = null; // last signal awaiting persist+ this._changeCbs = new Set();+ this._started = false;+ }++ // ── Lifecycle ────────────────────────────────────────────────────────────++ start() {+ if (this._started) return;+ this._started = true;++ // Track the active agent: load its mood, reset the feed, re-express.+ onActiveAgentChange((agent) => this._adoptAgent(agent?.id || null, agent));+ this._adoptAgent(getActiveAgentId(), peekActiveAgent());++ // Real signal producers from the shared bus.+ agentBus.on(EVENTS.MEMORY_ADDED, (p) => this._onMemoryAdded(p));+ agentBus.on(EVENTS.MEMORY_RECALLED, (p) => this._onMemoryRecalled(p));+ agentBus.on(EVENTS.MEMORY_FORGOTTEN, (p) => this._maybeSignal(p, 'memory:forgotten'));+ agentBus.on(EVENTS.DREAM_CREATED, (p) => this._maybeSignal(p, 'dream:insight', { weight: clamp01(p?.dream?.confidence ?? 0.7) }));+ agentBus.on(EVENTS.ACTION_TAKEN, (p) => this._onAction(p));+ agentBus.on(EVENTS.BRAIN_UPDATED, (p) => this._maybeSignal(p, 'brain:updated'));++ // Decay tick — paused when the tab is hidden so a backgrounded avatar+ // doesn't silently drain its mood; on return we catch up with real elapsed.+ if (typeof document !== 'undefined') {+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ this._lastTick = now();+ this._ensureTicking();+ } else {+ this._stopTicking();+ }+ });+ }+ this._ensureTicking();+ }++ _ensureTicking() {+ if (this._timer || (typeof document !== 'undefined' && document.visibilityState === 'hidden')) return;+ this._timer = setInterval(() => this._tick(), TICK_MS);+ }++ _stopTicking() {+ if (this._timer) clearInterval(this._timer);+ this._timer = null;+ }++ _adoptAgent(agentId, record) {+ this.agentId = agentId || null;+ const restored = this._restore(agentId, record);+ this.state = makeState(restored);+ this.sensitivity = clampSensitivity(restored.sensitivity);+ this._signals = [];+ this._lastTick = now();+ this._lastEmitted = { valence: NaN, arousal: NaN }; // force first emit+ this._emit(null); // resting expression+ }++ // Restore a persisted snapshot, decaying it by real elapsed time since it was+ // written so a mood that was hot last session is appropriately cooled now.+ _restore(agentId, record) {+ let snap = record?.meta?.mood || null;+ if (!snap && agentId) {+ try {+ const raw = localStorage.getItem(LS_PREFIX + agentId);+ if (raw) snap = JSON.parse(raw);+ } catch { /* storage unavailable */ }+ }+ if (!snap || !Number.isFinite(snap.valence)) {+ return { ...BASELINE, sensitivity: DEFAULT_SENSITIVITY };+ }+ let state = { valence: snap.valence, arousal: Number.isFinite(snap.arousal) ? snap.arousal : BASELINE.arousal };+ const updated = snap.updated_at || snap.updatedAt;+ if (updated) {+ const elapsed = Date.parse(isoNow()) - Date.parse(updated);+ if (Number.isFinite(elapsed) && elapsed > 0) state = decay(state, Math.min(elapsed, 86_400_000));+ }+ return { ...state, sensitivity: snap.sensitivity };+ }++ // ── Signal intake ────────────────────────────────────────────────────────++ /** Apply a catalogue (or explicit) signal, record it, and re-express. */+ ingestSignal(source, opts = {}) {+ if (!this._started) return;+ const def = typeof source === 'string' ? SIGNALS[source] : source;+ if (!def) return;+ const next = applySignal(this.state, source, { weight: opts.weight, sensitivity: this.sensitivity });+ const moved = moodDistance(next, this.state) > 0.0005;+ this.state = next;+ this._recordSignal({+ source: typeof source === 'string' ? source : 'custom',+ label: opts.sourceLabel || def.label || 'Signal',+ memoryId: opts.memoryId || null,+ });+ // Persist + emit only when something actually moved (sensitivity 0 = stoic).+ if (moved) {+ this._emit({ source: typeof source === 'string' ? source : 'custom', label: opts.sourceLabel || def.label, memoryId: opts.memoryId || null });+ this._schedulePersist({ source: typeof source === 'string' ? source : 'custom', label: opts.sourceLabel || def.label, memoryId: opts.memoryId || null });+ }+ }++ /**+ * Observe a real chat message and let its sentiment move the mood. Only the+ * active agent's own conversation counts. Sentiment comes from the+ * deterministic lexicon — real inference over the actual words, never random.+ */+ observeChat(agentId, text, role = 'user') {+ if (!this._started) return;+ if (agentId && this.agentId && agentId !== this.agentId) return;+ const clean = String(text || '').trim();+ if (clean.length < 2) return;+ const { score } = scoreSentiment([{ text: clean }]);+ const sig = signalFromSentiment(score);+ if (!sig) return;+ this.ingestSignal(sig.signal, {+ weight: sig.weight,+ sourceLabel: role === 'assistant' ? 'Its own words' : 'What you said',+ });+ }++ _onMemoryAdded(p) {+ if (!this._sameAgent(p)) return;+ const salience = clamp01(p?.memory?.salience ?? 0.5);+ this.ingestSignal('memory:added', { weight: 0.5 + salience * 0.5, memoryId: p?.memory?.id || null });+ }++ _onMemoryRecalled(p) {+ if (!this._sameAgent(p)) return;+ // A flicker of recognition — scale gently by how much was recalled.+ const n = Array.isArray(p?.memories) ? p.memories.length : 1;+ this.ingestSignal('memory:recalled', { weight: Math.min(1, 0.4 + n * 0.15) });+ }++ _onAction(p) {+ if (!this._sameAgent(p)) return;+ const a = p?.action || p || {};+ const ok = a.ok === true || a.success === true || a.outcome === 'success' || a.status === 'ok' || a.status === 'success';+ const bad = a.ok === false || a.success === false || a.error || a.outcome === 'failure' || a.status === 'error' || a.status === 'failed';+ if (ok) this.ingestSignal('action:success', { sourceLabel: a.title || a.label || SIGNALS['action:success'].label });+ else if (bad) this.ingestSignal('action:failure', { sourceLabel: a.title || a.label || SIGNALS['action:failure'].label });+ else this.ingestSignal('memory:recalled', { weight: 0.3, sourceLabel: 'Took an action' });+ }++ _maybeSignal(p, source, opts = {}) {+ if (!this._sameAgent(p)) return;+ this.ingestSignal(source, opts);+ }++ _sameAgent(p) {+ // Untagged events (no agentId) are assumed to be about the active agent.+ return !p?.agentId || !this.agentId || p.agentId === this.agentId;+ }++ // ── Tick / decay ──────────────────────────────────────────────────────────++ _tick() {+ const t = now();+ const dt = t - this._lastTick;+ this._lastTick = t;+ if (dt <= 0) return;+ this.state = decay(this.state, dt);+ this._maybeEmit(null);+ }++ // ── Emission ──────────────────────────────────────────────────────────────++ _maybeEmit(signal) {+ const prevLabel = moodLabel(this._lastEmitted.valence, this._lastEmitted.arousal).key;+ const curLabel = moodLabel(this.state.valence, this.state.arousal).key;+ if (curLabel !== prevLabel || moodDistance(this.state, this._lastEmitted) >= EMIT_EPSILON) {+ this._emit(signal);+ }+ }++ _emit(signal) {+ const mood = moodLabel(this.state.valence, this.state.arousal);+ const transitionDistance = moodDistance(this.state, this._lastEmitted);+ this._lastEmitted = { valence: this.state.valence, arousal: this.state.arousal };+ const payload = {+ agentId: this.agentId,+ valence: round3(this.state.valence),+ arousal: round3(this.state.arousal),+ mood,+ sensitivity: this.sensitivity,+ signal: signal ? { source: signal.source, label: signal.label } : null,+ // A large jump (a real spike) tells the body to play a one-shot beat.+ beat: signal && Number.isFinite(transitionDistance) && transitionDistance >= GESTURE_DISTANCE,+ ts: isoNow(),+ };+ if (this.agentId) {+ try { agentBus.emit(EVENTS.MOOD_CHANGED, payload); } catch { /* bus isolated */ }+ }+ for (const cb of this._changeCbs) { try { cb(payload); } catch { /* subscriber isolated */ } }+ this._mirrorLocal();+ }++ // ── Persistence ───────────────────────────────────────────────────────────++ _recordSignal({ source, label, memoryId }) {+ this._signals.unshift({+ source,+ label,+ memoryId: memoryId || null,+ valence: round3(this.state.valence),+ arousal: round3(this.state.arousal),+ mood: moodLabel(this.state.valence, this.state.arousal).key,+ ts: isoNow(),+ });+ if (this._signals.length > SIGNAL_LOG_MAX) this._signals.length = SIGNAL_LOG_MAX;+ }++ _mirrorLocal() {+ if (!this.agentId) return;+ try {+ localStorage.setItem(LS_PREFIX + this.agentId, JSON.stringify({+ valence: round3(this.state.valence),+ arousal: round3(this.state.arousal),+ label: moodLabel(this.state.valence, this.state.arousal).key,+ sensitivity: this.sensitivity,+ updated_at: isoNow(),+ }));+ } catch { /* storage full / unavailable — non-fatal */ }+ }++ _schedulePersist(signal) {+ this._pendingSignal = signal;+ if (!this.agentId || !isUuid(this.agentId)) return; // guest/local-only mood+ if (this._persistTimer) clearTimeout(this._persistTimer);+ this._persistTimer = setTimeout(() => this._flushPersist(), PERSIST_DEBOUNCE_MS);+ }++ async _flushPersist() {+ this._persistTimer = null;+ const signal = this._pendingSignal;+ this._pendingSignal = null;+ if (!this.agentId || !isUuid(this.agentId) || !signal) return;+ try {+ await apiFetch(`/api/agents/${this.agentId}/mood`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ valence: round3(this.state.valence),+ arousal: round3(this.state.arousal),+ label: moodLabel(this.state.valence, this.state.arousal).key,+ sensitivity: this.sensitivity,+ source: signal.source,+ source_label: signal.label,+ source_memory_id: signal.memoryId || undefined,+ }),+ });+ } catch { /* not the owner / offline — local mirror already keeps continuity */ }+ }++ // ── Public surface ─────────────────────────────────────────────────────────++ getState() { return { valence: this.state.valence, arousal: this.state.arousal }; }+ getMood() { return moodLabel(this.state.valence, this.state.arousal); }+ getSensitivity() { return this.sensitivity; }+ recentSignals() { return this._signals.slice(); }++ /** Snapshot for a freshly-mounted surface (inspector, embodiment binder). */+ snapshot() {+ return {+ agentId: this.agentId,+ valence: round3(this.state.valence),+ arousal: round3(this.state.arousal),+ mood: this.getMood(),+ sensitivity: this.sensitivity,+ ts: isoNow(),+ };+ }++ /** Set emotional sensitivity (0 stoic … 1 expressive); persists as a setting. */+ async setSensitivity(value) {+ this.sensitivity = clampSensitivity(value);+ this._mirrorLocal();+ this._emit(null);+ if (this.agentId && isUuid(this.agentId)) {+ try {+ await apiFetch(`/api/agents/${this.agentId}/mood/sensitivity`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ sensitivity: this.sensitivity }),+ });+ } catch { /* local mirror still holds the setting */ }+ }+ return this.sensitivity;+ }++ /** Fetch persisted history (for the inspector sparkline). */+ async loadHistory() {+ if (!this.agentId || !isUuid(this.agentId)) return [];+ try {+ const res = await apiFetch(`/api/agents/${this.agentId}/mood`, { credentials: 'include' });+ if (!res.ok) return [];+ const data = await res.json();+ return Array.isArray(data.history) ? data.history : [];+ } catch { return []; }+ }++ onChange(cb) {+ if (typeof cb !== 'function') return () => {};+ this._changeCbs.add(cb);+ try { cb(this.snapshot()); } catch { /* isolate */ }+ return () => this._changeCbs.delete(cb);+ }+}++function clamp01(n) { return Math.max(0, Math.min(1, Number(n) || 0)); }+function round3(n) { return Math.round((Number(n) || 0) * 1000) / 1000; }++// Singleton across the app (survives HMR + duplicate module graphs).+const GLOBAL_KEY = '__threewsMoodEngine';+export const moodEngine =+ (typeof globalThis !== 'undefined' && globalThis[GLOBAL_KEY]) || new MoodEngine();+if (typeof globalThis !== 'undefined' && !globalThis[GLOBAL_KEY]) {+ globalThis[GLOBAL_KEY] = moodEngine;+}++// Auto-start in the browser so any page that imports the engine (or the+// embodiment binder) gets a live mood without extra wiring.+if (typeof window !== 'undefined') {+ moodEngine.start();+ window.__moodEngine = moodEngine;+}++export default moodEngine;diff --git a/src/proof-of-custody/ui.js b/src/proof-of-custody/ui.jsindex 4782dace2..1aa0eeca0 100644--- a/src/proof-of-custody/ui.js+++ b/src/proof-of-custody/ui.js@@ -34,6 +34,7 @@ function fmtTime(iso) {* @param {object} [args.ctx] optional hub ctx (toast, copyToClipboard)*/export function renderProofUI(panel, { proof, verify, shareBase = '/proof', origin = '', ctx = {} }) {+ injectProofStyle();if (!proof || proof.included === false) {panel.innerHTML = notYetState(proof);panel.querySelector('[data-reload]')?.addEventListener('click', () => location.reload());@@ -134,24 +135,29 @@ export function renderProofUI(panel, { proof, verify, shareBase = '/proof', origfunction renderShare() {const wrap = panel.querySelector('[data-share]');if (!wrap) return;- const url = `${origin}${shareBase}?agent=${encodeURIComponent(proof.leaf.agentId)}`;- const embed = `<a href="${url}" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;gap:6px;font:600 12px system-ui;color:#4ade80;text-decoration:none;padding:5px 11px;border:1px solid #4ade8055;border-radius:999px;background:#4ade801a">✓ Custody verified on-chain · three.ws</a>`;+ // The public, re-verifiable artifact is the platform integrity page — anyone+ // can confirm the latest root on-chain there without auth. Per-wallet leaves+ // stay owner-gated, so the shared badge points at /integrity, not the private+ // per-wallet proof.+ const publicUrl = `${origin}/integrity`;+ const ownUrl = `${esc(shareBase)}?agent=${encodeURIComponent(proof.leaf.agentId)}`;+ const embed = `<a href="${publicUrl}" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;gap:6px;font:600 12px system-ui;color:#4ade80;text-decoration:none;padding:5px 11px;border:1px solid #4ade8055;border-radius:999px;background:#4ade801a">✓ Custody verified on-chain · three.ws</a>`;wrap.hidden = false;wrap.className = 'awh-proof-card';wrap.innerHTML = `<h2>Show it off</h2>- <p class="awh-proof-lead">Your custody is provable — share it. Anyone can re-verify from the link, in their own browser.</p>+ <p class="awh-proof-lead">Your custody is provable. The badge links to the public integrity page, where anyone can re-verify the platform's on-chain root in their own browser.</p><div class="awh-proof-actions"><span class="awh-proof-badge">Custody verified on-chain</span>- <button class="awh-proof-btn ghost" type="button" data-copy-link>Copy verify link</button>+ <button class="awh-proof-btn ghost" type="button" data-copy-link>Copy integrity link</button><button class="awh-proof-btn ghost" type="button" data-copy-embed>Copy badge embed</button>- <a class="awh-proof-btn ghost" href="${esc(shareBase)}?agent=${encodeURIComponent(proof.leaf.agentId)}" target="_blank" rel="noopener">Open verifier page ↗</a>+ <a class="awh-proof-btn ghost" href="${ownUrl}" target="_blank" rel="noopener">Open my verifier ↗</a></div><div class="awh-proof-share"><textarea class="awh-proof-embed" readonly rows="2" aria-label="Badge embed HTML">${esc(embed)}</textarea></div>`;- wrap.querySelector('[data-copy-link]')?.addEventListener('click', () => copy(url, 'Verify link copied'));+ wrap.querySelector('[data-copy-link]')?.addEventListener('click', () => copy(publicUrl, 'Integrity link copied'));wrap.querySelector('[data-copy-embed]')?.addEventListener('click', () => copy(embed, 'Badge embed copied'));}diff --git a/src/proof-of-custody/verifier.js b/src/proof-of-custody/verifier.jsindex 04d91541d..10c02c3c0 100644--- a/src/proof-of-custody/verifier.js+++ b/src/proof-of-custody/verifier.js@@ -80,6 +80,28 @@ function extractMemo(tx) {return null;}+/**+ * Read the committed Merkle root straight off the chain for an anchor signature.+ * Public + dependency-light — the /integrity page uses it to let anyone confirm+ * the platform's latest root on-chain without trusting our API.+ *+ * @returns {Promise<{ epoch: number, root: string, walletCount: number|null, endpoint: string }>}+ */+export async function readOnchainAnchor(signature, network, opts = {}) {+ const fetchTx = opts.fetchTx || fetchTransaction;+ const { tx, endpoint } = await fetchTx(signature, network);+ const memo = extractMemo(tx);+ if (!memo) throw new Error('no memo found in the anchor transaction');+ const payload = JSON.parse(memo);+ if (payload.kind !== 'threews.custody.v1') throw new Error('anchor memo is not a custody attestation');+ return {+ epoch: Number(payload.epoch),+ root: String(payload.root || '').toLowerCase(),+ walletCount: payload.wallet_count != null ? Number(payload.wallet_count) : null,+ endpoint,+ };+}+/*** Verify an inclusion proof end-to-end.*diff --git a/vercel.json b/vercel.jsonindex 993b00761..b02897820 100644--- a/vercel.json+++ b/vercel.json@@ -1965,6 +1965,10 @@"src": "/api/agents/([^/]+)/brain(/.*)?","dest": "/api/agents/[id]"},+ {+ "src": "/api/agents/([^/]+)/mood(/.*)?",+ "dest": "/api/agents/[id]"+ },{"src": "/api/agents/([^/]+)/eth-vanity/([^/]+)","dest": "/api/agents/[id]"@@ -4211,6 +4215,10 @@"path": "/api/cron/three-holders-snapshot","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/recompute-reputation",+ "schedule": "*/10 * * * *"+ },{"path": "/api/cron/custody-attest","schedule": "17 */6 * * *"diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex ea792ff35..81a935e73 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -104,23 +104,35 @@ function bn(ctx, v) {// (api/_lib/agent-trade-guards.js). Returns { blocked, reason }. Never throws:// the sniper's own lamports caps stay the hard backstop, so a pricing or DB// hiccup here degrades to "allow" rather than stalling the trader.-async function enforceSharedSpendPolicy(agentId, network, perTradeLamports) {+async function enforceSharedSpendPolicy(agentId, network, perTradeLamports, { holderRef = null, target = null } = {}) {try {const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;const limits = getSpendLimits(row?.meta);- // No USD ceiling set → nothing to price or enforce; skip the price call.- if (limits.daily_usd == null && limits.per_tx_usd == null) return { blocked: false };+ // Gate when there's something to enforce: a USD ceiling, or least-privilege+ // mode (require_capabilities) which makes a covering scoped session key+ // mandatory for every autonomous spend. Otherwise skip — keep the hot path+ // price-call- and query-free.+ const needGate = limits.require_capabilities || limits.daily_usd != null || limits.per_tx_usd != null;+ if (!needGate) return { blocked: false };let usdValue = null;try {usdValue = await lamportsToUsd(perTradeLamports);} catch {- // Can't price the SOL spend right now — don't block (lamports caps hold).- return { blocked: false };+ // Can't price the SOL spend right now. If a capability is REQUIRED we still+ // enforce scope (action/target/expiry/revoked) with a null USD value — only+ // the per-use/aggregate USD metering is skipped. If capabilities aren't+ // required, the USD caps can't bite, so don't block (lamports caps hold).+ if (!limits.require_capabilities) return { blocked: false };}- await enforceSpendLimit({ agentId, limits, category: 'snipe', usdValue, network });- return { blocked: false };+ // Pass the strategy as the capability holder + the mint as the spend target so+ // a strategy-scoped, mint-restricted session key is resolved + enforced here.+ const res = await enforceSpendLimit({+ agentId, limits, category: 'snipe', usdValue, network,+ capabilityHolderRef: holderRef, target,+ });+ return { blocked: false, capabilityId: res?.capabilityId || null };} catch (err) {- if (err instanceof SpendLimitError) return { blocked: true, reason: 'spend_limit' };+ if (err instanceof SpendLimitError) return { blocked: true, reason: err.code || 'spend_limit' };log.warn?.('spend_policy_check_failed', { agent: agentId, message: err?.message });return { blocked: false };}@@ -133,13 +145,13 @@ async function enforceSharedSpendPolicy(agentId, network, perTradeLamports) {// must finish the write before returning so a rapid next snipe sees this spend// against the ceiling rather than racing an unwritten record. Prices the SOL// spend best-effort; a pricing hiccup records lamports with a null USD value.-async function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode, mint }) {+async function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode, mint, capabilityId = null }) {try {let usd = null;try { usd = await lamportsToUsd(lamports); } catch { usd = null; }await recordSpend({agentId, userId, category: 'snipe', network, asset: 'SOL',- amountLamports: lamports, usd,+ amountLamports: lamports, usd, capabilityId,signature: signature && signature !== 'SIMULATED' ? signature : null,status: mode === 'live' ? 'confirmed' : 'ok',meta: { mint, mode },@@ -235,8 +247,11 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {// has actually set a USD ceiling, so the hot snipe path stays price-call-// free otherwise. Pricing/DB hiccups never block — the lamports caps above// remain the hard backstop.- const policy = await enforceSharedSpendPolicy(strat.agent_id, cfg.network, perTrade);+ const policy = await enforceSharedSpendPolicy(strat.agent_id, cfg.network, perTrade, {+ holderRef: String(strat.id), target: mint.mint,+ });if (policy.blocked) return skip(tag, policy.reason);+ const spendCapabilityId = policy.capabilityId || null;// 4. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.const claimed = await sql`@@ -374,7 +389,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {`;log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });- await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint });+ await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint, capabilityId: spendCapabilityId });await recordSnipeDecision({strat, network: cfg.network, mint, posId, sig, mode: cfg.mode,priceImpactPct: Number(quote.priceImpactPct), firewall: firewallSnapshot, perTradeLamports: perTrade,