Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Add proof-of-custody, spend policies, wallet capabilities, and agent mind/mood

nirholasda1c29072d9c
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index c7dacedbe..13e8285fc 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -27,6 +27,26 @@ import { PublicKey } from '@solana/web3.js';
import { sql } from './db.js';
import { solUsdPrice } from './avatar-wallet.js';
import { logAudit } from './audit.js';
+// The wallet's behavioral immune system — an additive anomaly predicate layered on
+// top of the static caps in this file. See api/_lib/anomaly-events.js +
+// api/_lib/wallet-anomaly.js. Only referenced inside function bodies, so the
+// mutual import with that module resolves fine at call time.
+import { guardOutboundAnomaly } from './anomaly-events.js';
+// Natural-language spend policies: the LLM authors the rule document, this pure,
+// total evaluator enforces it. Layered ON TOP of the numeric caps below — never
+// weakening them. See api/_lib/spend-policy-rules.js.
+import {
+ getPolicyRules, normalizePolicyRules, evaluatePolicy, isDenied,
+ referencedFields, describePolicyRules, diffPolicies,
+} from './spend-policy-rules.js';
+// Scoped session keys (least-privilege capabilities). Imported for the additive
+// capability gate composed into enforceSpendLimit / reserveSpendUsd below. The
+// import is circular (wallet-capabilities imports recordCustodyEvent from here);
+// safe because both sides only touch the bindings at runtime, never at module eval.
+import {
+ evaluateCapabilityScope, capabilityError, capabilitySpentUsd, checkAggregate,
+ resolveCapabilityForSpend, reserveCapabilitySpend,
+} from './wallet-capabilities.js';
// Base58 alphabet, 32–44 chars covers every ed25519 pubkey. A cheap pre-filter
// before the (heavier) PublicKey parse + curve check.
@@ -50,6 +70,15 @@ export const SPEND_LIMIT_DEFAULTS = Object.freeze({
// safe direction (sweeping out) stays open so a freeze can be used to lock down
// a misbehaving agent while still evacuating its balance.
frozen: false,
+ // Least-privilege enforcement. When true, every AUTONOMOUS outbound path
+ // (trade, snipe, x402) must present a valid, unexpired, unrevoked scoped
+ // capability that covers the action — no covering capability ⇒ deny (fail
+ // safe). When false (default), capabilities still STRICTLY NARROW any spend
+ // that presents one, but an autonomous spend without a capability is governed
+ // by the wallet-wide policy alone (preserves existing automated flows). See
+ // api/_lib/wallet-capabilities.js. Owner withdraw is never a delegated
+ // capability and is unaffected by this flag.
+ require_capabilities: false,
});
// Per-agent discretionary-trade policy (lamports-denominated), stored at
@@ -146,6 +175,7 @@ export function normalizeSpendLimits(raw) {
per_tx_usd: numOrNull(r.per_tx_usd),
withdraw_allowlist: deduped,
frozen: r.frozen === true,
+ require_capabilities: r.require_capabilities === true,
updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
};
}
@@ -175,6 +205,8 @@ export async function setSpendLimits(agentId, userId, patch, { req = null } = {}
withdraw_allowlist:
'withdraw_allowlist' in patch ? patch.withdraw_allowlist : prev.withdraw_allowlist,
frozen: 'frozen' in patch ? patch.frozen === true : prev.frozen,
+ require_capabilities:
+ 'require_capabilities' in patch ? patch.require_capabilities === true : prev.require_capabilities,
});
next.updated_at = new Date().toISOString();
@@ -428,27 +460,249 @@ export async function getDailySpendUsd(agentId, network = 'mainnet', windowHours
return Number(row?.usd || 0);
}
+// ── natural-language policy enforcement ───────────────────────────────────────
+// The owner-authored, code-enforced policy (meta.policy_rules) layered on top of
+// the numeric caps. A block here returns the HUMAN rule that caught the spend.
+
+/** Count how many times this agent has previously paid a given destination. Backs
+ * the `counterparty_seen_before` signal ("only pay services you've used before").
+ * Best-effort: any error reports "not seen", and the rule itself decides what that
+ * means (a `is false` rule then fires — fail-safe-to-block for that intent). */
+async function countPriorSpendsTo(agentId, destination, network = 'mainnet') {
+ if (!destination) return 0;
+ const [row] = await sql`
+ SELECT COUNT(*)::int AS n
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type = 'spend'
+ AND destination = ${destination}
+ AND status IN ('ok', 'pending', 'confirmed')
+ `;
+ return Number(row?.n || 0);
+}
+
+/** Lazily load an agent's policy document from the DB (only when a caller passes
+ * pre-resolved `limits` without `meta`, so enforcement is universal regardless of
+ * how the call site resolved its caps). */
+async function loadPolicyRulesById(agentId) {
+ try {
+ const [row] = await sql`SELECT meta->'policy_rules' AS policy_rules FROM agent_identities WHERE id = ${agentId}`;
+ return normalizePolicyRules(row?.policy_rules);
+ } catch (e) {
+ console.warn('[policy] load rules failed', e?.message);
+ return normalizePolicyRules(null);
+ }
+}
+
+/** Trip the wallet freeze switch from a `freeze` policy rule. Idempotent, audited,
+ * and never throws — a logging/DB hiccup must not turn the (correct) block into a
+ * pass. Owner withdraw stays open exactly as a manual freeze. */
+async function freezeWalletFromPolicy(agentId, userId, rule, network) {
+ try {
+ await sql`
+ UPDATE agent_identities
+ SET meta = jsonb_set(
+ jsonb_set(coalesce(meta, '{}'::jsonb), '{spend_limits}', coalesce(meta->'spend_limits', '{}'::jsonb)),
+ '{spend_limits,frozen}', 'true'::jsonb
+ )
+ WHERE id = ${agentId} AND coalesce((meta->'spend_limits'->>'frozen')::boolean, false) = false
+ `;
+ await recordCustodyEvent({
+ agentId, userId: userId ?? null, eventType: 'limit_change', network,
+ reason: 'policy_freeze',
+ meta: { trigger: 'policy_rule', rule_id: rule?.id || null, rule: rule?.label || null },
+ });
+ logAudit({ userId: userId ?? null, action: 'custody.policy_freeze', resourceId: agentId, meta: { rule_id: rule?.id || null } });
+ } catch (e) {
+ console.warn('[policy] auto-freeze failed', e?.message);
+ }
+}
+
+/**
+ * Evaluate the natural-language policy for one outbound spend and throw the human
+ * rule that catches it. Total: any internal failure on an AUTONOMOUS path fails
+ * safe to a block; the owner's own withdraw is never trapped by an internal error.
+ *
+ * @param {object} o
+ * @param {string} o.agentId
+ * @param {object} o.policy normalized policy document
+ * @param {string} o.category
+ * @param {number|null} o.usdValue
+ * @param {string} [o.asset]
+ * @param {string} [o.destination]
+ * @param {object} [o.limits] resolved numeric limits (for destination_allowlisted)
+ * @param {object} [o.policyContext] extra live signals: token_age_hours, trade_pnl_pct, sol_reserve_after
+ * @param {number} [o.userId]
+ * @param {string} [o.network]
+ * @throws {SpendLimitError} when the policy denies the spend
+ */
+async function enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits, policyContext = {}, userId, network = 'mainnet' }) {
+ if (!policy || !Array.isArray(policy.rules) || !policy.rules.length) return;
+ const autonomous = category !== 'withdraw';
+
+ let ctx;
+ try {
+ const refs = referencedFields(policy);
+ const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
+ const dest = typeof destination === 'string' ? destination.trim() : '';
+ const allow = Array.isArray(limits?.withdraw_allowlist) ? limits.withdraw_allowlist : [];
+
+ ctx = {
+ category,
+ asset: asset || undefined,
+ counterparty: dest || undefined,
+ amount_usd: hasUsd ? usdValue : undefined,
+ time_of_day_utc: new Date().getUTCHours(),
+ destination_allowlisted: dest ? allow.includes(dest) : undefined,
+ // Live signals the trade/snipe paths can supply (token age, P&L, reserve).
+ ...sanitizePolicyContext(policyContext),
+ };
+
+ // Async signals — only fetched when a live rule references them.
+ if ((refs.has('daily_spent_usd') || refs.has('daily_total_usd')) && hasUsd) {
+ const spent = await getDailySpendUsd(agentId, network);
+ ctx.daily_spent_usd = spent;
+ ctx.daily_total_usd = spent + usdValue;
+ }
+ if (refs.has('counterparty_seen_before') && dest) {
+ ctx.counterparty_seen_before = (await countPriorSpendsTo(agentId, dest, network)) > 0;
+ }
+ } catch (e) {
+ // Building the context failed (DB outage, etc.). Fail safe: block an
+ // autonomous spend; never trap the owner's withdraw.
+ console.warn('[policy] context build failed', e?.message);
+ if (!autonomous) return;
+ throw new SpendLimitError('policy_unavailable', 'Couldn’t verify this spend against your safety rules right now. The spend was blocked to stay safe — try again in a moment.', { category });
+ }
+
+ const verdict = evaluatePolicy(policy, ctx);
+ if (!isDenied(verdict.decision)) return;
+
+ // A `freeze` rule also trips the wallet kill-switch so everything else stops.
+ if (verdict.decision === 'freeze') {
+ await freezeWalletFromPolicy(agentId, userId, verdict.matched, network);
+ throw new SpendLimitError(
+ 'policy_freeze',
+ `Wallet frozen by your rule: ${verdict.message} All autonomous spending is now paused; unfreeze it under Limits & Safety.`,
+ { rule_id: verdict.matched?.id || null, rule: verdict.message, rule_index: verdict.ruleIndex, decision: 'freeze' },
+ );
+ }
+
+ const code = verdict.decision === 'step_up' ? 'policy_step_up' : 'policy_blocked';
+ const prefix = verdict.decision === 'step_up' ? 'This spend needs your approval' : 'Blocked by your rule';
+ throw new SpendLimitError(
+ code,
+ `${prefix}: ${verdict.message}`,
+ { rule_id: verdict.matched?.id || null, rule: verdict.message, rule_index: verdict.ruleIndex, decision: verdict.decision },
+ );
+}
+
+/** Keep only the numeric live signals the evaluator understands, coerced + finite. */
+function sanitizePolicyContext(extra) {
+ const out = {};
+ if (!extra || typeof extra !== 'object') return out;
+ for (const k of ['token_age_hours', 'trade_pnl_pct', 'sol_reserve_after']) {
+ const n = Number(extra[k]);
+ if (extra[k] != null && Number.isFinite(n)) out[k] = n;
+ }
+ return out;
+}
+
+/**
+ * Persist a natural-language policy onto the agent (owner-only). The caller passes
+ * the validated rule array (from the compiler) plus the original English. The
+ * document is re-normalized here so the stored policy is always enforceable, a
+ * `limit_change` custody event records the English + a diff vs the prior policy, and
+ * a platform audit row is written. Returns the new normalized document.
+ */
+export async function setPolicyRules(agentId, userId, rules, { english = null, req = null } = {}) {
+ const [row] = await sql`
+ SELECT id, user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });
+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403, code: 'forbidden' });
+
+ const prev = getPolicyRules(row.meta);
+ const next = normalizePolicyRules({ rules, source_text: typeof english === 'string' ? english : prev.source_text });
+ next.updated_at = new Date().toISOString();
+ const diff = diffPolicies(prev, next);
+
+ const meta = { ...(row.meta || {}), policy_rules: next };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;
+
+ await recordCustodyEvent({
+ agentId,
+ userId,
+ eventType: 'limit_change',
+ reason: 'policy_updated',
+ meta: { english: next.source_text, prev_rules: prev.rules, next_rules: next.rules, readback: describePolicyRules(next), diff },
+ }).catch((e) => console.warn('[custody] policy limit_change record failed', e?.message));
+ logAudit({ userId, action: 'custody.policy_change', resourceId: agentId, meta: { diff, rule_count: next.rules.length }, req });
+
+ return next;
+}
+
/**
* Enforce the per-agent spend policy for one outbound movement.
*
* @param {object} o
* @param {string} o.agentId
- * @param {object} [o.meta] agent meta (limits read from here if `limits` absent)
+ * @param {object} [o.meta] agent meta (limits + policy read from here if absent)
* @param {object} [o.limits] pre-resolved limits (skips the meta read)
+ * @param {object} [o.policyRules] pre-resolved NL policy document (skips the meta/DB read)
* @param {'trade'|'snipe'|'x402'|'withdraw'} o.category
* @param {number|null} o.usdValue USD-equivalent of this tx (null = unpriceable)
+ * @param {string} [o.asset] 'SOL' | 'USDC' | mint — for asset-scoped policy rules
* @param {string} [o.destination] base58 recipient (required for allowlist on withdraw)
+ * @param {object} [o.policyContext] live signals for policy rules (token_age_hours, trade_pnl_pct, sol_reserve_after)
+ * @param {number} [o.userId] actor (for policy-freeze audit)
* @param {string} [o.network]
* @returns {Promise<{ ok: true, limits: object, dailySpentUsd: number|null }>}
* @throws {SpendLimitError} on any breach (always 4xx)
*/
+// ── capability gate (scoped session keys) ──────────────────────────────────
+// Resolve + scope-check the capability that authorizes an autonomous spend, if any.
+// Composed additively into both shared guards. A capability STRICTLY NARROWS: the
+// wallet-wide checks must pass AND this gate must pass. Autonomous categories only
+// (trade/snipe/x402); an owner-initiated withdraw is never a delegated capability.
+//
+// A caller may pass a pre-resolved `capability`, or a `capabilityHolderRef`
+// (skill/strategy/integration id) we resolve to the tightest live grant. When the
+// wallet has require_capabilities on and no covering grant exists, the spend is
+// DENIED (fail safe). Returns the resolved capability, or null when none applies
+// and none is required (unchanged behavior for wallets not using capabilities).
+async function resolveSpendCapability({ agentId, lim, category, usdValue, target, capability, capabilityHolderRef, now }) {
+ if (category === 'withdraw') return null;
+ let cap = capability || null;
+ if (!cap && (lim.require_capabilities || capabilityHolderRef)) {
+ cap = await resolveCapabilityForSpend({ agentId, action: category, holderRef: capabilityHolderRef ?? null, target, usdValue, now });
+ }
+ if (!cap) {
+ if (lim.require_capabilities) throw capabilityError('capability_required', { category });
+ return null;
+ }
+ const scope = evaluateCapabilityScope({ cap, action: category, target, usdValue, now });
+ if (scope) throw capabilityError(scope.reason, scope.detail);
+ return cap;
+}
+
export async function enforceSpendLimit({
agentId,
meta,
limits,
+ policyRules,
category,
usdValue,
+ asset,
destination,
+ policyContext,
+ userId,
+ capability,
+ capabilityHolderRef,
+ target,
+ now,
network = 'mainnet',
}) {
const lim = limits || getSpendLimits(meta);
@@ -474,9 +728,15 @@ 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));
+ await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network });
+
const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
- // 2. Per-transaction ceiling.
+ // 3. Per-transaction ceiling.
if (lim.per_tx_usd != null && hasUsd && usdValue > lim.per_tx_usd + 1e-9) {
throw new SpendLimitError(
'per_tx_exceeded',
@@ -485,7 +745,7 @@ export async function enforceSpendLimit({
);
}
- // 3. Rolling daily ceiling.
+ // 4. Rolling daily ceiling.
let dailySpentUsd = null;
if (lim.daily_usd != null && hasUsd) {
dailySpentUsd = await getDailySpendUsd(agentId, network);
@@ -498,7 +758,30 @@ export async function enforceSpendLimit({
}
}
- return { ok: true, limits: lim, dailySpentUsd };
+ // 5. Behavioral anomaly guard (the wallet's immune system). Scores this action
+ // against the agent's learned normal; on a freeze verdict it has already frozen
+ // the wallet + notified the owner, and we surface a SpendLimitError so the
+ // triggering action is held. Self-contained fail-safe — never fails open here.
+ const anomaly = await guardOutboundAnomaly({
+ agentId, userId, meta, category, usdValue, destination, asset, network,
+ });
+ if (anomaly.decision === 'freeze') {
+ throw new SpendLimitError('wallet_anomaly_frozen', anomaly.message, anomaly.detail || {});
+ }
+
+ // 4b. Capability gate (least-privilege). Scope (action/target/expiry/revoked/
+ // per-use) + a non-atomic aggregate read-check, mirroring how this enforce path
+ // already treats the daily cap non-atomically. The atomic aggregate reserve lives
+ // in reserveSpendUsd → reserveCapabilitySpend.
+ const _cap = await resolveSpendCapability({ agentId, lim, category, usdValue, target, capability, capabilityHolderRef, now });
+ const capabilityId = _cap?.id || null;
+ if (_cap && _cap.aggregate_usd != null && hasUsd) {
+ const _spent = await capabilitySpentUsd(_cap.id);
+ const _agg = checkAggregate(_spent, usdValue, _cap);
+ if (_agg) throw capabilityError(_agg.reason, _agg.detail);
+ }
+
+ return { ok: true, limits: lim, dailySpentUsd, capabilityId, anomaly: anomaly.verdict || null };
}
/**
@@ -520,9 +803,15 @@ export async function reserveSpendUsd({
userId,
meta,
limits,
+ policyRules,
category,
usdValue,
destination,
+ policyContext,
+ capability,
+ capabilityHolderRef,
+ target,
+ now,
network = 'mainnet',
asset = 'USDC',
rowMeta = {},
@@ -550,6 +839,11 @@ 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));
+ await enforcePolicyRules({ agentId, policy, category, usdValue, asset, destination, limits: lim, policyContext, userId, network });
+
const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
// Per-transaction ceiling (no lock needed — a single value vs a constant).
@@ -561,8 +855,41 @@ export async function reserveSpendUsd({
);
}
+ // Capability gate (least-privilege). When a capability is in play (presented,
+ // resolvable, or required for this wallet), delegate the reserve to
+ // reserveCapabilitySpend: it atomically meters BOTH the capability aggregate
+ // ceiling AND the wallet daily cap under advisory locks and tags the pending row
+ // with capability_id. Return early so we never double-insert.
+ if (category !== 'withdraw') {
+ const _cap = await resolveSpendCapability({ agentId, lim, category, usdValue, target: target ?? destination, capability, capabilityHolderRef, now });
+ if (_cap) {
+ const _r = await reserveCapabilitySpend({
+ capabilityId: _cap.id, agentId, userId, action: category,
+ target: target ?? destination, usdValue, dailyUsd: lim.daily_usd,
+ network, asset, destination, rowMeta, now,
+ });
+ return { ok: true, reservationId: _r.reservationId, dailySpentUsd: _r.spentBefore, capabilityId: _cap.id };
+ }
+ }
+
const metaJson = JSON.stringify(rowMeta ?? {});
+ // Behavioral anomaly guard for a just-reserved spend. The pending row already
+ // exists (selfCounted: live velocity counts include it), so on a freeze verdict
+ // we RELEASE the reservation — it must not hold daily headroom — before surfacing
+ // the SpendLimitError. guardOutboundAnomaly has already frozen + notified.
+ const runAnomaly = async (reservationId, dailySpentUsd) => {
+ const anomaly = await guardOutboundAnomaly({
+ agentId, userId, meta, category, usdValue, destination, asset, network,
+ custodyEventId: reservationId, selfCounted: true,
+ });
+ if (anomaly.decision === 'freeze') {
+ await releaseSpendReservation(reservationId, 'anomaly_frozen');
+ throw new SpendLimitError('wallet_anomaly_frozen', anomaly.message, anomaly.detail || {});
+ }
+ return { ok: true, reservationId, dailySpentUsd, anomaly: anomaly.verdict || null };
+ };
+
// No daily ceiling, or an unpriceable spend: just reserve a pending row (it
// can't gate a cap it has no number for) so the ledger still reflects it.
if (lim.daily_usd == null || !hasUsd) {
@@ -570,7 +897,7 @@ export async function reserveSpendUsd({
agentId, userId, eventType: 'spend', category, network, asset,
usd: hasUsd ? usdValue : null, destination, status: 'pending', meta: rowMeta,
});
- return { ok: true, reservationId, dailySpentUsd: null };
+ return runAnomaly(reservationId, null);
}
// Atomic daily-cap reserve: the advisory xact lock serializes concurrent spends
@@ -610,7 +937,7 @@ export async function reserveSpendUsd({
);
}
- return { ok: true, reservationId: rows[0].id, dailySpentUsd: Number(rows[0].spent_before || 0) };
+ return runAnomaly(rows[0].id, Number(rows[0].spent_before || 0));
}
/**
@@ -630,19 +957,22 @@ export async function releaseSpendReservation(reservationId, reason = 'spend_abo
const CUSTODY_COLUMNS = [
'agent_id', 'user_id', 'event_type', 'category', 'network', 'asset',
'amount_lamports', 'amount_raw', 'usd', 'destination', 'signature',
- 'reason', 'status', 'idempotency_key', 'meta',
+ 'reason', 'status', 'idempotency_key', 'capability_id', 'meta',
];
/**
* Write a row into the custody audit trail / spend ledger.
* Returns the new row id. Callers in fire-and-forget contexts should `.catch()`.
+ * `capabilityId` (optional) tags the row with the scoped session key that
+ * authorized the spend, so the per-capability aggregate ceiling and the owner
+ * Access UI read from the same ledger as the wallet daily cap.
*/
export async function recordCustodyEvent(e) {
const [row] = await sql`
INSERT INTO agent_custody_events
(agent_id, user_id, event_type, category, network, asset,
amount_lamports, amount_raw, usd, destination, signature,
- reason, status, idempotency_key, meta)
+ reason, status, idempotency_key, capability_id, meta)
VALUES (
${e.agentId},
${e.userId ?? null},
@@ -658,6 +988,7 @@ export async function recordCustodyEvent(e) {
${e.reason ?? null},
${e.status ?? 'ok'},
${e.idempotencyKey ?? null},
+ ${e.capabilityId ?? null},
${JSON.stringify(e.meta ?? {})}::jsonb
)
RETURNING id
diff --git a/api/_lib/anomaly-events.js b/api/_lib/anomaly-events.js
new file mode 100644
index 000000000..38a3d9735
--- /dev/null
+++ b/api/_lib/anomaly-events.js
@@ -0,0 +1,373 @@
+// Behavioral anomaly orchestration — the live wiring around the pure scoring
+// engine (api/_lib/wallet-anomaly.js). This module does the I/O the engine
+// deliberately avoids: it reads an agent's real custody history to build/cache a
+// baseline, pulls live velocity counts, scores each outbound action, records the
+// scored decision to the anomaly timeline, and — on a freeze verdict — flips the
+// wallet's freeze switch and fires a real owner notification.
+//
+// `guardOutboundAnomaly()` is the single hot-path entrypoint. It is called from
+// the shared spend guards (enforceSpendLimit / reserveSpendUsd) AFTER the static
+// caps pass, so it covers every autonomous outbound path (trade/snipe/x402) plus
+// withdraw. It is fail-safe: any internal error defaults to the safe side per the
+// owner's sensitivity (Strict freezes; otherwise the spend is allowed but the
+// error is recorded for the timeline). It never throws anything except a
+// SpendLimitError describing the freeze — so a boundary surfaces it as a clean 4xx.
+
+import { sql } from './db.js';
+import { insertNotification } from './notify.js';
+import {
+ computeBaseline,
+ scoreOutbound,
+ summarize,
+ getAnomalyConfig,
+ normalizeAnomalyConfig,
+ applyApproval,
+ sensitivityPreset,
+ MIN_HISTORY,
+} from './wallet-anomaly.js';
+
+// Cached baseline freshness. Recomputing the baseline from history on every spend
+// would be wasteful; we cache it in agent_identities.meta.anomaly_baseline and
+// refresh at most this often. The velocity counts are always read live (cheap).
+const BASELINE_TTL_MS = 3 * 60 * 60 * 1000; // 3h
+// How many recent spend rows feed a baseline recompute (capped so a busy wallet
+// can't make the recompute query unbounded).
+const BASELINE_SAMPLE = 2000;
+
+// A freeze verdict is returned (not thrown) from guardOutboundAnomaly so the
+// shared guards can raise their OWN SpendLimitError — the one the boundaries
+// already match on with `instanceof`. This keeps the SpendLimitError class in one
+// place and avoids a circular import between this module and agent-trade-guards.js.
+const FREEZE_MESSAGE =
+ 'This action was held and the wallet frozen — it looked unusual for this agent. ' +
+ 'Review it under Self-defending wallet to approve or keep frozen.';
+
+/** Live spend velocity for an agent: counts in the trailing 1- and 10-minute windows. */
+async function recentVelocity(agentId, network) {
+ const [row] = await sql`
+ SELECT
+ count(*) FILTER (WHERE created_at > now() - interval '1 minute')::int AS c1,
+ count(*) FILTER (WHERE created_at > now() - interval '10 minutes')::int AS c10
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type = 'spend'
+ AND status IN ('ok', 'pending', 'confirmed')
+ `;
+ return { c1: Number(row?.c1) || 0, c10: Number(row?.c10) || 0 };
+}
+
+/** Recompute the baseline from the agent's recent priced custody spend history. */
+async function recomputeBaseline(agentId, nowMs) {
+ const rows = await sql`
+ SELECT usd, destination, asset, category, created_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND event_type = 'spend'
+ AND status IN ('ok', 'confirmed')
+ ORDER BY id DESC
+ LIMIT ${BASELINE_SAMPLE}
+ `;
+ return computeBaseline(rows, nowMs);
+}
+
+/** Read the cached baseline from meta, recomputing + persisting it if stale/missing. */
+async function resolveBaseline(agentId, meta, nowMs) {
+ const cached = meta?.anomaly_baseline;
+ const computedAt = cached?.computed_at ? Date.parse(cached.computed_at) : NaN;
+ if (cached && Number.isFinite(computedAt) && nowMs - computedAt < BASELINE_TTL_MS) {
+ return cached;
+ }
+ const baseline = await recomputeBaseline(agentId, nowMs);
+ // Persist back for the next caller. Fire-and-forget: a failed cache write must
+ // never block a spend, and the next call simply recomputes.
+ sql`
+ UPDATE agent_identities
+ SET meta = coalesce(meta, '{}'::jsonb) || ${JSON.stringify({ anomaly_baseline: baseline })}::jsonb
+ WHERE id = ${agentId}
+ `.catch((e) => console.warn('[anomaly] baseline cache write failed', e?.message));
+ return baseline;
+}
+
+/**
+ * Record one scored decision to the anomaly timeline. Allowed decisions with no
+ * contributing factors are NOT recorded (zero-signal spends would be pure noise);
+ * everything notable (any factor) and every freeze is recorded.
+ * @returns {Promise<string|null>} the new anomaly event id, or null if not recorded
+ */
+async function recordAnomalyEvent({ agentId, userId, network, action, verdict, custodyEventId = null }) {
+ const flagged = verdict.decision === 'freeze';
+ if (!flagged && (!verdict.factors || verdict.factors.length === 0)) return null;
+ const summary = summarize(verdict);
+ const hourUtc = Number.isFinite(action.atMs) ? new Date(action.atMs).getUTCHours() : null;
+ const [row] = await sql`
+ INSERT INTO agent_anomaly_events
+ (agent_id, user_id, network, category, asset, usd, destination, score, decision,
+ critical, sensitivity, factors, summary, status, hour_utc, custody_event_id)
+ VALUES (
+ ${agentId}, ${userId ?? null}, ${network}, ${action.category ?? null}, ${action.asset ?? null},
+ ${action.usdValue ?? null}, ${action.destination ?? null}, ${verdict.score}, ${verdict.decision},
+ ${verdict.critical}, ${verdict.sensitivity}, ${JSON.stringify(verdict.factors)}::jsonb, ${summary},
+ ${flagged ? 'flagged' : 'allowed'}, ${hourUtc}, ${custodyEventId != null ? String(custodyEventId) : null}
+ )
+ RETURNING id
+ `;
+ return row?.id ? String(row.id) : null;
+}
+
+/**
+ * Idempotently freeze a wallet via the shared spend-limit switch. Only flips the
+ * flag when it is currently off, so an anomaly can never thrash freeze→unfreeze→
+ * refreeze, and writes a custody audit row for the auto-action.
+ * @returns {Promise<boolean>} true if THIS call performed the freeze
+ */
+async function freezeWallet(agentId, userId, nowIso, reason) {
+ const rows = await sql`
+ UPDATE agent_identities
+ SET meta = coalesce(meta, '{}'::jsonb) || jsonb_build_object(
+ 'spend_limits',
+ coalesce(meta->'spend_limits', '{}'::jsonb) || jsonb_build_object('frozen', true, 'updated_at', ${nowIso}::text)
+ )
+ WHERE id = ${agentId}
+ AND coalesce((meta->'spend_limits'->>'frozen')::boolean, false) = false
+ RETURNING id
+ `;
+ const didFreeze = rows.length > 0;
+ if (didFreeze) {
+ await sql`
+ INSERT INTO agent_custody_events (agent_id, user_id, event_type, reason, status, meta)
+ VALUES (${agentId}, ${userId ?? null}, 'limit_change', ${reason}, 'ok',
+ ${JSON.stringify({ auto_freeze: true, source: 'anomaly_guard' })}::jsonb)
+ `.catch((e) => console.warn('[anomaly] freeze audit failed', e?.message));
+ }
+ return didFreeze;
+}
+
+/**
+ * Score one pending outbound action and enforce the graduated response.
+ *
+ * @param {object} o
+ * @param {string} o.agentId
+ * @param {string} [o.userId]
+ * @param {object} o.meta agent meta (carries anomaly config + cached baseline)
+ * @param {'trade'|'snipe'|'x402'|'withdraw'} o.category
+ * @param {number|null} o.usdValue
+ * @param {string} [o.destination]
+ * @param {string} [o.asset]
+ * @param {string} [o.network]
+ * @param {number|string|null} [o.custodyEventId] link the timeline row to a spend row
+ * @param {boolean} [o.selfCounted] true when a pending row for THIS action already exists
+ * (reserveSpendUsd path) so velocity isn't double-counted
+ * @returns {Promise<{ decision:'allow'|'freeze', verdict:object|null, anomalyId:string|null,
+ * froze:boolean, message?:string, detail?:object }>} on a 'freeze' decision the caller
+ * (the shared guard) raises a SpendLimitError using message/detail. Never throws on a
+ * normal verdict — only a programming error would propagate.
+ */
+export async function guardOutboundAnomaly({
+ agentId,
+ userId = null,
+ meta = null,
+ category,
+ usdValue = null,
+ destination = null,
+ asset = null,
+ network = 'mainnet',
+ custodyEventId = null,
+ selfCounted = false,
+}) {
+ const nowMs = Date.now();
+ const action = {
+ usdValue: typeof usdValue === 'number' && Number.isFinite(usdValue) ? usdValue : null,
+ destination: destination || null,
+ asset: asset || null,
+ category,
+ atMs: nowMs,
+ };
+
+ // `config` is resolved inside the try so a meta-load failure also lands on the
+ // fail-safe path. Default to a balanced posture if we never get that far.
+ let config = null;
+ let verdict;
+ try {
+ // Many autonomous callers pass `limits` but not `meta`/`userId`. Resolving the
+ // agent row here (one PK read) makes the guard cover EVERY outbound path and
+ // lets the owner notification reach the real owner regardless of the caller.
+ if (!meta || userId == null) {
+ const [row] = await sql`SELECT user_id, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!meta) meta = row?.meta || {};
+ if (userId == null) userId = row?.user_id || null;
+ }
+ config = getAnomalyConfig(meta);
+ // Guard disabled by the owner → nothing to do.
+ if (!config.enabled) return { decision: 'allow', verdict: null, anomalyId: null, froze: false };
+
+ const [baseline, vel] = await Promise.all([
+ resolveBaseline(agentId, meta, nowMs),
+ recentVelocity(agentId, network),
+ ]);
+ // Count THIS action exactly once. reserveSpendUsd inserts the pending row
+ // before calling us (selfCounted), so the live counts already include it.
+ const bump = selfCounted ? 0 : 1;
+ const recent = { count_1min: vel.c1 + bump, count_10min: vel.c10 + bump };
+ verdict = scoreOutbound({ baseline, config, action, recent });
+ } catch (err) {
+ // Fail-safe: never let a scoring/IO error silently fail open. Strict owners
+ // get a freeze on uncertainty; others are allowed but the error is recorded.
+ console.warn('[anomaly] scoring failed', err?.message);
+ const strict = config && sensitivityPreset(config.sensitivity).key === 'strict';
+ if (strict && category !== 'withdraw') {
+ const froze = await freezeWallet(agentId, userId, new Date(nowMs).toISOString(), 'anomaly_scoring_error').catch(() => false);
+ const [row] = await sql`
+ INSERT INTO agent_anomaly_events
+ (agent_id, user_id, network, category, usd, destination, score, decision, critical, sensitivity, factors, summary, status, hour_utc)
+ VALUES (${agentId}, ${userId ?? null}, ${network}, ${category}, ${usdValue ?? null}, ${destination ?? null},
+ 1, 'freeze', true, ${config.sensitivity}, '[]'::jsonb,
+ 'Froze on the safe side — the anomaly guard could not finish scoring this action.', 'flagged',
+ ${new Date(nowMs).getUTCHours()})
+ RETURNING id
+ `.catch(() => [null]);
+ const anomalyId = row?.id ? String(row.id) : null;
+ notifyFrozen({ agentId, userId, category, usdValue, summary: 'The guard could not score an action and froze the wallet to be safe.', score: 1, factors: [], anomalyId });
+ return {
+ decision: 'freeze', verdict: null, anomalyId, froze,
+ message: 'This wallet was frozen as a safety precaution — the guard could not finish scoring this action. Review it under Self-defending wallet, then approve or keep frozen.',
+ detail: { category, reason: 'scoring_error', anomaly_id: anomalyId },
+ };
+ }
+ return { decision: 'allow', verdict: null, anomalyId: null, froze: false };
+ }
+
+ // Withdraw is the owner's own escape hatch (it stays open even when frozen — a
+ // freeze must never trap funds). So we SCORE + RECORD withdraws for visibility
+ // and may freeze the autonomous paths, but never block the withdraw itself.
+ const enforce = category !== 'withdraw';
+ let froze = false;
+ let anomalyId = null;
+
+ if (verdict.decision === 'freeze' && enforce) {
+ froze = await freezeWallet(agentId, userId, new Date(nowMs).toISOString(), 'anomaly_autofreeze');
+ anomalyId = await recordAnomalyEvent({ agentId, userId, network, action, verdict, custodyEventId }).catch((e) => {
+ console.warn('[anomaly] flag record failed', e?.message);
+ return null;
+ });
+ notifyFrozen({
+ agentId, userId, category, usdValue: action.usdValue,
+ summary: summarize(verdict), score: verdict.score, factors: verdict.factors, anomalyId,
+ });
+ return {
+ decision: 'freeze', verdict, anomalyId, froze,
+ message: FREEZE_MESSAGE,
+ detail: { category, score: verdict.score, anomaly_id: anomalyId, factors: verdict.factors.map((f) => f.label) },
+ };
+ }
+
+ // Allowed (or a withdraw we only record). Persist if notable. A withdraw that
+ // scored a freeze is recorded as 'flagged' for the timeline but never blocked.
+ anomalyId = await recordAnomalyEvent({ agentId, userId, network, action, verdict, custodyEventId }).catch((e) => {
+ console.warn('[anomaly] record failed', e?.message);
+ return null;
+ });
+ return { decision: verdict.decision === 'freeze' ? 'freeze' : 'allow', verdict, anomalyId, froze };
+}
+
+/** Real owner notification for an auto-freeze (in-app + push, gated by prefs). */
+function notifyFrozen({ agentId, userId, category, usdValue, summary, score, factors, anomalyId = null }) {
+ if (!userId) return;
+ insertNotification(userId, 'wallet_anomaly_frozen', {
+ agent_id: agentId,
+ link: `/agent/${encodeURIComponent(agentId)}/wallet#guard`,
+ category,
+ usd: usdValue ?? null,
+ score,
+ summary,
+ factors: Array.isArray(factors) ? factors.slice(0, 4).map((f) => f.label) : [],
+ anomaly_id: anomalyId,
+ });
+}
+
+// ── timeline + adjudication (read by the guard endpoint) ────────────────────────
+
+/** Owner-facing anomaly timeline, newest first, keyset-paginated by id. */
+export async function listAnomalyEvents(agentId, { limit = 50, beforeId = null } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ const rows = await sql`
+ SELECT id, network, category, asset, usd, destination, score, decision, critical,
+ sensitivity, factors, summary, status, hour_utc, swept, adjudicated_at, created_at
+ FROM agent_anomaly_events
+ WHERE agent_id = ${agentId}
+ AND (${beforeId}::bigint IS NULL OR id < ${beforeId})
+ ORDER BY id DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
+
+/** The open flags (frozen, awaiting the owner's one-tap call) for an agent. */
+export async function listOpenFlags(agentId) {
+ return sql`
+ SELECT id, category, asset, usd, destination, score, factors, summary, hour_utc, created_at
+ FROM agent_anomaly_events
+ WHERE agent_id = ${agentId} AND status = 'flagged'
+ ORDER BY id DESC
+ LIMIT 20
+ `;
+}
+
+/** Fetch one flagged event by id (owner-scoped by the caller). */
+export async function getAnomalyEvent(agentId, eventId) {
+ const [row] = await sql`
+ SELECT id, agent_id, user_id, category, asset, usd, destination, score, factors, summary,
+ status, hour_utc, created_at
+ FROM agent_anomaly_events
+ WHERE agent_id = ${agentId} AND id = ${eventId}
+ `;
+ return row || null;
+}
+
+/** Mark a flagged event's adjudication outcome. */
+export async function setAnomalyStatus(eventId, { status, userId, swept = false }) {
+ await sql`
+ UPDATE agent_anomaly_events
+ SET status = ${status},
+ adjudicated_by = ${userId ?? null},
+ adjudicated_at = now(),
+ swept = ${swept ? true : false} OR swept
+ WHERE id = ${eventId}
+ `;
+}
+
+// ── owner-facing helpers (used by the guard endpoint) ───────────────────────────
+
+/**
+ * Load the agent's behavioral baseline for display, recomputing + caching if stale.
+ * Adds a `low_history` flag so the UI can be honest when tolerances are wide.
+ */
+export async function loadBaselineForDisplay(agentId, meta) {
+ const baseline = await resolveBaseline(agentId, meta, Date.now());
+ return { ...baseline, low_history: (baseline.n || 0) < MIN_HISTORY };
+}
+
+/**
+ * Persist an owner config patch onto agent_identities.meta.anomaly. Returns the new
+ * normalized config. The caller must have already verified ownership.
+ */
+export async function saveAnomalyConfig(agentId, prevMeta, patch) {
+ const next = normalizeAnomalyConfig({ ...getAnomalyConfig(prevMeta), ...patch });
+ next.updated_at = new Date().toISOString();
+ await sql`
+ UPDATE agent_identities
+ SET meta = coalesce(meta, '{}'::jsonb) || ${JSON.stringify({ anomaly: next })}::jsonb
+ WHERE id = ${agentId}
+ `;
+ return next;
+}
+
+/**
+ * Teach the baseline from an owner-approved flagged action: fold the action's
+ * destination / size / hour into the config so the same pattern won't re-trip.
+ * Returns the new normalized config.
+ */
+export async function teachFromApproval(agentId, meta, evt) {
+ const taught = applyApproval(getAnomalyConfig(meta), evt);
+ return saveAnomalyConfig(agentId, meta, taught);
+}
diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.js
index 2e1be90ed..5f57ebcf5 100644
--- a/api/_lib/coin/three-holders.js
+++ b/api/_lib/coin/three-holders.js
@@ -35,9 +35,18 @@ function ensureTables() {
create table if not exists three_holder_snapshot (
wallet text primary key,
balance bigint not null,
- updated_at timestamptz not null default now()
+ updated_at timestamptz not null default now(),
+ -- When this wallet's CONTINUOUS hold of $THREE began. Set on first
+ -- insert and preserved across refreshes; a wallet that fully exits is
+ -- hard-deleted, so re-entry honestly restarts the clock. Powers the
+ -- holding-duration component of the agent reputation score.
+ held_since timestamptz not null default now()
)
`;
+ // Existing deployments: add the column and backfill conservatively to "now"
+ // — we never fabricate a holding history we can't prove from real snapshots.
+ await sql`alter table three_holder_snapshot add column if not exists held_since timestamptz`;
+ await sql`update three_holder_snapshot set held_since = coalesce(held_since, updated_at, now()) where held_since is null`;
await sql`
create index if not exists three_holder_snapshot_balance_idx
on three_holder_snapshot (balance desc)
@@ -89,12 +98,16 @@ export async function persistThreeHolderSnapshot(balances) {
const chunk = wallets.slice(i, i + UPSERT_CHUNK);
const balanceStrs = chunk.map((w) => balances.get(w).toString());
await sql`
- insert into three_holder_snapshot (wallet, balance, updated_at)
- select u.wallet, u.balance, ${now}
+ insert into three_holder_snapshot (wallet, balance, updated_at, held_since)
+ select u.wallet, u.balance, ${now}, ${now}
from unnest(${chunk}::text[], ${balanceStrs}::bigint[]) as u(wallet, balance)
on conflict (wallet) do update set
balance = excluded.balance,
updated_at = excluded.updated_at
+ -- held_since is intentionally NOT touched on update: it marks the start
+ -- of the wallet's UNBROKEN hold, so a continuing holder keeps accruing
+ -- duration while a wallet that exited (deleted below) and returned starts
+ -- fresh on its re-insert above.
`;
}
@@ -204,6 +217,35 @@ export async function threeHolderBalances() {
return _inflightColdScan;
}
+/**
+ * $THREE holding for a SINGLE wallet, straight from the cached snapshot — one
+ * indexed primary-key lookup, no Helius walk. Used by the agent reputation engine
+ * to score the $THREE-conviction pillar (balance held + continuous duration)
+ * without adding an RPC read per agent. Returns zero/null for a wallet that holds
+ * no $THREE (absent from the snapshot) so callers degrade honestly.
+ *
+ * @param {string} wallet base58 Solana address
+ * @returns {Promise<{ balance: bigint, heldSince: Date|null }>}
+ */
+export async function threeHoldingFor(wallet) {
+ if (!wallet) return { balance: 0n, heldSince: null };
+ let row;
+ try {
+ [row] = await sql`
+ select balance, held_since from three_holder_snapshot where wallet = ${wallet} limit 1
+ `;
+ } catch {
+ // Snapshot table not migrated yet / DB blip — treat as "unknown, holds none"
+ // rather than erroring the score computation.
+ return { balance: 0n, heldSince: null };
+ }
+ if (!row) return { balance: 0n, heldSince: null };
+ return {
+ balance: BigInt(row.balance),
+ heldSince: row.held_since ? new Date(row.held_since) : null,
+ };
+}
+
async function coldFallbackScan() {
const gotLock = await acquireLock(COLD_SCAN_LOCK_KEY, COLD_SCAN_LOCK_TTL);
if (!gotLock) {
diff --git a/api/_lib/custody-proof.js b/api/_lib/custody-proof.js
new file mode 100644
index 000000000..184f5e94d
--- /dev/null
+++ b/api/_lib/custody-proof.js
@@ -0,0 +1,496 @@
+// @ts-check
+// Verifiable Proof-of-Custody — server prover.
+//
+// Snapshots every custodial agent wallet's PUBLIC facts (address, live on-chain
+// balance, a commitment to its authorized-state head from the custody ledger),
+// builds a Merkle tree over all wallets, persists the epoch + leaves, and anchors
+// the Merkle root on-chain as a signed SPL-Memo. Owners later fetch a per-wallet
+// inclusion proof and verify it themselves in the browser against the on-chain
+// root (src/proof-of-custody/verifier.js) — "don't trust, verify".
+//
+// The leaf encoding + tree construction live in src/proof-of-custody/merkle.js —
+// the SAME module the browser verifier imports — so prover and verifier can never
+// drift. This file must never hash a leaf any other way.
+
+import {
+ PublicKey,
+ Transaction,
+ TransactionInstruction,
+ sendAndConfirmTransaction,
+} from '@solana/web3.js';
+
+import { sql } from './db.js';
+import { solanaConnection } from './solana/connection.js';
+import { RPC } from './solana-attestations.js';
+import { loadAttesterKeypair } from './attest-event.js';
+import { explorerTxUrl } from './avatar-wallet.js';
+import {
+ computeLeafHash,
+ buildMerkleTree,
+ getMerkleProof,
+} from '../../src/proof-of-custody/merkle.js';
+
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+const ANCHOR_KIND = 'threews.custody.v1';
+const TX_TIMEOUT_MS = 20_000;
+
+// The balances are read on the network the custodial wallets actually operate on
+// (mainnet). The root commitment is a hash with no value, so it is anchored on
+// the cheaper devnet by default — still a real, independently-fetchable on-chain
+// artifact. Both are overridable for operators who want mainnet anchoring.
+export const SNAPSHOT_NETWORK = process.env.CUSTODY_SNAPSHOT_NETWORK === 'devnet' ? 'devnet' : 'mainnet';
+export const ANCHOR_NETWORK = process.env.CUSTODY_ANCHOR_NETWORK === 'mainnet' ? 'mainnet' : 'devnet';
+
+// Reconciliation fee tolerance: a withdraw burns ~5k lamports of network fee that
+// the ledger's recorded amount does not include, and a SOL "max" sweep leaves a
+// rent/fee reserve. Allow a small floor plus per-authorized-event headroom so a
+// legitimately-explained drop is never flagged as unexplained.
+const RECON_FEE_FLOOR_LAMPORTS = 1_000_000n; // 0.001 SOL
+const RECON_FEE_PER_EVENT_LAMPORTS = 50_000n; // generous per-tx fee allowance
+
+function isValidSolAddress(addr) {
+ if (typeof addr !== 'string' || addr.length < 32 || addr.length > 44) return false;
+ if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(addr)) return false;
+ try { new PublicKey(addr); return true; } catch { return false; }
+}
+
+/** Enumerate every custodial wallet with a syntactically valid Solana address. */
+export async function listCustodialWallets() {
+ const rows = await sql`
+ SELECT id, user_id, meta->>'solana_address' AS address
+ FROM agent_identities
+ WHERE deleted_at IS NULL
+ AND meta->>'solana_address' IS NOT NULL
+ ORDER BY id ASC
+ `;
+ return rows
+ .filter((r) => isValidSolAddress(r.address))
+ .map((r) => ({ agentId: r.id, userId: r.user_id, address: r.address }));
+}
+
+/**
+ * Commitment to a wallet's authorized-state head: the id (and signature) of the
+ * most recent custody-ledger event for that agent on the snapshot network, or
+ * 'genesis' if the wallet has no recorded custody events yet. Folding the ledger
+ * head into the leaf is what ties verification to the movement ledger — any
+ * authorized change advances the head, so the leaf changes epoch-over-epoch in a
+ * way the owner can map to a logged reason.
+ */
+export async function ledgerHeadFor(agentId, network = SNAPSHOT_NETWORK) {
+ const [row] = await sql`
+ SELECT id, signature
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network}
+ ORDER BY id DESC
+ LIMIT 1
+ `;
+ if (!row) return 'genesis';
+ return `${row.id}:${row.signature || ''}`;
+}
+
+/** Live on-chain lamports for an address; null on RPC failure (caller decides). */
+async function readLamports(conn, address) {
+ try {
+ return await conn.getBalance(new PublicKey(address), 'confirmed');
+ } catch {
+ return null;
+ }
+}
+
+/** Next monotonic epoch number (max + 1, starting at 1). */
+async function nextEpoch() {
+ const [row] = await sql`SELECT COALESCE(MAX(epoch), 0) AS max FROM custody_attestation_epochs`;
+ return BigInt(row?.max ?? 0) + 1n;
+}
+
+/**
+ * Run one attestation round: snapshot → Merkle → persist → anchor on-chain.
+ *
+ * Idempotent-ish by monotonic epoch: each call mints a NEW epoch (epochs are a
+ * monotonic, append-only log so rollback/replay is detectable). Anchoring is
+ * best-effort — if the attester key is unfunded/unset the epoch is still recorded
+ * with anchor_status 'pending' and can be anchored later, exactly like the other
+ * on-chain payout lanes. Returns a summary.
+ *
+ * @param {object} [opts]
+ * @param {boolean} [opts.anchor=true] set false to snapshot without an on-chain write
+ */
+export async function runAttestationEpoch({ anchor = true } = {}) {
+ const startedAt = Date.now();
+ const wallets = await listCustodialWallets();
+ const conn = solanaConnection({ url: RPC[SNAPSHOT_NETWORK] || RPC.mainnet, commitment: 'confirmed' });
+
+ const epoch = await nextEpoch();
+ const epochNum = Number(epoch);
+
+ // Build leaves in a stable order (wallets are already ordered by agent id).
+ const leaves = [];
+ let totalLamports = 0n;
+ let rpcFailures = 0;
+ for (const w of wallets) {
+ const lamports = await readLamports(conn, w.address);
+ // An RPC failure must not silently attest a wrong (zero) balance. Skip the
+ // wallet this epoch rather than committing an unverifiable leaf; it is
+ // included again next epoch once RPC recovers.
+ if (lamports == null) { rpcFailures++; continue; }
+ const balanceLamports = String(lamports);
+ const ledgerHead = await ledgerHeadFor(w.agentId, SNAPSHOT_NETWORK);
+ const leafHash = await computeLeafHash({
+ agentId: w.agentId,
+ address: w.address,
+ balanceLamports,
+ ledgerHead,
+ epoch: epochNum,
+ });
+ leaves.push({
+ agentId: w.agentId,
+ address: w.address,
+ balanceLamports,
+ ledgerHead,
+ leafHash,
+ });
+ totalLamports += BigInt(lamports);
+ }
+
+ const tree = await buildMerkleTree(leaves.map((l) => l.leafHash));
+ const root = tree.root;
+ if (!root) {
+ // No verifiable wallets this round — record an empty epoch so the chain of
+ // epochs stays contiguous and the public page can show "0 wallets".
+ await sql`
+ INSERT INTO custody_attestation_epochs
+ (epoch, network, anchor_network, merkle_root, wallet_count, total_lamports,
+ anchor_status, snapshot_ms)
+ VALUES (${String(epoch)}, ${SNAPSHOT_NETWORK}, ${ANCHOR_NETWORK},
+ ${'0'.repeat(64)}, 0, 0, 'empty', ${Date.now() - startedAt})
+ `;
+ return { epoch: epochNum, wallet_count: 0, root: null, anchor_status: 'empty', rpc_failures: rpcFailures };
+ }
+
+ // Persist the epoch + leaves atomically so a proof read can never see a
+ // half-written tree.
+ await sql.transaction([
+ sql`
+ INSERT INTO custody_attestation_epochs
+ (epoch, network, anchor_network, merkle_root, wallet_count, total_lamports,
+ anchor_status, snapshot_ms)
+ VALUES (${String(epoch)}, ${SNAPSHOT_NETWORK}, ${ANCHOR_NETWORK}, ${root},
+ ${leaves.length}, ${String(totalLamports)}, 'pending', ${Date.now() - startedAt})
+ `,
+ ...leaves.map((l, i) => sql`
+ INSERT INTO custody_attestation_leaves
+ (epoch, leaf_index, agent_id, address, balance_lamports, ledger_head, leaf_hash)
+ VALUES (${String(epoch)}, ${i}, ${l.agentId}, ${l.address},
+ ${l.balanceLamports}, ${l.ledgerHead}, ${l.leafHash})
+ `),
+ ]);
+
+ let anchorResult = { status: 'pending', signature: null };
+ if (anchor) {
+ anchorResult = await anchorRoot({ epoch, root, walletCount: leaves.length });
+ }
+
+ return {
+ epoch: epochNum,
+ wallet_count: leaves.length,
+ root,
+ total_lamports: String(totalLamports),
+ anchor_status: anchorResult.status,
+ anchor_signature: anchorResult.signature,
+ rpc_failures: rpcFailures,
+ snapshot_ms: Date.now() - startedAt,
+ };
+}
+
+/**
+ * Commit a Merkle root on-chain as a signed SPL-Memo and record the signature.
+ * Best-effort: a missing/undecodable/unfunded attester key marks the epoch
+ * 'anchor_failed' with the reason instead of throwing, so the snapshot still
+ * stands and a later run can re-anchor.
+ *
+ * @returns {Promise<{ status: 'anchored'|'anchor_failed', signature: string|null, error?: string }>}
+ */
+export async function anchorRoot({ epoch, root, walletCount }) {
+ let attester;
+ try {
+ attester = loadAttesterKeypair();
+ } catch (e) {
+ await markAnchorFailed(epoch, e.code || 'attester_key_not_configured');
+ return { status: 'anchor_failed', signature: null, error: e.code || e.message };
+ }
+
+ const payload = {
+ v: 1,
+ kind: ANCHOR_KIND,
+ epoch: Number(epoch),
+ root,
+ wallet_count: walletCount,
+ snapshot_network: SNAPSHOT_NETWORK,
+ ts: Math.floor(Date.now() / 1000),
+ };
+ const conn = solanaConnection({ url: RPC[ANCHOR_NETWORK] || RPC.devnet, commitment: 'confirmed' });
+ const ix = new TransactionInstruction({
+ programId: MEMO_PROGRAM_ID,
+ keys: [{ pubkey: attester.publicKey, isSigner: true, isWritable: false }],
+ data: Buffer.from(JSON.stringify(payload), 'utf8'),
+ });
+ const tx = new Transaction().add(ix);
+
+ let signature;
+ try {
+ signature = await withTimeout(
+ sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),
+ TX_TIMEOUT_MS,
+ );
+ } catch (e) {
+ await markAnchorFailed(epoch, (e && e.message) ? String(e.message).slice(0, 300) : 'anchor_send_failed');
+ return { status: 'anchor_failed', signature: null, error: 'anchor_send_failed' };
+ }
+
+ await sql`
+ UPDATE custody_attestation_epochs
+ SET anchor_sig = ${signature}, anchor_status = 'anchored',
+ anchor_error = NULL, anchored_at = now()
+ WHERE epoch = ${String(epoch)}
+ `;
+ return { status: 'anchored', signature };
+}
+
+async function markAnchorFailed(epoch, reason) {
+ await sql`
+ UPDATE custody_attestation_epochs
+ SET anchor_status = 'anchor_failed', anchor_error = ${String(reason).slice(0, 300)}
+ WHERE epoch = ${String(epoch)} AND anchor_status <> 'anchored'
+ `;
+}
+
+function withTimeout(promise, ms) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`anchor rpc timeout after ${ms}ms`)), ms);
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+function epochRowToPublic(row) {
+ if (!row) return null;
+ const anchorNet = row.anchor_network || ANCHOR_NETWORK;
+ const totalLamports = String(row.total_lamports ?? '0');
+ return {
+ epoch: Number(row.epoch),
+ network: row.network,
+ anchor_network: anchorNet,
+ merkle_root: row.merkle_root,
+ wallet_count: row.wallet_count,
+ total_lamports: totalLamports,
+ total_sol: Number(BigInt(totalLamports)) / 1e9,
+ anchor_sig: row.anchor_sig || null,
+ anchor_explorer: row.anchor_sig ? explorerTxUrl(row.anchor_sig, anchorNet) : null,
+ anchor_status: row.anchor_status,
+ created_at: row.created_at,
+ anchored_at: row.anchored_at || null,
+ };
+}
+
+/** Public, no-auth aggregate for the integrity page — never per-wallet data. */
+export async function getPublicIntegrity() {
+ const [latest] = await sql`
+ SELECT * FROM custody_attestation_epochs
+ ORDER BY epoch DESC LIMIT 1
+ `;
+ const [agg] = await sql`
+ SELECT COUNT(*)::int AS epochs, MIN(created_at) AS since,
+ COUNT(*) FILTER (WHERE anchor_status = 'anchored')::int AS anchored
+ FROM custody_attestation_epochs
+ `;
+ const recent = await sql`
+ SELECT epoch, network, anchor_network, merkle_root, wallet_count, total_lamports,
+ anchor_sig, anchor_status, created_at, anchored_at
+ FROM custody_attestation_epochs
+ ORDER BY epoch DESC LIMIT 12
+ `;
+ return {
+ latest: epochRowToPublic(latest),
+ epochs_total: agg?.epochs ?? 0,
+ epochs_anchored: agg?.anchored ?? 0,
+ since: agg?.since ?? null,
+ recent: recent.map(epochRowToPublic),
+ };
+}
+
+/** Public anchor reference for one epoch (lets a verifier cross-check the root). */
+export async function getAnchorRef(epoch) {
+ const [row] = await sql`
+ SELECT * FROM custody_attestation_epochs WHERE epoch = ${String(epoch)}
+ `;
+ return epochRowToPublic(row);
+}
+
+/**
+ * Owner-gated inclusion proof for one agent's wallet at the latest epoch in which
+ * it was attested. Returns the leaf's public fields, the Merkle path to the root,
+ * the on-chain anchor reference, and a movement reconciliation against the custody
+ * ledger. The caller (api/agents/solana-wallet.js) has already verified ownership.
+ *
+ * @returns {Promise<object>} { included, ...proof } — included:false if the wallet
+ * has no leaf yet (e.g. provisioned after the last snapshot).
+ */
+export async function getInclusionProof(agentId) {
+ // Latest epoch that actually contains this wallet's leaf.
+ const [leafRow] = await sql`
+ SELECT epoch, leaf_index, agent_id, address, balance_lamports, ledger_head, leaf_hash
+ FROM custody_attestation_leaves
+ WHERE agent_id = ${agentId}
+ ORDER BY epoch DESC LIMIT 1
+ `;
+ if (!leafRow) {
+ const [anyEpoch] = await sql`SELECT MAX(epoch) AS epoch FROM custody_attestation_epochs`;
+ return {
+ included: false,
+ latest_epoch: anyEpoch?.epoch != null ? Number(anyEpoch.epoch) : null,
+ reason: 'no_leaf_yet',
+ };
+ }
+
+ const epoch = leafRow.epoch;
+ const [epochRow] = await sql`SELECT * FROM custody_attestation_epochs WHERE epoch = ${String(epoch)}`;
+
+ // Rebuild the epoch's tree from its stored leaves to emit a verifiable path.
+ const all = await sql`
+ SELECT leaf_index, leaf_hash FROM custody_attestation_leaves
+ WHERE epoch = ${String(epoch)} ORDER BY leaf_index ASC
+ `;
+ const tree = await buildMerkleTree(all.map((r) => r.leaf_hash));
+ const proof = getMerkleProof(tree.layers, leafRow.leaf_index);
+
+ const reconciliation = await reconcile(agentId, epoch, leafRow);
+
+ const anchorNet = epochRow.anchor_network || ANCHOR_NETWORK;
+ return {
+ included: true,
+ epoch: Number(epoch),
+ network: epochRow.network,
+ anchor: {
+ network: anchorNet,
+ signature: epochRow.anchor_sig || null,
+ explorer: epochRow.anchor_sig ? explorerTxUrl(epochRow.anchor_sig, anchorNet) : null,
+ status: epochRow.anchor_status,
+ kind: ANCHOR_KIND,
+ },
+ // Everything the browser needs to recompute the leaf hash itself.
+ leaf: {
+ agentId,
+ address: leafRow.address,
+ balanceLamports: String(leafRow.balance_lamports),
+ balanceSol: Number(BigInt(String(leafRow.balance_lamports))) / 1e9,
+ ledgerHead: leafRow.ledger_head,
+ epoch: Number(epoch),
+ index: leafRow.leaf_index,
+ leafHash: leafRow.leaf_hash,
+ },
+ proof,
+ // The server's claimed root. The verifier recomputes from leaf+proof and
+ // then confirms THAT against the on-chain anchor — it never trusts this.
+ merkle_root: epochRow.merkle_root,
+ wallet_count: epochRow.wallet_count,
+ snapshot_at: epochRow.created_at,
+ reconciliation,
+ };
+}
+
+/**
+ * Movement reconciliation: does the balance change since the previous epoch map
+ * to authorized, logged custody events? Surfaces "no unexplained movements" as a
+ * verifiable claim and loudly flags an outflow the ledger can't account for.
+ */
+export async function reconcile(agentId, epoch, currentLeaf) {
+ const [prev] = await sql`
+ SELECT epoch, balance_lamports FROM custody_attestation_leaves
+ WHERE agent_id = ${agentId} AND epoch < ${String(epoch)}
+ ORDER BY epoch DESC LIMIT 1
+ `;
+ const currentBalance = BigInt(String(currentLeaf.balance_lamports));
+
+ if (!prev) {
+ return {
+ status: 'baseline',
+ human: 'First attested epoch for this wallet — nothing to reconcile against yet. Future epochs will check every balance change against your authorized custody events.',
+ current_balance_lamports: String(currentBalance),
+ };
+ }
+
+ const prevBalance = BigInt(String(prev.balance_lamports));
+ const delta = currentBalance - prevBalance;
+
+ // Window between the two epochs' snapshots.
+ const [bounds] = await sql`
+ SELECT
+ (SELECT created_at FROM custody_attestation_epochs WHERE epoch = ${String(prev.epoch)}) AS prev_at,
+ (SELECT created_at FROM custody_attestation_epochs WHERE epoch = ${String(epoch)}) AS cur_at
+ `;
+ const events = await sql`
+ SELECT id, event_type, category, amount_lamports, usd, signature, reason, created_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${SNAPSHOT_NETWORK}
+ AND event_type IN ('withdraw', 'spend')
+ AND asset = 'SOL'
+ AND amount_lamports IS NOT NULL
+ AND created_at > ${bounds.prev_at}
+ AND created_at <= ${bounds.cur_at}
+ ORDER BY id ASC
+ `;
+ let authorizedOutflow = 0n;
+ for (const e of events) authorizedOutflow += BigInt(String(e.amount_lamports));
+ const tolerance = RECON_FEE_FLOOR_LAMPORTS + BigInt(events.length) * RECON_FEE_PER_EVENT_LAMPORTS;
+
+ const summarized = events.map((e) => ({
+ id: String(e.id),
+ event_type: e.event_type,
+ category: e.category,
+ amount_lamports: String(e.amount_lamports),
+ amount_sol: Number(BigInt(String(e.amount_lamports))) / 1e9,
+ reason: e.reason,
+ signature: e.signature,
+ explorer: e.signature ? explorerTxUrl(e.signature, SNAPSHOT_NETWORK) : null,
+ created_at: e.created_at,
+ }));
+
+ if (delta >= 0n) {
+ // Balance flat or up. Incoming deposits are external (not in the custody
+ // ledger), so an increase is expected and benign; there is no unexplained
+ // OUTFLOW, which is the property we attest.
+ return {
+ status: 'reconciled',
+ prev_epoch: Number(prev.epoch),
+ prev_balance_lamports: String(prevBalance),
+ current_balance_lamports: String(currentBalance),
+ delta_lamports: String(delta),
+ delta_sol: Number(delta) / 1e9,
+ authorized_outflow_lamports: String(authorizedOutflow),
+ authorized_events: summarized,
+ unexplained_lamports: '0',
+ human: delta === 0n
+ ? 'Balance unchanged since the previous epoch. No movement, nothing unexplained.'
+ : `Balance increased by ${(Number(delta) / 1e9).toFixed(6)} SOL — an incoming deposit. Deposits are external to custody and never move funds out, so there is nothing to authorize.`,
+ };
+ }
+
+ const outflow = -delta;
+ const unexplained = outflow > authorizedOutflow + tolerance ? outflow - authorizedOutflow : 0n;
+ const reconciled = unexplained === 0n;
+ return {
+ status: reconciled ? 'reconciled' : 'unexplained',
+ prev_epoch: Number(prev.epoch),
+ prev_balance_lamports: String(prevBalance),
+ current_balance_lamports: String(currentBalance),
+ delta_lamports: String(delta),
+ delta_sol: Number(delta) / 1e9,
+ authorized_outflow_lamports: String(authorizedOutflow),
+ authorized_events: summarized,
+ unexplained_lamports: String(unexplained),
+ human: reconciled
+ ? `Balance fell by ${(Number(outflow) / 1e9).toFixed(6)} SOL, fully explained by ${summarized.length} authorized custody event${summarized.length === 1 ? '' : 's'} (withdraw/spend) plus network fees. No unexplained movement.`
+ : `⚠ Balance fell by ${(Number(outflow) / 1e9).toFixed(6)} SOL but only ${(Number(authorizedOutflow) / 1e9).toFixed(6)} SOL is accounted for by authorized custody events. ${(Number(unexplained) / 1e9).toFixed(6)} SOL of outflow is UNEXPLAINED — this should never happen and warrants investigation.`,
+ };
+}
diff --git a/api/_lib/migrations/20260623120000_custody_attestation.sql b/api/_lib/migrations/20260623120000_custody_attestation.sql
new file mode 100644
index 000000000..583818bee
--- /dev/null
+++ b/api/_lib/migrations/20260623120000_custody_attestation.sql
@@ -0,0 +1,75 @@
+begin;
+
+-- Verifiable Proof-of-Custody — on-chain-anchored attestation of every custodial
+-- agent wallet's state.
+--
+-- On a schedule (api/cron/custody-attest.js) the platform snapshots each
+-- custodial Solana wallet's *public* facts — address, live on-chain balance, and
+-- a commitment to its authorized-state head from agent_custody_events — builds a
+-- Merkle tree over all wallets, and commits the root on-chain (SPL Memo). Owners
+-- get a per-wallet inclusion proof they verify themselves in the browser against
+-- the on-chain root. No secrets, no cross-tenant data: every column here is
+-- public or owner-authorized.
+--
+-- Leaf encoding + tree construction are pinned by src/proof-of-custody/merkle.js
+-- (the one module both the server prover and the browser verifier import) and by
+-- tests/custody-merkle.test.js. Do not recompute hashes anywhere else.
+
+-- One row per attestation round. `epoch` is strictly monotonic (rollback/replay
+-- is therefore obvious — an owner verifies the latest and can walk back). The
+-- Merkle root and the on-chain anchor tx are public.
+create table if not exists custody_attestation_epochs (
+ epoch bigint primary key, -- monotonic round number, starts at 1
+ network text not null, -- network the balances were read from
+ anchor_network text, -- network the root memo was committed on
+ merkle_root text not null, -- 64-char hex sha256 Merkle root
+ wallet_count integer not null default 0, -- leaves in the tree
+ total_lamports numeric not null default 0, -- aggregate SOL across wallets (public)
+ anchor_sig text, -- on-chain memo tx signature (null until anchored)
+ anchor_status text not null default 'pending', -- pending | anchored | anchor_failed
+ anchor_error text, -- last anchor failure reason (operator-facing)
+ snapshot_ms integer, -- how long the snapshot took (telemetry)
+ created_at timestamptz not null default now(),
+ anchored_at timestamptz -- when the root landed on-chain
+);
+
+create index if not exists custody_attestation_epochs_created
+ on custody_attestation_epochs (created_at desc);
+
+create index if not exists custody_attestation_epochs_anchored
+ on custody_attestation_epochs (anchor_status, epoch desc);
+
+-- One row per wallet per epoch — the leaves of that epoch's Merkle tree, in
+-- tree order (`leaf_index`). Stores ONLY the public/owner-authorized facts that
+-- go into the leaf hash, so a per-owner inclusion proof can be rebuilt on demand
+-- (load the epoch's leaves → reconstruct tree → emit path) without ever exposing
+-- another owner's leaf: the inclusion-proof endpoint is ownership-gated and the
+-- public integrity page reads only the epochs table aggregates.
+create table if not exists custody_attestation_leaves (
+ epoch bigint not null references custody_attestation_epochs(epoch) on delete cascade,
+ leaf_index integer not null, -- position in the ordered tree
+ agent_id uuid not null,
+ address text not null, -- custodial Solana address (base58, public)
+ balance_lamports numeric not null, -- on-chain balance at snapshot (lamports)
+ ledger_head text not null, -- authorized-state commitment ("<id>:<sig>" | "genesis")
+ leaf_hash text not null, -- 64-char hex sha256 leaf hash
+ created_at timestamptz not null default now(),
+ primary key (epoch, leaf_index)
+);
+
+-- The inclusion-proof endpoint looks a wallet up by (epoch, agent_id).
+create index if not exists custody_attestation_leaves_agent
+ on custody_attestation_leaves (agent_id, epoch desc);
+
+create index if not exists custody_attestation_leaves_epoch
+ on custody_attestation_leaves (epoch, leaf_index);
+
+comment on table custody_attestation_epochs is
+ 'Proof-of-Custody attestation rounds: monotonic epoch, Merkle root over all '
+ 'custodial wallets, and the on-chain anchor tx. Public face at /integrity.';
+comment on table custody_attestation_leaves is
+ 'Per-wallet leaves of each epoch''s Merkle tree (public facts only). Backs the '
+ 'owner-gated inclusion proof at GET /api/agents/:id/solana/proof. Rebuild the '
+ 'tree from these to emit a path; never expose another owner''s leaf.';
+
+commit;
diff --git a/api/_lib/migrations/20260629010000_agent_mood.sql b/api/_lib/migrations/20260629010000_agent_mood.sql
new file mode 100644
index 000000000..d8784eb0f
--- /dev/null
+++ b/api/_lib/migrations/20260629010000_agent_mood.sql
@@ -0,0 +1,44 @@
+-- Emotion & Embodiment — persistent agent mood (Living Agents · Task 07).
+--
+-- An agent carries a real emotional state derived from its mind and the user's
+-- world: a point in the valence × arousal circumplex that moves only on real
+-- signals (chat sentiment, memory, dreams, actions, market/alert events) and
+-- decays toward a baseline. The *live snapshot* lives on agent_identities.meta
+-- (meta.mood) so it restores instantly with the agent record; this table is the
+-- append-only HISTORY that powers the "mood over time" sparkline and the
+-- inspector's "what real signal moved it" feed.
+--
+-- Every row cites the signal that produced it — no mood change without a real
+-- triggering signal is the product invariant, and the source column enforces it
+-- as a data invariant too.
+
+create table if not exists agent_mood_history (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ -- The mood point AFTER this signal was applied + decayed.
+ valence real not null check (valence >= -1.0 and valence <= 1.0),
+ arousal real not null check (arousal >= 0.0 and arousal <= 1.0),
+ -- Projected discrete mood (calm | alert | elated | content | agitated | subdued).
+ label text not null,
+ -- The real signal that moved the mood here (e.g. 'chat:positive',
+ -- 'action:failure', 'dream:insight'). Mandatory — provenance, not decoration.
+ source text not null,
+ -- Human-readable summary of the signal for the inspector feed.
+ source_label text,
+ -- Optional provenance link to the memory that triggered this, when relevant.
+ source_memory_id uuid references agent_memories(id) on delete set null,
+ metadata jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists agent_mood_history_agent_time
+ on agent_mood_history(agent_id, created_at desc);
+
+-- Live snapshot contract (written to agent_identities.meta.mood by the mood API):
+-- meta.mood = {
+-- valence: number (-1..1),
+-- arousal: number (0..1),
+-- label: string,
+-- sensitivity: number (0..1) -- the owner's "emotional sensitivity" setting
+-- updated_at: ISO8601 string
+-- }
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.js
index ff901e0e0..52c991fe2 100644
--- a/api/_lib/notify-prefs.js
+++ b/api/_lib/notify-prefs.js
@@ -87,6 +87,7 @@ const TYPE_CATEGORY = {
asset_payment_mismatch: 'account',
skill_payment_mismatch: 'account',
security_alert: 'account',
+ wallet_anomaly_frozen: 'account',
};
export function categoryForType(type) {
diff --git a/api/_lib/spend-policy-compiler.js b/api/_lib/spend-policy-compiler.js
new file mode 100644
index 000000000..e2e97ff2b
--- /dev/null
+++ b/api/_lib/spend-policy-compiler.js
@@ -0,0 +1,240 @@
+// Natural-language → validated spend-policy compiler.
+//
+// The owner writes how their agent wallet may spend in plain English ("let it trade
+// up to $50/day on tokens at least a day old, never spend my last 1 SOL, stop
+// everything if a single trade drops more than 30%, and only ever pay services I've
+// used before"). We compile that to the structured rule DSL in
+// spend-policy-rules.js, HARD-validate it (normalizePolicyRules drops anything that
+// wouldn't enforce), and hand back a numbered plain-English readback so the owner
+// confirms intent before saving.
+//
+// The model AUTHORS; it never enforces. Its JSON is parsed, normalized, and only
+// the normalized result is ever stored or run — anything it emits that doesn't
+// validate is discarded, never enforced. Prefers the platform free-first LLM chain
+// (llm.js); falls back to a real deterministic intent parser so the feature always
+// compiles, model or not.
+
+import { llmComplete, llmConfigured } from './llm.js';
+import { normalizePolicyRules, describePolicyRules } from './spend-policy-rules.js';
+
+const COMPILE_SYSTEM = `You convert an agent-wallet owner's plain-English spending rules into ONE JSON object describing a deterministic policy. Output ONLY the JSON — no prose, no markdown fence.
+
+The wallet belongs to an autonomous AI agent that spends on its own (trades tokens, snipes launches, pays other services via x402, and the owner can withdraw). The owner is setting safety rules. Your job is ONLY to translate intent into structured rules — you never make spending decisions.
+
+Output shape:
+{
+ "rules": [
+ { "action": "block" | "allow" | "require_step_up" | "freeze",
+ "when": [ { "field": "...", "op": "...", "value": ... }, ... ] } // ALL clauses must be true (AND) for the rule to fire
+ ],
+ "refusal": string|null, // set ONLY if the request is too ambiguous or unsafe to compile; explain what you need
+ "assumptions": [string] // anything you defaulted, inferred, or could not capture
+}
+
+Rules are evaluated top-to-bottom, first match wins (like a firewall). Put "allow" carve-outs BEFORE the "block" they should override.
+
+Fields (use the exact name; pick the operator that fits):
+- amount_usd number USD value of a single spend ops: gt,gte,lt,lte,eq,neq
+- daily_total_usd number today's running total INCLUDING this spend (use for "up to $X per day")
+- daily_spent_usd number today's total BEFORE this spend
+- token_age_hours number age of the token being bought (trade/snipe). "at least a day old" => gte 24
+- sol_reserve_after number SOL left in the wallet AFTER the spend. "never spend my last 1 SOL" => lt 1
+- trade_pnl_pct number a trade's profit/loss %. A 30% drop => lt -30 (loss is negative)
+- time_of_day_utc number hour 0-23 UTC
+- asset string "SOL" | "USDC" | a mint ops: eq,neq,in,not_in
+- category string "trade" | "snipe" | "x402" | "withdraw" ops: eq,neq,in,not_in
+- counterparty string a destination address ops: eq,neq,in,not_in
+- destination_allowlisted boolean on the withdraw allowlist op: is
+- counterparty_seen_before boolean the wallet has paid this recipient before op: is
+
+Encoding intents (think in terms of what to BLOCK):
+- "up to $50/day" => block when daily_total_usd gt 50.
+- "no payment over $X" => block when amount_usd gt X.
+- "only trade tokens at least a day old" => block trades on young tokens: action block, when [{category eq trade},{token_age_hours lt 24}]. (Also covers "snipe" with category in ["trade","snipe"].)
+- "never spend my last 1 SOL" => block when sol_reserve_after lt 1.
+- "stop everything if a trade drops more than 30%" => action freeze, when [{trade_pnl_pct lt -30}].
+- "only ever pay services I've used before" => block when [{category eq x402},{counterparty_seen_before is false}].
+- "pause all payments at night" / time windows => block with time_of_day_utc.
+- "always allow withdrawals to my own wallet ADDRESS" => action allow, when [{category eq withdraw},{counterparty eq "ADDRESS"}].
+
+Rules:
+- Prefer the smallest set of rules that captures the intent. Never invent limits the owner didn't ask for.
+- A rule MUST have at least one clause. Never emit an empty "when".
+- If you genuinely cannot map the request to these fields, set "refusal" and leave "rules" empty.
+- Never reference any coin or token other than $THREE.`;
+
+function str(v, max = 300) {
+ if (typeof v !== 'string') return '';
+ return v.trim().slice(0, max);
+}
+
+function safeJsonExtract(text) {
+ if (typeof text !== 'string') return null;
+ const t = text.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
+ const start = t.indexOf('{');
+ const end = t.lastIndexOf('}');
+ if (start < 0 || end < start) return null;
+ try {
+ return JSON.parse(t.slice(start, end + 1));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Compile NL → validated policy document.
+ * @param {string} text the owner's plain-English description
+ * @param {object} [opts]
+ * @param {string[]} [opts.allowlist] known destinations (lets "addresses I've used" map to a counterparty allowlist)
+ * @param {object} [opts.track] llm spend attribution
+ * @returns {Promise<{ ok: boolean, error?: string, message?: string, refusal?: string|null,
+ * via?: string, source_text?: string, policy?: object, readback?: object[],
+ * assumptions?: string[] }>}
+ */
+export async function compilePolicyFromText(text, { allowlist = [], track = null } = {}) {
+ const source = typeof text === 'string' ? text.trim().slice(0, 4000) : '';
+ if (source.length < 3) {
+ return { ok: false, error: 'empty', message: 'Describe how your agent should spend, in a sentence or two.' };
+ }
+
+ let parsed = null;
+ let via = 'heuristic';
+ let refusal = null;
+ if (llmConfigured()) {
+ try {
+ const out = await llmComplete({
+ system: COMPILE_SYSTEM,
+ user: source,
+ maxTokens: 900,
+ timeoutMs: 25_000,
+ track: track ? { ...track, tool: 'spend-policy-compile' } : { tool: 'spend-policy-compile' },
+ });
+ parsed = safeJsonExtract(out.text);
+ if (parsed) {
+ via = 'model';
+ if (typeof parsed.refusal === 'string' && parsed.refusal.trim()) refusal = str(parsed.refusal, 400);
+ }
+ } catch (e) {
+ console.warn('[spend-policy-compiler] LLM compile failed, using heuristic:', e?.message);
+ }
+ }
+ if (!parsed) parsed = heuristicCompile(source, allowlist);
+
+ const assumptions = Array.isArray(parsed.assumptions) ? parsed.assumptions.map((w) => str(w)).filter(Boolean) : [];
+
+ // HARD validation: only the normalized document is ever returned/stored/run.
+ const policy = normalizePolicyRules({ rules: parsed.rules, source_text: source });
+
+ // Nothing enforceable came out. Honour an explicit model refusal, else explain.
+ if (!policy.rules.length) {
+ const heur = via === 'model' ? heuristicCompile(source, allowlist) : null;
+ const fallback = heur ? normalizePolicyRules({ rules: heur.rules, source_text: source }) : null;
+ if (fallback && fallback.rules.length) {
+ return finalize(fallback, 'heuristic', source, Array.isArray(heur.assumptions) ? heur.assumptions.map((w) => str(w)).filter(Boolean) : [], null);
+ }
+ return {
+ ok: false,
+ error: 'unparseable',
+ via,
+ source_text: source,
+ refusal: refusal || null,
+ message:
+ refusal ||
+ 'I couldn’t turn that into a concrete spending rule. Try something like “block any payment over $50”, “only trade tokens at least a day old”, or “never let SOL drop below 1”.',
+ };
+ }
+
+ return finalize(policy, via, source, assumptions, refusal);
+}
+
+function finalize(policy, via, source, assumptions, refusal) {
+ return {
+ ok: true,
+ via,
+ source_text: source,
+ policy,
+ readback: describePolicyRules(policy),
+ assumptions: [...new Set(assumptions)],
+ refusal: refusal || null,
+ };
+}
+
+// ── deterministic intent parser — real implementation, not a mock ──────────────────
+// Covers the phrasings the README's worked example uses plus the common variants, so
+// the feature compiles even with no model configured. Each matched intent becomes a
+// real rule; the same normalizer validates the output.
+function heuristicCompile(text, allowlist = []) {
+ const WORDS = { a: '1', one: '1', two: '2', three: '3', four: '4', five: '5', ten: '10' };
+ let lowered = text.toLowerCase();
+ const t = ` ${lowered} `;
+ const rules = [];
+ const assumptions = [];
+
+ const money = (m) => {
+ if (!m) return null;
+ let v = parseFloat(String(m).replace(/[$,\s]/g, ''));
+ if (/k\b/i.test(m)) v *= 1_000;
+ if (/m(?:m|illion)?\b/i.test(m)) v *= 1_000_000;
+ return Number.isFinite(v) ? v : null;
+ };
+ const numWord = (w) => (WORDS[w] != null ? Number(WORDS[w]) : Number(w));
+
+ // "up to $50/day", "$50 per day", "max $50 a day"
+ const daily = t.match(/(?:up to|max(?:imum)?|under|below|no more than)\s*\$?\s*([\d.,]+\s*[km]?)\s*(?:\/|per|a)\s*day/) ||
+ t.match(/\$?\s*([\d.,]+\s*[km]?)\s*(?:\/|per|a)\s*day/);
+ if (daily) {
+ const v = money(daily[1]);
+ if (v != null) rules.push({ action: 'block', when: [{ field: 'daily_total_usd', op: 'gt', value: v }] });
+ }
+
+ // "never spend over $X", "no payment over $X", "block payments above $X" (single tx)
+ const perTx = t.match(/(?:over|above|more than|exceed(?:ing|s)?|bigger than)\s*\$?\s*([\d.,]+\s*[km]?)/);
+ if (perTx && !/\bday\b/.test(perTx[0])) {
+ const v = money(perTx[1]);
+ if (v != null) rules.push({ action: 'block', when: [{ field: 'amount_usd', op: 'gt', value: v }] });
+ }
+
+ // "tokens at least a day old" / "older than N hours/days"
+ const ageDay = t.match(/(?:at least|older than|more than)\s*(a|one|two|three|\d+)\s*day/);
+ const ageHr = t.match(/(?:at least|older than|more than)\s*(\d+)\s*hour/);
+ if (ageDay || ageHr) {
+ const hours = ageHr ? Number(ageHr[1]) : numWord(ageDay[1]) * 24;
+ if (Number.isFinite(hours) && hours > 0) {
+ const cat = /snipe/.test(t) ? { field: 'category', op: 'in', value: ['trade', 'snipe'] } : { field: 'category', op: 'eq', value: 'trade' };
+ rules.push({ action: 'block', when: [cat, { field: 'token_age_hours', op: 'lt', value: hours }] });
+ }
+ }
+
+ // "never spend my last 1 SOL" / "keep at least 1 SOL" / "don't let SOL drop below 1"
+ const reserve = t.match(/(?:last|keep|reserve|leave|below|under|drop below)\s*(?:at least\s*)?(\d+(?:\.\d+)?)\s*sol/) ||
+ t.match(/(\d+(?:\.\d+)?)\s*sol\s*(?:reserve|floor|minimum|min)/);
+ if (reserve) {
+ const v = parseFloat(reserve[1]);
+ if (Number.isFinite(v) && v > 0) rules.push({ action: 'block', when: [{ field: 'sol_reserve_after', op: 'lt', value: v }] });
+ }
+
+ // "stop everything if a trade drops more than 30%" => freeze
+ const drop = t.match(/(?:drops?|down|loses?|lose|loss|falls?)\D{0,18}?(\d+(?:\.\d+)?)\s*%/);
+ if (drop && /(stop everything|freeze|halt|kill|stop trading|shut)/.test(t)) {
+ const v = parseFloat(drop[1]);
+ if (Number.isFinite(v) && v > 0) rules.push({ action: 'freeze', when: [{ field: 'trade_pnl_pct', op: 'lt', value: -Math.abs(v) }] });
+ } else if (drop && /(stop loss|stop-loss|sell if|exit if)/.test(t)) {
+ const v = parseFloat(drop[1]);
+ if (Number.isFinite(v) && v > 0) rules.push({ action: 'freeze', when: [{ field: 'trade_pnl_pct', op: 'lt', value: -Math.abs(v) }] });
+ }
+
+ // "only ever pay services I've used before" / "only pay known services"
+ if (/(only|just).{0,30}(pay|services?).{0,30}(used before|i'?ve used|known|familiar|trusted)/.test(t) ||
+ /(services?|people|addresses?).{0,20}(i'?ve|i have)\s*(used|paid)\s*before/.test(t) ||
+ /no new (services?|payees?|recipients?)/.test(t)) {
+ rules.push({ action: 'block', when: [{ field: 'category', op: 'eq', value: 'x402' }, { field: 'counterparty_seen_before', op: 'is', value: false }] });
+ assumptions.push('Read "only pay services you’ve used before" as: block first-time x402 payees. The agent can still pay any recipient it has paid before.');
+ }
+
+ // "only withdraw to my allowlist" — leans on the existing withdraw allowlist signal.
+ if (/(only|just).{0,30}withdraw.{0,30}(allowlist|approved|my own|trusted)/.test(t) || /withdraw.{0,20}only.{0,20}(allowlist|approved)/.test(t)) {
+ rules.push({ action: 'block', when: [{ field: 'category', op: 'eq', value: 'withdraw' }, { field: 'destination_allowlisted', op: 'is', value: false }] });
+ }
+
+ return { rules, assumptions };
+}
diff --git a/api/_lib/spend-policy-rules.js b/api/_lib/spend-policy-rules.js
new file mode 100644
index 000000000..ab7f1740b
--- /dev/null
+++ b/api/_lib/spend-policy-rules.js
@@ -0,0 +1,596 @@
+// Natural-language spend policies — the deterministic, code-enforced core.
+//
+// Owners describe how their agent's custodial wallet may spend in plain English.
+// A Claude call (api/_lib/spend-policy-compiler.js) COMPILES that English into the
+// structured, versioned rule document defined here. From that point on the LLM is
+// out of the loop entirely: every runtime decision is made by `evaluatePolicy()`
+// below — a pure, total function with no network, no clock dependence beyond an
+// injected context, and no throw path. The model authors and explains; this file
+// enforces. That separation is the whole trust model.
+//
+// The document lives at agent_identities.meta.policy_rules (jsonb, versioned). It
+// is ADDITIVE to the numeric caps in agent-trade-guards.js (per_tx_usd, daily_usd,
+// withdraw_allowlist, frozen) — those hard floors always apply; policy rules layer
+// richer, conditional intent on top. A policy rule can tighten ("block payments to
+// services you haven't used before") but the numeric caps and the freeze switch are
+// never weakened by it.
+//
+// Evaluation is an ordered, first-match firewall — the same mental model the owner
+// sees in the numbered readback. The first rule whose conditions all match decides;
+// if none match, the spend is allowed (and still subject to the numeric caps). This
+// is auditable by construction: "rule N caught it" is always answerable.
+//
+// Everything here is pure + synchronous + total. Malformed input never throws — it
+// normalizes away or fails safe. Unit-tested in tests/spend-policy-rules.test.js.
+
+// ── shape + bounds ──────────────────────────────────────────────────────────────
+// Small, total, auditable: a policy can't grow into an unbounded eval or a DoS.
+export const POLICY_VERSION = 1;
+export const MAX_RULES = 40;
+export const MAX_CLAUSES_PER_RULE = 8;
+const MAX_LABEL = 220;
+const MAX_STR_VALUE = 80;
+const MAX_IN_LIST = 60;
+
+// The actions a rule can take. `allow` is an explicit carve-out that short-circuits
+// later policy rules (a whitelist); `block` denies; `require_step_up` denies an
+// autonomous spend that would need a human present (treated as a block on the
+// autonomous paths, with an honest "needs your approval" message); `freeze` denies
+// AND trips the wallet kill-switch so everything else stops too.
+export const ACTIONS = Object.freeze(['allow', 'block', 'require_step_up', 'freeze']);
+
+// Every field the evaluator understands, with its value type. A clause may only
+// reference a field listed here; anything else is dropped at normalization. The
+// type drives which operators are legal and how the value is coerced.
+//
+// amount_usd USD-equivalent of THIS spend
+// daily_spent_usd rolling-24h USD already spent BEFORE this one
+// daily_total_usd daily_spent_usd + amount_usd (for "up to $X/day")
+// token_age_hours age of the token being bought (trade/snipe only)
+// sol_reserve_after SOL the wallet would hold AFTER this spend
+// trade_pnl_pct realized P&L % of the trade (sells; negative = loss)
+// time_of_day_utc hour 0–23 (UTC) the spend is happening
+// asset 'SOL' | 'USDC' | mint base58
+// counterparty destination / payTo address (base58)
+// category 'trade' | 'snipe' | 'x402' | 'withdraw' | …
+// destination_allowlisted is the destination on the withdraw allowlist
+// counterparty_seen_before has this wallet ever paid this counterparty before
+export const FIELD_TYPES = Object.freeze({
+ amount_usd: 'number',
+ daily_spent_usd: 'number',
+ daily_total_usd: 'number',
+ token_age_hours: 'number',
+ sol_reserve_after: 'number',
+ trade_pnl_pct: 'number',
+ time_of_day_utc: 'number',
+ asset: 'string',
+ counterparty: 'string',
+ category: 'string',
+ destination_allowlisted: 'boolean',
+ counterparty_seen_before: 'boolean',
+});
+
+const NUMERIC_OPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'neq']);
+const STRING_OPS = Object.freeze(['eq', 'neq', 'in', 'not_in']);
+const BOOLEAN_OPS = Object.freeze(['is']);
+
+function opsForType(type) {
+ if (type === 'number') return NUMERIC_OPS;
+ if (type === 'string') return STRING_OPS;
+ if (type === 'boolean') return BOOLEAN_OPS;
+ return [];
+}
+
+// Fields that need an async lookup before the evaluator can see them — the enforce
+// layer only does the lookup when a live policy actually references the field.
+export const ASYNC_CONTEXT_FIELDS = Object.freeze([
+ 'daily_spent_usd',
+ 'daily_total_usd',
+ 'counterparty_seen_before',
+]);
+
+// ── normalization (total) ───────────────────────────────────────────────────────
+
+function isFiniteNum(n) {
+ return typeof n === 'number' && Number.isFinite(n);
+}
+
+function slug(s, fallback) {
+ const out = String(s == null ? '' : s)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40);
+ return out || fallback;
+}
+
+function clampStr(v, max = MAX_STR_VALUE) {
+ return String(v).trim().slice(0, max);
+}
+
+// Coerce one raw clause into a clean clause, or null if it can't be made valid.
+function normalizeClause(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const field = typeof raw.field === 'string' ? raw.field.trim() : '';
+ const type = FIELD_TYPES[field];
+ if (!type) return null;
+ const op = typeof raw.op === 'string' ? raw.op.trim() : '';
+ if (!opsForType(type).includes(op)) return null;
+
+ if (type === 'number') {
+ const value = Number(raw.value);
+ if (!Number.isFinite(value)) return null;
+ return { field, op, value };
+ }
+ if (type === 'boolean') {
+ // Only 'is' — value is the boolean to test against.
+ const value = raw.value === true || raw.value === 'true' ? true : raw.value === false || raw.value === 'false' ? false : null;
+ if (value === null) return null;
+ return { field, op, value };
+ }
+ // string
+ if (op === 'in' || op === 'not_in') {
+ const list = Array.isArray(raw.value) ? raw.value : [raw.value];
+ const vals = [...new Set(list.map((x) => clampStr(x)).filter(Boolean))].slice(0, MAX_IN_LIST);
+ if (!vals.length) return null;
+ return { field, op, value: vals };
+ }
+ const value = clampStr(raw.value);
+ if (!value) return null;
+ return { field, op, value };
+}
+
+// Coerce one raw rule into a clean rule, or null if it can't be enforced.
+function normalizeRule(raw, index) {
+ if (!raw || typeof raw !== 'object') return null;
+ const action = ACTIONS.includes(raw.action) ? raw.action : null;
+ if (!action) return null;
+ const rawWhen = Array.isArray(raw.when) ? raw.when : [];
+ const when = [];
+ for (const c of rawWhen) {
+ const nc = normalizeClause(c);
+ if (nc) when.push(nc);
+ if (when.length >= MAX_CLAUSES_PER_RULE) break;
+ }
+ // A rule with no surviving conditions would match every spend — a catch-all
+ // "block everything" that belongs to the freeze switch, not a typo'd rule. Drop
+ // it so a malformed/over-broad clause can never silently brick all spending.
+ if (!when.length) return null;
+ const id = slug(raw.id, `r${index + 1}`);
+ const label = typeof raw.label === 'string' && raw.label.trim() ? clampStr(raw.label, MAX_LABEL) : describeRule({ action, when });
+ return { id, action, when, label };
+}
+
+/**
+ * Coerce arbitrary input (the LLM's output, a stored blob, a hand-crafted PUT body)
+ * into a clean, bounded policy document. Never throws. Invalid clauses and rules are
+ * dropped; the result is always enforceable as-is.
+ * @returns {{ version: number, rules: object[], updated_at: string|null, source_text: string|null }}
+ */
+export function normalizePolicyRules(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const rawRules = Array.isArray(r.rules) ? r.rules : Array.isArray(r) ? r : [];
+ const rules = [];
+ const seenIds = new Set();
+ for (let i = 0; i < rawRules.length; i++) {
+ if (rules.length >= MAX_RULES) break;
+ const nr = normalizeRule(rawRules[i], rules.length);
+ if (!nr) continue;
+ // Guarantee unique ids so a block can be attributed unambiguously.
+ let id = nr.id;
+ let n = 2;
+ while (seenIds.has(id)) id = `${nr.id}-${n++}`;
+ seenIds.add(id);
+ nr.id = id;
+ rules.push(nr);
+ }
+ return {
+ version: POLICY_VERSION,
+ rules,
+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
+ source_text: typeof r.source_text === 'string' ? r.source_text.slice(0, 4000) : null,
+ };
+}
+
+/** Read the effective policy document off an agent's meta blob. Always normalized. */
+export function getPolicyRules(meta) {
+ return normalizePolicyRules(meta?.policy_rules);
+}
+
+/** True when the policy actually has at least one enforceable rule. */
+export function hasPolicyRules(doc) {
+ return !!(doc && Array.isArray(doc.rules) && doc.rules.length);
+}
+
+/** The set of context fields any rule in the document references. */
+export function referencedFields(doc) {
+ const out = new Set();
+ for (const rule of doc?.rules || []) {
+ for (const c of rule.when || []) out.add(c.field);
+ }
+ return out;
+}
+
+// ── evaluation (pure + total) ────────────────────────────────────────────────────
+
+function clauseMatches(clause, ctx) {
+ try {
+ const raw = ctx ? ctx[clause.field] : undefined;
+ // An unobservable signal (not supplied for this spend) can never match — so a
+ // token-age rule is simply inert on an x402 payment, never a false block.
+ if (raw === undefined || raw === null) return false;
+ const type = FIELD_TYPES[clause.field];
+
+ if (type === 'number') {
+ const v = Number(raw);
+ const t = Number(clause.value);
+ if (!Number.isFinite(v) || !Number.isFinite(t)) return false;
+ switch (clause.op) {
+ case 'gt': return v > t;
+ case 'gte': return v >= t;
+ case 'lt': return v < t;
+ case 'lte': return v <= t;
+ case 'eq': return v === t;
+ case 'neq': return v !== t;
+ default: return false;
+ }
+ }
+ if (type === 'boolean') {
+ const v = raw === true || raw === 'true';
+ return clause.op === 'is' ? v === (clause.value === true) : false;
+ }
+ // string
+ const v = String(raw);
+ switch (clause.op) {
+ case 'eq': return v === clause.value;
+ case 'neq': return v !== clause.value;
+ case 'in': return Array.isArray(clause.value) && clause.value.includes(v);
+ case 'not_in': return Array.isArray(clause.value) && !clause.value.includes(v);
+ default: return false;
+ }
+ } catch {
+ return false;
+ }
+}
+
+function ruleMatches(rule, ctx) {
+ // AND across clauses. A rule always has ≥1 clause post-normalization.
+ for (const c of rule.when || []) {
+ if (!clauseMatches(c, ctx)) return false;
+ }
+ return true;
+}
+
+/**
+ * The single runtime decision. Ordered first-match: the first rule whose conditions
+ * all match decides the spend. No match → allowed (numeric caps still apply).
+ *
+ * @param {object} doc normalized policy document (or anything — it's re-normalized cheaply if raw)
+ * @param {object} ctx the spend context — see FIELD_TYPES for the keys it reads
+ * @returns {{ decision: 'allow'|'block'|'step_up'|'freeze', matched: object|null, ruleIndex: number|null, message: string|null }}
+ */
+export function evaluatePolicy(doc, ctx) {
+ const rules = Array.isArray(doc?.rules) ? doc.rules : [];
+ for (let i = 0; i < rules.length; i++) {
+ const rule = rules[i];
+ if (!rule || !Array.isArray(rule.when)) continue;
+ if (!ruleMatches(rule, ctx)) continue;
+ const decision = rule.action === 'allow' ? 'allow' : rule.action === 'require_step_up' ? 'step_up' : rule.action;
+ return { decision, matched: rule, ruleIndex: i, message: rule.label || describeRule(rule) };
+ }
+ return { decision: 'allow', matched: null, ruleIndex: null, message: null };
+}
+
+/** True when a decision denies the spend (everything except an allow). */
+export function isDenied(decision) {
+ return decision === 'block' || decision === 'step_up' || decision === 'freeze';
+}
+
+// ── readback (deterministic, golden-tested) ──────────────────────────────────────
+// The plain-English the owner confirms is GENERATED from the compiled DSL — never
+// the model's free-text — so the readback can never drift from what code enforces.
+
+const FIELD_NOUN = {
+ amount_usd: 'the amount',
+ daily_spent_usd: 'today’s spend so far',
+ daily_total_usd: 'today’s total spend',
+ token_age_hours: 'the token’s age',
+ sol_reserve_after: 'the SOL left afterward',
+ trade_pnl_pct: 'the trade’s profit/loss',
+ time_of_day_utc: 'the hour (UTC)',
+ asset: 'the asset',
+ counterparty: 'the recipient',
+ category: 'the spend type',
+ destination_allowlisted: 'the destination',
+ counterparty_seen_before: 'the recipient',
+};
+
+function usd(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '$0';
+ return `$${v % 1 === 0 ? v.toLocaleString('en-US') : v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+}
+
+function describeClause(c) {
+ const f = c.field;
+ const cmp = { gt: 'over', gte: 'at least', lt: 'under', lte: 'at most', eq: 'exactly', neq: 'not' };
+ switch (f) {
+ case 'amount_usd': return `the amount is ${cmp[c.op] || c.op} ${usd(c.value)}`;
+ case 'daily_spent_usd': return `today’s spend so far is ${cmp[c.op] || c.op} ${usd(c.value)}`;
+ case 'daily_total_usd': return `today’s total would be ${cmp[c.op] || c.op} ${usd(c.value)}`;
+ case 'token_age_hours': {
+ const h = Number(c.value);
+ const human = h % 24 === 0 ? `${h / 24} day${h === 24 ? '' : 's'}` : `${h} hour${h === 1 ? '' : 's'}`;
+ return `the token is ${c.op === 'lt' || c.op === 'lte' ? 'younger than' : c.op === 'gt' || c.op === 'gte' ? 'older than' : cmp[c.op]} ${human}`;
+ }
+ case 'sol_reserve_after': return `it would leave ${c.op === 'lt' || c.op === 'lte' ? 'less than' : c.op === 'gt' || c.op === 'gte' ? 'more than' : cmp[c.op]} ${Number(c.value)} SOL in the wallet`;
+ case 'trade_pnl_pct': {
+ const v = Number(c.value);
+ if ((c.op === 'lt' || c.op === 'lte') && v < 0) return `the trade is down more than ${Math.abs(v)}%`;
+ if ((c.op === 'gt' || c.op === 'gte') && v > 0) return `the trade is up more than ${v}%`;
+ return `the trade’s P&L is ${cmp[c.op] || c.op} ${v}%`;
+ }
+ case 'time_of_day_utc': return `the hour (UTC) is ${cmp[c.op] || c.op} ${Number(c.value)}:00`;
+ case 'asset':
+ if (c.op === 'in') return `the asset is one of ${c.value.join(', ')}`;
+ if (c.op === 'not_in') return `the asset is not ${c.value.join(', ')}`;
+ return `the asset is ${c.op === 'neq' ? 'not ' : ''}${c.value}`;
+ case 'category':
+ if (c.op === 'in') return `it is a ${c.value.join(' or ')}`;
+ if (c.op === 'not_in') return `it is not a ${c.value.join(' or ')}`;
+ return `it is ${c.op === 'neq' ? 'not ' : ''}a ${c.value}`;
+ case 'counterparty':
+ if (c.op === 'in') return `the recipient is a known address`;
+ if (c.op === 'not_in') return `the recipient is not an approved address`;
+ return `the recipient is ${c.op === 'neq' ? 'not ' : ''}${c.value}`;
+ case 'destination_allowlisted':
+ return c.value === true ? 'the destination is on your allowlist' : 'the destination is not on your allowlist';
+ case 'counterparty_seen_before':
+ return c.value === true ? 'you have paid this recipient before' : 'you have never paid this recipient before';
+ default: {
+ const noun = FIELD_NOUN[f] || f;
+ return `${noun} ${cmp[c.op] || c.op} ${c.value}`;
+ }
+ }
+}
+
+const ACTION_VERB = {
+ allow: 'Always allow',
+ block: 'Block',
+ require_step_up: 'Require your approval for',
+ freeze: 'Freeze the wallet and block',
+};
+
+/** One numbered, human sentence for a single rule, built purely from the DSL. */
+export function describeRule(rule) {
+ if (!rule || !Array.isArray(rule.when) || !rule.when.length) return '';
+ const verb = ACTION_VERB[rule.action] || 'Block';
+ const conds = rule.when.map(describeClause);
+ const when = conds.length === 1 ? conds[0] : conds.slice(0, -1).join(', ') + ' and ' + conds.slice(-1);
+ // "Block a spend when the amount is over $50." reads naturally for every action.
+ const object = rule.action === 'freeze' ? 'all spending' : 'the spend';
+ return `${verb} ${object} when ${when}.`;
+}
+
+/** The numbered plain-English readback of an entire policy. */
+export function describePolicyRules(doc) {
+ const rules = Array.isArray(doc?.rules) ? doc.rules : [];
+ return rules.map((r, i) => ({ n: i + 1, id: r.id, action: r.action, text: r.label || describeRule(r) }));
+}
+
+// ── policy diff (for the audit trail + loosening warnings) ────────────────────────
+
+function ruleKey(r) {
+ // Order-insensitive signature of a rule's enforced effect.
+ const clauses = (r.when || [])
+ .map((c) => `${c.field}:${c.op}:${Array.isArray(c.value) ? [...c.value].sort().join('|') : c.value}`)
+ .sort()
+ .join(';');
+ return `${r.action}#${clauses}`;
+}
+
+// Actions ranked by how much protection they provide. Replacing a stronger action
+// with a weaker one on the same conditions is a loosening the owner must confirm.
+const PROTECTION_RANK = { freeze: 4, block: 3, require_step_up: 2, allow: 1 };
+
+/**
+ * Diff two policy documents for the audit trail and the "this loosens protection"
+ * confirmation. Returns added/removed rules plus an explicit `loosened` flag set
+ * when a rule was removed or downgraded (so we never weaken protection silently).
+ */
+export function diffPolicies(prevDoc, nextDoc) {
+ const prev = Array.isArray(prevDoc?.rules) ? prevDoc.rules : [];
+ const next = Array.isArray(nextDoc?.rules) ? nextDoc.rules : [];
+ const prevKeys = new Map(prev.map((r) => [ruleKey(r), r]));
+ const nextKeys = new Map(next.map((r) => [ruleKey(r), r]));
+
+ const added = next.filter((r) => !prevKeys.has(ruleKey(r)));
+ const removed = prev.filter((r) => !nextKeys.has(ruleKey(r)));
+
+ // Loosening: a protective rule disappeared, or the overall strongest protection
+ // dropped. Removing a `block`/`freeze` is the clearest case.
+ const removedProtective = removed.filter((r) => PROTECTION_RANK[r.action] >= 3);
+ const loosened = removedProtective.length > 0 || (prev.length > 0 && next.length === 0);
+
+ return {
+ added: added.map((r) => ({ id: r.id, action: r.action, text: r.label || describeRule(r) })),
+ removed: removed.map((r) => ({ id: r.id, action: r.action, text: r.label || describeRule(r) })),
+ loosened,
+ loosening_notes: removedProtective.map((r) => `Removes: “${r.label || describeRule(r)}”`),
+ };
+}
+
+// ── backtest engine ──────────────────────────────────────────────────────────────
+
+function hourOf(ts) {
+ const d = ts instanceof Date ? ts : new Date(ts);
+ const h = d.getUTCHours();
+ return Number.isFinite(h) ? h : null;
+}
+
+/**
+ * Build the evaluation context for one historical custody 'spend' row. `extra`
+ * carries signals that live in the row's meta (token age, P&L) so a backtest is
+ * exactly as informed as the live path would have been.
+ */
+export function contextFromEvent(event, { allowlist = [], dailySpentUsd = null, seenCounterparties = null } = {}) {
+ const usdVal = event?.usd != null ? Number(event.usd) : null;
+ const m = event?.meta && typeof event.meta === 'object' ? event.meta : {};
+ const dest = event?.destination || m.counterparty || null;
+ const ctx = {
+ amount_usd: usdVal != null && Number.isFinite(usdVal) ? usdVal : undefined,
+ category: event?.category || undefined,
+ asset: event?.asset || undefined,
+ counterparty: dest || undefined,
+ time_of_day_utc: event?.created_at ? hourOf(event.created_at) ?? undefined : undefined,
+ destination_allowlisted: dest ? allowlist.includes(dest) : undefined,
+ };
+ if (dailySpentUsd != null && Number.isFinite(dailySpentUsd)) {
+ ctx.daily_spent_usd = dailySpentUsd;
+ if (ctx.amount_usd != null) ctx.daily_total_usd = dailySpentUsd + ctx.amount_usd;
+ }
+ if (seenCounterparties && dest) ctx.counterparty_seen_before = seenCounterparties.has(dest);
+ // Signals that the meta may carry for trade/snipe rows.
+ if (isFiniteNum(Number(m.token_age_hours))) ctx.token_age_hours = Number(m.token_age_hours);
+ if (m.trade_pnl_pct != null && Number.isFinite(Number(m.trade_pnl_pct))) ctx.trade_pnl_pct = Number(m.trade_pnl_pct);
+ if (m.sol_reserve_after != null && Number.isFinite(Number(m.sol_reserve_after))) ctx.sol_reserve_after = Number(m.sol_reserve_after);
+ return ctx;
+}
+
+/**
+ * Replay an agent's real custody history against a proposed policy and report what
+ * it would have done — computed by the SAME `evaluatePolicy` that runs in
+ * production, so the preview is honest. Events should be 'spend' rows; they are
+ * replayed oldest→newest so the rolling daily total a rule sees is the one the
+ * policy itself would have produced.
+ *
+ * @param {object} doc normalized policy document
+ * @param {object[]} events custody events (any order; non-spend rows ignored)
+ * @param {object} [opts]
+ * @param {string[]} [opts.allowlist] withdraw allowlist for destination_allowlisted
+ * @returns {{ total, allowed, blocked, blocked_usd, allowed_usd, items, by_rule }}
+ */
+export function backtestPolicy(doc, events, { allowlist = [] } = {}) {
+ const spends = (Array.isArray(events) ? events : [])
+ .filter((e) => e && e.event_type === 'spend')
+ .slice()
+ .sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
+
+ const refs = referencedFields(doc);
+ const needsDaily = refs.has('daily_spent_usd') || refs.has('daily_total_usd');
+ const needsSeen = refs.has('counterparty_seen_before');
+
+ // Rolling 24h window of ALLOWED priced spends — the faithful daily total the
+ // policy would have observed (a blocked spend never adds to the day's tally).
+ const window = []; // [{ t: epochMs, usd }]
+ const seen = needsSeen ? new Set() : null;
+
+ const items = [];
+ const byRule = new Map();
+ let allowed = 0;
+ let blocked = 0;
+ let blockedUsd = 0;
+ let allowedUsd = 0;
+
+ for (const e of spends) {
+ const tMs = new Date(e.created_at).getTime();
+ let dailySpent = null;
+ if (needsDaily) {
+ const cutoff = tMs - 24 * 3600 * 1000;
+ while (window.length && window[0].t <= cutoff) window.shift();
+ dailySpent = window.reduce((s, w) => s + w.usd, 0);
+ }
+ const ctx = contextFromEvent(e, { allowlist, dailySpentUsd: dailySpent, seenCounterparties: seen });
+ const verdict = evaluatePolicy(doc, ctx);
+ const denied = isDenied(verdict.decision);
+ const usdVal = e.usd != null ? Number(e.usd) : 0;
+
+ if (denied) {
+ blocked++;
+ blockedUsd += Number.isFinite(usdVal) ? usdVal : 0;
+ const idx = verdict.ruleIndex;
+ const key = idx;
+ const agg = byRule.get(key) || { ruleIndex: idx, id: verdict.matched?.id, action: verdict.matched?.action, label: verdict.message, count: 0, usd: 0 };
+ agg.count++;
+ agg.usd += Number.isFinite(usdVal) ? usdVal : 0;
+ byRule.set(key, agg);
+ } else {
+ allowed++;
+ allowedUsd += Number.isFinite(usdVal) ? usdVal : 0;
+ // Only allowed priced spends accumulate toward the rolling daily total.
+ if (needsDaily && Number.isFinite(usdVal) && usdVal > 0) window.push({ t: tMs, usd: usdVal });
+ }
+ if (needsSeen && (e.destination || ctx.counterparty)) seen.add(e.destination || ctx.counterparty);
+
+ items.push({
+ id: e.id != null ? String(e.id) : null,
+ created_at: e.created_at,
+ category: e.category || null,
+ asset: e.asset || null,
+ usd: e.usd != null ? Number(e.usd) : null,
+ destination: e.destination || null,
+ decision: verdict.decision,
+ denied,
+ rule_index: verdict.ruleIndex,
+ rule_id: verdict.matched?.id || null,
+ rule_text: verdict.message || null,
+ });
+ }
+
+ // Newest-first for display; rolling math above already used chronological order.
+ items.reverse();
+
+ return {
+ total: spends.length,
+ allowed,
+ blocked,
+ blocked_usd: Number(blockedUsd.toFixed(2)),
+ allowed_usd: Number(allowedUsd.toFixed(2)),
+ items,
+ by_rule: [...byRule.values()].sort((a, b) => b.count - a.count),
+ };
+}
+
+// ── synthetic probes ─────────────────────────────────────────────────────────────
+// A handful of hypothetical spends, derived from the policy's own thresholds, run
+// through the same evaluator. Lets the owner see "a $60 payment → blocked" even with
+// zero history. Clearly labelled as hypothetical in the UI — never mixed into the
+// real backtest counts.
+
+/** Build a small, honest set of "what would happen if…" probes for a policy. */
+export function syntheticProbes(doc) {
+ const refs = referencedFields(doc);
+ const probes = [];
+ const add = (label, ctx) => {
+ const v = evaluatePolicy(doc, ctx);
+ probes.push({ label, decision: v.decision, denied: isDenied(v.decision), rule_index: v.ruleIndex, rule_text: v.message || null });
+ };
+ const base = { category: 'trade', asset: 'SOL', amount_usd: 10, daily_spent_usd: 0, daily_total_usd: 10 };
+
+ if (refs.has('amount_usd') || refs.has('per_tx')) {
+ add('A $5 payment', { ...base, category: 'x402', asset: 'USDC', amount_usd: 5, daily_total_usd: 5 });
+ add('A $250 payment', { ...base, category: 'x402', asset: 'USDC', amount_usd: 250, daily_total_usd: 250 });
+ }
+ if (refs.has('token_age_hours')) {
+ add('Buying a 30-minute-old token', { ...base, token_age_hours: 0.5 });
+ add('Buying a 3-day-old token', { ...base, token_age_hours: 72 });
+ }
+ if (refs.has('sol_reserve_after')) {
+ add('A trade leaving 0.4 SOL', { ...base, sol_reserve_after: 0.4 });
+ add('A trade leaving 5 SOL', { ...base, sol_reserve_after: 5 });
+ }
+ if (refs.has('trade_pnl_pct')) {
+ add('A trade down 40%', { ...base, trade_pnl_pct: -40 });
+ add('A trade up 20%', { ...base, trade_pnl_pct: 20 });
+ }
+ if (refs.has('counterparty_seen_before')) {
+ add('Paying a brand-new service', { ...base, category: 'x402', asset: 'USDC', counterparty_seen_before: false });
+ add('Paying a service used before', { ...base, category: 'x402', asset: 'USDC', counterparty_seen_before: true });
+ }
+ if (refs.has('daily_total_usd') || refs.has('daily_spent_usd')) {
+ add('A $30 trade after $40 spent today', { ...base, daily_spent_usd: 40, amount_usd: 30, daily_total_usd: 70 });
+ }
+ // Always include a plain small spend so the owner sees the default-allow baseline.
+ if (!probes.length) add('A typical small spend', base);
+ return probes.slice(0, 8);
+}
diff --git a/api/_lib/wallet-capabilities.js b/api/_lib/wallet-capabilities.js
new file mode 100644
index 000000000..f3c5ea2f7
--- /dev/null
+++ b/api/_lib/wallet-capabilities.js
@@ -0,0 +1,669 @@
+// Scoped session keys — capability-based least-privilege for autonomous agent
+// spending. The companion to the wallet-wide policy in agent-trade-guards.js.
+//
+// THE MODEL
+// A capability is a signed, scoped, time-boxed, independently-revocable grant
+// that lets a SPECIFIC actor (a skill / strategy / integration) spend a NARROW
+// slice of the wallet's authority — e.g. "this sniper strategy may spend up to
+// 2 SOL on these mints for the next 24h, and nothing else." Each capability is
+// audited and killable on its own; a rogue or buggy holder can never exceed the
+// leash the owner gave it.
+//
+// CAPABILITIES STRICTLY SUBTRACT AUTHORITY
+// On every autonomous spend BOTH the capability ceiling AND the wallet-wide
+// policy must pass. A capability can only ever narrow — never widen — what the
+// wallet policy already allows. A bug here must fail toward LESS access: an
+// unverifiable / expired / revoked / out-of-scope grant is rejected (deny), and
+// when the owner turns on "require a capability for every autonomous spend",
+// the absence of a covering grant is also a deny.
+//
+// UNFORGEABLE + TAMPER-EVIDENT
+// `grant_sig` is an HMAC-SHA256 over the immutable scope keyed by a server-held
+// secret (env.WALLET_CAPABILITY_SECRET). It is re-verified server-side on every
+// use. A DB-write attacker who forges a row or edits a scope field produces a
+// grant whose HMAC no longer verifies, so the spend path rejects it. Expiry and
+// revocation are likewise enforced server-side on every use, never client-trusted.
+//
+// AGGREGATE ACCOUNTING (concurrency-safe)
+// Per-capability lifetime spend is summed from agent_custody_events rows tagged
+// with capability_id — the SAME ledger that backs the wallet daily ceiling, so
+// one pending row counts toward both. reserveCapabilitySpend() does the check +
+// reserve as ONE statement under a per-capability advisory lock (and, when a
+// wallet daily cap is in play, the per-agent lock too), so K concurrent uses can
+// never all read the same stale total and overspend the ceiling.
+
+import { createHmac, timingSafeEqual, randomUUID } from 'node:crypto';
+import { sql } from './db.js';
+import { env } from './env.js';
+// Circular by design: the shared guards import the capability gate from here, and
+// we import the custody-ledger writer + the SpendLimitError class from there. Both
+// sides only touch these bindings inside function bodies (never at module eval), so
+// the cycle resolves cleanly at call time. Capability denials ARE spend-policy
+// breaches and reuse SpendLimitError so every existing `instanceof SpendLimitError`
+// catch site (x402, trade, snipe, withdraw) handles them with no change.
+import { recordCustodyEvent, SpendLimitError } from './agent-trade-guards.js';
+
+// Back-compat / intent-revealing alias: a capability breach is a SpendLimitError.
+export { SpendLimitError as CapabilityError };
+
+// The action types a capability can authorize. Mirrors the `category` vocabulary
+// the shared guards already use for autonomous outbound paths. 'withdraw' is
+// deliberately absent: an owner-initiated sweep is not a delegated capability.
+export const CAPABILITY_ACTIONS = Object.freeze(['trade', 'snipe', 'x402']);
+const ACTION_SET = new Set(CAPABILITY_ACTIONS);
+
+export const CAPABILITY_TARGET_KINDS = Object.freeze(['any', 'mint', 'service', 'destination']);
+const TARGET_KIND_SET = new Set(CAPABILITY_TARGET_KINDS);
+
+export const HOLDER_KINDS = Object.freeze(['skill', 'strategy', 'integration', 'manual']);
+const HOLDER_KIND_SET = new Set(HOLDER_KINDS);
+
+const MAX_TARGETS = 50;
+const MAX_LABEL = 120;
+const MAX_TTL_SECONDS = 366 * 24 * 60 * 60; // a year — capabilities are always time-boxed
+const MIN_TTL_SECONDS = 60; // a grant that expires in <1min is almost certainly a mistake
+
+// An issuance-input breach: surfaced as a 400 (bad request) rather than the 403 a
+// runtime spend denial uses. Reuses SpendLimitError so callers can treat capability
+// and policy errors uniformly; only the status differs.
+function capInvalid(message, detail = {}) {
+ const e = new SpendLimitError('invalid', message, detail);
+ e.status = 400;
+ return e;
+}
+
+function nowMs(now) {
+ // Date.now() is forbidden in some sandboxes; callers may inject `now`. Default
+ // to the real clock at runtime (server code, not a workflow script).
+ return now instanceof Date ? now.getTime() : typeof now === 'number' ? now : Date.now();
+}
+
+function numOrNull(v) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) return null;
+ return n;
+}
+
+function cleanStr(v, max = 200) {
+ return typeof v === 'string' ? v.trim().slice(0, max) : '';
+}
+
+// Normalize a service allow entry to a bare lowercase host. Accepts a full URL, a
+// scheme-less host, or a host:port — anything else is dropped. So an owner can
+// type "api.weather.com", "https://api.weather.com/v1" or "weather.com" and the
+// stored allowlist is a canonical set of hosts to match a payment target against.
+function normalizeServiceHost(raw) {
+ const s = cleanStr(raw, 253).toLowerCase();
+ if (!s) return '';
+ try {
+ const u = new URL(s.includes('://') ? s : `https://${s}`);
+ return u.hostname || '';
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * Coerce arbitrary issuance input into a clean, bounded capability scope. Throws
+ * CapabilityError('invalid', …) when the request can't describe a real, useful
+ * leash — issuance must fail safe (no half-defined grant ever reaches the DB).
+ *
+ * @returns {{ actions, perUseUsd, aggregateUsd, targetKind, targets, expiresAt }}
+ */
+export function normalizeCapabilityInput(raw, { now } = {}) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+
+ const actions = [...new Set(
+ (Array.isArray(r.actions) ? r.actions : [])
+ .map((a) => cleanStr(a, 16).toLowerCase())
+ .filter((a) => ACTION_SET.has(a)),
+ )];
+ if (actions.length === 0) {
+ throw capInvalid('A capability must allow at least one action (trade, snipe, or x402).', { field: 'actions' });
+ }
+
+ const perUseUsd = numOrNull(r.per_use_usd ?? r.perUseUsd);
+ const aggregateUsd = numOrNull(r.aggregate_usd ?? r.aggregateUsd);
+ // A capability with no ceiling at all isn't a leash — it would only narrow by
+ // action/target/expiry, which is fine, but most callers want a budget. Require
+ // at least ONE bound (ceiling or a non-'any' target) so "least privilege" is
+ // real and the owner can't accidentally mint an effectively-unbounded grant.
+ let targetKind = cleanStr(r.target_kind ?? r.targetKind ?? 'any', 16).toLowerCase();
+ if (!TARGET_KIND_SET.has(targetKind)) targetKind = 'any';
+
+ let targets = [];
+ if (targetKind !== 'any') {
+ const rawTargets = Array.isArray(r.targets) ? r.targets : [];
+ const mapped = rawTargets
+ .map((t) => (targetKind === 'service' ? normalizeServiceHost(t) : cleanStr(t, 64)))
+ .filter(Boolean);
+ targets = [...new Set(mapped)].slice(0, MAX_TARGETS);
+ if (targets.length === 0) {
+ throw capInvalid(`A "${targetKind}" capability needs at least one allowed target.`, { field: 'targets' });
+ }
+ }
+
+ const hasBound = perUseUsd != null || aggregateUsd != null || targetKind !== 'any';
+ if (!hasBound) {
+ throw capInvalid('A capability must set a spend ceiling or a target allowlist — otherwise it grants no narrower authority than the wallet itself.', { field: 'ceiling' });
+ }
+ if (perUseUsd != null && aggregateUsd != null && perUseUsd > aggregateUsd + 1e-9) {
+ throw capInvalid('The per-use ceiling cannot exceed the total budget.', { field: 'per_use_usd' });
+ }
+
+ // Expiry: a capability is ALWAYS time-boxed. Accept either an absolute
+ // `expires_at` (ISO) or a `ttl_seconds`; clamp to a sane window.
+ const base = nowMs(now);
+ let expiresAt;
+ if (r.expires_at || r.expiresAt) {
+ const t = new Date(r.expires_at || r.expiresAt).getTime();
+ if (!Number.isFinite(t)) throw capInvalid('expires_at is not a valid date.', { field: 'expires_at' });
+ expiresAt = new Date(t);
+ } else {
+ let ttl = Number(r.ttl_seconds ?? r.ttlSeconds);
+ if (!Number.isFinite(ttl) || ttl <= 0) ttl = 24 * 60 * 60; // sensible default: 24h
+ ttl = Math.min(MAX_TTL_SECONDS, Math.max(MIN_TTL_SECONDS, Math.floor(ttl)));
+ expiresAt = new Date(base + ttl * 1000);
+ }
+ if (expiresAt.getTime() <= base) {
+ throw capInvalid('A capability must expire in the future.', { field: 'expires_at' });
+ }
+ if (expiresAt.getTime() - base > MAX_TTL_SECONDS * 1000 + 1000) {
+ throw capInvalid('A capability can last at most one year.', { field: 'expires_at' });
+ }
+
+ return { actions: actions.sort(), perUseUsd, aggregateUsd, targetKind, targets: targets.sort(), expiresAt };
+}
+
+// ── tamper-evidence (HMAC over the immutable scope) ────────────────────────────
+
+/**
+ * Deterministic canonical string of a grant's SECURITY-relevant, immutable scope.
+ * Anything that changes what the grant authorizes is in here; pure-display fields
+ * (label) and mutable lifecycle fields (revoked_at, use_count) are not — so a
+ * revoke doesn't need a re-sign, but editing actions/targets/ceilings/expiry/
+ * holder does invalidate the HMAC.
+ */
+export function canonicalScope(cap) {
+ const expISO = cap.expires_at instanceof Date
+ ? cap.expires_at.toISOString()
+ : new Date(cap.expires_at).toISOString();
+ return JSON.stringify([
+ 'cap-v1',
+ String(cap.id),
+ String(cap.agent_id),
+ String(cap.holder_kind || 'manual'),
+ cap.holder_ref ? String(cap.holder_ref) : '',
+ [...(cap.actions || [])].sort(),
+ cap.per_use_usd == null ? null : Number(cap.per_use_usd),
+ cap.aggregate_usd == null ? null : Number(cap.aggregate_usd),
+ String(cap.target_kind || 'any'),
+ [...(cap.targets || [])].sort(),
+ expISO,
+ ]);
+}
+
+function capabilitySecret() {
+ const s = env.WALLET_CAPABILITY_SECRET;
+ if (!s || String(s).length < 8) {
+ // Never sign with a weak/empty key — that would let a DB-write attacker forge
+ // grants. Fail safe: refuse to mint rather than mint an unforgeable-in-name-only grant.
+ { const e = new SpendLimitError('config', 'Capability signing is not configured (WALLET_CAPABILITY_SECRET).'); e.status = 503; throw e; }
+ }
+ return String(s);
+}
+
+export function signGrant(cap) {
+ return createHmac('sha256', capabilitySecret()).update(canonicalScope(cap)).digest('hex');
+}
+
+/** Constant-time verification that a stored grant's HMAC matches its current scope. */
+export function verifyGrant(cap) {
+ const expected = signGrant(cap);
+ const got = String(cap.grant_sig || '');
+ if (got.length !== expected.length) return false;
+ try {
+ return timingSafeEqual(Buffer.from(got, 'utf8'), Buffer.from(expected, 'utf8'));
+ } catch {
+ return false;
+ }
+}
+
+// ── pure scope predicates (unit-testable; no DB, no clock side effects) ─────────
+
+/** Live = signed scope verifies, not revoked, not expired. */
+export function capabilityLive(cap, { now } = {}) {
+ if (!cap) return { ok: false, reason: 'not_found' };
+ if (!verifyGrant(cap)) return { ok: false, reason: 'tampered' };
+ if (cap.revoked_at) return { ok: false, reason: 'revoked' };
+ const exp = cap.expires_at instanceof Date ? cap.expires_at.getTime() : new Date(cap.expires_at).getTime();
+ if (!Number.isFinite(exp) || exp <= nowMs(now)) return { ok: false, reason: 'expired' };
+ return { ok: true };
+}
+
+export function capabilityCoversAction(cap, action) {
+ return Array.isArray(cap?.actions) && cap.actions.includes(action);
+}
+
+/**
+ * Does the grant's target allowlist cover this spend's target? 'any' covers
+ * everything; 'mint'/'destination' need an exact base58 match; 'service' matches
+ * the host of the payment target (so "api.x.com" covers https://api.x.com/v1/…).
+ */
+export function capabilityCoversTarget(cap, target) {
+ const kind = cap?.target_kind || 'any';
+ if (kind === 'any') return true;
+ const list = Array.isArray(cap?.targets) ? cap.targets : [];
+ if (list.length === 0) return false;
+ const t = typeof target === 'string' ? target.trim() : '';
+ if (!t) return false;
+ if (kind === 'service') {
+ const host = normalizeServiceHost(t);
+ return host ? list.includes(host) : false;
+ }
+ return list.includes(t);
+}
+
+/** Per-use ceiling. Blocked when this single spend exceeds the cap. */
+export function checkPerUse(cap, usdValue) {
+ if (cap?.per_use_usd == null) return null;
+ if (typeof usdValue !== 'number' || !Number.isFinite(usdValue)) return null;
+ if (usdValue > Number(cap.per_use_usd) + 1e-9) {
+ return { reason: 'per_use_exceeded', detail: { usd: usdValue, per_use_usd: Number(cap.per_use_usd) } };
+ }
+ return null;
+}
+
+/** Aggregate (lifetime) ceiling. Blocked when prior spend + this spend exceeds it. */
+export function checkAggregate(spentUsd, usdValue, cap) {
+ if (cap?.aggregate_usd == null) return null;
+ if (typeof usdValue !== 'number' || !Number.isFinite(usdValue)) return null;
+ const spent = Number(spentUsd) || 0;
+ if (spent + usdValue > Number(cap.aggregate_usd) + 1e-9) {
+ return { reason: 'aggregate_exceeded', detail: { usd: usdValue, spent_usd: spent, aggregate_usd: Number(cap.aggregate_usd) } };
+ }
+ return null;
+}
+
+/**
+ * Compose every read-only check a capability must pass for one spend EXCEPT the
+ * aggregate ceiling (which needs the live ledger total and an advisory lock — see
+ * reserveCapabilitySpend). Returns null when in scope, or a structured
+ * { reason, detail } when the spend is outside the leash. Pure + synchronous.
+ *
+ * @param {object} o
+ * @param {object} o.cap the capability row
+ * @param {string} o.action trade | snipe | x402
+ * @param {string} [o.target] mint / service URL / destination of this spend
+ * @param {number} [o.usdValue] USD value of this spend (null = unpriceable)
+ * @param {number|Date} [o.now]
+ */
+export function evaluateCapabilityScope({ cap, action, target, usdValue, now }) {
+ const live = capabilityLive(cap, { now });
+ if (!live.ok) return { reason: live.reason, detail: {} };
+ if (!capabilityCoversAction(cap, action)) {
+ return { reason: 'action_not_allowed', detail: { action, allowed: cap.actions || [] } };
+ }
+ if (!capabilityCoversTarget(cap, target)) {
+ return { reason: 'target_not_allowed', detail: { target: target ?? null, target_kind: cap.target_kind } };
+ }
+ const perUse = checkPerUse(cap, usdValue);
+ if (perUse) return perUse;
+ return null;
+}
+
+// ── boundary message mapping ────────────────────────────────────────────────────
+
+const CAP_MESSAGE = {
+ not_found: () => 'No capability authorizes this action. Issue a scoped session key under Access, or remove the requirement.',
+ tampered: () => 'This capability failed its integrity check and was rejected. Revoke it and issue a fresh one.',
+ revoked: () => 'This capability has been revoked. Issue a new one under Access to allow this action.',
+ expired: () => 'This capability has expired. Issue a new one under Access to allow this action.',
+ action_not_allowed: (d) => `This capability does not allow ${d.action} actions (it allows: ${(d.allowed || []).join(', ') || 'none'}).`,
+ target_not_allowed: (d) => `This capability is restricted to specific ${d.target_kind === 'service' ? 'services' : d.target_kind === 'mint' ? 'mints' : 'destinations'} and does not cover this one.`,
+ per_use_exceeded: (d) => `This $${Number(d.usd).toFixed(2)} spend is over the capability's $${Number(d.per_use_usd).toFixed(2)} per-use limit.`,
+ aggregate_exceeded: (d) => `This spend would bring the capability's total to $${(Number(d.spent_usd) + Number(d.usd)).toFixed(2)}, over its $${Number(d.aggregate_usd).toFixed(2)} budget.`,
+ capability_required: () => 'This wallet requires a scoped capability for every autonomous spend, and none covers this action. Issue one under Access.',
+};
+
+/** Turn a capability reason into a CapabilityError ready for the boundary. */
+export function capabilityError(reason, detail = {}) {
+ const msg = (CAP_MESSAGE[reason] || (() => `Action not permitted by capability (${reason}).`))(detail);
+ return new SpendLimitError(reason, msg, detail);
+}
+
+// ── DB: issuance + lifecycle ────────────────────────────────────────────────────
+
+function shapeRow(row) {
+ if (!row) return null;
+ return {
+ ...row,
+ actions: Array.isArray(row.actions) ? row.actions : [],
+ targets: Array.isArray(row.targets) ? row.targets : [],
+ per_use_usd: row.per_use_usd == null ? null : Number(row.per_use_usd),
+ aggregate_usd: row.aggregate_usd == null ? null : Number(row.aggregate_usd),
+ };
+}
+
+/**
+ * Mint a capability. Validates + bounds the scope, signs it (tamper-evidence),
+ * inserts the row, and writes a custody audit event. The owner-check is the
+ * caller's responsibility (the endpoint gates ownership before calling).
+ */
+export async function mintCapability({
+ agentId, userId, label, holderKind = 'manual', holderRef = null,
+ actions, perUseUsd, aggregateUsd, targetKind, targets, expiresAt, ttlSeconds, meta = {}, now,
+}) {
+ const scope = normalizeCapabilityInput(
+ { actions, per_use_usd: perUseUsd, aggregate_usd: aggregateUsd, target_kind: targetKind, targets, expires_at: expiresAt, ttl_seconds: ttlSeconds },
+ { now },
+ );
+ const kind = HOLDER_KIND_SET.has(holderKind) ? holderKind : 'manual';
+ const id = randomUUID();
+ const cap = {
+ id,
+ agent_id: agentId,
+ holder_kind: kind,
+ holder_ref: holderRef ? cleanStr(holderRef, 128) : null,
+ actions: scope.actions,
+ per_use_usd: scope.perUseUsd,
+ aggregate_usd: scope.aggregateUsd,
+ target_kind: scope.targetKind,
+ targets: scope.targets,
+ expires_at: scope.expiresAt,
+ };
+ const grantSig = signGrant(cap);
+ const cleanLabel = cleanStr(label, MAX_LABEL) || defaultLabel(kind, holderRef, scope.actions);
+
+ const [row] = await sql`
+ INSERT INTO agent_wallet_capabilities
+ (id, agent_id, user_id, label, holder_kind, holder_ref, actions, per_use_usd,
+ aggregate_usd, target_kind, targets, expires_at, grant_sig, meta)
+ VALUES (
+ ${id}, ${agentId}, ${userId}, ${cleanLabel}, ${kind}, ${cap.holder_ref},
+ ${scope.actions}, ${scope.perUseUsd}, ${scope.aggregateUsd}, ${scope.targetKind},
+ ${scope.targets}, ${scope.expiresAt.toISOString()}, ${grantSig},
+ ${JSON.stringify(meta || {})}::jsonb
+ )
+ RETURNING *
+ `;
+
+ await recordCustodyEvent({
+ agentId, userId, eventType: 'capability_mint', category: null,
+ reason: 'capability_minted', capabilityId: id,
+ meta: {
+ label: cleanLabel, holder_kind: kind, holder_ref: cap.holder_ref,
+ actions: scope.actions, per_use_usd: scope.perUseUsd, aggregate_usd: scope.aggregateUsd,
+ target_kind: scope.targetKind, targets: scope.targets, expires_at: scope.expiresAt.toISOString(),
+ },
+ }).catch((e) => console.warn('[capabilities] mint custody record failed', e?.message));
+
+ return shapeRow(row);
+}
+
+function defaultLabel(kind, holderRef, actions) {
+ const verb = actions.join('/');
+ if (kind === 'strategy') return `Strategy · ${verb}`;
+ if (kind === 'integration') return `Integration · ${verb}`;
+ if (kind === 'skill') return `Skill · ${verb}`;
+ return `${verb} capability`;
+}
+
+export async function getCapability(id) {
+ const [row] = await sql`SELECT * FROM agent_wallet_capabilities WHERE id = ${id}`;
+ return shapeRow(row);
+}
+
+/** Sum the priced spend a capability has consumed (its aggregate-ceiling ledger). */
+export async function capabilitySpentUsd(id) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE capability_id = ${id}
+ AND status IN ('ok', 'pending', 'confirmed')
+ AND usd IS NOT NULL
+ `;
+ return Number(row?.usd || 0);
+}
+
+/**
+ * List a wallet's capabilities for the owner Access surface, each decorated with
+ * its live status and how much of its budget is spent. Newest first.
+ */
+export async function listCapabilities(agentId, { includeRevoked = true, now } = {}) {
+ const rows = await sql`
+ SELECT c.*, COALESCE(s.spent, 0)::float8 AS spent_usd, COALESCE(s.uses, 0)::int AS spend_count
+ FROM agent_wallet_capabilities c
+ LEFT JOIN (
+ SELECT capability_id, SUM(usd) AS spent, COUNT(*) AS uses
+ FROM agent_custody_events
+ WHERE capability_id IS NOT NULL
+ AND status IN ('ok', 'pending', 'confirmed')
+ GROUP BY capability_id
+ ) s ON s.capability_id = c.id
+ WHERE c.agent_id = ${agentId}
+ ${includeRevoked ? sql`` : sql`AND c.revoked_at IS NULL`}
+ ORDER BY c.created_at DESC
+ LIMIT 200
+ `;
+ const t = nowMs(now);
+ return rows.map((row) => {
+ const cap = shapeRow(row);
+ const live = capabilityLive(cap, { now: t });
+ const status = live.ok ? 'active' : live.reason; // active | revoked | expired | tampered
+ return {
+ id: cap.id,
+ label: cap.label,
+ holder_kind: cap.holder_kind,
+ holder_ref: cap.holder_ref,
+ actions: cap.actions,
+ per_use_usd: cap.per_use_usd,
+ aggregate_usd: cap.aggregate_usd,
+ target_kind: cap.target_kind,
+ targets: cap.targets,
+ expires_at: cap.expires_at,
+ revoked_at: cap.revoked_at,
+ revoked_reason: cap.revoked_reason,
+ created_at: cap.created_at,
+ last_used_at: cap.last_used_at,
+ use_count: cap.use_count,
+ spent_usd: Number(row.spent_usd || 0),
+ spend_count: Number(row.spend_count || 0),
+ status,
+ };
+ });
+}
+
+/**
+ * Resolve the best live capability that covers an autonomous spend for a holder.
+ * Autonomous callers (sniper, x402) use this to FIND the grant to present without
+ * the owner threading an id through every call. Prefers a holder_ref match, then
+ * any holder; among candidates picks the one expiring soonest with budget left, so
+ * a tight short-lived grant is consumed before a looser one. Returns null when no
+ * live capability covers the action+target.
+ */
+export async function resolveCapabilityForSpend({ agentId, action, holderRef = null, target = null, usdValue = null, now }) {
+ const rows = await sql`
+ SELECT * FROM agent_wallet_capabilities
+ WHERE agent_id = ${agentId}
+ AND revoked_at IS NULL
+ AND expires_at > now()
+ AND ${action} = ANY(actions)
+ ORDER BY (holder_ref IS NOT DISTINCT FROM ${holderRef}) DESC, expires_at ASC
+ LIMIT 50
+ `;
+ for (const raw of rows) {
+ const cap = shapeRow(raw);
+ const scope = evaluateCapabilityScope({ cap, action, target, usdValue, now });
+ if (scope) continue; // out of scope (target/per-use/integrity) — try the next
+ return cap;
+ }
+ return null;
+}
+
+/** Revoke one capability immediately (owner-gated by the caller). Idempotent. */
+export async function revokeCapability(id, { agentId, userId, reason = 'owner_revoked' } = {}) {
+ const [row] = await sql`
+ UPDATE agent_wallet_capabilities
+ SET revoked_at = now(), revoked_reason = ${cleanStr(reason, 80) || 'owner_revoked'}, updated_at = now()
+ WHERE id = ${id}
+ AND ${agentId}::uuid IS NOT DISTINCT FROM agent_id
+ AND revoked_at IS NULL
+ RETURNING id, label
+ `;
+ if (!row) return null;
+ await recordCustodyEvent({
+ agentId, userId, eventType: 'capability_revoke', capabilityId: id,
+ reason: 'capability_revoked', meta: { label: row.label, reason },
+ }).catch((e) => console.warn('[capabilities] revoke custody record failed', e?.message));
+ return row;
+}
+
+/** Revoke every live capability for an agent at once ("kill all"). Returns count. */
+export async function revokeAllCapabilities(agentId, userId, reason = 'owner_revoked_all') {
+ const rows = await sql`
+ UPDATE agent_wallet_capabilities
+ SET revoked_at = now(), revoked_reason = ${cleanStr(reason, 80) || 'owner_revoked_all'}, updated_at = now()
+ WHERE agent_id = ${agentId} AND revoked_at IS NULL
+ RETURNING id
+ `;
+ if (rows.length) {
+ await recordCustodyEvent({
+ agentId, userId, eventType: 'capability_revoke', reason: 'capability_revoked_all',
+ meta: { count: rows.length, reason },
+ }).catch((e) => console.warn('[capabilities] revoke-all custody record failed', e?.message));
+ }
+ return rows.length;
+}
+
+// ── hot path: atomic scoped reserve ─────────────────────────────────────────────
+
+/**
+ * Atomically verify a capability covers a spend AND reserve a pending custody row
+ * against its aggregate ceiling (and, when supplied, the wallet daily ceiling),
+ * under per-capability + per-agent advisory locks. This is the capability analogue
+ * of reserveSpendUsd: check + reserve are ONE statement, so concurrent uses can
+ * never both pass on the same stale total and overspend a leash.
+ *
+ * The capability is RE-LOADED inside the locked statement, so a revoke or a spend
+ * that landed a microsecond earlier is always seen — revocation can't be raced.
+ *
+ * Returns { reservationId, capability, spentBefore }. Finalize with
+ * updateCustodyEvent(reservationId, { status, signature }) after settlement, or
+ * releaseSpendReservation(reservationId) if the spend never moved.
+ *
+ * @throws {CapabilityError} on integrity / scope / per-use / aggregate breach.
+ */
+export async function reserveCapabilitySpend({
+ capabilityId, agentId, userId, action, target = null, usdValue,
+ dailyUsd = null, network = 'mainnet', asset = null, destination = null, rowMeta = {}, now,
+}) {
+ const cap = await getCapability(capabilityId);
+ if (!cap || String(cap.agent_id) !== String(agentId)) throw capabilityError('not_found', {});
+
+ // Static scope checks first (cheap, no lock): integrity, expiry, revoked at read
+ // time, action, target, per-use. The authoritative revoke/expiry re-check happens
+ // again inside the locked statement below so a concurrent revoke can't slip through.
+ const scope = evaluateCapabilityScope({ cap, action, target, usdValue, now });
+ if (scope) throw capabilityError(scope.reason, scope.detail);
+
+ const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
+ const metaJson = JSON.stringify({ ...(rowMeta || {}), action, target: target ?? null });
+
+ // No priceable amount and no aggregate cap → nothing to meter; still write the
+ // pending row tagged with the capability so it shows on the leash + audit trail.
+ // (Per-use was already checked above; an unpriceable spend can't gate a USD cap.)
+ if (!hasUsd || (cap.aggregate_usd == null && dailyUsd == null)) {
+ const reservationId = await reserveUnmetered({ cap, agentId, userId, action, network, asset, destination, usd: hasUsd ? usdValue : null, metaJson });
+ if (reservationId == null) throw capabilityError('revoked', {}); // lost the revoke race
+ return { reservationId, capability: cap, spentBefore: null };
+ }
+
+ // Atomic metered reserve. Two advisory locks (capability + agent) serialize
+ // concurrent spends touching this leash and/or this wallet's daily cap. The
+ // INSERT…SELECT materializes the pending row ONLY when, at this instant, the
+ // capability is still live AND both ceilings have room. `live` re-reads the row
+ // under the lock, so a revoke/expiry that landed first is always honored.
+ const aggCap = cap.aggregate_usd == null ? null : Number(cap.aggregate_usd);
+ const dCap = dailyUsd == null ? null : Number(dailyUsd);
+ const rows = await sql`
+ WITH lock_cap AS (
+ SELECT pg_advisory_xact_lock(hashtextextended(${'cap:' + String(capabilityId)}, 0))
+ ),
+ lock_agent AS (
+ SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
+ ),
+ live AS (
+ SELECT id FROM agent_wallet_capabilities
+ WHERE id = ${capabilityId} AND revoked_at IS NULL AND expires_at > now()
+ ),
+ cap_spent AS (
+ SELECT COALESCE(SUM(usd), 0)::float8 AS s
+ FROM agent_custody_events
+ WHERE capability_id = ${capabilityId}
+ AND status IN ('ok', 'pending', 'confirmed') AND usd IS NOT NULL
+ ),
+ day_spent AS (
+ SELECT COALESCE(SUM(usd), 0)::float8 AS s
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND event_type = 'spend' AND status IN ('ok', 'pending', 'confirmed')
+ AND usd IS NOT NULL AND created_at > now() - interval '24 hours'
+ )
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset, usd, destination, status, capability_id, meta)
+ SELECT ${agentId}, ${userId ?? null}, 'spend', ${action}, ${network}, ${asset},
+ ${usdValue}, ${destination ?? null}, 'pending', ${capabilityId}, ${metaJson}::jsonb
+ FROM cap_spent, day_spent, lock_cap, lock_agent
+ WHERE (SELECT count(*) FROM live) = 1
+ AND (${aggCap}::float8 IS NULL OR cap_spent.s + ${usdValue}::float8 <= ${aggCap}::float8 + 1e-9)
+ AND (${dCap}::float8 IS NULL OR day_spent.s + ${usdValue}::float8 <= ${dCap}::float8 + 1e-9)
+ RETURNING id, (SELECT s FROM cap_spent) AS cap_before, (SELECT s FROM day_spent) AS day_before
+ `;
+
+ if (!rows.length) {
+ // Distinguish WHY nothing inserted so the boundary message is honest: a
+ // concurrent revoke/expiry vs. an exhausted ceiling. Re-read outside the lock.
+ const fresh = await getCapability(capabilityId);
+ const liveNow = capabilityLive(fresh, { now });
+ if (!liveNow.ok) throw capabilityError(liveNow.reason, {});
+ const spent = await capabilitySpentUsd(capabilityId);
+ const agg = checkAggregate(spent, usdValue, cap);
+ if (agg) throw capabilityError(agg.reason, agg.detail);
+ // Otherwise the wallet daily cap is what rejected — surface that uniformly.
+ throw new SpendLimitError('daily_exceeded', `This spend would exceed the wallet's daily limit of $${Number(dCap).toFixed(2)}.`, { spent_usd: 0, daily_usd: dCap });
+ }
+
+ // Best-effort usage stats (not on the spend hot path's critical correctness).
+ void sql`UPDATE agent_wallet_capabilities SET use_count = use_count + 1, last_used_at = now(), updated_at = now() WHERE id = ${capabilityId}`
+ .catch(() => {});
+
+ return { reservationId: rows[0].id, capability: cap, spentBefore: Number(rows[0].cap_before || 0) };
+}
+
+// Unmetered reserve: a capability spend with no USD ceiling to meter. Still gated
+// on the capability being live at insert time (so a revoke is never raced) and
+// tagged with capability_id for the audit trail + leash UI.
+async function reserveUnmetered({ cap, agentId, userId, action, network, asset, destination, usd, metaJson }) {
+ const rows = await sql`
+ WITH lock_cap AS (
+ SELECT pg_advisory_xact_lock(hashtextextended(${'cap:' + String(cap.id)}, 0))
+ ),
+ live AS (
+ SELECT id FROM agent_wallet_capabilities
+ WHERE id = ${cap.id} AND revoked_at IS NULL AND expires_at > now()
+ )
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset, usd, destination, status, capability_id, meta)
+ SELECT ${agentId}, ${userId ?? null}, 'spend', ${action}, ${network}, ${asset},
+ ${usd}, ${destination ?? null}, 'pending', ${cap.id}, ${metaJson}::jsonb
+ FROM live, lock_cap
+ WHERE (SELECT count(*) FROM live) = 1
+ RETURNING id
+ `;
+ if (!rows.length) return null;
+ void sql`UPDATE agent_wallet_capabilities SET use_count = use_count + 1, last_used_at = now(), updated_at = now() WHERE id = ${cap.id}`
+ .catch(() => {});
+ return rows[0].id;
+}
diff --git a/api/agents/solana-guard.js b/api/agents/solana-guard.js
new file mode 100644
index 000000000..2b4fb5c2d
--- /dev/null
+++ b/api/agents/solana-guard.js
@@ -0,0 +1,201 @@
+// /api/agents/:id/solana/guard — the Self-Defending Wallet control surface.
+//
+// Owner-only. Reads the wallet's behavioral baseline + anomaly timeline, lets the
+// owner tune sensitivity / set a safe-sweep address, and provides one-tap
+// adjudication of a freeze: APPROVE (unfreeze + teach the baseline so it won't
+// re-trip) or DENY (keep frozen). The scoring + freeze themselves happen inline on
+// the spend path (api/_lib/agent-trade-guards.js → anomaly-events.js); this
+// endpoint is the owner's window into, and control over, that system.
+//
+// GET → config + baseline + open flags + paginated timeline
+// PUT → update config (sensitivity | enabled | safe_address | clear_learned) [CSRF]
+// POST → adjudicate { event_id, action: approve|deny|mark_swept } | { action: unfreeze } [CSRF]
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { setSpendLimits, getSpendLimits, validateSolanaAddress } from '../_lib/agent-trade-guards.js';
+import { SENSITIVITY_PRESETS, getAnomalyConfig } from '../_lib/wallet-anomaly.js';
+import {
+ listAnomalyEvents, listOpenFlags, getAnomalyEvent, setAnomalyStatus,
+ loadBaselineForDisplay, saveAnomalyConfig, teachFromApproval,
+} from '../_lib/anomaly-events.js';
+
+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;
+}
+
+async function loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return { error: true }; }
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return { error: true }; }
+ return { auth, meta: { ...(row.meta || {}) } };
+}
+
+// Public config shape — never leak internal allowlist contents back wholesale, but
+// the owner SHOULD see what's been learned so they can audit it.
+function publicConfig(cfg) {
+ return {
+ enabled: cfg.enabled,
+ sensitivity: cfg.sensitivity,
+ safe_address: cfg.safe_address,
+ size_ceiling_usd: cfg.size_ceiling_usd,
+ extra_hours: cfg.extra_hours,
+ learned_destinations: cfg.allow_destinations.length,
+ updated_at: cfg.updated_at,
+ };
+}
+
+function eventOut(e) {
+ return {
+ id: String(e.id),
+ network: e.network,
+ category: e.category,
+ asset: e.asset,
+ usd: e.usd != null ? Number(e.usd) : null,
+ destination: e.destination,
+ score: e.score != null ? Number(e.score) : 0,
+ decision: e.decision,
+ critical: !!e.critical,
+ sensitivity: e.sensitivity,
+ factors: Array.isArray(e.factors) ? e.factors : [],
+ summary: e.summary,
+ status: e.status,
+ hour_utc: e.hour_utc,
+ swept: !!e.swept,
+ adjudicated_at: e.adjudicated_at || null,
+ created_at: e.created_at,
+ };
+}
+
+export async function handleGuard(req, res, id) {
+ if (cors(req, res, { methods: 'GET,PUT,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'POST'])) return;
+
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const { auth, meta } = owned;
+
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const config = getAnomalyConfig(meta);
+
+ // ── GET — full guard state ──────────────────────────────────────────────────
+ if (req.method === 'GET') {
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '40', 10) || 40));
+ const beforeRaw = url.searchParams.get('before');
+ const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? beforeRaw : null;
+
+ const [baseline, flags, events] = await Promise.all([
+ loadBaselineForDisplay(id, meta).catch(() => null),
+ listOpenFlags(id).catch(() => []),
+ listAnomalyEvents(id, { limit, beforeId }).catch(() => []),
+ ]);
+ const spendLimits = getSpendLimits(meta);
+ const items = events.map(eventOut);
+ const nextCursor = items.length === limit ? items[items.length - 1].id : null;
+
+ return json(res, 200, {
+ data: {
+ config: publicConfig(config),
+ presets: Object.values(SENSITIVITY_PRESETS),
+ frozen: spendLimits.frozen,
+ baseline,
+ open_flags: flags.map(eventOut),
+ timeline: { items, next_cursor: nextCursor },
+ },
+ });
+ }
+
+ // Mutations require CSRF — disarming the guard or unfreezing a wallet is exactly
+ // as sensitive as editing the spend policy.
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+
+ // ── PUT — tune config ───────────────────────────────────────────────────────
+ if (req.method === 'PUT') {
+ const patch = {};
+ if ('enabled' in body) patch.enabled = body.enabled === true;
+ if ('sensitivity' in body) {
+ if (!SENSITIVITY_PRESETS[body.sensitivity]) {
+ return error(res, 400, 'invalid_sensitivity', 'sensitivity must be relaxed, balanced, or strict');
+ }
+ patch.sensitivity = body.sensitivity;
+ }
+ if ('safe_address' in body) {
+ if (body.safe_address === null || body.safe_address === '') {
+ patch.safe_address = null;
+ } else {
+ const v = validateSolanaAddress(body.safe_address);
+ if (!v.valid) return error(res, 400, 'invalid_address', 'safe_address is not a valid Solana address');
+ if (!v.onCurve) return error(res, 400, 'invalid_address', 'safe_address looks like a program address (PDA); funds sent there could be unrecoverable');
+ patch.safe_address = v.base58;
+ }
+ }
+ // Reset everything the guard has learned (destinations / size ceiling / hours).
+ if (body.clear_learned === true) {
+ patch.allow_destinations = [];
+ patch.size_ceiling_usd = null;
+ patch.extra_hours = [];
+ }
+ const next = await saveAnomalyConfig(id, meta, patch);
+ return json(res, 200, { data: { config: publicConfig(next) } });
+ }
+
+ // ── POST — adjudicate ───────────────────────────────────────────────────────
+ const action = typeof body.action === 'string' ? body.action : '';
+
+ // Generic unfreeze (owner override) — not tied to a specific flag.
+ if (action === 'unfreeze') {
+ await setSpendLimits(id, auth.userId, { frozen: false }, { req });
+ // Clear any still-open flags as approved-by-unfreeze so the UI settles.
+ await sql`UPDATE agent_anomaly_events SET status = 'approved', adjudicated_by = ${auth.userId}, adjudicated_at = now() WHERE agent_id = ${id} AND status = 'flagged'`;
+ return json(res, 200, { data: { frozen: false, action: 'unfreeze' } });
+ }
+
+ const eventId = body.event_id != null && /^\d+$/.test(String(body.event_id)) ? String(body.event_id) : null;
+ if (!eventId) return error(res, 400, 'bad_request', 'event_id is required');
+ const evt = await getAnomalyEvent(id, eventId);
+ if (!evt) return error(res, 404, 'not_found', 'anomaly event not found');
+
+ if (action === 'approve') {
+ // Teach the baseline so this exact pattern won't re-trip, then unfreeze.
+ const next = await teachFromApproval(id, meta, { destination: evt.destination, usd: evt.usd, hour_utc: evt.hour_utc });
+ await setSpendLimits(id, auth.userId, { frozen: false }, { req });
+ await setAnomalyStatus(eventId, { status: 'approved', userId: auth.userId });
+ return json(res, 200, { data: { frozen: false, action: 'approve', event_id: eventId, config: publicConfig(next) } });
+ }
+
+ if (action === 'deny') {
+ // Confirmed bad: keep the wallet frozen, record the verdict.
+ await setAnomalyStatus(eventId, { status: 'denied', userId: auth.userId });
+ return json(res, 200, { data: { frozen: getSpendLimits(meta).frozen, action: 'deny', event_id: eventId } });
+ }
+
+ if (action === 'mark_swept') {
+ // The owner used one-tap "sweep to safety" (a real audited withdraw, run
+ // against the standard withdraw endpoint). Record it on the flag; keep frozen.
+ await setAnomalyStatus(eventId, { status: 'denied', userId: auth.userId, swept: true });
+ return json(res, 200, { data: { action: 'mark_swept', event_id: eventId, swept: true } });
+ }
+
+ return error(res, 400, 'bad_request', 'action must be approve, deny, mark_swept, or unfreeze');
+}
+
+export default handleGuard;
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index b466522db..512ab3317 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -30,7 +30,14 @@ import {
validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,
getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent, recordCustodyEvent,
getDailySpendUsd, getTradeLimits, setTradeLimits, getDailySpendLamports,
+ setPolicyRules, getPolicyRules,
} from '../_lib/agent-trade-guards.js';
+// Natural-language spend policies — owner authors rules in English (compiler),
+// code enforces them deterministically (rules engine). Owner-only Policy surface.
+import {
+ describePolicyRules, backtestPolicy, syntheticProbes, normalizePolicyRules, MAX_RULES,
+} from '../_lib/spend-policy-rules.js';
+import { compilePolicyFromText } from '../_lib/spend-policy-compiler.js';
import { getBalances, walletUsdTotal } from '../_lib/balances.js';
import {
THREE_MINT, computeLook, computeMarks, normalizePrefs,
@@ -959,6 +966,29 @@ async function handleCustody(req, res, id) {
return json(res, 200, { data: { items, next_cursor: nextCursor } });
}
+// ── proof of custody ──────────────────────────────────────────────────────────
+// GET /api/agents/:id/solana/proof — owner-only inclusion proof for this wallet's
+// custody attestation. Returns the leaf's public fields, the Merkle path to the
+// anchored root, the on-chain anchor reference, and a movement reconciliation
+// against the custody ledger. The browser verifier (src/proof-of-custody) then
+// recomputes the leaf, walks the path, fetches the on-chain root, and confirms it
+// matches — never trusting this server's word for the verification.
+async function handleCustodyProof(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const owned = await loadOwnedWallet(req, res, id);
+ if (owned.error) return;
+ const { auth } = owned;
+
+ const rl = await limits.auditLogRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const { getInclusionProof } = await import('../_lib/custody-proof.js');
+ const proof = await getInclusionProof(id);
+ return json(res, 200, { data: proof });
+}
+
// ── spend limits ────────────────────────────────────────────────────────────
// GET/PUT /api/agents/:id/solana/limits — owner-only read + edit of the shared
// per-agent spend policy. Includes today's spend so the hub can show headroom.
@@ -1019,6 +1049,129 @@ async function handleLimits(req, res, id) {
return json(res, 200, { data: { limits: limitsOut, trade_limits: getTradeLimits(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
+// ── natural-language spend policy ─────────────────────────────────────────────
+// Owner-only. The owner writes safety rules in plain English; a real Claude call
+// COMPILES them to a deterministic rule document (api/_lib/spend-policy-rules.js)
+// that the shared guards enforce on every spend. The LLM only authors + explains —
+// it never decides a spend. All endpoints are ownership-gated via loadOwnedWallet.
+//
+// GET /policy current compiled policy + numbered plain-English readback
+// POST /policy {op:compile, text} compile English → rules + readback + live backtest
+// POST /policy {op:backtest, rules} replay a rule set against real custody history
+// PUT /policy {rules, english} save a validated policy (CSRF-gated, audited)
+async function handlePolicy(req, res, id) {
+ if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'PUT'])) return;
+
+ const owned = await loadOwnedWallet(req, res, id);
+ if (owned.error) return;
+ const { auth, meta } = owned;
+
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const spendLimits = getSpendLimits(meta);
+ const allowlist = Array.isArray(spendLimits.withdraw_allowlist) ? spendLimits.withdraw_allowlist : [];
+
+ // Real spend history for the backtest — the last 60 days of spend rows, capped.
+ // The same deterministic evaluator that runs in production scores these, so the
+ // preview is honest, not an approximation.
+ async function loadHistory() {
+ return sql`
+ SELECT id, event_type, category, network, asset, usd, destination, created_at, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network} AND event_type = 'spend'
+ AND created_at > now() - interval '60 days'
+ ORDER BY created_at DESC
+ LIMIT 1000
+ `;
+ }
+
+ if (req.method === 'GET') {
+ const policy = getPolicyRules(meta);
+ return json(res, 200, {
+ data: { policy, readback: describePolicyRules(policy), source_text: policy.source_text, numeric_limits: spendLimits },
+ });
+ }
+
+ if (req.method === 'POST') {
+ // compile + backtest are read-only previews (no mutation) — owner-gated above.
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const op = body?.op === 'backtest' ? 'backtest' : 'compile';
+
+ if (op === 'compile') {
+ const text = typeof body?.text === 'string' ? body.text : '';
+ const result = await compilePolicyFromText(text, { allowlist, track: { userId: auth.userId, agentId: id } });
+ if (!result.ok) {
+ return json(res, 200, { data: { ok: false, error: result.error, refusal: result.refusal || null, message: result.message, via: result.via || null } });
+ }
+ let backtest = null;
+ try {
+ backtest = backtestPolicy(result.policy, await loadHistory(), { allowlist });
+ } catch (e) {
+ console.warn('[policy] backtest failed', e?.message);
+ }
+ return json(res, 200, {
+ data: {
+ ok: true, via: result.via, policy: result.policy, readback: result.readback,
+ assumptions: result.assumptions, source_text: result.source_text,
+ backtest, synthetic: syntheticProbes(result.policy),
+ },
+ });
+ }
+
+ // backtest a supplied (or current) rule set against real history.
+ const policy = normalizePolicyRules({ rules: body?.rules, source_text: body?.english });
+ let backtest = null;
+ try {
+ backtest = backtestPolicy(policy, await loadHistory(), { allowlist });
+ } catch (e) {
+ console.warn('[policy] backtest failed', e?.message);
+ }
+ return json(res, 200, { data: { ok: true, policy, readback: describePolicyRules(policy), backtest, synthetic: syntheticProbes(policy) } });
+ }
+
+ // PUT — save a validated policy. Changing the wallet's safety rules requires CSRF.
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const rules = Array.isArray(body?.rules) ? body.rules : Array.isArray(body?.policy?.rules) ? body.policy.rules : [];
+ if (rules.length > MAX_RULES) {
+ return error(res, 422, 'too_many_rules', `A policy can have at most ${MAX_RULES} rules. Simplify it and try again.`);
+ }
+ const english = typeof body?.english === 'string' ? body.english : typeof body?.source_text === 'string' ? body.source_text : null;
+ let saved;
+ try {
+ saved = await setPolicyRules(id, auth.userId, rules, { english, req });
+ } catch (e) {
+ if (e?.status) return error(res, e.status, e.code || 'error', e.message);
+ throw e;
+ }
+ // The caller sent rules but none survived validation — refuse loudly rather than
+ // silently saving an empty (unprotective) policy.
+ if (!saved.rules.length && rules.length) {
+ return error(res, 422, 'invalid_policy', 'None of those rules could be validated as enforceable, so nothing was saved.');
+ }
+ let backtest = null;
+ try {
+ backtest = backtestPolicy(saved, await loadHistory(), { allowlist });
+ } catch (e) {
+ console.warn('[policy] post-save backtest failed', e?.message);
+ }
+ return json(res, 200, { data: { policy: saved, readback: describePolicyRules(saved), backtest } });
+}
+
// ── vanity grind + custodial swap ──────────────────────────────────────────────
// GET /api/agents/:id/solana/vanity — owner-only current vanity status.
// POST /api/agents/:id/solana/vanity — owner-only: grind a vanity keypair
@@ -2313,7 +2466,13 @@ export default async function handler(req, res, id, action) {
}
if (action === 'networth') return handleNetWorth(req, res, id);
if (action === 'custody') return handleCustody(req, res, id);
+ if (action === 'proof') return handleCustodyProof(req, res, id);
if (action === 'limits') return handleLimits(req, res, id);
+ if (action === 'guard') {
+ const mod = await import('./solana-guard.js');
+ return mod.handleGuard(req, res, id);
+ }
+ if (action === 'policy') return handlePolicy(req, res, id);
if (action === 'tip') return handleTip(req, res, id);
if (action === 'royalty') return handleRoyalty(req, res, id);
if (action === 'stream') return handleStream(req, res, id);
diff --git a/api/cron/custody-attest.js b/api/cron/custody-attest.js
new file mode 100644
index 000000000..850ab5711
--- /dev/null
+++ b/api/cron/custody-attest.js
@@ -0,0 +1,34 @@
+// GET/POST /api/cron/custody-attest — Verifiable Proof-of-Custody snapshot+anchor.
+//
+// Runs one attestation epoch: snapshots every custodial wallet's public state
+// (address, live on-chain balance, custody-ledger head), builds a Merkle tree,
+// persists the epoch + leaves, and commits the root on-chain as a signed SPL-Memo
+// (api/_lib/custody-proof.js). Owners then verify their own inclusion proof in the
+// browser against the on-chain root.
+//
+// Best-effort anchoring, like the other on-chain lanes: with no funded attester
+// key (ATTEST_AGENT_SECRET_KEY) the epoch is still recorded with anchor_status
+// 'pending'/'anchor_failed' and can be re-anchored later — the snapshot never
+// 500s on a missing key.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { runAttestationEpoch } from '../_lib/custody-proof.js';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const result = await runAttestationEpoch({ anchor: true });
+ return json(res, 200, { ok: true, ...result });
+});
diff --git a/api/custody/anchor.js b/api/custody/anchor.js
new file mode 100644
index 000000000..526b7bd9d
--- /dev/null
+++ b/api/custody/anchor.js
@@ -0,0 +1,31 @@
+// GET /api/custody/anchor?epoch=N — public anchor reference for one epoch: the
+// Merkle root, the on-chain anchor tx signature, and the network it was committed
+// on. Lets a verifier cross-check the root it computed against what the platform
+// recorded — though the authoritative check reads the root straight off-chain.
+//
+// Returns only public epoch metadata; no per-wallet leaves.
+
+import { cors, json, method, error, serverError } from '../_lib/http.js';
+import { getAnchorRef, getPublicIntegrity } from '../_lib/custody-proof.js';
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ try {
+ const url = new URL(req.url, 'http://x');
+ const epochRaw = url.searchParams.get('epoch');
+ let ref;
+ if (epochRaw == null || epochRaw === '' || epochRaw === 'latest') {
+ ref = (await getPublicIntegrity()).latest;
+ } else if (/^\d+$/.test(epochRaw)) {
+ ref = await getAnchorRef(epochRaw);
+ } else {
+ return error(res, 400, 'bad_request', 'epoch must be a positive integer or "latest"');
+ }
+ if (!ref) return error(res, 404, 'not_found', 'no such epoch');
+ res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');
+ return json(res, 200, { data: ref });
+ } catch (err) {
+ return serverError(res, 500, 'anchor_lookup_failed', err);
+ }
+}
diff --git a/api/custody/integrity.js b/api/custody/integrity.js
new file mode 100644
index 000000000..958c83046
--- /dev/null
+++ b/api/custody/integrity.js
@@ -0,0 +1,21 @@
+// GET /api/custody/integrity — public, no-auth aggregate for the Proof-of-Custody
+// integrity page. Returns the latest attestation epoch, its Merkle root, the
+// on-chain anchor tx, the wallet count, and aggregate SOL — never any per-wallet
+// private data. The public face of "our custody is provable".
+
+import { cors, json, method, serverError } from '../_lib/http.js';
+import { getPublicIntegrity } from '../_lib/custody-proof.js';
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ try {
+ const data = await getPublicIntegrity();
+ // Public aggregate — safe to CDN-cache briefly so the integrity page stays
+ // snappy without hammering the DB. New epochs land at most every few hours.
+ res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');
+ return json(res, 200, { data });
+ } catch (err) {
+ return serverError(res, 500, 'integrity_failed', err);
+ }
+}
diff --git a/api/og/agent.js b/api/og/agent.js
index 193ed0c95..0d42be492 100644
--- a/api/og/agent.js
+++ b/api/og/agent.js
@@ -1,36 +1,42 @@
/**
* GET /api/og/agent?id=<agentId>
*
- * Dynamic OG image for 3D AI Agent collectible pages.
- * SVG 1200×630. Shows agent name, avatar image (or initial fallback), and
- * on-chain badge when deployed — so every shared agent link previews with
- * real identity data.
+ * Dynamic OG image — the agent's wallet as a screenshot-worthy TRADING CARD.
+ * SVG 1200×630, rendered entirely from REAL data so a shared agent link unfurls
+ * with a card that matches the on-page one (src/shared/wallet-card.js):
*
- * Card anatomy (1200×630, dark):
- * top — three.ws wordmark + "3D AI Agent"
- * left — avatar image (300×300 circle) or gradient-initial
- * center — agent name (large), description (truncated)
- * right — on-chain badge (when deployed)
- * footer — "Build · Deploy · Trade · three.ws"
+ * - avatar portrait (or gradient-initial fallback)
+ * - agent name + vanity-highlighted custodial Solana address
+ * - live net worth (USD, from the same priced-balance path the wallet uses)
+ * - holdings count, realized P&L (when positive), lifetime tips
+ * - reputation tier badge (new…elite) + $THREE-holder mark
+ * - a "rarity finish" (Common…Mythic) that scales with the agent's REAL wealth
+ * and reputation tier — matte for a dormant new wallet, holo for a luminous one
+ *
+ * Every enrichment is best-effort and individually timeout-guarded: a slow or
+ * failed chain/reputation read degrades that one field (a "—" balance, no badge),
+ * never a broken unfurl. Private avatars never render a card (visibility re-checked
+ * server-side). Public/unlisted only. Cached sensibly.
*/
import { cors, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { env } from '../_lib/env.js';
import { isUuid } from '../_lib/validate.js';
+import { getBalances, walletUsdTotal } from '../_lib/balances.js';
+import { getAgentReputation } from '../_lib/trust/wallet-reputation.js';
+import { tierForUsd, NETWORTH_TIERS, THREE_MINT } from '../../src/shared/wallet-networth.js';
+
+const CACHE = 'public, max-age=180, s-maxage=900, stale-while-revalidate=120';
-const CACHE = 'public, max-age=300, s-maxage=3600, stale-while-revalidate=60';
+// Reputation tier → rank (0..4). Kept in sync with REP_RANK in wallet-card.js and
+// TIERS in agent-financial-reputation.js so the finish matches on page and image.
+const REP_RANK = { new: 0, emerging: 1, established: 2, trusted: 3, elite: 4 };
+const FINISH_LABELS = ['Common', 'Uncommon', 'Rare', 'Epic', 'Legendary', 'Mythic'];
-// Name-based gradient palette (same GRADIENTS array used in agent-detail.js)
const GRADIENTS = [
- ['#6366f1', '#8b5cf6'],
- ['#06b6d4', '#6366f1'],
- ['#10b981', '#06b6d4'],
- ['#f59e0b', '#ef4444'],
- ['#ec4899', '#8b5cf6'],
- ['#14b8a6', '#3b82f6'],
- ['#f97316', '#ec4899'],
- ['#8b5cf6', '#06b6d4'],
+ ['#6366f1', '#8b5cf6'], ['#06b6d4', '#6366f1'], ['#10b981', '#06b6d4'], ['#f59e0b', '#ef4444'],
+ ['#ec4899', '#8b5cf6'], ['#14b8a6', '#3b82f6'], ['#f97316', '#ec4899'], ['#8b5cf6', '#06b6d4'],
];
function gradientForName(name) {
const idx = (name || '').charCodeAt(0) % GRADIENTS.length;
@@ -47,11 +53,60 @@ function trunc(s, n) {
return s.length <= n ? s : s.slice(0, n - 1) + '…';
}
+// Race a best-effort enrichment against a deadline so one slow read never blocks
+// the unfurl. Resolves to `fallback` on timeout or any error.
+function withTimeout(promise, ms, fallback) {
+ return Promise.race([
+ Promise.resolve(promise).catch(() => fallback),
+ new Promise((resolve) => setTimeout(() => resolve(fallback), ms)),
+ ]);
+}
+
+// Compact USD, matching src/shared/wallet-format.formatWalletUsd so the image
+// number reads identically to the on-page card.
+function fmtUsd(n) {
+ if (n == null || !Number.isFinite(n)) return null;
+ if (n <= 0) return '$0';
+ if (n < 0.01) return '<$0.01';
+ if (n < 10) return `$${n.toFixed(2)}`;
+ if (n < 1000) return `$${Math.round(n)}`;
+ if (n < 1e6) return `$${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}K`;
+ if (n < 1e9) return `$${(n / 1e6).toFixed(1)}M`;
+ return `$${(n / 1e9).toFixed(1)}B`;
+}
+
+async function realizedPnlFor(id) {
+ try {
+ const [r] = await sql`
+ SELECT COALESCE(sum(realized_pnl_lamports), 0)::float8 AS lamports,
+ count(*) FILTER (WHERE realized_pnl_lamports > 0)::int AS wins
+ FROM agent_sniper_positions
+ WHERE agent_id = ${id} AND status = 'closed' AND realized_pnl_lamports IS NOT NULL
+ `;
+ return { sol: (Number(r?.lamports) || 0) / 1e9, wins: r?.wins || 0 };
+ } catch {
+ return { sol: 0, wins: 0 };
+ }
+}
+
+async function tipsCountFor(id) {
+ try {
+ const [agg] = await sql`
+ SELECT COUNT(*)::int AS n
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND event_type = 'tip' AND status = 'confirmed'
+ `;
+ return agg?.n ?? 0;
+ } catch {
+ return 0;
+ }
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
- const id = (url.searchParams.get('id') || '').trim();
+ const id = (url.searchParams.get('id') || '').trim();
if (!isUuid(id)) return fallback(res);
@@ -70,148 +125,174 @@ export default wrap(async (req, res) => {
}
if (!row) return fallback(res);
+ // Respect visibility — a private agent must never render a public card.
+ if (row.visibility === 'private') return fallback(res);
- const name = trunc(row.name || 'Agent', 32);
- const desc = trunc(row.description || '3D AI Agent on three.ws', 80);
- const isOnchain = Boolean(row.erc8004_agent_id) || Boolean(row.meta?.onchain);
+ const name = trunc(row.name || 'Agent', 30);
- // Wallet identity for the share card — the agent's real custodial address
- // (vanity-aware) plus lifetime tips, so a shared wallet link previews with a
- // stat worth screenshotting and a clear "pay me / fork me" hook. Public data
- // only; never a secret. Tolerates a tip-ledger read failure (omits the stat).
const solAddress = typeof row.meta?.solana_address === 'string' ? row.meta.solana_address : null;
const vanPrefix = row.meta?.solana_vanity_prefix || null;
const vanSuffix = row.meta?.solana_vanity_suffix || null;
- let tipsCount = 0;
- if (solAddress) {
- try {
- const [agg] = await sql`
- SELECT COUNT(*)::int AS n
- FROM agent_custody_events
- WHERE agent_id = ${id} AND event_type = 'tip' AND status = 'confirmed'
- `;
- tipsCount = agg?.n ?? 0;
- } catch { /* omit the tips stat, keep the card */ }
- }
+ const realPrefix = vanPrefix && solAddress?.startsWith(vanPrefix) ? vanPrefix : '';
+ const realSuffix = vanSuffix && solAddress?.endsWith(vanSuffix) ? vanSuffix : '';
+ const isVanity = Boolean(realPrefix || realSuffix);
const addrShort = solAddress
- ? `${vanPrefix && solAddress.startsWith(vanPrefix) ? vanPrefix : solAddress.slice(0, 4)}…${vanSuffix && solAddress.endsWith(vanSuffix) ? vanSuffix : solAddress.slice(-4)}`
+ ? `${realPrefix || solAddress.slice(0, 4)}…${realSuffix || solAddress.slice(-4)}`
: null;
- const isVanity = Boolean((vanPrefix && solAddress?.startsWith(vanPrefix)) || (vanSuffix && solAddress?.endsWith(vanSuffix)));
+
+ // ── Real enrichments, each timeout-guarded so the card always renders ──────
+ const [balances, rep, pnl, tipsCount] = await Promise.all([
+ solAddress ? withTimeout(getBalances({ chain: 'solana', address: solAddress }), 3000, null) : null,
+ withTimeout(getAgentReputation(id, { lite: true }), 3000, null),
+ withTimeout(realizedPnlFor(id), 2000, { sol: 0, wins: 0 }),
+ solAddress ? withTimeout(tipsCountFor(id), 1500, 0) : 0,
+ ]);
+
+ const usd = balances ? walletUsdTotal(balances) : 0;
+ const tokens = balances?.tokens || [];
+ const tokenCount = tokens.length;
+ const hasThree = tokens.some((t) => t.mint === THREE_MINT && (t.amount || 0) > 0);
+ const usdLabel = balances ? (fmtUsd(usd) ?? '$0') : '—';
+
+ const wealthTier = tierForUsd(usd);
+ const repRank = rep?.tier ? (REP_RANK[rep.tier] ?? 0) : 0;
+ const finishLevel = Math.max(
+ 0,
+ Math.min(5, Math.max(wealthTier.level, rep?.tier && repRank > 0 ? repRank + 1 : 0)),
+ );
+ const finishLabel = FINISH_LABELS[finishLevel];
+ const rim = rep?.accent || '#c4b5fd';
+ const holoOpacity = [0, 0, 0.12, 0.2, 0.3, 0.42][finishLevel];
+
+ const repLabel = rep?.tierLabel || null;
+ const repScore = rep && Number.isFinite(Number(rep.score)) ? Math.round(Number(rep.score)) : null;
const [c1, c2] = gradientForName(row.name);
const initial = (row.name || 'A')[0].toUpperCase();
- // Attempt to embed avatar image as base64
+ // Avatar embed (public/unlisted only) — same path as before.
let avatarData = null;
- const CDN_BASE = env.S3_PUBLIC_DOMAIN || 'https://three.ws/cdn';
- const thumbKey = row.thumbnail_key;
- const thumbVis = row.visibility;
- const thumbPublic = thumbVis === 'public' || thumbVis === 'unlisted';
-
- if (thumbKey && thumbPublic) {
- const imgUrl = `${CDN_BASE}/${thumbKey}`;
+ const CDN_BASE = env.S3_PUBLIC_DOMAIN || 'https://three.ws/cdn';
+ const thumbPublic = row.visibility === 'public' || row.visibility === 'unlisted';
+ if (row.thumbnail_key && thumbPublic) {
try {
- const imgResp = await fetch(imgUrl, { signal: AbortSignal.timeout(3000) });
+ const imgResp = await fetch(`${CDN_BASE}/${row.thumbnail_key}`, { signal: AbortSignal.timeout(3000) });
if (imgResp.ok) {
- // Cap the inlined avatar so a large/corrupt thumbnail can't bloat the
- // SVG (and this function's memory). Thumbnails are small JPEGs/PNGs.
- const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
+ const MAX = 2 * 1024 * 1024;
const declared = Number(imgResp.headers.get('content-length') || 0);
- if (!declared || declared <= MAX_AVATAR_BYTES) {
+ if (!declared || declared <= MAX) {
const ct = imgResp.headers.get('content-type') || 'image/jpeg';
const ab = await imgResp.arrayBuffer();
- if (ab.byteLength <= MAX_AVATAR_BYTES) {
- const b64 = Buffer.from(ab).toString('base64');
- avatarData = { ct, b64 };
- }
+ if (ab.byteLength <= MAX) avatarData = { ct, b64: Buffer.from(ab).toString('base64') };
}
}
- } catch { /* non-fatal — use gradient fallback */ }
+ } catch { /* gradient fallback */ }
}
- const AV_CX = 200, AV_CY = 315, AV_R = 140;
+ const AV_CX = 215, AV_CY = 300, AV_R = 150;
+
+ // Build the right-column stat chips from real, public-safe aggregates.
+ const stats = [];
+ stats.push({ label: 'HOLDINGS', val: tokenCount === 0 ? '—' : String(tokenCount), accent: false });
+ if (pnl.sol > 0) stats.push({ label: 'REALIZED P&L', val: `+${pnl.sol.toFixed(pnl.sol < 1 ? 3 : 2)} ◎`, accent: true });
+ else if (tipsCount > 0) stats.push({ label: 'TIPS', val: String(tipsCount), accent: false });
+ else stats.push({ label: 'WEALTH TIER', val: wealthTier.label, accent: false });
+ if (repScore != null) stats.push({ label: 'REPUTATION', val: `${repScore}`, accent: false });
+ else stats.push({ label: 'STATUS', val: balances ? 'Live' : 'New', accent: false });
+
+ const STAT_X = 440, STAT_Y = 470, STAT_W = 232, STAT_GAP = 12;
+ const statsSvg = stats.slice(0, 3).map((s, i) => {
+ const sx = STAT_X + i * (STAT_W + STAT_GAP);
+ const fill = s.accent ? 'rgba(74,222,128,.1)' : 'rgba(255,255,255,.04)';
+ const stroke = s.accent ? 'rgba(74,222,128,.3)' : 'rgba(255,255,255,.08)';
+ const valFill = s.accent ? '#86efac' : '#ece9f8';
+ return `<rect x="${sx}" y="${STAT_Y}" width="${STAT_W}" height="72" rx="14" fill="${fill}" stroke="${stroke}" stroke-width="1"/>
+ <text x="${sx + 18}" y="${STAT_Y + 34}" font-family="Inter,system-ui,sans-serif" font-size="26" font-weight="800" fill="${valFill}">${x(s.val)}</text>
+ <text x="${sx + 18}" y="${STAT_Y + 56}" font-family="Inter,system-ui,sans-serif" font-size="11" font-weight="700" letter-spacing=".1em" fill="#6f6889">${x(s.label)}</text>`;
+ }).join('\n');
+
+ // Badge row (reputation tier + $THREE mark), placed under the name.
+ const badges = [];
+ if (repLabel) badges.push({ text: repLabel.toUpperCase(), color: rim, bg: true });
+ if (hasThree) badges.push({ text: '◆ $THREE', color: '#fbbf24', bg: true });
+ let badgeX = 440;
+ const badgesSvg = badges.map((b) => {
+ const w = 26 + b.text.length * 9.4;
+ const seg = `<rect x="${badgeX}" y="208" width="${w}" height="30" rx="15" fill="${b.color}22" stroke="${b.color}66" stroke-width="1"/>
+ <text x="${badgeX + 14}" y="228" font-family="Inter,system-ui,sans-serif" font-size="12" font-weight="800" letter-spacing=".06em" fill="${b.color}">${x(b.text)}</text>`;
+ badgeX += w + 10;
+ return seg;
+ }).join('\n');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="1200" height="630" viewBox="0 0 1200 630">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
- <stop offset="0" stop-color="#050508"/>
- <stop offset="1" stop-color="#0d0d14"/>
+ <stop offset="0" stop-color="#0b0a11"/>
+ <stop offset="1" stop-color="#06060a"/>
</linearGradient>
+ <radialGradient id="rimGlow" cx="20%" cy="0%" r="80%">
+ <stop offset="0" stop-color="${x(rim)}" stop-opacity=".22"/>
+ <stop offset="1" stop-color="${x(rim)}" stop-opacity="0"/>
+ </radialGradient>
<radialGradient id="avGlow" cx="50%" cy="50%" r="50%">
- <stop offset="0" stop-color="${x(c1)}" stop-opacity=".35"/>
+ <stop offset="0" stop-color="${x(c1)}" stop-opacity=".4"/>
<stop offset="1" stop-color="${x(c1)}" stop-opacity="0"/>
</radialGradient>
<linearGradient id="avGrad" x1="0" y1="0" x2="1" y2="1">
- <stop offset="0" stop-color="${x(c1)}"/>
- <stop offset="1" stop-color="${x(c2)}"/>
+ <stop offset="0" stop-color="${x(c1)}"/><stop offset="1" stop-color="${x(c2)}"/>
+ </linearGradient>
+ <linearGradient id="holo" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0.30" stop-color="#7c6cb0" stop-opacity="0"/>
+ <stop offset="0.45" stop-color="#7c6cb0" stop-opacity="1"/>
+ <stop offset="0.52" stop-color="#60a5fa" stop-opacity="1"/>
+ <stop offset="0.60" stop-color="#ec72b6" stop-opacity="1"/>
+ <stop offset="0.72" stop-color="#ec72b6" stop-opacity="0"/>
</linearGradient>
${avatarData ? `<clipPath id="avClip"><circle cx="${AV_CX}" cy="${AV_CY}" r="${AV_R}"/></clipPath>` : ''}
</defs>
- <!-- background -->
<rect width="1200" height="630" fill="url(#bg)"/>
- <rect x="0" y="0" width="4" height="630" fill="${x(c1)}" opacity=".7"/>
+ <rect width="1200" height="630" fill="url(#rimGlow)"/>
+ ${holoOpacity > 0 ? `<rect width="1200" height="630" fill="url(#holo)" opacity="${holoOpacity}"/>` : ''}
+ <rect x="8" y="8" width="1184" height="614" rx="22" fill="none" stroke="${x(rim)}" stroke-width="2" opacity=".4"/>
- <!-- avatar glow -->
- <ellipse cx="${AV_CX}" cy="${AV_CY}" rx="200" ry="200" fill="url(#avGlow)" opacity=".6"/>
-
- <!-- avatar circle -->
+ <!-- avatar -->
+ <ellipse cx="${AV_CX}" cy="${AV_CY}" rx="210" ry="210" fill="url(#avGlow)" opacity=".7"/>
${avatarData
- ? `<image href="data:${avatarData.ct};base64,${avatarData.b64}"
- x="${AV_CX - AV_R}" y="${AV_CY - AV_R}" width="${AV_R * 2}" height="${AV_R * 2}"
- clip-path="url(#avClip)" preserveAspectRatio="xMidYMid slice"/>`
+ ? `<image href="data:${avatarData.ct};base64,${avatarData.b64}" x="${AV_CX - AV_R}" y="${AV_CY - AV_R}" width="${AV_R * 2}" height="${AV_R * 2}" clip-path="url(#avClip)" preserveAspectRatio="xMidYMid slice"/>`
: `<circle cx="${AV_CX}" cy="${AV_CY}" r="${AV_R}" fill="url(#avGrad)" opacity=".9"/>
- <text x="${AV_CX}" y="${AV_CY + 18}" text-anchor="middle" dominant-baseline="middle"
- font-family="Inter,system-ui,sans-serif" font-size="96" font-weight="800"
- fill="rgba(255,255,255,.9)">${x(initial)}</text>`}
- <circle cx="${AV_CX}" cy="${AV_CY}" r="${AV_R}" fill="none" stroke="${x(c1)}" stroke-width="2" opacity=".4"/>
+ <text x="${AV_CX}" y="${AV_CY + 20}" text-anchor="middle" dominant-baseline="middle" font-family="Inter,system-ui,sans-serif" font-size="104" font-weight="800" fill="rgba(255,255,255,.92)">${x(initial)}</text>`}
+ <circle cx="${AV_CX}" cy="${AV_CY}" r="${AV_R}" fill="none" stroke="${x(rim)}" stroke-width="2.5" opacity=".55"/>
<!-- top bar -->
- <text x="440" y="34" font-family="Inter,system-ui,sans-serif" font-size="12" font-weight="600"
- letter-spacing=".12em" fill="#4b5563">THREE.WS</text>
- <text x="1176" y="34" font-family="Inter,system-ui,sans-serif" font-size="12"
- fill="#4b5563" text-anchor="end">3D AI Agent</text>
-
- <line x1="440" y1="48" x2="1176" y2="48" stroke="#1f2937" stroke-width="1"/>
+ <text x="440" y="40" font-family="Inter,system-ui,sans-serif" font-size="13" font-weight="700" letter-spacing=".14em" fill="#5b5470">THREE.WS · WALLET CARD</text>
+ <rect x="1010" y="22" width="166" height="30" rx="15" fill="${x(rim)}1c" stroke="${x(rim)}55" stroke-width="1"/>
+ <text x="1093" y="42" text-anchor="middle" font-family="Inter,system-ui,sans-serif" font-size="12" font-weight="800" letter-spacing=".14em" fill="${x(rim)}">${x(finishLabel.toUpperCase())}</text>
+ <line x1="440" y1="58" x2="1176" y2="58" stroke="#211d2e" stroke-width="1"/>
- <!-- agent name -->
- <text x="440" y="130" font-family="Inter,system-ui,sans-serif" font-size="${name.length > 20 ? 42 : 52}" font-weight="800"
- fill="#f9fafb">${x(name)}</text>
+ <!-- name -->
+ <text x="440" y="128" font-family="Inter,system-ui,sans-serif" font-size="${name.length > 18 ? 46 : 56}" font-weight="800" fill="#f5f3ff">${x(name)}</text>
- <!-- description -->
- ${desc ? `<text x="440" y="178" font-family="Inter,system-ui,sans-serif" font-size="17" fill="#6b7280">${x(desc)}</text>` : ''}
+ <!-- vanity address -->
+ ${addrShort ? `
+ <text x="440" y="176" font-family="ui-monospace,'JetBrains Mono',Menlo,monospace" font-size="28" font-weight="700" fill="${isVanity ? '#e9d5ff' : '#a8a0c4'}">${isVanity ? '✦ ' : ''}${x(addrShort)}</text>
+ ` : `<text x="440" y="176" font-family="Inter,system-ui,sans-serif" font-size="20" fill="#6b6485">Wallet provisioning…</text>`}
- <!-- on-chain badge -->
- ${isOnchain ? `<rect x="440" y="208" width="140" height="28" rx="14" fill="rgba(16,185,129,.1)" stroke="rgba(16,185,129,.4)" stroke-width="1"/>
- <text x="460" y="227" font-family="Inter,system-ui,sans-serif" font-size="11" font-weight="600"
- letter-spacing=".08em" fill="#10b981">◈ ON-CHAIN</text>` : ''}
+ <!-- badges -->
+ ${badgesSvg}
- <!-- skills / description panels -->
- <line x1="440" y1="260" x2="1176" y2="260" stroke="#1f2937" stroke-width="1"/>
+ <!-- net worth hero -->
+ <text x="440" y="360" font-family="Inter,system-ui,sans-serif" font-size="84" font-weight="800" letter-spacing="-.02em" fill="#ffffff">${x(usdLabel)}</text>
+ <text x="440" y="404" font-family="Inter,system-ui,sans-serif" font-size="15" font-weight="700" letter-spacing=".12em" fill="#7c7596">${x(wealthTier.label.toUpperCase())} · NET WORTH</text>
- <!-- wallet identity strip (vanity address + lifetime tips) -->
- ${addrShort ? `
- <text x="440" y="296" font-family="Inter,system-ui,sans-serif" font-size="11" font-weight="600"
- letter-spacing=".1em" fill="#7c6bb0">${isVanity ? '✦ VANITY WALLET' : 'AGENT WALLET'}</text>
- <text x="440" y="330" font-family="ui-monospace,'JetBrains Mono',Menlo,monospace" font-size="26" font-weight="700"
- fill="#c4b5fd">${x(addrShort)}</text>
- ${tipsCount > 0 ? `
- <rect x="440" y="350" width="${88 + String(tipsCount).length * 14}" height="32" rx="16" fill="rgba(139,92,246,.12)" stroke="rgba(139,92,246,.4)" stroke-width="1"/>
- <text x="458" y="371" font-family="Inter,system-ui,sans-serif" font-size="14" font-weight="700" fill="#c4b5fd">◎ ${tipsCount} tip${tipsCount === 1 ? '' : 's'} received</text>`
- : `<text x="440" y="372" font-family="Inter,system-ui,sans-serif" font-size="14" fill="#6b7280">Tip it · fork it · own its wallet on three.ws</text>`}
- ` : `
- <!-- proof tagline -->
- <text x="440" y="300" font-family="Inter,system-ui,sans-serif" font-size="15" fill="#374151">
- Build · Deploy · Trade · three.ws
- </text>`}
+ <!-- stat chips -->
+ ${statsSvg}
<!-- footer -->
- <rect x="0" y="594" width="1200" height="36" fill="#030305"/>
- <text x="24" y="618" font-family="Inter,system-ui,sans-serif" font-size="12" fill="#374151"
- letter-spacing=".08em">3D AI AGENT COLLECTIBLE</text>
- <text x="1176" y="618" font-family="Inter,system-ui,sans-serif" font-size="12" fill="#374151"
- text-anchor="end">three.ws/agent/${x(id)}</text>
+ <rect x="0" y="588" width="1200" height="42" fill="#040408"/>
+ <text x="440" y="615" font-family="Inter,system-ui,sans-serif" font-size="13" font-weight="600" fill="#5b5470">Tip it · Fork it · own its wallet</text>
+ <text x="1176" y="615" font-family="Inter,system-ui,sans-serif" font-size="13" fill="#5b5470" text-anchor="end">three.ws/agent/${x(id)}</text>
</svg>`;
res.statusCode = 200;
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 34a6cf0a9..7243f644d 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -568,6 +568,16 @@
<div class="ad-services" id="ad-services"></div>
</section>
+ <section class="ad-card" id="ad-trading-card-section" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet"></span>
+ <h2>TRADING CARD</h2>
+ <span class="ad-card-link" id="ad-trading-card-share" role="button" tabindex="0"
+ style="margin-left:auto;font-size:.7rem;color:var(--ink-dim,#888);cursor:pointer">Share card →</span>
+ </div>
+ <div id="ad-trading-card-mount"></div>
+ </section>
+
<section class="ad-card">
<div class="ad-card-head">
<span class="ad-bullet"></span>
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index 1d000f60f..d01e89a2c 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -1203,6 +1203,7 @@
<div class="edit-sidebar-group-title">Brain</div>
<button class="edit-tab" data-tab="brain" role="tab" aria-selected="false" aria-controls="panel-brain" id="tab-brain">Brain Studio</button>
<button class="edit-tab" data-tab="knowledge" role="tab" aria-selected="false" aria-controls="panel-knowledge" id="tab-knowledge">Knowledge</button>
+ <button class="edit-tab" data-tab="mind" role="tab" aria-selected="false" aria-controls="panel-mind" id="tab-mind">Mind Palace</button>
<button class="edit-tab" data-tab="ownership" role="tab" aria-selected="false" aria-controls="panel-ownership" id="tab-ownership">Ownership</button>
<button class="edit-tab" data-tab="dreams" role="tab" aria-selected="false" aria-controls="panel-dreams" id="tab-dreams">Dreams<span class="tab-badge" id="dreams-tab-badge" hidden aria-hidden="true">0</span></button>
<button class="edit-tab" data-tab="skills" role="tab" aria-selected="false" aria-controls="panel-skills" id="tab-skills">Skills</button>
@@ -1612,6 +1613,14 @@
</div>
</section>
+ <!-- Mind Palace tab -->
+ <section class="edit-panel" id="panel-mind" role="tabpanel" aria-labelledby="tab-mind" hidden>
+ <div class="mind-tab-intro">
+ <p class="hint" style="margin:0 0 .75rem">Walk through your agent's mind. Every memory is an object you can see, search, and shape — drag one to the centre to pin it, flick it into the well to forget. <a href="#" id="mind-fullscreen-link" target="_blank" rel="noopener" style="color:#9ad0ff">Open full-screen ↗</a></p>
+ </div>
+ <div id="mind-palace-host" style="position:relative;width:100%;height:min(640px,72vh);min-height:440px"></div>
+ </section>
+
<!-- Dreams tab -->
<section class="edit-panel persona-panel" id="panel-dreams" role="tabpanel" aria-labelledby="tab-dreams" hidden>
<div class="dreams-head">
diff --git a/pages/agent-mind.html b/pages/agent-mind.html
new file mode 100644
index 000000000..4a8237425
--- /dev/null
+++ b/pages/agent-mind.html
@@ -0,0 +1,60 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <title>Mind Palace — three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#06080f" />
+ <meta name="description" content="Walk through your agent's mind — every memory as a tangible object you can see, search, pin, and forget." />
+
+ <meta property="og:type" content="website">
+ <meta property="og:url" content="https://three.ws/agent/mind">
+ <meta property="og:title" content="The Mind Palace — three.ws">
+ <meta property="og:description" content="Your agent's memory, rendered as a place you can explore.">
+ <meta property="og:image" content="https://three.ws/og-image.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ body { overflow: hidden; display: flex; flex-direction: column; min-height: 100vh; background: #04050a; }
+ .mind-page-header {
+ display: flex; align-items: center; gap: 1rem;
+ padding: 0.7rem 1.1rem; border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ flex: none; z-index: 20; background: rgba(6, 8, 15, 0.9); backdrop-filter: blur(10px);
+ }
+ .mind-page-header .back {
+ display: inline-flex; align-items: center; gap: 0.45rem; color: rgba(255, 255, 255, 0.7);
+ text-decoration: none; font-size: 0.82rem; font-weight: 600; padding: 0.35rem 0.6rem; border-radius: 8px;
+ }
+ .mind-page-header .back:hover { color: #fff; background: rgba(255, 255, 255, 0.07); }
+ .mind-page-header h1 { font-size: 0.98rem; margin: 0; font-weight: 650; color: #eef2fa; }
+ .mind-page-header .sub { font-size: 0.72rem; color: rgba(255, 255, 255, 0.45); margin-left: auto; }
+ #mind-root { flex: 1; min-height: 0; position: relative; }
+ .mind-boot { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: rgba(255, 255, 255, 0.6); font: 500 0.9rem system-ui, sans-serif; }
+ .mind-signin { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1rem; text-align: center; padding: 2rem; color: #e8edf7; font-family: system-ui, sans-serif; }
+ .mind-signin a { display: inline-flex; align-items: center; gap: 0.5rem; border-radius: 10px; padding: 0.6rem 1.1rem; font-weight: 650; text-decoration: none; background: linear-gradient(135deg, #7aa2ff, #9d7aff); color: #06080f; }
+ </style>
+ </head>
+ <body>
+ <script src="/nav.js"></script>
+ <header class="mind-page-header">
+ <a class="back" id="mind-back" href="/agents"><span aria-hidden="true">←</span> Back</a>
+ <h1 id="mind-title">Mind Palace</h1>
+ <span class="sub">Living Agents · memory you can walk through</span>
+ </header>
+ <main id="mind-root">
+ <div class="mind-boot" id="mind-boot">Entering the mind…</div>
+ </main>
+ <script type="module" src="/src/agent-mind.js"></script>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/prompts/nvidia/0.md b/prompts/nvidia/0.md
new file mode 100644
index 000000000..b852f9f41
--- /dev/null
+++ b/prompts/nvidia/0.md
@@ -0,0 +1,142 @@
+# 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.md
new file mode 100644
index 000000000..ea72842b0
--- /dev/null
+++ b/prompts/nvidia/1.md
@@ -0,0 +1,88 @@
+# 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.md
new file mode 100644
index 000000000..3d2007c72
--- /dev/null
+++ b/prompts/nvidia/2.md
@@ -0,0 +1,81 @@
+# 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.md
new file mode 100644
index 000000000..6b0b5aba6
--- /dev/null
+++ b/prompts/nvidia/3.md
@@ -0,0 +1,84 @@
+# 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.md
new file mode 100644
index 000000000..f91164ad5
--- /dev/null
+++ b/prompts/nvidia/4.md
@@ -0,0 +1,83 @@
+# 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.md
new file mode 100644
index 000000000..42cd43313
--- /dev/null
+++ b/prompts/nvidia/5.md
@@ -0,0 +1,82 @@
+# 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.md
new file mode 100644
index 000000000..c955f7589
--- /dev/null
+++ b/prompts/nvidia/6.md
@@ -0,0 +1,76 @@
+# 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.md
new file mode 100644
index 000000000..ac27e440e
--- /dev/null
+++ b/prompts/nvidia/7.md
@@ -0,0 +1,86 @@
+# 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.md
new file mode 100644
index 000000000..e21148cbc
--- /dev/null
+++ b/prompts/nvidia/8.md
@@ -0,0 +1,84 @@
+# 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.md
new file mode 100644
index 000000000..fef71f53d
--- /dev/null
+++ b/prompts/nvidia/9.md
@@ -0,0 +1,78 @@
+# 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/src/agent-detail.js b/src/agent-detail.js
index 23a161068..c2a995555 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -25,6 +25,7 @@ import { renderError as renderAsyncError } from './shared/async-state.js';
import { skeletonHTML } from './shared/state-kit.js';
import { openCoinLaunch } from './shared/agent-coin.js';
import { showSharePanel } from './shared/share.js';
+import { mountWalletCard } from './shared/wallet-card.js';
import { enrichAgentDetail, renderEmbed as renderAgentEmbed } from './agent-detail-market.js';
import { log } from './shared/log.js';
import { track, trackError, ANALYTICS_EVENTS } from './analytics.js';
@@ -42,6 +43,7 @@ let _pulseHandle = null;
let _mirrorHandle = null;
let _streamHandle = null;
let _strategyHandle = null;
+let _cardHandle = null;
let _patronageHandle = null;
// The hero's wallet aura controller — torn down on re-render/unload so its live
@@ -877,6 +879,50 @@ function render(agent) {
}
$('ad-holdings-sol').textContent = String(agent.solBalance ?? 0);
+ // Wallet trading card — the agent's living, screenshot-worthy identity object:
+ // avatar, vanity address, live net worth, holdings, P&L, reputation tier, and a
+ // tip/fork/share CTA. Rendered only when the agent has a custodial wallet, from
+ // the same public, server-authoritative reads every wallet surface uses. The
+ // card's image twin (api/og/agent.js) is what a shared link unfurls as.
+ {
+ const cardSection = $('ad-trading-card-section');
+ const cardMount = $('ad-trading-card-mount');
+ const wMeta = agent.rawMetadata?.meta || {};
+ if (_cardHandle) { try { _cardHandle.destroy(); } catch { /* idempotent */ } _cardHandle = null; }
+ if (cardSection && cardMount && wMeta.solana_address) {
+ cardSection.hidden = false;
+ _cardHandle = mountWalletCard(cardMount, {
+ id: agent.id,
+ name: agent.name,
+ solana_address: wMeta.solana_address,
+ avatar_thumbnail_url: agent.avatar || '',
+ solana_vanity_prefix: wMeta.solana_vanity_prefix || null,
+ solana_vanity_suffix: wMeta.solana_vanity_suffix || null,
+ meta: wMeta,
+ }, { isOwner: !!agent.isOwner, network: 'mainnet' });
+
+ const shareTrigger = $('ad-trading-card-share');
+ if (shareTrigger && !shareTrigger._wired) {
+ shareTrigger._wired = true;
+ const openShare = () => showSharePanel({
+ kind: 'agent',
+ id: agent.id,
+ title: agent.name || 'Agent',
+ description: agent.description || '',
+ shareUrl: `${location.origin}/agent/${agent.id}/share`,
+ remixUrl: `${location.origin}/agents/${agent.id}`,
+ previewImage: `${location.origin}/api/og/agent?id=${encodeURIComponent(agent.id)}`,
+ }, shareTrigger);
+ shareTrigger.addEventListener('click', openShare);
+ shareTrigger.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openShare(); }
+ });
+ }
+ } else if (cardSection) {
+ cardSection.hidden = true;
+ }
+ }
+
// Money Stream — pay-per-second income. A visitor gets the live meter (set a
// rate, sign a cap, watch the agent earn while they're here); the owner gets the
// live "earning now" + lifetime streaming earnings view. Mounted only when the
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 5bb63d373..691b0fb04 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -3041,6 +3041,28 @@ async function ensureOwnershipTab() {
}
}
+// Mind Palace — the agent's memory as a navigable spatial scene with the live
+// avatar at its core. Mounts the same module the standalone /agent/:id/mind
+// route uses; the empty state can ask the editor to jump to the Knowledge tab.
+let mindMounted = false;
+let mindController = null;
+async function ensureMindTab() {
+ const link = $('mind-fullscreen-link');
+ if (link && agentId) link.href = `/agent/${agentId}/mind`;
+ if (mindMounted || !agentId) return;
+ mindMounted = true;
+ const host = $('mind-palace-host');
+ if (!host) return;
+ host.addEventListener('mind:add-memory', () => activateTab('knowledge'));
+ try {
+ const { mountMindPalace } = await import('./mind-palace.js');
+ mindController = mountMindPalace(host, { agentId, agent: agentData, embedded: true });
+ } catch (err) {
+ mindMounted = false;
+ host.innerHTML = `<div class="error-msg" style="padding:1rem">Could not load the Mind Palace: ${escapeHtml(err.message)}</div>`;
+ }
+}
+
// Memory-grounded Autopilot — explainable autonomy. The strategy textarea above
// stays; this mounts the scopes / proposals / trust / signed-receipts surface.
let autopilotMounted = false;
@@ -3057,6 +3079,7 @@ const TAB_LOADERS = {
outfit: ensureOutfitTab,
voice: ensureVoiceTab,
knowledge: ensureKnowledgeTab,
+ mind: ensureMindTab,
ownership: ensureOwnershipTab,
dreams: ensureDreamsTab,
autopilot: ensureAutopilotTab,
diff --git a/src/agent-mind.js b/src/agent-mind.js
new file mode 100644
index 000000000..a5a1baebc
--- /dev/null
+++ b/src/agent-mind.js
@@ -0,0 +1,67 @@
+// Standalone Mind Palace route — /agent/:id/mind.
+//
+// Resolves the agent from the URL, wires the header, and mounts the same
+// mountMindPalace() surface the editor's Mind tab uses. The Palace itself owns
+// all loading/empty/error states; this entry only handles route resolution and
+// the page chrome.
+
+import { apiFetch } from './api.js';
+import { setActiveAgent } from './agents/active-agent.js';
+import { mountMindPalace } from './mind-palace.js';
+
+const root = document.getElementById('mind-root');
+const boot = document.getElementById('mind-boot');
+const titleEl = document.getElementById('mind-title');
+const backEl = document.getElementById('mind-back');
+
+function agentIdFromPath() {
+ // /agent/:id/mind (also tolerate a trailing slash or ?id= override)
+ const m = location.pathname.match(/^\/agent\/([^/]+)\/mind\/?$/);
+ if (m) return decodeURIComponent(m[1]);
+ const q = new URLSearchParams(location.search).get('id') || new URLSearchParams(location.search).get('agentId');
+ return q || null;
+}
+
+async function resolveAgent(id) {
+ try {
+ const r = await apiFetch(`/api/agents/${encodeURIComponent(id)}`, { credentials: 'include', allowAnonymous: true });
+ if (!r.ok) return null;
+ const j = await r.json().catch(() => ({}));
+ return j.agent || null;
+ } catch {
+ return null;
+ }
+}
+
+function showError(msg) {
+ if (boot) {
+ boot.innerHTML = `<div style="max-width:420px;text-align:center;line-height:1.5">${msg}</div>`;
+ boot.hidden = false;
+ }
+}
+
+async function init() {
+ const id = agentIdFromPath();
+ if (!id) {
+ showError(`No agent specified. Open this page from your agent's editor, or pick one from <a style="color:#9ad0ff" href="/agents">your agents ↗</a>.`);
+ return;
+ }
+ const agent = await resolveAgent(id);
+ if (!agent) {
+ showError(`We couldn't find this agent, or it isn't yours to explore. <a style="color:#9ad0ff" href="/agents">See your agents ↗</a>`);
+ return;
+ }
+ const name = agent.name || 'Your agent';
+ titleEl.textContent = `${name} · Mind Palace`;
+ document.title = `${name}'s Mind — three.ws`;
+ if (backEl) backEl.href = `/agent/${agent.id}/edit`;
+ // Make this the active agent so the site-wide companion + HUD follow it.
+ setActiveAgent(agent.id).catch(() => {});
+
+ if (boot) boot.remove();
+ const controller = mountMindPalace(root, { agentId: agent.id, agent, embedded: false });
+ // Clean teardown if the SPA ever navigates away without a full reload.
+ window.addEventListener('pagehide', () => controller.destroy(), { once: true });
+}
+
+init();
diff --git a/src/agent-wallet-hub/tabs/proof.js b/src/agent-wallet-hub/tabs/proof.js
new file mode 100644
index 000000000..c442cf626
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/proof.js
@@ -0,0 +1,167 @@
+/**
+ * Agent Wallet hub — Proof of Custody tab (owner-only).
+ *
+ * Radical, verifiable transparency: the platform periodically anchors a Merkle
+ * root over every custodial wallet's state on-chain. This tab shows the owner
+ * their inclusion proof and lets them VERIFY it themselves — the verification
+ * runs entirely in their browser (src/proof-of-custody/verifier.js): it
+ * recomputes the leaf, walks the Merkle path, fetches the anchor straight off a
+ * public Solana RPC, and confirms the on-chain root matches. It never trusts our
+ * server for the answer, and it fails honestly (red, with the failing step) when
+ * anything doesn't reconcile.
+ *
+ * Movement transparency is first-class: the reconciliation maps every balance
+ * change since the previous epoch to an authorized, logged custody event, and
+ * loudly flags any outflow the ledger can't explain.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { apiFetch } from '../../api.js';
+import { verifyInclusionProof } from '../../proof-of-custody/verifier.js';
+import { renderProofUI } from '../../proof-of-custody/ui.js';
+
+const STYLE_ID = 'awh-proof-style';
+
+registerWalletTab({
+ id: 'proof',
+ label: 'Proof of Custody',
+ order: 70,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ let destroyed = false;
+
+ async function load() {
+ panel.innerHTML = skeleton();
+ let proof;
+ try {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(ctx.agentId)}/solana/proof`, {
+ allowAnonymous: true,
+ });
+ if (res.status === 401) { panel.innerHTML = signedOut(); return; }
+ if (!res.ok) throw new Error(`proof request failed (${res.status})`);
+ proof = (await res.json())?.data;
+ } catch (err) {
+ if (destroyed) return;
+ panel.innerHTML = errorState(err.message);
+ panel.querySelector('[data-retry]')?.addEventListener('click', load);
+ return;
+ }
+ if (destroyed) return;
+ renderProofUI(panel, {
+ proof,
+ ctx,
+ verify: verifyInclusionProof,
+ shareBase: '/proof',
+ origin: location.origin,
+ });
+ }
+
+ load();
+ return { destroy() { destroyed = true; } };
+ },
+});
+
+function skeleton() {
+ return `<div class="awh-proof awh-proof-skel" aria-busy="true">
+ <span style="height:64px"></span>
+ <span style="height:120px"></span>
+ <span style="height:90px"></span>
+ </div>`;
+}
+
+function signedOut() {
+ return `<div class="awh-proof"><div class="awh-proof-card">
+ <h2>Sign in to view your proof</h2>
+ <p class="awh-proof-lead">Custody proofs are private to the wallet owner. Sign in to verify this wallet's custody on-chain.</p>
+ <a class="awh-proof-btn" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a>
+ </div></div>`;
+}
+
+function errorState(msg) {
+ return `<div class="awh-proof"><div class="awh-proof-card awh-proof-bad">
+ <h2>Couldn't load your proof</h2>
+ <p class="awh-proof-lead">${escapeHtml(msg)}</p>
+ <button class="awh-proof-btn" data-retry type="button">Try again</button>
+ </div></div>`;
+}
+
+function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function injectStyle() {
+ if (document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = PROOF_STYLE;
+ document.head.appendChild(tag);
+}
+
+// Shared styling for the proof UI, used by both the hub tab and the standalone
+// /proof page (which imports renderProofUI from ../proof-of-custody/ui.js).
+export const PROOF_STYLE = `
+.awh-proof { display: flex; flex-direction: column; gap: var(--space-4,16px); }
+.awh-proof-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); background: var(--surface-1, rgba(255,255,255,.03)); padding: var(--space-4,16px); }
+.awh-proof-card h2 { margin: 0 0 6px; font-size: var(--text-md,.9rem); color: var(--ink-bright,#fff); font-family: var(--font-display, system-ui); font-weight: 600; }
+.awh-proof-lead { color: var(--ink-dim,#888); font-size: var(--text-sm,.8125rem); line-height: 1.55; margin: 0 0 4px; max-width: 64ch; }
+.awh-proof-hero { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; border-radius: var(--radius-lg,14px); padding: var(--space-4,16px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); transition: border-color var(--duration-base,220ms), background var(--duration-base,220ms); }
+.awh-proof-hero.is-verified { border-color: color-mix(in srgb, var(--success,#4ade80) 50%, transparent); background: color-mix(in srgb, var(--success,#4ade80) 8%, transparent); }
+.awh-proof-hero.is-failed { border-color: color-mix(in srgb, var(--danger,#f87171) 55%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); }
+.awh-proof-hero.is-pending { border-color: color-mix(in srgb, var(--warn,#fbbf24) 50%, transparent); background: color-mix(in srgb, var(--warn,#fbbf24) 7%, transparent); }
+.awh-proof-seal { width: 46px; height: 46px; border-radius: 50%; flex: none; display: grid; place-items: center; font-size: 22px; background: var(--surface-3, rgba(255,255,255,.08)); }
+.awh-proof-hero.is-verified .awh-proof-seal { background: color-mix(in srgb, var(--success,#4ade80) 18%, transparent); color: var(--success,#4ade80); }
+.awh-proof-hero.is-failed .awh-proof-seal { background: color-mix(in srgb, var(--danger,#f87171) 18%, transparent); color: var(--danger,#f87171); }
+.awh-proof-hero.is-pending .awh-proof-seal { background: color-mix(in srgb, var(--warn,#fbbf24) 18%, transparent); color: var(--warn,#fbbf24); }
+.awh-proof-hero-main { min-width: 0; flex: 1; }
+.awh-proof-hero-title { font-size: var(--text-lg,1.15rem); font-weight: 700; color: var(--ink-bright,#fff); font-family: var(--font-display, system-ui); line-height: 1.15; }
+.awh-proof-hero-sub { font-size: var(--text-sm,.8125rem); color: var(--ink-dim,#888); margin-top: 3px; }
+.awh-proof-hero-sub a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
+.awh-proof-spin { width: 18px; height: 18px; border-radius: 50%; border: 2px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); border-top-color: var(--warn,#fbbf24); animation: awh-proof-spin 0.7s linear infinite; }
+@keyframes awh-proof-spin { to { transform: rotate(360deg); } }
+@media (prefers-reduced-motion: reduce) { .awh-proof-spin { animation: none; } }
+
+.awh-proof-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: var(--space-3,12px); }
+.awh-proof-fact { 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 13px; }
+.awh-proof-fact-k { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim,#888); }
+.awh-proof-fact-v { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.8125rem); color: var(--ink-bright,#fff); margin-top: 4px; word-break: break-all; }
+.awh-proof-fact-v a { color: inherit; }
+
+.awh-proof-steps { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.awh-proof-step { display: flex; gap: 10px; align-items: flex-start; font-size: var(--text-sm,.8125rem); padding: 10px 12px; border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); }
+.awh-proof-step-ico { flex: none; width: 20px; height: 20px; border-radius: 50%; display: grid; place-items: center; font-size: 12px; font-weight: 700; }
+.awh-proof-step.ok { border-color: color-mix(in srgb, var(--success,#4ade80) 35%, transparent); }
+.awh-proof-step.ok .awh-proof-step-ico { background: color-mix(in srgb, var(--success,#4ade80) 18%, transparent); color: var(--success,#4ade80); }
+.awh-proof-step.bad { border-color: color-mix(in srgb, var(--danger,#f87171) 40%, transparent); }
+.awh-proof-step.bad .awh-proof-step-ico { background: color-mix(in srgb, var(--danger,#f87171) 18%, transparent); color: var(--danger,#f87171); }
+.awh-proof-step.pending .awh-proof-step-ico { background: var(--surface-3, rgba(255,255,255,.08)); color: var(--ink-dim,#888); }
+.awh-proof-step-c { min-width: 0; }
+.awh-proof-step-name { color: var(--ink-bright,#fff); font-weight: 600; }
+.awh-proof-step-detail { color: var(--ink-dim,#888); margin-top: 2px; line-height: 1.5; }
+
+.awh-proof-recon { border-radius: var(--radius-md,10px); padding: 12px 14px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); font-size: var(--text-sm,.8125rem); line-height: 1.55; color: var(--ink,#e8e8e8); }
+.awh-proof-recon.is-good { border-color: color-mix(in srgb, var(--success,#4ade80) 35%, transparent); }
+.awh-proof-recon.is-bad { border-color: color-mix(in srgb, var(--danger,#f87171) 50%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 7%, transparent); color: var(--danger,#f87171); }
+.awh-proof-recon-h { font-weight: 600; color: var(--ink-bright,#fff); display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
+.awh-proof-recon.is-bad .awh-proof-recon-h { color: var(--danger,#f87171); }
+.awh-proof-events { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.awh-proof-event { display: flex; justify-content: space-between; gap: 12px; font-size: var(--text-2xs,.72rem); font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink-dim,#888); padding: 6px 9px; border-radius: var(--radius-sm,6px); background: var(--surface-2, rgba(255,255,255,.04)); }
+.awh-proof-event a { color: var(--ink,#c8c8c8); }
+
+.awh-proof-btn { appearance: none; font: inherit; font-size: var(--text-sm,.8125rem); font-weight: 600; cursor: pointer; color: var(--bg-1,#0a0a0a); background: var(--accent,#fff); border: 1px solid var(--accent,#fff); border-radius: var(--radius-md,10px); padding: 9px 16px; text-decoration: none; display: inline-flex; align-items: center; gap: 7px; transition: opacity var(--duration-fast,140ms), transform var(--duration-fast,140ms); }
+.awh-proof-btn:hover { opacity: .9; }
+.awh-proof-btn:active { transform: translateY(1px); }
+.awh-proof-btn:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }
+.awh-proof-btn.ghost { color: var(--ink,#e8e8e8); background: transparent; border-color: var(--stroke, rgba(255,255,255,.12)); }
+.awh-proof-btn:disabled { opacity: .5; cursor: progress; }
+.awh-proof-actions { display: flex; gap: 10px; flex-wrap: wrap; }
+
+.awh-proof-share { margin-top: 12px; }
+.awh-proof-embed { width: 100%; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-2xs,.7rem); color: var(--ink-dim,#888); background: var(--surface-2, rgba(255,255,255,.04)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: 9px 11px; resize: vertical; min-height: 54px; }
+.awh-proof-badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: var(--radius-pill,999px); font-size: var(--text-2xs,.72rem); font-weight: 600; border: 1px solid color-mix(in srgb, var(--success,#4ade80) 40%, transparent); color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 10%, transparent); }
+.awh-proof-badge::before { content: '✓'; }
+
+.awh-proof-skel span { display: block; background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-md,10px); animation: awh-skel 1.4s ease-in-out infinite; }
+@keyframes awh-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }
+@media (prefers-reduced-motion: reduce) { .awh-proof-skel span { animation: none; } }
+`;
diff --git a/src/agents/mood-model.js b/src/agents/mood-model.js
new file mode 100644
index 000000000..08c217ced
--- /dev/null
+++ b/src/agents/mood-model.js
@@ -0,0 +1,181 @@
+// Mood model — the small, honest emotional state that drives an agent's body.
+//
+// This module is PURE: no DOM, no bus, no network, no wall-clock reads inside
+// the math. Everything is a function of explicit inputs, so the whole model is
+// unit-testable and reusable by the live engine (src/agents/mood-engine.js),
+// the server (history validation), and the inspector.
+//
+// ── The model ────────────────────────────────────────────────────────────────
+// Mood is a point in a continuous **circumplex**: valence (how pleasant,
+// -1..+1) × arousal (how activated, 0..1). This is the dimensional model from
+// affective psychology (Russell, 1980) — it captures *blends* (mildly-pleasant-
+// and-calm vs intensely-pleasant-and-energised) that a flat list of named moods
+// cannot. We additionally project the point onto a small set of **discrete
+// moods** for legible UI and for picking an embodiment trigger.
+//
+// Mood does not move on its own and never on a timer or `Math.random()`. It
+// moves only when a real **signal** arrives (chat sentiment, a memory added or
+// recalled, a dream, an action's outcome, a market/alert event), and otherwise
+// **decays toward a baseline** so a spike fades and the agent returns to its
+// resting temperament. Sensitivity scales every signal: a stoic agent
+// (sensitivity 0) never leaves baseline; an expressive one (1) swings freely.
+
+/** Resting temperament the agent decays back toward: calm and mildly positive. */
+export const BASELINE = Object.freeze({ valence: 0.12, arousal: 0.32 });
+
+/** Default emotional sensitivity (0 = stoic, never moves; 1 = very expressive). */
+export const DEFAULT_SENSITIVITY = 0.6;
+
+// Half-lives for the exponential decay back to baseline (seconds). Arousal
+// settles faster than valence — physiological activation fades quicker than the
+// felt pleasantness of an event, which is why a good or bad mood "lingers".
+const HALF_LIFE_VALENCE_S = 130;
+const HALF_LIFE_AROUSAL_S = 70;
+
+const clampValence = (v) => Math.max(-1, Math.min(1, Number(v) || 0));
+const clampArousal = (a) => Math.max(0, Math.min(1, Number.isFinite(a) ? a : BASELINE.arousal));
+export const clampSensitivity = (s) => Math.max(0, Math.min(1, Number.isFinite(s) ? s : DEFAULT_SENSITIVITY));
+
+/**
+ * Signal catalogue — the ONLY ways mood moves, each declaring its nominal pull
+ * on valence (`dv`) and arousal (`da`) plus a human label for the inspector.
+ * Real producers map their event to one of these (often scaling by salience /
+ * sentiment / outcome). Deltas are pre-sensitivity; the engine multiplies by the
+ * agent's sensitivity before applying.
+ *
+ * @type {Object<string,{dv:number,da:number,label:string}>}
+ */
+export const SIGNALS = Object.freeze({
+ 'chat:positive': { dv: 0.45, da: 0.22, label: 'Warm conversation' },
+ 'chat:negative': { dv: -0.45, da: 0.30, label: 'Tense conversation' },
+ 'memory:added': { dv: 0.06, da: 0.14, label: 'Learned something' },
+ 'memory:recalled': { dv: 0.03, da: 0.07, label: 'Remembered something' },
+ 'memory:forgotten':{ dv: -0.05, da: 0.05, label: 'Let something go' },
+ 'dream:insight': { dv: 0.26, da: 0.20, label: 'Had an insight' },
+ 'action:success': { dv: 0.28, da: 0.22, label: 'Handled something well' },
+ 'action:failure': { dv: -0.34, da: 0.28, label: 'An action went wrong' },
+ 'alert:good': { dv: 0.30, da: 0.30, label: 'Good news in your world' },
+ 'alert:bad': { dv: -0.36, da: 0.34, label: 'Trouble in your world' },
+ 'brain:updated': { dv: 0.08, da: 0.10, label: 'Personality reshaped' },
+});
+
+/**
+ * Discrete moods as octants of the circumplex, each with an emoji, a UI colour,
+ * and the embodiment trigger (an `<agent-3d>` `expressEmotion` vocabulary name)
+ * + base intensity used for the transient spike when the agent *enters* it.
+ * Ordering matters: the first whose predicate matches wins, so the neutral
+ * dead-zone is checked first.
+ */
+export const MOODS = Object.freeze([
+ { key: 'calm', label: 'Calm', emoji: '😌', color: '#7c93b3', trigger: 'patience', intensity: 0.35,
+ test: (v, a) => Math.abs(v) < 0.16 && a < 0.46 },
+ { key: 'alert', label: 'Alert', emoji: '👀', color: '#38bdf8', trigger: 'curiosity', intensity: 0.55,
+ test: (v, a) => Math.abs(v) < 0.16 && a >= 0.46 },
+ { key: 'elated', label: 'Elated', emoji: '🤩', color: '#f5a623', trigger: 'celebration', intensity: 0.9,
+ test: (v, a) => v >= 0.16 && a >= 0.55 },
+ { key: 'content', label: 'Content', emoji: '🙂', color: '#4ade80', trigger: 'celebration', intensity: 0.45,
+ test: (v, a) => v >= 0.16 && a < 0.55 },
+ { key: 'agitated', label: 'Agitated', emoji: '😟', color: '#f87171', trigger: 'concern', intensity: 0.85,
+ test: (v, a) => v <= -0.16 && a >= 0.55 },
+ { key: 'subdued', label: 'Subdued', emoji: '😔', color: '#818cf8', trigger: 'empathy', intensity: 0.5,
+ test: (v, a) => v <= -0.16 && a < 0.55 },
+]);
+
+const NEUTRAL_MOOD = MOODS[0];
+
+/**
+ * Project a (valence, arousal) point onto its discrete mood descriptor.
+ * @returns {{key:string,label:string,emoji:string,color:string,trigger:string,intensity:number}}
+ */
+export function moodLabel(valence, arousal) {
+ const v = clampValence(valence);
+ const a = clampArousal(arousal);
+ for (const m of MOODS) {
+ if (m.test(v, a)) return m;
+ }
+ return NEUTRAL_MOOD;
+}
+
+/**
+ * A fresh state at baseline (or restored from a persisted snapshot).
+ * @param {{valence?:number,arousal?:number,sensitivity?:number}} [seed]
+ */
+export function makeState(seed = {}) {
+ return {
+ valence: clampValence(seed.valence ?? BASELINE.valence),
+ arousal: clampArousal(seed.arousal ?? BASELINE.arousal),
+ };
+}
+
+/**
+ * Apply one signal to a state, returning a NEW state (pure). The signal can be a
+ * known key from {@link SIGNALS} or an explicit `{dv, da}` delta. `weight` (0..1,
+ * e.g. memory salience or |sentiment|) scales the delta; `sensitivity` scales it
+ * again — at sensitivity 0 the state is returned unchanged (a true stoic).
+ *
+ * @param {{valence:number,arousal:number}} state
+ * @param {string|{dv:number,da:number,label?:string}} signal
+ * @param {{weight?:number, sensitivity?:number}} [opts]
+ * @returns {{valence:number,arousal:number}}
+ */
+export function applySignal(state, signal, opts = {}) {
+ const def = typeof signal === 'string' ? SIGNALS[signal] : signal;
+ if (!def) return { valence: clampValence(state.valence), arousal: clampArousal(state.arousal) };
+ const sensitivity = clampSensitivity(opts.sensitivity);
+ const weight = Number.isFinite(opts.weight) ? Math.max(0, Math.min(1, opts.weight)) : 1;
+ const gain = sensitivity * weight;
+ return {
+ valence: clampValence(state.valence + (def.dv || 0) * gain),
+ arousal: clampArousal(state.arousal + (def.da || 0) * gain),
+ };
+}
+
+/**
+ * Decay a state toward baseline over `dtMs` milliseconds (pure). Uses true
+ * exponential relaxation per channel so the result is frame-rate independent:
+ * the same elapsed time produces the same mood whether ticked once or in many
+ * small steps.
+ *
+ * @param {{valence:number,arousal:number}} state
+ * @param {number} dtMs
+ * @param {{baseline?:{valence:number,arousal:number}}} [opts]
+ */
+export function decay(state, dtMs, opts = {}) {
+ const base = opts.baseline || BASELINE;
+ const dt = Math.max(0, Number(dtMs) || 0) / 1000;
+ if (dt === 0) return { valence: clampValence(state.valence), arousal: clampArousal(state.arousal) };
+ const kV = 1 - Math.pow(0.5, dt / HALF_LIFE_VALENCE_S);
+ const kA = 1 - Math.pow(0.5, dt / HALF_LIFE_AROUSAL_S);
+ return {
+ valence: clampValence(state.valence + (base.valence - state.valence) * kV),
+ arousal: clampArousal(state.arousal + (base.arousal - state.arousal) * kA),
+ };
+}
+
+/**
+ * Distance between two mood points in circumplex space (valence weighted equally
+ * to arousal). Used to decide when a change is "significant" enough to persist /
+ * emit / play a transition gesture.
+ */
+export function moodDistance(a, b) {
+ const dv = clampValence(a.valence) - clampValence(b.valence);
+ const da = clampArousal(a.arousal) - clampArousal(b.arousal);
+ return Math.hypot(dv, da);
+}
+
+/**
+ * Derive a mood signal from a real sentiment score in [-1, 1] (the deterministic
+ * lexicon scorer's output, or any other real sentiment source). Returns null for
+ * a neutral score so we never invent emotion from a flat message.
+ *
+ * @param {number} score sentiment in [-1, 1]
+ * @returns {{signal:string, weight:number}|null}
+ */
+export function signalFromSentiment(score) {
+ const s = Number(score) || 0;
+ if (Math.abs(s) < 0.05) return null;
+ return {
+ signal: s > 0 ? 'chat:positive' : 'chat:negative',
+ weight: Math.min(1, Math.abs(s) * 1.6),
+ };
+}
diff --git a/src/mind-palace.js b/src/mind-palace.js
new file mode 100644
index 000000000..2227658c3
--- /dev/null
+++ b/src/mind-palace.js
@@ -0,0 +1,1499 @@
+// The Mind Palace — your agent's memory rendered as a place you can walk through.
+//
+// Every row in `agent_memories` becomes a tangible object in a 3D constellation
+// with the live <agent-3d> avatar at its core. The mapping is honest and reads
+// at a glance:
+// • salience (0..1) → object size + emissive glow + proximity to the avatar
+// (core beliefs orbit close, fleeting notes drift out).
+// • type → a distinct geometric form AND a colour region
+// (user=octahedron/blue, feedback=tetra/rose,
+// project=cube/green, reference=icosa/amber).
+// • recency / expiry → freshness: newly-formed memories bloom in; memories
+// with an expires_at visibly desaturate and dim.
+// • shared tags → real association edges, a navigable knowledge graph.
+// • is_public → a halo ring; private memories are unadorned.
+//
+// Direct manipulation, not forms — every gesture hits the real API through the
+// shared memory-client (so the change ripples to the HUD and the chat too):
+// • drag a memory toward the avatar → pin it + raise salience (PATCH).
+// • flick it into the Forget well → schedule its expiry (PATCH), with undo.
+// • search / filter / sort → debounced, client-side over the loaded set.
+// • click a memory → inspect content, context, provenance,
+// and walk its tag-graph ("why this?").
+//
+// It is live: it subscribes to the agent bus, so a memory formed in a chat
+// blooms here in real time, and `memory:recalled` pulses the recalled nodes —
+// open the Palace during a conversation and you watch recall happen.
+//
+// Scales: GPU-instanced geometry (one draw call per type) + level-of-detail
+// labels keep thousands of nodes smooth. A 2D fallback, full keyboard
+// navigation, and prefers-reduced-motion make it usable without a mouse or a
+// GPU. Respects the shared WebGL context budget.
+//
+// Mounted lazily by the Mind tab in src/agent-edit.js, and full-screen by the
+// /agent/:id/mind route (src/agent-mind.js). Both call mountMindPalace().
+
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import {
+ listMemories,
+ updateMemory,
+ forgetMemory,
+} from './agents/memory-client.js';
+import { agentBus, EVENTS } from './agents/agent-bus.js';
+import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+// ── Type vocabulary: form + colour per memory type ─────────────────────────────
+// Each type owns a geometric form (the "crystal whose shape encodes type") and a
+// colour family, and is seeded into its own angular sector so types read as
+// distinct constellations.
+const TYPES = {
+ user: { label: 'You', color: 0x7aa2ff, hex: '#7aa2ff', sector: 0, geom: 'octahedron' },
+ feedback: { label: 'Guidance', color: 0xf28db4, hex: '#f28db4', sector: Math.PI * 0.5, geom: 'tetrahedron' },
+ project: { label: 'Projects', color: 0x86f0bc, hex: '#86f0bc', sector: Math.PI, geom: 'box' },
+ reference: { label: 'Knowledge', color: 0xf0cf8a, hex: '#f0cf8a', sector: Math.PI * 1.5, geom: 'icosahedron' },
+};
+const TYPE_ORDER = ['user', 'feedback', 'project', 'reference'];
+const ALL_TYPES = TYPE_ORDER;
+
+// Layout shell — high-salience memories sit near INNER_R, low-salience drift to
+// INNER_R + SPAN. Everything is centred on the avatar at the origin.
+const INNER_R = 3.2;
+const SPAN = 9.5;
+const MAX_EDGES = 700; // association edges cap (highest combined-salience first)
+const PULSE_MS = 1600; // recall pulse duration
+const BLOOM_MS = 900; // new-memory bloom-in duration
+
+const reduceMotion = () =>
+ typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+// Deterministic 0..1 hash from a string id — keeps layout stable across reloads.
+function hash01(str, salt = 0) {
+ let h = 2166136261 ^ salt;
+ const s = String(str);
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return ((h >>> 0) % 100000) / 100000;
+}
+
+let STYLE_INJECTED = false;
+function injectStyle() {
+ if (STYLE_INJECTED || typeof document === 'undefined') return;
+ STYLE_INJECTED = true;
+ const css = `
+.mind-palace{position:relative;width:100%;height:100%;min-height:480px;overflow:hidden;border-radius:14px;background:radial-gradient(120% 120% at 50% 30%,#0b1020 0%,#06080f 60%,#04050a 100%);color:#e8edf7;font:500 13px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;contain:layout paint;touch-action:none}
+.mp-canvas{position:absolute;inset:0;display:block}
+.mp-avatar{position:absolute;left:50%;top:50%;width:168px;height:168px;transform:translate(-50%,-50%);pointer-events:none;z-index:2;filter:drop-shadow(0 6px 30px rgba(122,162,255,.35))}
+.mp-avatar agent-3d{width:100%;height:100%;display:block}
+.mp-avatar-fallback{width:100%;height:100%;border-radius:50%;background:radial-gradient(circle at 50% 35%,rgba(122,162,255,.5),rgba(122,162,255,.05));border:1px solid rgba(122,162,255,.35);display:flex;align-items:center;justify-content:center;font-size:2rem}
+/* Toolbar */
+.mp-bar{position:absolute;left:12px;right:12px;top:12px;z-index:6;display:flex;flex-wrap:wrap;gap:8px;align-items:center;pointer-events:none}
+.mp-bar>*{pointer-events:auto}
+.mp-search{flex:1 1 220px;min-width:160px;max-width:360px;display:flex;align-items:center;gap:8px;background:rgba(12,16,28,.82);border:1px solid rgba(255,255,255,.12);border-radius:10px;padding:7px 11px;backdrop-filter:blur(8px)}
+.mp-search input{flex:1;background:none;border:0;color:#fff;font:inherit;outline:none;min-width:0}
+.mp-search svg{flex:none;opacity:.55}
+.mp-chips{display:flex;gap:6px;flex-wrap:wrap}
+.mp-chip{display:inline-flex;align-items:center;gap:6px;background:rgba(12,16,28,.8);border:1px solid rgba(255,255,255,.14);color:#cdd9ff;border-radius:999px;padding:5px 11px;font-size:.74rem;font-weight:600;cursor:pointer;transition:background .15s,border-color .15s,transform .1s;backdrop-filter:blur(8px)}
+.mp-chip:hover{background:rgba(255,255,255,.1)}
+.mp-chip:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.mp-chip[aria-pressed="true"]{border-color:transparent;color:#06080f}
+.mp-chip .dot{width:9px;height:9px;border-radius:50%;flex:none}
+.mp-tools{display:flex;gap:6px;margin-left:auto}
+.mp-btn{display:inline-flex;align-items:center;gap:6px;background:rgba(12,16,28,.8);border:1px solid rgba(255,255,255,.14);color:#cdd9ff;border-radius:9px;padding:6px 10px;font-size:.74rem;font-weight:600;cursor:pointer;transition:background .15s,transform .1s;backdrop-filter:blur(8px)}
+.mp-btn:hover{background:rgba(255,255,255,.1)}
+.mp-btn:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.mp-btn[aria-pressed="true"]{background:rgba(122,162,255,.22);border-color:rgba(122,162,255,.5);color:#fff}
+/* Legend + stats */
+.mp-legend{position:absolute;left:12px;bottom:12px;z-index:5;display:flex;flex-direction:column;gap:6px;background:rgba(8,11,20,.7);border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:9px 12px;backdrop-filter:blur(8px);font-size:.7rem;max-width:200px}
+.mp-legend b{font-size:.66rem;text-transform:uppercase;letter-spacing:.08em;color:rgba(255,255,255,.5);font-weight:700}
+.mp-legend .row{display:flex;align-items:center;gap:7px;color:rgba(255,255,255,.8)}
+.mp-legend .row .dot{width:9px;height:9px;border-radius:2px;flex:none}
+.mp-stat{position:absolute;right:12px;bottom:12px;z-index:5;background:rgba(8,11,20,.7);border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:8px 12px;backdrop-filter:blur(8px);font-size:.72rem;color:rgba(255,255,255,.78);text-align:right}
+.mp-stat b{color:#fff}
+/* Timeline scrubber */
+.mp-time{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);z-index:6;display:flex;align-items:center;gap:10px;background:rgba(8,11,20,.78);border:1px solid rgba(255,255,255,.12);border-radius:999px;padding:7px 14px;backdrop-filter:blur(8px);width:min(440px,72%);opacity:0;pointer-events:none;transition:opacity .2s}
+.mp-time.show{opacity:1;pointer-events:auto}
+.mp-time input[type=range]{flex:1;accent-color:#7aa2ff;cursor:pointer}
+.mp-time .play{background:none;border:0;color:#cdd9ff;cursor:pointer;font-size:1rem;padding:2px 4px;border-radius:6px}
+.mp-time .play:focus-visible{outline:2px solid #7aa2ff}
+.mp-time .lbl{font-size:.68rem;color:rgba(255,255,255,.7);white-space:nowrap;min-width:84px}
+/* Forget well */
+.mp-forget{position:absolute;right:18px;top:50%;transform:translateY(-50%);z-index:4;width:118px;height:118px;border-radius:50%;border:1.5px dashed rgba(240,141,180,.45);background:radial-gradient(circle,rgba(240,141,180,.1),transparent 70%);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;color:rgba(240,141,180,.85);font-size:.68rem;font-weight:600;text-align:center;opacity:0;transition:opacity .2s,transform .2s,box-shadow .2s;pointer-events:none}
+.mp-forget.armed{opacity:1}
+.mp-forget.hot{opacity:1;transform:translateY(-50%) scale(1.12);box-shadow:0 0 36px rgba(240,141,180,.6);border-style:solid;background:radial-gradient(circle,rgba(240,141,180,.28),transparent 70%)}
+.mp-forget svg{width:26px;height:26px}
+/* Tooltip */
+.mp-tip{position:absolute;z-index:8;max-width:260px;background:rgba(10,13,23,.95);border:1px solid rgba(255,255,255,.16);border-radius:9px;padding:8px 11px;font-size:.74rem;color:#e8edf7;pointer-events:none;opacity:0;transition:opacity .12s;box-shadow:0 8px 28px rgba(0,0,0,.5);transform:translate(-50%,calc(-100% - 14px))}
+.mp-tip.show{opacity:1}
+.mp-tip .t{font-size:.62rem;text-transform:uppercase;letter-spacing:.06em;opacity:.6;margin-bottom:3px}
+.mp-tip .s{font-size:.64rem;opacity:.55;margin-top:4px}
+/* Inspector */
+.mp-inspect{position:absolute;top:0;right:0;bottom:0;width:min(380px,86%);z-index:9;background:rgba(8,11,20,.97);border-left:1px solid rgba(255,255,255,.12);backdrop-filter:blur(14px);transform:translateX(100%);transition:transform .28s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column;box-shadow:-12px 0 40px rgba(0,0,0,.5)}
+.mp-inspect.open{transform:translateX(0)}
+.mp-inspect-hd{display:flex;align-items:center;gap:10px;padding:16px 18px 10px}
+.mp-inspect-hd .badge{font-size:.62rem;text-transform:uppercase;letter-spacing:.06em;font-weight:700;padding:3px 9px;border-radius:999px}
+.mp-inspect-hd .x{margin-left:auto;background:none;border:0;color:rgba(255,255,255,.6);font-size:1.3rem;cursor:pointer;line-height:1;padding:2px 6px;border-radius:6px}
+.mp-inspect-hd .x:hover{color:#fff;background:rgba(255,255,255,.08)}
+.mp-inspect-bd{flex:1;overflow:auto;padding:6px 18px 18px}
+.mp-inspect-bd h4{font-size:.64rem;text-transform:uppercase;letter-spacing:.07em;color:rgba(255,255,255,.45);margin:18px 0 7px;font-weight:700}
+.mp-inspect-content{font-size:.86rem;line-height:1.55;color:#eef2fa;white-space:pre-wrap;word-break:break-word}
+.mp-meta-grid{display:grid;grid-template-columns:auto 1fr;gap:5px 14px;font-size:.74rem}
+.mp-meta-grid dt{color:rgba(255,255,255,.5)}
+.mp-meta-grid dd{margin:0;color:#dde6f5;text-align:right;word-break:break-word}
+.mp-tag{display:inline-block;background:rgba(122,162,255,.16);border:1px solid rgba(122,162,255,.3);color:#cdd9ff;border-radius:999px;padding:2px 9px;font-size:.68rem;margin:0 5px 5px 0;cursor:pointer}
+.mp-tag:hover{background:rgba(122,162,255,.3)}
+.mp-tag:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}
+.mp-related button{display:flex;width:100%;text-align:left;gap:8px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;margin-bottom:6px;color:#dde6f5;cursor:pointer;font:inherit;font-size:.74rem;align-items:center;transition:background .12s}
+.mp-related button:hover{background:rgba(255,255,255,.09)}
+.mp-related button:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}
+.mp-related .rdot{width:8px;height:8px;border-radius:50%;flex:none}
+.mp-related .rwhy{margin-left:auto;font-size:.62rem;opacity:.55;white-space:nowrap}
+.mp-context{font-size:.72rem;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:8px;padding:9px 11px;color:#c7d2e6;white-space:pre-wrap;word-break:break-word;max-height:160px;overflow:auto}
+.mp-inspect-actions{display:flex;gap:8px;flex-wrap:wrap;padding:12px 18px;border-top:1px solid rgba(255,255,255,.1)}
+.mp-action{flex:1;min-width:96px;display:inline-flex;align-items:center;justify-content:center;gap:6px;border-radius:9px;padding:9px 10px;font-size:.76rem;font-weight:650;cursor:pointer;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.06);color:#e8edf7;transition:background .14s,transform .1s}
+.mp-action:hover{background:rgba(255,255,255,.12)}
+.mp-action:active{transform:scale(.97)}
+.mp-action:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.mp-action.pin[aria-pressed="true"]{background:linear-gradient(135deg,#7aa2ff,#9d7aff);color:#06080f;border-color:transparent}
+.mp-action.forget{color:#f7a8c4;border-color:rgba(240,141,180,.4)}
+.mp-action.forget:hover{background:rgba(240,141,180,.16)}
+.mp-prov{font-size:.72rem;color:#9ad0ff}
+.mp-prov a{color:#9ad0ff}
+/* Overlays: loading / empty / error */
+.mp-overlay{position:absolute;inset:0;z-index:7;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;text-align:center;padding:32px;background:radial-gradient(120% 120% at 50% 40%,rgba(11,16,32,.6),rgba(4,5,10,.92))}
+.mp-overlay h3{margin:0;font-size:1.15rem;font-weight:650}
+.mp-overlay p{margin:0;max-width:380px;color:rgba(255,255,255,.62);font-size:.84rem;line-height:1.5}
+.mp-overlay .cta{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;margin-top:6px}
+.mp-overlay .cta a,.mp-overlay .cta button{display:inline-flex;align-items:center;gap:7px;border-radius:10px;padding:10px 16px;font-size:.82rem;font-weight:650;cursor:pointer;text-decoration:none;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.07);color:#e8edf7;transition:background .15s,transform .1s;font-family:inherit}
+.mp-overlay .cta a.primary,.mp-overlay .cta button.primary{background:linear-gradient(135deg,#7aa2ff,#9d7aff);color:#06080f;border-color:transparent}
+.mp-overlay .cta a:hover,.mp-overlay .cta button:hover{transform:translateY(-1px)}
+.mp-orb{width:84px;height:84px;border-radius:50%;background:conic-gradient(from 0deg,#7aa2ff,#9d7aff,#86f0bc,#f0cf8a,#7aa2ff);filter:blur(2px);animation:mp-spin 2.4s linear infinite;opacity:.85}
+.mp-orb::after{content:"";position:absolute;inset:10px;border-radius:50%;background:#06080f}
+.mp-orb{position:relative}
+@keyframes mp-spin{to{transform:rotate(360deg)}}
+@media (prefers-reduced-motion:reduce){.mp-orb{animation:none}.mp-inspect{transition:none}.mp-tip{transition:none}}
+.mp-err-detail{font-size:.74rem;color:rgba(255,255,255,.5);max-width:420px;word-break:break-word}
+/* Undo toast */
+.mp-toast{position:absolute;left:50%;bottom:64px;transform:translateX(-50%) translateY(20px);z-index:10;display:flex;align-items:center;gap:14px;background:rgba(14,18,30,.97);border:1px solid rgba(255,255,255,.16);border-radius:11px;padding:11px 16px;box-shadow:0 12px 40px rgba(0,0,0,.55);font-size:.8rem;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s}
+.mp-toast.show{opacity:1;transform:translateX(-50%) translateY(0);pointer-events:auto}
+.mp-toast button{background:none;border:0;color:#9ad0ff;font-weight:700;cursor:pointer;font:inherit;font-size:.8rem;padding:2px 4px;border-radius:6px}
+.mp-toast button:hover{color:#bfe3ff}
+.mp-toast button:focus-visible{outline:2px solid #7aa2ff}
+/* 2D fallback */
+.mp-2d{position:absolute;inset:0;z-index:3;overflow:auto;padding:64px 16px 80px;display:none}
+.mp-palace.mode-2d .mp-2d{display:block}
+.mp-palace.mode-2d .mp-canvas,.mp-palace.mode-2d .mp-avatar,.mp-palace.mode-2d .mp-forget,.mp-palace.mode-2d .mp-time{display:none}
+.mp-2d-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px;max-width:1100px;margin:0 auto}
+.mp-2d-sec{grid-column:1/-1;font-size:.66rem;text-transform:uppercase;letter-spacing:.08em;color:rgba(255,255,255,.5);font-weight:700;margin-top:10px}
+.mp-card{position:relative;text-align:left;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);border-left-width:3px;border-radius:11px;padding:12px 13px;cursor:pointer;color:#e8edf7;font:inherit;transition:background .14s,transform .1s,border-color .14s;display:flex;flex-direction:column;gap:7px}
+.mp-card:hover{background:rgba(255,255,255,.08);transform:translateY(-2px)}
+.mp-card:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.mp-card.dim{opacity:.45}
+.mp-card .ctop{display:flex;align-items:center;gap:7px;font-size:.66rem}
+.mp-card .ctop .pct{margin-left:auto;font-variant-numeric:tabular-nums;opacity:.7}
+.mp-card .ctxt{font-size:.8rem;line-height:1.45;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}
+.mp-card .cbar{height:4px;border-radius:999px;background:rgba(255,255,255,.1);overflow:hidden}
+.mp-card .cbar i{display:block;height:100%;border-radius:999px}
+.mp-card .pin{position:absolute;top:8px;right:9px;font-size:.7rem;opacity:.85}
+.mp-card .ctags{display:flex;gap:4px;flex-wrap:wrap}
+.mp-card .ctags span{font-size:.6rem;background:rgba(255,255,255,.08);border-radius:999px;padding:1px 7px;color:rgba(255,255,255,.7)}
+/* Screen-reader / keyboard roster mirror of the scene */
+.mp-roster{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
+.mp-palace:focus-within .mp-roster:focus-within{position:absolute;left:12px;top:56px;width:min(320px,70%);height:auto;clip:auto;white-space:normal;z-index:11;background:rgba(8,11,20,.97);border:1px solid rgba(122,162,255,.4);border-radius:11px;padding:10px;max-height:60%;overflow:auto;box-shadow:0 12px 40px rgba(0,0,0,.55)}
+.mp-roster ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:4px}
+.mp-roster button{display:flex;width:100%;text-align:left;gap:8px;align-items:center;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);border-radius:7px;padding:7px 9px;color:#e8edf7;font:inherit;font-size:.74rem;cursor:pointer}
+.mp-roster button:focus-visible,.mp-roster button.focus{outline:2px solid #7aa2ff;outline-offset:1px;background:rgba(122,162,255,.18)}
+.mp-roster .rdot{width:8px;height:8px;border-radius:50%;flex:none}
+.mp-hint{position:absolute;left:12px;top:54px;z-index:5;font-size:.66rem;color:rgba(255,255,255,.4);background:rgba(8,11,20,.6);border-radius:8px;padding:5px 9px;backdrop-filter:blur(6px);max-width:260px;pointer-events:none;transition:opacity .4s}
+@media (max-width:640px){.mp-avatar{width:120px;height:120px}.mp-forget{width:90px;height:90px;right:10px}.mp-legend{display:none}}
+`;
+ const tag = document.createElement('style');
+ tag.id = 'mind-palace-style';
+ tag.textContent = css;
+ document.head.appendChild(tag);
+}
+
+// Load the <agent-3d> custom element (CDN → local fallbacks), matching the
+// loader pattern used elsewhere in the app.
+async function ensureAgent3D() {
+ if (typeof customElements !== 'undefined' && customElements.get('agent-3d')) return true;
+ const candidates = [
+ 'https://three.ws/agent-3d/latest/agent-3d.js',
+ '/agent-3d/latest/agent-3d.js',
+ '/dist-lib/agent-3d.js',
+ ];
+ for (const url of candidates) {
+ try {
+ await import(/* @vite-ignore */ url);
+ if (customElements.get('agent-3d')) return true;
+ } catch {
+ /* try next */
+ }
+ }
+ return false;
+}
+
+/**
+ * Mount the Mind Palace into `host`.
+ * @param {HTMLElement} host
+ * @param {{agentId:string, agent?:object, embedded?:boolean}} opts
+ * embedded: true when mounted inside the editor tab (affects empty-state CTAs).
+ * @returns {{destroy:()=>void, refresh:()=>Promise<void>}}
+ */
+export function mountMindPalace(host, { agentId, agent = null, embedded = false } = {}) {
+ injectStyle();
+ const palace = new MindPalace(host, { agentId, agent, embedded });
+ palace.boot();
+ return {
+ destroy: () => palace.destroy(),
+ refresh: () => palace.load(),
+ };
+}
+
+class MindPalace {
+ constructor(host, { agentId, agent, embedded }) {
+ this.host = host;
+ this.agentId = agentId;
+ this.agent = agent;
+ this.embedded = embedded;
+ this.nodes = []; // [{ mem, type, x,y,z, baseR, bornAt, pulseAt, instId }]
+ this.byId = new Map();
+ this.edges = [];
+ this.filter = { q: '', types: new Set(ALL_TYPES), sort: 'salience' };
+ this.mode = this.pickInitialMode();
+ this.selectedId = null;
+ this.focusIdx = -1; // keyboard roster cursor
+ this.timeCursor = 1; // 0..1 of the created_at span (1 = now)
+ this._raf = null;
+ this._disposed = false;
+ this._busOff = [];
+ this._undo = null;
+ this._undoTimer = null;
+ this._reduce = reduceMotion();
+ this._reservedCtx = false;
+ }
+
+ pickInitialMode() {
+ // Honour reduced-motion and obviously low-power / WebGL-less contexts with
+ // the 2D fallback; everyone else gets the spatial scene.
+ if (reduceMotion()) return '2d';
+ try {
+ const c = document.createElement('canvas');
+ const gl = c.getContext('webgl2') || c.getContext('webgl');
+ if (!gl) return '2d';
+ } catch {
+ return '2d';
+ }
+ if (typeof navigator !== 'undefined' && navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 2) {
+ return '2d';
+ }
+ return '3d';
+ }
+
+ boot() {
+ this.host.innerHTML = '';
+ this.root = document.createElement('div');
+ this.root.className = `mind-palace mp-palace mode-${this.mode}`;
+ this.root.innerHTML = this.scaffoldHTML();
+ this.host.appendChild(this.root);
+ this.cacheEls();
+ this.wireChrome();
+ this.subscribeBus();
+ this.load();
+ }
+
+ scaffoldHTML() {
+ const chipFor = (t) =>
+ `<button class="mp-chip" data-type="${t}" role="switch" aria-pressed="true" aria-label="Toggle ${esc(TYPES[t].label)} memories"><span class="dot" style="background:${TYPES[t].hex}"></span>${esc(TYPES[t].label)}</button>`;
+ return `
+<canvas class="mp-canvas" aria-hidden="true"></canvas>
+<div class="mp-avatar" id="mp-avatar" aria-hidden="true"></div>
+<div class="mp-forget" id="mp-forget" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14"/></svg>
+ Forget
+</div>
+<div class="mp-bar" role="toolbar" aria-label="Mind Palace controls">
+ <label class="mp-search">
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>
+ <input type="search" id="mp-q" placeholder="Search memories… ( / )" aria-label="Search memories" autocomplete="off" />
+ </label>
+ <div class="mp-chips" role="group" aria-label="Filter by type">${ALL_TYPES.map(chipFor).join('')}</div>
+ <div class="mp-tools">
+ <button class="mp-btn" id="mp-sort" aria-label="Sort order">↕ Salience</button>
+ <button class="mp-btn" id="mp-timeline" aria-pressed="false" aria-label="Toggle memory timeline">◷ Timeline</button>
+ <button class="mp-btn" id="mp-mode" aria-pressed="${this.mode === '2d'}" aria-label="Toggle 2D / 3D view">${this.mode === '2d' ? '◉ 3D' : '▦ 2D'}</button>
+ </div>
+</div>
+<div class="mp-hint" id="mp-hint">Drag a memory to the centre to pin it · flick it right to forget · click to inspect</div>
+<div class="mp-legend" aria-hidden="true">
+ <b>Salience → distance</b>
+ <div class="row"><span class="dot" style="background:#7aa2ff;width:13px;height:13px"></span>core belief (close)</div>
+ <div class="row"><span class="dot" style="background:#7aa2ff;width:7px;height:7px;opacity:.6"></span>fleeting note (far)</div>
+</div>
+<div class="mp-stat" id="mp-stat" aria-live="polite"></div>
+<div class="mp-time" id="mp-time" role="group" aria-label="Memory timeline">
+ <button class="play" id="mp-time-play" aria-label="Replay how the mind grew">▶</button>
+ <input type="range" id="mp-time-range" min="0" max="1000" value="1000" aria-label="Timeline position" />
+ <span class="lbl" id="mp-time-lbl">now</span>
+</div>
+<div class="mp-2d" id="mp-2d"><div class="mp-2d-grid" id="mp-2d-grid"></div></div>
+<div class="mp-roster" id="mp-roster" tabindex="-1" aria-label="Memory list — arrow keys to traverse, Enter to inspect, P to pin, Delete to forget">
+ <ul id="mp-roster-list"></ul>
+</div>
+<div class="mp-tip" id="mp-tip" role="status" aria-live="off"></div>
+<aside class="mp-inspect" id="mp-inspect" aria-label="Memory details" role="dialog" aria-modal="false" hidden></aside>
+<div class="mp-toast" id="mp-toast" role="status" aria-live="polite"></div>
+<div class="mp-overlay" id="mp-overlay" hidden></div>`;
+ }
+
+ cacheEls() {
+ const q = (s) => this.root.querySelector(s);
+ this.el = {
+ canvas: q('.mp-canvas'),
+ avatar: q('#mp-avatar'),
+ forget: q('#mp-forget'),
+ q: q('#mp-q'),
+ sort: q('#mp-sort'),
+ timelineBtn: q('#mp-timeline'),
+ modeBtn: q('#mp-mode'),
+ hint: q('#mp-hint'),
+ stat: q('#mp-stat'),
+ time: q('#mp-time'),
+ timePlay: q('#mp-time-play'),
+ timeRange: q('#mp-time-range'),
+ timeLbl: q('#mp-time-lbl'),
+ grid2d: q('#mp-2d-grid'),
+ roster: q('#mp-roster'),
+ rosterList: q('#mp-roster-list'),
+ tip: q('#mp-tip'),
+ inspect: q('#mp-inspect'),
+ toast: q('#mp-toast'),
+ overlay: q('#mp-overlay'),
+ };
+ }
+
+ // ── Chrome wiring (toolbar, keyboard, resize) ───────────────────────────────
+
+ wireChrome() {
+ const e = this.el;
+ let debounce = null;
+ e.q.addEventListener('input', () => {
+ clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ this.filter.q = e.q.value.trim().toLowerCase();
+ this.applyFilter();
+ }, 140);
+ });
+ this.root.querySelectorAll('.mp-chip').forEach((chip) => {
+ chip.addEventListener('click', () => {
+ const t = chip.dataset.type;
+ if (this.filter.types.has(t)) this.filter.types.delete(t);
+ else this.filter.types.add(t);
+ chip.setAttribute('aria-pressed', this.filter.types.has(t) ? 'true' : 'false');
+ chip.style.background = this.filter.types.has(t) ? TYPES[t].hex : '';
+ this.applyFilter();
+ });
+ // Initialise the pressed colour.
+ chip.style.background = TYPES[chip.dataset.type].hex;
+ });
+ const SORTS = [
+ ['salience', '↕ Salience'],
+ ['recent', '◷ Newest'],
+ ['oldest', '◷ Oldest'],
+ ['accessed', '↻ Most recalled'],
+ ];
+ let sortIdx = 0;
+ e.sort.addEventListener('click', () => {
+ sortIdx = (sortIdx + 1) % SORTS.length;
+ this.filter.sort = SORTS[sortIdx][0];
+ e.sort.textContent = SORTS[sortIdx][1];
+ this.applyFilter();
+ });
+ e.modeBtn.addEventListener('click', () => this.setMode(this.mode === '3d' ? '2d' : '3d'));
+ e.timelineBtn.addEventListener('click', () => this.toggleTimeline());
+ e.timeRange.addEventListener('input', () => {
+ this.timeCursor = Number(e.timeRange.value) / 1000;
+ this.applyTimeCursor();
+ });
+ e.timePlay.addEventListener('click', () => this.playTimeline());
+
+ // Keyboard: '/' focuses search; the roster handles graph traversal.
+ this._keyHandler = (ev) => this.onKey(ev);
+ this.root.addEventListener('keydown', this._keyHandler);
+ this.el.rosterList.addEventListener('keydown', (ev) => this.onRosterKey(ev));
+
+ // Pause rendering when offscreen — the avatar is on every page; don't burn
+ // frames on a Palace nobody is looking at.
+ if ('IntersectionObserver' in window) {
+ this._io = new IntersectionObserver((ents) => {
+ this._visible = ents[0]?.isIntersecting ?? true;
+ if (this._visible && this.mode === '3d') this.startLoop();
+ else this.stopLoop();
+ }, { threshold: 0.05 });
+ this._io.observe(this.root);
+ } else {
+ this._visible = true;
+ }
+
+ this._onResize = () => this.resize();
+ window.addEventListener('resize', this._onResize);
+ }
+
+ onKey(ev) {
+ if (ev.key === '/' && document.activeElement !== this.el.q) {
+ ev.preventDefault();
+ this.el.q.focus();
+ this.el.q.select();
+ } else if (ev.key === 'Escape') {
+ if (this.el.inspect.classList.contains('open')) this.closeInspector();
+ } else if ((ev.key === 'f' || ev.key === 'F') && document.activeElement === this.root) {
+ this.el.roster.focus();
+ this.moveFocus(0);
+ }
+ }
+
+ // ── Data loading ────────────────────────────────────────────────────────────
+
+ async load() {
+ this.showOverlay('loading');
+ try {
+ // Fetch per-type in parallel (the list endpoint caps at 500/request);
+ // the four types are disjoint, so this lifts capacity to ~2000 of the
+ // most-salient memories without any dedup.
+ const batches = await Promise.all(
+ ALL_TYPES.map((t) => listMemories(this.agentId, { type: t, limit: 500 }).catch(() => []))
+ );
+ const all = [];
+ for (const b of batches) for (const m of b) if (m && m.id) all.push(m);
+ this.ingest(all);
+ if (!all.length) {
+ this.showOverlay('empty');
+ return;
+ }
+ this.hideOverlay();
+ await this.ensureScene();
+ this.rebuild();
+ this.updateStat();
+ } catch (err) {
+ this.showOverlay('error', err?.message || String(err));
+ }
+ }
+
+ ingest(memories) {
+ this.nodes = [];
+ this.byId.clear();
+ // Time span for recency mapping + timeline scrub.
+ this.tMin = Infinity;
+ this.tMax = -Infinity;
+ for (const m of memories) {
+ const t = m.createdAt || 0;
+ if (t < this.tMin) this.tMin = t;
+ if (t > this.tMax) this.tMax = t;
+ }
+ if (!Number.isFinite(this.tMin)) { this.tMin = 0; this.tMax = 1; }
+ if (this.tMax <= this.tMin) this.tMax = this.tMin + 1;
+ for (const m of memories) this.addNode(m, { bloom: false });
+ this.computeEdges();
+ }
+
+ addNode(mem, { bloom = true } = {}) {
+ const type = TYPES[mem.type] ? mem.type : 'reference';
+ const pos = this.layoutPosition(mem, type);
+ const node = {
+ mem,
+ type,
+ x: pos.x, y: pos.y, z: pos.z,
+ baseR: pos.r,
+ bornAt: bloom ? now() : 0,
+ pulseAt: 0,
+ visible: true,
+ instId: -1,
+ };
+ this.nodes.push(node);
+ this.byId.set(mem.id, node);
+ return node;
+ }
+
+ // Deterministic layout: each type owns an angular sector; salience pulls a
+ // memory in toward the avatar; the id-hash spreads nodes on a shell so they
+ // don't overlap. Stable across reloads (no RAF, no randomness).
+ layoutPosition(mem, type) {
+ const sal = clamp01(mem.salience ?? 0.5);
+ const r = INNER_R + (1 - sal) * SPAN;
+ const sectorBase = TYPES[type].sector;
+ // Spread within a ~110° sector around the type's base angle.
+ const a = sectorBase + (hash01(mem.id, 1) - 0.5) * 1.92;
+ // Vertical band: high-salience memories ride near the equator (eye-level
+ // with the avatar); low-salience scatter up/down.
+ const phi = (hash01(mem.id, 2) - 0.5) * Math.PI * (0.35 + (1 - sal) * 0.65);
+ const x = Math.cos(phi) * Math.cos(a) * r;
+ const z = Math.cos(phi) * Math.sin(a) * r;
+ const y = Math.sin(phi) * r;
+ return { x, y, z, r };
+ }
+
+ computeEdges() {
+ // Association graph: connect memories that share at least one tag. Build a
+ // tag→nodes index, score each candidate pair by shared-tag count × combined
+ // salience, keep the strongest MAX_EDGES.
+ const byTag = new Map();
+ for (const n of this.nodes) {
+ for (const tag of n.mem.tags || []) {
+ const k = String(tag).toLowerCase();
+ if (!byTag.has(k)) byTag.set(k, []);
+ byTag.get(k).push(n);
+ }
+ }
+ const pairScore = new Map();
+ const pairKey = (a, b) => (a.mem.id < b.mem.id ? a.mem.id + '|' + b.mem.id : b.mem.id + '|' + a.mem.id);
+ for (const list of byTag.values()) {
+ if (list.length < 2 || list.length > 60) continue; // skip mega-tags (noise)
+ for (let i = 0; i < list.length; i++) {
+ for (let j = i + 1; j < list.length; j++) {
+ const k = pairKey(list[i], list[j]);
+ const prev = pairScore.get(k);
+ const score = (list[i].mem.salience || 0.3) + (list[j].mem.salience || 0.3);
+ if (prev) prev.w += 1; else pairScore.set(k, { a: list[i], b: list[j], w: 1, s: score });
+ }
+ }
+ }
+ this.edges = [...pairScore.values()]
+ .sort((x, y) => y.w * y.s - x.w * x.s)
+ .slice(0, MAX_EDGES);
+ // Adjacency for keyboard graph-walk + "why does it believe this".
+ this.adj = new Map();
+ for (const e of this.edges) {
+ if (!this.adj.has(e.a.mem.id)) this.adj.set(e.a.mem.id, []);
+ if (!this.adj.has(e.b.mem.id)) this.adj.set(e.b.mem.id, []);
+ this.adj.get(e.a.mem.id).push({ node: e.b, w: e.w });
+ this.adj.get(e.b.mem.id).push({ node: e.a, w: e.w });
+ }
+ }
+
+ // ── Three.js scene ──────────────────────────────────────────────────────────
+
+ async ensureScene() {
+ if (this.scene || this.mode !== '3d') {
+ if (this.mode === '3d') this.mountAvatar();
+ return;
+ }
+ reserveWebGLContext();
+ this._reservedCtx = true;
+ const canvas = this.el.canvas;
+ const w = this.root.clientWidth || 800;
+ const h = this.root.clientHeight || 520;
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ this.renderer.setSize(w, h, false);
+ this.scene = new THREE.Scene();
+ this.camera = new THREE.PerspectiveCamera(52, w / h, 0.1, 200);
+ this.camera.position.set(0, 2.2, 18);
+ this.controls = new OrbitControls(this.camera, canvas);
+ this.controls.target.set(0, 0, 0);
+ this.controls.enablePan = false; // keep the avatar locked to screen-centre
+ this.controls.enableDamping = !this._reduce;
+ this.controls.dampingFactor = 0.08;
+ this.controls.minDistance = 7;
+ this.controls.maxDistance = 40;
+ this.controls.autoRotate = false;
+ this.controls.rotateSpeed = 0.7;
+
+ this.scene.add(new THREE.AmbientLight(0xb9c7ff, 0.55));
+ const core = new THREE.PointLight(0x9db4ff, 2.2, 60, 1.4);
+ core.position.set(0, 0, 0);
+ this.scene.add(core);
+ // A faint inner "pin core" ring the avatar sits inside — the drop target.
+ const ringGeo = new THREE.RingGeometry(INNER_R - 0.5, INNER_R - 0.35, 64);
+ const ringMat = new THREE.MeshBasicMaterial({ color: 0x7aa2ff, transparent: true, opacity: 0.14, side: THREE.DoubleSide });
+ this.coreRing = new THREE.Mesh(ringGeo, ringMat);
+ this.coreRing.rotation.x = Math.PI / 2;
+ this.scene.add(this.coreRing);
+
+ this.nodeGroup = new THREE.Group();
+ this.scene.add(this.nodeGroup);
+ this.edgeObj = null;
+ this.instanced = {}; // type → { mesh, nodes:[] }
+
+ this.raycaster = new THREE.Raycaster();
+ this.pointer = new THREE.Vector2();
+ this.dragPlane = new THREE.Plane();
+ this._tmp = new THREE.Vector3();
+ this._mat4 = new THREE.Matrix4();
+ this._col = new THREE.Color();
+
+ this.bindPointer();
+ this.mountAvatar();
+ this.resize();
+ this.startLoop();
+ }
+
+ async mountAvatar() {
+ if (this._avatarMounted) return;
+ this._avatarMounted = true;
+ const ok = await ensureAgent3D();
+ if (this._disposed) return;
+ if (ok) {
+ const a = document.createElement('agent-3d');
+ if (this.agentId) a.setAttribute('agent-id', this.agentId);
+ if (this.agent?.avatar_id) a.setAttribute('avatar-id', this.agent.avatar_id);
+ a.setAttribute('mode', 'inline');
+ a.setAttribute('eager', '');
+ this.el.avatar.appendChild(a);
+ this.avatarEl = a;
+ } else {
+ this.el.avatar.innerHTML = `<div class="mp-avatar-fallback">🧠</div>`;
+ }
+ }
+
+ rebuild() {
+ if (this.mode === '3d' && this.scene) this.rebuildInstances();
+ this.rebuild2D();
+ this.rebuildRoster();
+ this.applyFilter();
+ }
+
+ geomFor(type) {
+ switch (TYPES[type].geom) {
+ case 'octahedron': return new THREE.OctahedronGeometry(0.5, 0);
+ case 'tetrahedron': return new THREE.TetrahedronGeometry(0.6, 0);
+ case 'box': return new THREE.BoxGeometry(0.72, 0.72, 0.72);
+ default: return new THREE.IcosahedronGeometry(0.52, 0);
+ }
+ }
+
+ rebuildInstances() {
+ // One InstancedMesh per type → 4 draw calls regardless of memory count.
+ for (const t of ALL_TYPES) {
+ const prev = this.instanced[t];
+ if (prev) { this.nodeGroup.remove(prev.mesh); prev.mesh.geometry.dispose(); prev.mesh.material.dispose(); }
+ const tNodes = this.nodes.filter((n) => n.type === t);
+ const count = Math.max(tNodes.length, 1);
+ const geo = this.geomFor(t);
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, metalness: 0.25, roughness: 0.35,
+ emissive: TYPES[t].color, emissiveIntensity: 0.4,
+ transparent: true, opacity: 1,
+ });
+ const mesh = new THREE.InstancedMesh(geo, mat, count);
+ mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(count * 3), 3);
+ mesh.frustumCulled = false;
+ mesh.userData.type = t;
+ tNodes.forEach((n, i) => { n.instId = i; });
+ this.instanced[t] = { mesh, nodes: tNodes };
+ this.nodeGroup.add(mesh);
+ }
+ this.rebuildEdges();
+ this.syncInstances(true);
+ }
+
+ rebuildEdges() {
+ if (this.edgeObj) { this.nodeGroup.remove(this.edgeObj); this.edgeObj.geometry.dispose(); this.edgeObj.material.dispose(); this.edgeObj = null; }
+ if (!this.edges.length) return;
+ const positions = new Float32Array(this.edges.length * 6);
+ this.edgeObj = new THREE.LineSegments(
+ new THREE.BufferGeometry(),
+ new THREE.LineBasicMaterial({ color: 0x6f86c9, transparent: true, opacity: 0.12 })
+ );
+ this.edgeObj.geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ this.edgeObj.frustumCulled = false;
+ this.nodeGroup.add(this.edgeObj);
+ }
+
+ // Push positions/scales/colours for every instance. `full` recomputes colours;
+ // otherwise only matrices (positions) update — cheap for drag/pulse frames.
+ syncInstances(full = false) {
+ if (!this.scene) return;
+ const tNow = now();
+ for (const t of ALL_TYPES) {
+ const inst = this.instanced[t];
+ if (!inst) continue;
+ const { mesh, nodes } = inst;
+ for (let i = 0; i < nodes.length; i++) {
+ const n = nodes[i];
+ const sal = clamp01(n.mem.salience ?? 0.5);
+ let scale = 0.5 + sal * 1.5;
+ // Bloom-in animation for freshly-formed memories.
+ if (n.bornAt && !this._reduce) {
+ const p = Math.min(1, (tNow - n.bornAt) / BLOOM_MS);
+ scale *= easeOut(p);
+ if (p >= 1) n.bornAt = 0;
+ }
+ // Recall pulse — a transient size + glow bump.
+ let pulse = 0;
+ if (n.pulseAt) {
+ const p = (tNow - n.pulseAt) / PULSE_MS;
+ if (p >= 1) n.pulseAt = 0;
+ else pulse = Math.sin(p * Math.PI);
+ }
+ scale *= 1 + pulse * 0.6;
+ if (!n.visible) scale = 0.0001;
+ this._tmp.set(n.x, n.y, n.z);
+ this._mat4.makeScale(scale, scale, scale);
+ this._mat4.setPosition(this._tmp);
+ mesh.setMatrixAt(i, this._mat4);
+ if (full || n.pulseAt || n.bornAt || n._colorDirty) {
+ // Brightness encodes salience + recency; expiring memories fade.
+ const recency = (n.mem.createdAt - this.tMin) / (this.tMax - this.tMin || 1);
+ let bright = 0.45 + sal * 0.55 + recency * 0.12;
+ if (n.mem.expiresAt && n.mem.expiresAt < Date.now() + 1000 * 60 * 60 * 24 * 7) {
+ bright *= 0.45; // dimming toward forgotten
+ }
+ if (this.selectedId === n.mem.id) bright = 1.25;
+ bright = Math.min(1.4, bright + pulse * 0.8);
+ this._col.setHex(TYPES[t].color).multiplyScalar(bright);
+ mesh.setColorAt(i, this._col);
+ n._colorDirty = false;
+ }
+ }
+ mesh.count = nodes.length;
+ mesh.instanceMatrix.needsUpdate = true;
+ if (full && mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ else if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ }
+ this.syncEdgePositions();
+ }
+
+ syncEdgePositions() {
+ if (!this.edgeObj) return;
+ const pos = this.edgeObj.geometry.attributes.position.array;
+ let k = 0;
+ for (const e of this.edges) {
+ const a = e.a, b = e.b;
+ const show = a.visible && b.visible ? 1 : 0;
+ pos[k++] = a.x * show; pos[k++] = a.y * show; pos[k++] = a.z * show;
+ pos[k++] = b.x * show; pos[k++] = b.y * show; pos[k++] = b.z * show;
+ }
+ this.edgeObj.geometry.attributes.position.needsUpdate = true;
+ }
+
+ startLoop() {
+ if (this._raf || this.mode !== '3d' || !this.scene) return;
+ const tick = () => {
+ this._raf = requestAnimationFrame(tick);
+ if (this.controls) this.controls.update();
+ // Only resync matrices when something is animating (bloom/pulse/drag).
+ const animating = this.dragging || this.nodes.some((n) => n.bornAt || n.pulseAt);
+ if (animating) this.syncInstances(false);
+ if (this.coreRing && !this._reduce) this.coreRing.rotation.z += 0.0015;
+ this.positionAvatarDepth();
+ this.renderer.render(this.scene, this.camera);
+ };
+ this._raf = requestAnimationFrame(tick);
+ }
+
+ stopLoop() {
+ if (this._raf) cancelAnimationFrame(this._raf);
+ this._raf = null;
+ }
+
+ positionAvatarDepth() {
+ // The avatar overlay sits at the projected origin. With pan disabled and
+ // target=origin it stays at screen-centre, but project precisely so it
+ // tracks during damping.
+ if (!this.el.avatar || !this.camera) return;
+ this._tmp.set(0, 0, 0).project(this.camera);
+ const x = (this._tmp.x * 0.5 + 0.5) * 100;
+ const y = (-this._tmp.y * 0.5 + 0.5) * 100;
+ this.el.avatar.style.left = x + '%';
+ this.el.avatar.style.top = y + '%';
+ }
+
+ resize() {
+ if (this.mode !== '3d' || !this.renderer) return;
+ const w = this.root.clientWidth || 800;
+ const h = this.root.clientHeight || 520;
+ this.renderer.setSize(w, h, false);
+ this.camera.aspect = w / h;
+ this.camera.updateProjectionMatrix();
+ }
+
+ // ── Pointer: hover, click, drag-to-pin, flick-to-forget ────────────────────
+
+ bindPointer() {
+ const c = this.el.canvas;
+ c.style.pointerEvents = 'auto';
+ this._onMove = (ev) => this.onPointerMove(ev);
+ this._onDown = (ev) => this.onPointerDown(ev);
+ this._onUp = (ev) => this.onPointerUp(ev);
+ c.addEventListener('pointermove', this._onMove);
+ c.addEventListener('pointerdown', this._onDown);
+ window.addEventListener('pointerup', this._onUp);
+ }
+
+ pickNode(ev) {
+ const rect = this.el.canvas.getBoundingClientRect();
+ this.pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
+ this.pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
+ this.raycaster.setFromCamera(this.pointer, this.camera);
+ for (const t of ALL_TYPES) {
+ const inst = this.instanced[t];
+ if (!inst || !inst.nodes.length) continue;
+ const hits = this.raycaster.intersectObject(inst.mesh);
+ for (const hit of hits) {
+ const n = inst.nodes[hit.instanceId];
+ if (n && n.visible) return { node: n, point: hit.point };
+ }
+ }
+ return null;
+ }
+
+ onPointerMove(ev) {
+ if (this._press && !this.dragging) this.maybeStartDrag(ev);
+ if (this.dragging) { this.dragMove(ev); return; }
+ const hit = this.pickNode(ev);
+ if (hit) {
+ this.el.canvas.style.cursor = 'grab';
+ this.showTip(hit.node, ev);
+ } else {
+ this.el.canvas.style.cursor = '';
+ this.hideTip();
+ }
+ }
+
+ onPointerDown(ev) {
+ const hit = this.pickNode(ev);
+ if (!hit) return;
+ ev.preventDefault();
+ this._press = { node: hit.node, x: ev.clientX, y: ev.clientY, moved: false, t: now() };
+ // Set a drag plane through the node, facing the camera.
+ this.camera.getWorldDirection(this._tmp);
+ this.dragPlane.setFromNormalAndCoplanarPoint(this._tmp.clone().negate(), new THREE.Vector3(hit.node.x, hit.node.y, hit.node.z));
+ }
+
+ dragMove(ev) {
+ const rect = this.el.canvas.getBoundingClientRect();
+ this.pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
+ this.pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
+ this.raycaster.setFromCamera(this.pointer, this.camera);
+ const hitP = new THREE.Vector3();
+ if (this.raycaster.ray.intersectPlane(this.dragPlane, hitP)) {
+ const n = this.dragging;
+ n.x = hitP.x; n.y = hitP.y; n.z = hitP.z;
+ }
+ // Arm + highlight the forget well when the pointer is over it.
+ const fr = this.el.forget.getBoundingClientRect();
+ const over = ev.clientX >= fr.left && ev.clientX <= fr.right && ev.clientY >= fr.top && ev.clientY <= fr.bottom;
+ this.el.forget.classList.toggle('hot', over);
+ // Glow the core ring when near centre (pin zone).
+ const dist = Math.hypot(this.dragging.x, this.dragging.y, this.dragging.z);
+ if (this.coreRing) this.coreRing.material.opacity = dist < INNER_R + 1.2 ? 0.4 : 0.14;
+ }
+
+ onPointerUp(ev) {
+ if (this.dragging) {
+ const n = this.dragging;
+ this.dragging = null;
+ this.el.canvas.style.cursor = '';
+ this.el.forget.classList.remove('armed', 'hot');
+ if (this.coreRing) this.coreRing.material.opacity = 0.14;
+ const fr = this.el.forget.getBoundingClientRect();
+ const overForget = ev.clientX >= fr.left && ev.clientX <= fr.right && ev.clientY >= fr.top && ev.clientY <= fr.bottom;
+ const dist = Math.hypot(n.x, n.y, n.z);
+ if (overForget) {
+ this.forget(n);
+ } else if (dist < INNER_R + 1.0) {
+ this.pin(n, true);
+ this.resetNodePos(n);
+ } else {
+ this.resetNodePos(n);
+ }
+ return;
+ }
+ if (this._press) {
+ const p = this._press;
+ this._press = null;
+ const moved = Math.hypot(ev.clientX - p.x, ev.clientY - p.y);
+ if (moved < 5 && now() - p.t < 500) this.openInspector(p.node.mem.id);
+ }
+ }
+
+ resetNodePos(n) {
+ const pos = this.layoutPosition(n.mem, n.type);
+ n.x = pos.x; n.y = pos.y; n.z = pos.z; n.baseR = pos.r;
+ n._colorDirty = true;
+ this.syncInstances(false);
+ }
+
+ // Promote a drag into a real drag once it crosses threshold (called from move
+ // while a press is active but not yet dragging).
+ maybeStartDrag(ev) {
+ if (!this._press || this.dragging) return;
+ const moved = Math.hypot(ev.clientX - this._press.x, ev.clientY - this._press.y);
+ if (moved > 6) {
+ this.dragging = this._press.node;
+ this.el.canvas.style.cursor = 'grabbing';
+ this.el.forget.classList.add('armed');
+ this.hideTip();
+ }
+ }
+
+ showTip(node, ev) {
+ const m = node.mem;
+ const rect = this.root.getBoundingClientRect();
+ this.el.tip.innerHTML = `<div class="t" style="color:${TYPES[node.type].hex}">${esc(TYPES[node.type].label)} · ${Math.round((m.salience || 0) * 100)}%</div>${esc(truncate(m.content, 120))}${(m.tags || []).length ? `<div class="s">#${(m.tags || []).slice(0, 4).map(esc).join(' #')}</div>` : ''}`;
+ this.el.tip.style.left = ev.clientX - rect.left + 'px';
+ this.el.tip.style.top = ev.clientY - rect.top + 'px';
+ this.el.tip.classList.add('show');
+ }
+
+ hideTip() { this.el.tip.classList.remove('show'); }
+
+ // ── Curation actions (real API via memory-client) ──────────────────────────
+
+ // Build a complete upsert entry from a decorated record so a PATCH never drops
+ // fields (the server upsert overwrites with whatever it receives).
+ entryFrom(mem, overrides = {}) {
+ return {
+ id: mem.id,
+ type: mem.type,
+ content: mem.content,
+ tags: mem.tags || [],
+ context: mem.context || {},
+ salience: mem.salience,
+ pinned: !!mem.pinned,
+ createdAt: mem.createdAt,
+ expiresAt: mem.expiresAt ?? null,
+ ...overrides,
+ };
+ }
+
+ async pin(node, on) {
+ const m = node.mem;
+ const prev = { salience: m.salience, pinned: m.pinned };
+ // Optimistic: pinning lifts salience toward the core.
+ const nextSal = on ? Math.max(m.salience || 0, 0.85) : Math.min(m.salience ?? 0.5, 0.5);
+ m.pinned = on; m.salience = nextSal;
+ node._colorDirty = true;
+ this.resetNodePos(node);
+ this.refreshInspectorIf(m.id);
+ this.updateCardFor(node);
+ try {
+ const updated = await updateMemory(this.agentId, this.entryFrom(m, { pinned: on, salience: nextSal }));
+ if (updated) Object.assign(m, updated);
+ this.flashHint(on ? 'Pinned to the core — your agent will keep this close.' : 'Unpinned.');
+ } catch (err) {
+ m.pinned = prev.pinned; m.salience = prev.salience; // rollback
+ node._colorDirty = true; this.resetNodePos(node); this.refreshInspectorIf(m.id); this.updateCardFor(node);
+ this.flashHint(`Could not pin: ${err.message}`, true);
+ }
+ }
+
+ async setSalience(node, value) {
+ const m = node.mem;
+ const prev = m.salience;
+ m.salience = clamp01(value);
+ node._colorDirty = true;
+ this.resetNodePos(node);
+ this.updateCardFor(node);
+ try {
+ const updated = await updateMemory(this.agentId, this.entryFrom(m, { salience: m.salience }));
+ if (updated) Object.assign(m, updated);
+ } catch (err) {
+ m.salience = prev; node._colorDirty = true; this.resetNodePos(node); this.updateCardFor(node);
+ this.flashHint(`Could not change salience: ${err.message}`, true);
+ }
+ }
+
+ // Flick-to-forget = schedule expiry (reversible). We set expires_at to now so
+ // the memory is excluded from future recall and visibly leaves the scene, but
+ // the row survives until the server's sweep — undo simply clears expires_at.
+ async forget(node) {
+ const m = node.mem;
+ const prevExpiry = m.expiresAt ?? null;
+ const expireAt = Date.now();
+ // Optimistic remove from the scene.
+ node.visible = false;
+ this.removeNodeFromScene(node);
+ if (this.selectedId === m.id) this.closeInspector();
+ try {
+ const updated = await updateMemory(this.agentId, this.entryFrom(m, { expiresAt: expireAt }));
+ if (updated) Object.assign(m, updated);
+ this.showUndo(`Forgot “${truncate(m.content, 40)}”`, async () => {
+ try {
+ const restored = await updateMemory(this.agentId, this.entryFrom(m, { expiresAt: prevExpiry }));
+ if (restored) Object.assign(m, restored);
+ node.visible = true;
+ this.restoreNodeToScene(node);
+ this.flashHint('Restored.');
+ } catch (err) {
+ this.flashHint(`Could not restore: ${err.message}`, true);
+ }
+ });
+ } catch (err) {
+ node.visible = true;
+ this.restoreNodeToScene(node);
+ this.flashHint(`Could not forget: ${err.message}`, true);
+ }
+ }
+
+ // Hard delete — used from the inspector "Delete forever" action.
+ async deleteForever(node) {
+ const m = node.mem;
+ const snapshot = { ...m };
+ node.visible = false;
+ this.removeNodeFromScene(node);
+ if (this.selectedId === m.id) this.closeInspector();
+ try {
+ await forgetMemory(this.agentId, m.id);
+ this.showUndo(`Deleted “${truncate(m.content, 40)}”`, async () => {
+ try {
+ // Re-create from the snapshot (new id assigned by the server).
+ const recreated = await import('./agents/memory-client.js').then((mod) =>
+ mod.addMemory(this.agentId, {
+ type: snapshot.type, content: snapshot.content, tags: snapshot.tags,
+ context: snapshot.context, salience: snapshot.salience, pinned: snapshot.pinned,
+ })
+ );
+ if (recreated) { this.byId.delete(m.id); this.addNode(recreated, { bloom: true }); this.computeEdges(); this.rebuild(); }
+ this.flashHint('Restored as a new memory.');
+ } catch (err) {
+ this.flashHint(`Could not restore: ${err.message}`, true);
+ }
+ });
+ } catch (err) {
+ node.visible = true; this.restoreNodeToScene(node);
+ this.flashHint(`Could not delete: ${err.message}`, true);
+ }
+ }
+
+ removeNodeFromScene(node) {
+ node._colorDirty = true;
+ if (this.mode === '3d' && this.scene) this.syncInstances(false);
+ this.updateStat();
+ this.removeCardFor(node);
+ this.rebuildRoster();
+ }
+ restoreNodeToScene(node) {
+ node.bornAt = this._reduce ? 0 : now();
+ node._colorDirty = true;
+ if (this.mode === '3d' && this.scene) { this.syncInstances(false); this.startLoop(); }
+ this.rebuild2D(); this.rebuildRoster(); this.updateStat();
+ }
+
+ // ── Filtering / sorting (client-side, debounced) ────────────────────────────
+
+ applyFilter() {
+ const q = this.filter.q;
+ for (const n of this.nodes) {
+ if (!this.byId.has(n.mem.id)) continue;
+ const m = n.mem;
+ let vis = this.filter.types.has(n.type);
+ if (vis && m.expiresAt && m.expiresAt < Date.now()) vis = false; // forgotten
+ if (vis && q) {
+ const hay = (m.content + ' ' + (m.tags || []).join(' ') + ' ' + n.type).toLowerCase();
+ vis = hay.includes(q);
+ }
+ if (vis && this.timeCursor < 1) {
+ const cut = this.tMin + (this.tMax - this.tMin) * this.timeCursor;
+ if (m.createdAt > cut) vis = false;
+ }
+ n.visible = vis;
+ n._colorDirty = true;
+ }
+ if (this.mode === '3d' && this.scene) this.syncInstances(false);
+ this.rebuild2D();
+ this.rebuildRoster();
+ this.updateStat();
+ }
+
+ sortedVisible() {
+ const arr = this.nodes.filter((n) => n.visible);
+ const s = this.filter.sort;
+ arr.sort((a, b) => {
+ if (s === 'recent') return b.mem.createdAt - a.mem.createdAt;
+ if (s === 'oldest') return a.mem.createdAt - b.mem.createdAt;
+ if (s === 'accessed') return (b.mem.accessCount || 0) - (a.mem.accessCount || 0);
+ return (b.mem.salience || 0) - (a.mem.salience || 0);
+ });
+ return arr;
+ }
+
+ updateStat() {
+ const vis = this.nodes.filter((n) => n.visible).length;
+ const total = this.byId.size;
+ const pinned = this.nodes.filter((n) => n.mem.pinned).length;
+ this.el.stat.innerHTML = `<b>${vis}</b> shown · ${total} total · <b>${pinned}</b> pinned`;
+ }
+
+ // ── Timeline scrub ──────────────────────────────────────────────────────────
+
+ toggleTimeline() {
+ const on = !this.el.time.classList.contains('show');
+ this.el.time.classList.toggle('show', on);
+ this.el.timelineBtn.setAttribute('aria-pressed', on ? 'true' : 'false');
+ if (!on) { this.timeCursor = 1; this.el.timeRange.value = 1000; this.applyFilter(); this.el.timeLbl.textContent = 'now'; }
+ }
+
+ applyTimeCursor() {
+ const cut = this.tMin + (this.tMax - this.tMin) * this.timeCursor;
+ this.el.timeLbl.textContent = this.timeCursor >= 1 ? 'now' : new Date(cut).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
+ this.applyFilter();
+ }
+
+ playTimeline() {
+ if (this._playing) { this._playing = false; this.el.timePlay.textContent = '▶'; return; }
+ this._playing = true;
+ this.el.timePlay.textContent = '⏸';
+ const dur = this._reduce ? 0 : 4200;
+ const start = now();
+ const from = this.timeCursor < 1 ? this.timeCursor : 0;
+ const step = () => {
+ if (!this._playing || this._disposed) return;
+ const p = dur ? Math.min(1, (now() - start) / dur) : 1;
+ this.timeCursor = from + (1 - from) * p;
+ this.el.timeRange.value = Math.round(this.timeCursor * 1000);
+ this.applyTimeCursor();
+ if (p < 1) requestAnimationFrame(step);
+ else { this._playing = false; this.el.timePlay.textContent = '▶'; }
+ };
+ requestAnimationFrame(step);
+ }
+
+ // ── 2D fallback ─────────────────────────────────────────────────────────────
+
+ setMode(mode) {
+ if (mode === this.mode) return;
+ this.mode = mode;
+ this.root.classList.toggle('mode-2d', mode === '2d');
+ this.root.classList.toggle('mode-3d', mode === '3d');
+ this.el.modeBtn.setAttribute('aria-pressed', mode === '2d' ? 'true' : 'false');
+ this.el.modeBtn.textContent = mode === '2d' ? '◉ 3D' : '▦ 2D';
+ if (mode === '3d') {
+ this.ensureScene().then(() => { this.rebuildInstances(); this.applyFilter(); this.startLoop(); });
+ } else {
+ this.stopLoop();
+ this.rebuild2D();
+ }
+ }
+
+ rebuild2D() {
+ if (!this.el.grid2d) return;
+ const grid = this.el.grid2d;
+ const visible = this.sortedVisible();
+ if (!this.byId.size) { grid.innerHTML = ''; return; }
+ // Group by type for legibility (constellations as sections).
+ const frag = document.createDocumentFragment();
+ const byType = {};
+ for (const n of visible) (byType[n.type] ||= []).push(n);
+ for (const t of ALL_TYPES) {
+ const list = byType[t];
+ if (!list || !list.length) continue;
+ const sec = document.createElement('div');
+ sec.className = 'mp-2d-sec';
+ sec.textContent = `${TYPES[t].label} · ${list.length}`;
+ frag.appendChild(sec);
+ for (const n of list) frag.appendChild(this.cardEl(n));
+ }
+ grid.innerHTML = '';
+ grid.appendChild(frag);
+ }
+
+ cardEl(n) {
+ const m = n.mem;
+ const card = document.createElement('button');
+ card.className = 'mp-card';
+ card.dataset.id = m.id;
+ card.style.borderLeftColor = TYPES[n.type].hex;
+ const pct = Math.round((m.salience || 0) * 100);
+ const expiring = m.expiresAt && m.expiresAt < Date.now() + 1000 * 60 * 60 * 24 * 7;
+ if (expiring) card.classList.add('dim');
+ card.innerHTML = `
+ ${m.pinned ? '<span class="pin" title="Pinned">📌</span>' : ''}
+ <div class="ctop"><span class="dot" style="display:inline-block;width:9px;height:9px;border-radius:2px;background:${TYPES[n.type].hex}"></span><span style="color:${TYPES[n.type].hex}">${esc(TYPES[n.type].label)}</span><span class="pct">${pct}%</span></div>
+ <div class="ctxt">${esc(m.content || '')}</div>
+ <div class="cbar"><i style="width:${pct}%;background:${TYPES[n.type].hex}"></i></div>
+ ${(m.tags || []).length ? `<div class="ctags">${(m.tags || []).slice(0, 5).map((x) => `<span>#${esc(x)}</span>`).join('')}</div>` : ''}`;
+ card.addEventListener('click', () => this.openInspector(m.id));
+ return card;
+ }
+
+ updateCardFor(node) {
+ if (this.mode !== '2d') return;
+ const old = this.el.grid2d.querySelector(`.mp-card[data-id="${cssEsc(node.mem.id)}"]`);
+ if (old) old.replaceWith(this.cardEl(node));
+ }
+ removeCardFor(node) {
+ const old = this.el.grid2d?.querySelector(`.mp-card[data-id="${cssEsc(node.mem.id)}"]`);
+ if (old) old.remove();
+ }
+
+ // ── Keyboard roster (a11y) — a real, operable mirror of the scene ──────────
+
+ rebuildRoster() {
+ const list = this.el.rosterList;
+ const visible = this.sortedVisible();
+ list.innerHTML = '';
+ visible.forEach((n, i) => {
+ const li = document.createElement('li');
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.dataset.id = n.mem.id;
+ b.tabIndex = i === 0 ? 0 : -1;
+ b.setAttribute('aria-label', `${TYPES[n.type].label} memory, salience ${Math.round((n.mem.salience || 0) * 100)} percent${n.mem.pinned ? ', pinned' : ''}: ${truncate(n.mem.content, 90)}`);
+ b.innerHTML = `<span class="rdot" style="background:${TYPES[n.type].hex}"></span><span>${esc(truncate(n.mem.content, 60))}</span>`;
+ b.addEventListener('click', () => this.openInspector(n.mem.id));
+ li.appendChild(b);
+ list.appendChild(li);
+ });
+ this.focusIdx = visible.length ? 0 : -1;
+ }
+
+ rosterButtons() { return [...this.el.rosterList.querySelectorAll('button')]; }
+
+ moveFocus(idx) {
+ const btns = this.rosterButtons();
+ if (!btns.length) return;
+ this.focusIdx = (idx + btns.length) % btns.length;
+ btns.forEach((b, i) => { b.tabIndex = i === this.focusIdx ? 0 : -1; b.classList.toggle('focus', i === this.focusIdx); });
+ const b = btns[this.focusIdx];
+ b.focus();
+ // Frame the focused node in the scene.
+ const n = this.byId.get(b.dataset.id);
+ if (n && this.selectedId !== n.mem.id) { this.selectedId = n.mem.id; n._colorDirty = true; if (this.scene) this.syncInstances(false); }
+ }
+
+ onRosterKey(ev) {
+ const btns = this.rosterButtons();
+ if (!btns.length) return;
+ const cur = this.byId.get(document.activeElement?.dataset?.id);
+ if (ev.key === 'ArrowDown' || ev.key === 'ArrowRight') { ev.preventDefault(); this.moveFocus(this.focusIdx + 1); }
+ else if (ev.key === 'ArrowUp' || ev.key === 'ArrowLeft') { ev.preventDefault(); this.moveFocus(this.focusIdx - 1); }
+ else if (ev.key === 'Home') { ev.preventDefault(); this.moveFocus(0); }
+ else if (ev.key === 'End') { ev.preventDefault(); this.moveFocus(btns.length - 1); }
+ else if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); if (cur) this.openInspector(cur.mem.id); }
+ else if ((ev.key === 'p' || ev.key === 'P') && cur) { ev.preventDefault(); this.pin(cur, !cur.mem.pinned); }
+ else if ((ev.key === 'Delete' || ev.key === 'Backspace') && cur) { ev.preventDefault(); this.forget(cur); }
+ else if (ev.key === 'g' && cur) {
+ // Graph-walk: jump to the strongest tag-neighbour.
+ ev.preventDefault();
+ const neigh = (this.adj.get(cur.mem.id) || []).filter((x) => x.node.visible).sort((a, b) => b.w - a.w)[0];
+ if (neigh) { const idx = btns.findIndex((b) => b.dataset.id === neigh.node.mem.id); if (idx >= 0) this.moveFocus(idx); }
+ }
+ }
+
+ // ── Inspector ───────────────────────────────────────────────────────────────
+
+ openInspector(id) {
+ const node = this.byId.get(id);
+ if (!node) return;
+ this.selectedId = id;
+ node._colorDirty = true;
+ if (this.scene) this.syncInstances(false);
+ const m = node.mem;
+ const ty = TYPES[node.type];
+ const created = m.createdAt ? new Date(m.createdAt) : null;
+ const related = (this.adj.get(id) || [])
+ .filter((x) => x.node.visible)
+ .sort((a, b) => b.w - a.w)
+ .slice(0, 6);
+ const prov = this.provenanceHTML(m);
+ const ctx = m.context && Object.keys(m.context).length
+ ? `<h4>Context</h4><div class="mp-context">${esc(JSON.stringify(m.context, null, 2))}</div>` : '';
+ this.el.inspect.hidden = false;
+ this.el.inspect.innerHTML = `
+<div class="mp-inspect-hd">
+ <span class="badge" style="background:${ty.hex}22;color:${ty.hex};border:1px solid ${ty.hex}55">${esc(ty.label)}</span>
+ <span style="font-size:.74rem;color:rgba(255,255,255,.55)">${Math.round((m.salience || 0) * 100)}% salient${m.pinned ? ' · 📌 pinned' : ''}</span>
+ <button class="x" aria-label="Close" id="mp-x">×</button>
+</div>
+<div class="mp-inspect-bd">
+ <div class="mp-inspect-content">${esc(m.content || '')}</div>
+ ${(m.tags || []).length ? `<h4>Tags</h4><div>${(m.tags || []).map((t) => `<button class="mp-tag" data-tag="${esc(t)}">#${esc(t)}</button>`).join('')}</div>` : ''}
+ <h4>Salience</h4>
+ <input type="range" id="mp-sal" min="0" max="100" value="${Math.round((m.salience || 0) * 100)}" style="width:100%;accent-color:${ty.hex}" aria-label="Adjust salience" />
+ <h4>Details</h4>
+ <dl class="mp-meta-grid">
+ <dt>Created</dt><dd>${created ? esc(created.toLocaleString()) : '—'}</dd>
+ <dt>Recalled</dt><dd>${m.accessCount || 0}×</dd>
+ <dt>Tier</dt><dd>${esc(m.tier || 'recall')}</dd>
+ <dt>Visibility</dt><dd>${m.isPublic ? 'Public' : 'Private'}</dd>
+ ${m.expiresAt ? `<dt>Expires</dt><dd>${esc(new Date(m.expiresAt).toLocaleString())}</dd>` : ''}
+ <dt>Indexed</dt><dd>${m.hasEmbedding ? 'embedded' : 'pending'}</dd>
+ </dl>
+ ${ctx}
+ ${prov}
+ ${related.length ? `<h4>Why your agent connects this</h4><div class="mp-related">${related.map((r) => `
+ <button data-goto="${esc(r.node.mem.id)}"><span class="rdot" style="background:${TYPES[r.node.type].hex}"></span><span>${esc(truncate(r.node.mem.content, 54))}</span><span class="rwhy">${sharedTags(m, r.node.mem)}</span></button>`).join('')}</div>` : ''}
+</div>
+<div class="mp-inspect-actions">
+ <button class="mp-action pin" id="mp-pin" aria-pressed="${m.pinned ? 'true' : 'false'}">${m.pinned ? '📌 Pinned' : '📌 Pin to core'}</button>
+ <button class="mp-action forget" id="mp-forget-btn">🗑 Forget</button>
+ <button class="mp-action forget" id="mp-del-btn" title="Permanently delete (with undo)">Delete forever</button>
+</div>`;
+ requestAnimationFrame(() => this.el.inspect.classList.add('open'));
+ const q = (s) => this.el.inspect.querySelector(s);
+ q('#mp-x').addEventListener('click', () => this.closeInspector());
+ q('#mp-pin').addEventListener('click', () => this.pin(node, !node.mem.pinned).then(() => this.refreshInspectorIf(id)));
+ q('#mp-forget-btn').addEventListener('click', () => this.forget(node));
+ q('#mp-del-btn').addEventListener('click', () => this.deleteForever(node));
+ const sal = q('#mp-sal');
+ let salDebounce;
+ sal.addEventListener('input', () => { clearTimeout(salDebounce); salDebounce = setTimeout(() => this.setSalience(node, Number(sal.value) / 100), 200); });
+ this.el.inspect.querySelectorAll('.mp-tag').forEach((b) => b.addEventListener('click', () => {
+ this.el.q.value = b.dataset.tag; this.filter.q = b.dataset.tag.toLowerCase(); this.applyFilter(); this.closeInspector();
+ }));
+ this.el.inspect.querySelectorAll('[data-goto]').forEach((b) => b.addEventListener('click', () => this.openInspector(b.dataset.goto)));
+ }
+
+ refreshInspectorIf(id) { if (this.selectedId === id && this.el.inspect.classList.contains('open')) this.openInspector(id); }
+
+ provenanceHTML(m) {
+ const c = m.context || {};
+ const src = c.source || c.origin || c.via;
+ const conv = c.conversationId || c.conversation_id || c.threadId;
+ const url = c.url || c.href;
+ const links = [];
+ if (conv) links.push(`<a href="/agent/${esc(this.agentId)}?conversation=${esc(conv)}">the conversation that formed it →</a>`);
+ if (url && /^https?:\/\//.test(url)) links.push(`<a href="${esc(url)}" target="_blank" rel="noopener">source page →</a>`);
+ if (!src && !links.length) return '';
+ return `<h4>Provenance</h4><div class="mp-prov">${src ? `Formed via <b>${esc(src)}</b>. ` : ''}${links.join(' · ')}</div>`;
+ }
+
+ closeInspector() {
+ this.el.inspect.classList.remove('open');
+ const prev = this.selectedId;
+ this.selectedId = null;
+ const n = this.byId.get(prev);
+ if (n) { n._colorDirty = true; if (this.scene) this.syncInstances(false); }
+ setTimeout(() => { if (!this.el.inspect.classList.contains('open')) this.el.inspect.hidden = true; }, 300);
+ }
+
+ // ── Undo toast ────────────────────────────────────────────────────────────
+
+ showUndo(label, onUndo) {
+ clearTimeout(this._undoTimer);
+ this.el.toast.innerHTML = `<span>${esc(label)}</span><button id="mp-undo">Undo</button>`;
+ this.el.toast.classList.add('show');
+ this.el.toast.querySelector('#mp-undo').addEventListener('click', () => {
+ this.el.toast.classList.remove('show');
+ clearTimeout(this._undoTimer);
+ onUndo();
+ });
+ this._undoTimer = setTimeout(() => this.el.toast.classList.remove('show'), 7000);
+ }
+
+ flashHint(msg, isError = false) {
+ this.el.hint.textContent = msg;
+ this.el.hint.style.color = isError ? '#f7a8c4' : 'rgba(255,255,255,.62)';
+ this.el.hint.style.opacity = '1';
+ clearTimeout(this._hintTimer);
+ this._hintTimer = setTimeout(() => { this.el.hint.style.opacity = '0'; }, 3200);
+ }
+
+ // ── Live bus ────────────────────────────────────────────────────────────────
+
+ subscribeBus() {
+ const mine = (p) => !p.agentId || p.agentId === this.agentId;
+ this._busOff.push(agentBus.on(EVENTS.MEMORY_ADDED, (p) => {
+ if (!mine(p) || !p.memory) return;
+ if (this.byId.has(p.memory.id)) return;
+ if (this.el.overlay && !this.el.overlay.hidden) this.hideOverlay();
+ this.addNode(p.memory, { bloom: true });
+ this.computeEdges();
+ if (this.mode === '3d' && this.scene) { this.rebuildInstances(); this.startLoop(); }
+ this.rebuild2D(); this.rebuildRoster(); this.updateStat();
+ this.flashHint('A new memory just formed.');
+ }));
+ this._busOff.push(agentBus.on(EVENTS.MEMORY_RECALLED, (p) => {
+ if (!mine(p)) return;
+ const mems = p.memories || [];
+ let any = false;
+ for (const rm of mems) {
+ const n = this.byId.get(rm.id);
+ if (n) { n.pulseAt = now(); n._colorDirty = true; any = true; }
+ }
+ if (any && this.mode === '3d' && this.scene) this.startLoop();
+ if (any) this.flashHint(`Recalled ${mems.length} ${mems.length === 1 ? 'memory' : 'memories'}${p.query ? ` for “${truncate(p.query, 30)}”` : ''}.`);
+ }));
+ this._busOff.push(agentBus.on(EVENTS.MEMORY_UPDATED, (p) => {
+ if (!mine(p) || !p.memory) return;
+ const n = this.byId.get(p.memory.id);
+ if (!n) return;
+ Object.assign(n.mem, p.memory);
+ n._colorDirty = true;
+ this.resetNodePos(n);
+ this.updateCardFor(n);
+ this.refreshInspectorIf(p.memory.id);
+ }));
+ this._busOff.push(agentBus.on(EVENTS.MEMORY_FORGOTTEN, (p) => {
+ if (!mine(p)) return;
+ const n = this.byId.get(p.memoryId);
+ if (!n) return;
+ n.visible = false;
+ this.byId.delete(p.memoryId);
+ this.removeNodeFromScene(n);
+ }));
+ }
+
+ // ── Overlays ─────────────────────────────────────────────────────────────────
+
+ showOverlay(kind, detail = '') {
+ const o = this.el.overlay;
+ o.hidden = false;
+ if (kind === 'loading') {
+ o.innerHTML = `<div class="mp-orb"></div><h3>Entering the mind…</h3><p>Reading every memory your agent holds.</p>`;
+ } else if (kind === 'empty') {
+ const chatHref = `/agent/${esc(this.agentId)}`;
+ const addCta = this.embedded
+ ? `<button class="primary" id="mp-empty-add">Add the first memory</button>`
+ : `<a class="primary" href="/agent/${esc(this.agentId)}/edit?tab=knowledge">Add the first memory</a>`;
+ o.innerHTML = `<div class="mp-orb" style="opacity:.5"></div>
+ <h3>This mind is a blank canvas</h3>
+ <p>Your agent hasn't formed any memories yet. Talk to it and watch its mind grow — every fact, preference, and lesson becomes an object you can see and shape here.</p>
+ <div class="cta"><a class="primary" href="${chatHref}">Start a conversation</a>${addCta}</div>`;
+ const add = o.querySelector('#mp-empty-add');
+ if (add) add.addEventListener('click', () => {
+ this.host.dispatchEvent(new CustomEvent('mind:add-memory', { bubbles: true }));
+ });
+ } else if (kind === 'error') {
+ o.innerHTML = `<h3>The mind is out of reach</h3>
+ <p>We couldn't load this agent's memories. This is usually a network hiccup or an expired session.</p>
+ <div class="mp-err-detail">${esc(detail)}</div>
+ <div class="cta"><button class="primary" id="mp-retry">Try again</button></div>`;
+ o.querySelector('#mp-retry').addEventListener('click', () => this.load());
+ }
+ }
+ hideOverlay() { this.el.overlay.hidden = true; this.el.overlay.innerHTML = ''; }
+
+ // ── Teardown ─────────────────────────────────────────────────────────────────
+
+ destroy() {
+ this._disposed = true;
+ this.stopLoop();
+ for (const off of this._busOff) { try { off(); } catch {} }
+ this._busOff = [];
+ if (this._io) this._io.disconnect();
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('pointerup', this._onUp);
+ if (this.controls) this.controls.dispose();
+ if (this.scene) {
+ this.scene.traverse((o) => {
+ if (o.geometry) o.geometry.dispose();
+ if (o.material) { const m = o.material; (Array.isArray(m) ? m : [m]).forEach((x) => x.dispose()); }
+ });
+ }
+ if (this.renderer) { this.renderer.dispose(); this.renderer.forceContextLoss?.(); }
+ if (this._reservedCtx) { releaseWebGLContext(); this._reservedCtx = false; }
+ if (this.avatarEl?.remove) this.avatarEl.remove();
+ this.host.innerHTML = '';
+ }
+}
+
+// ── small utils ────────────────────────────────────────────────────────────────
+function now() { return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now(); }
+function clamp01(v) { return Math.max(0, Math.min(1, Number(v) || 0)); }
+function easeOut(t) { return 1 - Math.pow(1 - t, 3); }
+function truncate(s, n) { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; }
+function cssEsc(s) { return String(s).replace(/["\\]/g, '\\$&'); }
+function sharedTags(a, b) {
+ const sb = new Set((b.tags || []).map((x) => String(x).toLowerCase()));
+ const shared = (a.tags || []).filter((x) => sb.has(String(x).toLowerCase()));
+ return shared.length ? '#' + shared.slice(0, 2).map(esc).join(' #') : 'related';
+}
+
+export default mountMindPalace;
diff --git a/src/proof-of-custody/merkle.js b/src/proof-of-custody/merkle.js
new file mode 100644
index 000000000..442817c5d
--- /dev/null
+++ b/src/proof-of-custody/merkle.js
@@ -0,0 +1,199 @@
+/**
+ * Proof-of-Custody — canonical leaf encoding + Merkle tree.
+ *
+ * This is the SINGLE source of truth for how a custodial-wallet attestation is
+ * hashed. The server prover (api/_lib/custody-proof.js) and the in-browser
+ * independent verifier (src/proof-of-custody/verifier.js) both import THIS file,
+ * so the leaf encoding and the tree construction can never drift between the
+ * side that builds a proof and the side that checks it. Any change here is a
+ * change to both at once, and the golden tests in tests/custody-merkle.test.js
+ * pin the exact bytes.
+ *
+ * Isomorphic by design: it uses only `globalThis.crypto.subtle` (Web Crypto),
+ * which is present in modern browsers and in the Node runtime the API functions
+ * run on — no Node-only (`node:crypto`) or browser-only imports — so the exact
+ * same module loads in a Vite bundle and in a Vercel function.
+ *
+ * Domain separation: leaf hashes are prefixed with 0x00 and internal nodes with
+ * 0x01 before hashing, so no internal node can ever be reinterpreted as a leaf
+ * (second-preimage hardening, the standard Certificate-Transparency convention).
+ */
+
+export const LEAF_DOMAIN = 'threews-custody-leaf:v1';
+const LEAF_PREFIX = 0x00;
+const NODE_PREFIX = 0x01;
+
+const enc = new TextEncoder();
+
+/** Resolve Web Crypto's SubtleCrypto in either runtime, or throw clearly. */
+function subtle() {
+ const s = globalThis.crypto && globalThis.crypto.subtle;
+ if (!s) {
+ throw new Error('Web Crypto SubtleCrypto unavailable — cannot hash custody leaves');
+ }
+ return s;
+}
+
+/** Lowercase hex of a byte array. */
+export function bytesToHex(bytes) {
+ let out = '';
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, '0');
+ return out;
+}
+
+/** Parse a 64-char lowercase/uppercase hex string into a 32-byte Uint8Array. */
+export function hexToBytes(hex) {
+ const h = String(hex || '').trim().toLowerCase();
+ if (!/^[0-9a-f]*$/.test(h) || h.length % 2 !== 0) {
+ throw new Error('invalid hex string');
+ }
+ const out = new Uint8Array(h.length / 2);
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
+ return out;
+}
+
+async function sha256(bytes) {
+ const digest = await subtle().digest('SHA-256', bytes);
+ return new Uint8Array(digest);
+}
+
+function concatBytes(...arrays) {
+ let total = 0;
+ for (const a of arrays) total += a.length;
+ const out = new Uint8Array(total);
+ let off = 0;
+ for (const a of arrays) { out.set(a, off); off += a.length; }
+ return out;
+}
+
+/**
+ * Canonical, injective preimage string for one custodial wallet at one epoch.
+ * Fields are newline-joined under a versioned domain header. Every field is a
+ * value with no newline (uuid, base58 address, decimal integer, ledger-head
+ * token, integer epoch), so the join is unambiguous and reproducible byte-for-
+ * byte on both server and client.
+ *
+ * @param {object} f
+ * @param {string} f.agentId wallet/agent UUID (public)
+ * @param {string} f.address custodial Solana address, base58 (public)
+ * @param {string|number|bigint} f.balanceLamports on-chain balance in lamports, integer
+ * @param {string} f.ledgerHead commitment to the authorized-state head
+ * (e.g. "<lastEventId>:<lastSignature>" or "genesis")
+ * @param {number} f.epoch monotonic epoch number, integer
+ * @returns {string}
+ */
+export function leafPreimage(f) {
+ const balance = normalizeInteger(f.balanceLamports, 'balanceLamports');
+ const epoch = normalizeInteger(f.epoch, 'epoch');
+ const agentId = requireField(f.agentId, 'agentId');
+ const address = requireField(f.address, 'address');
+ const ledgerHead = String(f.ledgerHead ?? 'genesis');
+ for (const [k, v] of [['agentId', agentId], ['address', address], ['ledgerHead', ledgerHead]]) {
+ if (v.includes('\n')) throw new Error(`custody leaf field ${k} must not contain a newline`);
+ }
+ return [LEAF_DOMAIN, agentId, address, balance, ledgerHead, epoch].join('\n');
+}
+
+function requireField(v, name) {
+ if (v == null || v === '') throw new Error(`custody leaf field ${name} is required`);
+ return String(v);
+}
+
+/** Coerce to a canonical non-negative integer decimal string (no float, no sign drift). */
+function normalizeInteger(v, name) {
+ if (typeof v === 'bigint') {
+ if (v < 0n) throw new Error(`custody leaf field ${name} must be >= 0`);
+ return v.toString();
+ }
+ const s = String(v).trim();
+ if (!/^\d+$/.test(s)) throw new Error(`custody leaf field ${name} must be a non-negative integer (got "${s}")`);
+ // strip a single leading run of zeros while keeping "0"
+ return s.replace(/^0+(?=\d)/, '');
+}
+
+/** 32-byte leaf hash (hex) of one wallet's attested state. */
+export async function computeLeafHash(fields) {
+ const preimage = leafPreimage(fields);
+ const h = await sha256(concatBytes(Uint8Array.of(LEAF_PREFIX), enc.encode(preimage)));
+ return bytesToHex(h);
+}
+
+/** Hash an internal node from its two child hashes (hex in, hex out). */
+export async function hashNode(leftHex, rightHex) {
+ const h = await sha256(concatBytes(Uint8Array.of(NODE_PREFIX), hexToBytes(leftHex), hexToBytes(rightHex)));
+ return bytesToHex(h);
+}
+
+/**
+ * Build a Merkle tree over an ordered array of leaf-hash hex strings.
+ * Odd layers promote by duplicating the last node (hash(last,last)).
+ * @param {string[]} leaves ordered leaf hashes (hex)
+ * @returns {Promise<{ root: string|null, layers: string[][], size: number }>}
+ * layers[0] === leaves; layers[last] === [root]. Empty input → root null.
+ */
+export async function buildMerkleTree(leaves) {
+ const size = leaves.length;
+ if (size === 0) return { root: null, layers: [[]], size: 0 };
+ const layers = [leaves.slice()];
+ let level = layers[0];
+ while (level.length > 1) {
+ const next = [];
+ for (let i = 0; i < level.length; i += 2) {
+ const left = level[i];
+ const right = i + 1 < level.length ? level[i + 1] : level[i]; // duplicate last when odd
+ next.push(await hashNode(left, right));
+ }
+ layers.push(next);
+ level = next;
+ }
+ return { root: layers[layers.length - 1][0], layers, size };
+}
+
+/** Convenience: just the root for an ordered leaf-hash array. */
+export async function merkleRoot(leaves) {
+ return (await buildMerkleTree(leaves)).root;
+}
+
+/**
+ * Inclusion proof for the leaf at `index` in a built tree's layers.
+ * @returns {{ sibling: string, position: 'left'|'right' }[]} bottom-up path.
+ * `position` is the SIBLING's side relative to the running node.
+ */
+export function getMerkleProof(layers, index) {
+ const proof = [];
+ let idx = index;
+ for (let level = 0; level < layers.length - 1; level++) {
+ const nodes = layers[level];
+ const isRight = idx % 2 === 1;
+ const siblingIdx = isRight ? idx - 1 : idx + 1;
+ // When the layer is odd and `idx` is the last (left) node, it pairs with
+ // itself — the sibling is the node itself, on the right.
+ const sibling = siblingIdx < nodes.length ? nodes[siblingIdx] : nodes[idx];
+ proof.push({ sibling, position: isRight ? 'left' : 'right' });
+ idx = Math.floor(idx / 2);
+ }
+ return proof;
+}
+
+/**
+ * Fold an inclusion proof from a leaf hash up to a root and return the computed
+ * root (hex). The verifier compares this against the on-chain anchored root.
+ */
+export async function computeRootFromProof(leafHex, proof) {
+ let node = String(leafHex).toLowerCase();
+ for (const step of proof) {
+ const sib = String(step.sibling).toLowerCase();
+ node = step.position === 'left' ? await hashNode(sib, node) : await hashNode(node, sib);
+ }
+ return node;
+}
+
+/**
+ * Verify that `leafHex` is included under `expectedRootHex` via `proof`.
+ * Pure boolean — never throws on a mismatch, only on malformed hex input.
+ */
+export async function verifyMerkleProof(leafHex, proof, expectedRootHex) {
+ if (!leafHex || !expectedRootHex || !Array.isArray(proof)) return false;
+ const computed = await computeRootFromProof(leafHex, proof);
+ return computed === String(expectedRootHex).toLowerCase();
+}
diff --git a/src/proof-of-custody/ui.js b/src/proof-of-custody/ui.js
new file mode 100644
index 000000000..4782dace2
--- /dev/null
+++ b/src/proof-of-custody/ui.js
@@ -0,0 +1,214 @@
+/**
+ * Proof-of-Custody — shared proof renderer.
+ *
+ * One renderer drives both the wallet-hub "Proof of Custody" tab and the
+ * standalone /proof page, so the verification experience is identical wherever
+ * an owner looks. It paints the inclusion proof, auto-runs the independent
+ * in-browser verifier (passed in as `verify`), and reflects the outcome with an
+ * honest green / red / pending state plus the per-step breakdown. It also renders
+ * the movement reconciliation and, once verified, a shareable "verified custody"
+ * badge + embed snippet.
+ */
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function short(s, head = 8, tail = 8) {
+ const v = String(s || '');
+ return v.length > head + tail + 1 ? `${v.slice(0, head)}…${v.slice(-tail)}` : v;
+}
+
+function fmtTime(iso) {
+ if (!iso) return '—';
+ try {
+ return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
+ } catch { return String(iso); }
+}
+
+/**
+ * @param {HTMLElement} panel
+ * @param {object} args
+ * @param {object} args.proof the `data` object from the inclusion-proof endpoint
+ * @param {(proof:object)=>Promise<object>} args.verify the independent verifier
+ * @param {string} [args.shareBase='/proof']
+ * @param {string} [args.origin]
+ * @param {object} [args.ctx] optional hub ctx (toast, copyToClipboard)
+ */
+export function renderProofUI(panel, { proof, verify, shareBase = '/proof', origin = '', ctx = {} }) {
+ if (!proof || proof.included === false) {
+ panel.innerHTML = notYetState(proof);
+ panel.querySelector('[data-reload]')?.addEventListener('click', () => location.reload());
+ return;
+ }
+
+ const anchor = proof.anchor || {};
+ const recon = proof.reconciliation || {};
+ const reconClass = recon.status === 'unexplained' ? 'is-bad' : recon.status === 'baseline' ? '' : 'is-good';
+
+ panel.innerHTML = `
+ <div class="awh-proof">
+ <div class="awh-proof-hero is-pending" data-hero>
+ <div class="awh-proof-seal" data-seal><span class="awh-proof-spin" aria-hidden="true"></span></div>
+ <div class="awh-proof-hero-main">
+ <div class="awh-proof-hero-title" data-hero-title>Verifying custody on-chain…</div>
+ <div class="awh-proof-hero-sub" data-hero-sub>Recomputing your leaf and reading the anchor straight from a public Solana RPC — no trust in our server.</div>
+ </div>
+ </div>
+
+ <div class="awh-proof-facts">
+ ${fact('Epoch', `#${esc(proof.epoch)}`)}
+ ${fact('Attested balance', `${formatSol(proof.leaf?.balanceSol)} SOL`)}
+ ${fact('Wallets in tree', esc(proof.wallet_count))}
+ ${fact('Snapshot', esc(fmtTime(proof.snapshot_at)))}
+ ${fact('Wallet', `<span title="${esc(proof.leaf?.address)}">${esc(short(proof.leaf?.address))}</span>`)}
+ ${fact('Ledger head', `<span title="${esc(proof.leaf?.ledgerHead)}">${esc(short(proof.leaf?.ledgerHead, 10, 6))}</span>`)}
+ ${fact('Merkle root', `<span title="${esc(proof.merkle_root)}">${esc(short(proof.merkle_root, 10, 10))}</span>`)}
+ ${fact('On-chain anchor', anchor.signature
+ ? `<a href="${esc(anchor.explorer)}" target="_blank" rel="noopener" title="${esc(anchor.signature)}">${esc(short(anchor.signature, 8, 8))} ↗</a>`
+ : `<span style="color:var(--warn,#fbbf24)">${esc(anchor.status || 'pending')}</span>`)}
+ </div>
+
+ <div class="awh-proof-card">
+ <h2>Verification steps</h2>
+ <p class="awh-proof-lead">Each step runs in your browser. You are not trusting three.ws to tell you it's fine — you're checking it.</p>
+ <ul class="awh-proof-steps" data-steps>${stepRow({ name: 'Independent verification', ok: null, detail: 'Running…' })}</ul>
+ </div>
+
+ <div class="awh-proof-recon ${reconClass}">
+ <div class="awh-proof-recon-h">${recon.status === 'unexplained' ? '⚠ Unexplained movement' : 'Movement reconciliation'}</div>
+ <div>${esc(recon.human || 'No reconciliation available.')}</div>
+ ${Array.isArray(recon.authorized_events) && recon.authorized_events.length
+ ? `<ul class="awh-proof-events">${recon.authorized_events.map(eventRow).join('')}</ul>`
+ : ''}
+ </div>
+
+ <div data-share hidden></div>
+ </div>
+ `;
+
+ runVerification();
+
+ async function runVerification() {
+ let result;
+ try {
+ result = await verify(proof);
+ } catch (e) {
+ result = { verified: false, steps: [{ name: 'Verifier error', ok: false, detail: e.message }], summary: 'Verifier crashed.' };
+ }
+ paintResult(result);
+ }
+
+ function paintResult(result) {
+ const hero = panel.querySelector('[data-hero]');
+ const seal = panel.querySelector('[data-seal]');
+ const title = panel.querySelector('[data-hero-title]');
+ const sub = panel.querySelector('[data-hero-sub]');
+ const stepsEl = panel.querySelector('[data-steps]');
+ if (!hero) return;
+
+ const pendingAnchor = !anchor.signature;
+ hero.classList.remove('is-pending');
+ if (result.verified) {
+ hero.classList.add('is-verified');
+ seal.innerHTML = '✓';
+ title.textContent = `Custody verified on-chain · epoch ${proof.epoch}`;
+ sub.innerHTML = anchor.explorer
+ ? `Verified at ${esc(fmtTime(new Date().toISOString()))} against <a href="${esc(anchor.explorer)}" target="_blank" rel="noopener">the anchor transaction ↗</a>. Your wallet was included with the stated balance and ledger head.`
+ : 'Verified against the on-chain anchor.';
+ } else if (pendingAnchor) {
+ hero.classList.add('is-pending');
+ seal.innerHTML = '◷';
+ title.textContent = 'Awaiting on-chain anchor';
+ sub.textContent = 'Your inclusion proof is internally consistent, but this epoch has not been committed on-chain yet. Verification completes once the root is anchored (usually within a few hours).';
+ } else {
+ hero.classList.add('is-failed');
+ seal.innerHTML = '✕';
+ title.textContent = 'Custody NOT verified';
+ sub.textContent = result.summary || 'Verification failed.';
+ }
+
+ stepsEl.innerHTML = (result.steps || []).map(stepRow).join('');
+
+ if (result.verified) renderShare();
+ }
+
+ function 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>`;
+ 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>
+ <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-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>
+ </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-embed]')?.addEventListener('click', () => copy(embed, 'Badge embed copied'));
+ }
+
+ async function copy(text, msg) {
+ try {
+ if (ctx.copyToClipboard) await ctx.copyToClipboard(text);
+ else await navigator.clipboard.writeText(text);
+ (ctx.toast || ((m) => {}))(msg);
+ } catch { /* clipboard blocked — the textarea is selectable as a fallback */ }
+ }
+}
+
+function fact(k, vHtml) {
+ return `<div class="awh-proof-fact"><div class="awh-proof-fact-k">${esc(k)}</div><div class="awh-proof-fact-v">${vHtml}</div></div>`;
+}
+
+function stepRow(step) {
+ const cls = step.ok === true ? 'ok' : step.ok === false ? 'bad' : 'pending';
+ const ico = step.ok === true ? '✓' : step.ok === false ? '✕' : '…';
+ return `<li class="awh-proof-step ${cls}">
+ <span class="awh-proof-step-ico" aria-hidden="true">${ico}</span>
+ <span class="awh-proof-step-c">
+ <span class="awh-proof-step-name">${esc(humanStep(step.name))}</span>
+ <span class="awh-proof-step-detail">${esc(step.detail || '')}</span>
+ </span>
+ </li>`;
+}
+
+function humanStep(name) {
+ return ({
+ leaf_recompute: 'Recompute leaf from public data',
+ merkle_path: 'Walk the Merkle path to the root',
+ onchain_anchor: 'Read the anchor straight from the chain',
+ root_match: 'Match computed root to on-chain root',
+ proof_present: 'Inclusion proof',
+ })[name] || name;
+}
+
+function eventRow(e) {
+ const sign = Number(e.amount_sol) ? `−${Math.abs(Number(e.amount_sol)).toFixed(6)}` : e.amount_sol;
+ const link = e.explorer
+ ? `<a href="${esc(e.explorer)}" target="_blank" rel="noopener">${esc((e.event_type || '').toUpperCase())} ↗</a>`
+ : esc((e.event_type || '').toUpperCase());
+ return `<li class="awh-proof-event"><span>${link}${e.category ? ` · ${esc(e.category)}` : ''}${e.reason ? ` · ${esc(e.reason)}` : ''}</span><span>${esc(sign)} SOL</span></li>`;
+}
+
+function notYetState(proof) {
+ const latest = proof && proof.latest_epoch != null ? proof.latest_epoch : null;
+ return `<div class="awh-proof"><div class="awh-proof-card">
+ <h2>Not attested yet</h2>
+ <p class="awh-proof-lead">This wallet hasn't been included in a custody attestation epoch yet${latest != null ? ` (latest epoch is #${esc(latest)})` : ''}. New wallets are picked up on the next snapshot — check back shortly and you'll be able to verify your custody on-chain.</p>
+ <button class="awh-proof-btn ghost" type="button" data-reload>Check again</button>
+ </div></div>`;
+}
+
+function formatSol(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ return v.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 6 });
+}
diff --git a/src/proof-of-custody/verifier.js b/src/proof-of-custody/verifier.js
new file mode 100644
index 000000000..04d91541d
--- /dev/null
+++ b/src/proof-of-custody/verifier.js
@@ -0,0 +1,184 @@
+/**
+ * Proof-of-Custody — independent, in-browser verifier.
+ *
+ * Given a per-owner inclusion proof (from GET /api/agents/:id/solana/proof) this
+ * verifies custody integrity WITHOUT trusting the three.ws server for the
+ * verification itself:
+ * 1. recompute the leaf hash from the public leaf fields,
+ * 2. fold the Merkle path to a computed root,
+ * 3. fetch the anchor transaction straight off-chain from a PUBLIC Solana RPC
+ * and read the root the platform actually committed,
+ * 4. confirm computed root === on-chain root.
+ *
+ * It fails honestly and specifically: each step reports pass/fail with a reason,
+ * and a failed anchor fetch is reported as "unverified", never "verified". The
+ * leaf hashing + path folding reuse src/proof-of-custody/merkle.js — the exact
+ * module the server prover used — so the two sides cannot drift.
+ */
+
+import { computeLeafHash, computeRootFromProof } from './merkle.js';
+
+// Public, keyless RPC endpoints with permissive CORS, tried in order. These are
+// deliberately NOT three.ws-operated for the on-chain read, so the verification
+// does not route through our infrastructure. The /api/solana-rpc proxy is a last
+// resort only if every public endpoint is unreachable from the browser.
+const PUBLIC_RPC = {
+ devnet: ['https://api.devnet.solana.com'],
+ mainnet: ['https://api.mainnet-beta.solana.com', 'https://solana-rpc.publicnode.com'],
+};
+
+function rpcEndpoints(network) {
+ const base = PUBLIC_RPC[network] || PUBLIC_RPC.mainnet;
+ return [...base, `/api/solana-rpc?network=${encodeURIComponent(network)}`];
+}
+
+/** Fetch a confirmed transaction's parsed form from a public RPC, with failover. */
+async function fetchTransaction(signature, network) {
+ const body = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'getTransaction',
+ params: [signature, { maxSupportedTransactionVersion: 0, encoding: 'jsonParsed', commitment: 'confirmed' }],
+ };
+ let lastErr = null;
+ for (const url of rpcEndpoints(network)) {
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) { lastErr = new Error(`rpc ${res.status}`); continue; }
+ const j = await res.json();
+ if (j.error) { lastErr = new Error(j.error.message || 'rpc error'); continue; }
+ if (j.result) return { tx: j.result, endpoint: url };
+ // result null = not found yet on this endpoint; try the next.
+ lastErr = new Error('transaction not found');
+ } catch (e) {
+ lastErr = e;
+ }
+ }
+ throw lastErr || new Error('all RPC endpoints failed');
+}
+
+/** Extract the first SPL-Memo string from a parsed transaction. */
+function extractMemo(tx) {
+ const msg = tx?.transaction?.message;
+ const instructions = msg?.instructions || [];
+ for (const ix of instructions) {
+ if (ix?.program === 'spl-memo' && typeof ix.parsed === 'string') return ix.parsed;
+ // Some RPCs surface the memo string directly on `parsed` for the memo program id.
+ if (ix?.programId === 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' && typeof ix.parsed === 'string') {
+ return ix.parsed;
+ }
+ }
+ // Fallback: parse the memo program log line.
+ for (const line of tx?.meta?.logMessages || []) {
+ const m = /Program log: Memo \(len \d+\): "(.*)"$/.exec(line);
+ if (m) return m[1].replace(/\\"/g, '"');
+ }
+ return null;
+}
+
+/**
+ * Verify an inclusion proof end-to-end.
+ *
+ * @param {object} proof the `data` object from GET /api/agents/:id/solana/proof
+ * @param {object} [opts]
+ * @param {(sig:string, net:string)=>Promise<{tx:object,endpoint:string}>} [opts.fetchTx]
+ * override the on-chain fetch (used by tests).
+ * @returns {Promise<{ verified: boolean, steps: object[], summary: string,
+ * onchain_root: string|null, computed_root: string|null }>}
+ */
+export async function verifyInclusionProof(proof, opts = {}) {
+ const steps = [];
+ const add = (name, ok, detail) => { steps.push({ name, ok, detail }); return ok; };
+ const done = (verified, summary, extra = {}) => ({
+ verified, steps, summary, onchain_root: null, computed_root: null, ...extra,
+ });
+
+ if (!proof || proof.included === false) {
+ add('proof_present', false, proof?.reason === 'no_leaf_yet'
+ ? 'This wallet has not been included in an attestation epoch yet — it was likely provisioned after the last snapshot. It will be covered in the next epoch.'
+ : 'No inclusion proof was returned.');
+ return done(false, 'No proof to verify yet.');
+ }
+
+ // 1. Recompute the leaf hash from the public fields.
+ let computedLeaf;
+ try {
+ computedLeaf = await computeLeafHash({
+ agentId: proof.leaf.agentId,
+ address: proof.leaf.address,
+ balanceLamports: proof.leaf.balanceLamports,
+ ledgerHead: proof.leaf.ledgerHead,
+ epoch: proof.leaf.epoch,
+ });
+ } catch (e) {
+ add('leaf_recompute', false, `Could not recompute the leaf: ${e.message}`);
+ return done(false, 'Leaf could not be recomputed from the public data.');
+ }
+ const leafMatches = computedLeaf === String(proof.leaf.leafHash).toLowerCase();
+ add('leaf_recompute', leafMatches, leafMatches
+ ? 'Recomputed the leaf hash from your wallet address, balance, ledger head and epoch — it matches the served leaf.'
+ : 'The leaf hash recomputed from the public data does NOT match the served leaf hash.');
+ if (!leafMatches) return done(false, 'Leaf hash mismatch — the served leaf does not commit to the stated data.');
+
+ // 2. Fold the Merkle path to a computed root.
+ let computedRoot;
+ try {
+ computedRoot = await computeRootFromProof(computedLeaf, proof.proof || []);
+ } catch (e) {
+ add('merkle_path', false, `Could not walk the Merkle path: ${e.message}`);
+ return done(false, 'Merkle path could not be evaluated.');
+ }
+ const rootMatchesServed = computedRoot === String(proof.merkle_root).toLowerCase();
+ add('merkle_path', rootMatchesServed, rootMatchesServed
+ ? `Walked the ${proof.proof?.length || 0}-step Merkle path from your leaf to the root — it matches the epoch root.`
+ : 'Walking the Merkle path did NOT reproduce the served root.');
+ if (!rootMatchesServed) {
+ return done(false, 'Merkle path does not lead to the stated root.', { computed_root: computedRoot });
+ }
+
+ // 3. Fetch the on-chain anchor and read the committed root.
+ const anchor = proof.anchor || {};
+ if (!anchor.signature) {
+ add('onchain_anchor', false, anchor.status === 'pending'
+ ? 'The Merkle proof is internally valid, but this epoch has not been anchored on-chain yet. Verification is incomplete until the root is committed.'
+ : `This epoch was not anchored on-chain (status: ${anchor.status || 'unknown'}). Treating as UNVERIFIED.`);
+ return done(false, 'Awaiting on-chain anchor — proof is internally consistent but not yet verifiable against the chain.', { computed_root: computedRoot });
+ }
+
+ let onchainRoot = null;
+ let endpoint = null;
+ try {
+ const fetchTx = opts.fetchTx || fetchTransaction;
+ const { tx, endpoint: ep } = await fetchTx(anchor.signature, anchor.network);
+ endpoint = ep;
+ 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');
+ onchainRoot = String(payload.root || '').toLowerCase();
+ if (Number(payload.epoch) !== Number(proof.epoch)) {
+ add('onchain_anchor', false, `On-chain anchor is for epoch ${payload.epoch}, not epoch ${proof.epoch}.`);
+ return done(false, 'On-chain anchor epoch does not match the proof epoch.', { computed_root: computedRoot, onchain_root: onchainRoot });
+ }
+ } catch (e) {
+ add('onchain_anchor', false, `Could not read the anchor from the chain (${e.message}). Treating as UNVERIFIED rather than trusting the server.`);
+ return done(false, 'Could not independently read the on-chain anchor — unverified.', { computed_root: computedRoot });
+ }
+ add('onchain_anchor', true, `Read the anchor transaction directly from a public Solana RPC (${endpoint}) — it commits epoch ${proof.epoch}.`);
+
+ // 4. The decisive comparison: computed root vs on-chain root.
+ const finalMatch = computedRoot === onchainRoot;
+ add('root_match', finalMatch, finalMatch
+ ? 'The root you computed from your own leaf matches the root committed on-chain. Custody is cryptographically verified.'
+ : 'The root computed from your leaf does NOT match the root committed on-chain. DO NOT TRUST.');
+
+ return done(finalMatch,
+ finalMatch
+ ? `Custody verified on-chain (epoch ${proof.epoch}).`
+ : 'Verification FAILED: on-chain root does not match.',
+ { computed_root: computedRoot, onchain_root: onchainRoot });
+}
diff --git a/src/shared/agent-financial-reputation.js b/src/shared/agent-financial-reputation.js
index 63d86e162..f085f139f 100644
--- a/src/shared/agent-financial-reputation.js
+++ b/src/shared/agent-financial-reputation.js
@@ -37,30 +37,39 @@
// ── The factors and their maxima (sum to 100) ────────────────────────────────
//
// tenure 12 wallet/agent age (log-scaled) + recent activity cadence
-// volume 18 real settled USD that flowed through the wallet
+// volume 13 real settled USD that flowed through the wallet
// tips 12 count of DISTINCT external funded wallets that tipped it
// reliability 12 on-chain settlement success rate (only once there's volume)
// generosity 8 tips/streams GIVEN to others (reciprocity), wash-excluded
// conduct 12 trading conduct: realized P&L + win rate − dumping penalty
+// conviction 10 $THREE held (log-scaled value) + continuous holding duration
// solvency 6 live reserves vs outstanding obligations (full mode only)
// lineage 6 how many times the avatar was forked (others valued it)
-// identity 14 verified ERC-8004 identity + registry feedback + attestations
+// identity 9 verified ERC-8004 identity + registry feedback + attestations
+//
+// v3 introduced the `conviction` pillar — holding the platform's only coin,
+// $THREE, through time is a costly, fully on-chain commitment to three.ws. Its 10
+// points were carved out of `volume` (18→13) and `identity` (14→9) rather than
+// inflating the scale: on this platform, conviction in the native coin is at least
+// as strong a trust signal as an external registry, and the score still sums to
+// exactly 100 so the tier thresholds and every persisted history stay comparable.
//
// loadReputationInputs / getAgentReputation (server) do the real I/O.
-export const REPUTATION_VERSION = 2;
+export const REPUTATION_VERSION = 3;
// Factor definitions — label + max points. Order is the display order.
export const PILLARS = [
{ key: 'tenure', label: 'Tenure & consistency', max: 12 },
- { key: 'volume', label: 'Earnings & volume', max: 18 },
+ { key: 'volume', label: 'Earnings & volume', max: 13 },
{ key: 'tips', label: 'Tips from distinct wallets', max: 12 },
{ key: 'reliability', label: 'Settlement reliability', max: 12 },
{ key: 'generosity', label: 'Generosity & reciprocity', max: 8 },
{ key: 'conduct', label: 'Trading conduct', max: 12 },
+ { key: 'conviction', label: '$THREE conviction', max: 10 },
{ key: 'solvency', label: 'Solvency (reserves vs owed)', max: 6 },
{ key: 'lineage', label: 'Fork lineage', max: 6 },
- { key: 'identity', label: 'On-chain identity', max: 14 },
+ { key: 'identity', label: 'On-chain identity', max: 9 },
];
export const MAX_SCORE = PILLARS.reduce((s, p) => s + p.max, 0); // 100
@@ -106,6 +115,9 @@ const log2 = (n) => Math.log(n) / Math.LN2;
* @param {number} inputs.winningTrades closed positions with positive realized P&L
* @param {number} inputs.realizedPnlSol net realized P&L in SOL across closed positions
* @param {number} inputs.dumpEvents detected dumps on its own coin's supporters
+ * @param {number} inputs.threeUsd live USD value of $THREE held by the wallet
+ * @param {number} inputs.threeTokens whole-token $THREE balance (price-independent gate)
+ * @param {number} inputs.threeHoldDays continuous days holding $THREE (resets on full exit)
* @param {number} inputs.reserveUsd live reserves USD (full mode only; 0 = unknown)
* @param {number} inputs.obligationsUsd outstanding obligations USD (active streams + pending)
* @param {boolean} inputs.reservesKnown whether live reserves were actually read
@@ -146,7 +158,7 @@ export function computeReputation(inputs = {}) {
// ── Earnings & volume (max 18) ─────────────────────────────────────────────
// Real USD that flowed through the wallet. Money moved is costly to fake.
const rawVolume = i.settledUsd + i.externalTipUsd;
- const volumePtsRaw = clamp(5.2 * Math.log10(rawVolume + 1), 0, 18);
+ const volumePtsRaw = clamp(4.4 * Math.log10(rawVolume + 1), 0, 13);
const volumePts = volumePtsRaw * diversityMultiplier;
pushPillar(pillars, 'volume', volumePts, {
detail:
@@ -235,6 +247,31 @@ export function computeReputation(inputs = {}) {
},
});
+ // ── $THREE conviction (max 10) ─────────────────────────────────────────────
+ // Holding the platform's ONLY coin — and holding it through time — is a costly,
+ // fully on-chain commitment to three.ws that no follower count can fake. Value
+ // is log-scaled so a whale can't buy the whole pillar in one transfer; duration
+ // rewards genuine long-term holders and resets honestly the instant a wallet
+ // fully exits its $THREE (the holder snapshot drops it, so held_since restarts).
+ // A flash-hold — buy, snapshot, sell — earns near-zero duration and only the
+ // log-scaled value of whatever was briefly held.
+ const holdsThree = i.threeTokens > 0;
+ const threeValuePts = clamp(2.4 * Math.log10(i.threeUsd + 1), 0, 6);
+ const threeDurationPts = holdsThree ? clamp((i.threeHoldDays / 120) * 4, 0, 4) : 0;
+ const convictionPts = clamp(threeValuePts + threeDurationPts, 0, 10);
+ pushPillar(pillars, 'conviction', convictionPts, {
+ detail: !holdsThree
+ ? 'Holds no $THREE yet — holding the platform coin builds long-term conviction.'
+ : `Holds $${fmtUsd(i.threeUsd)} of $THREE${
+ i.threeHoldDays >= 1 ? ` continuously for ${fmtAge(i.threeHoldDays)}` : ' (just started)'
+ }.`,
+ facts: {
+ three_usd: round1(i.threeUsd),
+ three_hold_days: Math.round(i.threeHoldDays),
+ three_tokens: Math.round(i.threeTokens),
+ },
+ });
+
// ── Solvency (max 6) ───────────────────────────────────────────────────────
// Can it cover what it owes? Live reserves measured against outstanding
// obligations (active streams still committed + pending spends). Only computes
@@ -272,30 +309,30 @@ export function computeReputation(inputs = {}) {
facts: { fork_count: i.forkCount },
});
- // ── On-chain identity & verification (max 14) ──────────────────────────────
+ // ── On-chain identity & verification (max 9) ───────────────────────────────
let identityPts = 0;
const idBits = [];
if (i.hasOnchainIdentity) {
- identityPts += 6;
+ identityPts += 4;
idBits.push('verified ERC-8004 identity');
}
if (i.registryCount > 0) {
// Registry average may arrive on a 0–5 star scale or a 0–100 scale.
const norm = i.registryAverage > 5 ? i.registryAverage / 100 : i.registryAverage / 5;
- const regPts = clamp(norm * 3 + clamp(log2(i.registryCount + 1), 0, 1.5), 0, 5);
+ const regPts = clamp(norm * 2 + clamp(log2(i.registryCount + 1), 0, 1.5), 0, 3.5);
identityPts += regPts;
idBits.push(`${i.registryCount} on-chain review${i.registryCount === 1 ? '' : 's'}`);
}
- const attPts = clamp(i.validationCount * 1.5 + i.feedbackCount * 0.4, 0, 2.5);
+ const attPts = clamp(i.validationCount * 1 + i.feedbackCount * 0.3, 0, 1.5);
if (attPts > 0) {
identityPts += attPts;
idBits.push(`${i.validationCount + i.feedbackCount} signed attestation${i.validationCount + i.feedbackCount === 1 ? '' : 's'}`);
}
if (i.hasSkillCollection) {
- identityPts += 1;
+ identityPts += 0.5;
idBits.push('on-chain skill licenses');
}
- identityPts = clamp(identityPts, 0, 14);
+ identityPts = clamp(identityPts, 0, 9);
pushPillar(pillars, 'identity', identityPts, {
detail: idBits.length ? `Carries ${idBits.join(', ')}.` : 'No on-chain identity or attestations yet.',
facts: { verified: i.hasOnchainIdentity, registry_count: i.registryCount, attestations: i.validationCount + i.feedbackCount },
@@ -348,6 +385,7 @@ export function computeReputation(inputs = {}) {
i.feedbackCount +
i.registryCount +
(i.hasOnchainIdentity ? 1 : 0) +
+ (holdsThree ? 1 : 0) +
(rawVolume > 0 ? 1 : 0);
const isNew = realActivity === 0;
@@ -372,6 +410,11 @@ export function computeReputation(inputs = {}) {
reserve_usd: i.reservesKnown ? round1(i.reserveUsd) : null,
fork_count: i.forkCount,
verified: i.hasOnchainIdentity,
+ // $THREE conviction — surfaced in totals so the access layer (unlocks) and
+ // the client can read holdings/duration without re-deriving them.
+ three_usd: round1(i.threeUsd),
+ three_hold_days: Math.round(i.threeHoldDays),
+ holds_three: holdsThree,
},
};
}
@@ -425,6 +468,9 @@ function normalizeInputs(raw) {
winningTrades: Math.max(0, num(raw.winningTrades)),
realizedPnlSol: num(raw.realizedPnlSol),
dumpEvents: Math.max(0, num(raw.dumpEvents)),
+ threeUsd: Math.max(0, num(raw.threeUsd)),
+ threeTokens: Math.max(0, num(raw.threeTokens)),
+ threeHoldDays: Math.max(0, num(raw.threeHoldDays)),
reserveUsd: Math.max(0, num(raw.reserveUsd)),
obligationsUsd: Math.max(0, num(raw.obligationsUsd)),
reservesKnown: Boolean(raw.reservesKnown),
diff --git a/src/shared/share.js b/src/shared/share.js
index cabe58450..7823c8361 100644
--- a/src/shared/share.js
+++ b/src/shared/share.js
@@ -15,6 +15,8 @@
* description string (optional)
* shareUrl string — canonical URL that has OG meta
* remixUrl string — deep-link back into the create flow
+ * previewImage string — optional OG/card image URL shown at the top of the panel
+ * so the user sees exactly what their link will unfurl as
*/
import { Modal } from './modal.js';
@@ -26,7 +28,7 @@ const X_INTENT = 'https://x.com/intent/tweet';
export function showSharePanel(entity, triggerEl = null) {
ensureShareStyles();
- const { title = '', description = '', shareUrl, remixUrl } = entity;
+ const { title = '', description = '', shareUrl, remixUrl, previewImage } = entity;
const xText = encodeURIComponent(`${title} on three.ws\n`);
const xUrl = encodeURIComponent(shareUrl || location.href);
@@ -40,6 +42,15 @@ export function showSharePanel(entity, triggerEl = null) {
? `<p class="tws-sp-desc">${esc(description)}</p>`
: '';
+ // Live preview of exactly what the link unfurls as — the real OG/card image.
+ // Lazy + graceful: if the image fails to load it simply removes itself.
+ const previewHtml = previewImage
+ ? `<div class="tws-sp-preview">
+ <img src="${esc(previewImage)}" alt="${esc(title)} card preview" loading="lazy" decoding="async"
+ onerror="this.closest('.tws-sp-preview')?.remove()" />
+ </div>`
+ : '';
+
const remixHtml = remixUrl
? `<a class="tws-sp-btn tws-sp-remix" href="${esc(remixUrl)}">
${sparkleIcon()}
@@ -49,6 +60,7 @@ export function showSharePanel(entity, triggerEl = null) {
const body = `
<div class="tws-sp">
+ ${previewHtml}
${descHtml}
<button class="tws-sp-btn tws-sp-copy" type="button" data-share-copy="${esc(shareUrl || '')}">
${linkIcon()}
@@ -168,6 +180,22 @@ const SHARE_CSS = `
line-height: 1.5;
}
+/* OG/card preview — what the shared link unfurls as */
+.tws-sp-preview {
+ margin: 0 0 10px;
+ border-radius: var(--radius-control, 10px);
+ overflow: hidden;
+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));
+ background: var(--surface-2, rgba(255,255,255,0.03));
+ aspect-ratio: 1200 / 630;
+}
+.tws-sp-preview img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
.tws-sp-btn {
display: flex;
align-items: center;
diff --git a/src/shared/wallet-card.js b/src/shared/wallet-card.js
new file mode 100644
index 000000000..311032b48
--- /dev/null
+++ b/src/shared/wallet-card.js
@@ -0,0 +1,554 @@
+/**
+ * Wallet Trading Card — the agent wallet as a living, screenshot-worthy artifact.
+ *
+ * One self-contained collectible card per agent: its avatar, its glowing vanity
+ * "license plate", its real net worth and holdings, its realized P&L, its
+ * reputation tier, the $THREE-holder mark, and a tip / fork / share CTA. Rarity
+ * "finish" scales with the agent's REAL wealth + reputation tier — matte for a
+ * dormant new wallet, holographic shimmer for a luminous, elite one — tasteful,
+ * never casino.
+ *
+ * Everything is real data. The card reads the same public, server-authoritative
+ * endpoints every other wallet surface uses:
+ * - GET /api/agents/:id/solana/networth → portfolio (USD, SOL, $THREE, holdings),
+ * public-safe reputation aggregates (forks, tips, realized P&L), wealth tier.
+ * - GET /api/agents/:id/reputation → 0–100 score + tier (new…elite).
+ * Both are public-safe: the card NEVER shows an owner-only datum (custody specifics,
+ * limits, keys). A real balance of $0 shows $0 — never a decorative number.
+ *
+ * The same card renders to a 1200×630 image server-side in api/og/agent.js, so a
+ * shared agent link unfurls with a card that matches what's on the page.
+ *
+ * Usage:
+ * import { mountWalletCard } from './shared/wallet-card.js';
+ * const handle = mountWalletCard(hostEl, agentRecord, { isOwner, network });
+ * // handle.destroy() to tear down (idempotent).
+ */
+
+import { getWalletIdentity } from './agent-wallet-chip.js';
+import { formatWalletUsd, shortAddress } from './wallet-format.js';
+import { tierForUsd, NETWORTH_TIERS } from './wallet-networth.js';
+import { showSharePanel } from './share.js';
+import { openTipModal } from './agent-tip-modal.js';
+
+const STYLE_ID = 'tws-wallet-card-styles';
+const THREE_MARK = '$THREE';
+
+// Reputation tier → rank (0..4). Mirrors TIERS in agent-financial-reputation.js
+// without importing the whole scoring engine into the client card.
+const REP_RANK = { new: 0, emerging: 1, established: 2, trusted: 3, elite: 4 };
+
+// Finish ladder (0..5): the visual "rarity" of the card, derived from the higher
+// of the wealth tier (0..5) and the reputation rank (0..4, shifted). Each step
+// adds a touch more presence: matte → satin → foil → holo → prism.
+const FINISHES = [
+ { key: 'matte', label: 'Common' },
+ { key: 'satin', label: 'Uncommon' },
+ { key: 'foil', label: 'Rare' },
+ { key: 'holo', label: 'Epic' },
+ { key: 'prism', label: 'Legendary' },
+ { key: 'aurora', label: 'Mythic' },
+];
+
+const reducedMotion = () =>
+ typeof window !== 'undefined' &&
+ window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+async function fetchJson(url) {
+ const r = await fetch(url, { credentials: 'include' });
+ if (!r.ok) {
+ const e = new Error(`http_${r.status}`);
+ e.status = r.status;
+ throw e;
+ }
+ return r.json();
+}
+
+/**
+ * Render the vanity-highlighted address: the matched prefix/suffix get the
+ * emphasized accent, the elided middle stays muted. Falls back to a plain short
+ * address when the agent has no vanity pattern.
+ */
+function addressHTML(identity) {
+ const addr = identity.address;
+ const pre = identity.prefix && addr.startsWith(identity.prefix) ? identity.prefix : '';
+ const suf = identity.suffix && addr.endsWith(identity.suffix) ? identity.suffix : '';
+ if (!pre && !suf) {
+ return `<span class="twc2-addr-mid">${esc(shortAddress(addr, 5, 5))}</span>`;
+ }
+ const head = pre ? addr.slice(0, Math.max(pre.length, 4)) : addr.slice(0, 4);
+ const tail = suf ? addr.slice(-Math.max(suf.length, 4)) : addr.slice(-4);
+ const headEmph = pre ? `<b class="twc2-addr-vanity">${esc(head)}</b>` : `<span class="twc2-addr-mid">${esc(head)}</span>`;
+ const tailEmph = suf ? `<b class="twc2-addr-vanity">${esc(tail)}</b>` : `<span class="twc2-addr-mid">${esc(tail)}</span>`;
+ return `${headEmph}<span class="twc2-addr-dots">…</span>${tailEmph}`;
+}
+
+/** Compute the card's finish from real wealth + reputation tiers. */
+function finishFor(wealthLevel, repTier) {
+ const repRank = REP_RANK[repTier] ?? 0;
+ // Reputation rank 0..4 maps onto the 0..5 finish ladder one step higher so an
+ // elite agent reads as mythic even on a modest balance; wealth tops out at 5.
+ const level = Math.max(Number(wealthLevel) || 0, repRank + 1 > 5 ? 5 : (repTier && repRank > 0 ? repRank + 1 : 0));
+ const clamped = Math.max(0, Math.min(5, level));
+ return { level: clamped, ...FINISHES[clamped] };
+}
+
+function statCell(label, value, opts = {}) {
+ const accentCls = opts.accent ? ' twc2-stat--accent' : '';
+ const title = opts.title ? ` title="${esc(opts.title)}"` : '';
+ return `
+ <div class="twc2-stat${accentCls}"${title}>
+ <span class="twc2-stat-val">${esc(value)}</span>
+ <span class="twc2-stat-label">${esc(label)}</span>
+ </div>`;
+}
+
+function skeletonHTML() {
+ return `
+ <div class="twc2-skel" aria-hidden="true">
+ <div class="twc2-skel-top">
+ <div class="twc2-skel-avatar"></div>
+ <div class="twc2-skel-lines">
+ <span class="twc2-skel-line w60"></span>
+ <span class="twc2-skel-line w40"></span>
+ </div>
+ </div>
+ <div class="twc2-skel-hero"></div>
+ <div class="twc2-skel-stats">
+ <span></span><span></span><span></span>
+ </div>
+ </div>`;
+}
+
+/**
+ * @param {HTMLElement} host where to mount
+ * @param {object} agent an agent/avatar record (id, name, meta.solana_address, vanity, avatar url)
+ * @param {object} [opts]
+ * @param {boolean} [opts.isOwner]
+ * @param {'mainnet'|'devnet'} [opts.network]
+ * @param {() => void} [opts.onFork] custom fork handler (default: go to the agent profile)
+ * @returns {{ destroy: () => void, refresh: () => void } | null}
+ */
+export function mountWalletCard(host, agent, opts = {}) {
+ if (typeof document === 'undefined' || !host) return null;
+ const identity = getWalletIdentity(agent);
+ const agentId = identity?.agentId || agent?.id || agent?.agent_id || null;
+ if (!agentId) return null;
+
+ ensureStyles();
+
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const isOwner = !!opts.isOwner;
+ const origin = typeof location !== 'undefined' ? location.origin : 'https://three.ws';
+
+ let destroyed = false;
+ let tiltRaf = 0;
+
+ const root = document.createElement('div');
+ root.className = 'twc2-wrap';
+ root.innerHTML = skeletonHTML();
+ host.replaceChildren(root);
+
+ function setHTML(html) {
+ if (destroyed) return;
+ root.innerHTML = html;
+ }
+
+ // ── Hover tilt + shine (pointer only, honors reduced-motion) ───────────────
+ function wireTilt(cardEl) {
+ if (reducedMotion()) return;
+ if (!window.matchMedia?.('(hover: hover) and (pointer: fine)')?.matches) return;
+ let rect = null;
+ const onEnter = () => { rect = cardEl.getBoundingClientRect(); cardEl.classList.add('twc2-card--live'); };
+ const onMove = (e) => {
+ if (!rect) rect = cardEl.getBoundingClientRect();
+ const px = (e.clientX - rect.left) / rect.width;
+ const py = (e.clientY - rect.top) / rect.height;
+ if (tiltRaf) cancelAnimationFrame(tiltRaf);
+ tiltRaf = requestAnimationFrame(() => {
+ const rx = (0.5 - py) * 7;
+ const ry = (px - 0.5) * 9;
+ cardEl.style.setProperty('--twc2-rx', `${rx.toFixed(2)}deg`);
+ cardEl.style.setProperty('--twc2-ry', `${ry.toFixed(2)}deg`);
+ cardEl.style.setProperty('--twc2-mx', `${(px * 100).toFixed(1)}%`);
+ cardEl.style.setProperty('--twc2-my', `${(py * 100).toFixed(1)}%`);
+ });
+ };
+ const onLeave = () => {
+ rect = null;
+ cardEl.classList.remove('twc2-card--live');
+ cardEl.style.removeProperty('--twc2-rx');
+ cardEl.style.removeProperty('--twc2-ry');
+ };
+ cardEl.addEventListener('pointerenter', onEnter);
+ cardEl.addEventListener('pointermove', onMove);
+ cardEl.addEventListener('pointerleave', onLeave);
+ }
+
+ function shareData() {
+ return {
+ kind: 'agent',
+ id: agentId,
+ title: identity.name || agent?.name || 'Agent',
+ description: `${identity.name || 'This agent'} on three.ws — its avatar, its wallet, its reputation.`,
+ shareUrl: `${origin}/agent/${agentId}/share`,
+ remixUrl: `${origin}/agents/${agentId}`,
+ previewImage: `${origin}/api/og/agent?id=${encodeURIComponent(agentId)}`,
+ };
+ }
+
+ function doFork() {
+ if (typeof opts.onFork === 'function') { opts.onFork(); return; }
+ // Prefer the live fork affordance if this card sits on the profile page.
+ const actions = document.getElementById('ad-avatar-actions');
+ if (actions) {
+ actions.scrollIntoView({ behavior: reducedMotion() ? 'auto' : 'smooth', block: 'center' });
+ actions.querySelector('button,[role=button]')?.click?.();
+ return;
+ }
+ location.href = `${origin}/agents/${agentId}`;
+ }
+
+ function wireActions(cardEl) {
+ cardEl.querySelector('[data-twc2-copy]')?.addEventListener('click', async (e) => {
+ const btn = e.currentTarget;
+ try {
+ await navigator.clipboard.writeText(identity.address);
+ btn.classList.add('twc2-copied');
+ const lbl = btn.querySelector('.twc2-copy-lbl');
+ const prev = lbl?.textContent;
+ if (lbl) lbl.textContent = 'Copied';
+ setTimeout(() => { btn.classList.remove('twc2-copied'); if (lbl) lbl.textContent = prev; }, 1800);
+ } catch { /* clipboard blocked — address is still selectable on screen */ }
+ });
+ cardEl.querySelector('[data-twc2-share]')?.addEventListener('click', (e) => {
+ showSharePanel(shareData(), e.currentTarget);
+ });
+ cardEl.querySelector('[data-twc2-tip]')?.addEventListener('click', () => {
+ openTipModal(agent, { network });
+ });
+ cardEl.querySelector('[data-twc2-fork]')?.addEventListener('click', (e) => {
+ e.preventDefault();
+ doFork();
+ });
+ }
+
+ function renderError() {
+ // Minimal valid card — identity only, never a broken artifact. Balance reads
+ // "—" honestly when the chain/price feed is unavailable.
+ const av = identity.avatarUrl
+ ? `<img class="twc2-avatar" src="${esc(identity.avatarUrl)}" alt="" loading="lazy" />`
+ : `<div class="twc2-avatar twc2-avatar--ph">${esc((identity.name || 'A')[0].toUpperCase())}</div>`;
+ setHTML(`
+ <article class="twc2-card" data-finish="matte" aria-label="${esc(identity.name || 'Agent')} wallet card">
+ <div class="twc2-shine" aria-hidden="true"></div>
+ <header class="twc2-head">
+ ${av}
+ <div class="twc2-id">
+ <h3 class="twc2-name">${esc(identity.name || 'Agent')}</h3>
+ <button type="button" class="twc2-addr" data-twc2-copy aria-label="Copy wallet address">
+ ${addressHTML(identity)}
+ <span class="twc2-copy-lbl">Copy</span>
+ </button>
+ </div>
+ </header>
+ <div class="twc2-hero">
+ <span class="twc2-hero-usd">—</span>
+ <span class="twc2-hero-sub">balance unavailable right now</span>
+ </div>
+ <footer class="twc2-cta">
+ <button type="button" class="twc2-btn twc2-btn-ghost" data-twc2-share>Share card</button>
+ </footer>
+ </article>`);
+ const cardEl = root.querySelector('.twc2-card');
+ wireActions(cardEl);
+ wireTilt(cardEl);
+ }
+
+ async function load() {
+ let nw = null, rep = null;
+ try {
+ nw = (await fetchJson(`/api/agents/${agentId}/solana/networth?network=${network}`))?.data || null;
+ } catch (err) {
+ if (err.status === 404) nw = null; // not provisioned → empty-wallet card below
+ else { renderError(); return; }
+ }
+ // Reputation is enhancement-only: a failed read just omits the tier badge.
+ try {
+ rep = (await fetchJson(`/api/agents/${agentId}/reputation`))?.data || null;
+ } catch { rep = null; }
+
+ render(nw, rep);
+ }
+
+ function render(nw, rep) {
+ if (destroyed) return;
+
+ const portfolio = nw?.portfolio || { usd: 0, sol: 0, three: null, token_count: 0 };
+ const repAgg = nw?.reputation || {};
+ const usd = Number(portfolio.usd) || 0;
+ const wealthTier = nw?.tier?.key
+ ? (NETWORTH_TIERS.find((t) => t.key === nw.tier.key) || tierForUsd(usd))
+ : tierForUsd(usd);
+ const finish = finishFor(wealthTier.level, rep?.tier);
+
+ const hasThree = !!(portfolio.three && Number(portfolio.three.amount) > 0);
+ const tokenCount = Number(portfolio.token_count) || 0;
+ const pnlSol = Number(repAgg.realized_pnl_sol) || 0;
+ const tips = repAgg.tips || { count: 0, usd: 0 };
+ const forks = Number(repAgg.fork_count) || 0;
+ const score = rep && Number.isFinite(Number(rep.score)) ? Number(rep.score) : null;
+ const repLabel = rep?.tierLabel || null;
+ const repAccent = rep?.accent || null;
+ const isEmpty = usd <= 0 && tokenCount === 0 && tips.count === 0 && forks === 0 && pnlSol === 0;
+
+ const usdLabel = nw?.address || usd > 0 ? (formatWalletUsd(usd) ?? '$0') : '$0';
+ const av = identity.avatarUrl
+ ? `<img class="twc2-avatar" src="${esc(identity.avatarUrl)}" alt="" loading="lazy" />`
+ : `<div class="twc2-avatar twc2-avatar--ph">${esc((identity.name || 'A')[0].toUpperCase())}</div>`;
+
+ // Stat grid — only real, public-safe aggregates. P&L shown only when positive
+ // (a public card never broadcasts a loss); reputation only when scored.
+ const stats = [];
+ stats.push(statCell('Holdings', tokenCount === 0 ? '—' : `${tokenCount}`, { title: `${tokenCount} token${tokenCount === 1 ? '' : 's'} held` }));
+ if (pnlSol > 0) stats.push(statCell('Realized P&L', `+${pnlSol.toFixed(pnlSol < 1 ? 3 : 2)} ◎`, { accent: true, title: `${repAgg.realized_wins || 0} winning closed trade(s)` }));
+ else if (tips.count > 0) stats.push(statCell('Tips', `${tips.count}`, { title: `${formatWalletUsd(tips.usd) || '$0'} tipped` }));
+ else stats.push(statCell('Forks', `${forks}`, { title: `forked ${forks} time(s)` }));
+ if (score != null) stats.push(statCell('Reputation', `${Math.round(score)}`, { title: `${repLabel || ''} · ${Math.round(score)}/100` }));
+ else stats.push(statCell('Tier', wealthTier.label));
+
+ const repBadge = repLabel
+ ? `<span class="twc2-rep" style="--rep:${esc(repAccent || '#c4b5fd')}">${esc(repLabel)}</span>`
+ : '';
+ const threeMark = hasThree
+ ? `<span class="twc2-three" title="Holds ${THREE_MARK}">◆ ${THREE_MARK}</span>`
+ : '';
+
+ const emptyHint = isEmpty
+ ? `<p class="twc2-empty-hint">A fresh wallet, ready for its first move. ${isOwner ? 'Fund it to bring its body to life.' : 'Tip it or fork it to start one of your own.'}</p>`
+ : '';
+
+ // CTA row by viewer role. Owner → manage/customize; visitor/logged-out →
+ // tip + fork. Share is universal. No owner-only datum is ever rendered above.
+ const primaryCta = isOwner
+ ? `<a class="twc2-btn twc2-btn-primary" href="${esc(identity.hubUrl || `/agent/${agentId}/wallet`)}">Manage wallet</a>`
+ : `<button type="button" class="twc2-btn twc2-btn-primary" data-twc2-tip>Tip</button>`;
+ const secondaryCta = isOwner
+ ? `<a class="twc2-btn twc2-btn-ghost" href="${esc(identity.hubUrl || `/agent/${agentId}/wallet`)}#customize">Customize</a>`
+ : `<button type="button" class="twc2-btn twc2-btn-ghost" data-twc2-fork>Fork to own</button>`;
+
+ setHTML(`
+ <article class="twc2-card" data-finish="${esc(finish.key)}" data-empty="${isEmpty ? '1' : '0'}"
+ style="--twc2-rim:${esc(repAccent || '#c4b5fd')}"
+ aria-label="${esc(identity.name || 'Agent')} wallet trading card — ${esc(finish.label)}">
+ <div class="twc2-shine" aria-hidden="true"></div>
+ <div class="twc2-foil" aria-hidden="true"></div>
+ <span class="twc2-finish" aria-label="Card finish: ${esc(finish.label)}">${esc(finish.label)}</span>
+
+ <header class="twc2-head">
+ ${av}
+ <div class="twc2-id">
+ <h3 class="twc2-name" title="${esc(identity.name || 'Agent')}">${esc(identity.name || 'Agent')}</h3>
+ <button type="button" class="twc2-addr ${identity.isVanity ? 'twc2-addr--vanity' : ''}" data-twc2-copy
+ aria-label="Copy wallet address ${esc(identity.address)}">
+ ${identity.isVanity ? '<span class="twc2-spark" aria-hidden="true">✦</span>' : ''}
+ ${addressHTML(identity)}
+ <span class="twc2-copy-lbl">Copy</span>
+ </button>
+ </div>
+ <div class="twc2-marks">${repBadge}${threeMark}</div>
+ </header>
+
+ <div class="twc2-hero">
+ <span class="twc2-hero-usd">${esc(usdLabel)}</span>
+ <span class="twc2-hero-sub">${esc(wealthTier.label)} · net worth</span>
+ </div>
+
+ <div class="twc2-stats">${stats.join('')}</div>
+ ${emptyHint}
+
+ <footer class="twc2-cta">
+ ${primaryCta}
+ ${secondaryCta}
+ <button type="button" class="twc2-btn twc2-btn-icon" data-twc2-share aria-label="Share this card" title="Share card">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
+ </button>
+ </footer>
+
+ <div class="twc2-wm">three.ws</div>
+ </article>`);
+
+ const cardEl = root.querySelector('.twc2-card');
+ wireActions(cardEl);
+ wireTilt(cardEl);
+ }
+
+ load();
+
+ return {
+ refresh: () => { if (!destroyed) load(); },
+ destroy: () => {
+ destroyed = true;
+ if (tiltRaf) cancelAnimationFrame(tiltRaf);
+ try { root.remove(); } catch { /* idempotent */ }
+ },
+ };
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = CARD_CSS;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+const CARD_CSS = `
+.twc2-wrap{ --twc2-accent:#c4b5fd; --twc2-rim:#c4b5fd; perspective:1100px; width:100%; }
+
+.twc2-card{
+ position:relative; overflow:hidden;
+ border-radius:18px; padding:18px 18px 16px;
+ background:
+ radial-gradient(120% 80% at 18% 0%, color-mix(in srgb, var(--twc2-rim) 16%, transparent), transparent 55%),
+ linear-gradient(165deg, #14121d 0%, #0b0a11 60%, #08070c 100%);
+ border:1px solid color-mix(in srgb, var(--twc2-rim) 28%, rgba(255,255,255,.06));
+ box-shadow:0 10px 34px rgba(0,0,0,.45), inset 0 1px 0 rgba(255,255,255,.05);
+ transform:rotateX(var(--twc2-rx,0)) rotateY(var(--twc2-ry,0));
+ transform-style:preserve-3d; transition:transform .25s ease, box-shadow .25s ease;
+ will-change:transform;
+}
+.twc2-card--live{ transition:none; box-shadow:0 18px 50px rgba(0,0,0,.55), 0 0 0 1px color-mix(in srgb, var(--twc2-rim) 40%, transparent); }
+
+/* Light sweep that tracks the cursor on hover (foil+ finishes only). */
+.twc2-shine{ position:absolute; inset:0; pointer-events:none; opacity:0; transition:opacity .25s ease;
+ background:radial-gradient(420px 280px at var(--twc2-mx,50%) var(--twc2-my,0%), rgba(255,255,255,.14), transparent 60%); }
+.twc2-card--live .twc2-shine{ opacity:1; }
+
+/* Holographic foil layer — its richness steps up with the finish. */
+.twc2-foil{ position:absolute; inset:0; pointer-events:none; opacity:0; mix-blend-mode:screen;
+ background:linear-gradient(115deg, transparent 30%,
+ rgba(124,108,176,.20) 42%, rgba(96,165,250,.18) 50%, rgba(236,114,182,.18) 58%, transparent 70%);
+ background-size:260% 260%; }
+.twc2-card[data-finish="foil"] .twc2-foil{ opacity:.35; }
+.twc2-card[data-finish="holo"] .twc2-foil{ opacity:.5; }
+.twc2-card[data-finish="prism"] .twc2-foil{ opacity:.7; }
+.twc2-card[data-finish="aurora"] .twc2-foil{ opacity:.9; }
+.twc2-card--live .twc2-foil{ background-position:var(--twc2-mx,50%) var(--twc2-my,50%); }
+
+.twc2-finish{ position:absolute; top:12px; right:14px; z-index:2;
+ font-size:9px; font-weight:800; letter-spacing:.12em; text-transform:uppercase;
+ color:color-mix(in srgb, var(--twc2-rim) 70%, #fff);
+ opacity:.85; }
+.twc2-card[data-finish="matte"] .twc2-finish,
+.twc2-card[data-finish="satin"] .twc2-finish{ color:#6b7280; }
+
+.twc2-head{ position:relative; z-index:1; display:flex; align-items:center; gap:12px; }
+.twc2-avatar{ width:54px; height:54px; border-radius:14px; object-fit:cover; flex:none;
+ border:1px solid color-mix(in srgb, var(--twc2-rim) 40%, rgba(255,255,255,.1));
+ background:#0c0b12; box-shadow:0 4px 14px rgba(0,0,0,.4); }
+.twc2-avatar--ph{ display:grid; place-items:center; font:800 22px/1 Inter,system-ui,sans-serif;
+ color:rgba(255,255,255,.85);
+ background:linear-gradient(135deg, color-mix(in srgb, var(--twc2-rim) 60%, #4338ca), #8b5cf6); }
+.twc2-id{ min-width:0; flex:1; }
+.twc2-name{ margin:0 0 3px; font:700 17px/1.15 Inter,system-ui,sans-serif; color:#f5f3ff;
+ white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:100%; }
+
+.twc2-addr{ display:inline-flex; align-items:center; gap:5px; max-width:100%;
+ padding:3px 7px; border-radius:7px; cursor:pointer;
+ font:600 12.5px/1 ui-monospace,'JetBrains Mono',Menlo,monospace;
+ background:rgba(124,108,176,.1); border:1px solid rgba(124,108,176,.22);
+ color:#c4b5fd; transition:background .14s ease, border-color .14s ease; }
+.twc2-addr:hover{ background:rgba(124,108,176,.18); border-color:rgba(124,108,176,.4); }
+.twc2-addr:focus-visible{ outline:2px solid rgba(196,181,253,.7); outline-offset:2px; }
+.twc2-addr--vanity{ background:rgba(167,139,250,.16); border-color:rgba(167,139,250,.45); }
+.twc2-addr-vanity{ color:#e9d5ff; font-weight:800; }
+.twc2-addr-mid{ color:#a8a0c4; }
+.twc2-addr-dots{ color:#6b6485; margin:0 1px; }
+.twc2-spark{ color:#e9d5ff; }
+.twc2-copy-lbl{ font-family:Inter,system-ui,sans-serif; font-size:9.5px; font-weight:700;
+ letter-spacing:.06em; text-transform:uppercase; color:#8b82ac; margin-left:2px; }
+.twc2-addr.twc2-copied{ background:rgba(74,222,128,.14); border-color:rgba(74,222,128,.45); color:#86efac; }
+.twc2-addr.twc2-copied .twc2-copy-lbl,.twc2-addr.twc2-copied .twc2-addr-mid{ color:#86efac; }
+
+.twc2-marks{ display:flex; flex-direction:column; align-items:flex-end; gap:5px; flex:none; }
+.twc2-rep{ font:800 9.5px/1 Inter,system-ui,sans-serif; letter-spacing:.08em; text-transform:uppercase;
+ padding:4px 8px; border-radius:999px; color:var(--rep,#c4b5fd);
+ background:color-mix(in srgb, var(--rep,#c4b5fd) 14%, transparent);
+ border:1px solid color-mix(in srgb, var(--rep,#c4b5fd) 40%, transparent); }
+.twc2-three{ font:800 9.5px/1 Inter,system-ui,sans-serif; letter-spacing:.06em;
+ padding:4px 8px; border-radius:999px; color:#fbbf24;
+ background:rgba(251,191,36,.12); border:1px solid rgba(251,191,36,.4); white-space:nowrap; }
+
+.twc2-hero{ position:relative; z-index:1; margin:16px 0 6px; display:flex; flex-direction:column; gap:1px; }
+.twc2-hero-usd{ font:800 34px/1 Inter,system-ui,sans-serif; letter-spacing:-.02em;
+ color:#fff; text-shadow:0 2px 18px color-mix(in srgb, var(--twc2-rim) 35%, transparent); }
+.twc2-hero-sub{ font:600 10.5px/1 Inter,system-ui,sans-serif; letter-spacing:.1em; text-transform:uppercase; color:#7c7596; }
+
+.twc2-stats{ position:relative; z-index:1; display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin-top:14px; }
+.twc2-stat{ display:flex; flex-direction:column; gap:3px; padding:9px 10px; border-radius:11px;
+ background:rgba(255,255,255,.03); border:1px solid rgba(255,255,255,.06); }
+.twc2-stat--accent{ background:rgba(74,222,128,.08); border-color:rgba(74,222,128,.22); }
+.twc2-stat-val{ font:800 16px/1 Inter,system-ui,sans-serif; color:#ece9f8; }
+.twc2-stat--accent .twc2-stat-val{ color:#86efac; }
+.twc2-stat-label{ font:600 8.5px/1 Inter,system-ui,sans-serif; letter-spacing:.1em; text-transform:uppercase; color:#6f6889; }
+
+.twc2-empty-hint{ position:relative; z-index:1; margin:12px 0 0; font:500 12px/1.45 Inter,system-ui,sans-serif; color:#8b82ac; }
+
+.twc2-cta{ position:relative; z-index:1; display:flex; gap:8px; margin-top:16px; }
+.twc2-btn{ display:inline-flex; align-items:center; justify-content:center; gap:6px;
+ padding:10px 14px; border-radius:10px; cursor:pointer; text-decoration:none;
+ font:700 13px/1 Inter,system-ui,sans-serif; border:1px solid transparent;
+ transition:background .14s ease, border-color .14s ease, transform .1s ease; }
+.twc2-btn:active{ transform:translateY(1px); }
+.twc2-btn:focus-visible{ outline:2px solid rgba(196,181,253,.7); outline-offset:2px; }
+.twc2-btn-primary{ flex:1; background:linear-gradient(135deg,#8b5cf6,#7c3aed); color:#fff;
+ box-shadow:0 4px 16px rgba(124,58,237,.35); }
+.twc2-btn-primary:hover{ background:linear-gradient(135deg,#956cf8,#8b48f0); }
+.twc2-btn-ghost{ flex:1; background:rgba(255,255,255,.05); border-color:rgba(255,255,255,.1); color:#d6d2e8; }
+.twc2-btn-ghost:hover{ background:rgba(255,255,255,.09); border-color:rgba(255,255,255,.18); }
+.twc2-btn-icon{ flex:none; width:40px; padding:10px; background:rgba(255,255,255,.05);
+ border-color:rgba(255,255,255,.1); color:#c4b5fd; }
+.twc2-btn-icon:hover{ background:rgba(124,108,176,.18); border-color:rgba(124,108,176,.4); }
+
+.twc2-wm{ position:absolute; bottom:11px; right:14px; z-index:1;
+ font:800 9px/1 Inter,system-ui,sans-serif; letter-spacing:.14em; text-transform:uppercase; color:#3a3550; }
+
+/* ── Skeleton ─────────────────────────────────────────────────────────────── */
+.twc2-skel{ border-radius:18px; padding:18px; background:linear-gradient(165deg,#14121d,#0a0910);
+ border:1px solid rgba(255,255,255,.06); }
+.twc2-skel-top{ display:flex; gap:12px; align-items:center; }
+.twc2-skel-avatar{ width:54px; height:54px; border-radius:14px; flex:none; }
+.twc2-skel-lines{ flex:1; display:flex; flex-direction:column; gap:8px; }
+.twc2-skel-line{ height:12px; border-radius:6px; display:block; }
+.twc2-skel-line.w60{ width:60%; } .twc2-skel-line.w40{ width:40%; }
+.twc2-skel-hero{ height:38px; border-radius:9px; margin:18px 0 6px; width:55%; }
+.twc2-skel-stats{ display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin-top:14px; }
+.twc2-skel-stats span{ height:44px; border-radius:11px; }
+.twc2-skel-avatar,.twc2-skel-line,.twc2-skel-hero,.twc2-skel-stats span{
+ background:linear-gradient(90deg, rgba(255,255,255,.04) 25%, rgba(255,255,255,.08) 37%, rgba(255,255,255,.04) 63%);
+ background-size:400% 100%; animation:twc2-shimmer 1.4s ease infinite; }
+
+@keyframes twc2-shimmer{ 0%{ background-position:100% 0; } 100%{ background-position:-100% 0; } }
+
+@media (max-width:380px){
+ .twc2-hero-usd{ font-size:28px; }
+ .twc2-cta{ flex-wrap:wrap; }
+ .twc2-btn-primary,.twc2-btn-ghost{ flex:1 1 40%; }
+}
+
+@media (prefers-reduced-motion:reduce){
+ .twc2-card{ transition:none; }
+ .twc2-skel-avatar,.twc2-skel-line,.twc2-skel-hero,.twc2-skel-stats span{ animation:none; }
+}
+`;
+
+if (typeof window !== 'undefined') {
+ window.twsWalletCard = { mountWalletCard };
+}
diff --git a/tests/mood-model.test.js b/tests/mood-model.test.js
new file mode 100644
index 000000000..75a147061
--- /dev/null
+++ b/tests/mood-model.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest';
+import {
+ BASELINE,
+ DEFAULT_SENSITIVITY,
+ SIGNALS,
+ MOODS,
+ moodLabel,
+ makeState,
+ applySignal,
+ decay,
+ moodDistance,
+ signalFromSentiment,
+ clampSensitivity,
+} from '../src/agents/mood-model.js';
+
+describe('mood-model', () => {
+ it('starts at a calm, mildly-positive baseline', () => {
+ const s = makeState();
+ expect(s.valence).toBeCloseTo(BASELINE.valence);
+ expect(s.arousal).toBeCloseTo(BASELINE.arousal);
+ expect(moodLabel(s.valence, s.arousal).key).toBe('calm');
+ });
+
+ it('projects the circumplex into the documented discrete octants', () => {
+ expect(moodLabel(0.6, 0.8).key).toBe('elated');
+ expect(moodLabel(0.6, 0.3).key).toBe('content');
+ expect(moodLabel(-0.6, 0.8).key).toBe('agitated');
+ expect(moodLabel(-0.6, 0.3).key).toBe('subdued');
+ expect(moodLabel(0.0, 0.8).key).toBe('alert');
+ expect(moodLabel(0.0, 0.2).key).toBe('calm');
+ });
+
+ it('every mood declares a real embodiment trigger + emoji + colour', () => {
+ const triggers = new Set(['celebration', 'concern', 'curiosity', 'empathy', 'patience', 'uncertain']);
+ for (const m of MOODS) {
+ expect(triggers.has(m.trigger)).toBe(true);
+ expect(m.emoji.length).toBeGreaterThan(0);
+ expect(m.color).toMatch(/^#[0-9a-f]{6}$/i);
+ expect(m.intensity).toBeGreaterThan(0);
+ }
+ });
+
+ it('applies a known signal scaled by sensitivity and weight', () => {
+ const s = makeState();
+ const after = applySignal(s, 'action:success', { sensitivity: 1, weight: 1 });
+ expect(after.valence).toBeGreaterThan(s.valence);
+ expect(after.arousal).toBeGreaterThan(s.arousal);
+ // The dv/da come straight from the catalogue at full gain.
+ expect(after.valence).toBeCloseTo(BASELINE.valence + SIGNALS['action:success'].dv);
+ });
+
+ it('a stoic agent (sensitivity 0) never leaves baseline', () => {
+ const s = makeState();
+ const after = applySignal(s, 'alert:bad', { sensitivity: 0 });
+ expect(after.valence).toBeCloseTo(s.valence);
+ expect(after.arousal).toBeCloseTo(s.arousal);
+ });
+
+ it('accepts an explicit {dv,da} delta as well as a catalogue key', () => {
+ const s = makeState();
+ const after = applySignal(s, { dv: -0.2, da: 0.1 }, { sensitivity: 1 });
+ expect(after.valence).toBeLessThan(s.valence);
+ expect(after.arousal).toBeGreaterThan(s.arousal);
+ });
+
+ it('ignores an unknown signal key (no movement)', () => {
+ const s = { valence: 0.5, arousal: 0.5 };
+ const after = applySignal(s, 'nope:nope', { sensitivity: 1 });
+ expect(after).toEqual(s);
+ });
+
+ it('clamps valence to [-1,1] and arousal to [0,1] under repeated signals', () => {
+ let s = makeState();
+ for (let i = 0; i < 50; i++) s = applySignal(s, 'alert:good', { sensitivity: 1 });
+ expect(s.valence).toBeLessThanOrEqual(1);
+ expect(s.arousal).toBeLessThanOrEqual(1);
+ let t = makeState();
+ for (let i = 0; i < 50; i++) t = applySignal(t, 'action:failure', { sensitivity: 1 });
+ expect(t.valence).toBeGreaterThanOrEqual(-1);
+ expect(t.arousal).toBeLessThanOrEqual(1);
+ });
+
+ it('decays toward baseline and is frame-rate independent', () => {
+ const spiked = { valence: 0.9, arousal: 0.9 };
+ const oneStep = decay(spiked, 60_000);
+ // Many small steps over the same elapsed time land in the same place.
+ let many = spiked;
+ for (let i = 0; i < 600; i++) many = decay(many, 100);
+ expect(many.valence).toBeCloseTo(oneStep.valence, 3);
+ expect(many.arousal).toBeCloseTo(oneStep.arousal, 3);
+ // And it moved toward baseline, not past it.
+ expect(oneStep.valence).toBeLessThan(spiked.valence);
+ expect(oneStep.valence).toBeGreaterThan(BASELINE.valence);
+ expect(oneStep.arousal).toBeLessThan(spiked.arousal);
+ });
+
+ it('decay eventually settles to baseline', () => {
+ let s = { valence: -0.8, arousal: 0.95 };
+ for (let i = 0; i < 100; i++) s = decay(s, 60_000);
+ expect(s.valence).toBeCloseTo(BASELINE.valence, 2);
+ expect(s.arousal).toBeCloseTo(BASELINE.arousal, 2);
+ });
+
+ it('arousal decays faster than valence (lingering mood)', () => {
+ const spiked = { valence: 0.9, arousal: 0.9 };
+ const d = decay(spiked, 70_000);
+ const valenceDrop = spiked.valence - d.valence;
+ const arousalDrop = spiked.arousal - d.arousal;
+ expect(arousalDrop).toBeGreaterThan(valenceDrop);
+ });
+
+ it('derives a sentiment signal only from a non-neutral score', () => {
+ expect(signalFromSentiment(0)).toBeNull();
+ expect(signalFromSentiment(0.02)).toBeNull();
+ const pos = signalFromSentiment(0.5);
+ expect(pos.signal).toBe('chat:positive');
+ expect(pos.weight).toBeGreaterThan(0);
+ const neg = signalFromSentiment(-0.5);
+ expect(neg.signal).toBe('chat:negative');
+ });
+
+ it('moodDistance is symmetric and zero for identical points', () => {
+ const a = { valence: 0.2, arousal: 0.4 };
+ const b = { valence: -0.3, arousal: 0.7 };
+ expect(moodDistance(a, a)).toBe(0);
+ expect(moodDistance(a, b)).toBeCloseTo(moodDistance(b, a));
+ expect(moodDistance(a, b)).toBeGreaterThan(0);
+ });
+
+ it('clampSensitivity falls back to the default for garbage', () => {
+ expect(clampSensitivity(NaN)).toBe(DEFAULT_SENSITIVITY);
+ expect(clampSensitivity(2)).toBe(1);
+ expect(clampSensitivity(-1)).toBe(0);
+ expect(clampSensitivity(0.4)).toBe(0.4);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 975cff550..993b00761 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2801,6 +2801,10 @@
"src": "/api/og/three-token-badge",
"dest": "/api/og/three-token-badge.js"
},
+ {
+ "src": "/agent/([^/]+)/mind/?",
+ "dest": "/agent-mind.html"
+ },
{
"src": "/agent/([^/]+)/edit",
"dest": "/agent-edit.html"
@@ -4207,6 +4211,10 @@
"path": "/api/cron/three-holders-snapshot",
"schedule": "*/5 * * * *"
},
+ {
+ "path": "/api/cron/custody-attest",
+ "schedule": "17 */6 * * *"
+ },
{
"path": "/api/cron/pumpfun-monitor",
"schedule": "*/3 * * * *"
diff --git a/vite.config.js b/vite.config.js
index 111b00681..165f15e55 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -332,6 +332,7 @@ const appConfig = {
'marketplace-analytics': resolve(__dirname, 'pages/marketplace-analytics.html'),
collection: resolve(__dirname, 'pages/collection.html'),
'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),
+ 'agent-mind': resolve(__dirname, 'pages/agent-mind.html'),
'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),
'create-video': resolve(__dirname, 'pages/create/video.html'),
'extension-privacy': resolve(__dirname, 'pages/extension-privacy.html'),
@@ -1186,6 +1187,8 @@ support: resolve(__dirname, 'pages/support.html'),
filePath = resolve(root, 'pages/agent-wallet.html');
else if (!filePath && /^\/agents\/[^/.]+\/?$/.test(path))
filePath = resolve(root, 'pages/agent-detail.html');
+ else if (!filePath && /^\/agent\/[^/]+\/mind\/?$/.test(path))
+ filePath = resolve(root, 'pages/agent-mind.html');
else if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path))
filePath = resolve(root, 'pages/agent-edit.html');
else if (!filePath && /^\/agent\/[^/]+\/embed$/.test(path))