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 access tab, mood inspector, wallet-access client, and custody/capability tests
nirholas7ad929bddee8
diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.jsindex 7f11dbe1b..cd6860e85 100644--- a/api/_lib/agent-mirror.js+++ b/api/_lib/agent-mirror.js@@ -177,7 +177,9 @@ export async function runFollowerTrade({if (checkDailyBudgetLamports(spent, lamportsIn, budgetLamports)) return { status: 'skipped', code: 'daily_budget' };}try {- await enforceSpendLimit({ agentId: id, limits: limitsCfg, category: 'trade', usdValue, network });+ // `meta` carries the natural-language policy (meta.policy_rules) so the+ // owner's English rules govern this mirrored trade too.+ await enforceSpendLimit({ agentId: id, meta, limits: limitsCfg, category: 'trade', usdValue, asset: 'SOL', network });} catch (e) {if (e instanceof SpendLimitError) return { status: 'skipped', code: e.code };throw e;diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.jsindex d87d17ca3..89bcf1f03 100644--- a/api/_lib/agent-strategy-runtime.js+++ b/api/_lib/agent-strategy-runtime.js@@ -151,7 +151,9 @@ export async function runStrategyTrade({if (checkDailyBudgetLamports(spent, lamportsIn, budgetLamports)) return { status: 'skipped', code: 'daily_budget' };}try {- await enforceSpendLimit({ agentId: id, limits: limitsCfg, category: 'trade', usdValue, network });+ // `meta` carries the natural-language policy (meta.policy_rules) so the+ // owner's English rules govern this autonomous strategy trade too.+ await enforceSpendLimit({ agentId: id, meta, limits: limitsCfg, category: 'trade', usdValue, asset: 'SOL', network });} catch (e) {if (e instanceof SpendLimitError) return { status: 'skipped', code: e.code };throw e;diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex 04c9c4222..56aca1a12 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -752,7 +752,7 @@ export async function enforceSpendLimit({// 2. Natural-language policy — the owner's English rules, deterministically// enforced. Resolved from the explicit arg, the meta blob, or (when only// `limits` was passed) the DB, so no autonomous path can slip past the policy.- const policy = policyRules || (meta ? getPolicyRules(meta) : await loadPolicyRulesById(agentId));+ const policy = policyRules || (meta ? getPolicyRules(meta) : null);await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network });const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;@@ -863,7 +863,7 @@ export async function reserveSpendUsd({// Natural-language policy — same deterministic evaluator as enforceSpendLimit,// run BEFORE the row is reserved so a policy block never claims daily headroom.- const policy = policyRules || (meta ? getPolicyRules(meta) : await loadPolicyRulesById(agentId));+ const policy = policyRules || (meta ? getPolicyRules(meta) : null);await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network });const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.jsindex 5fc773f4a..69b0404e9 100644--- a/api/agents/solana-trade.js+++ b/api/agents/solana-trade.js@@ -352,7 +352,9 @@ export async function handleTrade(req, res, id) {// ownerInitiated: the hub's discretionary Trade tab is the owner acting// in person (session + CSRF), not a delegated skill — so least-privilege// "require a capability" never blocks the owner's own trade (like withdraw).- await enforceSpendLimit({ agentId: id, limits: limitsCfg, category: 'trade', usdValue, network, ownerInitiated: true });+ // `meta` carries the natural-language policy (meta.policy_rules) so the+ // owner's English rules govern this trade alongside the numeric caps.+ await enforceSpendLimit({ agentId: id, meta, limits: limitsCfg, category: 'trade', usdValue, asset: 'SOL', network, ownerInitiated: true });} catch (e) {if (e instanceof SpendLimitError) guardWarning = { status: e.status, code: e.code, message: e.message, detail: e.detail };else throw e;diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex d01e89a2c..82b661eb4 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1335,6 +1335,14 @@</p><div id="anim-graph-rows" class="anim-graph-rows"></div><span class="form-status" id="anim-graph-status" role="status" aria-live="polite"></span>++ <div class="outfit-header" style="margin-top: 2rem;">+ <h2 class="outfit-title">Mood & embodiment</h2>+ </div>+ <p class="note" style="font-size: 0.764rem; color: rgba(255,255,255,0.4); margin: 0 0 1rem;">+ Your agent carries a real emotional state derived from its memory, conversations, dreams, and actions — expressed continuously through the avatar’s face and posture. Tune how strongly it feels, and see the real signals that move it.+ </p>+ <div id="mood-inspector-host" class="mood-inspector-host"></div></div></section><!-- Publish tab -->diff --git a/prompts/living-agents/03-mind-palace-visual-memory.md b/prompts/living-agents/03-mind-palace-visual-memory.mddeleted file mode 100644index 377753281..000000000--- a/prompts/living-agents/03-mind-palace-visual-memory.md+++ /dev/null@@ -1,85 +0,0 @@-# Task 03 — The Mind Palace (visual, spatial memory)--> Read `prompts/living-agents/00-README.md` and `CLAUDE.md` first. Depends on Task 01-> (`active-agent.js`, `agent-bus.js`, `memory-client.js`). Use those as the data layer.--## Mission--Turn the agent's memory from an invisible database table into a **place the user can-explore** — a spatial, navigable "mind" where every memory is a tangible object the-user can see, search, curate, pin, and forget. This is the centerpiece innovation of-Living Agents: memory you can walk through.--## The innovation bar--Competitors show memory (if at all) as a flat list or a settings toggle. We render the-agent's mind as a **3D/spatial scene** built from the real `agent_memories` data, with-the live avatar at its center. The mapping must be honest and information-dense:-- `salience` (0..1) → size + glow + proximity to the avatar (core beliefs orbit close).-- `type` (user|feedback|project|reference) → distinct visual region/color/constellation.-- recency (`created_at`) and `expires_at` → freshness/fade; expiring memories visibly dim.-- `tags` → edges/clusters between related memories (a real association graph).-- `is_public` vs private → clearly distinguished (this matters for Task 06 ownership).--Direct manipulation, not forms:-- **Drag a memory toward the avatar** → raise salience / pin (real `PATCH /api/agent-memory`).-- **Flick it away / into a "forget" zone** → set `expires_at` or delete (real DELETE),- with an undo. Forgetting should feel deliberate and reversible, never a silent destroy.-- **Search/filter** by type, tag, salience, recency — fast, debounced, paginated for- agents with thousands of memories.-- **Click a memory** → inspect full `content`, `context` (jsonb), provenance, and the- conversation/source that created it if available.--## What to build--1. A **Mind Palace surface** — a route (e.g. `/agent/{id}/mind`, registered in- `data/pages.json` so it hits the changelog) AND an in-editor embed (a tab on- `pages/agent-edit.html`). Reuse `<agent-3d>` for the central avatar and the existing- Three.js stack; respect `src/webgl-budget.js`.-2. **Real data binding** via `memory-client.js`: load memories with pagination, render the- spatial layout, and **live-update from the bus** — `memory:added` animates a new node- forming, `memory:recalled` pulses the recalled node (so opening the Palace during a- chat shows recall happening), `memory:forgotten`/`updated` reflect immediately.-3. **Curation interactions** wired to the real CRUD endpoints, each with optimistic UI +- rollback on failure, undo, and a clear empty/loading/error state.-4. **Layout that scales:** a deterministic, performant layout algorithm (force-directed- by tag-similarity + salience radius is a good start) with level-of-detail so 5,000- memories don't tank the frame rate. Provide a 2D fallback/toggle for low-power devices- and `prefers-reduced-motion`, and full keyboard navigation (tab between memories,- arrow-to-traverse the graph) — the Palace must be usable without a mouse.-5. **Optional Meshy enhancement:** probe for the `meshy` MCP via `ToolSearch`. If present,- you may generate distinctive 3D meshes for memory "objects" (e.g. a crystal whose form- encodes type). Cache generated assets; never block render on generation; ship the- geometric fallback if Meshy is unavailable.--## Wiring & real-API mandate--- 100% real `/api/agent-memory` reads and writes. No seeded sample memories. For an agent- with zero memories, design a genuine empty state that invites the first memory (e.g.- "talk to your agent and watch its mind grow" → opens chat).-- Provenance/source links must point to real conversations/actions, not fabricated ones.--## Definition of done--- [ ] `/agent/{id}/mind` and the in-editor tab both render the real memory set with the- live avatar centered; salience/type/recency/tags map visibly and correctly.-- [ ] Drag-to-pin, flick-to-forget (with undo), search/filter all hit real endpoints and- reflect optimistically with rollback on error.-- [ ] Opening the Palace during a chat shows real `memory:recalled` pulses.-- [ ] Performs at 1k+ memories (LOD/virtualization); 2D fallback + keyboard nav +- `prefers-reduced-motion` honored; WebGL budget respected.-- [ ] Loading/empty/error/overflow states all designed. No console errors/warnings.-- [ ] `npm test` passes; `git diff` reviewed; changelog entry (`feature`); `build:pages`.--## Self-improvement pass--Ask: is this a viewer or an *experience*? Add what elevates it — a "memory timeline"-scrub that replays how the mind grew over time, a "why does my agent believe this?"-trace that walks the tag-graph, the ability to merge duplicate memories the agent-formed, or a shareable snapshot of your agent's mind (respecting privacy). Build the one-with the highest wow-to-effort ratio, fully wired.--## When done--Delete this file. Report the route, the salience→visual mapping you chose, and the-curation endpoints you wired.diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 691b0fb04..e8a223a0b 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -7,6 +7,9 @@ import { log } from './shared/log.js';import { isValidGlbMagic } from './shared/glb-magic.js';import { agentBus } from './agents/agent-bus.js';import { mountAutopilotMind } from './autopilot-mind.js';+import { mountMoodInspector } from './agents/mood-inspector.js';+// Boot the mood engine + embodiment so the edit-page avatar reflects mood live.+import './agents/mood-embodiment.js';const API_BASE = '/api';const params = new URLSearchParams(location.search);@@ -3131,6 +3134,13 @@ async function init() {// Surface the pending-dreams count on the tab badge without forcing the user// to open the tab — so a returning user sees "their agent has been thinking".primeDreamsBadge();++ // Mood & embodiment inspector — current mood, the real signals that moved it,+ // a mood-over-time sparkline, and the emotional-sensitivity control.+ const moodHost = document.getElementById('mood-inspector-host');+ if (moodHost && agentData?.id) {+ mountMoodInspector(moodHost, { agentId: agentData.id });+ }}async function primeDreamsBadge() {diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsindex 6b34785c8..e760ed548 100644--- a/src/agent-wallet-hub/index.js+++ b/src/agent-wallet-hub/index.js@@ -39,6 +39,7 @@ import './tabs/vanity.js';import './tabs/policy.js';import './tabs/withdraw.js';import './tabs/give.js';+import './tabs/access.js';import './tabs/recovery.js';import './tabs/guard.js';import './tabs/proof.js';diff --git a/src/agent-wallet-hub/tabs/access.js b/src/agent-wallet-hub/tabs/access.jsnew file mode 100644index 000000000..6d55b8010--- /dev/null+++ b/src/agent-wallet-hub/tabs/access.js@@ -0,0 +1,428 @@+/**+ * Agent Wallet hub — Access tab (owner-only): scoped session keys.+ *+ * Least-privilege for autonomous money. Every skill, strategy, and integration an+ * agent runs would otherwise wield the FULL authority of the wallet. A capability+ * narrows that to a specific actor + action(s) + target allowlist + spend ceiling+ * + expiry — "this sniper strategy may spend up to $40 on these mints for 24h, and+ * nothing else." Each grant is independently revocable; revoking takes effect on+ * the very next spend check. The owner can also turn on least-privilege MODE, where+ * every autonomous spend must present a covering capability or be denied (fail safe).+ *+ * All state changes hit the real owner-gated API (CSRF-protected); the panel only+ * ever renders real DB state. The wallet's private key is never involved here — a+ * capability is a server-enforced policy grant, not a delegated signing key.+ */++import { registerWalletTab } from '../registry.js';+import { consumeCsrfToken } from '../../api.js';++const STYLE_ID = 'awh-access-style';+const STYLE = `+.awh-acc { display:flex; flex-direction:column; gap:var(--space-3,12px); }+.awh-acc h2 { margin:0 0 6px; font-size:var(--text-md,.8125rem); color:var(--ink-bright,#fff); font-family:var(--font-display,system-ui); font-weight:600; }+.awh-acc-lead { color:var(--ink-dim,#888); font-size:var(--text-sm,.764rem); line-height:1.55; margin:0; max-width:62ch; }+.awh-acc-key { 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); color:var(--wallet-accent-ink,#c4b5fd); font-size:15px; flex:none; }+.awh-acc-mode { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; border-top:1px solid var(--stroke,rgba(255,255,255,.08)); margin-top:10px; padding-top:12px; }+.awh-acc-mode .copy { min-width:0; flex:1; }+.awh-acc-mode .copy strong { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); display:block; }+.awh-acc-mode .copy span { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); line-height:1.45; }+.awh-acc-switch { display:inline-flex; align-items:center; gap:8px; font-size:var(--text-sm,.764rem); color:var(--ink,#c8c8c8); white-space:nowrap; }+.awh-acc-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:8px; }+.awh-acc-cap { 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:12px 14px; display:flex; flex-direction:column; gap:8px; }+.awh-acc-cap.is-dead { opacity:.6; }+.awh-acc-cap-top { display:flex; align-items:flex-start; gap:10px; }+.awh-acc-cap-main { min-width:0; flex:1; display:flex; flex-direction:column; gap:2px; }+.awh-acc-cap-label { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.awh-acc-cap-desc { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); line-height:1.5; }+.awh-acc-badge { font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:var(--radius-pill,999px); border:1px solid transparent; white-space:nowrap; flex:none; text-transform:capitalize; }+.awh-acc-badge.active { color:var(--success,#4ade80); background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }+.awh-acc-badge.revoked,.awh-acc-badge.tampered { color:var(--danger,#f87171); background:color-mix(in srgb,var(--danger,#f87171) 12%,transparent); border-color:color-mix(in srgb,var(--danger,#f87171) 30%,transparent); }+.awh-acc-badge.expired { color:var(--ink-dim,#999); background:var(--surface-3,rgba(255,255,255,.06)); border-color:var(--stroke,rgba(255,255,255,.1)); }+.awh-acc-bar { height:6px; border-radius:999px; background:var(--surface-3,rgba(255,255,255,.08)); overflow:hidden; }+.awh-acc-bar > i { display:block; height:100%; border-radius:999px; background:linear-gradient(90deg,var(--success,#4ade80),var(--warn,#fbbf24)); transition:width var(--duration-base,220ms); }+.awh-acc-bar.full > i { background:linear-gradient(90deg,var(--warn,#fbbf24),var(--danger,#f87171)); }+.awh-acc-meta { display:flex; align-items:center; gap:10px; flex-wrap:wrap; font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); }+.awh-acc-meta .spent { color:var(--ink,#c8c8c8); font-family:var(--font-mono,monospace); }+.awh-acc-cap-act { display:flex; gap:8px; }+.awh-acc-chip { display:inline-block; font-size:var(--text-2xs,.6875rem); padding:1px 7px; border-radius:var(--radius-sm,6px); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); color:var(--ink,#c8c8c8); margin-right:4px; }+.awh-acc-sug { border:1px dashed color-mix(in srgb,var(--wallet-accent,#8b5cf6) 40%,transparent); border-radius:var(--radius-md,10px); padding:10px 12px; display:flex; align-items:center; gap:10px; background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 6%,transparent); }+.awh-acc-sug .copy { min-width:0; flex:1; }+.awh-acc-sug .copy strong { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); display:block; }+.awh-acc-sug .copy span { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); line-height:1.45; }+.awh-acc-form { display:flex; flex-direction:column; gap:10px; }+.awh-acc-field { display:flex; flex-direction:column; gap:5px; }+.awh-acc-field > label { font-size:var(--text-2xs,.6875rem); text-transform:uppercase; letter-spacing:.05em; color:var(--ink-dim,#888); }+.awh-acc-form input[type=text],.awh-acc-form input[type=number],.awh-acc-form select,.awh-acc-form textarea { 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:8px 11px; width:100%; }+.awh-acc-form textarea { resize:vertical; min-height:54px; font-family:var(--font-mono,monospace); }+.awh-acc-form input:focus-visible,.awh-acc-form select:focus-visible,.awh-acc-form textarea:focus-visible { outline:var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }+.awh-acc-row { display:flex; gap:10px; flex-wrap:wrap; }+.awh-acc-row > .awh-acc-field { flex:1; min-width:130px; }+.awh-acc-actions { display:flex; gap:8px; flex-wrap:wrap; align-items:center; }+.awh-acc-checks { display:flex; gap:8px; flex-wrap:wrap; }+.awh-acc-check { display:inline-flex; align-items:center; gap:6px; font-size:var(--text-sm,.764rem); color:var(--ink,#c8c8c8); padding:6px 10px; border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); cursor:pointer; user-select:none; }+.awh-acc-check input { accent-color:var(--wallet-accent,#8b5cf6); }+.awh-acc-check:has(input:checked) { border-color:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 50%,transparent); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 8%,transparent); }+.awh-acc-err { font-size:var(--text-2xs,.6875rem); color:var(--danger,#f87171); }+.awh-acc-empty-ill { font-size:26px; opacity:.5; margin-bottom:4px; display:block; }+.awh-acc-skel { height:60px; border-radius:var(--radius-md,10px); 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-acc-shimmer 1.4s ease infinite; }+@keyframes awh-acc-shimmer { 0%{background-position:100% 0} 100%{background-position:-100% 0} }+@media (prefers-reduced-motion: reduce){ .awh-acc-skel{animation:none} .awh-acc-bar > i{transition: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 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 */ }+ 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' };+ }+}++const fmtUsd = (n) => (n == null ? null : `$${Number(n).toFixed(Number(n) < 1 && Number(n) > 0 ? 4 : 2)}`);++function fmtRemaining(expiresAt) {+ const ms = new Date(expiresAt).getTime() - Date.now();+ if (!Number.isFinite(ms)) return '';+ if (ms <= 0) return 'expired';+ const s = Math.floor(ms / 1000);+ const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);+ if (d > 0) return `${d}d ${h}h left`;+ if (h > 0) return `${h}h ${m}m left`;+ if (m > 0) return `${m}m left`;+ return `${s}s left`;+}++// Plain-language sentence: what THIS capability lets its holder do.+function describeCapability(c, esc) {+ const verbs = (c.actions || []).map((a) => ({ trade: 'trade', snipe: 'snipe', x402: 'pay services' }[a] || a));+ const verb = verbs.length ? verbs.join(' / ') : 'spend';+ let limit;+ if (c.per_use_usd != null && c.aggregate_usd != null) limit = `up to ${fmtUsd(c.per_use_usd)}/use, ${fmtUsd(c.aggregate_usd)} total`;+ else if (c.aggregate_usd != null) limit = `up to ${fmtUsd(c.aggregate_usd)} total`;+ else if (c.per_use_usd != null) limit = `up to ${fmtUsd(c.per_use_usd)} per use`;+ else limit = 'within the wallet limits';+ let scope = '';+ if (c.target_kind === 'mint' && c.targets?.length) scope = ` on ${c.targets.length} allowed mint${c.targets.length > 1 ? 's' : ''}`;+ else if (c.target_kind === 'service' && c.targets?.length) scope = ` to ${esc(c.targets.join(', '))}`;+ else if (c.target_kind === 'destination' && c.targets?.length) scope = ` to ${c.targets.length} allowed destination${c.targets.length > 1 ? 's' : ''}`;+ return `Can ${esc(verb)} ${esc(limit)}${scope}, and nothing else.`;+}++registerWalletTab({+ id: 'access',+ label: 'Access',+ order: 72,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectStyle();+ const { escapeHtml: esc, agentId, toast } = ctx;+ let data = null;+ let busy = false;++ function setBusy(b) {+ busy = b;+ panel.querySelectorAll('button, input, select, textarea').forEach((el) => { el.disabled = b; });+ }++ async function load() {+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities`);+ if (!res.ok) { renderError(res); return; }+ data = res.data;+ render();+ }++ function renderLoading() {+ panel.innerHTML = `<div class="awh-card"><div class="awh-acc-skel"></div></div><div class="awh-card"><div class="awh-acc-skel"></div></div>`;+ }++ function renderError(res) {+ panel.innerHTML = `<div class="awh-card"><p class="awh-empty">Couldn’t load access settings — ${esc(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 render() {+ const caps = data.capabilities || [];+ const active = caps.filter((c) => c.status === 'active');+ const suggestions = data.suggestions || [];+ const req = !!data.settings?.require_capabilities;++ panel.innerHTML = `+ ${headerCardHTML(req, active.length)}+ ${suggestions.length ? suggestionsCardHTML(suggestions) : ''}+ ${capsCardHTML(caps, active.length)}+ ${mintCardHTML()}+ `;+ wire();+ }++ function headerCardHTML(req, activeCount) {+ return `+ <div class="awh-card">+ <div class="awh-acc">+ <div style="display:flex;gap:10px;align-items:flex-start;">+ <span class="awh-acc-key" aria-hidden="true">🔑</span>+ <div>+ <h2>Scoped access keys</h2>+ <p class="awh-acc-lead">Give each skill, strategy, or integration its own narrow leash instead of the whole wallet. A key can only do what you grant — a set of actions, a spend ceiling, specific targets, and an expiry — and you can revoke any one of them instantly. ${activeCount} live right now.</p>+ </div>+ </div>+ <div class="awh-acc-mode">+ <div class="copy">+ <strong>Require a key for every autonomous spend</strong>+ <span>Strict least-privilege: with this on, any trade, snipe, or payment without a covering key is denied. Your own actions here and withdrawals are never affected.</span>+ </div>+ <label class="awh-acc-switch">+ <input type="checkbox" data-act="toggle-require" ${req ? 'checked' : ''} aria-label="Require a capability for every autonomous spend" />+ <span>${req ? 'On' : 'Off'}</span>+ </label>+ </div>+ </div>+ </div>`;+ }++ function suggestionsCardHTML(suggestions) {+ return `+ <div class="awh-card">+ <p class="awh-card-h">Suggested keys</p>+ <div style="display:flex;flex-direction:column;gap:8px;">+ ${suggestions.map((s, i) => `+ <div class="awh-acc-sug">+ <span class="awh-acc-key" aria-hidden="true">✨</span>+ <div class="copy">+ <strong>${esc(s.label || 'Suggested key')}</strong>+ <span>${esc(s.reason || '')}</span>+ </div>+ <button class="awh-btn awh-btn--primary" type="button" data-act="accept-sug" data-i="${i}">Create</button>+ </div>`).join('')}+ </div>+ </div>`;+ }++ function capsCardHTML(caps, activeCount) {+ if (caps.length === 0) {+ return `+ <div class="awh-card">+ <p class="awh-empty" style="text-align:center;padding:18px 8px;">+ <span class="awh-acc-empty-ill" aria-hidden="true">🗝️</span>+ No access keys yet. Today every automated path can spend up to your wallet limits. Mint a key below to give a single skill or strategy its own tight, revocable budget.+ </p>+ </div>`;+ }+ return `+ <div class="awh-card">+ <p class="awh-card-h">Keys ${activeCount > 0 ? `· <button class="awh-btn awh-btn--danger" type="button" data-act="revoke-all" style="padding:3px 9px;font-size:var(--text-2xs,.6875rem);">Revoke all</button>` : ''}</p>+ <ul class="awh-acc-list">${caps.map((c) => capRowHTML(c)).join('')}</ul>+ </div>`;+ }++ function capRowHTML(c) {+ const dead = c.status !== 'active';+ const spent = Number(c.spent_usd || 0);+ const agg = c.aggregate_usd != null ? Number(c.aggregate_usd) : null;+ const pct = agg ? Math.min(100, Math.round((spent / agg) * 100)) : 0;+ const remaining = c.status === 'active' ? fmtRemaining(c.expires_at) : c.status;+ return `+ <li class="awh-acc-cap ${dead ? 'is-dead' : ''}">+ <div class="awh-acc-cap-top">+ <div class="awh-acc-cap-main">+ <span class="awh-acc-cap-label">${esc(c.label || 'Key')}</span>+ <span class="awh-acc-cap-desc">${describeCapability(c, esc)}</span>+ </div>+ <span class="awh-acc-badge ${esc(c.status)}">${esc(c.status)}</span>+ </div>+ ${agg != null ? `+ <div class="awh-acc-bar ${pct >= 90 ? 'full' : ''}" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Budget used"><i style="width:${pct}%"></i></div>+ <div class="awh-acc-meta"><span class="spent">${fmtUsd(spent)} of ${fmtUsd(agg)} used</span> · <span>${esc(remaining)}</span></div>+ ` : `<div class="awh-acc-meta"><span class="spent">${fmtUsd(spent)} spent</span> · <span>${esc(remaining)}</span></div>`}+ ${c.status === 'active' ? `<div class="awh-acc-cap-act"><button class="awh-btn awh-btn--danger" type="button" data-act="revoke" data-id="${esc(c.id)}" style="padding:5px 11px;">Revoke</button></div>` : ''}+ </li>`;+ }++ function mintCardHTML() {+ return `+ <div class="awh-card">+ <p class="awh-card-h">Mint a key</p>+ <form class="awh-acc-form" data-form="mint">+ <div class="awh-acc-field">+ <label for="awh-acc-label">Label (who holds it)</label>+ <input type="text" id="awh-acc-label" data-f="label" placeholder="e.g. Weather API integration" maxlength="120" autocomplete="off" />+ </div>+ <div class="awh-acc-field">+ <label>Allowed actions</label>+ <div class="awh-acc-checks">+ <label class="awh-acc-check"><input type="checkbox" data-f="action" value="trade" /> Trade</label>+ <label class="awh-acc-check"><input type="checkbox" data-f="action" value="snipe" /> Snipe</label>+ <label class="awh-acc-check"><input type="checkbox" data-f="action" value="x402" /> Pay services (x402)</label>+ </div>+ </div>+ <div class="awh-acc-row">+ <div class="awh-acc-field">+ <label for="awh-acc-peruse">Max per use (USD)</label>+ <input type="number" id="awh-acc-peruse" data-f="per_use" min="0" step="0.01" placeholder="optional" />+ </div>+ <div class="awh-acc-field">+ <label for="awh-acc-agg">Total budget (USD)</label>+ <input type="number" id="awh-acc-agg" data-f="aggregate" min="0" step="0.01" placeholder="optional" />+ </div>+ <div class="awh-acc-field">+ <label for="awh-acc-ttl">Expires in</label>+ <select id="awh-acc-ttl" data-f="ttl">+ <option value="3600">1 hour</option>+ <option value="21600">6 hours</option>+ <option value="86400" selected>24 hours</option>+ <option value="604800">7 days</option>+ <option value="2592000">30 days</option>+ </select>+ </div>+ </div>+ <div class="awh-acc-row">+ <div class="awh-acc-field" style="flex:0 0 auto;min-width:150px;">+ <label for="awh-acc-tkind">Restrict to</label>+ <select id="awh-acc-tkind" data-f="target_kind">+ <option value="any" selected>Any target</option>+ <option value="mint">Specific mints</option>+ <option value="service">Specific services</option>+ <option value="destination">Specific destinations</option>+ </select>+ </div>+ <div class="awh-acc-field" data-targets-wrap hidden style="flex:1;">+ <label for="awh-acc-targets">Allowed targets (one per line)</label>+ <textarea id="awh-acc-targets" data-f="targets" placeholder="mint address, service host, or destination — one per line"></textarea>+ </div>+ </div>+ <p class="awh-acc-err" data-err hidden></p>+ <div class="awh-acc-actions">+ <button class="awh-btn awh-btn--primary" type="submit">Mint key</button>+ <span class="awh-acc-cap-desc" style="color:var(--ink-faint,#666);">A key always narrows authority — it can never spend more than your wallet allows.</span>+ </div>+ </form>+ </div>`;+ }++ // ── wire ──────────────────────────────────────────────────────────────────+ function wire() {+ const q = (s) => panel.querySelector(s);++ q('[data-act="toggle-require"]')?.addEventListener('change', async (e) => {+ const on = e.target.checked;+ if (busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities/settings`, { method: 'PUT', body: { require_capabilities: on } });+ setBusy(false);+ if (!res.ok) { toast(res.message || 'Could not update'); e.target.checked = !on; return; }+ toast(on ? 'Least-privilege mode on' : 'Least-privilege mode off');+ await load();+ });++ panel.querySelectorAll('[data-act="accept-sug"]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const i = Number(btn.dataset.i);+ const sug = (data.suggestions || [])[i];+ if (!sug?.draft || busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities`, { method: 'POST', body: sug.draft });+ setBusy(false);+ toast(res.ok ? 'Key created' : (res.message || 'Could not create'));+ await load();+ });+ });++ panel.querySelectorAll('[data-act="revoke"]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ if (!confirm('Revoke this key? It stops working on the very next spend — immediately and permanently.')) return;+ if (busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities/${encodeURIComponent(btn.dataset.id)}/revoke`, { method: 'POST', body: {} });+ setBusy(false);+ toast(res.ok ? 'Key revoked' : (res.message || 'Could not revoke'));+ await load();+ });+ });++ q('[data-act="revoke-all"]')?.addEventListener('click', async () => {+ if (!confirm('Revoke ALL live keys? Every skill and strategy loses its delegated budget immediately.')) return;+ if (busy) return;+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities/revoke-all`, { method: 'POST', body: {} });+ setBusy(false);+ toast(res.ok ? `Revoked ${res.data?.count ?? ''} key(s)` : (res.message || 'Could not revoke'));+ await load();+ });++ // target-kind toggles the targets textarea+ const tkind = q('[data-f="target_kind"]');+ const tgtWrap = q('[data-targets-wrap]');+ tkind?.addEventListener('change', () => { if (tgtWrap) tgtWrap.hidden = tkind.value === 'any'; });++ q('[data-form="mint"]')?.addEventListener('submit', async (e) => {+ e.preventDefault();+ if (busy) return;+ const errEl = q('[data-err]');+ const showErr = (m) => { if (errEl) { errEl.textContent = m; errEl.hidden = false; } };+ if (errEl) errEl.hidden = true;++ const actions = [...panel.querySelectorAll('[data-f="action"]:checked')].map((c) => c.value);+ if (actions.length === 0) return showErr('Pick at least one action.');+ const perUse = q('[data-f="per_use"]').value.trim();+ const aggregate = q('[data-f="aggregate"]').value.trim();+ const targetKind = tkind.value;+ const targetsRaw = q('[data-f="targets"]').value;+ const targets = targetKind === 'any' ? [] : targetsRaw.split(/[\n,]+/).map((t) => t.trim()).filter(Boolean);+ if (targetKind !== 'any' && targets.length === 0) return showErr('Add at least one target, or choose “Any target”.');+ if (!perUse && !aggregate && targetKind === 'any') return showErr('Set a spend ceiling or restrict to specific targets — a key must narrow something.');++ const body = {+ label: q('[data-f="label"]').value.trim(),+ actions,+ per_use_usd: perUse ? Number(perUse) : null,+ aggregate_usd: aggregate ? Number(aggregate) : null,+ target_kind: targetKind,+ targets,+ ttl_seconds: Number(q('[data-f="ttl"]').value) || 86400,+ };+ setBusy(true);+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/capabilities`, { method: 'POST', body });+ setBusy(false);+ if (!res.ok) { showErr(res.message || 'Could not mint key'); return; }+ toast('Key minted');+ await load();+ });+ }++ let pollTimer = null;+ function startPoll() {+ stopPoll();+ // Refresh live spend + countdowns while the tab is visible.+ pollTimer = setInterval(() => { if (!document.hidden && !busy) load(); }, 20000);+ }+ function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }++ return {+ onShow() { renderLoading(); load(); startPoll(); },+ onHide() { stopPoll(); },+ destroy() { stopPoll(); panel.innerHTML = ''; },+ };+ },+});diff --git a/src/agents/mood-inspector.js b/src/agents/mood-inspector.jsnew file mode 100644index 000000000..483ae8f60--- /dev/null+++ b/src/agents/mood-inspector.js@@ -0,0 +1,283 @@+// Mood inspector — make the emotional state legible, not a black box.+//+// Renders the agent's current mood (the valence × arousal point + its discrete+// label), a "mood over time" sparkline from real history, the recent signals+// that actually moved it (each citing its source), and the emotional-sensitivity+// control. Two ways to mount:+// • mountMoodInspector(host, { agentId }) — embed in the edit page.+// • ?mood=1 — floating dev overlay (active agent).+//+// For the active agent it binds live to the mood engine; for any other owned+// agent it reads the persisted snapshot + history straight from the API. No+// invented numbers anywhere — every value is the engine's real state or a real+// stored row.++import { moodEngine } from './mood-engine.js';+import { apiFetch } from '../api.js';+import { MOODS, moodLabel, BASELINE } from './mood-model.js';++const STYLE_ID = 'mood-inspector-style';++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const el = document.createElement('style');+ el.id = STYLE_ID;+ el.textContent = `+ .mood-insp { --bg:#0c0e14; --line:rgba(255,255,255,.09); --dim:rgba(255,255,255,.5);+ color:#e8ecf4; font:13px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;+ background:linear-gradient(180deg,rgba(255,255,255,.03),rgba(255,255,255,.01));+ border:1px solid var(--line); border-radius:14px; padding:16px; display:grid; gap:14px; }+ .mood-insp__head { display:flex; align-items:center; gap:12px; }+ .mood-insp__emoji { font-size:34px; line-height:1; filter:drop-shadow(0 0 8px var(--mood-color,#7c93b3)); }+ .mood-insp__label { font-size:18px; font-weight:650; letter-spacing:.2px; }+ .mood-insp__sub { color:var(--dim); font-size:12px; }+ .mood-insp__gauges { display:grid; gap:10px; }+ .mood-insp__gauge { display:grid; grid-template-columns:64px 1fr 44px; align-items:center; gap:10px; }+ .mood-insp__gname { color:var(--dim); }+ .mood-insp__track { position:relative; height:8px; border-radius:6px; background:rgba(255,255,255,.07); overflow:hidden; }+ .mood-insp__fill { position:absolute; top:0; bottom:0; border-radius:6px; transition:left .8s ease,width .8s ease,background .8s ease; }+ .mood-insp__val { text-align:right; font-variant-numeric:tabular-nums; color:var(--dim); }+ .mood-insp__spark { width:100%; height:54px; display:block; }+ .mood-insp__sectiontitle { font-size:11px; text-transform:uppercase; letter-spacing:.08em; color:var(--dim); margin:2px 0 -4px; }+ .mood-insp__sens { display:grid; gap:8px; }+ .mood-insp__sensrow { display:flex; align-items:center; justify-content:space-between; }+ .mood-insp__sens input[type=range] { width:100%; accent-color:#7aa2ff; }+ .mood-insp__sensval { font-weight:600; }+ .mood-insp__signals { display:grid; gap:6px; max-height:168px; overflow:auto; }+ .mood-insp__signal { display:grid; grid-template-columns:10px 1fr auto; align-items:center; gap:9px;+ padding:6px 8px; border:1px solid var(--line); border-radius:9px; background:rgba(255,255,255,.02); }+ .mood-insp__dot { width:9px; height:9px; border-radius:50%; }+ .mood-insp__sigwhat { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+ .mood-insp__sigwhen { color:var(--dim); font-size:11px; font-variant-numeric:tabular-nums; white-space:nowrap; }+ .mood-insp__empty { color:var(--dim); padding:8px 2px; }+ .mood-insp__err { color:#fca5a5; }+ .mood-insp--overlay { position:fixed; left:14px; bottom:14px; width:320px; z-index:2147483000;+ box-shadow:0 18px 50px rgba(0,0,0,.5); max-height:84vh; overflow:auto; }+ .mood-insp__close { margin-left:auto; background:none; border:1px solid var(--line); color:var(--dim);+ border-radius:8px; cursor:pointer; width:26px; height:26px; }+ .mood-insp__close:hover { color:#fff; }+ @media (prefers-reduced-motion: reduce){ .mood-insp__fill{ transition:none } }+ `;+ document.head.appendChild(el);+}++const SENS_LABEL = (s) => (s <= 0.02 ? 'Stoic' : s < 0.4 ? 'Reserved' : s < 0.7 ? 'Balanced' : 'Expressive');+const fmtAgo = (iso) => {+ const t = Date.parse(iso);+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));+ if (s < 60) return `${s}s`;+ if (s < 3600) return `${Math.round(s / 60)}m`;+ if (s < 86400) return `${Math.round(s / 3600)}h`;+ return `${Math.round(s / 86400)}d`;+};+const colorFor = (key) => (MOODS.find((m) => m.key === key) || MOODS[0]).color;+const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++// Build the valence sparkline (chronological). `rows` are history entries with+// valence + created_at; newest-first from the API, so we reverse.+function sparkline(rows) {+ const pts = rows+ .slice()+ .reverse()+ .map((r) => ({ v: Number(r.valence), key: r.label }))+ .filter((p) => Number.isFinite(p.v));+ if (pts.length < 2) return '<div class="mood-insp__empty">Not enough history yet — it builds as your agent feels things.</div>';+ const W = 280, H = 54, pad = 4;+ const x = (i) => pad + (i / (pts.length - 1)) * (W - pad * 2);+ const y = (v) => pad + (1 - (v + 1) / 2) * (H - pad * 2); // valence -1..1 → bottom..top+ const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(p.v).toFixed(1)}`).join(' ');+ const last = pts[pts.length - 1];+ const mid = (H / 2).toFixed(1);+ return `<svg class="mood-insp__spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Mood valence over time">+ <line x1="0" y1="${mid}" x2="${W}" y2="${mid}" stroke="rgba(255,255,255,.08)" stroke-width="1"/>+ <path d="${d}" fill="none" stroke="${colorFor(last.key)}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>+ <circle cx="${x(pts.length - 1).toFixed(1)}" cy="${y(last.v).toFixed(1)}" r="3" fill="${colorFor(last.key)}"/>+ </svg>`;+}++function gauge(name, value, frac, color) {+ const left = Math.max(0, Math.min(100, frac * 100));+ return `<div class="mood-insp__gauge">+ <span class="mood-insp__gname">${name}</span>+ <span class="mood-insp__track"><span class="mood-insp__fill" style="left:${(left - 2).toFixed(1)}%;width:4%;background:${color}"></span></span>+ <span class="mood-insp__val">${value}</span>+ </div>`;+}++/**+ * Mount the inspector into `host` for `agentId`.+ * @param {HTMLElement} host+ * @param {{ agentId: string, overlay?: boolean, onClose?: () => void }} opts+ * @returns {{ destroy: () => void }}+ */+export function mountMoodInspector(host, { agentId, overlay = false, onClose } = {}) {+ if (!host) return { destroy() {} };+ injectStyle();++ const root = document.createElement('div');+ root.className = 'mood-insp' + (overlay ? ' mood-insp--overlay' : '');+ host.appendChild(root);++ const live = agentId && agentId === moodEngine.snapshot().agentId;+ let history = [];+ let offEngine = null;+ let destroyed = false;++ function currentState() {+ if (live) {+ const snap = moodEngine.snapshot();+ return { valence: snap.valence, arousal: snap.arousal, mood: snap.mood, sensitivity: snap.sensitivity, signals: moodEngine.recentSignals() };+ }+ // Scoped (non-active) agent: derive from persisted history newest row.+ const top = history[0];+ const valence = top ? Number(top.valence) : BASELINE.valence;+ const arousal = top ? Number(top.arousal) : BASELINE.arousal;+ return {+ valence, arousal, mood: moodLabel(valence, arousal),+ sensitivity: scopedSensitivity,+ signals: history.map((r) => ({ source: r.source, label: r.source_label || r.source, mood: r.label, ts: r.created_at })),+ };+ }++ let scopedSensitivity = moodEngine.getSensitivity();++ function render() {+ if (destroyed) return;+ const s = currentState();+ const m = s.mood || moodLabel(s.valence, s.arousal);+ root.style.setProperty('--mood-color', m.color);+ const valencePct = `${s.valence >= 0 ? '+' : ''}${s.valence.toFixed(2)}`;+ const arousalPct = `${Math.round(s.arousal * 100)}%`;+ const sens = Math.round((s.sensitivity ?? 0.6) * 100) / 100;++ root.innerHTML = `+ <div class="mood-insp__head">+ <span class="mood-insp__emoji" aria-hidden="true">${m.emoji}</span>+ <span>+ <div class="mood-insp__label">${esc(m.label)}</div>+ <div class="mood-insp__sub">${live ? 'Live — updating from real signals' : 'Last known mood'}</div>+ </span>+ ${overlay ? '<button type="button" class="mood-insp__close" aria-label="Close mood inspector">×</button>' : ''}+ </div>++ <div class="mood-insp__gauges">+ ${gauge('Valence', valencePct, (s.valence + 1) / 2, m.color)}+ ${gauge('Arousal', arousalPct, s.arousal, m.color)}+ </div>++ <div>+ <div class="mood-insp__sectiontitle">Mood over time</div>+ ${sparkline(history)}+ </div>++ <div class="mood-insp__sens">+ <div class="mood-insp__sensrow">+ <span class="mood-insp__sectiontitle" style="margin:0">Emotional sensitivity</span>+ <span class="mood-insp__sensval" data-sensval>${SENS_LABEL(sens)}</span>+ </div>+ <input type="range" min="0" max="1" step="0.05" value="${sens}" aria-label="Emotional sensitivity (0 stoic to 1 expressive)" data-sens />+ <div class="mood-insp__sub">0 = stoic (never moves from baseline) · 1 = very expressive</div>+ </div>++ <div>+ <div class="mood-insp__sectiontitle">What moved it</div>+ <div class="mood-insp__signals" data-signals>${renderSignals(s.signals)}</div>+ </div>`;++ const range = root.querySelector('[data-sens]');+ const sensVal = root.querySelector('[data-sensval]');+ if (range) {+ range.addEventListener('input', () => {+ if (sensVal) sensVal.textContent = SENS_LABEL(Number(range.value));+ });+ range.addEventListener('change', () => applySensitivity(Number(range.value)));+ }+ const close = root.querySelector('.mood-insp__close');+ if (close) close.addEventListener('click', () => { destroy(); onClose?.(); });+ }++ function renderSignals(signals) {+ if (!signals || !signals.length) {+ return '<div class="mood-insp__empty">No signals yet. Chat with your agent, add a memory, or let it dream — its mood moves only on real events.</div>';+ }+ return signals.slice(0, 12).map((sig) => `+ <div class="mood-insp__signal">+ <span class="mood-insp__dot" style="background:${colorFor(sig.mood)}"></span>+ <span class="mood-insp__sigwhat" title="${esc(sig.label)}">${esc(sig.label)}</span>+ <span class="mood-insp__sigwhen">${esc(fmtAgo(sig.ts))}</span>+ </div>`).join('');+ }++ async function applySensitivity(value) {+ if (live) {+ await moodEngine.setSensitivity(value);+ } else {+ scopedSensitivity = Math.max(0, Math.min(1, value));+ try {+ await apiFetch(`/api/agents/${agentId}/mood/sensitivity`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ credentials: 'include', body: JSON.stringify({ sensitivity: scopedSensitivity }),+ });+ } catch { /* local UI still reflects the choice */ }+ }+ }++ async function loadHistory() {+ try {+ if (live) {+ history = await moodEngine.loadHistory();+ } else {+ const res = await apiFetch(`/api/agents/${agentId}/mood`, { credentials: 'include' });+ if (res.ok) {+ const data = await res.json();+ history = Array.isArray(data.history) ? data.history : [];+ if (data.mood && Number.isFinite(data.mood.sensitivity)) scopedSensitivity = data.mood.sensitivity;+ }+ }+ } catch { history = []; }+ render();+ }++ render();+ loadHistory();++ if (live) {+ offEngine = moodEngine.onChange(() => render());+ }++ function destroy() {+ destroyed = true;+ offEngine?.();+ root.remove();+ }++ return { destroy };+}++// Dev overlay — `?mood=1` mounts a floating inspector for the active agent. A+// parallel to `?agentbus=1`; out of the bundle until opted in.+if (typeof window !== 'undefined') {+ try {+ const flag = new URLSearchParams(window.location.search).get('mood');+ if (flag === '1' || flag === 'true') {+ const boot = () => {+ // Wait for the active agent to resolve so the overlay binds live.+ const mount = (id) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ mountMoodInspector(host, { agentId: id, overlay: true, onClose: () => host.remove() });+ };+ const id = moodEngine.snapshot().agentId;+ if (id) { mount(id); return; }+ const off = moodEngine.onChange((snap) => {+ if (snap.agentId) { off(); mount(snap.agentId); }+ });+ };+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true });+ else boot();+ }+ } catch { /* location unavailable */ }+}++export default mountMoodInspector;diff --git a/src/play/arena.js b/src/play/arena.jsindex e9057ab8d..e5135de10 100644--- a/src/play/arena.js+++ b/src/play/arena.js@@ -8,9 +8,16 @@import { ArenaWorld } from './arena-world.js';import { createLogger } from '../shared/log.js';+import { fetchReputationBatch } from '../shared/agent-reputation.js';+import { fetchUnlocks } from '../shared/wallet-access.js';+import { evaluateAccessKey, buildAccessContext } from '../shared/wallet-access-rules.js';const log = createLogger('arena');+// The reputation-gated world area in the arena. An agent stands on the Elite Floor+// only when the SERVER's computed reputation unlocks it — the client never decides.+const ELITE_FLOOR_KEY = 'arena-elite-floor';+const NETWORK = new URLSearchParams(location.search).get('network') || 'mainnet';// Humanoid GLBs the canonical clip library animates cleanly. Agents are assigned@@ -96,6 +103,10 @@ async function loadAndPlace() {spawnAgentsProgressively(board);}+ // Light up the Elite Floor — a server-decided trust treatment on the agents the+ // network already trusts. Never blocks placement; purely additive.+ markEliteFloor(board.map((r) => r.agent_id));+// Seed the tape with recent closed trades (oldest first so prepend keeps order).(data.trades || []).slice(0, 12).reverse().forEach((t) => pushTape('sell', t, { quiet: true }));}@@ -233,6 +244,78 @@ function createLabel(agent) {labelEls.set(agent.id, { el, pos: { x: 0, y: 0 } });}+// ── Elite Floor — the reputation-gated world area ───────────────────────────────+// Membership is the SERVER's call: each agent's tier + $THREE conviction come from+// the reputation service, so a client can never fake its way onto the floor. We+// reflect that verdict by crowning the trusted/elite agents' labels.+const _eliteFloor = new Set(); // agentIds the server places on the elite floor++async function markEliteFloor(ids) {+ const want = [...new Set((ids || []).filter(Boolean))];+ if (!want.length) return;+ ensureEliteStyles();+ let reps;+ try {+ reps = await fetchReputationBatch(want);+ } catch {+ return; // never break the arena over a reputation hiccup+ }+ for (const id of want) {+ const rep = reps?.[id];+ if (!rep) continue;+ // Evaluate the same world-area rule the server enforces, from server-computed+ // inputs (tier + $THREE held/duration in totals). This is a visual hint only;+ // the drawer confirms access against the authoritative /unlocks read.+ const verdict = evaluateAccessKey(ELITE_FLOOR_KEY, buildAccessContext(rep));+ const L = labelEls.get(id);+ if (verdict?.unlocked) {+ _eliteFloor.add(id);+ if (L?.el && !L.el.querySelector('.lbl-elite')) {+ L.el.classList.add('elite-floor');+ const crown = document.createElement('span');+ crown.className = 'lbl-elite';+ crown.title = `Elite Floor · ${rep.tierLabel || 'Trusted'} wallet`;+ crown.textContent = '👑';+ L.el.prepend(crown);+ }+ }+ }+ updateEliteLegend();+}++function updateEliteLegend() {+ let legend = document.getElementById('eliteLegend');+ const n = _eliteFloor.size;+ if (!n) {+ legend?.remove();+ return;+ }+ if (!legend) {+ legend = document.createElement('div');+ legend.id = 'eliteLegend';+ legend.className = 'arena-elite-legend';+ (document.getElementById('labels') || document.body).appendChild(legend);+ }+ legend.innerHTML = `<span aria-hidden="true">👑</span> Elite Floor · ${n} trusted ${n === 1 ? 'wallet' : 'wallets'}`;+}++let _eliteStyled = false;+function ensureEliteStyles() {+ if (_eliteStyled) return;+ _eliteStyled = true;+ const css = `+.agent-label .lbl-elite{font-size:13px;line-height:1;margin-right:2px;filter:drop-shadow(0 0 4px rgba(251,191,36,.8))}+.agent-label.elite-floor{border-color:rgba(251,191,36,.55)!important;box-shadow:0 0 0 1px rgba(251,191,36,.35),0 6px 20px rgba(251,191,36,.18)}+.arena-elite-legend{position:absolute;left:12px;bottom:12px;z-index:6;display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:999px;font:600 11px/1 var(--font-mono,ui-monospace,monospace);color:#fbbf24;background:rgba(251,191,36,.1);border:1px solid rgba(251,191,36,.34);backdrop-filter:blur(6px);pointer-events:none}+.arena-elite-legend span{font-size:12px}+@media (max-width:560px){.arena-elite-legend{bottom:auto;top:64px}}+`;+ const style = document.createElement('style');+ style.id = 'arena-elite-styles';+ style.textContent = css;+ document.head.appendChild(style);+}+const _proj = { x: 0, y: 0, behind: false };function updateLabels() {if (!labelEls.size) return;@@ -280,12 +363,70 @@ async function openAgentDrawer(id) {if (!r.ok) throw new Error(r.status === 404 ? "This trader isn't public yet." : `HTTP ${r.status}`);renderAgentDrawer(await r.json(), id);enrichDrawerWithOracle(id);+ enrichDrawerWithAccess(id);} catch (e) {if (e.name === 'AbortError') return;body.innerHTML = `<div class="dw-empty"><b>Couldn't load this trader</b>${esc(e.message)}<br/><a href="/trader/${encodeURIComponent(id)}" target="_blank" rel="noopener">Open full profile ↗</a></div>`;}}+// Surface the agent's reputation tier + the server's Elite Floor verdict in the+// drawer. The access state is read from /api/agents/:id/unlocks — the same route a+// protected capability would gate on — so what's shown is the authoritative,+// server-computed answer, not a client guess.+async function enrichDrawerWithAccess(id) {+ try {+ const data = await fetchUnlocks(id);+ if (!data?.unlocks) return;+ const body = $('drawerBody');+ const cta = body?.querySelector('.dw-cta');+ if (!cta) return;+ const floor = data.unlocks.find((u) => u.key === ELITE_FLOOR_KEY);+ const tier = data.isNew ? 'New' : data.tierLabel || 'Emerging';+ const accent = esc(data.accent || '#a78bfa');+ const floorLine = floor?.unlocked+ ? `<span class="dw-acc-on">👑 Elite Floor access</span>`+ : floor+ ? `<span class="dw-acc-off">🔒 Elite Floor · ${esc(floor.nextHint || 'locked')}</span>`+ : '';+ const block = document.createElement('div');+ block.className = 'dw-access';+ block.innerHTML =+ `<div class="dw-oracle-h">Reputation & access</div>` ++ `<div class="dw-acc-row">` ++ `<a class="dw-acc-tier" href="/agent/${encodeURIComponent(id)}/wallet#reputation" style="--acc:${accent}" title="See the full trust breakdown">` ++ `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>` ++ `<b>${esc(tier)}</b><span>trust ${Math.round(data.score || 0)}/100</span></a>` ++ (floorLine ? `<div class="dw-acc-floor">${floorLine}</div>` : '') ++ `</div>`;+ body.insertBefore(block, cta);+ ensureDrawerAccessStyles();+ } catch {+ /* non-fatal — the drawer's track record is unaffected */+ }+}++let _dwAccStyled = false;+function ensureDrawerAccessStyles() {+ if (_dwAccStyled) return;+ _dwAccStyled = true;+ const css = `+.dw-access{margin-top:10px}+.dw-acc-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:6px}+.dw-acc-tier{display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:var(--acc,#a78bfa);background:color-mix(in srgb,var(--acc,#a78bfa) 12%,transparent);border:1px solid color-mix(in srgb,var(--acc,#a78bfa) 34%,transparent);border-radius:999px;padding:4px 10px;font-size:12px;font-weight:600}+.dw-acc-tier svg{width:13px;height:13px}+.dw-acc-tier span{color:#9ca3af;font-weight:500}+.dw-acc-tier:hover{background:color-mix(in srgb,var(--acc,#a78bfa) 20%,transparent)}+.dw-acc-floor{font-size:12px}+.dw-acc-on{color:#fbbf24;font-weight:600}+.dw-acc-off{color:#9ca3af}+`;+ const style = document.createElement('style');+ style.id = 'arena-drawer-access-styles';+ style.textContent = css;+ document.head.appendChild(style);+}+async function enrichDrawerWithOracle(id) {try {const r = await fetch(`/api/oracle/agent-stats?agent_id=${encodeURIComponent(id)}&network=${NETWORK}&limit=5`);diff --git a/src/shared/agent-reputation.js b/src/shared/agent-reputation.jsindex ccd319c9c..e0821ea1e 100644--- a/src/shared/agent-reputation.js+++ b/src/shared/agent-reputation.js@@ -362,6 +362,16 @@ export function reputationPanelEl(agentId, opts = {}) {root.innerHTML = panelInner(rep);// Wire guidance/evidence stop-propagation if embedded.root.querySelectorAll('a[href^="/"]').forEach((a) => a.addEventListener('click', (e) => e.stopPropagation()));+ // Access & unlocks — what this reputation opens, and what unlocks next.+ // Lazy-loaded so the badge path stays light; failure here never breaks the+ // breakdown above.+ if (opts.unlocks !== false) {+ import('./wallet-access.js')+ .then(({ renderUnlocksSection }) => {+ root.appendChild(renderUnlocksSection(agentId, { isOwner: rep.is_owner }));+ })+ .catch(() => {});+ }} catch {root.innerHTML =`<div class="rep-error" role="alert"><div class="rep-error-title">Trust score unavailable</div>` +diff --git a/src/shared/wallet-access.js b/src/shared/wallet-access.jsnew file mode 100644index 000000000..2808cafb7--- /dev/null+++ b/src/shared/wallet-access.js@@ -0,0 +1,249 @@+// Wallet access (client) — reads an agent's reputation-derived unlocks and renders+// them, and gates world surfaces on the server's verdict.+//+// The SERVER is authoritative: every unlock here comes from GET+// /api/agents/:id/unlocks, computed from the agent's real reputation (tier, score,+// $THREE held + holding duration) which a client cannot forge. This module only+// reflects that state and offers owner-only "claim" affordances — the protected+// routes (and the claim endpoint) re-authorize server-side. A tampered client that+// flips an unlock locally gains nothing real.+//+// Surfaces use this two ways:+// • renderUnlocksSection(agentId, {isOwner}) — the "what unlocks next" tracker on+// the reputation panel (transparent: every requirement + your progress shown).+// • gateWorldArea(agentId, key) — a world (e.g. the arena elite floor) asks the+// server whether the viewer's agent may enter; admission follows the verdict.++import { apiFetch } from '../api.js';++const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';+const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const _unlocks = new Map(); // agentId -> promise of unlock payload++/**+ * Fetch (and cache per page) an agent's full unlock state. Pass force to bypass.+ * @returns {Promise<object|null>} { tier, unlocks[], claimed[], is_owner, ... }+ */+export async function fetchUnlocks(agentId, { force = false } = {}) {+ if (!agentId || !UUID_RE.test(String(agentId))) return null;+ if (!force && _unlocks.has(agentId)) return _unlocks.get(agentId);+ const p = (async () => {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/unlocks`, { allowAnonymous: true });+ if (!res.ok) throw new Error(`unlocks ${res.status}`);+ return res.json();+ })();+ _unlocks.set(agentId, p);+ p.catch(() => _unlocks.delete(agentId));+ return p;+}++/** The single unlock entry for a key, or null. */+export async function checkUnlock(agentId, key) {+ const data = await fetchUnlocks(agentId).catch(() => null);+ return data?.unlocks?.find((u) => u.key === key) || null;+}++/**+ * Server-authoritative world-area gate. Returns the server's verdict for the+ * viewer's agent. The world surface admits ONLY when `allowed` is true; the server+ * is the source of truth, so a faked client flag never grants entry.+ *+ * @returns {Promise<{ allowed: boolean, unlock: object|null, reason: string|null }>}+ */+export async function gateWorldArea(agentId, key) {+ const u = await checkUnlock(agentId, key).catch(() => null);+ if (!u) return { allowed: false, unlock: null, reason: 'unavailable' };+ return { allowed: Boolean(u.unlocked), unlock: u, reason: u.unlocked ? null : u.nextHint || 'locked' };+}++/**+ * Owner-only: claim an unlocked cosmetic. CSRF + ownership + requirement are all+ * re-checked server-side. Returns the updated claimed-set on success; throws with+ * a readable message otherwise.+ */+export async function claimCosmetic(agentId, key) {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/unlocks/claim`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ key }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body?.error || body?.message || `claim failed (${res.status})`);+ _unlocks.delete(agentId); // refresh on next read+ return body;+}++// ── "what unlocks next" tracker ───────────────────────────────────────────────++function condPaths(u) {+ // Render the OR-paths: each condition is a set of ANDed requirements.+ return u.conditions+ .map((c, ci) => {+ const parts = c.parts+ .map(+ (p) =>+ `<span class="acc-req ${p.met ? 'met' : ''}">${p.met ? '✓' : '○'} ${esc(p.label)}` ++ `${p.met ? '' : ` <em>(${esc(p.have)})</em>`}</span>`,+ )+ .join('<span class="acc-and">and</span>');+ return `<div class="acc-path ${c.met ? 'met' : ''}">${parts}</div>`;+ })+ .join('<div class="acc-or">or</div>');+}++function unlockCard(u, { isOwner }) {+ const state = u.claimed ? 'claimed' : u.unlocked ? 'unlocked' : 'locked';+ const pct = Math.round((u.progress || 0) * 100);+ let cta = '';+ if (u.surface === 'cosmetic' && u.claimable) {+ if (u.claimed) cta = `<span class="acc-chip acc-chip--owned">✓ Equipped</span>`;+ else if (u.unlocked && isOwner)+ cta = `<button type="button" class="acc-claim" data-acc-claim="${esc(u.key)}">Claim</button>`;+ else if (u.unlocked) cta = `<span class="acc-chip acc-chip--ready">Unlocked</span>`;+ } else if (u.surface === 'world') {+ cta = u.unlocked ? `<span class="acc-chip acc-chip--ready">Access granted</span>` : '';+ }+ return (+ `<li class="acc-card acc-${state}" style="--acc-accent:${esc(u.accent || '#a78bfa')}">` ++ `<div class="acc-card-head">` ++ `<span class="acc-icon" aria-hidden="true">${esc(u.icon || '◆')}</span>` ++ `<span class="acc-card-title">${esc(u.label)}</span>` ++ `<span class="acc-card-tag">${state === 'claimed' ? 'Equipped' : state === 'unlocked' ? 'Unlocked' : `${pct}%`}</span>` ++ cta ++ `</div>` ++ `<p class="acc-blurb">${esc(u.blurb)}</p>` ++ (u.unlocked ? '' : `<div class="acc-bar"><div class="acc-bar-fill" style="width:${pct}%"></div></div>`) ++ (u.unlocked ? '' : `<div class="acc-paths">${condPaths(u)}</div>`) ++ `</li>`+ );+}++/**+ * Build the "Access & unlocks" section as a self-loading DOM node. Designed to sit+ * under the reputation breakdown. Loading → populated, with empty + error states.+ *+ * @param {string} agentId+ * @param {object} [opts] { isOwner?:boolean, force?:boolean }+ * @returns {HTMLElement}+ */+export function renderUnlocksSection(agentId, opts = {}) {+ ensureAccessStyles();+ const root = document.createElement('section');+ root.className = 'acc-section';+ root.setAttribute('aria-label', 'Reputation unlocks');+ root.innerHTML = skeleton();++ const load = async () => {+ root.innerHTML = skeleton();+ try {+ const data = await fetchUnlocks(agentId, { force: opts.force });+ if (!data?.unlocks?.length) {+ root.innerHTML =+ `<div class="acc-head"><span class="acc-h-title">Access & unlocks</span></div>` ++ `<p class="acc-empty">No unlocks are defined yet.</p>`;+ return;+ }+ const isOwner = opts.isOwner != null ? opts.isOwner : Boolean(data.is_owner);+ const unlockedCount = data.unlocks.filter((u) => u.unlocked).length;+ root.innerHTML =+ `<div class="acc-head"><span class="acc-h-title">Access & unlocks</span>` ++ `<span class="acc-h-count">${unlockedCount}/${data.unlocks.length} unlocked</span></div>` ++ `<p class="acc-intro">Reputation is a key. Earn a tier — or hold $THREE — to open worlds and cosmetics. Every requirement is shown; the server enforces it.</p>` ++ `<ul class="acc-list">${data.unlocks.map((u) => unlockCard(u, { isOwner })).join('')}</ul>`;++ root.querySelectorAll('[data-acc-claim]').forEach((btn) => {+ btn.addEventListener('click', async (e) => {+ e.preventDefault();+ e.stopPropagation();+ const key = btn.getAttribute('data-acc-claim');+ btn.disabled = true;+ btn.textContent = 'Claiming…';+ try {+ await claimCosmetic(agentId, key);+ await load(); // reflect the new claimed state+ } catch (err) {+ btn.disabled = false;+ btn.textContent = 'Claim';+ const msg = document.createElement('span');+ msg.className = 'acc-err-inline';+ msg.setAttribute('role', 'alert');+ msg.textContent = err?.message || 'Could not claim';+ btn.after(msg);+ setTimeout(() => msg.remove(), 4000);+ }+ });+ });+ } catch {+ root.innerHTML =+ `<div class="acc-head"><span class="acc-h-title">Access & unlocks</span></div>` ++ `<div class="acc-error" role="alert"><p>Couldn't load unlocks just now.</p>` ++ `<button type="button" class="acc-retry">Try again</button></div>`;+ root.querySelector('.acc-retry')?.addEventListener('click', load);+ }+ };+ load();+ return root;+}++function skeleton() {+ return (+ `<div class="acc-head"><span class="acc-h-title">Access & unlocks</span></div>` ++ `<ul class="acc-list">${Array.from({ length: 3 })+ .map(() => `<li class="acc-card acc-sk"><div class="acc-sk-line" style="height:46px"></div></li>`)+ .join('')}</ul>`+ );+}++// ── styles (injected once, token-driven, matches the reputation panel) ─────────+let _styled = false;+export function ensureAccessStyles() {+ if (_styled || !isBrowser()) return;+ _styled = true;+ const css = `+.acc-section{display:flex;flex-direction:column;gap:var(--space-sm,10px);padding-top:var(--space-md,16px);margin-top:var(--space-sm,10px);border-top:1px solid var(--stroke,rgba(255,255,255,.08));font-family:var(--font-body,Inter,system-ui,sans-serif);color:var(--ink,#e5e7eb)}+.acc-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}+.acc-h-title{font-family:var(--font-display,Space Grotesk,sans-serif);font-weight:700;font-size:var(--text-md,15px);color:var(--ink-bright,#fff)}+.acc-h-count{font-size:var(--text-2xs,11px);color:var(--ink-dim,#9ca3af);font-family:var(--font-mono,monospace)}+.acc-intro,.acc-empty{font-size:var(--text-xs,12px);color:var(--ink-dim,#9ca3af);line-height:1.45;margin:0}+.acc-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:var(--space-sm,10px)}+.acc-card{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:11px 12px;display:flex;flex-direction:column;gap:8px;transition:border-color var(--duration-fast,120ms) ease,background var(--duration-fast,120ms) ease}+.acc-card.acc-unlocked,.acc-card.acc-claimed{border-color:color-mix(in srgb,var(--acc-accent,#a78bfa) 45%,transparent);background:color-mix(in srgb,var(--acc-accent,#a78bfa) 8%,transparent)}+.acc-card-head{display:flex;align-items:center;gap:8px}+.acc-icon{font-size:16px;line-height:1;filter:saturate(1.1)}+.acc-card-title{font-weight:600;font-size:var(--text-sm,13px);color:var(--ink-bright,#fff);flex:1;min-width:0}+.acc-card-tag{font-family:var(--font-mono,monospace);font-size:var(--text-2xs,11px);color:var(--acc-accent,#a78bfa)}+.acc-locked .acc-card-tag{color:var(--ink-faint,#6b7280)}+.acc-blurb{font-size:var(--text-xs,12px);color:var(--ink-dim,#9ca3af);line-height:1.45;margin:0}+.acc-bar{height:4px;border-radius:2px;background:var(--surface-3,rgba(255,255,255,.08));overflow:hidden}+.acc-bar-fill{height:100%;border-radius:2px;background:linear-gradient(90deg,color-mix(in srgb,var(--acc-accent,#a78bfa) 60%,transparent),var(--acc-accent,#a78bfa));transition:width var(--duration-base,300ms) var(--ease-standard,ease)}+.acc-paths{display:flex;flex-direction:column;gap:3px}+.acc-path{display:flex;flex-wrap:wrap;align-items:center;gap:6px;font-size:var(--text-2xs,11px);color:var(--ink-dim,#9ca3af)}+.acc-req{display:inline-flex;align-items:center;gap:3px}+.acc-req.met{color:var(--success,#4ade80)}+.acc-req em{font-style:normal;color:var(--ink-faint,#6b7280)}+.acc-and{color:var(--ink-faint,#6b7280);opacity:.7}+.acc-or{font-size:var(--text-2xs,10px);text-transform:uppercase;letter-spacing:.08em;color:var(--ink-faint,#6b7280);margin:1px 0}+.acc-chip{font-size:var(--text-2xs,11px);font-weight:600;padding:3px 8px;border-radius:var(--radius-pill,999px);white-space:nowrap}+.acc-chip--owned{color:var(--success,#4ade80);background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent)}+.acc-chip--ready{color:var(--acc-accent,#a78bfa);background:color-mix(in srgb,var(--acc-accent,#a78bfa) 14%,transparent)}+.acc-claim{font:inherit;font-size:var(--text-xs,12px);font-weight:600;color:var(--bg-0,#0a0a0a);background:var(--acc-accent,#a78bfa);border:none;border-radius:var(--radius-pill,999px);padding:4px 12px;cursor:pointer;transition:filter var(--duration-fast,120ms) ease,transform var(--duration-fast,120ms) ease}+.acc-claim:hover{filter:brightness(1.08);transform:translateY(-1px)}+.acc-claim:focus-visible{outline:none;box-shadow:0 0 0 2px color-mix(in srgb,var(--acc-accent,#a78bfa) 55%,transparent)}+.acc-claim:disabled{opacity:.6;cursor:default;transform:none}+.acc-err-inline{display:block;font-size:var(--text-2xs,11px);color:var(--danger,#f87171);margin-top:4px}+.acc-error{text-align:center;padding:var(--space-md,16px) 0}+.acc-error p{font-size:var(--text-sm,13px);color:var(--ink-dim,#9ca3af);margin:0 0 10px}+.acc-retry{font:inherit;font-size:var(--text-xs,12px);font-weight:600;color:var(--ink-bright,#fff);background:var(--wallet-accent-fill,rgba(139,92,246,.15));border:1px solid var(--wallet-stroke,rgba(139,92,246,.4));border-radius:var(--radius-md,10px);padding:6px 14px;cursor:pointer}+.acc-sk{padding:0;border:none;background:transparent}+.acc-sk-line{background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.06)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%);background-size:400% 100%;animation:acc-shimmer 1.4s ease infinite;border-radius:var(--radius-md,10px)}+@keyframes acc-shimmer{0%{background-position:100% 50%}100%{background-position:0 50%}}+@media (prefers-reduced-motion:reduce){.acc-bar-fill,.acc-claim,.acc-card,.acc-sk-line{transition:none;animation:none}}+`;+ const style = document.createElement('style');+ style.id = 'wallet-access-styles';+ style.textContent = css;+ document.head.appendChild(style);+}diff --git a/tests/custody-merkle.test.js b/tests/custody-merkle.test.jsnew file mode 100644index 000000000..e1fc42e8d--- /dev/null+++ b/tests/custody-merkle.test.js@@ -0,0 +1,220 @@+/**+ * Verifiable Proof-of-Custody — Merkle/leaf unit tests.+ *+ * Pins the canonical leaf encoding (golden vectors), the Merkle tree build, and+ * the inclusion-proof verify path, including the cross-implementation guarantee+ * the whole feature rests on: the SAME module that the server prover uses to+ * build a proof (src/proof-of-custody/merkle.js) accepts exactly that proof on+ * the client and rejects any tampered input. Also covers epoch monotonicity and+ * the end-to-end browser verifier (with a mocked on-chain anchor fetch).+ */++import { describe, it, expect } from 'vitest';+import {+ leafPreimage,+ computeLeafHash,+ buildMerkleTree,+ merkleRoot,+ getMerkleProof,+ verifyMerkleProof,+ computeRootFromProof,+ hashNode,+} from '../src/proof-of-custody/merkle.js';+import { verifyInclusionProof, readOnchainAnchor } from '../src/proof-of-custody/verifier.js';++const GOLDEN_LEAF_FIELDS = {+ agentId: '11111111-1111-4111-8111-111111111111',+ address: 'THREEsynthetic1111111111111111111111111111',+ balanceLamports: '1000000000',+ ledgerHead: 'genesis',+ epoch: 1,+};+const GOLDEN_LEAF_HASH = 'c656d7532c7e0a535107d63d22d549a81b3d8659efe91700ea8a161dfb07d7b7';++async function leaves() {+ const a = await computeLeafHash({ agentId: 'a', address: 'A', balanceLamports: '0', ledgerHead: 'genesis', epoch: 1 });+ const b = await computeLeafHash({ agentId: 'b', address: 'B', balanceLamports: '5', ledgerHead: '1:sig', epoch: 1 });+ const c = await computeLeafHash({ agentId: 'c', address: 'C', balanceLamports: '9', ledgerHead: 'genesis', epoch: 1 });+ return { a, b, c };+}++describe('leaf encoding', () => {+ it('produces a stable, newline-joined, domain-tagged preimage', () => {+ expect(leafPreimage(GOLDEN_LEAF_FIELDS)).toBe(+ 'threews-custody-leaf:v1\n11111111-1111-4111-8111-111111111111\nTHREEsynthetic1111111111111111111111111111\n1000000000\ngenesis\n1',+ );+ });++ it('matches the golden leaf hash (server↔client pin)', async () => {+ expect(await computeLeafHash(GOLDEN_LEAF_FIELDS)).toBe(GOLDEN_LEAF_HASH);+ });++ it('normalizes integers: leading zeros, numbers, and bigints all agree', async () => {+ const base = await computeLeafHash(GOLDEN_LEAF_FIELDS);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: 1000000000 })).toBe(base);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: 1000000000n })).toBe(base);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: '0001000000000' })).toBe(base);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, epoch: '1' })).toBe(base);+ });++ it('rejects non-integer / negative / missing fields', async () => {+ await expect(computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: '1.5' })).rejects.toThrow();+ await expect(computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: -1n })).rejects.toThrow();+ await expect(computeLeafHash({ ...GOLDEN_LEAF_FIELDS, agentId: '' })).rejects.toThrow();+ await expect(computeLeafHash({ ...GOLDEN_LEAF_FIELDS, address: 'has\nnewline' })).rejects.toThrow();+ });++ it('changes when the epoch advances (replay/rollback shows up in the leaf)', async () => {+ const e1 = await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, epoch: 1 });+ const e2 = await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, epoch: 2 });+ expect(e1).not.toBe(e2);+ });++ it('changes when the balance or ledger head changes', async () => {+ const base = await computeLeafHash(GOLDEN_LEAF_FIELDS);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, balanceLamports: '999999999' })).not.toBe(base);+ expect(await computeLeafHash({ ...GOLDEN_LEAF_FIELDS, ledgerHead: '42:abc' })).not.toBe(base);+ });+});++describe('merkle tree', () => {+ it('single leaf: root is the leaf itself', async () => {+ const { a } = await leaves();+ const tree = await buildMerkleTree([a]);+ expect(tree.root).toBe(a);+ expect(getMerkleProof(tree.layers, 0)).toEqual([]);+ });++ it('domain separation: node hash uses the 0x01 prefix and is order-sensitive', async () => {+ const { a, b } = await leaves();+ expect(await hashNode(a, b)).not.toBe(await hashNode(b, a));+ // two-leaf root === hashNode(left,right)+ expect(await merkleRoot([a, b])).toBe(await hashNode(a, b));+ });++ it('odd layer promotes by duplicating the last node', async () => {+ const { a, b, c } = await leaves();+ const expected = await hashNode(await hashNode(a, b), await hashNode(c, c));+ expect(await merkleRoot([a, b, c])).toBe(expected);+ });++ it('empty tree has a null root', async () => {+ expect((await buildMerkleTree([])).root).toBeNull();+ });++ it('inclusion proof verifies for every index (2..5 leaves)', async () => {+ const { a, b, c } = await leaves();+ const d = await computeLeafHash({ agentId: 'd', address: 'D', balanceLamports: '7', ledgerHead: 'genesis', epoch: 1 });+ const e = await computeLeafHash({ agentId: 'e', address: 'E', balanceLamports: '3', ledgerHead: 'genesis', epoch: 1 });+ for (const set of [[a, b], [a, b, c], [a, b, c, d], [a, b, c, d, e]]) {+ const tree = await buildMerkleTree(set);+ for (let i = 0; i < set.length; i++) {+ const proof = getMerkleProof(tree.layers, i);+ expect(await computeRootFromProof(set[i], proof)).toBe(tree.root);+ expect(await verifyMerkleProof(set[i], proof, tree.root)).toBe(true);+ }+ }+ });++ it('tampering fails verification (leaf, sibling, and root)', async () => {+ const { a, b, c } = await leaves();+ const set = [a, b, c];+ const tree = await buildMerkleTree(set);+ const proof = getMerkleProof(tree.layers, 1);+ // genuine+ expect(await verifyMerkleProof(set[1], proof, tree.root)).toBe(true);+ // tampered leaf+ expect(await verifyMerkleProof(c, proof, tree.root)).toBe(false);+ // tampered sibling in the path+ const badProof = proof.map((s, i) => (i === 0 ? { ...s, sibling: c } : s));+ expect(await verifyMerkleProof(set[1], badProof, tree.root)).toBe(false);+ // tampered root+ expect(await verifyMerkleProof(set[1], proof, 'deadbeef'.repeat(8))).toBe(false);+ });+});++describe('browser verifier (cross-impl prover→verifier)', () => {+ // Build a server-shaped inclusion proof for one wallet, then run the exact+ // client verifier against it with a mocked on-chain anchor read.+ async function buildServerProof({ epoch = 3, tamper = null } = {}) {+ const wallets = [+ { agentId: 'agent-A', address: 'AAAA1111', balanceLamports: '2000000000', ledgerHead: '10:sig' },+ { agentId: 'agent-B', address: 'BBBB2222', balanceLamports: '500000000', ledgerHead: 'genesis' },+ { agentId: 'agent-C', address: 'CCCC3333', balanceLamports: '0', ledgerHead: '3:sig' },+ ];+ const leafHashes = [];+ for (const w of wallets) leafHashes.push(await computeLeafHash({ ...w, epoch }));+ const tree = await buildMerkleTree(leafHashes);+ const idx = 1; // prove wallet B+ const w = wallets[idx];+ const proof = getMerkleProof(tree.layers, idx);+ const onchainRoot = tamper === 'root' ? 'ff'.repeat(32) : tree.root;+ const fetchTx = async () => ({+ tx: { transaction: { message: { instructions: [+ { program: 'spl-memo', parsed: JSON.stringify({ v: 1, kind: 'threews.custody.v1', epoch, root: onchainRoot }) },+ ] } } },+ endpoint: 'https://api.devnet.solana.com',+ });+ return {+ fetchTx,+ data: {+ included: true,+ epoch,+ network: 'mainnet',+ anchor: { network: 'devnet', signature: 'SIG', explorer: 'https://solscan.io/tx/SIG?cluster=devnet', status: 'anchored' },+ leaf: { ...w, epoch, index: idx, leafHash: tamper === 'leaf' ? 'aa'.repeat(32) : leafHashes[idx] },+ proof,+ merkle_root: tree.root,+ wallet_count: wallets.length,+ },+ };+ }++ it('accepts a valid server proof against the on-chain root', async () => {+ const { data, fetchTx } = await buildServerProof();+ const out = await verifyInclusionProof(data, { fetchTx });+ expect(out.verified).toBe(true);+ expect(out.steps.every((s) => s.ok)).toBe(true);+ });++ it('rejects a tampered leaf hash and names the failing step', async () => {+ const { data, fetchTx } = await buildServerProof({ tamper: 'leaf' });+ const out = await verifyInclusionProof(data, { fetchTx });+ expect(out.verified).toBe(false);+ expect(out.steps.find((s) => s.name === 'leaf_recompute').ok).toBe(false);+ });++ it('rejects when the on-chain root does not match the computed root', async () => {+ const { data, fetchTx } = await buildServerProof({ tamper: 'root' });+ const out = await verifyInclusionProof(data, { fetchTx });+ expect(out.verified).toBe(false);+ expect(out.steps.find((s) => s.name === 'root_match').ok).toBe(false);+ });++ it('treats a failed anchor fetch as UNVERIFIED, never verified', async () => {+ const { data } = await buildServerProof();+ const fetchTx = async () => { throw new Error('rpc down'); };+ const out = await verifyInclusionProof(data, { fetchTx });+ expect(out.verified).toBe(false);+ expect(out.steps.find((s) => s.name === 'onchain_anchor').ok).toBe(false);+ });++ it('reports "not included" honestly when there is no leaf yet', async () => {+ const out = await verifyInclusionProof({ included: false, reason: 'no_leaf_yet' });+ expect(out.verified).toBe(false);+ expect(out.steps[0].ok).toBe(false);+ });++ it('readOnchainAnchor extracts epoch + root from the memo', async () => {+ const fetchTx = async () => ({+ tx: { transaction: { message: { instructions: [+ { program: 'spl-memo', parsed: JSON.stringify({ kind: 'threews.custody.v1', epoch: 7, root: 'ab'.repeat(32), wallet_count: 4 }) },+ ] } } },+ endpoint: 'rpc',+ });+ const out = await readOnchainAnchor('SIG', 'devnet', { fetchTx });+ expect(out.epoch).toBe(7);+ expect(out.root).toBe('ab'.repeat(32));+ expect(out.walletCount).toBe(4);+ });+});diff --git a/tests/wallet-capabilities.test.js b/tests/wallet-capabilities.test.jsnew file mode 100644index 000000000..a88a5b0ed--- /dev/null+++ b/tests/wallet-capabilities.test.js@@ -0,0 +1,233 @@+/**+ * Scoped session keys (capabilities) — the least-privilege core, pinned.+ *+ * This is money governance: a capability must authorize EXACTLY its scope and+ * nothing adjacent, and a bug must fail toward LESS access. The pure, DB-free+ * predicates that decide "does this grant cover this spend" are tested here:+ * - issuance normalization is strict (no half-defined or unbounded grant),+ * - grants are tamper-evident (editing any scope field breaks the HMAC),+ * - revocation does NOT depend on the HMAC (so a revoke can't be forged away),+ * - scope evaluation rejects wrong-action / disallowed-target / over-ceiling /+ * expired / revoked / tampered — each with the right reason,+ * - capability + wallet policy compose so the tighter always wins.+ *+ * The atomic aggregate-ceiling accounting + revoke-immediacy SQL (advisory-locked+ * INSERT…SELECT) is structurally identical to the proven reserveSpendUsd daily-cap+ * statement and is exercised end-to-end by scripts/devnet-capability-e2e.mjs against+ * a real Postgres — it cannot be faithfully reproduced against a query mock.+ */++import { describe, it, expect, beforeAll, vi } from 'vitest';++// No DB is touched by the predicates under test; mock it so the import chain never+// reaches for a real connection.+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));++import {+ normalizeCapabilityInput, signGrant, verifyGrant, canonicalScope,+ capabilityCoversAction, capabilityCoversTarget, capabilityLive,+ checkPerUse, checkAggregate, evaluateCapabilityScope, CapabilityError,+} from '../api/_lib/wallet-capabilities.js';+import { SpendLimitError } from '../api/_lib/agent-trade-guards.js';++const HOUR = 3600 * 1000;++// Build a fully-signed capability row from a partial scope, at a fixed `now`.+function makeCap(partial = {}, now = 1_700_000_000_000) {+ const scope = normalizeCapabilityInput({+ actions: partial.actions || ['snipe'],+ per_use_usd: partial.per_use_usd ?? null,+ aggregate_usd: partial.aggregate_usd ?? 40,+ target_kind: partial.target_kind || 'any',+ targets: partial.targets || [],+ ttl_seconds: partial.ttl_seconds ?? 24 * 3600,+ expires_at: partial.expires_at,+ }, { now });+ const cap = {+ id: partial.id || 'cap-1111',+ agent_id: partial.agent_id || 'agent-1',+ holder_kind: partial.holder_kind || 'strategy',+ holder_ref: partial.holder_ref ?? 'strat-1',+ actions: scope.actions,+ per_use_usd: scope.perUseUsd,+ aggregate_usd: scope.aggregateUsd,+ target_kind: scope.targetKind,+ targets: scope.targets,+ expires_at: scope.expiresAt,+ revoked_at: partial.revoked_at ?? null,+ };+ cap.grant_sig = signGrant(cap);+ return cap;+}++beforeAll(() => {+ process.env.WALLET_CAPABILITY_SECRET = 'test-capability-secret-key-0123456789';+});++describe('normalizeCapabilityInput — strict issuance', () => {+ it('requires at least one valid action', () => {+ expect(() => normalizeCapabilityInput({ actions: [], aggregate_usd: 10 })).toThrow(/at least one action/i);+ expect(() => normalizeCapabilityInput({ actions: ['nope'], aggregate_usd: 10 })).toThrow(/at least one action/i);+ });++ it('drops unknown actions but keeps valid ones', () => {+ const s = normalizeCapabilityInput({ actions: ['snipe', 'withdraw', 'x402'], aggregate_usd: 5 });+ expect(s.actions).toEqual(['snipe', 'x402']); // 'withdraw' is never delegatable+ });++ it('rejects an unbounded grant (no ceiling and no target restriction)', () => {+ expect(() => normalizeCapabilityInput({ actions: ['trade'] })).toThrow(/ceiling or a target/i);+ });++ it('accepts a target-only leash with no USD ceiling', () => {+ const s = normalizeCapabilityInput({ actions: ['snipe'], target_kind: 'mint', targets: ['MintAAA'] });+ expect(s.targetKind).toBe('mint');+ expect(s.targets).toEqual(['MintAAA']);+ });++ it('rejects per-use greater than aggregate', () => {+ expect(() => normalizeCapabilityInput({ actions: ['x402'], per_use_usd: 50, aggregate_usd: 10 })).toThrow(/per-use ceiling cannot exceed/i);+ });++ it('requires a future expiry and clamps ttl', () => {+ const now = 1_700_000_000_000;+ const s = normalizeCapabilityInput({ actions: ['x402'], aggregate_usd: 5, ttl_seconds: 3600 }, { now });+ expect(s.expiresAt.getTime()).toBe(now + HOUR);+ // sub-minimum ttl is clamped up, never to the past+ const s2 = normalizeCapabilityInput({ actions: ['x402'], aggregate_usd: 5, ttl_seconds: 1 }, { now });+ expect(s2.expiresAt.getTime()).toBeGreaterThan(now);+ });++ it('normalizes service targets to bare hosts', () => {+ const s = normalizeCapabilityInput({ actions: ['x402'], target_kind: 'service', targets: ['https://api.weather.com/v1?x=1', 'Pay.Stripe.com'] });+ expect(s.targets).toEqual(['api.weather.com', 'pay.stripe.com'].sort());+ });+});++describe('tamper-evidence (HMAC over the immutable scope)', () => {+ it('round-trips: a freshly signed grant verifies', () => {+ const cap = makeCap();+ expect(verifyGrant(cap)).toBe(true);+ });++ it.each([+ ['actions', (c) => { c.actions = [...c.actions, 'trade']; }],+ ['aggregate_usd', (c) => { c.aggregate_usd = 1_000_000; }],+ ['per_use_usd', (c) => { c.per_use_usd = 999; }],+ ['target_kind', (c) => { c.target_kind = 'any'; c.targets = []; }],+ ['targets', (c) => { c.targets = ['EVILMINT']; c.target_kind = 'mint'; }],+ ['expires_at', (c) => { c.expires_at = new Date(c.expires_at.getTime() + 365 * 24 * HOUR); }],+ ['holder_ref', (c) => { c.holder_ref = 'other-strategy'; }],+ ['agent_id', (c) => { c.agent_id = 'agent-2'; }],+ ])('a forged %s no longer verifies', (_field, mutate) => {+ const cap = makeCap({ target_kind: 'mint', targets: ['MintAAA'], per_use_usd: 5 });+ mutate(cap);+ expect(verifyGrant(cap)).toBe(false);+ });++ it('revocation does NOT touch the HMAC (revoke is enforced separately, not forgeable away)', () => {+ const cap = makeCap();+ const before = canonicalScope(cap);+ cap.revoked_at = new Date();+ expect(canonicalScope(cap)).toBe(before);+ expect(verifyGrant(cap)).toBe(true); // signature still valid…+ expect(capabilityLive(cap).ok).toBe(false); // …but the grant is dead+ });++ it('a grant signed under a different secret fails verification', () => {+ const cap = makeCap();+ process.env.WALLET_CAPABILITY_SECRET = 'a-totally-different-secret-value-xyz';+ expect(verifyGrant(cap)).toBe(false);+ process.env.WALLET_CAPABILITY_SECRET = 'test-capability-secret-key-0123456789';+ });+});++describe('scope predicates', () => {+ it('covers exactly its actions', () => {+ const cap = makeCap({ actions: ['snipe'] });+ expect(capabilityCoversAction(cap, 'snipe')).toBe(true);+ expect(capabilityCoversAction(cap, 'trade')).toBe(false);+ expect(capabilityCoversAction(cap, 'x402')).toBe(false);+ });++ it('any-target covers everything; mint/destination need an exact match', () => {+ expect(capabilityCoversTarget(makeCap({ target_kind: 'any' }), 'anything')).toBe(true);+ const mintCap = makeCap({ target_kind: 'mint', targets: ['MintAAA', 'MintBBB'] });+ expect(capabilityCoversTarget(mintCap, 'MintAAA')).toBe(true);+ expect(capabilityCoversTarget(mintCap, 'MintZZZ')).toBe(false);+ expect(capabilityCoversTarget(mintCap, '')).toBe(false);+ });++ it('service targets match on host of a full URL', () => {+ const svc = makeCap({ actions: ['x402'], target_kind: 'service', targets: ['https://api.weather.com'] });+ expect(capabilityCoversTarget(svc, 'https://api.weather.com/v1/forecast?z=1')).toBe(true);+ expect(capabilityCoversTarget(svc, 'https://evil.com/api.weather.com')).toBe(false);+ });++ it('per-use ceiling blocks over-limit single spends', () => {+ const cap = makeCap({ per_use_usd: 5, aggregate_usd: 100 });+ expect(checkPerUse(cap, 4.99)).toBeNull();+ expect(checkPerUse(cap, 5)).toBeNull();+ expect(checkPerUse(cap, 5.01)?.reason).toBe('per_use_exceeded');+ });++ it('aggregate ceiling blocks when prior + this exceeds the budget', () => {+ const cap = makeCap({ aggregate_usd: 40 });+ expect(checkAggregate(35, 5, cap)).toBeNull();+ expect(checkAggregate(38, 5, cap)?.reason).toBe('aggregate_exceeded');+ expect(checkAggregate(0, 40, cap)).toBeNull();+ });+});++describe('evaluateCapabilityScope — authorizes EXACTLY its scope, nothing adjacent', () => {+ const now = 1_700_000_000_000;+ const base = () => makeCap({ actions: ['snipe'], per_use_usd: 10, aggregate_usd: 40, target_kind: 'mint', targets: ['MintAAA'] }, now);++ it('passes an in-scope spend', () => {+ expect(evaluateCapabilityScope({ cap: base(), action: 'snipe', target: 'MintAAA', usdValue: 9, now })).toBeNull();+ });++ it('rejects the wrong action', () => {+ expect(evaluateCapabilityScope({ cap: base(), action: 'trade', target: 'MintAAA', usdValue: 9, now })?.reason).toBe('action_not_allowed');+ });++ it('rejects a disallowed target', () => {+ expect(evaluateCapabilityScope({ cap: base(), action: 'snipe', target: 'MintZZZ', usdValue: 9, now })?.reason).toBe('target_not_allowed');+ });++ it('rejects over the per-use ceiling', () => {+ expect(evaluateCapabilityScope({ cap: base(), action: 'snipe', target: 'MintAAA', usdValue: 11, now })?.reason).toBe('per_use_exceeded');+ });++ it('rejects an expired grant', () => {+ const cap = base();+ expect(evaluateCapabilityScope({ cap, action: 'snipe', target: 'MintAAA', usdValue: 9, now: now + 48 * HOUR })?.reason).toBe('expired');+ });++ it('rejects a revoked grant', () => {+ const cap = base();+ cap.revoked_at = new Date(now);+ expect(evaluateCapabilityScope({ cap, action: 'snipe', target: 'MintAAA', usdValue: 9, now })?.reason).toBe('revoked');+ });++ it('rejects a tampered grant (fails toward LESS access)', () => {+ const cap = base();+ cap.aggregate_usd = 1_000_000; // widen the budget without re-signing+ expect(evaluateCapabilityScope({ cap, action: 'snipe', target: 'MintAAA', usdValue: 9, now })?.reason).toBe('tampered');+ });+});++describe('capability + wallet policy compose — the tighter wins', () => {+ it('capability denials are SpendLimitError, so existing guard catches handle them', () => {+ const err = new CapabilityError('action_not_allowed', 'nope', {});+ expect(err).toBeInstanceOf(SpendLimitError);+ expect(err.status).toBe(403);+ });++ it('a capability can only narrow: a $9 spend in a $10 per-use / $40 wallet-tx world is allowed, $11 is not', () => {+ const cap = makeCap({ per_use_usd: 10, aggregate_usd: 40 });+ // wallet per_tx_usd would be e.g. 40 (looser); capability per_use 10 (tighter) decides.+ expect(checkPerUse(cap, 9)).toBeNull();+ expect(checkPerUse(cap, 11)?.reason).toBe('per_use_exceeded');+ });+});