Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add agent reflection/dreams, alpha co-pilot, vaults, theater feed, and economy shaping
nirholas36db02742cb0
diff --git a/api/_lib/alpha-read.js b/api/_lib/alpha-read.jsnew file mode 100644index 000000000..c7fae9f95--- /dev/null+++ b/api/_lib/alpha-read.js@@ -0,0 +1,299 @@+// In-Character Alpha Co-pilot — the grounding + validation core (pure, no I/O).+//+// The agent's LLM persona reads a REAL live launch and returns a structured+// verdict plus a short in-character line its avatar will speak aloud. This+// module owns everything that must be deterministic and testable:+// - buildReadPrompt: the persona-grounded prompt, fed ONLY real signals+// - parseReadJson: tolerant extraction of the model's JSON object+// - validateRead: clamp/repair the model output against the real inputs+// (the anti-hallucination layer) and derive the action gate+//+// The cardinal rule (the prompt's "touching money" guardrails): the model may+// only ever speak numbers we actually fetched. validateRead re-derives the+// verdict's allowed shape, clamps any suggested size to the live spend policy ++// wallet balance, and scrubs the spoken line of fabricated figures — replacing+// it with a grounded, templated line rather than ever voicing an invented price,+// liquidity, or holder count. The UI also renders the real `signals` beside the+// read so ground truth is always visible.+//+// No I/O, no heavy imports — api/agents/alpha.js fetches the real signals and+// calls these; tests exercise them directly.++export const VERDICTS = Object.freeze(['snipe', 'watch', 'pass']);+const VERDICT_SET = new Set(VERDICTS);++// Kept above a buy so it never fails for lack of lamports to pay fees / open the+// token ATA. Mirrors SOL_FEE_HEADROOM_LAMPORTS (0.003 SOL) in agent-trade-guards.+export const SIZE_HEADROOM_SOL = 0.003;++const num = (v) => (v == null || !Number.isFinite(Number(v)) ? null : Number(v));+const round4 = (n) => Math.round(n * 1e4) / 1e4;++// ── prompt ──────────────────────────────────────────────────────────────────++/**+ * Build the persona-grounded read prompt. The model sees ONLY the real signals+ * we pass and is told, in no uncertain terms, never to invent a number.+ *+ * @param {object} o+ * @param {string} o.agentName+ * @param {string} [o.persona] the agent's persona_prompt (its voice + risk stance)+ * @param {string} o.network+ * @param {object} o.signals the real, fetched signal bundle (see alpha.js)+ * @param {boolean} o.owner whether the viewer owns the wallet (size advice on)+ * @returns {{ system: string, user: string }}+ */+export function buildReadPrompt({ agentName, persona, network, signals, owner }) {+ const base = (persona || '').trim();+ const system = [+ base ? `You speak in character as ${agentName}. Persona:\n${base}\n` : `You are ${agentName}, an on-chain trading agent with a distinct voice.`,+ `You are the IN-CHARACTER ALPHA CO-PILOT for the three.ws agent "${agentName}" and its self-custodied Solana wallet (network: ${network}).`,+ `A real pump.fun launch is in front of you. You will judge it OUT LOUD, in character, and decide what you would do.`,+ ``,+ `ABSOLUTE RULES (you are reasoning about real money):`,+ `• You may ONLY use the numbers in the SIGNALS JSON below. Never invent or estimate a price, liquidity, market cap, holder count, score, or percentage. If a signal is null, say it's unknown — do not guess it.`,+ `• Your "spoken_line" is read aloud by your 3D avatar: 1–3 sentences, in your voice, conversational, no markdown, no lists, no emojis. Reference at most one or two concrete signals — and only ones present in SIGNALS.`,+ `• Let your PERSONA shape the call. A cautious agent and an aggressive agent should reach different conclusions on the same data. Reason about conflicting signals honestly rather than hyping.`,+ `• This is your opinion grounded in data, NOT financial advice or a guaranteed call. Surface the real risks.`,+ `• "verdict" is one of: "snipe" (you'd take a position now), "watch" (interesting, not yet), "pass" (not for you).`,+ owner+ ? `• If you say "snipe", suggest a position size in SOL that respects the wallet balance and limits in SIGNALS. Stay small and sane. If signals are thin or risky, prefer "watch" or "pass".`+ : `• You are speaking publicly (this viewer is not the owner). Do not suggest a position size; "suggested_size_sol" must be null.`,+ ``,+ `Respond with ONLY a JSON object, no prose around it, exactly this shape:`,+ `{"verdict":"snipe|watch|pass","conviction":0-100,"suggested_size_sol":number|null,"risks":["short risk", ...],"cited_signals":["signal name you used", ...],"spoken_line":"what your avatar says aloud"}`,+ ].join('\n');++ const user = [+ `SIGNALS (the only real data you have — every number you speak must come from here):`,+ JSON.stringify(signals, null, 2),+ ``,+ `Give your in-character read as the JSON object specified. Be honest. If nothing here is compelling, say so plainly and verdict "pass".`,+ ].join('\n');++ return { system, user };+}++// ── parsing ───────────────────────────────────────────────────────────────────++/** Tolerantly pull the first JSON object out of a model response. */+export function parseReadJson(text) {+ if (typeof text !== 'string' || !text.trim()) return null;+ // Fast path: clean JSON.+ try { return JSON.parse(text); } catch { /* fall through */ }+ // Strip code fences, then grab the outermost balanced {...}.+ const cleaned = text.replace(/```json|```/gi, '');+ const start = cleaned.indexOf('{');+ if (start < 0) return null;+ let depth = 0;+ for (let i = start; i < cleaned.length; i++) {+ const ch = cleaned[i];+ if (ch === '{') depth++;+ else if (ch === '}') {+ depth--;+ if (depth === 0) {+ try { return JSON.parse(cleaned.slice(start, i + 1)); } catch { return null; }+ }+ }+ }+ return null;+}++// ── anti-hallucination: number grounding ───────────────────────────────────────++/** Pull standalone numbers out of free text (handles 1,234 / 12.5 / 3k / 2m). */+export function extractNumbers(text) {+ if (typeof text !== 'string') return [];+ const out = [];+ const re = /(\d[\d,]*\.?\d*)\s*([kmb])?/gi;+ let m;+ while ((m = re.exec(text))) {+ let n = parseFloat(m[1].replace(/,/g, ''));+ if (!Number.isFinite(n)) continue;+ const suffix = (m[2] || '').toLowerCase();+ if (suffix === 'k') n *= 1e3;+ else if (suffix === 'm') n *= 1e6;+ else if (suffix === 'b') n *= 1e9;+ out.push(n);+ }+ return out;+}++/** Every real numeric value a read is allowed to voice, plus its k / m forms. */+export function collectSignalNumbers(signals, extra = []) {+ const vals = new Set();+ const add = (v) => {+ const n = num(v);+ if (n == null) return;+ vals.add(Math.abs(n));+ vals.add(Math.abs(Math.round(n)));+ if (Math.abs(n) >= 1000) { vals.add(Math.round(Math.abs(n) / 1e3)); vals.add(Math.round(Math.abs(n) / 1e3) * 1e3); }+ if (Math.abs(n) >= 1e6) { vals.add(Math.round(Math.abs(n) / 1e6)); vals.add(Math.round(Math.abs(n) / 1e6) * 1e6); }+ };+ const walk = (o) => {+ if (o == null) return;+ if (typeof o === 'number') return add(o);+ if (Array.isArray(o)) return o.forEach(walk);+ if (typeof o === 'object') return Object.values(o).forEach(walk);+ };+ walk(signals);+ extra.forEach(add);+ return vals;+}++const GROUNDING_TOLERANCE = 0.04; // 4% — a spoken "≈72" still matches a 72.3 score++function matchesAllowed(n, allowed) {+ const a = Math.abs(n);+ if (allowed.has(a) || allowed.has(Math.round(a))) return true;+ for (const v of allowed) {+ if (v === 0) { if (a === 0) return true; continue; }+ if (Math.abs(a - v) / Math.abs(v) <= GROUNDING_TOLERANCE) return true;+ }+ return false;+}++/**+ * Flag any specific number in the spoken line / risks that does not trace to a+ * real signal. Small integers (≤ 12 — "two risk flags", "3 wallets", a year-ish+ * count) and bare years pass; large or precise unmatched figures are suspicious.+ * @returns {{ ok: boolean, suspicious: number[] }}+ */+export function checkGrounding(texts, allowed) {+ const suspicious = [];+ for (const t of texts) {+ for (const n of extractNumbers(t)) {+ if (Math.abs(n) <= 12 && Number.isInteger(n)) continue; // benign small counts+ if (matchesAllowed(n, allowed)) continue;+ suspicious.push(n);+ }+ }+ return { ok: suspicious.length === 0, suspicious };+}++// ── size clamping ──────────────────────────────────────────────────────────────++/**+ * Clamp a model-suggested position size to the live spend policy AND wallet+ * balance. Returns a safe number (≥ 0) or null when no size applies. Execution+ * still re-checks server-side; this is the advisory clamp shown to the owner.+ */+export function clampSize(suggested, { perTradeSol = null, balanceSol = null, dailyBudgetSol = null, dailySpentSol = 0 } = {}) {+ let s = num(suggested);+ if (s == null || s <= 0) return null;+ if (perTradeSol != null) s = Math.min(s, perTradeSol);+ if (dailyBudgetSol != null) s = Math.min(s, Math.max(0, dailyBudgetSol - (num(dailySpentSol) || 0)));+ if (balanceSol != null) s = Math.min(s, Math.max(0, balanceSol - SIZE_HEADROOM_SOL));+ if (!(s > 0)) return 0;+ return round4(s);+}++// ── validation + gate ───────────────────────────────────────────────────────────++/** A deterministic, grounded line to speak when the model's line is unusable. */+export function templatedSpokenLine(verdict, agentName, signals) {+ const sym = signals?.symbol ? `$${signals.symbol}` : 'this launch';+ if (verdict === 'snipe') return `I like what I'm seeing on ${sym}. The signals line up for me — I'd take a small position here.`;+ if (verdict === 'pass') return `I'm passing on ${sym}. The data in front of me doesn't earn a position right now.`;+ return `${sym} is worth watching, but I'm not convinced yet — I want cleaner signals before I commit.`;+}++function cleanLine(s) {+ if (typeof s !== 'string') return '';+ return s.replace(/\s+/g, ' ').replace(/[*_`#>]/g, '').trim().slice(0, 360);+}++/**+ * Repair + ground the raw model output against the real signals, and derive the+ * owner action gate. Pure — caller supplies the live wallet/limit context.+ *+ * @param {object} o+ * @param {object|null} o.raw parsed model JSON (or null on parse failure)+ * @param {object} o.signals the real signal bundle+ * @param {string} o.agentName+ * @param {boolean} o.owner+ * @param {object} [o.context] { balanceSol, perTradeSol, dailyBudgetSol, dailySpentSol, killSwitch, frozen }+ * @returns {{ read: object, gate: object }}+ */+export function validateRead({ raw, signals, agentName, owner, context = {} }) {+ const r = raw && typeof raw === 'object' ? raw : {};++ let verdict = typeof r.verdict === 'string' ? r.verdict.toLowerCase().trim() : '';+ if (!VERDICT_SET.has(verdict)) verdict = 'watch';++ let conviction = num(r.conviction);+ conviction = conviction == null ? 50 : Math.max(0, Math.min(100, Math.round(conviction)));++ const risks = Array.isArray(r.risks)+ ? r.risks.map(cleanLine).filter(Boolean).slice(0, 5)+ : [];+ const citedSignals = Array.isArray(r.cited_signals)+ ? r.cited_signals.map((s) => cleanLine(String(s))).filter(Boolean).slice(0, 6)+ : [];++ // Size only ever applies to the owner on a "snipe", and is clamped to policy.+ let suggestedSize = null;+ if (owner && verdict === 'snipe') {+ suggestedSize = clampSize(r.suggested_size_sol, {+ perTradeSol: num(context.perTradeSol),+ balanceSol: num(context.balanceSol),+ dailyBudgetSol: num(context.dailyBudgetSol),+ dailySpentSol: num(context.dailySpentSol) || 0,+ });+ }++ // Number grounding: never voice a fabricated figure. Allowed = every real+ // signal value plus the (already-grounded) conviction and clamped size.+ const allowed = collectSignalNumbers(signals, [conviction, suggestedSize]);+ let spokenLine = cleanLine(r.spoken_line);+ const grounding = checkGrounding([spokenLine, ...risks], allowed);+ let guardOk = grounding.ok && !!spokenLine;+ if (!guardOk) spokenLine = templatedSpokenLine(verdict, agentName, signals);++ const read = {+ verdict,+ conviction,+ suggested_size_sol: suggestedSize,+ risks,+ cited_signals: citedSignals,+ spoken_line: spokenLine,+ hallucination_guard: {+ ok: guardOk,+ // What we caught + did about it, so the UI can show the honest note.+ suspicious_numbers: grounding.suspicious,+ line_replaced: !guardOk,+ },+ };++ const gate = deriveGate({ owner, verdict, suggestedSize, signals, context });+ return { read, gate };+}++/**+ * The advisory action gate shown to the owner. Mirrors the trade-guard+ * predicates so the UI never offers an action the server would reject — but the+ * server (executeAgentTrade → /solana/trade) remains the source of truth and+ * re-checks every guard at execution time.+ */+export function deriveGate({ owner, verdict, suggestedSize, signals, context = {} }) {+ if (!owner) return { can_act: false, reason: 'not_owner', message: 'Sign in as the owner to act on this read.' };+ if (verdict !== 'snipe') return { can_act: false, reason: 'not_actionable', message: `${agentVerb(verdict)} — nothing to execute.` };+ if (context.frozen) return { can_act: false, reason: 'wallet_frozen', message: 'Wallet is frozen. Unfreeze it under Limits & Safety to act.' };+ if (context.killSwitch) return { can_act: false, reason: 'kill_switch', message: 'Trading is paused (kill switch). Re-enable it to act.' };+ if (!(suggestedSize > 0)) {+ const bal = num(context.balanceSol);+ if (bal != null && bal <= SIZE_HEADROOM_SOL) return { can_act: false, reason: 'insufficient_sol', message: 'Fund the agent wallet to act on a snipe.' };+ return { can_act: false, reason: 'no_size', message: 'No sane position size fits the current limits — adjust limits or fund the wallet.' };+ }+ return {+ can_act: true,+ reason: 'ok',+ message: `Ready to buy ◎${suggestedSize} SOL — confirm to execute within your limits.`,+ size_sol: suggestedSize,+ };+}++function agentVerb(verdict) {+ if (verdict === 'pass') return 'Passing on this one';+ return 'Watching, not buying yet';+}diff --git a/api/_lib/brain-bundle.js b/api/_lib/brain-bundle.jsnew file mode 100644index 000000000..43120e35f--- /dev/null+++ b/api/_lib/brain-bundle.js@@ -0,0 +1,381 @@+/**+ * Portable brain bundle — the `.brain` file format.+ *+ * A schema-versioned, self-describing snapshot of an agent's mind: its persona,+ * a curated set of (signed) memories, an optional on-chain anchor, and a+ * manifest whose `brain_hash` content-addresses the whole set. The bundle is+ * itself signed by the agent's wallet, so a recipient can verify — entirely+ * offline — both that each memory was authored by the agent and that the+ * collection was exported as a coherent, untampered whole.+ *+ * Private memories never travel in the clear: in `encrypted-ipfs` mode their+ * plaintext is replaced by a reference to the wallet-encrypted IPFS object+ * (the owner moves the ciphertext + the key; we cannot read it). In a plaintext+ * export the owner must explicitly opt into including private content, and the+ * UI confirms that consequence.+ *+ * Validation uses zod (already a platform dependency) so import rejects a+ * malformed or partial bundle before it can reconstitute a broken mind.+ */++import { createHash } from 'node:crypto';+import { z } from 'zod';+import { verifyMessage } from 'ethers';++import { memoryDigest, verifyMemorySignature, signDigest, signMessageBody } from './brain-sign.js';++export const BRAIN_BUNDLE_VERSION = 'brain/1';+export const BRAIN_HASH_VERSION = 'threews:brain:hash:v1';++const hexHash = z.string().regex(/^[a-f0-9]{64}$/i);++const memoryEntrySchema = z.object({+ id: z.string(),+ type: z.enum(['user', 'feedback', 'project', 'reference']),+ tags: z.array(z.string()).default([]),+ salience: z.number().min(0).max(1).default(0.5),+ tier: z.enum(['working', 'recall', 'archival']).default('recall'),+ is_public: z.boolean().default(false),+ created_at: z.string(),+ // Exactly one of `content` (plaintext) or `cipher` (encrypted reference) is present.+ content: z.string().optional(),+ cipher: z+ .object({+ scheme: z.literal('wallet-aes-gcm-v1'),+ cid: z.string().min(1),+ filename: z.string().min(1),+ })+ .optional(),+ content_hash: hexHash.optional(),+ signature: z.string().optional(),+ signer_address: z.string().optional(),+ signed_at: z.string().nullable().optional(),+});++const anchorSchema = z+ .object({+ brain_hash: hexHash,+ proof_uri: z.string().url().optional(),+ proof_hash: z.string().optional(),+ tx_hash: z.string().optional(),+ chain_id: z.number().int().optional(),+ anchored_at: z.string().optional(),+ explorer_url: z.string().url().nullable().optional(),+ })+ .nullable();++export const brainBundleSchema = z.object({+ version: z.literal(BRAIN_BUNDLE_VERSION),+ exported_at: z.string(),+ agent: z.object({+ id: z.string(),+ name: z.string().nullable().optional(),+ description: z.string().nullable().optional(),+ avatar_id: z.string().nullable().optional(),+ chain_id: z.number().int().nullable().optional(),+ erc8004_agent_id: z.union([z.string(), z.number()]).nullable().optional(),+ wallet_address: z.string().nullable().optional(),+ }),+ persona: z+ .object({+ prompt: z.string().nullable().optional(),+ prompt_hash: z.string().nullable().optional(),+ prompt_sig: z.string().nullable().optional(),+ tone_tags: z.array(z.string()).default([]),+ extracted_at: z.string().nullable().optional(),+ })+ .nullable(),+ memories: z.array(memoryEntrySchema),+ anchor: anchorSchema.optional(),+ manifest: z.object({+ memory_count: z.number().int(),+ public_count: z.number().int(),+ private_count: z.number().int(),+ encrypted_count: z.number().int(),+ brain_hash: hexHash,+ signer_address: z.string().nullable().optional(),+ persona_prompt_hash: z.string().nullable().optional(),+ }),+ // The agent-wallet signature over the manifest.brain_hash. Null when the+ // agent has no provisioned wallet (bundle is then portable but unsigned).+ signature: z+ .object({+ brain_hash: hexHash,+ value: z.string(),+ signer_address: z.string(),+ })+ .nullable(),+ // Provenance is set on a forked/imported bundle so the chain of custody is+ // preserved across owners.+ provenance: z+ .object({+ source_agent_id: z.string(),+ source_brain_hash: hexHash,+ forked_at: z.string(),+ })+ .nullable()+ .optional(),+});++/**+ * Content-address a brain state. Deterministic over the persona hash and the+ * sorted set of memory content-hashes — the same curated mind always yields the+ * same hash, which is what makes the on-chain anchor and the bundle signature+ * meaningful. This exact value is what gets anchored on-chain.+ *+ * @param {object} p+ * @param {string|null} p.personaPromptHash+ * @param {string[]} p.memoryHashes content_hash of each included memory+ * @param {string} p.agentId+ * @returns {string} 64-char hex+ */+export function computeBrainHash({ personaPromptHash = null, memoryHashes = [], agentId = '' }) {+ const sorted = [...memoryHashes].filter(Boolean).map((h) => h.toLowerCase()).sort();+ const core = JSON.stringify({+ v: BRAIN_HASH_VERSION,+ agentId: String(agentId),+ persona: personaPromptHash ? String(personaPromptHash).toLowerCase() : null,+ memories: sorted,+ });+ return createHash('sha256').update(core).digest('hex');+}++/**+ * Build a memory entry for the bundle from a DB row, honoring the storage mode.+ * In encrypted-ipfs mode a private memory's plaintext is dropped in favor of a+ * cipher reference (must have been pinned already); public memories stay plain.+ *+ * @param {object} row agent_memories row (snake_case)+ * @param {object} opts+ * @param {boolean} opts.includePrivatePlaintext include private plaintext (explicit opt-in)+ * @param {Map<string,{cid:string,filename:string}>} [opts.cipherRefs] memoryId → pinned cipher ref+ * @returns {object|null} bundle memory entry, or null if a private memory must be excluded+ */+export function buildMemoryEntry(row, { includePrivatePlaintext = false, cipherRefs = new Map() } = {}) {+ const isPublic = row.is_public === true;+ const content_hash = row.content_hash || memoryDigest(row);+ const base = {+ id: String(row.id),+ type: row.type || 'project',+ tags: Array.isArray(row.tags) ? row.tags : [],+ salience: typeof row.salience === 'number' ? row.salience : 0.5,+ tier: row.tier || 'recall',+ is_public: isPublic,+ created_at: new Date(row.created_at ?? row.createdAt ?? Date.now()).toISOString(),+ content_hash,+ signature: row.signature || undefined,+ signer_address: row.signer_address || undefined,+ signed_at: row.signed_at || row.signedAt || null,+ };++ if (isPublic || includePrivatePlaintext) {+ return { ...base, content: String(row.content ?? '') };+ }++ // Private + not opted into plaintext: only travel as an encrypted reference.+ const ref = cipherRefs.get(String(row.id));+ if (ref) {+ return { ...base, cipher: { scheme: 'wallet-aes-gcm-v1', cid: ref.cid, filename: ref.filename } };+ }+ return null;+}++/**+ * Assemble a full bundle and (optionally) sign it with the agent wallet key.+ *+ * @param {object} p+ * @param {object} p.agent agent identity row+ * @param {object|null} p.persona persona fields+ * @param {object[]} p.memoryEntries entries from buildMemoryEntry (no nulls)+ * @param {object|null} [p.anchor] on-chain anchor record+ * @param {object|null} [p.provenance]+ * @param {string} p.exportedAt ISO timestamp (server-supplied)+ * @param {string|null} [p.signerPrivKey] agent private key to sign the brain_hash+ * @returns {Promise<object>} validated bundle+ */+export async function buildBundle({+ agent,+ persona,+ memoryEntries,+ anchor = null,+ provenance = null,+ exportedAt,+ signerPrivKey = null,+}) {+ const memoryHashes = memoryEntries.map((m) => m.content_hash).filter(Boolean);+ const personaPromptHash = persona?.prompt_hash || null;+ const brainHash = computeBrainHash({ personaPromptHash, memoryHashes, agentId: agent.id });++ const publicCount = memoryEntries.filter((m) => m.is_public).length;+ const encryptedCount = memoryEntries.filter((m) => m.cipher).length;++ let signature = null;+ let signerAddress = agent.wallet_address || null;+ if (signerPrivKey) {+ const { signature: value, signer_address } = await signDigest(signerPrivKey, brainHash);+ signature = { brain_hash: brainHash, value, signer_address };+ signerAddress = signer_address;+ }++ const bundle = {+ version: BRAIN_BUNDLE_VERSION,+ exported_at: exportedAt,+ agent: {+ id: String(agent.id),+ name: agent.name ?? null,+ description: agent.description ?? null,+ avatar_id: agent.avatar_id ?? null,+ chain_id: agent.chain_id ?? null,+ erc8004_agent_id: agent.erc8004_agent_id != null ? String(agent.erc8004_agent_id) : null,+ wallet_address: agent.wallet_address ?? null,+ },+ persona: persona+ ? {+ prompt: persona.prompt ?? null,+ prompt_hash: persona.prompt_hash ?? null,+ prompt_sig: persona.prompt_sig ?? null,+ tone_tags: persona.tone_tags ?? [],+ extracted_at: persona.extracted_at ?? null,+ }+ : null,+ memories: memoryEntries,+ anchor,+ manifest: {+ memory_count: memoryEntries.length,+ public_count: publicCount,+ private_count: memoryEntries.length - publicCount,+ encrypted_count: encryptedCount,+ brain_hash: brainHash,+ signer_address: signerAddress,+ persona_prompt_hash: personaPromptHash,+ },+ signature,+ provenance,+ };++ // Validate our own output — a build bug must never ship a malformed bundle.+ return brainBundleSchema.parse(bundle);+}++/**+ * Verify a bundle end-to-end. Pure — the offline trust check a buyer/forker runs.+ * Reports per-memory verdicts plus aggregate integrity (brain_hash recompute,+ * manifest consistency, bundle signature).+ *+ * @param {object} bundle+ * @returns {{+ * valid: boolean,+ * schemaValid: boolean,+ * brainHashValid: boolean,+ * bundleSignatureValid: boolean|null,+ * memories: Array<{ id: string, signed: boolean, valid: boolean, reason: string, recovered: string|null }>,+ * signedCount: number,+ * verifiedCount: number,+ * errors: string[],+ * }}+ */+export function verifyBundle(bundle) {+ const errors = [];+ const parsed = brainBundleSchema.safeParse(bundle);+ if (!parsed.success) {+ return {+ valid: false,+ schemaValid: false,+ brainHashValid: false,+ bundleSignatureValid: null,+ memories: [],+ signedCount: 0,+ verifiedCount: 0,+ errors: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),+ };+ }+ const b = parsed.data;++ // Per-memory signature verification. Encrypted (cipher) entries can't be+ // content-verified offline without the key — report them honestly as+ // "encrypted", neither pass nor forged.+ const memories = b.memories.map((m) => {+ if (m.cipher) {+ return { id: m.id, signed: Boolean(m.signature), valid: false, reason: 'encrypted', recovered: null };+ }+ const v = verifyMemorySignature(+ { id: m.id, agent_id: b.agent.id, type: m.type, content: m.content, tags: m.tags, created_at: m.created_at },+ { signature: m.signature, signer_address: m.signer_address, content_hash: m.content_hash },+ );+ return { id: m.id, signed: Boolean(m.signature), valid: v.valid, reason: v.reason, recovered: v.recovered };+ });++ const signedCount = memories.filter((m) => m.signed).length;+ const verifiedCount = memories.filter((m) => m.valid).length;++ // Recompute the brain_hash over the included memory content-hashes.+ const recomputed = computeBrainHash({+ personaPromptHash: b.manifest.persona_prompt_hash,+ memoryHashes: b.memories.map((m) => m.content_hash).filter(Boolean),+ agentId: b.agent.id,+ });+ const brainHashValid = recomputed.toLowerCase() === b.manifest.brain_hash.toLowerCase();+ if (!brainHashValid) errors.push('brain_hash does not match the included memory set');++ // Manifest counts must match the actual array.+ const publicCount = b.memories.filter((m) => m.is_public).length;+ const encryptedCount = b.memories.filter((m) => m.cipher).length;+ if (b.manifest.memory_count !== b.memories.length) errors.push('manifest.memory_count mismatch');+ if (b.manifest.public_count !== publicCount) errors.push('manifest.public_count mismatch');+ if (b.manifest.encrypted_count !== encryptedCount) errors.push('manifest.encrypted_count mismatch');++ // Bundle signature over the brain_hash.+ let bundleSignatureValid = null;+ if (b.signature) {+ if (b.signature.brain_hash.toLowerCase() !== b.manifest.brain_hash.toLowerCase()) {+ bundleSignatureValid = false;+ errors.push('bundle signature is over a different brain_hash');+ } else {+ bundleSignatureValid = verifyBrainHashSignature(b.manifest.brain_hash, b.signature);+ if (!bundleSignatureValid) errors.push('bundle signature failed to verify');+ }+ }++ // A bundle is valid when: schema ok, brain_hash consistent, manifest+ // consistent, bundle signature (if present) verifies, and every+ // *signed plaintext* memory verifies. Unsigned or encrypted memories do not+ // fail the bundle — they are reported, not penalized.+ const plaintextSignedAllValid = memories+ .filter((m) => m.signed && m.reason !== 'encrypted')+ .every((m) => m.valid);++ const valid =+ brainHashValid &&+ errors.length === 0 &&+ (bundleSignatureValid === null || bundleSignatureValid === true) &&+ plaintextSignedAllValid;++ return {+ valid,+ schemaValid: true,+ brainHashValid,+ bundleSignatureValid,+ memories,+ signedCount,+ verifiedCount,+ errors,+ };+}++/**+ * Verify an ERC-191 signature over a brain_hash (the bundle-level signature).+ * signDigest(privKey, brainHash) signs `signMessageBody(brainHash)`, so verify+ * with the identical framing.+ *+ * @param {string} brainHash+ * @param {{ value: string, signer_address: string }} signature+ * @returns {boolean}+ */+export function verifyBrainHashSignature(brainHash, signature) {+ try {+ const recovered = verifyMessage(signMessageBody(brainHash), signature.value);+ return recovered.toLowerCase() === String(signature.signer_address).toLowerCase();+ } catch {+ return false;+ }+}diff --git a/api/_lib/brain-sign.js b/api/_lib/brain-sign.jsnew file mode 100644index 000000000..ab8d9b7d1--- /dev/null+++ b/api/_lib/brain-sign.js@@ -0,0 +1,218 @@+/**+ * Signed memory — the integrity + authorship layer of the Portable & Verifiable Brain.+ *+ * Every memory an agent commits is signed by the agent's own EVM wallet+ * (the same secp256k1 key behind its ERC-8004 on-chain identity) using ERC-191+ * `personal_sign`. The signature is publicly verifiable: anyone holding the+ * memory and the agent's wallet address can `ecrecover` the signer and confirm+ * the content was authored by that agent and has not been tampered with. This+ * is what makes a forked or purchased brain trustworthy — its history is+ * cryptographically provable, not a claim in our database.+ *+ * The module is split deliberately:+ * - Pure functions (canonicalizeMemory, memoryDigest, signMessageBody,+ * verifyMemorySignature) have no DB or wallet dependency and are unit-tested+ * directly — they are the verification primitive a buyer/forker runs.+ * - signMemoryWithAgent / loadAgentSigner touch the DB + custodial key vault+ * (recoverAgentKey) and are exercised through the live endpoints.+ *+ * Signing is best-effort at the write boundary: an agent without a provisioned+ * wallet stores its memory unsigned (signature null) rather than failing the+ * write. The verification path reports "unsigned" honestly — never a fake green+ * check.+ */++import { createHash } from 'node:crypto';+import { Wallet, verifyMessage, computeAddress } from 'ethers';++import { sql } from './db.js';+import { recoverAgentKey } from './agent-wallet.js';++// Bump this prefix on any breaking change to the canonical form or message+// framing — old signatures stay verifiable against their own version string.+export const MEMORY_SIG_VERSION = 'threews:brain:memory:v1';++/**+ * Deterministic, stable serialization of the signable fields of a memory.+ * Field order and tag order are fixed so the same logical memory always+ * produces the same bytes on any machine — the precondition for a reproducible+ * hash and signature. Mutable, non-authorship fields (salience, tier, pinned,+ * access counts, updated_at) are intentionally excluded: re-tiering a memory+ * must not invalidate its authorship signature.+ *+ * Accepts either the snake_case DB row shape or the camelCase decorated shape.+ *+ * @param {object} mem+ * @returns {string} canonical JSON string+ */+export function canonicalizeMemory(mem) {+ const id = mem.id ?? mem.memoryId ?? '';+ const agentId = mem.agent_id ?? mem.agentId ?? '';+ const type = mem.type ?? 'project';+ const content = mem.content ?? '';+ const rawTags = Array.isArray(mem.tags) ? mem.tags : [];+ const tags = [...rawTags].map((t) => String(t)).sort();+ const createdRaw = mem.created_at ?? mem.createdAt ?? null;+ // Normalize timestamps to ISO so a numeric ms input and an ISO input that+ // denote the same instant hash identically.+ const createdAt = createdRaw == null ? '' : new Date(createdRaw).toISOString();++ return JSON.stringify({+ v: MEMORY_SIG_VERSION,+ id: String(id),+ agentId: String(agentId),+ type: String(type),+ content: String(content),+ tags,+ createdAt,+ });+}++/**+ * SHA-256 (hex) of the canonical memory form. This is the `content_hash`+ * persisted alongside the signature — a fast tamper check that does not require+ * elliptic-curve math.+ *+ * @param {object} mem+ * @returns {string} 64-char lowercase hex digest+ */+export function memoryDigest(mem) {+ return createHash('sha256').update(canonicalizeMemory(mem)).digest('hex');+}++/**+ * The exact string that gets ERC-191 signed. Framing the digest with a+ * domain-separating prefix prevents a memory signature from ever being replayed+ * as a signature over some other three.ws message.+ *+ * @param {string} digest hex digest from memoryDigest+ * @returns {string}+ */+export function signMessageBody(digest) {+ return `${MEMORY_SIG_VERSION}:${digest}`;+}++/**+ * Sign a precomputed memory digest with a raw EVM private key. Pure crypto —+ * no DB. Returns the ERC-191 signature and the recovered signer address.+ *+ * @param {string} privKeyHex 0x-prefixed 32-byte private key+ * @param {string} digest hex digest from memoryDigest+ * @returns {Promise<{ signature: string, signer_address: string }>}+ */+export async function signDigest(privKeyHex, digest) {+ const wallet = new Wallet(privKeyHex);+ const signature = await wallet.signMessage(signMessageBody(digest));+ return { signature, signer_address: wallet.address };+}++/**+ * Verify a memory against a signature + claimed signer. Pure crypto — this is+ * the function a buyer/forker runs offline to trust a brain.+ *+ * @param {object} mem the memory (DB row or decorated)+ * @param {object} proof+ * @param {string} proof.signature ERC-191 signature+ * @param {string} proof.signer_address claimed signer (the agent wallet)+ * @param {string} [proof.content_hash] optional stored hash to cross-check+ * @returns {{ valid: boolean, recovered: string|null, digest: string, reason: string }}+ */+export function verifyMemorySignature(mem, { signature, signer_address, content_hash } = {}) {+ const digest = memoryDigest(mem);++ if (content_hash && content_hash.toLowerCase() !== digest.toLowerCase()) {+ return { valid: false, recovered: null, digest, reason: 'content_hash_mismatch' };+ }+ if (!signature || !signer_address) {+ return { valid: false, recovered: null, digest, reason: 'unsigned' };+ }++ let recovered = null;+ try {+ recovered = verifyMessage(signMessageBody(digest), signature);+ } catch {+ return { valid: false, recovered: null, digest, reason: 'malformed_signature' };+ }++ const valid = recovered.toLowerCase() === String(signer_address).toLowerCase();+ return {+ valid,+ recovered,+ digest,+ reason: valid ? 'ok' : 'signer_mismatch',+ };+}++/**+ * Resolve the agent's signing identity: its EVM wallet address + a decrypted+ * private key. DB + custodial vault. Returns null when the agent has no+ * provisioned EVM wallet (caller stores the memory unsigned).+ *+ * @param {string} agentId+ * @param {object} [audit] passed through to recoverAgentKey for the custody trail+ * @returns {Promise<{ address: string, privKey: string }|null>}+ */+export async function loadAgentSigner(agentId, audit = null) {+ const [row] = await sql`+ SELECT wallet_address, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!row) return null;+ const encrypted = row.meta?.encrypted_wallet_key;+ if (!encrypted) return null;++ const privKey = await recoverAgentKey(encrypted, audit || { agentId, reason: 'brain_sign' });+ const address = row.wallet_address || computeAddress(privKey);+ return { address, privKey };+}++/**+ * Sign a memory row with its agent's wallet and persist the signature.+ * Best-effort: returns an unsigned descriptor (signature null) when no wallet+ * exists, never throws on a missing key.+ *+ * @param {object} mem the freshly-inserted memory row (must carry real id + created_at)+ * @param {object} [opts]+ * @param {boolean} [opts.persist=true] write the signature columns back to the row+ * @returns {Promise<{ content_hash: string, signature: string|null, signer_address: string|null, signed_at: string|null }>}+ */+export async function signMemoryWithAgent(mem, { persist = true } = {}) {+ const agentId = mem.agent_id ?? mem.agentId;+ const digest = memoryDigest(mem);++ let signer = null;+ try {+ signer = await loadAgentSigner(agentId);+ } catch (err) {+ // A vault/decrypt failure must not lose the memory — store unsigned and+ // surface the reason for the ops trail.+ console.error('[brain-sign] loadAgentSigner failed', agentId, err?.message);+ }++ if (!signer) {+ if (persist) {+ await sql`+ UPDATE agent_memories SET content_hash = ${digest}+ WHERE id = ${mem.id}+ `;+ }+ return { content_hash: digest, signature: null, signer_address: null, signed_at: null };+ }++ const { signature, signer_address } = await signDigest(signer.privKey, digest);+ const signed_at = new Date().toISOString();++ if (persist) {+ await sql`+ UPDATE agent_memories+ SET content_hash = ${digest},+ signature = ${signature},+ signer_address = ${signer_address},+ signed_at = ${signed_at}+ WHERE id = ${mem.id}+ `;+ }++ return { content_hash: digest, signature, signer_address, signed_at };+}diff --git a/api/_lib/economy-shape.js b/api/_lib/economy-shape.jsnew file mode 100644index 000000000..efc47a18e--- /dev/null+++ b/api/_lib/economy-shape.js@@ -0,0 +1,43 @@+// Pure shaping for the owner-facing agent economy summary (api/agents/:id/economy).+//+// Money is earned three real, distinct ways on three.ws and each is its own+// ledger: skill sales (agent_revenue_events), hires from other agents over the+// x402 mesh (agent_hires), and tips (agent_custody_events). This module composes+// those buckets into the summary's `earnings` object and the running total.+//+// It is deliberately I/O-free — every input is already a plain number from a+// ledger query — so the invariants that matter (hires are their own bucket; the+// total sums all three without double-counting) are unit-testable in full.++function num(v) {+ const n = Number(v);+ return Number.isFinite(n) ? n : 0;+}++function int(v) {+ const n = Math.trunc(Number(v));+ return Number.isFinite(n) ? n : 0;+}++/**+ * Compose the three earning buckets into the summary `earnings` object plus a+ * total across all three. Each bucket is passed through verbatim (preserving any+ * extra fields such as skill_sales.non_usdc_count); only `total` is derived.+ *+ * @param {{ skill_sales: object, hires: object, tips: object }} buckets+ * @returns {{ skill_sales: object, hires: object, tips: object, total: object }}+ */+export function composeEarnings({ skill_sales = {}, hires = {}, tips = {} } = {}) {+ const all = [skill_sales, hires, tips];+ return {+ skill_sales,+ hires,+ tips,+ total: {+ today: all.reduce((s, b) => s + num(b.today), 0),+ week: all.reduce((s, b) => s + num(b.week), 0),+ lifetime: all.reduce((s, b) => s + num(b.lifetime), 0),+ count: all.reduce((s, b) => s + int(b.count), 0),+ },+ };+}diff --git a/api/_lib/migrations/20260623210000_agent_reflections.sql b/api/_lib/migrations/20260623210000_agent_reflections.sqlnew file mode 100644index 000000000..dfaf00b85--- /dev/null+++ b/api/_lib/migrations/20260623210000_agent_reflections.sql@@ -0,0 +1,67 @@+-- Reflection & Dreams — memory consolidation engine (Living Agents · Task 04).+--+-- An agent periodically *reflects*: it reads its own recent raw memories and+-- action log and synthesizes higher-order insights ("dreams"). Each dream is a+-- candidate the owner reviews — accept turns it into a real, higher-salience+-- memory (and/or a proposed Autopilot rule); reject is itself stored so future+-- reflections learn from the rejection.+--+-- Two tables:+-- agent_reflections — the dreams themselves (one row per candidate insight)+-- agent_reflection_runs — one row per reflection pass, even when it produced+-- zero dreams or was skipped. This is what enforces the+-- per-agent daily cap + debounce WITHOUT a silent cap:+-- every skip records its reason here.++create table if not exists agent_reflections (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ status text not null default 'pending'+ check (status in ('pending', 'accepted', 'rejected')),+ -- The kind of consolidation. 'insight' = a noticed pattern; 'belief' = a+ -- synthesized user/feedback fact; 'question' = a low-confidence clarification+ -- the agent wants the user to answer; 'prune' = a proposal to merge/forget.+ kind text not null default 'insight'+ check (kind in ('insight', 'belief', 'question', 'prune')),+ statement text not null,+ rationale text,+ confidence real not null default 0.5 check (confidence >= 0 and confidence <= 1),+ -- Provenance is mandatory: every dream cites the raw memory ids it drew from.+ source_memory_ids uuid[] not null default '{}',+ proposed_type text check (proposed_type in ('user', 'feedback', 'project', 'reference')),+ proposed_salience real not null default 0.7 check (proposed_salience >= 0 and proposed_salience <= 1),+ proposed_action jsonb,+ -- For kind='question': the clarification asked, and the user's answer if given.+ question text,+ answer text,+ run_id uuid,+ -- The memory row written when this dream is accepted (provenance for the+ -- accept side: lets the UI link the dream to the memory it became).+ accepted_memory_id uuid,+ created_at timestamptz not null default now(),+ reviewed_at timestamptz+);++create index if not exists agent_reflections_agent_status+ on agent_reflections(agent_id, status, created_at desc);++create index if not exists agent_reflections_run+ on agent_reflections(run_id)+ where run_id is not null;++create table if not exists agent_reflection_runs (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ trigger text not null check (trigger in ('cron', 'on-demand', 'manual')),+ status text not null check (status in ('ok', 'skipped', 'error')),+ reason text,+ dreams_created integer not null default 0,+ candidates integer not null default 0,+ model text,+ input_tokens integer,+ output_tokens integer,+ created_at timestamptz not null default now()+);++create index if not exists agent_reflection_runs_agent_time+ on agent_reflection_runs(agent_id, created_at desc);diff --git a/api/_lib/migrations/20260623230000_autopilot_proposals.sql b/api/_lib/migrations/20260623230000_autopilot_proposals.sqlnew file mode 100644index 000000000..b7d1f973a--- /dev/null+++ b/api/_lib/migrations/20260623230000_autopilot_proposals.sql@@ -0,0 +1,63 @@+-- Memory-grounded Autopilot — explainable autonomy (Living Agents · Task 08).+--+-- The agent proposes and (within user-granted scope) takes REAL actions —+-- creating pump alert rules, authoring briefings, transferring $THREE — and+-- every action is traceable to the memory or reflection that motivated it.+--+-- Permission/scope is stored on agent_identities.meta.autopilot (same slot+-- convention as meta.strategy / meta.spend_limits). This table is the proposal+-- queue: the "mind" (high-salience memories + accepted/pending dreams) generates+-- candidates here; the owner approves / dry-runs / dismisses; on execution the+-- real action is recorded in agent_actions (signed) and linked back via+-- executed_action_id. Provenance (source_memory_ids + source_reflection_id) is+-- mandatory — a proposal that cites nothing is never written.++create table if not exists agent_autopilot_proposals (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ -- The real action this proposal would take when executed.+ -- create_alert → inserts a pump_alert_rules row (reversible)+ -- briefing → authors a memory-grounded briefing notification (reversible)+ -- wallet_transfer → sends $THREE from the agent's custodial wallet (irreversible)+ kind text not null+ check (kind in ('create_alert', 'briefing', 'wallet_transfer')),+ title text not null,+ -- The receipt: plain-language "I want to do X because …" the owner reads.+ rationale text not null,+ -- Concrete, validated action parameters (e.g. the alert-rule body, the+ -- transfer recipient + $THREE amount, the briefing cadence).+ params jsonb not null default '{}'::jsonb,+ -- Provenance is mandatory: every proposal cites the raw memory ids and/or the+ -- reflection it was derived from. CHECK enforces at least one source.+ source_memory_ids uuid[] not null default '{}',+ source_reflection_id uuid references agent_reflections(id) on delete set null,+ confidence real not null default 0.6 check (confidence >= 0 and confidence <= 1),+ -- Irreversible actions (spends/publishes) default to requiring an explicit+ -- confirmation at execution time unless the owner durably pre-authorized.+ requires_confirmation boolean not null default true,+ status text not null default 'pending'+ check (status in ('pending', 'executed', 'dismissed', 'undone', 'failed')),+ -- The append-only agent_actions row id written when this proposal executed —+ -- the signed receipt the Activity surface links to.+ executed_action_id bigint,+ -- Execution outcome: created rule id, tx signature, error string, undo info.+ result jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ decided_at timestamptz,+ executed_at timestamptz,+ constraint agent_autopilot_proposals_has_source+ check (array_length(source_memory_ids, 1) > 0 or source_reflection_id is not null)+);++create index if not exists agent_autopilot_proposals_agent_status+ on agent_autopilot_proposals(agent_id, status, created_at desc);++create index if not exists agent_autopilot_proposals_user+ on agent_autopilot_proposals(user_id, created_at desc);++-- One pending proposal per reflection — re-running the generator must not+-- enqueue the same dream twice.+create unique index if not exists agent_autopilot_proposals_reflection_pending+ on agent_autopilot_proposals(source_reflection_id)+ where source_reflection_id is not null and status = 'pending';diff --git a/api/_lib/migrations/20260628130000_agent_vaults.sql b/api/_lib/migrations/20260628130000_agent_vaults.sqlnew file mode 100644index 000000000..f250e4f90--- /dev/null+++ b/api/_lib/migrations/20260628130000_agent_vaults.sql@@ -0,0 +1,145 @@+begin;++-- Back-an-Agent Vaults — copy-trade a 3D agent with a verifiable reputation+-- ==========================================================================+-- A reputation-verified agent's owner opens a vault; backers deposit USDC; the+-- agent trades the POOLED capital within hard, owner-and-protocol-enforced spend+-- limits; P&L is shared pro-rata via real share accounting; the owner earns a+-- transparent, disclosed performance fee charged only on a backer's realized+-- gain. Custody is real and segregated: each vault has its OWN custodial Solana+-- wallet (never co-mingled with the agent's personal wallet or another vault).+--+-- All money is stored as exact USDC atomic units (6 decimals) in numeric(40,0) —+-- never a float. Shares are unitless BigInt; the first deposit mints shares 1:1+-- with USDC atomics (initial share price = 1.000000 USDC), and every later+-- deposit/redemption is priced against live NAV. See api/_lib/vault-accounting.js+-- for the canonical (pure, unit-tested) math.++-- ── Vaults ──────────────────────────────────────────────────────────────────+-- One open vault per agent (a fork is a different agent_id → its own empty vault,+-- never co-mingled). `encrypted_secret` is the AES-256-GCM-encrypted secret key+-- of the vault's dedicated custodial wallet (api/_lib/secret-box.js), decrypted+-- only at signing time. `status` is the kill switch: only 'open' vaults accept+-- deposits or trade; 'paused' halts autonomous trading (owner pause OR an+-- automatic drawdown-breaker trip) while still allowing redemptions.+create table if not exists agent_vaults (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ owner_user_id uuid not null,+ network text not null default 'mainnet',+ vault_address text not null,+ encrypted_secret text not null,+ status text not null default 'open'+ check (status in ('open', 'paused', 'closing', 'closed')),+ -- Disclosed terms (set at open, editable by the owner while no capital is at risk+ -- of being mis-priced; the UI discloses every one of these at the moment of backing).+ performance_fee_bps int not null default 1000 check (performance_fee_bps between 0 and 5000),+ per_backer_cap_atomics numeric(40,0) check (per_backer_cap_atomics is null or per_backer_cap_atomics > 0),+ max_drawdown_bps int not null default 2500 check (max_drawdown_bps between 100 and 9000),+ max_per_trade_atomics numeric(40,0) not null check (max_per_trade_atomics > 0),+ daily_budget_atomics numeric(40,0) not null check (daily_budget_atomics > 0),+ -- Live accounting state (re-derived from chain before every settlement, never trusted blindly).+ total_shares numeric(40,0) not null default 0 check (total_shares >= 0),+ peak_nav_atomics numeric(40,0) not null default 0 check (peak_nav_atomics >= 0),+ accrued_fee_atomics numeric(40,0) not null default 0 check (accrued_fee_atomics >= 0),+ halt_reason text,+ paused_at timestamptz,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- At most one non-closed vault per agent. A closed vault can be superseded by a+-- new one; an open/paused/closing one cannot be duplicated.+create unique index if not exists agent_vaults_one_active+ on agent_vaults (agent_id)+ where status <> 'closed';++create index if not exists agent_vaults_owner_idx on agent_vaults (owner_user_id, created_at desc);+create index if not exists agent_vaults_status_idx on agent_vaults (status, updated_at desc);++-- ── Backer positions ──────────────────────────────────────────────────────────+-- One row per (vault, backer). `shares` is the backer's current share balance;+-- `cost_basis_atomics` is their net principal still at risk (deposits minus the+-- cost basis already returned on redemptions) — the performance fee is charged+-- ONLY on realized gain above this basis, never on principal or on a loss.+-- `backer_agent_id` is the agent wallet the backer funds from / is paid back to+-- (a backer backs WITH one of their own agents' custodial USDC wallets).+create table if not exists vault_backers (+ id bigserial primary key,+ vault_id uuid not null references agent_vaults(id) on delete cascade,+ user_id uuid not null,+ backer_agent_id uuid not null references agent_identities(id) on delete restrict,+ shares numeric(40,0) not null default 0 check (shares >= 0),+ cost_basis_atomics numeric(40,0) not null default 0 check (cost_basis_atomics >= 0),+ deposited_atomics numeric(40,0) not null default 0 check (deposited_atomics >= 0),+ redeemed_atomics numeric(40,0) not null default 0 check (redeemed_atomics >= 0),+ realized_gain_atomics numeric(40,0) not null default 0,+ fees_paid_atomics numeric(40,0) not null default 0 check (fees_paid_atomics >= 0),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create unique index if not exists vault_backers_one_per_user+ on vault_backers (vault_id, user_id);+create index if not exists vault_backers_user_idx on vault_backers (user_id, updated_at desc);++-- ── Open token positions held by the vault ──────────────────────────────────────+-- Capital the vault has deployed out of USDC into a token. Marked to market via+-- real Jupiter quotes when computing NAV; closed (status='closed') on full exit.+create table if not exists vault_positions (+ id bigserial primary key,+ vault_id uuid not null references agent_vaults(id) on delete cascade,+ mint text not null,+ token_decimals int not null default 0,+ amount_raw numeric(40,0) not null default 0 check (amount_raw >= 0),+ cost_atomics numeric(40,0) not null default 0 check (cost_atomics >= 0),+ realized_pnl_atomics numeric(40,0) not null default 0,+ last_mark_atomics numeric(40,0),+ status text not null default 'open' check (status in ('open', 'closed')),+ opened_at timestamptz not null default now(),+ closed_at timestamptz,+ updated_at timestamptz not null default now()+);++-- One open position per (vault, mint); a re-buy of the same mint adds to it.+create unique index if not exists vault_positions_open_mint+ on vault_positions (vault_id, mint)+ where status = 'open';+create index if not exists vault_positions_vault_idx on vault_positions (vault_id, status);++-- ── Vault event ledger (the full, immutable audit trail) ─────────────────────────+-- Every vault action — open, deposit, redeem, trade, fee accrual/claim, drawdown+-- halt, pause/resume, terms change, close — lands here with the on-chain signature+-- where one exists. This is what the owner-and-backer-facing audit feed renders and+-- what proves the vault never exceeded its mandate.+create table if not exists vault_events (+ id bigserial primary key,+ vault_id uuid not null references agent_vaults(id) on delete cascade,+ type text not null check (type in (+ 'open', 'deposit', 'redeem', 'trade', 'fee', 'fee_claim',+ 'drawdown_halt', 'pause', 'resume', 'terms', 'close', 'nav'+ )),+ user_id uuid,+ backer_agent_id uuid,+ shares_delta numeric(40,0),+ atomics_delta numeric(40,0),+ nav_atomics numeric(40,0),+ share_price_e6 numeric(40,0),+ signature text,+ status text not null default 'ok' check (status in ('ok', 'pending', 'failed')),+ reason text,+ idempotency_key text,+ meta jsonb not null default '{}',+ created_at timestamptz not null default now()+);++-- Idempotency: a deposit/redeem/trade keyed by an on-chain signature or client key+-- is recorded exactly once (a retry/replay is a silent no-op via ON CONFLICT).+create unique index if not exists vault_events_idem+ on vault_events (vault_id, idempotency_key)+ where idempotency_key is not null;++create index if not exists vault_events_feed_idx on vault_events (vault_id, id desc);+create index if not exists vault_events_type_idx on vault_events (vault_id, type, id desc);++commit;diff --git a/api/_lib/migrations/20260628130000_brain_studio_persona.sql b/api/_lib/migrations/20260628130000_brain_studio_persona.sqlnew file mode 100644index 000000000..a73c33c33--- /dev/null+++ b/api/_lib/migrations/20260628130000_brain_studio_persona.sql@@ -0,0 +1,41 @@+begin;++-- Brain Studio — structured, editable personality with versioned history+-- =======================================================================+-- The persona system already stores a signed `persona_prompt` produced by a+-- one-time 5-question extraction interview. The Brain Studio turns personality+-- into a tangible thing the owner sculpts: continuous trait dimensions (warmth,+-- formality, verbosity, humour, proactivity, risk appetite, directness), tone+-- chips, and characteristic vocabulary, which compile deterministically into+-- that same `persona_prompt` (src/agents/persona-compile.js).+--+-- Two halves:+-- 1. persona_traits — the editable source of truth on the live agent. The+-- compiled prompt above is always derivable from it, but we persist the+-- structure so the sliders restore exactly and a trait diff is possible.+-- 2. agent_versions persona snapshot — every Brain Studio save is a real+-- version (sharing the agent's single version timeline with marketplace+-- publishes) carrying the persona prompt + tone tags + traits, so history,+-- diff, and restore all work on real rows.++-- ── Live agent: structured personality ─────────────────────────────────────────+alter table agent_identities+ add column if not exists persona_traits jsonb not null default '{}'::jsonb;+alter table agent_identities+ add column if not exists persona_updated_at timestamptz;++-- ── Version snapshots: persona alongside the marketplace prompt ────────────────+-- agent_versions is created in 2026-04-29-agent-marketplace.sql (sorts earlier).+alter table agent_versions+ add column if not exists persona_prompt text;+alter table agent_versions+ add column if not exists persona_tone_tags jsonb not null default '[]'::jsonb;+alter table agent_versions+ add column if not exists persona_traits jsonb not null default '{}'::jsonb;++-- A "kind" tag distinguishes a persona save from a marketplace publish on the+-- shared timeline so the Brain Studio history view can filter to persona edits.+alter table agent_versions+ add column if not exists kind text not null default 'publish';++commit;diff --git a/api/_lib/reflection.js b/api/_lib/reflection.jsnew file mode 100644index 000000000..da36db283--- /dev/null+++ b/api/_lib/reflection.js@@ -0,0 +1,398 @@+// Reflection & Dreams — the memory-consolidation engine (Living Agents · Task 04).+//+// An agent "reflects": it reads its own recent raw memories + signed action log+// and runs a real LLM pass that synthesizes higher-order insights ("dreams").+// Each dream cites the raw memory ids it drew from — provenance is mandatory; a+// dream with no real source memory is dropped, never stored.+//+// This module is pure orchestration over the DB + the shared LLM proxy+// (api/_lib/llm.js). It is called from three places, all real triggers:+// • POST /api/agent/reflect — on-demand, when the owner opens the review surface+// • /api/cron/reflect-sweep — scheduled pass over agents with recent activity+// • the dreams review endpoint — to enforce caps / read state+//+// Cost & rate discipline (no silent caps): every pass writes an+// agent_reflection_runs row — including skips — recording why it ran or didn't,+// how many candidates the model produced, and the token counts. The daily cap+// and debounce are enforced against that log.++import { sql } from './db.js';+import { llmComplete, LlmUnavailableError } from './llm.js';++// Preferred synthesis model. Per CLAUDE.md, default to the latest Claude for+// synthesis quality — passed as the Anthropic model so that when the paid key+// is live the chain uses it; the free providers (Groq/OpenRouter/NVIDIA) remain+// the actual workhorses and the call still succeeds when the paid key is dead.+export const REFLECTION_MODEL = 'claude-opus-4-7';++// How many successful reflection passes an agent may run per rolling 24h. A pass+// can produce 0..MAX_INSIGHTS dreams; this caps the LLM spend, not the dreams.+export const REFLECTION_DAILY_CAP = Number(process.env.REFLECTION_DAILY_CAP) || 8;++// Don't reflect more often than this (debounce). Opening the review surface+// repeatedly must not trigger a fresh pass each time. Manual/forced runs bypass.+export const REFLECTION_DEBOUNCE_MS = Number(process.env.REFLECTION_DEBOUNCE_MS) || 30 * 60 * 1000;++// Below this much new raw material there's nothing worth consolidating — skip.+export const MIN_NEW_SIGNALS = 3;++// Hard ceiling on dreams per pass so one run can't flood the review queue.+export const MAX_INSIGHTS = 5;++// How far back to look on the very first reflection (no prior run to bound from).+const FIRST_LOOKBACK_MS = 14 * 24 * 60 * 60 * 1000;++// Caps on how much context we feed the model, to bound token cost.+const MAX_MEMORIES_IN_CONTEXT = 60;+const MAX_ACTIONS_IN_CONTEXT = 40;+const MAX_REJECTED_IN_CONTEXT = 12;++/**+ * Decide whether an agent is eligible to reflect right now and, if so, gather+ * the raw signal since its last pass.+ *+ * Returns one of:+ * { eligible: false, reason } — skip (logged)+ * { eligible: true, since, memories, actions, rejected } — go+ */+export async function gatherReflectionContext(agentId, { force = false } = {}) {+ const [lastRun] = await sql`+ SELECT created_at, status+ FROM agent_reflection_runs+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ LIMIT 1+ `;++ if (!force && lastRun) {+ const sinceLast = Date.now() - new Date(lastRun.created_at).getTime();+ if (sinceLast < REFLECTION_DEBOUNCE_MS) {+ const mins = Math.ceil((REFLECTION_DEBOUNCE_MS - sinceLast) / 60000);+ return { eligible: false, reason: `debounced — reflected ${Math.round(sinceLast / 60000)}m ago, next in ~${mins}m` };+ }+ }++ const [{ runs } = { runs: 0 }] = await sql`+ SELECT COUNT(*)::int AS runs+ FROM agent_reflection_runs+ WHERE agent_id = ${agentId}+ AND status = 'ok'+ AND created_at > now() - interval '24 hours'+ `;+ if (!force && runs >= REFLECTION_DAILY_CAP) {+ return { eligible: false, reason: `daily cap reached (${runs}/${REFLECTION_DAILY_CAP} reflections in 24h)` };+ }++ // Bound the window to "since the last successful reflection" so we only+ // consolidate genuinely new material. Falls back to a fixed lookback on the+ // first-ever pass.+ const [lastOk] = await sql`+ SELECT created_at+ FROM agent_reflection_runs+ WHERE agent_id = ${agentId} AND status = 'ok'+ ORDER BY created_at DESC+ LIMIT 1+ `;+ const since = lastOk ? new Date(lastOk.created_at) : new Date(Date.now() - FIRST_LOOKBACK_MS);+ const sinceIso = since.toISOString();++ const memories = await sql`+ SELECT id, type, content, tags, salience, created_at+ FROM agent_memories+ WHERE agent_id = ${agentId}+ AND (expires_at IS NULL OR expires_at > now())+ AND created_at > ${sinceIso}+ ORDER BY salience DESC, created_at DESC+ LIMIT ${MAX_MEMORIES_IN_CONTEXT}+ `;++ const actions = await sql`+ SELECT id, type, payload, source_skill, created_at+ FROM agent_actions+ WHERE agent_id = ${agentId}+ AND created_at > ${sinceIso}+ ORDER BY created_at DESC+ LIMIT ${MAX_ACTIONS_IN_CONTEXT}+ `;++ const signals = memories.length + actions.length;+ if (signals < MIN_NEW_SIGNALS) {+ return { eligible: false, reason: `not enough new material (${signals} new signals since last reflection; need ${MIN_NEW_SIGNALS})` };+ }++ // Feed prior rejections back in so the agent learns not to re-propose a+ // synthesis the owner already rejected. This is the learning loop.+ const rejected = await sql`+ SELECT statement+ FROM agent_reflections+ WHERE agent_id = ${agentId} AND status = 'rejected'+ ORDER BY reviewed_at DESC NULLS LAST, created_at DESC+ LIMIT ${MAX_REJECTED_IN_CONTEXT}+ `;++ return { eligible: true, since, memories, actions, rejected };+}++const SYSTEM_PROMPT = [+ 'You are the reflective faculty of a personal AI agent — the part of its mind that,',+ 'while the user is away, reviews recent experience and consolidates it into',+ 'higher-order understanding. This is the Stanford "Generative Agents" reflection',+ 'mechanism: from many raw observations, synthesize a few durable insights.',+ '',+ 'You are given the agent\'s recent raw MEMORIES (each with a stable id) and recent',+ 'ACTIONS. Produce up to ' + MAX_INSIGHTS + ' candidate insights. Rules:',+ '',+ '1. PROVENANCE IS MANDATORY. Every insight must cite "source_memory_ids" — the',+ ' exact ids of the memories it was derived from. Use only ids that appear in the',+ ' provided memories. An insight you cannot ground in specific memories is invalid;',+ ' do not emit it.',+ '2. SYNTHESIZE, don\'t restate. A good insight notices a pattern across multiple',+ ' memories ("three conversations were about settlement speed → the user prioritizes',+ ' finality over fees"), or proposes a useful routine, or forms a belief about the',+ ' user. Prefer insights grounded in 2+ memories.',+ '3. Be honest about confidence (0..1). If you are unsure but the pattern matters,',+ ' set kind="question" and put a specific clarifying question in "question".',+ '4. Do not repeat anything in PREVIOUSLY REJECTED — the user already rejected those',+ ' syntheses; proposing them again is a mistake.',+ '5. Choose a memory "proposed_type": user (facts about the user), feedback (how the',+ ' agent should behave), project (ongoing work/goals), reference (external pointers).',+ ' Set "proposed_salience" higher (0.6–0.95) than a raw memory — a consolidated',+ ' insight is more important than any single observation.',+ '6. Optionally propose ONE automation in "proposed_action" when an insight implies a',+ ' recurring helpful behavior (e.g. {"kind":"briefing","summary":"morning $THREE',+ ' alert digest","trigger":"daily 9am"}). Otherwise null.',+ '',+ 'Return ONLY a JSON object, no prose, no markdown fences:',+ '{"insights":[{"kind":"insight|belief|question|prune","statement":"...","rationale":"why, from the memories","confidence":0.0,"source_memory_ids":["uuid",...],"proposed_type":"user|feedback|project|reference","proposed_salience":0.0,"proposed_action":{...}|null,"question":"...|null"}]}',+ 'If there is nothing worth consolidating, return {"insights":[]}.',+].join('\n');++function buildUserPrompt({ agent, memories, actions, rejected }) {+ const lines = [];+ lines.push(`AGENT: ${agent?.name || 'Agent'}${agent?.description ? ` — ${agent.description}` : ''}`);+ lines.push('');+ lines.push('RECENT MEMORIES:');+ for (const m of memories) {+ const tags = Array.isArray(m.tags) && m.tags.length ? ` [${m.tags.join(', ')}]` : '';+ const when = new Date(m.created_at).toISOString().slice(0, 10);+ lines.push(`- id=${m.id} (${m.type}, salience ${Number(m.salience).toFixed(2)}, ${when})${tags}: ${truncate(m.content, 500)}`);+ }+ if (actions.length) {+ lines.push('');+ lines.push('RECENT ACTIONS (what the agent actually did):');+ for (const a of actions) {+ const when = new Date(a.created_at).toISOString().slice(0, 16).replace('T', ' ');+ const detail = a.payload ? truncate(JSON.stringify(a.payload), 200) : '';+ lines.push(`- ${when} ${a.type}${a.source_skill ? ` via ${a.source_skill}` : ''}: ${detail}`);+ }+ }+ if (rejected?.length) {+ lines.push('');+ lines.push('PREVIOUSLY REJECTED (do not propose these again):');+ for (const r of rejected) lines.push(`- ${truncate(r.statement, 200)}`);+ }+ lines.push('');+ lines.push(`Synthesize up to ${MAX_INSIGHTS} grounded insights as the specified JSON.`);+ return lines.join('\n');+}++function truncate(s, n) {+ const str = String(s ?? '');+ return str.length > n ? str.slice(0, n - 1) + '…' : str;+}++/**+ * Extract the first JSON object from a model response, tolerant of code fences+ * or stray prose around it. Returns the parsed object or null — never throws.+ */+export function parseInsightPayload(text) {+ if (!text) return null;+ let body = String(text).trim();+ // Strip ```json … ``` fences if present.+ const fence = body.match(/```(?:json)?\s*([\s\S]*?)```/i);+ if (fence) body = fence[1].trim();+ // Fall back to the first balanced { … } span.+ if (body[0] !== '{') {+ const start = body.indexOf('{');+ const end = body.lastIndexOf('}');+ if (start === -1 || end === -1 || end <= start) return null;+ body = body.slice(start, end + 1);+ }+ try {+ return JSON.parse(body);+ } catch {+ return null;+ }+}++const VALID_TYPES = ['user', 'feedback', 'project', 'reference'];+const VALID_KINDS = ['insight', 'belief', 'question', 'prune'];++function clamp(n, lo, hi, dflt) {+ const v = Number(n);+ if (!Number.isFinite(v)) return dflt;+ return Math.max(lo, Math.min(hi, v));+}++/**+ * Validate one raw model insight against the strict schema + provenance rule.+ * `validIds` is a Set of memory ids that were actually fed to the model.+ * Returns a normalized insight object, or null if it must be dropped.+ */+export function validateInsight(raw, validIds) {+ if (!raw || typeof raw !== 'object') return null;++ const statement = typeof raw.statement === 'string' ? raw.statement.trim() : '';+ if (!statement || statement.length > 1000) return null;++ // Provenance: keep only cited ids that were really in the context. Require ≥1.+ const cited = Array.isArray(raw.source_memory_ids) ? raw.source_memory_ids : [];+ const sourceIds = [...new Set(cited.filter((id) => typeof id === 'string' && validIds.has(id)))];+ if (sourceIds.length === 0) return null;++ let kind = VALID_KINDS.includes(raw.kind) ? raw.kind : 'insight';+ const confidence = clamp(raw.confidence, 0, 1, 0.5);+ const question = typeof raw.question === 'string' && raw.question.trim() ? raw.question.trim().slice(0, 600) : null;+ // A genuine clarification with a question is a 'question' dream regardless of+ // the model's label — that's what unlocks the answer flow in the UI.+ if (question && confidence < 0.55) kind = 'question';++ const proposedType = VALID_TYPES.includes(raw.proposed_type) ? raw.proposed_type : 'project';+ const proposedSalience = clamp(raw.proposed_salience, 0.5, 0.95, 0.7);++ let proposedAction = null;+ if (raw.proposed_action && typeof raw.proposed_action === 'object' && !Array.isArray(raw.proposed_action)) {+ // Store the proposal verbatim but bounded; Autopilot (Task 08) consumes it.+ const serialized = JSON.stringify(raw.proposed_action);+ if (serialized.length <= 4000) proposedAction = raw.proposed_action;+ }++ return {+ kind,+ statement,+ rationale: typeof raw.rationale === 'string' ? raw.rationale.trim().slice(0, 1200) : null,+ confidence,+ sourceIds,+ proposedType,+ proposedSalience,+ proposedAction,+ question,+ };+}++/**+ * Run one reflection pass for an agent. Always records an agent_reflection_runs+ * row (ok / skipped / error) so caps + debounce are enforceable and nothing is+ * silently dropped.+ *+ * @param {object} opts+ * @param {string} opts.agentId+ * @param {string} opts.userId owner (for LLM spend attribution)+ * @param {string} opts.trigger 'cron' | 'on-demand' | 'manual'+ * @param {object} opts.agent { name, description } for prompt context+ * @param {boolean} opts.force bypass debounce + daily cap (manual only)+ * @returns {Promise<{status:'ok'|'skipped'|'error', reason?:string, runId?:string,+ * created:Array, candidates:number}>}+ */+export async function runReflection({ agentId, userId = null, trigger = 'on-demand', agent = null, force = false }) {+ if (!agentId) throw new Error('agentId required');++ const ctx = await gatherReflectionContext(agentId, { force: force || trigger === 'manual' });+ if (!ctx.eligible) {+ await recordRun({ agentId, trigger, status: 'skipped', reason: ctx.reason });+ return { status: 'skipped', reason: ctx.reason, created: [], candidates: 0 };+ }++ const { memories, actions, rejected } = ctx;+ const validIds = new Set(memories.map((m) => m.id));++ let completion;+ try {+ completion = await llmComplete({+ system: SYSTEM_PROMPT,+ user: buildUserPrompt({ agent, memories, actions, rejected }),+ maxTokens: 1600,+ anthropicModel: REFLECTION_MODEL,+ timeoutMs: 45_000,+ track: { userId, agentId, tool: 'reflection' },+ });+ } catch (err) {+ const reason = err instanceof LlmUnavailableError ? 'no LLM provider available' : (err?.message || 'llm error').slice(0, 300);+ await recordRun({ agentId, trigger, status: 'error', reason });+ return { status: 'error', reason, created: [], candidates: 0 };+ }++ const payload = parseInsightPayload(completion.text);+ if (!payload || !Array.isArray(payload.insights)) {+ await recordRun({+ agentId, trigger, status: 'error', reason: 'unparseable model output',+ model: completion.model, inputTokens: completion.usage?.input, outputTokens: completion.usage?.output,+ });+ return { status: 'error', reason: 'unparseable model output', created: [], candidates: 0 };+ }++ const candidates = payload.insights.slice(0, MAX_INSIGHTS);+ const valid = candidates.map((c) => validateInsight(c, validIds)).filter(Boolean);++ const run = await recordRun({+ agentId, trigger, status: 'ok',+ reason: valid.length === 0 ? 'no groundable insights this pass' : null,+ dreamsCreated: valid.length, candidates: candidates.length,+ model: completion.model, inputTokens: completion.usage?.input, outputTokens: completion.usage?.output,+ });++ const created = [];+ for (const v of valid) {+ const [row] = await sql`+ INSERT INTO agent_reflections+ (agent_id, status, kind, statement, rationale, confidence, source_memory_ids,+ proposed_type, proposed_salience, proposed_action, question, run_id)+ VALUES (+ ${agentId}, 'pending', ${v.kind}, ${v.statement}, ${v.rationale}, ${v.confidence},+ ${v.sourceIds}::uuid[], ${v.proposedType}, ${v.proposedSalience},+ ${v.proposedAction ? JSON.stringify(v.proposedAction) : null}::jsonb,+ ${v.question}, ${run.id}+ )+ RETURNING *+ `;+ created.push(decorateReflection(row));+ }++ return { status: 'ok', runId: run.id, created, candidates: candidates.length };+}++async function recordRun({ agentId, trigger, status, reason = null, dreamsCreated = 0, candidates = 0, model = null, inputTokens = null, outputTokens = null }) {+ const [row] = await sql`+ INSERT INTO agent_reflection_runs+ (agent_id, trigger, status, reason, dreams_created, candidates, model, input_tokens, output_tokens)+ VALUES (${agentId}, ${trigger}, ${status}, ${reason}, ${dreamsCreated}, ${candidates}, ${model}, ${inputTokens}, ${outputTokens})+ RETURNING id, created_at+ `;+ if (status === 'skipped' || (status === 'ok' && dreamsCreated === 0)) {+ // No silent caps: surface why a pass produced nothing.+ console.log(`[reflection] agent=${agentId} trigger=${trigger} ${status}: ${reason || 'no dreams'}`);+ }+ return row;+}++/** Shape a DB reflection row for API/UI consumption. */+export function decorateReflection(row) {+ return {+ id: row.id,+ agentId: row.agent_id,+ status: row.status,+ kind: row.kind,+ statement: row.statement,+ rationale: row.rationale,+ confidence: row.confidence,+ sourceMemoryIds: row.source_memory_ids || [],+ proposedType: row.proposed_type,+ proposedSalience: row.proposed_salience,+ proposedAction: row.proposed_action || null,+ question: row.question || null,+ answer: row.answer || null,+ acceptedMemoryId: row.accepted_memory_id || null,+ createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,+ reviewedAt: row.reviewed_at ? (row.reviewed_at instanceof Date ? row.reviewed_at.toISOString() : row.reviewed_at) : null,+ };+}diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 23a59df8a..16b604d32 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -488,6 +488,13 @@ alter table agent_identities add column if not exists persona_prompt_hash textalter table agent_identities add column if not exists persona_prompt_sig text;alter table agent_identities add column if not exists persona_tone_tags jsonb not null default '[]'::jsonb;alter table agent_identities add column if not exists persona_extracted_at timestamptz;+-- Brain Studio: structured, editable personality. `persona_traits` is the source+-- of truth for the slider dimensions + vocabulary + base persona; it compiles+-- (src/agents/persona-compile.js) into the signed `persona_prompt` above.+-- `persona_updated_at` tracks the last Brain Studio save (distinct from the+-- one-time extraction interview in `persona_extracted_at`).+alter table agent_identities add column if not exists persona_traits jsonb not null default '{}'::jsonb;+alter table agent_identities add column if not exists persona_updated_at timestamptz;-- is_public arrived via inline CREATE on fresh DBs but never as an additive-- migration, so pre-existing deployments are missing the column entirely —-- that 500s /api/avatars/:id/agents. Add it and backfill to the new default.@@ -563,6 +570,93 @@ do $$ beginfor each row execute function set_updated_at();exception when duplicate_object then null; end $$;+-- ── agent_reflections / _reflection_runs — Reflection & Dreams (Living Agents) ─+-- The agent consolidates raw memories + actions into higher-order "dreams" the+-- owner reviews. agent_reflections holds the candidate insights (provenance via+-- source_memory_ids is mandatory); agent_reflection_runs logs every pass — even+-- skipped ones — so the per-agent daily cap + debounce never silently truncate.+-- See migrations/20260623210000_agent_reflections.sql.+create table if not exists agent_reflections (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ status text not null default 'pending'+ check (status in ('pending', 'accepted', 'rejected')),+ kind text not null default 'insight'+ check (kind in ('insight', 'belief', 'question', 'prune')),+ statement text not null,+ rationale text,+ confidence real not null default 0.5 check (confidence >= 0 and confidence <= 1),+ source_memory_ids uuid[] not null default '{}',+ proposed_type text check (proposed_type in ('user', 'feedback', 'project', 'reference')),+ proposed_salience real not null default 0.7 check (proposed_salience >= 0 and proposed_salience <= 1),+ proposed_action jsonb,+ question text,+ answer text,+ run_id uuid,+ accepted_memory_id uuid,+ created_at timestamptz not null default now(),+ reviewed_at timestamptz+);+create index if not exists agent_reflections_agent_status+ on agent_reflections(agent_id, status, created_at desc);+create index if not exists agent_reflections_run+ on agent_reflections(run_id)+ where run_id is not null;++create table if not exists agent_reflection_runs (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ trigger text not null check (trigger in ('cron', 'on-demand', 'manual')),+ status text not null check (status in ('ok', 'skipped', 'error')),+ reason text,+ dreams_created integer not null default 0,+ candidates integer not null default 0,+ model text,+ input_tokens integer,+ output_tokens integer,+ created_at timestamptz not null default now()+);+create index if not exists agent_reflection_runs_agent_time+ on agent_reflection_runs(agent_id, created_at desc);++-- ── agent_autopilot_proposals — Memory-grounded Autopilot (Living Agents) ─────+-- Explainable autonomy: the agent proposes and (within owner-granted scope) takes+-- REAL actions, each traceable to the memory/reflection that motivated it. Scope+-- lives on agent_identities.meta.autopilot; this is the proposal queue. Execution+-- records a signed agent_actions row linked via executed_action_id. Provenance+-- (source_memory_ids and/or source_reflection_id) is mandatory.+-- See migrations/20260623230000_autopilot_proposals.sql.+create table if not exists agent_autopilot_proposals (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ kind text not null+ check (kind in ('create_alert', 'briefing', 'wallet_transfer')),+ title text not null,+ rationale text not null,+ params jsonb not null default '{}'::jsonb,+ source_memory_ids uuid[] not null default '{}',+ source_reflection_id uuid references agent_reflections(id) on delete set null,+ confidence real not null default 0.6 check (confidence >= 0 and confidence <= 1),+ requires_confirmation boolean not null default true,+ status text not null default 'pending'+ check (status in ('pending', 'executed', 'dismissed', 'undone', 'failed')),+ executed_action_id bigint,+ result jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ decided_at timestamptz,+ executed_at timestamptz,+ constraint agent_autopilot_proposals_has_source+ check (array_length(source_memory_ids, 1) > 0 or source_reflection_id is not null)+);+create index if not exists agent_autopilot_proposals_agent_status+ on agent_autopilot_proposals(agent_id, status, created_at desc);+create index if not exists agent_autopilot_proposals_user+ on agent_autopilot_proposals(user_id, created_at desc);+create unique index if not exists agent_autopilot_proposals_reflection_pending+ on agent_autopilot_proposals(source_reflection_id)+ where source_reflection_id is not null and status = 'pending';+-- ── agent_memory_entities / _entity_links — temporal knowledge graph (P2) ────-- Nodes are the entities (mints, tickers, wallets, people, strategies, topics)-- the agent's memories mention; edges are derived at read time from co-occurrencediff --git a/api/_lib/vault-accounting.js b/api/_lib/vault-accounting.jsnew file mode 100644index 000000000..61b0be911--- /dev/null+++ b/api/_lib/vault-accounting.js@@ -0,0 +1,220 @@+// @ts-check+// Back-an-Agent Vaults — the canonical share-accounting + safety math.+//+// PURE by construction: every function here is a deterministic BigInt computation+// with no DB, network, clock, or randomness. That's deliberate — this is the code+// that decides how many shares a deposit mints, what a redemption pays, what+// performance fee the owner earns, and whether the drawdown circuit breaker trips.+// It must be auditable and unit-testable in isolation (see tests/vault-accounting),+// and identical wherever it runs (server settlement + client preview).+//+// Units+// • All money is USDC atomic units (6 decimals): 1 USDC = 1_000_000n atomics.+// • Shares are unitless BigInt. The FIRST deposit into an empty vault mints+// shares 1:1 with the USDC atomics deposited, so the initial share price is+// exactly 1.000000 USDC. Every later deposit/redemption is priced against the+// live NAV (vault USDC balance + mark-to-market value of open positions).+// • Share price is reported scaled by 1e6 (`*_e6`) so a price of 1.5 USDC/share+// is the integer 1_500_000 — exact, no float.+//+// Invariants the tests pin down+// • A redemption never pays out more than the vault's pro-rata NAV (floor div).+// • The sum of all backers' redemptions at a fixed NAV never exceeds NAV (no+// dust overdraw) — the vault can never be drained below what it holds.+// • The performance fee is charged ONLY on a backer's realized gain above their+// own cost basis — never on principal, never on a loss, never cross-subsidized.++export const SHARE_PRICE_SCALE = 1_000_000n; // 1e6 — share price fixed-point scale+export const USDC_DECIMALS = 6;+export const USDC_ATOMICS = 1_000_000n;+export const BPS = 10_000n;++/** Coerce a value (BigInt | number | numeric-string | null) to BigInt atomics. */+export function toBig(v) {+ if (typeof v === 'bigint') return v;+ if (v == null) return 0n;+ if (typeof v === 'number') {+ if (!Number.isFinite(v)) return 0n;+ return BigInt(Math.trunc(v));+ }+ const s = String(v).trim();+ if (!s) return 0n;+ // numeric(40,0) columns come back as plain integer strings; tolerate a stray+ // decimal tail by truncating it (never round up into funds that aren't there).+ const dot = s.indexOf('.');+ return BigInt(dot >= 0 ? s.slice(0, dot) : s);+}++/** Float USDC → 6-decimal atomics (BigInt, floored, never negative). */+export function usdcToAtomics(usdc) {+ const n = Number(usdc);+ if (!Number.isFinite(n) || n <= 0) return 0n;+ return BigInt(Math.floor(n * Number(USDC_ATOMICS)));+}++/** Atomics → float USDC (for display only — never feed back into accounting). */+export function atomicsToUsdc(atomics) {+ return Number(toBig(atomics)) / Number(USDC_ATOMICS);+}++/**+ * Share price scaled by 1e6. An empty vault (no shares) is 1.000000 by definition,+ * so the first deposit always mints at par. With shares outstanding the price is+ * NAV per share: a vault that doubled shows 2_000_000.+ */+export function sharePriceE6(navAtomics, totalShares) {+ const nav = toBig(navAtomics);+ const shares = toBig(totalShares);+ if (shares <= 0n) return SHARE_PRICE_SCALE;+ return (nav * SHARE_PRICE_SCALE) / shares;+}++/**+ * Shares minted for a deposit of `depositAtomics` against the NAV measured BEFORE+ * the deposit lands. Floors so the vault never over-issues shares against the+ * capital actually received. A first deposit (or a wiped-out vault with no+ * recoverable NAV) mints 1:1 at par.+ */+export function sharesForDeposit(depositAtomics, navBeforeAtomics, totalShares) {+ const deposit = toBig(depositAtomics);+ const navBefore = toBig(navBeforeAtomics);+ const shares = toBig(totalShares);+ if (deposit <= 0n) return 0n;+ if (shares <= 0n || navBefore <= 0n) return deposit; // par: 1 share = 1 atomic+ return (deposit * shares) / navBefore;+}++/**+ * Gross USDC value of redeeming `shares` out of a vault holding `navAtomics`+ * across `totalShares`. Floors — the pro-rata claim, never a cent more than held.+ */+export function payoutForShares(shares, navAtomics, totalShares) {+ const s = toBig(shares);+ const nav = toBig(navAtomics);+ const total = toBig(totalShares);+ if (s <= 0n || total <= 0n || nav <= 0n) return 0n;+ if (s >= total) return nav; // last holder out takes the remainder exactly (no dust left behind)+ return (s * nav) / total;+}++/**+ * Crystallize a redemption: gross pro-rata payout, the cost basis attributable to+ * the redeemed shares, the realized gain, the owner's performance fee (only on a+ * positive gain), and the backer's net payout. All exact BigInt, floored.+ *+ * @param {object} a+ * @param {bigint|string|number} a.shares shares being redeemed+ * @param {bigint|string|number} a.backerShares backer's total shares before this redemption+ * @param {bigint|string|number} a.costBasisAtomics backer's principal still at risk+ * @param {bigint|string|number} a.navAtomics live vault NAV+ * @param {bigint|string|number} a.totalShares vault total shares before this redemption+ * @param {number} a.feeBps performance fee in basis points+ */+export function settleRedemption({ shares, backerShares, costBasisAtomics, navAtomics, totalShares, feeBps }) {+ const s = toBig(shares);+ const bShares = toBig(backerShares);+ const basis = toBig(costBasisAtomics);+ const fee_bps = BigInt(Math.max(0, Math.min(5000, Math.round(Number(feeBps) || 0))));++ const grossPayout = payoutForShares(s, navAtomics, totalShares);+ // Cost basis attributable to exactly the redeemed slice of the backer's holding.+ const costPortion = bShares > 0n ? (basis * s) / bShares : 0n;+ const gain = grossPayout - costPortion; // signed+ const fee = gain > 0n ? (gain * fee_bps) / BPS : 0n;+ const netPayout = grossPayout - fee;+ return {+ grossPayout,+ costPortion,+ gain,+ fee,+ netPayout,+ // Remaining basis after this redemption (clamped at 0).+ remainingBasis: basis > costPortion ? basis - costPortion : 0n,+ };+}++/**+ * Largest whole number of shares redeemable RIGHT NOW given only `freeAtomics`+ * of liquid USDC on hand (the rest of NAV is in open positions). Used for honest+ * partial redemptions: we never quote an instant number we can't actually pay.+ * Returns the share count whose gross payout is ≤ freeAtomics, capped at the+ * backer's holding.+ */+export function sharesRedeemableNow({ requestedShares, navAtomics, totalShares, freeAtomics }) {+ const want = toBig(requestedShares);+ const nav = toBig(navAtomics);+ const total = toBig(totalShares);+ const free = toBig(freeAtomics);+ if (want <= 0n || total <= 0n || nav <= 0n || free <= 0n) return 0n;+ // payout(shares) = shares * nav / total ≤ free → shares ≤ free * total / nav+ const cap = (free * total) / nav;+ const redeemable = cap < want ? cap : want;+ return redeemable < 0n ? 0n : redeemable;+}++/**+ * Drawdown from the high-water peak, in basis points (floored). 0 when at/above+ * peak. A 25% drop from peak returns 2500.+ */+export function drawdownBps(peakNavAtomics, currentNavAtomics) {+ const peak = toBig(peakNavAtomics);+ const cur = toBig(currentNavAtomics);+ if (peak <= 0n || cur >= peak) return 0;+ const drop = ((peak - cur) * BPS) / peak;+ return Number(drop);+}++/**+ * The drawdown circuit breaker. True when the vault has fallen `maxDrawdownBps` or+ * more from its high-water peak — at which point trading must halt and remaining+ * capital be protected.+ */+export function isDrawdownBreached(peakNavAtomics, currentNavAtomics, maxDrawdownBps) {+ const max = Math.max(0, Math.round(Number(maxDrawdownBps) || 0));+ if (max <= 0) return false;+ return drawdownBps(peakNavAtomics, currentNavAtomics) >= max;+}++/** Per-backer cap check: would this deposit push the backer over their cap? */+export function depositExceedsCap(currentContribAtomics, depositAtomics, capAtomics) {+ if (capAtomics == null) return false;+ const cap = toBig(capAtomics);+ if (cap <= 0n) return false;+ return toBig(currentContribAtomics) + toBig(depositAtomics) > cap;+}++/** Per-trade size check: is this buy larger than the vault's per-trade ceiling? */+export function tradeExceedsPerTrade(amountAtomics, maxPerTradeAtomics) {+ const cap = toBig(maxPerTradeAtomics);+ if (cap <= 0n) return false;+ return toBig(amountAtomics) > cap;+}++/** Rolling daily-budget check: would this buy push 24h spend over the budget? */+export function tradeExceedsDailyBudget(spentAtomics, amountAtomics, dailyBudgetAtomics) {+ const budget = toBig(dailyBudgetAtomics);+ if (budget <= 0n) return false;+ return toBig(spentAtomics) + toBig(amountAtomics) > budget;+}++/**+ * Roll the high-water peak forward. The peak only ever rises (it's the reference+ * the drawdown breaker measures against), so a new NAV that exceeds it becomes the+ * new peak; otherwise the peak is unchanged.+ */+export function nextPeak(peakNavAtomics, currentNavAtomics) {+ const peak = toBig(peakNavAtomics);+ const cur = toBig(currentNavAtomics);+ return cur > peak ? cur : peak;+}++/**+ * Simple, holdings-derived ROI in basis points for display: how the current share+ * price compares to par (1.0). +50% shows 5000, −20% shows −2000.+ */+export function roiBps(navAtomics, totalShares) {+ const total = toBig(totalShares);+ if (total <= 0n) return 0;+ const priceE6 = sharePriceE6(navAtomics, total);+ return Number(((priceE6 - SHARE_PRICE_SCALE) * BPS) / SHARE_PRICE_SCALE);+}diff --git a/api/agent/dreams.js b/api/agent/dreams.jsnew file mode 100644index 000000000..d5e1ed4ee--- /dev/null+++ b/api/agent/dreams.js@@ -0,0 +1,230 @@+// /api/agent/dreams — the review surface for an agent's reflections ("dreams").+//+// GET /api/agent/dreams?agentId=&status=pending&limit= (owner-only)+// → { dreams: [...], pending, lastRun }+// Each dream carries its cited source memories (provenance), so the UI can+// link straight into the Mind Palace.+//+// POST /api/agent/dreams (owner-only) { agentId, dreamId, decision, answer? }+// decision = 'accept' → writes a real, higher-salience memory (the dream+// becomes part of the mind) and links it back.+// 'reject' → stores the rejection; future reflections learn from it.+// 'answer' → for kind='question' dreams: writes the user's answer+// as a real memory and resolves the dream.+//+// Real reads of agent_memories; real writes on accept/answer. No mocks.++import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { decorateReflection } from '../_lib/reflection.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 requireOwnedAgent(req, res, agentId, auth) {+ if (!agentId) {+ error(res, 400, 'validation_error', 'agentId required');+ return null;+ }+ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) {+ error(res, 404, 'not_found', 'agent not found');+ return null;+ }+ if (agent.user_id !== auth.userId) {+ error(res, 403, 'forbidden', 'not your agent');+ return null;+ }+ return agent;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') return handleList(req, res, auth);+ return handleReview(req, res, auth);+});++async function handleList(req, res, auth) {+ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');+ const status = url.searchParams.get('status'); // pending | accepted | rejected | (all)+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);++ const agent = await requireOwnedAgent(req, res, agentId, auth);+ if (!agent) return;++ const rows = status && ['pending', 'accepted', 'rejected'].includes(status)+ ? await sql`+ SELECT * FROM agent_reflections+ WHERE agent_id = ${agentId} AND status = ${status}+ ORDER BY created_at DESC+ LIMIT ${limit}+ `+ : await sql`+ SELECT * FROM agent_reflections+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ LIMIT ${limit}+ `;++ // Hydrate cited source memories so the UI can show + link the evidence.+ const allIds = [...new Set(rows.flatMap((r) => r.source_memory_ids || []))];+ const memRows = allIds.length+ ? await sql`+ SELECT id, type, content, salience, created_at+ FROM agent_memories+ WHERE agent_id = ${agentId} AND id = ANY(${allIds}::uuid[])+ `+ : [];+ const memById = new Map(memRows.map((m) => [m.id, {+ id: m.id, type: m.type, content: m.content, salience: m.salience,+ createdAt: m.created_at instanceof Date ? m.created_at.toISOString() : m.created_at,+ }]));++ const dreams = rows.map((r) => {+ const d = decorateReflection(r);+ // A cited memory may have since been forgotten; mark it rather than drop it.+ d.sources = (d.sourceMemoryIds || []).map((id) => memById.get(id) || { id, forgotten: true });+ return d;+ });++ const [{ pending } = { pending: 0 }] = await sql`+ SELECT COUNT(*)::int AS pending FROM agent_reflections+ WHERE agent_id = ${agentId} AND status = 'pending'+ `;+ const [lastRun] = await sql`+ SELECT trigger, status, reason, dreams_created, created_at+ FROM agent_reflection_runs+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC+ LIMIT 1+ `;++ return json(res, 200, {+ dreams,+ pending,+ lastRun: lastRun+ ? {+ trigger: lastRun.trigger,+ status: lastRun.status,+ reason: lastRun.reason,+ dreamsCreated: lastRun.dreams_created,+ at: lastRun.created_at instanceof Date ? lastRun.created_at.toISOString() : lastRun.created_at,+ }+ : null,+ });+}++async function handleReview(req, res, auth) {+ if (!(await requireCsrf(req, res, auth.userId))) return;++ const body = await readJson(req);+ const agentId = body.agentId || body.agent_id;+ const dreamId = body.dreamId || body.dream_id;+ const decision = body.decision;++ if (!dreamId) return error(res, 400, 'validation_error', 'dreamId required');+ if (!['accept', 'reject', 'answer'].includes(decision)) {+ return error(res, 400, 'validation_error', "decision must be 'accept', 'reject', or 'answer'");+ }++ const agent = await requireOwnedAgent(req, res, agentId, auth);+ if (!agent) return;++ const [dream] = await sql`+ SELECT * FROM agent_reflections WHERE id = ${dreamId} AND agent_id = ${agentId}+ `;+ if (!dream) return error(res, 404, 'not_found', 'dream not found');+ if (dream.status !== 'pending') {+ return error(res, 409, 'already_reviewed', `dream already ${dream.status}`);+ }++ if (decision === 'reject') {+ // Storing the rejection is the learning signal — the engine feeds rejected+ // statements back into future passes so the synthesis isn't re-proposed.+ const [row] = await sql`+ UPDATE agent_reflections+ SET status = 'rejected', reviewed_at = now()+ WHERE id = ${dreamId} AND agent_id = ${agentId} AND status = 'pending'+ RETURNING *+ `;+ if (!row) return error(res, 409, 'already_reviewed', 'dream already reviewed');+ return json(res, 200, { dream: decorateReflection(row) });+ }++ // accept / answer both write a real memory. For 'answer', the user's reply+ // is folded into the stored fact so the agent remembers the clarification.+ let content = dream.statement;+ let answer = null;+ if (decision === 'answer') {+ answer = typeof body.answer === 'string' ? body.answer.trim() : '';+ if (!answer) return error(res, 400, 'validation_error', 'answer required for an answer decision');+ answer = answer.slice(0, 2000);+ content = `${dream.statement} — ${answer}`;+ }++ const memType = ['user', 'feedback', 'project', 'reference'].includes(dream.proposed_type)+ ? dream.proposed_type+ : 'project';+ const tags = ['dream', dream.kind].filter(Boolean);+ const context = {+ source: 'reflection',+ reflection_id: dream.id,+ source_memory_ids: dream.source_memory_ids || [],+ confidence: dream.confidence,+ ...(answer ? { answered: true } : {}),+ ...(dream.proposed_action ? { proposed_action: dream.proposed_action } : {}),+ };++ const [memory] = await sql`+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, tier, pinned)+ VALUES (+ gen_random_uuid(), ${agentId}, ${memType},+ ${content.slice(0, 10000)}, ${tags}, ${JSON.stringify(context)}::jsonb,+ ${dream.proposed_salience}, 'recall', false+ )+ RETURNING id, type, content, salience, created_at+ `;++ const [row] = await sql`+ UPDATE agent_reflections+ SET status = 'accepted', reviewed_at = now(),+ accepted_memory_id = ${memory.id},+ answer = ${answer}+ WHERE id = ${dreamId} AND agent_id = ${agentId} AND status = 'pending'+ RETURNING *+ `;+ if (!row) {+ // Lost the race — another reviewer accepted/rejected first. Roll back the+ // memory we just wrote so we don't leave an orphan.+ await sql`DELETE FROM agent_memories WHERE id = ${memory.id}`;+ return error(res, 409, 'already_reviewed', 'dream already reviewed');+ }++ return json(res, 200, {+ dream: decorateReflection(row),+ memory: {+ id: memory.id,+ type: memory.type,+ content: memory.content,+ salience: memory.salience,+ createdAt: memory.created_at instanceof Date ? memory.created_at.toISOString() : memory.created_at,+ },+ // Surface the proposed automation so the UI can hand it to Autopilot (Task 08).+ proposedAction: dream.proposed_action || null,+ });+}diff --git a/api/agent/reflect.js b/api/agent/reflect.jsnew file mode 100644index 000000000..a72670aff--- /dev/null+++ b/api/agent/reflect.js@@ -0,0 +1,66 @@+// POST /api/agent/reflect — run a real reflection pass for an agent (owner-only).+//+// Body: { agentId, force? }+// Triggers the memory-consolidation engine (api/_lib/reflection.js): the agent+// reads its own recent raw memories + signed action log, runs a real LLM pass,+// and persists schema-valid "dreams" (each citing the source memory ids it drew+// from). Debounced + daily-capped server-side, so the review surface can call+// this on open without spamming the model. `force` (owner-initiated "Reflect+// now") bypasses the debounce.+//+// Response: { status, reason?, created: [dream...], candidates, capped }++import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { runReflection } from '../_lib/reflection.js';++export const maxDuration = 60;++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;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ if (!(await requireCsrf(req, res, auth.userId))) return;++ const body = await readJson(req);+ const agentId = body.agentId || body.agent_id;+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');++ const [agent] = await sql`+ SELECT id, user_id, name, description+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ // Reflection is an LLM call — rate-limit per caller independently of the+ // engine's own debounce (which protects the model spend over a longer window).+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many reflection requests');++ const force = body.force === true;+ const result = await runReflection({+ agentId,+ userId: auth.userId,+ trigger: force ? 'manual' : 'on-demand',+ agent: { name: agent.name, description: agent.description },+ force,+ });++ const code = result.status === 'error' ? 502 : 200;+ return json(res, code, result);+});diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 7fef400ad..616b61ec0 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -77,6 +77,11 @@ export default wrap(async function handler(req, res) {return mod.default(req, res, id, action);}+ if (sub === 'alpha') {+ const mod = await import('./alpha.js');+ return mod.default(req, res, id, action);+ }+if (sub === 'portfolio') {const mod = await import('./portfolio.js');return mod.default(req, res, id, action);diff --git a/api/agents/[id]/economy.js b/api/agents/[id]/economy.jsindex 8a246e586..784ac6c5c 100644--- a/api/agents/[id]/economy.js+++ b/api/agents/[id]/economy.js@@ -1,8 +1,9 @@// GET /api/agents/:id/economy — the owner-facing economy summary for one agent.//// "Your avatar has a job." This is the single read behind the wallet hub's Earn-// tab: every dollar the agent has earned (skill sales + tips) and every dollar-// it has spent paying other services over x402, plus the live spend policy that+// tab: every dollar the agent has earned (skill sales + hires from other agents+// + tips) and every dollar it has spent paying other services over x402, plus+// the live spend policy that// keeps autonomous spending safe, and a unified receipts statement. Every number// traces to a real ledger row — agent_custody_events, agent_revenue_events,// skill_purchases — never a mock.@@ -12,16 +13,23 @@// (agent_identities.user_id === auth.userId). A public "earned $X" brag uses the// public pulse agent-summary instead; this endpoint never leaks to a visitor.//-// earnings : skill sales + tips, windowed today / 7d / lifetime (USD)-// spending : x402 agent-to-agent payments, windowed (USD)-// policy : daily/per-tx caps, allowlist size, frozen, today's spend-// receipts : recent in + out movements as a clean statement-// peers : top counterparties the agent has paid (the A2A network edge)+// earnings : skill sales + hires + tips, windowed today / 7d / lifetime (USD)+// spending : x402 agent-to-agent payments, windowed (USD)+// policy : daily/per-tx caps, allowlist size, frozen, today's spend+// receipts : recent in + out movements as a clean statement+// customers : top agents that have hired this one (the income edge)+// peers : top counterparties the agent has paid (the outlay edge)+//+// "Hires" are the headline of the agent economy: another agent autonomously paid+// this one for a skill over the real x402 rails (api/agents/a2a-hire.js). That+// income is the authoritative agent_hires ledger — surfaced as its own earnings+// bucket and receipts, never silently lumped into tips.import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';import { sql } from '../../_lib/db.js';import { getSpendLimits, getDailySpendUsd } from '../../_lib/agent-trade-guards.js';+import { composeEarnings } from '../../_lib/economy-shape.js';import { env } from '../../_lib/env.js';// Skill prices are denominated in USDC (6 decimals) across the platform — the@@ -86,7 +94,10 @@ export default wrap(async (req, res) => {FROM agent_revenue_eventsWHERE agent_id = ${id}`,- // Tips received (already USD-priced on the custody row).+ // Tips received (already USD-priced on the custody row). A2A hire income+ // is also written as a 'tip' custody row for the live money pulse, but it+ // is the agent_hires ledger's job to surface it as earned-by-hire — exclude+ // it here so it is counted once, in its own bucket, not mislabeled as a tip.sql`SELECTCOALESCE(SUM(usd) FILTER (WHERE created_at >= date_trunc('day', now())), 0)::float8 AS today,@@ -96,6 +107,7 @@ export default wrap(async (req, res) => {FROM agent_custody_eventsWHERE agent_id = ${id} AND network = ${network}AND event_type = 'tip' AND status IN ('ok', 'confirmed')+ AND (meta->>'source') IS DISTINCT FROM 'a2a_hire'`,// Outbound agent-to-agent payments over x402 (USD-priced).sql`@@ -116,12 +128,14 @@ export default wrap(async (req, res) => {WHERE agent_id = ${id} AND is_active = trueORDER BY amount DESC`,- // Inbound receipts — tips.+ // Inbound receipts — tips (a2a hire 'tip' rows excluded; hires get their+ // own receipts from the agent_hires ledger below).sql`SELECT id, usd, amount_lamports, signature, created_at, metaFROM agent_custody_eventsWHERE agent_id = ${id} AND network = ${network}AND event_type = 'tip' AND status IN ('ok', 'confirmed')+ AND (meta->>'source') IS DISTINCT FROM 'a2a_hire'ORDER BY created_at DESCLIMIT ${RECEIPTS_LIMIT}`,@@ -165,12 +179,55 @@ export default wrap(async (req, res) => {getDailySpendUsd(id, network).catch(() => null),]);+ // A2A hire income lives on the real, mainnet-settled agent_hires ledger (USDC+ // over x402). It is the authoritative record of "another agent paid mine for a+ // skill" — surfaced as its own earnings bucket, its own receipts, and the+ // top-customers edge. Scoped to the mainnet view (the only place real hires+ // settle); a devnet view shows none, matching the rest of this endpoint.+ const [hireEarn, hireReceipts, customers] = network === 'mainnet'+ ? await Promise.all([+ sql`+ SELECT+ COALESCE(SUM(usd) FILTER (WHERE COALESCE(completed_at, created_at) >= date_trunc('day', now())), 0)::float8 AS today,+ COALESCE(SUM(usd) FILTER (WHERE COALESCE(completed_at, created_at) >= now() - interval '7 days'), 0)::float8 AS week,+ COALESCE(SUM(usd), 0)::float8 AS lifetime,+ COUNT(*)::int AS count+ FROM agent_hires+ WHERE provider_agent_id = ${id} AND status = 'completed'+ `,+ sql`+ SELECT h.id, h.usd, h.skill_name, h.payment_signature, h.invocation_signature,+ h.hirer_agent_id, hr.name AS hirer_name,+ COALESCE(h.completed_at, h.created_at) AS at+ FROM agent_hires h+ LEFT JOIN agent_identities hr ON hr.id = h.hirer_agent_id+ WHERE h.provider_agent_id = ${id} AND h.status = 'completed'+ ORDER BY COALESCE(h.completed_at, h.created_at) DESC+ LIMIT ${RECEIPTS_LIMIT}+ `,+ sql`+ SELECT h.hirer_agent_id, hr.name AS hirer_name, hr.is_public AS hirer_public,+ COUNT(*)::int AS count,+ COALESCE(SUM(h.usd), 0)::float8 AS usd,+ MAX(COALESCE(h.completed_at, h.created_at)) AS last_at+ FROM agent_hires h+ LEFT JOIN agent_identities hr ON hr.id = h.hirer_agent_id+ WHERE h.provider_agent_id = ${id} AND h.status = 'completed'+ AND h.hirer_agent_id IS NOT NULL+ GROUP BY h.hirer_agent_id, hr.name, hr.is_public+ ORDER BY usd DESC, count DESC+ LIMIT ${PEERS_LIMIT}+ `,+ ])+ : [[{}], [], []];+const usdc = (atomic) => Number(BigInt(atomic || '0')) / 1e6;const se = skillEarn[0] || {};const tp = tips[0] || {};const sp = spend[0] || {};+ const he = hireEarn[0] || {};- const earnings = {+ const earnings = composeEarnings({skill_sales: {today: usdc(se.today),week: usdc(se.week),@@ -178,19 +235,20 @@ export default wrap(async (req, res) => {count: Number(se.count || 0),non_usdc_count: Number(se.non_usdc_count || 0),},+ // Agents hiring this agent — paid, on-chain, over the x402 rails.+ hires: {+ today: Number(he.today || 0),+ week: Number(he.week || 0),+ lifetime: Number(he.lifetime || 0),+ count: Number(he.count || 0),+ },tips: {today: Number(tp.today || 0),week: Number(tp.week || 0),lifetime: Number(tp.lifetime || 0),count: Number(tp.count || 0),},- };- earnings.total = {- today: earnings.skill_sales.today + earnings.tips.today,- week: earnings.skill_sales.week + earnings.tips.week,- lifetime: earnings.skill_sales.lifetime + earnings.tips.lifetime,- count: earnings.skill_sales.count + earnings.tips.count,- };+ });const spending = {x402: {@@ -240,6 +298,22 @@ export default wrap(async (req, res) => {created_at: r.created_at,});}+ for (const r of hireReceipts) {+ receipts.push({+ id: `hire-${r.id}`,+ direction: 'in',+ kind: 'hire',+ usd: r.usd != null ? Number(r.usd) : null,+ counterparty: r.hirer_name || r.hirer_agent_id || null,+ counterparty_agent_id: r.hirer_agent_id || null,+ label: r.skill_name ? `Hired · ${r.skill_name}` : 'Agent hire',+ skill: r.skill_name || null,+ signature: r.payment_signature || null,+ invocation_signature: r.invocation_signature || null,+ status: 'confirmed',+ created_at: r.at,+ });+ }for (const r of spendReceipts) {receipts.push({id: `pay-${r.id}`,@@ -273,6 +347,16 @@ export default wrap(async (req, res) => {pricing_type: p.pricing_type,})),receipts: receipts.slice(0, RECEIPTS_LIMIT),+ // Top agents that have hired this one — the income edge of the mesh.+ // Each links to a real agent profile (public ones are navigable).+ customers: customers.map((c) => ({+ agent_id: c.hirer_agent_id,+ name: c.hirer_name || 'Agent',+ is_public: c.hirer_public !== false,+ count: Number(c.count || 0),+ usd: Number(c.usd || 0),+ last_at: c.last_at,+ })),peers: peers.map((p) => ({address: p.destination,count: Number(p.count || 0),diff --git a/api/agents/alpha.js b/api/agents/alpha.jsnew file mode 100644index 000000000..d964f8b5f--- /dev/null+++ b/api/agents/alpha.js@@ -0,0 +1,373 @@+// /api/agents/:id/alpha — the In-Character Alpha Co-pilot.+//+// The intelligence + voice layer ON TOP of the wallet program's trade rails.+// The agent's LLM persona reads a REAL live pump.fun launch, decides what it+// would do, and explains it in character for its 3D avatar to speak aloud. The+// owner can then act on the read — but only ever through the same guarded path+// the conversational copilot uses (executeAgentTrade → POST /solana/trade),+// which enforces the spend policy, the rug/honeypot firewall, and the custody+// audit. This endpoint NEVER signs and NEVER moves funds.+//+// GET /api/agents/:id/alpha/candidates?network= → real live launches to read+// POST /api/agents/:id/alpha/read { mint, network } → grounded in-character read+//+// Anti-hallucination: the model only ever sees real numbers we fetched, and its+// output is clamped + scrubbed against those inputs (api/_lib/alpha-read.js)+// before it is shown or spoken — a fabricated figure is rejected, never voiced.+//+// $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is the only coin three.ws+// promotes. This reads whatever runtime mint the live feed surfaces — coin-+// agnostic analytics — and never names or recommends any other token.++import { PublicKey } from '@solana/web3.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error, readJson, rateLimited, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { solanaPublicConnection } from '../_lib/agent-pumpfun.js';+import { getSmartMoneyForMint } from '../_lib/smart-money.js';+import { getTradeLimits, getSpendLimits, getDailySpendLamports } from '../_lib/agent-trade-guards.js';+import { getBondingCurveState, getBuyQuote, getGraduationProgress } from '../_lib/solana/sdk-bridge.js';+import { connectPumpFunFeed, recentBuffered, recentGraduations } from '../_lib/pumpfun-ws-feed.js';+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';+import { buildReadPrompt, parseReadJson, validateRead } from '../_lib/alpha-read.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const LAMPORTS_PER_SOL = 1_000_000_000;+const PUMPFUN_COIN_API = 'https://frontend-api-v3.pump.fun/coins';+const REFERENCE_BUY_SOL = 0.1; // probe size for a real, non-binding price-impact read++const num = (v) => (v == null || !Number.isFinite(Number(v)) ? null : Number(v));++// ── auth (optional — public commentary works logged-out) ───────────────────────+async function resolveAuth(req) {+ const session = await getSessionUser(req).catch(() => null);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req)).catch(() => null);+ if (bearer) return { userId: bearer.userId };+ return null;+}++// Load the agent for an alpha read. Public commentary is allowed for published+// agents; the owner additionally unlocks wallet-aware sizing + the action gate.+async function loadAgent(id, userId) {+ const [row] = await sql`+ SELECT id, user_id, name, persona_prompt, voice_provider, voice_id, avatar_id,+ is_published, meta+ FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!row) return { error: { status: 404, code: 'not_found', msg: 'agent not found' } };+ const owner = !!userId && row.user_id === userId;+ if (!owner && !row.is_published) return { error: { status: 404, code: 'not_found', msg: 'agent not found' } };+ return { row, owner };+}++// ── live launch candidates ──────────────────────────────────────────────────────++async function fetchPumpCoin(mint) {+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), 2500);+ try {+ const r = await fetch(`${PUMPFUN_COIN_API}/${encodeURIComponent(mint)}`, {+ signal: ctrl.signal,+ headers: { accept: 'application/json', 'user-agent': 'three.ws-alpha-copilot/1' },+ });+ if (!r.ok) return null;+ return await r.json();+ } catch { return null; } finally { clearTimeout(tid); }+}++// Briefly tap the live PumpPortal mint feed to gather fresh launches. Bounded so+// a serverless request never hangs; resolves with whatever real mints arrived.+function collectLiveMints({ ms = 3200, want = 12 } = {}) {+ return new Promise((resolve) => {+ const out = [];+ const seen = new Set();+ const abort = new AbortController();+ let done = false;+ const finish = () => { if (done) return; done = true; try { abort.abort(); } catch {} resolve(out); };+ try {+ connectPumpFunFeed({+ kind: 'mint',+ signal: abort.signal,+ onEvent: ({ kind, data }) => {+ if (done || kind !== 'mint' || !data?.mint || seen.has(data.mint)) return;+ seen.add(data.mint);+ out.push(data);+ if (out.length >= want) finish();+ },+ });+ } catch { finish(); }+ setTimeout(finish, ms);+ });+}++async function enrichCandidate(c, network) {+ const [sm, intel] = await Promise.all([+ getSmartMoneyForMint(c.mint, network).catch(() => null),+ loadIntel(c.mint, network).catch(() => null),+ ]);+ const createdSec = num(c.created_at) || num(c.timestamp);+ const ageSeconds = createdSec ? Math.max(0, Math.floor(Date.now() / 1000 - createdSec)) : null;+ return {+ mint: c.mint,+ symbol: c.symbol || intel?.symbol || null,+ name: c.name || intel?.name || null,+ image_uri: c.image_uri || null,+ age_seconds: ageSeconds,+ market_cap_usd: num(c.market_cap_usd) ?? num(c.usd_market_cap),+ initial_buy_sol: num(c.initial_buy_sol),+ creator: c.creator || null,+ creator_launches: num(c.creator_launches),+ creator_graduated: num(c.creator_graduated),+ twitter: c.twitter || null,+ telegram: c.telegram || null,+ website: c.website || null,+ smart_money_score: sm?.smart_money_score ?? null,+ smart_money_count: sm?.count ?? null,+ sybil_flag: sm?.sybil_flag ?? false,+ quality_score: intel?.quality_score ?? null,+ risk_flags: intel?.risk_flags ?? [],+ };+}++async function handleCandidates(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const auth = await resolveAuth(req);+ const rl = await limits.publicIp(clientIp(req)).catch(() => ({ success: true }));+ if (rl && rl.success === false) return rateLimited(res, rl);++ const loaded = await loadAgent(id, auth?.userId);+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);++ const url = new URL(req.url, 'http://x');+ const network = netOf(url.searchParams.get('network'));++ // Merge three real sources, newest-first, deduped by mint: the warm in-process+ // buffer (instant), a brief live tap of the feed (fresh mints), and persisted+ // graduations from Postgres (always available, even on a cold instance).+ const byMint = new Map();+ const add = (d) => { if (d?.mint && !byMint.has(d.mint)) byMint.set(d.mint, d); };++ if (network === 'mainnet') {+ recentBuffered({ kind: 'mint', limit: 12 }).forEach((e) => add(e.data));+ if (byMint.size < 8) {+ const live = await collectLiveMints({ want: 12 - byMint.size }).catch(() => []);+ live.forEach(add);+ }+ recentBuffered({ kind: 'graduation', limit: 6 }).forEach((e) => add(e.data));+ if (byMint.size < 4) {+ const grads = await recentGraduations({ limit: 8 }).catch(() => []);+ grads.forEach(add);+ }+ }++ const raw = [...byMint.values()].slice(0, 10);+ const items = await Promise.all(raw.map((c) => enrichCandidate(c, network).catch(() => null)));+ return json(res, 200, { network, items: items.filter(Boolean) }, { 'cache-control': 'no-store' });+}++// ── intel read (same shape the copilot uses) ────────────────────────────────────+async function loadIntel(mint, network) {+ const [row] = await sql`+ SELECT i.mint, i.symbol, i.name, i.quality_score, i.bundle_score, i.organic_score,+ i.snipe_ratio, i.concentration_top10, i.fresh_wallet_ratio, i.risk_flags,+ i.category, i.narrative, i.dev_sold, i.unique_buyers,+ o.outcome, o.ath_multiple+ FROM pump_coin_intel i+ LEFT JOIN pump_coin_outcomes o ON o.mint = i.mint AND o.network = i.network+ WHERE i.mint = ${mint} AND i.network = ${network}+ LIMIT 1`.catch(() => []);+ if (!row) return null;+ return {+ symbol: row.symbol, name: row.name,+ quality_score: num(row.quality_score),+ bundle_score: num(row.bundle_score), organic_score: num(row.organic_score),+ snipe_ratio: num(row.snipe_ratio), concentration_top10: num(row.concentration_top10),+ fresh_wallet_ratio: num(row.fresh_wallet_ratio), risk_flags: row.risk_flags || [],+ category: row.category, narrative: row.narrative, dev_sold: row.dev_sold,+ unique_buyers: num(row.unique_buyers),+ outcome: row.outcome || null, ath_multiple: num(row.ath_multiple),+ };+}++// Gather every REAL signal for one mint. Each source degrades to null on its own+// — a thin coin yields a thin (but honest) signal bundle, never a fabricated one.+async function gatherSignals(mint, network, { agentId, meta, owner }) {+ const conn = solanaPublicConnection(network);+ const mintPk = new PublicKey(mint);+ const refLamports = Math.floor(REFERENCE_BUY_SOL * LAMPORTS_PER_SOL);+ const walletPk = owner && meta.solana_address ? new PublicKey(meta.solana_address) : null;++ const [coin, intel, sm, curve, grad, buyQuote, walletLamports, dailySpentLamports] = await Promise.all([+ network === 'mainnet' ? fetchPumpCoin(mint).catch(() => null) : Promise.resolve(null),+ loadIntel(mint, network).catch(() => null),+ getSmartMoneyForMint(mint, network).catch(() => null),+ getBondingCurveState(conn, mintPk).catch(() => null),+ getGraduationProgress(conn, mintPk).catch(() => null),+ getBuyQuote(conn, mintPk, refLamports).catch(() => null),+ walletPk ? conn.getBalance(walletPk).catch(() => null) : Promise.resolve(null),+ owner ? getDailySpendLamports(agentId, network).catch(() => 0n) : Promise.resolve(0n),+ ]);++ const solPrice = num(coin?.usd_market_cap) && num(coin?.market_cap) ? coin.usd_market_cap / coin.market_cap : null;+ const createdSec = num(coin?.created_timestamp) ? Math.floor(coin.created_timestamp / 1000) : null;+ const liquiditySol = curve ? round3(Number(BigInt(curve.realSolReserves)) / 1e9) : null;+ const gradPct = num(grad?.progress) != null ? Math.round(num(grad.progress) * 100) : (curve?.complete ? 100 : null);++ const tradeLimits = getTradeLimits(meta);+ const spendLimits = getSpendLimits(meta);+ const balanceSol = walletLamports != null ? round3(Number(walletLamports) / 1e9) : null;+ const dailySpentSol = round3(Number(dailySpentLamports || 0n) / 1e9);++ const signals = {+ symbol: coin?.symbol || intel?.symbol || null,+ name: coin?.name || intel?.name || null,+ network,+ age_minutes: createdSec ? Math.max(0, Math.round((Date.now() / 1000 - createdSec) / 60)) : null,+ market_cap_usd: num(coin?.usd_market_cap),+ liquidity_sol: liquiditySol,+ bonding_curve_progress_pct: gradPct,+ graduated: curve ? !!curve.complete : (coin?.complete ?? null),+ reference_buy_sol: buyQuote ? REFERENCE_BUY_SOL : null,+ reference_buy_price_impact_pct: buyQuote ? round2(buyQuote.priceImpact) : null,+ // Intelligence engine fingerprint (null when the engine hasn't observed it).+ quality_score: intel?.quality_score ?? null,+ organic_score: intel?.organic_score ?? null,+ bundle_score: intel?.bundle_score ?? null,+ concentration_top10_pct: intel?.concentration_top10 ?? null,+ fresh_wallet_ratio: intel?.fresh_wallet_ratio ?? null,+ unique_buyers: intel?.unique_buyers ?? null,+ dev_sold: intel?.dev_sold ?? null,+ narrative: intel?.narrative || null,+ risk_flags: intel?.risk_flags ?? [],+ outcome: intel?.outcome ?? null,+ // Smart money (reputation graph).+ smart_money_score: sm?.smart_money_score ?? null,+ smart_money_wallets: sm?.count ?? null,+ sybil_dominated: sm?.sybil_flag ?? null,+ };++ // Owner-only wallet context (also feeds the size clamp + action gate).+ const context = owner+ ? {+ balanceSol,+ perTradeSol: tradeLimits.per_trade_sol,+ dailyBudgetSol: tradeLimits.daily_budget_sol,+ dailySpentSol,+ killSwitch: tradeLimits.kill_switch,+ frozen: spendLimits.frozen,+ }+ : {};+ if (owner) {+ signals.wallet_balance_sol = balanceSol;+ signals.per_trade_limit_sol = tradeLimits.per_trade_sol;+ signals.daily_budget_sol = tradeLimits.daily_budget_sol;+ signals.daily_spent_sol = dailySpentSol;+ signals.trading_paused = tradeLimits.kill_switch || spendLimits.frozen;+ }++ // True when literally nothing real is known — used to skip the LLM and answer+ // honestly rather than ask the model to opine on a void.+ const hasData = [signals.market_cap_usd, signals.liquidity_sol, signals.quality_score,+ signals.smart_money_score, signals.symbol, signals.reference_buy_price_impact_pct]+ .some((v) => v != null);++ return { signals, context, hasData };+}++const round3 = (n) => Math.round(n * 1e3) / 1e3;+const round2 = (n) => Math.round(n * 1e2) / 1e2;++async function handleRead(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ const rl = auth?.userId+ ? await limits.tradePerUser(auth.userId).catch(() => ({ success: true }))+ : await limits.publicIp(clientIp(req)).catch(() => ({ success: true }));+ if (rl && rl.success === false) return rateLimited(res, rl);++ const loaded = await loadAgent(id, auth?.userId);+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);+ const { row, owner } = loaded;+ const meta = row.meta || {};++ const body = await readJson(req).catch(() => null);+ const network = netOf(body?.network);+ const mint = typeof body?.mint === 'string' ? body.mint.trim() : '';+ if (!BASE58_RE.test(mint)) return error(res, 422, 'invalid_mint', 'a valid token mint is required');+ if (owner && !meta.solana_address) return error(res, 409, 'no_wallet', 'this agent has no wallet yet');++ const agentName = row.name || 'Agent';+ const agentMeta = {+ id: row.id,+ name: agentName,+ voice_provider: row.voice_provider || 'browser',+ voice_id: row.voice_id || null,+ avatar_id: row.avatar_id || null,+ };++ let signals, context, hasData;+ try {+ ({ signals, context, hasData } = await gatherSignals(mint, network, { agentId: id, meta, owner }));+ } catch (e) {+ return error(res, 502, 'signal_error', 'could not read live signals for this launch — try again');+ }++ // Nothing real to go on: answer honestly, no LLM, no invented confidence.+ if (!hasData) {+ const read = {+ verdict: 'pass',+ conviction: 0,+ suggested_size_sol: null,+ risks: ['No live data is available for this mint yet.'],+ cited_signals: [],+ spoken_line: `I can't read ${signals.symbol ? '$' + signals.symbol : 'this one'} yet — there's no live data in front of me, so I'm not going to pretend I have a call.`,+ hallucination_guard: { ok: true, suspicious_numbers: [], line_replaced: false },+ };+ return json(res, 200, {+ mint, network, agent: agentMeta, owner, signals, read,+ gate: { can_act: false, reason: owner ? 'no_data' : 'not_owner', message: 'No data to act on.' },+ grounded: true, source: 'no_data',+ }, { 'cache-control': 'no-store' });+ }++ const { system, user } = buildReadPrompt({ agentName, persona: row.persona_prompt, network, signals, owner });++ let completion;+ try {+ completion = await llmComplete({+ system, user, maxTokens: 700, anthropicModel: 'claude-sonnet-4-6', timeoutMs: 30_000,+ track: { userId: auth?.userId ?? null, agentId: id, tool: 'alpha_read' },+ });+ } catch (e) {+ if (e instanceof LlmUnavailableError || e?.code === 'llm_unavailable') {+ return error(res, 503, 'narrator_offline', 'The co-pilot narrator is offline right now. Your wallet and trading still work — try the read again shortly.');+ }+ if (e?.code === 'daily_spend_cap_exceeded') return error(res, 429, e.code, e.message);+ return error(res, 502, 'read_failed', 'The co-pilot could not complete this read. Try again.');+ }++ const raw = parseReadJson(completion.text);+ const { read, gate } = validateRead({ raw, signals, agentName, owner, context });++ return json(res, 200, {+ mint, network, agent: agentMeta, owner, signals, read, gate,+ grounded: read.hallucination_guard.ok,+ model: completion.model, provider: completion.provider,+ source: 'llm',+ }, { 'cache-control': 'no-store' });+}++// ── dispatch ────────────────────────────────────────────────────────────────────+export default wrap(async function handler(req, res, id, action) {+ if (action === 'candidates') return handleCandidates(req, res, id);+ if (action === 'read') return handleRead(req, res, id);+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ return error(res, 404, 'not_found', 'unknown alpha sub-resource');+});diff --git a/api/cron/reflect-sweep.js b/api/cron/reflect-sweep.jsnew file mode 100644index 000000000..c0ce52b21--- /dev/null+++ b/api/cron/reflect-sweep.js@@ -0,0 +1,99 @@+// GET /api/cron/reflect-sweep — scheduled memory-consolidation pass.+//+// Walks agents with recent activity (new memories or actions) that haven't+// reflected within the debounce window and runs a real reflection pass for each+// (api/_lib/reflection.js). This is the "while you were away" engine: the user+// comes back to find their agent has genuinely consolidated what it saw.+//+// Cost discipline (no silent caps):+// • A cheap SQL pre-filter skips agents with no recent activity or a run in the+// last 30 minutes, so the engine isn't invoked for idle agents.+// • The engine itself re-checks the per-agent daily cap + debounce + minimum+// new-signal threshold and records every skip in agent_reflection_runs.+// • A wall-clock budget bounds the batch; whatever it couldn't reach is logged+// and picked up on the next tick — never silently dropped.++import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { runReflection } from '../_lib/reflection.js';++export const maxDuration = 120;++// How many agents to attempt per tick, and the wall-clock budget. The cron runs+// every 30 min, so a backlog drains over a few ticks rather than in one long run.+const BATCH_LIMIT = Number(process.env.REFLECT_SWEEP_BATCH) || 12;+const TIME_BUDGET_MS = 100_000;++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 (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ const startedAt = Date.now();++ // Pre-filter: agents with activity in the last 36h and no reflection run in+ // the last 30 minutes (the engine's debounce is authoritative; this just+ // avoids waking it for agents that would only be told to wait).+ const candidates = await sql`+ WITH active AS (+ SELECT agent_id FROM agent_memories WHERE created_at > now() - interval '36 hours'+ UNION+ SELECT agent_id FROM agent_actions WHERE created_at > now() - interval '36 hours'+ )+ SELECT a.id, a.name, a.description, a.user_id+ FROM agent_identities a+ JOIN active ac ON ac.agent_id = a.id+ WHERE a.deleted_at IS NULL+ AND NOT EXISTS (+ SELECT 1 FROM agent_reflection_runs r+ WHERE r.agent_id = a.id AND r.created_at > now() - interval '30 minutes'+ )+ ORDER BY a.id+ LIMIT ${BATCH_LIMIT}+ `;++ const summary = { eligible: candidates.length, processed: 0, dreamsCreated: 0, skipped: 0, errors: 0, deferred: 0 };++ for (const agent of candidates) {+ if (Date.now() - startedAt > TIME_BUDGET_MS) {+ summary.deferred = candidates.length - summary.processed;+ console.log(`[reflect-sweep] time budget reached; deferring ${summary.deferred} agents to next tick`);+ break;+ }+ summary.processed++;+ try {+ const result = await runReflection({+ agentId: agent.id,+ userId: agent.user_id,+ trigger: 'cron',+ agent: { name: agent.name, description: agent.description },+ });+ if (result.status === 'ok') summary.dreamsCreated += result.created.length;+ else if (result.status === 'skipped') summary.skipped++;+ else summary.errors++;+ } catch (err) {+ summary.errors++;+ console.error(`[reflect-sweep] agent=${agent.id} failed:`, err?.message);+ }+ }++ summary.elapsedMs = Date.now() - startedAt;+ return json(res, 200, summary);+});diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex 8c552558b..979254af6 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1105,6 +1105,7 @@<div class="edit-sidebar-group"><div class="edit-sidebar-group-title">Brain</div><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="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><button class="edit-tab" data-tab="autopilot" role="tab" aria-selected="false" aria-controls="panel-autopilot" id="tab-autopilot">Autopilot</button></div>@@ -1481,6 +1482,28 @@</div></section>+ <!-- Dreams tab -->+ <section class="edit-panel persona-panel" id="panel-dreams" role="tabpanel" aria-labelledby="tab-dreams" hidden>+ <div class="dreams-head">+ <div>+ <p class="hint" style="margin:0">While you're away, your agent <strong>reflects</strong> — it reads its own memories and actions and consolidates them into higher-order insights. Review each below: accept one and it becomes a real, higher-salience memory; reject it and your agent learns the synthesis was wrong.</p>+ <div class="dreams-meta" id="dreams-meta" aria-live="polite"></div>+ </div>+ <button class="btn-ghost dreams-reflect-btn" id="dreams-reflect-btn" title="Run a reflection pass now">+ <span class="dreams-reflect-label">Reflect now</span>+ </button>+ </div>++ <div id="dreams-list" class="dreams-list" aria-live="polite"><div class="muted">Loading…</div></div>++ <div class="dreams-journal" id="dreams-journal" hidden>+ <button class="dreams-journal-toggle" id="dreams-journal-toggle" aria-expanded="false" aria-controls="dreams-journal-list">+ <span class="dreams-journal-caret" aria-hidden="true">▸</span> Dream journal <span class="muted" id="dreams-journal-count"></span>+ </button>+ <div id="dreams-journal-list" class="dreams-journal-list" hidden></div>+ </div>+ </section>+<!-- Skills tab --><section class="edit-panel persona-panel" id="panel-skills" role="tabpanel" aria-labelledby="tab-skills" hidden><p class="hint">Skills the agent exposes. Built-ins (greet, present-model, validate-model, remember, think) are always available. Add custom skills below.</p>diff --git a/pages/alpha-copilot.html b/pages/alpha-copilot.htmlnew file mode 100644index 000000000..8b2d0292c--- /dev/null+++ b/pages/alpha-copilot.html@@ -0,0 +1,124 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Alpha Co-pilot · three.ws</title>+ <meta+ name="description"+ content="Your agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict out loud through its 3D avatar. The owner can act on it within hard, server-enforced spend limits."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/alpha-copilot" />+ <meta property="og:title" content="Alpha Co-pilot · three.ws" />+ <meta+ property="og:description"+ content="A 3D agent that narrates its own alpha: it reads real launches in character, cites the live signals it used, and acts only within its spend limits. No competitor has a persona, avatar, and wallet fused like this."+ />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Alpha+Co-pilot&d=Your+agent+reads+a+real+launch+in+character+and+speaks+its+verdict+aloud.&p=%2Falpha-copilot" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Alpha Co-pilot · three.ws" />+ <meta name="twitter:description" content="A 3D agent narrates its own alpha — reading real launches in character and acting only within hard spend limits." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Alpha+Co-pilot&d=Your+agent+reads+a+real+launch+in+character+and+speaks+its+verdict+aloud.&p=%2Falpha-copilot" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/alpha-copilot.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/alpha-copilot" />+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Alpha Co-pilot","description":"A 3D AI agent reads a real pump.fun launch in character, grounded in live data, and speaks its verdict aloud — acting only within server-enforced spend limits.","url":"https://three.ws/alpha-copilot","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="ac-shell" aria-labelledby="ac-title">+ <section class="ac-hero">+ <p class="ac-kicker">+ <span class="ac-live-dot" aria-hidden="true"></span>+ In-character alpha · grounded in real pump.fun data+ </p>+ <h1 id="ac-title" class="ac-title">Alpha Co-pilot</h1>+ <p class="ac-sub">+ Pick an agent. It reads a <strong>real</strong> live launch in character — citing the live+ liquidity, holder, and smart-money signals it actually saw — and speaks its verdict aloud+ through its 3D avatar. If you own it, you can act on the call within+ <strong>hard, server-enforced spend limits</strong>. The persona advises; the limits govern; you consent.+ </p>+ <div class="ac-agentpick">+ <label class="ac-field" for="ac-agent-input">+ <span>Agent</span>+ <input type="text" id="ac-agent-input" placeholder="agent id or paste a profile URL" autocomplete="off" spellcheck="false" />+ </label>+ <button type="button" class="ac-btn" id="ac-agent-load">Load agent</button>+ </div>+ </section>++ <div class="ac-grid">+ <!-- The narrator: avatar + spoken verdict -->+ <section class="ac-stage" aria-label="Agent narrator">+ <div class="ac-stage-avatar" id="ac-avatar-host">+ <div class="ac-stage-placeholder" id="ac-avatar-placeholder">Load an agent to begin.</div>+ </div>+ <div class="ac-stage-meta">+ <div class="ac-stage-name" id="ac-agent-name">—</div>+ <div class="ac-stage-role" id="ac-agent-role">Alpha co-pilot</div>+ </div>+ <div class="ac-speak" id="ac-speak" aria-live="polite" hidden>+ <button type="button" class="ac-speak-btn" id="ac-replay" title="Replay aloud" aria-label="Replay aloud">▶</button>+ <p class="ac-speak-line" id="ac-speak-line"></p>+ </div>+ </section>++ <!-- The verdict -->+ <section class="ac-read" aria-label="The read" id="ac-read-panel">+ <div class="ac-read-empty" id="ac-read-empty">+ <p>Choose a live launch and ask your agent for a read. Its verdict, conviction, and the exact signals it used will appear here.</p>+ </div>+ <div class="ac-read-body" id="ac-read-body" hidden></div>+ </section>++ <!-- Live launches -->+ <section class="ac-launches" aria-label="Live launches">+ <header class="ac-launches-head">+ <h2><span class="ac-live-dot" aria-hidden="true"></span> Live launches</h2>+ <button type="button" class="ac-btn ac-btn-ghost" id="ac-refresh" title="Refresh feed">Refresh</button>+ </header>+ <div class="ac-launches-list" id="ac-launches-list" aria-live="polite"></div>+ </section>+ </div>++ <p class="ac-disclaimer">+ This is an agent's opinion grounded in real on-chain data — not financial advice or a guaranteed call.+ Every number it speaks is checked against the live signals shown; fabricated figures are rejected, never voiced.+ Actions execute only through the agent's guarded wallet, clamped to its spend policy and fully audited.+ </p>+ </main>++ <!-- Confirm-to-act drawer (owner only) -->+ <div class="ac-drawer" id="ac-act-drawer" hidden role="dialog" aria-modal="true" aria-labelledby="ac-act-title">+ <div class="ac-modal-backdrop" data-close></div>+ <div class="ac-drawer-card" role="document">+ <button class="ac-modal-x" type="button" data-close aria-label="Close">×</button>+ <h3 id="ac-act-title">Act on this read</h3>+ <div id="ac-act-body"></div>+ </div>+ </div>++ <script type="module" src="/src/alpha-copilot.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/src/agent-wallet-hub/tabs/earn.js b/src/agent-wallet-hub/tabs/earn.jsindex 1726ec2ea..cd2be4d49 100644--- a/src/agent-wallet-hub/tabs/earn.js+++ b/src/agent-wallet-hub/tabs/earn.js@@ -2,7 +2,8 @@* Agent Wallet hub — Earn tab (fully built). Owner-only.** "Your avatar has a job." This is the economy home: what the agent has earned- * (skill sales + tips), the prices that make it money, the bounded allowance ++ * (skill sales + hires from other agents + tips), who its top customers are, the+ * prices that make it money, the bounded allowance +* kill switch that lets it pay other agents safely, and a clean receipts* statement of every dollar in and out. Every number is real — it traces to* agent_custody_events / skill_payment_earnings via GET /api/agents/:id/economy.@@ -97,6 +98,15 @@ const STYLE = `.awh-rcpt-amt.out { color: var(--ink-dim,#888); }.awh-rcpt-amt.pending { color: var(--warn,#fbbf24); }+.awh-cust { margin: 0 0 var(--space-3,12px); }+.awh-cust-h { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .04em; color: var(--ink-dim,#888); margin: 0 0 6px; }+.awh-cust-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }+.awh-cust-row { display: flex; align-items: baseline; gap: var(--space-2,8px); padding: 5px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.05)); }+.awh-cust-row:last-child { border-bottom: none; }+.awh-cust-name { flex: 1 1 auto; min-width: 0; color: var(--ink,#e8e8e8); text-decoration: none; font-size: var(--text-sm,.764rem); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-bottom: 1px dotted transparent; }+.awh-cust-name:hover { color: var(--ink-bright,#fff); border-bottom-color: currentColor; }+.awh-cust-meta { flex: none; color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); }+.awh-cust-usd { flex: none; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); color: var(--success,#4ade80); font-variant-numeric: tabular-nums; }.awh-earn-disc { display: flex; gap: var(--space-2,8px); flex-wrap: wrap; }.awh-earn-skel span { display: block; height: 16px; border-radius: var(--radius-sm,6px); background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; margin-bottom: 10px; }.awh-earn-skel span:nth-child(2){ width: 60%; } .awh-earn-skel span:nth-child(3){ width: 80%; }@@ -127,6 +137,20 @@ function unixSec(iso) {return Number.isFinite(t) ? Math.floor(t / 1000) : 0;}+// Lifetime earnings breakdown across the three real income streams. Only streams+// that actually earned are named, so the sentence reads true for every agent:+// just sales, just hires, or all three. money() output is numeric — safe HTML.+function earnSplit(e) {+ const parts = [];+ if ((e.skill_sales?.lifetime || 0) > 0) parts.push(`<b>${money(e.skill_sales.lifetime)}</b> in skill sales`);+ if ((e.hires?.lifetime || 0) > 0) parts.push(`<b>${money(e.hires.lifetime)}</b> from agents hiring it`);+ if ((e.tips?.lifetime || 0) > 0) parts.push(`<b>${money(e.tips.lifetime)}</b> in tips`);+ if (!parts.length) return `Every dollar in and out shows up below as a real, signed receipt.`;+ if (parts.length === 1) return `From ${parts[0]}.`;+ const last = parts.pop();+ return `From ${parts.join(', ')} and ${last}.`;+}+registerWalletTab({id: 'earn',label: 'Earn',@@ -217,7 +241,7 @@ registerWalletTab({<div class="awh-earn-chip"><b>${escapeHtml(money(e.total.week))}</b><span>7 days</span></div><div class="awh-earn-chip"><b>${escapeHtml(money(e.total.lifetime))}</b><span>All time</span></div></div>- <p class="awh-earn-split">From <b>${escapeHtml(money(e.skill_sales.lifetime))}</b> in skill sales${e.tips.lifetime > 0 ? ` and <b>${escapeHtml(money(e.tips.lifetime))}</b> in tips` : ''}.</p>+ <p class="awh-earn-split">${earnSplit(e)}</p></div>`;animateCount();}@@ -471,7 +495,7 @@ registerWalletTab({const rows = state.econ.receipts || [];if (!rows.length) {h.innerHTML = `<h2 class="awh-card-h">Receipts</h2>- <div class="awh-earn-empty">No money has moved yet. Every payment in and out — skill sales, tips, services your agent pays for — shows up here as a receipt with its on-chain signature.</div>`;+ <div class="awh-earn-empty">No money has moved yet. Every payment in and out — skill sales, hires from other agents, tips, and services your agent pays for — shows up here as a receipt with its on-chain signature.</div>`;return;}const net = ctx.getNetwork?.() || 'mainnet';@@ -479,11 +503,17 @@ registerWalletTab({const inbound = r.direction === 'in';const amt = r.usd != null ? money(r.usd) : (r.sol != null ? `${r.sol.toFixed(4)} SOL` : '—');const pending = r.status && r.status !== 'confirmed' && r.status !== 'ok';- const cp = r.counterparty- ? (looksLikeAddress(r.counterparty)- ? `<a href="${escapeHtml(explorerAddressUrl(r.counterparty, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(r.counterparty, 4, 4))} ↗</a>`- : escapeHtml(shortAddress(r.counterparty, 4, 4)))- : '';+ // An agent counterparty (e.g. another agent that hired this one) links to+ // its real profile by name; an on-chain address links to the explorer; a+ // bare id falls back to a short label.+ let cp = '';+ if (r.counterparty_agent_id) {+ cp = `<a href="/agent/${escapeHtml(r.counterparty_agent_id)}">${escapeHtml(clampName(r.counterparty || 'Agent'))}</a>`;+ } else if (r.counterparty && looksLikeAddress(r.counterparty)) {+ cp = `<a href="${escapeHtml(explorerAddressUrl(r.counterparty, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(r.counterparty, 4, 4))} ↗</a>`;+ } else if (r.counterparty) {+ cp = escapeHtml(shortAddress(r.counterparty, 4, 4));+ }const when = r.created_at ? timeAgo(unixSec(r.created_at)) : '';const sig = r.signature? ` · <a href="${escapeHtml(explorerTxUrl(r.signature, net))}" target="_blank" rel="noopener">tx ↗</a>`@@ -504,12 +534,30 @@ registerWalletTab({function renderDiscover() {const h = host('discover');if (!h) return;+ const customers = state.econ?.customers || [];const peers = state.econ?.peers || [];const net = ctx.getNetwork?.() || 'mainnet';++ // The income edge: agents that have hired this one, ranked by spend. Each+ // links to a real agent profile. This is the owner's "who's my best+ // customer?" — the signal for which skills to price up or promote.+ const customerBlock = customers.length+ ? `<div class="awh-cust">+ <p class="awh-cust-h">Top customers</p>+ <ul class="awh-cust-list">${customers.slice(0, 5).map((c) => `+ <li class="awh-cust-row">+ <a class="awh-cust-name" href="/agent/${escapeHtml(c.agent_id)}" title="${escapeHtml(c.name)}">${escapeHtml(clampName(c.name))}</a>+ <span class="awh-cust-meta">${c.count} hire${c.count === 1 ? '' : 's'}</span>+ <span class="awh-cust-usd">${escapeHtml(money(c.usd))}</span>+ </li>`).join('')}</ul>+ </div>`+ : '';+const peerLine = peers.length? `<p class="awh-earn-split" style="margin-top:0">Your agent has paid ${peers.length} counterpart${peers.length === 1 ? 'y' : 'ies'}: ${peers.slice(0, 4).map((p) => `<a class="awh-earn-link" href="${escapeHtml(explorerAddressUrl(p.address, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(p.address, 4, 4))}</a>`).join(', ')}.</p>`: `<p class="awh-earn-split" style="margin-top:0">Discover agents and x402 services your avatar can hire — the network where agents pay agents.</p>`;h.innerHTML = `<h2 class="awh-card-h">The agent economy</h2>+ ${customerBlock}${peerLine}<div class="awh-earn-disc"><a class="awh-btn awh-btn--primary" href="/economy">Services directory →</a>@@ -628,3 +676,9 @@ registerWalletTab({function looksLikeAddress(s) {return typeof s === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);}++// Keep a display name to a sane length so a long agent name can't break the row.+function clampName(s, max = 28) {+ const v = String(s ?? '').trim();+ return v.length > max ? `${v.slice(0, max - 1)}…` : v;+}diff --git a/src/agents/active-agent.js b/src/agents/active-agent.jsnew file mode 100644index 000000000..ed5227a7f--- /dev/null+++ b/src/agents/active-agent.js@@ -0,0 +1,138 @@+// The single canonical "my agent" — one resolved agent record shared by every+// Living-Agents surface, persisted across reloads, and broadcast on change via+// the agent bus. Defined by the Foundation task; treated as a FIXED API by+// every other feature.++import { apiFetch } from '../api.js';+import { agentBus } from './agent-bus.js';++const STORAGE_KEY = 'threews:active-agent';++let _record = null; // last resolved agent record (or null)+let _resolving = null; // in-flight resolve promise (deduped)+const _listeners = new Set();++function readStoredId() {+ try {+ return localStorage.getItem(STORAGE_KEY) || null;+ } catch {+ return null;+ }+}++function writeStoredId(id) {+ try {+ if (id) localStorage.setItem(STORAGE_KEY, id);+ else localStorage.removeItem(STORAGE_KEY);+ } catch {+ /* storage unavailable (private mode) — in-memory state still works */+ }+}++function notify() {+ for (const cb of _listeners) {+ try {+ cb(_record);+ } catch (err) {+ console.error('[active-agent] listener threw', err);+ }+ }+ agentBus.emit('agent:changed', {+ agentId: _record?.id || null,+ agent: _record,+ ts: _record?.updated_at || new Date().toISOString(),+ });+}++async function resolveById(id) {+ if (!id) return null;+ const r = await apiFetch(`/api/agents/${id}`, { credentials: 'include' });+ if (!r.ok) return null;+ const j = await r.json().catch(() => ({}));+ return j.agent || null;+}++/**+ * Resolve the active agent record. Reads the stored id, fetches it once, and+ * caches. Returns null when no agent is selected or the stored one is gone.+ */+export async function getActiveAgent({ force = false } = {}) {+ if (_record && !force) return _record;+ if (_resolving && !force) return _resolving;+ const id = readStoredId();+ if (!id) return null;+ _resolving = resolveById(id)+ .then((agent) => {+ _record = agent;+ if (!agent) writeStoredId(null); // stale id — drop it+ return agent;+ })+ .finally(() => {+ _resolving = null;+ });+ return _resolving;+}++/** Current cached record without triggering a fetch. */+export function peekActiveAgent() {+ return _record;+}++export function activeAgentId() {+ return _record?.id || readStoredId();+}++/**+ * Set the active agent by id, persist, resolve, and broadcast. Pass null to+ * clear. Returns the resolved record (or null).+ */+export async function setActiveAgent(id) {+ if (!id) {+ _record = null;+ writeStoredId(null);+ notify();+ return null;+ }+ writeStoredId(id);+ const agent = await resolveById(id);+ _record = agent;+ if (!agent) writeStoredId(null);+ notify();+ return agent;+}++/**+ * Replace the cached record in place (e.g. after an owner edits their agent) and+ * broadcast. The id must match the active agent, or this is a no-op.+ */+export function updateActiveAgent(patch) {+ if (!patch || !_record) return _record;+ if (patch.id && patch.id !== _record.id) return _record;+ _record = { ..._record, ...patch };+ notify();+ return _record;+}++/** Subscribe to active-agent changes. Returns an unsubscribe function. */+export function onActiveAgentChange(cb) {+ _listeners.add(cb);+ return () => _listeners.delete(cb);+}++// Cross-tab sync: a selection made in one tab reflects in the others.+if (typeof window !== 'undefined') {+ window.addEventListener('storage', (e) => {+ if (e.key !== STORAGE_KEY) return;+ const id = e.newValue || null;+ if (id === (_record?.id || null)) return;+ if (!id) {+ _record = null;+ notify();+ } else {+ resolveById(id).then((agent) => {+ _record = agent;+ notify();+ });+ }+ });+}diff --git a/src/agents/agent-bus.d.ts b/src/agents/agent-bus.d.tsnew file mode 100644index 000000000..97f13982b--- /dev/null+++ b/src/agents/agent-bus.d.ts@@ -0,0 +1,147 @@+// Type contract for the Living-Agents bus. This file is documentation-as-types:+// it gives tasks 02–08 autocomplete on every event payload without changing the+// runtime (the bus is plain JS). Each payload extends BaseEvent, so `agentId`+// and `ts` are always present.+//+// `ts` is an ISO-8601 string sourced from the server (a row's `created_at`, a+// chat `done` event's recall timestamp, etc.) or passed by the caller; the bus+// only stamps a fallback when none is provided.++export type Iso = string;+export type Uuid = string;++export interface BaseEvent {+ /** The agent this event is about. Null only for a signed-out guest avatar. */+ agentId: Uuid | null;+ /** ISO-8601 timestamp, server-sourced when available. */+ ts: Iso;+}++export type MemoryTier = 'working' | 'recall' | 'archival';+export type MemoryType = 'user' | 'feedback' | 'project' | 'reference';++export interface MemoryRecord {+ id: Uuid;+ type: MemoryType;+ content: string;+ tags: string[];+ salience: number;+ tier: MemoryTier;+ pinned: boolean;+ isPublic: boolean;+ createdAt: number;+ updatedAt: number;+}++/** A memory was created (manual add, import, or a reflection pass). */+export interface MemoryAddedEvent extends BaseEvent {+ memory: MemoryRecord;+}++/** A memory's content / visibility / salience changed. */+export interface MemoryUpdatedEvent extends BaseEvent {+ memory: MemoryRecord;+}++/** A memory was deleted/forgotten. Only the id is guaranteed. */+export interface MemoryForgottenEvent extends BaseEvent {+ memoryId: Uuid;+}++/** One memory the server actually injected into a live chat's context. */+export interface RecalledMemory {+ id: Uuid;+ type: MemoryType;+ tier: MemoryTier;+ salience: number;+ /** Truncated content for display — never the full row. */+ snippet: string;+ /** How it surfaced: pinned/working context, semantic, or lexical match. */+ match: 'context' | 'semantic' | 'lexical';+}++/** Memories were injected into a chat's context by the server (real recall). */+export interface MemoryRecalledEvent extends BaseEvent {+ memories: RecalledMemory[];+ /** The user message that triggered the recall, if the surface knows it. */+ query?: string;+ /** Whether semantic embeddings (vs lexical fallback) drove the ranking. */+ semantic?: boolean;+}++/** Persona / trait / system-prompt change landed (Brain Studio). */+export interface BrainUpdatedEvent extends BaseEvent {+ personaPrompt?: string;+ toneTags?: string[];+ /** Free-form description of what changed, for the HUD chip. */+ change?: string;+}++/** The agent's emotional state changed (Emotion engine). */+export interface MoodChangedEvent extends BaseEvent {+ mood: string;+ valence?: number;+ arousal?: number;+}++/** A higher-order insight consolidated during idle time (Dreams). */+export interface DreamCreatedEvent extends BaseEvent {+ dreamId: Uuid;+ title?: string;+ insight: string;+ sourceMemoryIds?: Uuid[];+}++/** The agent took an autonomous action (Autopilot: alert/wallet/etc.). */+export interface ActionTakenEvent extends BaseEvent {+ actionId?: Uuid;+ kind: string;+ summary: string;+ /** Memories that motivated the action — the explainability trail. */+ motivatedBy?: Uuid[];+}++/** The active "my agent" changed. */+export interface AgentChangedEvent extends BaseEvent {+ agent: Record<string, unknown> | null;+}++export interface AgentEventMap {+ 'memory:added': MemoryAddedEvent;+ 'memory:recalled': MemoryRecalledEvent;+ 'memory:updated': MemoryUpdatedEvent;+ 'memory:forgotten': MemoryForgottenEvent;+ 'brain:updated': BrainUpdatedEvent;+ 'mood:changed': MoodChangedEvent;+ 'dream:created': DreamCreatedEvent;+ 'action:taken': ActionTakenEvent;+ 'agent:changed': AgentChangedEvent;+}++export type AgentEventType = keyof AgentEventMap;++export interface OnOptions {+ replay?: boolean | 'all';+ throttleMs?: number;+ signal?: AbortSignal;+}++export interface AgentBus {+ emit<T extends AgentEventType>(type: T, detail: AgentEventMap[T]): AgentEventMap[T];+ on<T extends AgentEventType>(+ type: T,+ handler: (payload: AgentEventMap[T], type?: T) => void,+ opts?: OnOptions,+ ): () => void;+ on(type: '*', handler: (payload: BaseEvent, type: AgentEventType) => void, opts?: OnOptions): () => void;+ once<T extends AgentEventType>(type: T, handler: (payload: AgentEventMap[T], type?: T) => void): () => void;+ last<T extends AgentEventType>(type: T): AgentEventMap[T] | null;+ backlog<T extends AgentEventType>(type: T): AgentEventMap[T][];+ reset(): void;+}++export declare const agentBus: AgentBus;+export declare const AGENT_EVENTS: readonly AgentEventType[];+export declare const WILDCARD: '*';+export declare const EVENTS: Record<string, AgentEventType>;+export default agentBus;diff --git a/src/agents/agent-bus.js b/src/agents/agent-bus.jsnew file mode 100644index 000000000..f9afc17c4--- /dev/null+++ b/src/agents/agent-bus.js@@ -0,0 +1,291 @@+// The Living-Agents event bus — a typed pub/sub singleton every client surface+// subscribes to so the agent feels alive everywhere without each page knowing+// about every feature. The HUD shows a "recalled" chip on `memory:recalled`;+// the Mind Palace animates a node on `memory:added`; the avatar re-expresses on+// `mood:changed`; the Companion re-greets on `brain:updated`.+//+// Defined by the Foundation task and treated as a FIXED API by every other+// Living-Agents feature. Each event carries `{ agentId, ...payload, ts }` where+// `ts` is an ISO string sourced from the server response (or passed by the+// caller) — never wall-clock invented at emit time except as a last-resort+// fallback, so cross-surface ordering stays honest.+//+// Why this is a nervous system and not a bare EventEmitter:+// • Replay — a surface that mounts late (the Mind Palace opened mid-session)+// can ask for the recent backlog and catch up instantly, so liveness never+// depends on being mounted at emit time.+// • Backpressure / coalescing — a burst of `memory:added` (bulk import, a+// reflection pass) can be throttled per-subscriber so a heavy UI re-renders+// at most once per window instead of thrashing.+// • Wildcard tap — `on('*', …)` sees every event; the basis of the debug+// overlay and any cross-feature instrumentation.+// • Cross-context safe — no DOM/`window` access at import time, so it loads+// cleanly under Node (tests) and in every browser context, and survives HMR+// + duplicate module graphs via a single global instance.+//+// See agent-bus.d.ts for the full per-event payload typedefs (autocomplete for+// tasks 02–08).++export const AGENT_EVENTS = Object.freeze([+ 'memory:added',+ 'memory:recalled',+ 'memory:updated',+ 'memory:forgotten',+ 'brain:updated',+ 'mood:changed',+ 'dream:created',+ 'action:taken',+ 'agent:changed',+]);++/**+ * Ergonomic, autocompleting alias for the event names so callers can write+ * `EVENTS.MEMORY_RECALLED` instead of a bare string and have a rename caught by+ * tooling. The string values ARE the contract — both forms interoperate.+ * @readonly+ */+export const EVENTS = Object.freeze({+ MEMORY_ADDED: 'memory:added',+ MEMORY_RECALLED: 'memory:recalled',+ MEMORY_UPDATED: 'memory:updated',+ MEMORY_FORGOTTEN: 'memory:forgotten',+ BRAIN_UPDATED: 'brain:updated',+ MOOD_CHANGED: 'mood:changed',+ DREAM_CREATED: 'dream:created',+ ACTION_TAKEN: 'action:taken',+ AGENT_CHANGED: 'agent:changed',+});++/** Wildcard subscription key — receives `(payload, type)` for every event. */+export const WILDCARD = '*';++const EVENT_SET = new Set(AGENT_EVENTS);+// How many recent events to retain per type for `{ replay: 'all' }` and the+// debug overlay's history. Deep enough to rebuild a late-mounting surface's+// view, shallow enough to stay memory-cheap on a long session.+const REPLAY_DEPTH = 50;++/**+ * Leading+trailing throttle. The first call fires immediately; calls inside the+ * window collapse into one trailing call carrying the most recent payload. This+ * is the backpressure primitive a burst of `memory:added` rides on so a+ * subscriber re-renders at most once per `ms`.+ */+function throttle(fn, ms) {+ let last = 0;+ let timer = null;+ let pending = null;+ const clock = () =>+ typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();+ const invoke = (args) => {+ last = clock();+ fn(...args);+ };+ const wrapped = (...args) => {+ const elapsed = clock() - last;+ if (elapsed >= ms) {+ invoke(args);+ } else {+ pending = args;+ if (!timer) {+ timer = setTimeout(() => {+ timer = null;+ if (pending) {+ const a = pending;+ pending = null;+ invoke(a);+ }+ }, ms - elapsed);+ }+ }+ };+ wrapped.cancel = () => {+ if (timer) clearTimeout(timer);+ timer = null;+ pending = null;+ };+ return wrapped;+}++class AgentBus {+ constructor() {+ /** @type {Map<string, Set<Function>>} typed subscribers */+ this._typed = new Map();+ /** @type {Set<Function>} wildcard subscribers (see every event) */+ this._wild = new Set();+ // Most recent payload per event — late subscribers sync to current state+ // without waiting for the next emit (e.g. a HUD mounted after+ // `brain:updated` already fired).+ this._last = new Map();+ // Bounded per-type history for full backlog replay.+ this._log = new Map();+ }++ _assert(type) {+ if (!EVENT_SET.has(type)) {+ throw new Error(`[agent-bus] unknown event "${type}". Known: ${AGENT_EVENTS.join(', ')}`);+ }+ }++ /**+ * Emit an event. `detail` must carry `agentId`; `ts` is normalised to an ISO+ * string (server-provided when available, else stamped at emit as a fallback).+ * Subscribers are isolated: one that throws is logged and never blocks the+ * others or the emitter. Returns the frozen, delivered payload.+ */+ emit(type, detail = {}) {+ this._assert(type);+ const payload = { ...detail };+ if (!payload.ts) payload.ts = new Date().toISOString();+ Object.freeze(payload);+ this._last.set(type, payload);+ this._record(type, payload);++ // Snapshot the sets so a subscriber that (un)subscribes during dispatch+ // can't mutate what we're iterating.+ const set = this._typed.get(type);+ if (set) for (const h of [...set]) this._safe(h, payload, type, set);+ if (this._wild.size) for (const h of [...this._wild]) this._safe(h, payload, type, this._wild);+ return payload;+ }++ /**+ * Subscribe to an event (or {@link WILDCARD} for all). Returns an unsubscribe+ * function.+ *+ * @param {string} type - An {@link AGENT_EVENTS} value, or `'*'`.+ * @param {(payload:Object, type?:string)=>void} handler+ * @param {Object} [opts]+ * @param {boolean|'all'} [opts.replay] - `true` immediately delivers the last+ * payload (if any); `'all'` delivers the retained backlog oldest→newest so a+ * late-mounting surface fully catches up. Ignored for the wildcard.+ * @param {number} [opts.throttleMs] - Coalesce bursts: deliver at most once+ * per this many ms (leading + trailing). Backpressure for high-rate events.+ * @param {AbortSignal} [opts.signal] - Auto-unsubscribe when the signal aborts.+ * @returns {() => void} unsubscribe+ */+ on(type, handler, opts = {}) {+ if (typeof handler !== 'function') {+ throw new TypeError('[agent-bus] on(type, handler) requires a function');+ }+ const wildcard = type === WILDCARD;+ if (!wildcard) this._assert(type);++ const wrapped = opts.throttleMs ? throttle(handler, opts.throttleMs) : handler;+ const bucket = wildcard ? this._wild : this._getTyped(type);+ bucket.add(wrapped);++ const off = () => {+ bucket.delete(wrapped);+ if (!wildcard && !bucket.size) this._typed.delete(type);+ if (wrapped.cancel) wrapped.cancel();+ };++ if (opts.signal) {+ if (opts.signal.aborted) {+ off();+ return () => {};+ }+ opts.signal.addEventListener('abort', off, { once: true });+ }++ if (!wildcard && opts.replay) {+ if (opts.replay === 'all') {+ for (const p of this._log.get(type) || []) this._safe(wrapped, p, type, bucket);+ } else if (this._last.has(type)) {+ this._safe(wrapped, this._last.get(type), type, bucket);+ }+ }+ return off;+ }++ /** Subscribe for a single emission, then auto-unsubscribe. */+ once(type, handler) {+ const off = this.on(type, (payload, t) => {+ off();+ handler(payload, t);+ });+ return off;+ }++ /** Last payload seen for an event, or null. */+ last(type) {+ this._assert(type);+ return this._last.get(type) || null;+ }++ /** Retained backlog for an event (oldest→newest), without subscribing. */+ backlog(type) {+ this._assert(type);+ return [...(this._log.get(type) || [])];+ }++ /** Drop all subscribers and history. Primarily for tests. */+ reset() {+ for (const set of this._typed.values()) {+ for (const h of set) if (h.cancel) h.cancel();+ }+ for (const h of this._wild) if (h.cancel) h.cancel();+ this._typed.clear();+ this._wild.clear();+ this._last.clear();+ this._log.clear();+ }++ _getTyped(type) {+ let set = this._typed.get(type);+ if (!set) {+ set = new Set();+ this._typed.set(type, set);+ }+ return set;+ }++ _record(type, payload) {+ let log = this._log.get(type);+ if (!log) {+ log = [];+ this._log.set(type, log);+ }+ log.push(payload);+ if (log.length > REPLAY_DEPTH) log.shift();+ }++ _safe(handler, payload, type, owner) {+ // A handler removed earlier in this same dispatch pass must not fire.+ if (owner && !owner.has(handler)) return;+ try {+ handler(payload, type);+ } catch (err) {+ console.error(`[agent-bus] subscriber for "${type}" threw`, err);+ }+ }+}++// Singleton across the whole app, surviving HMR and duplicate module graphs by+// stashing on the global. Every `import { agentBus }` resolves to one instance.+const GLOBAL_KEY = '__threewsAgentBus';+export const agentBus =+ (typeof globalThis !== 'undefined' && globalThis[GLOBAL_KEY]) || new AgentBus();+if (typeof globalThis !== 'undefined' && !globalThis[GLOBAL_KEY]) {+ globalThis[GLOBAL_KEY] = agentBus;+}++// Browser-only conveniences. The debug overlay is a dev tool, not product UI:+// it loads only when the operator opts in with ?agentbus=1. The dynamic import+// keeps it out of every page's bundle and out of Node test runs.+if (typeof window !== 'undefined') {+ window.__agentBus = agentBus;+ try {+ const flag = new URLSearchParams(window.location.search).get('agentbus');+ if (flag === '1' || flag === 'true') {+ import('./agent-bus-debug.js')+ .then((m) => m.mountAgentBusDebug?.())+ .catch(() => {});+ }+ } catch {+ /* location unavailable (sandboxed iframe) — overlay simply doesn't mount */+ }+}++export default agentBus;diff --git a/src/agents/persona-compile.js b/src/agents/persona-compile.jsnew file mode 100644index 000000000..3e5bcb23f--- /dev/null+++ b/src/agents/persona-compile.js@@ -0,0 +1,263 @@+// Persona trait model + deterministic compiler.+//+// This is the SINGLE source of truth for how editable personality dimensions+// become a real `persona_prompt`. It is imported by BOTH the browser (the Brain+// Studio live editor, src/brain-studio.js) and the server (the persona save+// endpoint, api/agents/_id/persona.js) so the candidate the user previews is+// byte-for-byte the prompt that gets stored and signed — no drift between+// "what I heard in preview" and "what my agent became".+//+// Pure ESM. No DOM, no Node, no imports — runs anywhere.++// Each trait is a continuous 0..1 dimension. The compiler maps the value to one+// of three descriptive bands (low / mid / high). The mid band is deliberately+// understated — a slider left at the centre should read as "no strong opinion"+// and contribute a light, neutral clause rather than noise.+export const PERSONA_TRAITS = [+ {+ key: 'warmth',+ label: 'Warmth',+ low: 'Clinical',+ high: 'Warm',+ hint: 'How emotionally present and caring the agent feels.',+ bands: [+ 'Keep an even, professional distance — lead with substance, not sentiment.',+ 'Be courteous and human, neither cold nor effusive.',+ 'Be warm and genuinely caring; let real empathy show in how you address people.',+ ],+ },+ {+ key: 'formality',+ label: 'Formality',+ low: 'Casual',+ high: 'Formal',+ hint: 'Register, from relaxed and conversational to precise and buttoned-up.',+ bands: [+ 'Speak casually, like a sharp friend — contractions, plain words, no stiffness.',+ 'Keep a balanced register: clear and polished without being stiff.',+ 'Maintain a formal, polished register with precise, well-structured language.',+ ],+ },+ {+ key: 'verbosity',+ label: 'Verbosity',+ low: 'Terse',+ high: 'Elaborate',+ hint: 'How much you say — clipped and economical vs. rich and expansive.',+ bands: [+ 'Be terse. Answer in as few words as the question honestly allows; cut filler.',+ 'Be appropriately concise — enough detail to be useful, no padding.',+ 'Be expansive and thorough; give context, examples, and the reasoning behind answers.',+ ],+ },+ {+ key: 'humor',+ label: 'Humor',+ low: 'Serious',+ high: 'Playful',+ hint: 'How much wit and levity colours your delivery.',+ bands: [+ 'Stay earnest and focused; humour is rare and only when it genuinely helps.',+ 'Allow occasional light wit, but never at the cost of clarity.',+ 'Be playful and quick-witted; a well-placed joke or vivid turn of phrase is welcome.',+ ],+ },+ {+ key: 'proactivity',+ label: 'Proactivity',+ low: 'Reactive',+ high: 'Proactive',+ hint: 'Whether you wait to be asked or take initiative.',+ bands: [+ 'Answer exactly what is asked and wait for direction before going further.',+ 'Answer the question, then offer one useful next step when it clearly helps.',+ 'Take initiative: anticipate needs, surface risks unprompted, and suggest the next move.',+ ],+ },+ {+ key: 'riskTolerance',+ label: 'Risk appetite',+ low: 'Cautious',+ high: 'Bold',+ hint: 'How decisively you commit to a recommendation under uncertainty.',+ bands: [+ 'Be cautious: hedge appropriately, flag uncertainty, and prefer the safe option.',+ 'Be measured: give a clear recommendation while naming the key trade-offs.',+ 'Be bold: take a clear, confident stance and commit to a recommendation.',+ ],+ },+ {+ key: 'directness',+ label: 'Directness',+ low: 'Diplomatic',+ high: 'Blunt',+ hint: 'How softened or unvarnished your feedback is.',+ bands: [+ 'Be diplomatic — soften hard truths, lead with the positive, and frame gently.',+ 'Be straightforward and tactful in equal measure.',+ 'Be blunt and unvarnished; say the hard thing plainly without cushioning.',+ ],+ },+];++export const PERSONA_TRAIT_KEYS = PERSONA_TRAITS.map((t) => t.key);+export const DEFAULT_TRAIT_VALUE = 0.5;++const clamp01 = (n) => {+ const v = Number(n);+ if (!Number.isFinite(v)) return DEFAULT_TRAIT_VALUE;+ return v < 0 ? 0 : v > 1 ? 1 : v;+};++// Band index for a 0..1 value: 0 = low, 1 = mid, 2 = high.+export function bandIndex(value) {+ const v = clamp01(value);+ if (v < 0.34) return 0;+ if (v > 0.66) return 2;+ return 1;+}++export function defaultTraitValues() {+ const out = {};+ for (const t of PERSONA_TRAITS) out[t.key] = DEFAULT_TRAIT_VALUE;+ return out;+}++// Coerce arbitrary input into a clean {key: 0..1} map over the known traits.+// Unknown keys are dropped; missing keys default to the mid value.+export function clampTraits(traits) {+ const out = {};+ const src = traits && typeof traits === 'object' ? traits : {};+ for (const t of PERSONA_TRAITS) {+ out[t.key] = src[t.key] == null ? DEFAULT_TRAIT_VALUE : clamp01(src[t.key]);+ }+ return out;+}++// A one-word register label for a trait at a given value (used on chips / a11y).+export function describeTrait(key, value) {+ const trait = PERSONA_TRAITS.find((t) => t.key === key);+ if (!trait) return '';+ const band = bandIndex(value);+ if (band === 0) return trait.low;+ if (band === 2) return trait.high;+ return 'Balanced';+}++function clean(str) {+ return typeof str === 'string' ? str.replace(/\s+/g, ' ').trim() : '';+}++function sanitizeTags(tags) {+ if (!Array.isArray(tags)) return [];+ const seen = new Set();+ const out = [];+ for (const raw of tags) {+ const t = clean(raw).slice(0, 40);+ if (!t) continue;+ const key = t.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(t);+ if (out.length >= 12) break;+ }+ return out;+}++function sanitizeVocab(vocab) {+ if (!Array.isArray(vocab)) return [];+ const seen = new Set();+ const out = [];+ for (const raw of vocab) {+ const v = clean(raw).slice(0, 120);+ if (!v) continue;+ const key = v.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(v);+ if (out.length >= 10) break;+ }+ return out;+}++// Length guidance is derived from verbosity so the directive and the actual+// answer length agree.+function lengthGuidance(verbosity) {+ const band = bandIndex(verbosity);+ if (band === 0) return 'Default to one to three sentences unless more is explicitly requested.';+ if (band === 2) return 'Take the space you need to be genuinely thorough.';+ return 'Keep answers focused and proportional to the question.';+}++/**+ * Compile editable personality into a real system prompt.+ *+ * @param {object} input+ * @param {string} [input.name] Agent display name.+ * @param {string} [input.description] Short role/description (the "what").+ * @param {string} [input.base] A base persona paragraph (e.g. the output+ * of the extraction interview) that the trait+ * directives refine. Optional.+ * @param {object} [input.traits] {key: 0..1} over PERSONA_TRAIT_KEYS.+ * @param {string[]} [input.toneTags] Tone descriptors.+ * @param {string[]} [input.vocabulary] Characteristic phrases.+ * @returns {string} A system prompt beginning with "You are …".+ */+export function compilePersona(input = {}) {+ const name = clean(input.name) || 'this agent';+ const description = clean(input.description);+ const base = typeof input.base === 'string' ? input.base.trim() : '';+ const traits = clampTraits(input.traits);+ const toneTags = sanitizeTags(input.toneTags);+ const vocabulary = sanitizeVocab(input.vocabulary);++ const lines = [];++ // Opening — who the agent is.+ let opener = `You are ${name}`;+ if (description) opener += `, ${description.replace(/\.$/, '')}`;+ opener += '.';+ lines.push(opener);++ // Base persona (extraction interview output, or freeform), woven in verbatim+ // so a hand-authored voice survives the trait layer on top of it.+ if (base) {+ lines.push('', base);+ }++ // Personality directives — one clause per trait, in declarative second person.+ lines.push('', 'How you communicate:');+ for (const trait of PERSONA_TRAITS) {+ lines.push(`- ${trait.bands[bandIndex(traits[trait.key])]}`);+ }++ if (toneTags.length) {+ lines.push('', `Your tone is ${toneTags.join(', ')}.`);+ }++ if (vocabulary.length) {+ const quoted = vocabulary.map((v) => `“${v}”`).join('; ');+ lines.push(+ `Characteristic phrasing you naturally reach for: ${quoted}. Use it sparingly and only where it fits — never force it.`,+ );+ }++ lines.push('', `Stay in character at all times. ${lengthGuidance(traits.verbosity)}`);++ return lines.join('\n');+}++// A compact human-readable summary of the register, for UI subtitles and the+// shareable "personality DNA" card. Returns e.g. "Warm · Casual · Playful".+export function registerSummary(traits) {+ const t = clampTraits(traits);+ const parts = [];+ for (const trait of PERSONA_TRAITS) {+ if (bandIndex(t[trait.key]) === 1) continue; // skip balanced dims+ parts.push(describeTrait(trait.key, t[trait.key]));+ }+ if (!parts.length) return 'Balanced across every dimension';+ return parts.join(' · ');+}++export { sanitizeTags as sanitizeToneTags, sanitizeVocab as sanitizeVocabulary };diff --git a/src/agents/persona-compile.test.js b/src/agents/persona-compile.test.jsnew file mode 100644index 000000000..298136917--- /dev/null+++ b/src/agents/persona-compile.test.js@@ -0,0 +1,136 @@+import { describe, it, expect } from 'vitest';+import {+ PERSONA_TRAITS,+ PERSONA_TRAIT_KEYS,+ DEFAULT_TRAIT_VALUE,+ bandIndex,+ defaultTraitValues,+ clampTraits,+ describeTrait,+ compilePersona,+ registerSummary,+ sanitizeToneTags,+ sanitizeVocabulary,+} from './persona-compile.js';++describe('persona trait model', () => {+ it('exposes seven editable dimensions with three bands each', () => {+ expect(PERSONA_TRAITS).toHaveLength(7);+ expect(PERSONA_TRAIT_KEYS).toContain('warmth');+ for (const t of PERSONA_TRAITS) {+ expect(t.bands).toHaveLength(3);+ expect(typeof t.label).toBe('string');+ }+ });++ it('defaults every trait to the mid value', () => {+ const d = defaultTraitValues();+ expect(Object.keys(d).sort()).toEqual([...PERSONA_TRAIT_KEYS].sort());+ for (const v of Object.values(d)) expect(v).toBe(DEFAULT_TRAIT_VALUE);+ });++ it('bands split low / mid / high', () => {+ expect(bandIndex(0)).toBe(0);+ expect(bandIndex(0.2)).toBe(0);+ expect(bandIndex(0.5)).toBe(1);+ expect(bandIndex(0.9)).toBe(2);+ expect(bandIndex(1)).toBe(2);+ });++ it('clamps out-of-range and unknown trait input', () => {+ const c = clampTraits({ warmth: 5, formality: -3, bogus: 0.4 });+ expect(c.warmth).toBe(1);+ expect(c.formality).toBe(0);+ expect(c).not.toHaveProperty('bogus');+ expect(c.humor).toBe(DEFAULT_TRAIT_VALUE); // missing → default+ });++ it('handles non-finite and missing input gracefully', () => {+ const c = clampTraits({ warmth: NaN, formality: 'x', verbosity: undefined });+ expect(c.warmth).toBe(DEFAULT_TRAIT_VALUE);+ expect(c.formality).toBe(DEFAULT_TRAIT_VALUE);+ expect(clampTraits(null).humor).toBe(DEFAULT_TRAIT_VALUE);+ });++ it('describes a trait by band', () => {+ expect(describeTrait('warmth', 0.9)).toBe('Warm');+ expect(describeTrait('warmth', 0.1)).toBe('Clinical');+ expect(describeTrait('warmth', 0.5)).toBe('Balanced');+ expect(describeTrait('nope', 0.5)).toBe('');+ });+});++describe('compilePersona', () => {+ it('produces a system prompt that starts with "You are"', () => {+ const p = compilePersona({ name: 'Aria', description: 'a research assistant' });+ expect(p.startsWith('You are Aria, a research assistant.')).toBe(true);+ expect(p).toContain('How you communicate:');+ });++ it('is deterministic — same input yields identical output', () => {+ const input = {+ name: 'Aria',+ traits: { warmth: 0.9, humor: 0.8 },+ toneTags: ['warm', 'witty'],+ vocabulary: ['let’s dig in'],+ };+ expect(compilePersona(input)).toBe(compilePersona(input));+ });++ it('changes the prompt when a trait band changes', () => {+ const cold = compilePersona({ name: 'X', traits: { warmth: 0.1 } });+ const warm = compilePersona({ name: 'X', traits: { warmth: 0.95 } });+ expect(cold).not.toBe(warm);+ expect(warm).toContain('genuinely caring');+ expect(cold).toContain('even, professional distance');+ });++ it('weaves a base persona paragraph in verbatim', () => {+ const base = 'You speak like a seasoned trader who has seen three cycles.';+ const p = compilePersona({ name: 'X', base });+ expect(p).toContain(base);+ });++ it('includes tone tags and characteristic phrasing', () => {+ const p = compilePersona({+ name: 'X',+ toneTags: ['punchy', 'candid'],+ vocabulary: ['ship it', 'no fluff'],+ });+ expect(p).toContain('Your tone is punchy, candid.');+ expect(p).toContain('“ship it”');+ });++ it('ties answer-length guidance to verbosity', () => {+ expect(compilePersona({ name: 'X', traits: { verbosity: 0.05 } })).toContain(+ 'one to three sentences',+ );+ expect(compilePersona({ name: 'X', traits: { verbosity: 0.95 } })).toContain(+ 'genuinely thorough',+ );+ });+});++describe('sanitizers', () => {+ it('dedupes and caps tone tags', () => {+ const tags = sanitizeToneTags(['Warm', 'warm', ' witty ', '', 123, 'a'.repeat(100)]);+ expect(tags).toContain('Warm');+ expect(tags.filter((t) => t.toLowerCase() === 'warm')).toHaveLength(1);+ expect(tags.every((t) => t.length <= 40)).toBe(true);+ });++ it('dedupes and caps vocabulary', () => {+ const v = sanitizeVocabulary(Array.from({ length: 30 }, (_, i) => `phrase ${i % 3}`));+ expect(v.length).toBeLessThanOrEqual(10);+ expect(new Set(v.map((s) => s.toLowerCase())).size).toBe(v.length);+ });+});++describe('registerSummary', () => {+ it('summarises only the non-balanced dimensions', () => {+ expect(registerSummary({ warmth: 0.9, humor: 0.1 })).toBe('Warm · Serious');+ });+ it('reports fully-balanced personas', () => {+ expect(registerSummary(defaultTraitValues())).toBe('Balanced across every dimension');+ });+});diff --git a/src/studio/money/trading-compile.js b/src/studio/money/trading-compile.jsnew file mode 100644index 000000000..96ea6432d--- /dev/null+++ b/src/studio/money/trading-compile.js@@ -0,0 +1,215 @@+/**+ * Trading Brain — rule compiler (P4)+ * ==================================+ * The Trading Brain is a *visual* rule: connected blocks the user draws (trigger+ * → filters → buy → exits → risk). This module is the single, framework-agnostic+ * source of truth that turns that visual rule into the two real backend shapes —+ * never a mock, never a paper config:+ *+ * compileRuleToConfig(rule) → the nested Strategy Object config the live+ * engine validates + runs (api/_lib/strategy-schema.js,+ * POST /api/strategies, the cron fan-out runner).+ * configToSniperStrategy(config) → the flat sniper shape the honest historical+ * backtester replays (POST /api/sniper/backtest).+ *+ * It also renders the rule to plain English (ruleToEnglish) so a trader always+ * sees, in their own words, exactly what their agent will do before it does it.+ *+ * Pure + dependency-free so it runs identically in the browser (Trading Brain UI)+ * and in node (unit tests) — the same compile the studio shows is the one the+ * server enforces.+ */++export const LAMPORTS_PER_SOL = 1_000_000_000;++/** The shape persisted at meta.studio.trading.rule — the visual rule's data. */+export const DEFAULT_RULE = Object.freeze({+ name: 'My sniper',+ network: 'mainnet',+ trigger: { type: 'new_launch', max_age_minutes: 30 },+ filters: {+ min_market_cap_usd: null,+ max_market_cap_usd: 60000,+ min_liquidity_sol: null,+ require_socials: true,+ max_creator_launches: null,+ min_creator_graduated: null,+ require_sol_quote: true,+ },+ buy: { amount_sol: 0.1, max_slippage_bps: 500 },+ exits: { take_profit_pct: 100, stop_loss_pct: 40, trailing_stop_pct: null, max_hold_minutes: null },+ risk: { max_concurrent_positions: 3, cooldown_minutes: 0 },+});++function num(v) {+ if (v === '' || v === null || v === undefined) return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}++/** Deep-clone the default rule (so callers never mutate the frozen template). */+export function emptyRule() {+ return structuredClone(DEFAULT_RULE);+}++/**+ * Merge a stored/partial rule over the defaults so every block is always present+ * even if an older saved rule predates a field. Never mutates the input.+ */+export function normalizeRule(raw) {+ const r = raw && typeof raw === 'object' ? raw : {};+ const d = DEFAULT_RULE;+ return {+ name: typeof r.name === 'string' && r.name.trim() ? r.name.trim().slice(0, 60) : d.name,+ network: r.network === 'devnet' ? 'devnet' : 'mainnet',+ trigger: {+ type: 'new_launch',+ max_age_minutes: num(r.trigger?.max_age_minutes) ?? d.trigger.max_age_minutes,+ },+ filters: {+ min_market_cap_usd: num(r.filters?.min_market_cap_usd),+ max_market_cap_usd: num(r.filters?.max_market_cap_usd),+ min_liquidity_sol: num(r.filters?.min_liquidity_sol),+ require_socials: r.filters?.require_socials === true,+ max_creator_launches: num(r.filters?.max_creator_launches),+ min_creator_graduated: num(r.filters?.min_creator_graduated),+ require_sol_quote: r.filters?.require_sol_quote !== false,+ },+ buy: {+ amount_sol: num(r.buy?.amount_sol) ?? d.buy.amount_sol,+ max_slippage_bps: num(r.buy?.max_slippage_bps) ?? d.buy.max_slippage_bps,+ },+ exits: {+ take_profit_pct: num(r.exits?.take_profit_pct),+ stop_loss_pct: num(r.exits?.stop_loss_pct) ?? d.exits.stop_loss_pct,+ trailing_stop_pct: num(r.exits?.trailing_stop_pct),+ max_hold_minutes: num(r.exits?.max_hold_minutes),+ },+ risk: {+ max_concurrent_positions: num(r.risk?.max_concurrent_positions) ?? d.risk.max_concurrent_positions,+ cooldown_minutes: num(r.risk?.cooldown_minutes) ?? d.risk.cooldown_minutes,+ },+ };+}++/**+ * Compile the visual rule into the nested Strategy Object config the live engine+ * runs. This is the EXACT shape api/_lib/strategy-schema.js#normalizeStrategyConfig+ * accepts; the server re-normalizes + re-validates it, so the client compile can+ * never widen the leash.+ */+export function compileRuleToConfig(rule) {+ const r = normalizeRule(rule);+ return {+ network: r.network,+ entry: {+ trigger: 'new_launch',+ max_age_minutes: r.trigger.max_age_minutes,+ min_market_cap_usd: r.filters.min_market_cap_usd,+ max_market_cap_usd: r.filters.max_market_cap_usd,+ min_liquidity_sol: r.filters.min_liquidity_sol,+ require_socials: r.filters.require_socials,+ max_creator_launches: r.filters.max_creator_launches,+ min_creator_graduated: r.filters.min_creator_graduated,+ require_sol_quote: r.filters.require_sol_quote,+ },+ sizing: {+ amount_sol: r.buy.amount_sol,+ max_slippage_bps: r.buy.max_slippage_bps,+ },+ exits: {+ take_profit_pct: r.exits.take_profit_pct,+ stop_loss_pct: r.exits.stop_loss_pct,+ trailing_stop_pct: r.exits.trailing_stop_pct,+ max_hold_minutes: r.exits.max_hold_minutes,+ },+ risk: {+ max_concurrent_positions: r.risk.max_concurrent_positions,+ cooldown_minutes: r.risk.cooldown_minutes,+ },+ };+}++/**+ * Compile a nested config into the flat sniper-strategy shape the historical+ * backtester replays (api/_lib/strategy-backtest.js). `maxPriceImpactPct` comes+ * from the agent's server-side guardrails so the projection honors the same+ * circuit breaker the live trade will.+ */+export function configToSniperStrategy(config, { maxPriceImpactPct = null } = {}) {+ const c = config || {};+ const e = c.entry || {};+ const s = c.sizing || {};+ const x = c.exits || {};+ const amountSol = Number(s.amount_sol) > 0 ? Number(s.amount_sol) : 0.1;+ return {+ trigger: 'new_mint',+ per_trade_lamports: String(Math.floor(amountSol * LAMPORTS_PER_SOL)),+ slippage_bps: Number.isFinite(Number(s.max_slippage_bps)) ? Math.round(Number(s.max_slippage_bps)) : 500,+ max_price_impact_pct: num(maxPriceImpactPct),+ min_market_cap_usd: num(e.min_market_cap_usd),+ max_market_cap_usd: num(e.max_market_cap_usd),+ min_creator_graduated: num(e.min_creator_graduated),+ max_creator_launches: num(e.max_creator_launches),+ require_socials: e.require_socials === true,+ require_sol_quote: e.require_sol_quote !== false,+ take_profit_pct: num(x.take_profit_pct),+ stop_loss_pct: num(x.stop_loss_pct),+ trailing_stop_pct: num(x.trailing_stop_pct),+ max_hold_seconds: num(x.max_hold_minutes) != null ? Math.round(num(x.max_hold_minutes) * 60) : null,+ };+}++/**+ * Validate the rule for the things the UI must catch before save (the server+ * re-validates authoritatively). Returns { valid, errors:{ [field]: message } }.+ */+export function validateRule(rule) {+ const r = normalizeRule(rule);+ const errors = {};+ if (!(r.buy.amount_sol > 0)) errors['buy.amount_sol'] = 'Per-trade size must be greater than 0 SOL.';+ if (r.buy.amount_sol > 100) errors['buy.amount_sol'] = 'Per-trade size is capped at 100 SOL.';+ if (!(r.exits.stop_loss_pct > 0 && r.exits.stop_loss_pct < 100)) {+ errors['exits.stop_loss_pct'] = 'A stop-loss between 1% and 99% is required — every rule must define its downside.';+ }+ if (r.exits.take_profit_pct == null && r.exits.trailing_stop_pct == null && r.exits.max_hold_minutes == null) {+ errors['exits'] = 'Define at least one upside exit: take-profit, trailing stop, or max hold.';+ }+ if (r.filters.min_market_cap_usd != null && r.filters.max_market_cap_usd != null &&+ r.filters.min_market_cap_usd > r.filters.max_market_cap_usd) {+ errors['filters.max_market_cap_usd'] = 'Max market cap must be greater than min market cap.';+ }+ return { valid: Object.keys(errors).length === 0, errors };+}++const usd = (n) => '$' + Number(n).toLocaleString(undefined, { maximumFractionDigits: 0 });++/**+ * Render the rule as a plain-English sentence a trader can verify at a glance.+ * No hype, no guarantees — just exactly what the agent will do.+ */+export function ruleToEnglish(rule) {+ const r = normalizeRule(rule);+ const f = r.filters;+ const conds = [];+ if (r.trigger.max_age_minutes != null) conds.push(`launched in the last ${r.trigger.max_age_minutes} min`);+ if (f.max_market_cap_usd != null) conds.push(`market cap under ${usd(f.max_market_cap_usd)}`);+ if (f.min_market_cap_usd != null) conds.push(`market cap over ${usd(f.min_market_cap_usd)}`);+ if (f.min_liquidity_sol != null) conds.push(`at least ${f.min_liquidity_sol} SOL liquidity`);+ if (f.require_socials) conds.push('has socials');+ if (f.max_creator_launches != null) conds.push(`creator has ≤ ${f.max_creator_launches} prior launches`);+ if (f.min_creator_graduated != null) conds.push(`creator has graduated ≥ ${f.min_creator_graduated} coins`);+ if (f.require_sol_quote) conds.push('SOL-quoted');++ const when = conds.length ? conds.join(', ') : 'any new launch';+ const exits = [];+ if (r.exits.take_profit_pct != null) exits.push(`take profit at +${r.exits.take_profit_pct}%`);+ if (r.exits.stop_loss_pct != null) exits.push(`cut losses at −${r.exits.stop_loss_pct}%`);+ if (r.exits.trailing_stop_pct != null) exits.push(`trail the peak by ${r.exits.trailing_stop_pct}%`);+ if (r.exits.max_hold_minutes != null) exits.push(`exit after ${r.exits.max_hold_minutes} min`);++ return `When a new coin appears that is ${when}, buy ${r.buy.amount_sol} SOL ` ++ `(max ${(r.buy.max_slippage_bps / 100).toFixed(1)}% slippage), then ${exits.join(', ') || 'manage the exit manually'}. ` ++ `Hold at most ${r.risk.max_concurrent_positions} position${r.risk.max_concurrent_positions === 1 ? '' : 's'} at once` ++ `${r.risk.cooldown_minutes ? `, with a ${r.risk.cooldown_minutes} min cooldown between buys` : ''}.`;+}diff --git a/src/theater-feed.js b/src/theater-feed.jsnew file mode 100644index 000000000..9a031807b--- /dev/null+++ b/src/theater-feed.js@@ -0,0 +1,128 @@+// Live Trading Theater — the real event spine.+//+// Every confirmed action on three.ws (a coin buy, an agent going on-chain, an+// x402 payment, a new agent) is published to the capped Redis list `feed:events`+// (api/_lib/feed.js) and tailed by GET /api/feed-stream (SSE). This module owns+// that connection: a fast snapshot from GET /api/feed for first paint, then the+// live stream, normalised into one shape the theater can route to a performer.+//+// Nothing here invents activity. If the stream is quiet, the theater shows its+// quiet-market state from the real recent snapshot — never a fabricated bot.++const SOL_EXPLORER = 'https://solscan.io';++function solscanToken(mint, network) {+ const base = `${SOL_EXPLORER}/token/${encodeURIComponent(mint)}`;+ return network === 'devnet' ? `${base}?cluster=devnet` : base;+}++function fmtSol(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return null;+ return `${v >= 100 ? Math.round(v) : v.toFixed(v < 1 ? 3 : 2)} SOL`;+}+function fmtUsdc(atomic) {+ const v = Number(atomic) / 1e6;+ if (!Number.isFinite(v)) return null;+ return `$${v >= 1000 ? Math.round(v).toLocaleString() : v.toFixed(2)}`;+}+function shortMint(m) {+ return typeof m === 'string' && m.length > 10 ? `${m.slice(0, 4)}…${m.slice(-4)}` : m || '';+}++/**+ * Normalise a raw feed event into the theater's routing shape, or null for an+ * event type the stage doesn't visualise (it still reaches the ticker raw).+ *+ * { id, ts, type, kind, actor, agentId, mint, title, sub, href }+ * kind ∈ buy | launch | verify | pay | win | loss | misc+ */+export function normalizeEvent(e) {+ if (!e || !e.type) return null;+ const base = {+ id: e.id || `${e.ts || Date.now()}-${Math.abs((e.type || '').length)}`,+ ts: Number(e.ts) || Date.now(),+ type: e.type,+ actor: typeof e.actor === 'string' ? e.actor : '',+ agentId: null,+ mint: null,+ href: null,+ };+ switch (e.type) {+ case 'coin-buy':+ return { ...base, kind: 'buy', mint: e.mint || null, title: 'Buy filled', sub: fmtSol(e.sol) || shortMint(e.mint), href: e.mint ? solscanToken(e.mint, e.network) : null };+ case 'agent-deploy':+ return { ...base, kind: 'launch', agentId: e.agentId || null, title: 'New agent', sub: e.name || base.actor, href: e.agentId ? `/agent/${e.agentId}` : null };+ case 'agent-onchain':+ return { ...base, kind: 'verify', agentId: e.agentId || null, title: 'Verified on-chain', sub: e.name || base.actor, href: e.agentId ? `/agent/${e.agentId}` : null };+ case 'payment':+ return { ...base, kind: 'pay', title: 'Payment', sub: fmtUsdc(e.usdcAtomic) || e.recipientLabel || base.actor, href: e.explorerUrl || null };+ case 'jackpot':+ return { ...base, kind: 'win', title: 'Jackpot', sub: e.reward ? `${e.reward}` : base.actor, href: null };+ default:+ return { ...base, kind: 'misc', title: e.type.replace(/-/g, ' '), sub: base.actor, href: null };+ }+}++/**+ * Fetch the recent feed snapshot for first paint (quiet-market highlights and+ * the replay seed). Returns normalised events newest-first.+ */+export async function loadSnapshot(limit = 40) {+ try {+ const r = await fetch(`/api/feed?limit=${limit}`, { headers: { accept: 'application/json' } });+ if (!r.ok) return [];+ const body = await r.json();+ const events = Array.isArray(body.events) ? body.events : [];+ return events.map(normalizeEvent).filter(Boolean);+ } catch {+ return [];+ }+}++/**+ * Open the live SSE stream. Calls onEvent(normalized) for each fresh event and+ * onStatus('connecting'|'live'|'reconnecting'|'offline') on connection changes.+ * EventSource reconnects automatically; we surface that as 'reconnecting' so the+ * UI never shows stale data as live. Returns { close }.+ */+export function connectFeed({ onEvent, onStatus }) {+ if (typeof EventSource === 'undefined') {+ onStatus?.('offline');+ return { close() {} };+ }+ let es = null;+ let closed = false;+ let firstOpen = true;++ const open = () => {+ if (closed) return;+ onStatus?.(firstOpen ? 'connecting' : 'reconnecting');+ es = new EventSource('/api/feed-stream');+ es.addEventListener('hello', () => { firstOpen = false; onStatus?.('live'); });+ es.addEventListener('open', () => { onStatus?.('live'); });+ es.addEventListener('event', (ev) => {+ let raw;+ try { raw = JSON.parse(ev.data); } catch { return; }+ const n = normalizeEvent(raw);+ if (n) onEvent?.(n);+ });+ es.onerror = () => {+ // EventSource transitions to CLOSED only on fatal errors; for transient+ // drops it retries on its own. Surface 'reconnecting' either way.+ onStatus?.('reconnecting');+ if (es && es.readyState === EventSource.CLOSED && !closed) {+ try { es.close(); } catch {}+ setTimeout(open, 2500);+ }+ };+ };+ open();++ return {+ close() {+ closed = true;+ try { es?.close(); } catch {}+ },+ };+}diff --git a/src/theater-stage.js b/src/theater-stage.jsnew file mode 100644index 000000000..bfbbc20cb--- /dev/null+++ b/src/theater-stage.js@@ -0,0 +1,482 @@+// Live Trading Theater — the shared 3D stage.+//+// A single Three.js scene holds every staged agent as a real 3D avatar, arranged+// in a tiered arc so the highest-reputation performers stand center-front. When a+// REAL on-chain event for an agent lands (driven from src/theater-feed.js, which+// tails the same Redis-backed feed every surface uses), that agent's avatar plays+// a one-shot performance and a real receipt rises above it with an explorer link.+//+// No timers fake activity here: this module only animates when the controller+// hands it a real, already-confirmed event. The idle loop is the only ambient+// motion, and it's the pre-baked canonical clip every avatar shares.+//+// Reuses the platform primitives rather than rebuilding them:+// • gltfLoader(renderer) — shared Draco/KTX2/Meshopt loader+// • AnimationManager — retargets the canonical clip library onto any rig+// • agentAvatarGlb(agent) — resolves a real GLB (custom or mannequin fallback)+// so a brand-new agent with no custom body still renders as a real figure, never a+// T-pose (CLAUDE.md: no rig allowlist, mannequin is the designed fallback).++import {+ Scene,+ PerspectiveCamera,+ WebGLRenderer,+ Group,+ Box3,+ Vector3,+ Color,+ Fog,+ HemisphereLight,+ DirectionalLight,+ SpotLight,+ PointLight,+ CircleGeometry,+ RingGeometry,+ CylinderGeometry,+ MeshStandardMaterial,+ MeshBasicMaterial,+ Mesh,+ Raycaster,+ Vector2,+ SRGBColorSpace,+ ACESFilmicToneMapping,+ DoubleSide,+} from 'three';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';+import { gltfLoader, disposeGltfLoader } from './loaders/gltf.js';+import { AnimationManager } from './animation-manager.js';+import { agentAvatarGlb } from './shared/agent-3d.js';+import { log } from './shared/log.js';++// Reaction vocabulary mapped onto the real pre-baked clip library+// (public/animations/manifest.json). Each kind picks deterministically from its+// pool so the same agent reacting to the same event type looks consistent.+const REACTIONS = {+ win: ['celebrate', 'av-celebrating', 'av-joy', 'av-cheering'],+ buy: ['av-cheering', 'celebrate', 'av-joy'],+ launch: ['av-celebrating', 'celebrate', 'av-joy'],+ verify: ['wave', 'av-cheering'],+ pay: ['av-cheering', 'wave'],+ loss: ['defeated', 'reaction'],+ taunt: ['taunt', 'reaction'],+};+const ALL_REACTION_CLIPS = [...new Set(Object.values(REACTIONS).flat())];++// Clips every performer registers. `idle` loops as the resting state; the rest+// are one-shots loaded lazily on first reaction so startup only fetches idle.+const CLIP_DEFS = [+ { name: 'idle', url: '/animations/clips/idle.json', loop: true },+ ...ALL_REACTION_CLIPS.map((name) => ({ name, url: `/animations/clips/${name}.json`, loop: false })),+];++const _box = new Box3();+const _v = new Vector3();+const _v2 = new Vector3();++function scaleToHeight(obj, h) {+ _box.setFromObject(obj, true);+ const cur = _box.max.y - _box.min.y || 1;+ obj.scale.multiplyScalar(h / cur);+}+function groundFeet(obj) {+ _box.setFromObject(obj, true);+ if (Number.isFinite(_box.min.y)) obj.position.y -= _box.min.y;+}++// Deterministic small hash so a given agent id always picks the same reaction+// from a pool (stable performances across reconnects).+function hashPick(arr, key) {+ let h = 0;+ const s = String(key || '');+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;+ return arr[Math.abs(h) % arr.length];+}++/**+ * Tiered-arc layout: rank 0 dead center & closest to camera, then fan outward+ * and back in widening rows. Returns { x, z, scale } for a given index.+ */+function arcSlot(index, total) {+ // Rows of increasing width: 3, 5, 7, … keeps the front row tight and the+ // crowd receding so the leader reads as center stage.+ let row = 0;+ let placed = 0;+ let rowSize = 3;+ let idxInRow = index;+ while (idxInRow >= rowSize) {+ idxInRow -= rowSize;+ placed += rowSize;+ row += 1;+ rowSize += 2;+ }+ const spanHalf = (rowSize - 1) / 2;+ const spread = 1.55 + row * 0.25; // wider gaps further back+ const x = (idxInRow - spanHalf) * spread;+ const z = -row * 2.15;+ const scale = Math.max(0.86, 1 - row * 0.05); // gentle falloff with depth+ return { x, z, scale };+}++export function createStage({ canvas, overlay, onSelect, reducedMotion = false }) {+ const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));+ renderer.outputColorSpace = SRGBColorSpace;+ renderer.toneMapping = ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.12;++ const scene = new Scene();+ scene.fog = new Fog(0x05050a, 14, 38);++ const camera = new PerspectiveCamera(42, 1, 0.1, 200);+ camera.position.set(0, 2.35, 9.4);+ camera.lookAt(0, 1.25, -2);++ // Lighting — a cool key from above the audience plus a warm rim so avatars+ // read against the near-black backdrop. Violet accent matches the finance tokens.+ scene.add(new HemisphereLight(0xaab4ff, 0x0a0a12, 0.9));+ const key = new DirectionalLight(0xffffff, 1.5);+ key.position.set(3, 9, 6);+ scene.add(key);+ const rim = new DirectionalLight(0x8b5cf6, 0.8);+ rim.position.set(-5, 4, -6);+ scene.add(rim);+ const spot = new SpotLight(0xc4b5fd, 1.6, 30, Math.PI / 5, 0.4, 1.2);+ spot.position.set(0, 11, 4);+ spot.target.position.set(0, 0, -1);+ scene.add(spot);+ scene.add(spot.target);++ // Stage floor — a dark reflective-feeling disc with a violet ring horizon.+ const floor = new Mesh(+ new CircleGeometry(22, 64),+ new MeshStandardMaterial({ color: 0x0b0b14, roughness: 0.62, metalness: 0.35 }),+ );+ floor.rotation.x = -Math.PI / 2;+ floor.position.y = 0;+ scene.add(floor);+ const ring = new Mesh(+ new RingGeometry(7.6, 7.9, 96),+ new MeshBasicMaterial({ color: 0x8b5cf6, transparent: true, opacity: 0.28, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.y = 0.01;+ scene.add(ring);++ // Group that holds all performers so we can gently auto-orbit the whole cast.+ const cast = new Group();+ scene.add(cast);++ const loader = gltfLoader(renderer);+ const templates = new Map(); // glbUrl → Promise<{ scene }>+ const performers = new Map(); // agentId → performer record+ const receipts = []; // floating DOM receipts anchored to world points++ let disposed = false;+ let raf = 0;+ let last = performance.now();+ let autoOrbit = !reducedMotion;+ let orbitYaw = 0;+ let highlightId = null;++ // ── Avatar templates ────────────────────────────────────────────────────────+ function template(url) {+ if (templates.has(url)) return templates.get(url);+ const p = loader+ .loadAsync(url)+ .then((gltf) => {+ gltf.scene.traverse((n) => { if (n.isMesh) { n.frustumCulled = true; n.castShadow = false; } });+ return { scene: gltf.scene };+ })+ .catch((err) => {+ log.warn('[theater] template load failed', url, err?.message);+ return { scene: null };+ });+ templates.set(url, p);+ return p;+ }++ async function addPerformer(agent, index, total) {+ if (disposed || performers.has(agent.id)) return;+ const url = agentAvatarGlb(agent);+ const tpl = await template(url);+ if (disposed || !tpl.scene || performers.has(agent.id)) return;++ const slot = arcSlot(index, total);+ const model = cloneSkinnedScene(tpl.scene);+ model.traverse((n) => { if (n.isMesh) n.frustumCulled = true; });++ const group = new Group();+ group.name = `performer:${agent.id}`;+ group.add(model);+ scaleToHeight(model, 1.74 * slot.scale);+ groundFeet(model);+ group.position.set(slot.x, 0, slot.z);+ group.rotation.y = (Math.atan2(-group.position.x, 9 - group.position.z) || 0) * 0.35; // toward the audience+ group.userData.agentId = agent.id;+ cast.add(group);++ // A soft pedestal glow under each performer; brightens when highlighted.+ const pad = new Mesh(+ new CircleGeometry(0.78, 40),+ new MeshBasicMaterial({ color: 0x8b5cf6, transparent: true, opacity: 0.0, side: DoubleSide }),+ );+ pad.rotation.x = -Math.PI / 2;+ pad.position.set(slot.x, 0.02, slot.z);+ cast.add(pad);++ const anim = new AnimationManager();+ const drivable = (() => {+ try {+ anim.attach(model, { avatarUrl: url });+ anim.setAnimationDefs(CLIP_DEFS);+ return anim.supportsCanonicalClips();+ } catch (err) {+ log.warn('[theater] anim attach failed', agent.id, err?.message);+ return false;+ }+ })();+ if (drivable && !reducedMotion) anim.play('idle');++ const rec = { agent, group, model, pad, anim, drivable, slot, busy: false };+ performers.set(agent.id, rec);+ }++ /**+ * Reconcile the staged cast with a new roster (room switch / refresh). Removes+ * performers no longer present and adds new ones, preserving any that stay.+ */+ async function setRoster(agents) {+ const keep = new Set(agents.map((a) => a.id));+ for (const [id, rec] of [...performers]) {+ if (!keep.has(id)) removePerformer(id, rec);+ }+ // Add sequentially with a micro-yield so a full room fills progressively+ // instead of stalling one frame on a dozen GLB clones.+ for (let i = 0; i < agents.length; i++) {+ if (disposed) return;+ await addPerformer(agents[i], i, agents.length);+ if ((i & 3) === 3) await new Promise((r) => setTimeout(r, 0));+ }+ }++ function removePerformer(id, rec) {+ performers.delete(id);+ try { rec.anim?.dispose?.(); } catch {}+ rec.group?.parent?.remove(rec.group);+ rec.pad?.parent?.remove(rec.pad);+ rec.group?.traverse?.((n) => {+ if (n.isMesh) { n.geometry?.dispose?.(); disposeMaterial(n.material); }+ });+ }++ function disposeMaterial(m) {+ if (!m) return;+ (Array.isArray(m) ? m : [m]).forEach((x) => x?.dispose?.());+ }++ // ── Performances ─────────────────────────────────────────────────────────────+ /**+ * Trigger a real performance for an agent. `kind` selects the reaction pool;+ * `receipt` (optional) is a DOM node that rises above the avatar and fades.+ * No-op if the agent isn't staged — the controller still shows it in the ticker.+ */+ function perform(agentId, { kind = 'win', receipt = null } = {}) {+ const rec = performers.get(agentId);+ if (!rec) { if (receipt) attachReceiptToCenter(receipt); return false; }+ if (rec.drivable && !reducedMotion) {+ const pool = REACTIONS[kind] || REACTIONS.win;+ const clip = hashPick(pool, agentId + kind);+ rec.busy = true;+ rec.anim.playOnce(clip, { settleTo: 'idle' });+ }+ pulsePad(rec);+ if (receipt) attachReceiptToPerformer(rec, receipt);+ return true;+ }++ function pulsePad(rec) {+ rec.pad.material.opacity = 0.55;+ rec.pad.userData.fade = performance.now();+ }++ // ── Floating receipts (DOM projected over the canvas) ───────────────────────+ // Anchored to the rotating cast so a receipt tracks its performer as the stage+ // orbits; centre receipts (for unstaged actors) anchor to the stage middle.+ function attachReceiptToCenter(el) {+ receipts.push({ el, anchor: new Vector3(0, 2.4, -1), born: performance.now(), rise: 1.1 });+ overlay.appendChild(el);+ }+ function attachReceiptToPerformer(rec, el) {+ receipts.push({ el, born: performance.now(), rise: 0.9, follow: rec });+ overlay.appendChild(el);+ }++ /**+ * A centerpiece object for a launch / coin-buy spectacle — a glowing token+ * coin rises from the stage floor, holds, then sinks and is removed. Driven+ * only by a real coin-buy/launch event.+ */+ function spawnCenterpiece({ tint = 0x8b5cf6 } = {}) {+ const coin = new Mesh(+ new CylinderGeometry(0.62, 0.62, 0.12, 40),+ new MeshStandardMaterial({ color: tint, emissive: new Color(tint), emissiveIntensity: 0.9, metalness: 0.7, roughness: 0.25 }),+ );+ coin.rotation.x = Math.PI / 2;+ coin.position.set(0, 0.2, -1);+ coin.userData.born = performance.now();+ scene.add(coin);+ const glow = new PointLight(tint, 2.4, 9, 2);+ glow.position.set(0, 1.6, -1);+ scene.add(glow);+ coin.userData.glow = glow;+ centerpieces.push(coin);+ }+ const centerpieces = [];++ // ── Selection (raycast) ──────────────────────────────────────────────────────+ const raycaster = new Raycaster();+ const ndc = new Vector2();+ let downX = 0, downY = 0, downAt = 0;+ function onPointerDown(e) { downX = e.clientX; downY = e.clientY; downAt = performance.now(); }+ function onPointerUp(e) {+ const moved = Math.hypot(e.clientX - downX, e.clientY - downY);+ if (moved > 8 || performance.now() - downAt > 600) return; // a drag, not a click+ const rect = canvas.getBoundingClientRect();+ ndc.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;+ ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;+ raycaster.setFromCamera(ndc, camera);+ const hits = raycaster.intersectObjects(cast.children, true);+ for (const h of hits) {+ let o = h.object;+ while (o && !o.userData?.agentId) o = o.parent;+ if (o?.userData?.agentId) { onSelect?.(o.userData.agentId); return; }+ }+ }+ canvas.addEventListener('pointerdown', onPointerDown);+ canvas.addEventListener('pointerup', onPointerUp);++ // Drag to rotate the cast; pauses auto-orbit while dragging.+ let dragging = false, lastX = 0;+ canvas.addEventListener('pointerdown', (e) => { dragging = true; lastX = e.clientX; autoOrbit = false; });+ window.addEventListener('pointerup', () => { dragging = false; });+ window.addEventListener('pointermove', (e) => {+ if (!dragging) return;+ orbitYaw += (e.clientX - lastX) * 0.005;+ lastX = e.clientX;+ });++ function highlight(agentId) {+ highlightId = agentId;+ }++ // ── Render loop ──────────────────────────────────────────────────────────────+ function frame(now) {+ if (disposed) return;+ raf = requestAnimationFrame(frame);+ const dt = Math.min(0.05, (now - last) / 1000);+ last = now;++ if (autoOrbit && !reducedMotion) orbitYaw += dt * 0.06;+ cast.rotation.y = orbitYaw;+ ring.rotation.z += dt * 0.05;++ if (!reducedMotion) {+ for (const rec of performers.values()) {+ if (rec.drivable) rec.anim.update(dt);+ // fade pedestal pulse back down+ if (rec.pad.material.opacity > 0) {+ const target = rec.agent.id === highlightId ? 0.32 : 0;+ rec.pad.material.opacity += (target - rec.pad.material.opacity) * Math.min(1, dt * 3);+ } else if (rec.agent.id === highlightId) {+ rec.pad.material.opacity = 0.32;+ }+ }+ }++ // Centerpiece coins: rise (0–0.6s), hold, sink + remove (after 3.4s).+ for (let i = centerpieces.length - 1; i >= 0; i--) {+ const coin = centerpieces[i];+ const age = (now - coin.userData.born) / 1000;+ coin.rotation.z += dt * 2.2;+ coin.position.y = age < 0.6 ? 0.2 + age * 2.4 : age < 2.8 ? 1.64 : Math.max(0.2, 1.64 - (age - 2.8) * 2.4);+ if (coin.userData.glow) coin.userData.glow.position.y = coin.position.y + 0.3;+ if (age > 3.4) {+ scene.remove(coin); if (coin.userData.glow) scene.remove(coin.userData.glow);+ coin.geometry.dispose(); disposeMaterial(coin.material);+ centerpieces.splice(i, 1);+ }+ }++ projectReceipts(now);+ renderer.render(scene, camera);+ }++ function projectReceipts(now) {+ for (let i = receipts.length - 1; i >= 0; i--) {+ const r = receipts[i];+ const age = (now - r.born) / 1000;+ if (age > 4.4) { r.el.remove(); receipts.splice(i, 1); continue; }+ // follow a moving performer (cast rotates), else use static anchor+ if (r.follow) {+ _v.set(r.follow.group.position.x, 2.05 * (r.follow.slot?.scale || 1), r.follow.group.position.z);+ _v.applyMatrix4(cast.matrixWorld);+ } else {+ _v.copy(r.anchor);+ }+ _v.y += Math.min(r.rise, age * r.rise); // rise then settle+ _v2.copy(_v).project(camera);+ const rect = canvas.getBoundingClientRect();+ const x = (_v2.x * 0.5 + 0.5) * rect.width;+ const y = (-_v2.y * 0.5 + 0.5) * rect.height;+ const visible = _v2.z < 1 && x > -120 && x < rect.width + 120;+ r.el.style.opacity = visible ? String(age < 0.25 ? age / 0.25 : age > 3.6 ? Math.max(0, (4.4 - age) / 0.8) : 1) : '0';+ r.el.style.transform = `translate(-50%, -100%) translate(${x.toFixed(1)}px, ${y.toFixed(1)}px)`;+ }+ }++ function resize() {+ const rect = canvas.getBoundingClientRect();+ const w = Math.max(1, rect.width), h = Math.max(1, rect.height);+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ }++ function setReducedMotion(on) {+ reducedMotion = on;+ autoOrbit = !on;+ for (const rec of performers.values()) {+ if (!rec.drivable) continue;+ if (on) rec.anim.freeze?.();+ else rec.anim.play('idle');+ }+ }++ function dispose() {+ disposed = true;+ cancelAnimationFrame(raf);+ canvas.removeEventListener('pointerdown', onPointerDown);+ canvas.removeEventListener('pointerup', onPointerUp);+ for (const [id, rec] of [...performers]) removePerformer(id, rec);+ for (const r of receipts) r.el.remove();+ receipts.length = 0;+ for (const coin of centerpieces) { scene.remove(coin); coin.userData.glow && scene.remove(coin.userData.glow); }+ try { disposeGltfLoader(renderer); } catch {}+ renderer.dispose();+ }++ resize();+ raf = requestAnimationFrame(frame);++ return {+ setRoster,+ perform,+ spawnCenterpiece,+ highlight,+ resize,+ setReducedMotion,+ dispose,+ hasPerformer: (id) => performers.has(id),+ get count() { return performers.size; },+ };+}diff --git a/tests/economy-shape.test.js b/tests/economy-shape.test.jsnew file mode 100644index 000000000..63e78249e--- /dev/null+++ b/tests/economy-shape.test.js@@ -0,0 +1,67 @@+// Owner economy summary — earnings composition (api/_lib/economy-shape.js).+//+// The agent economy's headline income is one agent hiring another over the x402+// mesh. That income must surface as its own `hires` bucket and roll into the+// total alongside skill sales and tips — never be silently lumped into "tips" or+// double-counted. These tests lock that contract down.++import { describe, it, expect } from 'vitest';+import { composeEarnings } from '../api/_lib/economy-shape.js';++describe('composeEarnings', () => {+ it('keeps skill sales, hires, and tips as three distinct buckets', () => {+ const e = composeEarnings({+ skill_sales: { today: 1, week: 2, lifetime: 10, count: 5 },+ hires: { today: 3, week: 4, lifetime: 20, count: 7 },+ tips: { today: 0.5, week: 1.5, lifetime: 5, count: 9 },+ });+ expect(e.skill_sales.lifetime).toBe(10);+ expect(e.hires.lifetime).toBe(20);+ expect(e.tips.lifetime).toBe(5);+ expect(e.hires.count).toBe(7);+ });++ it('totals all three streams across every window without double-counting', () => {+ const e = composeEarnings({+ skill_sales: { today: 1, week: 2, lifetime: 10, count: 5 },+ hires: { today: 3, week: 4, lifetime: 20, count: 7 },+ tips: { today: 0.5, week: 1.5, lifetime: 5, count: 9 },+ });+ expect(e.total.today).toBe(4.5);+ expect(e.total.week).toBe(7.5);+ expect(e.total.lifetime).toBe(35);+ expect(e.total.count).toBe(21);+ });++ it('surfaces hire income in the total even with zero sales and tips', () => {+ const e = composeEarnings({+ skill_sales: { today: 0, week: 0, lifetime: 0, count: 0 },+ hires: { today: 2, week: 6, lifetime: 42, count: 3 },+ tips: { today: 0, week: 0, lifetime: 0, count: 0 },+ });+ expect(e.total.lifetime).toBe(42);+ expect(e.total.count).toBe(3);+ });++ it('preserves extra bucket fields (e.g. skill_sales.non_usdc_count)', () => {+ const e = composeEarnings({+ skill_sales: { today: 0, week: 0, lifetime: 0, count: 0, non_usdc_count: 4 },+ hires: { today: 0, week: 0, lifetime: 0, count: 0 },+ tips: { today: 0, week: 0, lifetime: 0, count: 0 },+ });+ expect(e.skill_sales.non_usdc_count).toBe(4);+ });++ it('defaults missing buckets and non-numeric values to zero', () => {+ const e = composeEarnings({ hires: { lifetime: 'oops', count: null } });+ expect(e.total.lifetime).toBe(0);+ expect(e.total.count).toBe(0);+ expect(e.skill_sales).toEqual({});+ expect(e.tips).toEqual({});+ });++ it('returns a zeroed total when called with no arguments', () => {+ const e = composeEarnings();+ expect(e.total).toEqual({ today: 0, week: 0, lifetime: 0, count: 0 });+ });+});diff --git a/vercel.json b/vercel.jsonindex 3fc10c95b..c2deeaa41 100644--- a/vercel.json+++ b/vercel.json@@ -77,6 +77,9 @@"api/cron/forge-seed-cron.js": {"maxDuration": 70},+ "api/cron/reflect-sweep.js": {+ "maxDuration": 120+ },"api/cron/oracle-score.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 120@@ -4259,6 +4262,10 @@"path": "/api/cron/forge-seed-cron","schedule": "* * * * *"},+ {+ "path": "/api/cron/reflect-sweep",+ "schedule": "*/30 * * * *"+ },{"path": "/api/cron/oracle-digest","schedule": "0 8 * * *"