Skip to content

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

feat: add Memory Studio with entity store, graph, and curation APIs

nirholas96b8106d434f
diff --git a/api/_lib/memory-entities.js b/api/_lib/memory-entities.js
new file mode 100644
index 000000000..af59eabb9
Binary files /dev/null and b/api/_lib/memory-entities.js differ
diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.js
new file mode 100644
index 000000000..8f2f66547
--- /dev/null
+++ b/api/_lib/memory-store.js
@@ -0,0 +1,408 @@
+// Memory Store (P2 — Memory Studio engine)
+// =========================================
+// The real, tiered memory engine shared by api/agent-memory.js and api/memory/**.
+//
+// Tiers (Letta/MemGPT model):
+// working — the small, always-in-context core (pinned + the agent's identity
+// and active rules). Token-budgeted.
+// recall — recent interactions/trades, searchable.
+// archival — long-term store; semantic search over real embeddings.
+//
+// Embeddings are produced by api/_lib/embeddings.js (free NIM lane first, OpenAI
+// backstop), stored as JSONB vectors tagged with the embedder that made them,
+// and scored strictly within their own vector space (scoreRowsBySpace). No fake
+// similarity: when no provider is configured, search degrades to substring +
+// salience, never a fabricated cosine score.
+//
+// Entity graph (Zep/Graphiti-style temporal KG): every memory is mined for the
+// mints, tickers, wallets, people and strategies it mentions; entities are
+// upserted as graph nodes and linked to their source memory. Edges between
+// entities are derived at read time from co-occurrence within a memory.
+
+import { sql } from './db.js';
+import {
+ embeddingsConfigured,
+ defaultIngestEmbedderTag,
+ embedPassages,
+ scoreRowsBySpace,
+} from './embeddings.js';
+import { extractEntities } from './memory-entities.js';
+
+export const MEMORY_TIERS = ['working', 'recall', 'archival'];
+
+// The working core is kept small on purpose — this is what's always paged into
+// the model's context. ~4 chars/token is the platform's standard estimate
+// (matches widget knowledge chunking).
+export const WORKING_TOKEN_BUDGET = 2000;
+export const CHARS_PER_TOKEN = 4;
+
+// How many un-embedded / un-extracted rows a single read-triggered lazy pass
+// processes. Bounds the work per request; repeated reads converge the backlog.
+const EMBED_CAP = 24;
+const ENTITY_CAP = 40;
+
+export function estimateTokens(text) {
+ return Math.ceil(String(text || '').length / CHARS_PER_TOKEN);
+}
+
+// ── Decoration ──────────────────────────────────────────────────────────────
+
+export function decorateMemory(row, extra = {}) {
+ const createdMs = row.created_at ? new Date(row.created_at).getTime() : Date.now();
+ return {
+ id: row.id,
+ agent_id: row.agent_id,
+ type: row.type,
+ content: row.content,
+ tags: row.tags || [],
+ context: row.context || {},
+ salience: row.salience,
+ tier: row.tier || 'recall',
+ pinned: !!row.pinned,
+ embedder: row.embedder || null,
+ hasEmbedding: row.has_embedding ?? row.embedding != null,
+ accessCount: row.access_count ?? 0,
+ isPublic: row.is_public ?? false,
+ tokens: estimateTokens(row.content),
+ createdAt: createdMs,
+ updatedAt: row.updated_at ? new Date(row.updated_at).getTime() : createdMs,
+ lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at).getTime() : null,
+ expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
+ ...extra,
+ };
+}
+
+// ── Lazy embedding ────────────────────────────────────────────────────────────
+
+/**
+ * Embed up to EMBED_CAP not-yet-embedded memories for an agent. Best-effort:
+ * returns counts and never throws (a provider outage just leaves rows for the
+ * next pass). Covers every write path uniformly — no writer needs to embed.
+ * @returns {Promise<{configured:boolean, embedded:number, remaining:number}>}
+ */
+export async function ensureEmbeddings(agentId, cap = EMBED_CAP) {
+ if (!embeddingsConfigured()) return { configured: false, embedded: 0, remaining: 0 };
+ const tag = defaultIngestEmbedderTag();
+ if (!tag) return { configured: false, embedded: 0, remaining: 0 };
+
+ let rows;
+ try {
+ rows = await sql`
+ SELECT id, content FROM agent_memories
+ WHERE agent_id = ${agentId} AND embedding IS NULL
+ AND (expires_at IS NULL OR expires_at > now())
+ ORDER BY created_at DESC
+ LIMIT ${cap + 1}
+ `;
+ } catch {
+ return { configured: true, embedded: 0, remaining: 0 };
+ }
+ if (!rows.length) return { configured: true, embedded: 0, remaining: 0 };
+
+ const capped = rows.length > cap;
+ const batch = capped ? rows.slice(0, cap) : rows;
+
+ let vectors;
+ try {
+ vectors = await embedPassages(tag, batch.map((r) => r.content || ''));
+ } catch (err) {
+ console.warn('[memory-store] embed batch failed', err?.code || err?.message);
+ return { configured: true, embedded: 0, remaining: rows.length };
+ }
+
+ let embedded = 0;
+ for (let i = 0; i < batch.length; i++) {
+ const vec = vectors[i];
+ if (!vec) continue;
+ try {
+ await sql`
+ UPDATE agent_memories
+ SET embedding = ${JSON.stringify(Array.from(vec))}::jsonb, embedder = ${tag}
+ WHERE id = ${batch[i].id}
+ `;
+ embedded++;
+ } catch {
+ /* leave for next pass */
+ }
+ }
+ return { configured: true, embedded, remaining: capped ? 1 : 0 };
+}
+
+// ── Semantic search (mem0 search()) ────────────────────────────────────────────
+
+/**
+ * Rank an agent's memories against a query. Embeds the query in each stored
+ * vector space (never crossing spaces), filters by minScore, and fills any
+ * shortfall with a salience-ranked substring match so recall is never empty
+ * just because a provider is down.
+ *
+ * @param {string} agentId
+ * @param {string} query
+ * @param {{ topK?:number, minScore?:number, tiers?:string[], type?:string, bump?:boolean }} [opts]
+ * @returns {Promise<{ results:Array<object>, provider:boolean, scored:number }>}
+ */
+export async function searchMemories(agentId, query, opts = {}) {
+ const { topK = 8, minScore = 0.25, tiers, type, bump = true } = opts;
+ const q = String(query || '').trim();
+ if (!q) return { results: [], provider: false, scored: 0 };
+
+ await ensureEmbeddings(agentId).catch(() => {});
+
+ const tierList = Array.isArray(tiers) && tiers.length ? tiers.filter((t) => MEMORY_TIERS.includes(t)) : null;
+ const rows = await sql`
+ SELECT id, agent_id, type, content, tags, context, salience, tier, pinned,
+ embedder, embedding, access_count, is_public, created_at, updated_at,
+ last_accessed_at, expires_at
+ FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND (expires_at IS NULL OR expires_at > now())
+ AND (${type ?? null}::text IS NULL OR type = ${type ?? null})
+ AND (${tierList}::text[] IS NULL OR tier = ANY(${tierList}))
+ ORDER BY created_at DESC
+ LIMIT 1500
+ `;
+ if (!rows.length) return { results: [], provider: embeddingsConfigured(), scored: 0 };
+
+ const embedded = rows.filter((r) => Array.isArray(r.embedding) && r.embedding.length);
+ let semantic = [];
+ let usedProvider = false;
+ if (embedded.length && embeddingsConfigured()) {
+ try {
+ const { scored } = await scoreRowsBySpace(embedded, q);
+ semantic = scored
+ .filter((r) => r.score >= minScore)
+ .sort((a, b) => b.score - a.score);
+ usedProvider = true;
+ } catch (err) {
+ console.warn('[memory-store] scoring failed', err?.code || err?.message);
+ }
+ }
+
+ const ranked = [];
+ const seen = new Set();
+ for (const r of semantic) {
+ if (seen.has(r.id)) continue;
+ seen.add(r.id);
+ ranked.push(decorateMemory(r, { score: Number(r.score.toFixed(4)), match: 'semantic' }));
+ if (ranked.length >= topK) break;
+ }
+
+ // Substring + salience fill so a query always surfaces obvious lexical hits
+ // (and so recall works at all before embeddings backfill / when unconfigured).
+ if (ranked.length < topK) {
+ const ql = q.toLowerCase();
+ const lexical = rows
+ .filter((r) => !seen.has(r.id) && String(r.content || '').toLowerCase().includes(ql))
+ .sort((a, b) => (b.salience || 0) - (a.salience || 0));
+ for (const r of lexical) {
+ if (seen.has(r.id)) continue;
+ seen.add(r.id);
+ ranked.push(decorateMemory(r, { score: null, match: 'lexical' }));
+ if (ranked.length >= topK) break;
+ }
+ }
+
+ if (bump && ranked.length) {
+ const ids = ranked.map((r) => r.id);
+ // Reinforcement: accessed memories gain a little salience (capped) and
+ // record the access — the recency/decay loop the Letta tiering relies on.
+ sql`
+ UPDATE agent_memories
+ SET access_count = access_count + 1,
+ last_accessed_at = now(),
+ salience = LEAST(1.0, salience + 0.02)
+ WHERE id = ANY(${ids})
+ `.catch(() => {});
+ }
+
+ return { results: ranked, provider: usedProvider, scored: semantic.length };
+}
+
+// ── Entity extraction + graph ──────────────────────────────────────────────────
+
+/**
+ * Mine up to ENTITY_CAP not-yet-processed memories for entities, upsert them as
+ * graph nodes, and link each to its source memory. Idempotent + best-effort.
+ * @returns {Promise<{processed:number, remaining:number}>}
+ */
+export async function ensureEntities(agentId, cap = ENTITY_CAP) {
+ let rows;
+ try {
+ rows = await sql`
+ SELECT id, content, tags, context FROM agent_memories
+ WHERE agent_id = ${agentId} AND entities_extracted = false
+ AND (expires_at IS NULL OR expires_at > now())
+ ORDER BY created_at DESC
+ LIMIT ${cap + 1}
+ `;
+ } catch {
+ return { processed: 0, remaining: 0 };
+ }
+ if (!rows.length) return { processed: 0, remaining: 0 };
+
+ const capped = rows.length > cap;
+ const batch = capped ? rows.slice(0, cap) : rows;
+
+ let processed = 0;
+ for (const row of batch) {
+ const entities = extractEntities(row.content, row.tags || [], row.context || {});
+ try {
+ for (const e of entities) {
+ const [ent] = await sql`
+ INSERT INTO agent_memory_entities (agent_id, kind, label, normalized, mention_count, salience, meta)
+ VALUES (${agentId}, ${e.kind}, ${e.label}, ${e.normalized}, 1, 0.5, ${JSON.stringify(e.meta || {})}::jsonb)
+ ON CONFLICT (agent_id, kind, normalized) DO UPDATE
+ SET mention_count = agent_memory_entities.mention_count + 1,
+ last_seen_at = now(),
+ label = EXCLUDED.label,
+ salience = LEAST(1.0, agent_memory_entities.salience + 0.05)
+ RETURNING id
+ `;
+ if (ent?.id) {
+ await sql`
+ INSERT INTO agent_memory_entity_links (entity_id, memory_id)
+ VALUES (${ent.id}, ${row.id})
+ ON CONFLICT DO NOTHING
+ `;
+ }
+ }
+ await sql`UPDATE agent_memories SET entities_extracted = true WHERE id = ${row.id}`;
+ processed++;
+ } catch (err) {
+ console.warn('[memory-store] entity extraction failed for', row.id, err?.message);
+ }
+ }
+ return { processed, remaining: capped ? 1 : 0 };
+}
+
+/**
+ * Build the agent's knowledge graph: entity nodes + co-occurrence edges.
+ * @returns {Promise<{nodes:Array<object>, edges:Array<object>, stats:object}>}
+ */
+export async function buildGraph(agentId, { limit = 200 } = {}) {
+ await ensureEntities(agentId).catch(() => {});
+
+ const entities = await sql`
+ SELECT id, kind, label, normalized, salience, mention_count, first_seen_at, last_seen_at, meta
+ FROM agent_memory_entities
+ WHERE agent_id = ${agentId}
+ ORDER BY mention_count DESC, last_seen_at DESC
+ LIMIT ${limit}
+ `;
+ if (!entities.length) return { nodes: [], edges: [], stats: { entities: 0, edges: 0 } };
+
+ const ids = entities.map((e) => e.id);
+ const links = await sql`
+ SELECT entity_id, memory_id FROM agent_memory_entity_links
+ WHERE entity_id = ANY(${ids})
+ `;
+
+ // Group entities by the memory they co-occur in; every pair in a memory is an edge.
+ const byMemory = new Map();
+ for (const l of links) {
+ if (!byMemory.has(l.memory_id)) byMemory.set(l.memory_id, []);
+ byMemory.get(l.memory_id).push(l.entity_id);
+ }
+ const edgeWeights = new Map();
+ for (const entIds of byMemory.values()) {
+ const uniq = [...new Set(entIds)];
+ for (let i = 0; i < uniq.length; i++) {
+ for (let j = i + 1; j < uniq.length; j++) {
+ const [a, b] = uniq[i] < uniq[j] ? [uniq[i], uniq[j]] : [uniq[j], uniq[i]];
+ const key = `${a}|${b}`;
+ edgeWeights.set(key, (edgeWeights.get(key) || 0) + 1);
+ }
+ }
+ }
+
+ const nodes = entities.map((e) => ({
+ id: e.id,
+ kind: e.kind,
+ label: e.label,
+ salience: e.salience,
+ mentions: e.mention_count,
+ firstSeenAt: e.first_seen_at ? new Date(e.first_seen_at).getTime() : null,
+ lastSeenAt: e.last_seen_at ? new Date(e.last_seen_at).getTime() : null,
+ meta: e.meta || {},
+ }));
+ const edges = [...edgeWeights.entries()].map(([key, weight]) => {
+ const [source, target] = key.split('|');
+ return { source, target, weight };
+ });
+ return { nodes, edges, stats: { entities: nodes.length, edges: edges.length } };
+}
+
+/**
+ * Memories that mention a given entity (by id) — powers "what does my agent
+ * remember about <mint>?" and graph-node drilldown.
+ */
+export async function memoriesForEntity(agentId, entityId, { limit = 50 } = {}) {
+ const rows = await sql`
+ SELECT m.id, m.agent_id, m.type, m.content, m.tags, m.context, m.salience, m.tier,
+ m.pinned, m.embedder, m.embedding, m.access_count, m.is_public, m.created_at,
+ m.updated_at, m.last_accessed_at, m.expires_at
+ FROM agent_memories m
+ JOIN agent_memory_entity_links l ON l.memory_id = m.id
+ JOIN agent_memory_entities e ON e.id = l.entity_id
+ WHERE e.id = ${entityId} AND e.agent_id = ${agentId} AND m.agent_id = ${agentId}
+ AND (m.expires_at IS NULL OR m.expires_at > now())
+ ORDER BY m.created_at DESC
+ LIMIT ${limit}
+ `;
+ return rows.map((r) => decorateMemory(r));
+}
+
+// ── Working context + token budget ──────────────────────────────────────────────
+
+/**
+ * The "in-context now" working set: pinned and working-tier memories, ordered by
+ * salience, with a live token-budget accounting so the UI can show exactly what
+ * the model carries and whether the core has overflowed its budget.
+ */
+export async function computeContext(agentId) {
+ const rows = await sql`
+ SELECT id, agent_id, type, content, tags, context, salience, tier, pinned,
+ embedder, embedding, access_count, is_public, created_at, updated_at,
+ last_accessed_at, expires_at
+ FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND (expires_at IS NULL OR expires_at > now())
+ AND (pinned = true OR tier = 'working')
+ ORDER BY pinned DESC, salience DESC, created_at DESC
+ `;
+ let tokens = 0;
+ const entries = rows.map((r) => {
+ const dec = decorateMemory(r);
+ tokens += dec.tokens;
+ return dec;
+ });
+ const [counts] = await sql`
+ SELECT
+ COUNT(*)::int AS total,
+ COUNT(*) FILTER (WHERE tier = 'working')::int AS working,
+ COUNT(*) FILTER (WHERE tier = 'recall')::int AS recall,
+ COUNT(*) FILTER (WHERE tier = 'archival')::int AS archival,
+ COUNT(*) FILTER (WHERE embedding IS NOT NULL)::int AS embedded
+ FROM agent_memories
+ WHERE agent_id = ${agentId} AND (expires_at IS NULL OR expires_at > now())
+ `;
+ return {
+ entries,
+ tokens,
+ budget: WORKING_TOKEN_BUDGET,
+ overBudget: tokens > WORKING_TOKEN_BUDGET,
+ counts: counts || { total: 0, working: 0, recall: 0, archival: 0, embedded: 0 },
+ };
+}
+
+// ── Tier assignment helper (used at write time) ──────────────────────────────────
+
+/**
+ * Default tier for a new memory: pinned/working when the caller pins it,
+ * archival for low-salience reference material, recall otherwise.
+ */
+export function defaultTier({ pinned, salience = 0.5, type } = {}) {
+ if (pinned) return 'working';
+ if (type === 'reference' && salience < 0.5) return 'archival';
+ return 'recall';
+}
diff --git a/api/_lib/migrations/20260619120000_memory_studio.sql b/api/_lib/migrations/20260619120000_memory_studio.sql
new file mode 100644
index 000000000..1ee1754ef
--- /dev/null
+++ b/api/_lib/migrations/20260619120000_memory_studio.sql
@@ -0,0 +1,77 @@
+-- Memory Studio (P2) — tiered memory + semantic search + temporal entity graph.
+--
+-- Adds the proven tiered model (Letta/MemGPT: working / recall / archival) and
+-- mem0-style add()/search() ergonomics to agent_memories, plus a Zep/Graphiti-
+-- style temporal knowledge graph of the entities (mints, tickers, wallets,
+-- people, strategies) the agent's memories mention.
+--
+-- Vectors are stored as JSONB float arrays tagged with the embedder that
+-- produced them (model id + dim), mirroring widget_knowledge_chunks. Different
+-- embedders are different vector spaces; query-time code embeds with the SAME
+-- tag and never compares across tags (api/_lib/embeddings.js scoreRowsBySpace).
+
+-- ── tiered memory + recall bookkeeping on agent_memories ──────────────────────
+alter table agent_memories add column if not exists tier text not null default 'recall'
+ check (tier in ('working', 'recall', 'archival'));
+alter table agent_memories add column if not exists embedding jsonb;
+alter table agent_memories add column if not exists embedder text; -- vector-space tag
+alter table agent_memories add column if not exists pinned boolean not null default false;
+alter table agent_memories add column if not exists last_accessed_at timestamptz;
+alter table agent_memories add column if not exists access_count integer not null default 0;
+-- Lazy-processing flag: set true once entities have been extracted + linked for
+-- this row. The search/graph read paths process any row still false, so every
+-- write path (api/agent-memory.js POST and /api/agents/:id/memories POST) is
+-- covered uniformly without coupling the writers to the extractor.
+alter table agent_memories add column if not exists entities_extracted boolean not null default false;
+
+-- Working set: pinned + high-salience rows the agent always carries in context.
+create index if not exists agent_memories_working
+ on agent_memories(agent_id, salience desc)
+ where tier = 'working' and expires_at is null;
+-- Rows still needing a vector (lazy embed cursor).
+create index if not exists agent_memories_needs_embed
+ on agent_memories(agent_id, created_at desc)
+ where embedding is null and expires_at is null;
+-- Rows still needing entity extraction (lazy graph cursor).
+create index if not exists agent_memories_needs_entities
+ on agent_memories(agent_id, created_at desc)
+ where entities_extracted = false and expires_at is null;
+
+-- ── agent_memory_entities — the nodes of the temporal knowledge graph ─────────
+-- One row per distinct (agent, normalized entity). `kind` buckets the entity:
+-- mint — a Solana token mint address (runtime data only; $THREE is the
+-- only coin the platform promotes — see CLAUDE.md)
+-- ticker — a $SYMBOL cashtag
+-- wallet — a base58 wallet / account address
+-- person — an @handle
+-- strategy — a rule/strategy tag the agent follows
+-- topic — a free tag
+create table if not exists agent_memory_entities (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ kind text not null,
+ label text not null, -- display form
+ normalized text not null, -- dedupe key (lowercased / canonical)
+ salience real not null default 0.5,
+ mention_count integer not null default 0,
+ first_seen_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now(),
+ meta jsonb not null default '{}'::jsonb,
+ unique (agent_id, kind, normalized)
+);
+create index if not exists agent_memory_entities_agent
+ on agent_memory_entities(agent_id, last_seen_at desc);
+create index if not exists agent_memory_entities_kind
+ on agent_memory_entities(agent_id, kind, mention_count desc);
+
+-- ── agent_memory_entity_links — which memory mentions which entity ────────────
+-- Edges between entities are derived at read time from co-occurrence within the
+-- same memory (two entities linked here to the same memory_id share an edge).
+create table if not exists agent_memory_entity_links (
+ entity_id uuid not null references agent_memory_entities(id) on delete cascade,
+ memory_id uuid not null references agent_memories(id) on delete cascade,
+ created_at timestamptz not null default now(),
+ primary key (entity_id, memory_id)
+);
+create index if not exists agent_memory_entity_links_memory
+ on agent_memory_entity_links(memory_id);
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 5ee595d70..1919fbf16 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -504,11 +504,63 @@ create index if not exists agent_memories_public
on agent_memories(agent_id, created_at desc)
where is_public = true and expires_at is null;
+-- Memory Studio (P2): tiered model (working/recall/archival) + recall bookkeeping
+-- + lazy embedding/entity cursors. See migrations/20260619120000_memory_studio.sql.
+alter table agent_memories add column if not exists tier text not null default 'recall'
+ check (tier in ('working', 'recall', 'archival'));
+alter table agent_memories add column if not exists embedding jsonb;
+alter table agent_memories add column if not exists embedder text;
+alter table agent_memories add column if not exists pinned boolean not null default false;
+alter table agent_memories add column if not exists last_accessed_at timestamptz;
+alter table agent_memories add column if not exists access_count integer not null default 0;
+alter table agent_memories add column if not exists entities_extracted boolean not null default false;
+
+create index if not exists agent_memories_working
+ on agent_memories(agent_id, salience desc)
+ where tier = 'working' and expires_at is null;
+create index if not exists agent_memories_needs_embed
+ on agent_memories(agent_id, created_at desc)
+ where embedding is null and expires_at is null;
+create index if not exists agent_memories_needs_entities
+ on agent_memories(agent_id, created_at desc)
+ where entities_extracted = false and expires_at is null;
+
do $$ begin
create trigger agent_memories_set_updated_at before update on agent_memories
for each row execute function set_updated_at();
exception when duplicate_object then null; end $$;
+-- ── 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-occurrence
+-- within the same memory. See migrations/20260619120000_memory_studio.sql.
+create table if not exists agent_memory_entities (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ kind text not null,
+ label text not null,
+ normalized text not null,
+ salience real not null default 0.5,
+ mention_count integer not null default 0,
+ first_seen_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now(),
+ meta jsonb not null default '{}'::jsonb,
+ unique (agent_id, kind, normalized)
+);
+create index if not exists agent_memory_entities_agent
+ on agent_memory_entities(agent_id, last_seen_at desc);
+create index if not exists agent_memory_entities_kind
+ on agent_memory_entities(agent_id, kind, mention_count desc);
+
+create table if not exists agent_memory_entity_links (
+ entity_id uuid not null references agent_memory_entities(id) on delete cascade,
+ memory_id uuid not null references agent_memories(id) on delete cascade,
+ created_at timestamptz not null default now(),
+ primary key (entity_id, memory_id)
+);
+create index if not exists agent_memory_entity_links_memory
+ on agent_memory_entity_links(memory_id);
+
-- ── agent_memory_pins — IPFS CIDs an agent has pinned ────────────────────────
-- Lets the read proxy (GET /api/agents/:id/memory/:cid) confirm the requested
-- CID belongs to this agent instead of proxying any caller-supplied CID.
diff --git a/api/agent-memory.js b/api/agent-memory.js
index b664abb8d..67801b012 100644
--- a/api/agent-memory.js
+++ b/api/agent-memory.js
@@ -13,6 +13,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.j
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
+import { decorateMemory, defaultTier, MEMORY_TIERS } from './_lib/memory-store.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
@@ -56,7 +57,10 @@ async function handleList(req, res) {
const rows = type
? await sql`
- SELECT * FROM agent_memories
+ SELECT id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at
+ FROM agent_memories
WHERE agent_id = ${agentId}
AND type = ${type}
AND (expires_at IS NULL OR expires_at > now())
@@ -65,7 +69,10 @@ async function handleList(req, res) {
LIMIT ${limit}
`
: await sql`
- SELECT * FROM agent_memories
+ SELECT id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at
+ FROM agent_memories
WHERE agent_id = ${agentId}
AND (expires_at IS NULL OR expires_at > now())
AND created_at > ${new Date(since).toISOString()}
@@ -73,7 +80,7 @@ async function handleList(req, res) {
LIMIT ${limit}
`;
- return json(res, 200, { entries: rows.map(decorateMemory) });
+ return json(res, 200, { entries: rows.map((r) => decorateMemory(r)) });
}
// ── Upsert ────────────────────────────────────────────────────────────────
@@ -100,18 +107,28 @@ async function handleUpsert(req, res) {
const validTypes = ['user', 'feedback', 'project', 'reference'];
const memType = validTypes.includes(entry.type) ? entry.type : 'project';
+ const salience = entry.salience || 0.5;
+ const pinned = entry.pinned === true;
+ const tier = MEMORY_TIERS.includes(entry.tier)
+ ? entry.tier
+ : defaultTier({ pinned, salience, type: memType });
+
// Upsert by id (idempotent — local storage may resync the same entry).
// The WHERE clause on ON CONFLICT is critical: IDs come from the client,
// so without it, user B could write an entry with user A's memory id and
// the conflict would overwrite A's content. Constrain updates to rows
// belonging to the same agent (ownership already verified above).
+ //
+ // When an upsert changes the content, the stored vector + extracted entities
+ // are stale — reset both so the lazy read-path pipeline re-embeds and
+ // re-mines the row (this is what makes an edited memory re-index itself).
const entryUpdatedAt = entry.updatedAt
? new Date(entry.updatedAt).toISOString()
: new Date().toISOString();
const [row] = entry.id
? await sql`
- INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, created_at, expires_at, updated_at)
+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, tier, pinned, created_at, expires_at, updated_at)
VALUES (
${entry.id},
${agentId},
@@ -119,7 +136,9 @@ async function handleUpsert(req, res) {
${String(entry.content || '').slice(0, 10000)},
${entry.tags || []},
${JSON.stringify(entry.context || {})}::jsonb,
- ${entry.salience || 0.5},
+ ${salience},
+ ${tier},
+ ${pinned},
${entry.createdAt ? new Date(entry.createdAt).toISOString() : new Date().toISOString()},
${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
${entryUpdatedAt}
@@ -127,20 +146,28 @@ async function handleUpsert(req, res) {
ON CONFLICT (id) DO UPDATE SET
content = EXCLUDED.content,
salience = EXCLUDED.salience,
+ tier = EXCLUDED.tier,
+ pinned = EXCLUDED.pinned,
expires_at = EXCLUDED.expires_at,
- updated_at = EXCLUDED.updated_at
+ updated_at = EXCLUDED.updated_at,
+ embedding = CASE WHEN agent_memories.content IS DISTINCT FROM EXCLUDED.content
+ THEN NULL ELSE agent_memories.embedding END,
+ entities_extracted = CASE WHEN agent_memories.content IS DISTINCT FROM EXCLUDED.content
+ THEN false ELSE agent_memories.entities_extracted END
WHERE agent_memories.agent_id = EXCLUDED.agent_id
RETURNING *
`
: await sql`
- INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, expires_at, updated_at)
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, tier, pinned, expires_at, updated_at)
VALUES (
${agentId},
${memType},
${String(entry.content || '').slice(0, 10000)},
${entry.tags || []},
${JSON.stringify(entry.context || {})}::jsonb,
- ${entry.salience || 0.5},
+ ${salience},
+ ${tier},
+ ${pinned},
${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
${entryUpdatedAt}
)
@@ -185,19 +212,3 @@ async function resolveAuth(req) {
if (bearer) return { userId: bearer.userId };
return null;
}
-
-function decorateMemory(row) {
- const createdMs = row.created_at ? new Date(row.created_at).getTime() : Date.now();
- return {
- id: row.id,
- agent_id: row.agent_id,
- type: row.type,
- content: row.content,
- tags: row.tags || [],
- context: row.context || {},
- salience: row.salience,
- createdAt: createdMs,
- updatedAt: row.updated_at ? new Date(row.updated_at).getTime() : createdMs,
- expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
- };
-}
diff --git a/api/memory/context.js b/api/memory/context.js
new file mode 100644
index 000000000..9023f8c3c
--- /dev/null
+++ b/api/memory/context.js
@@ -0,0 +1,52 @@
+/**
+ * Working context + token budget (P2 — Memory Studio)
+ * ---------------------------------------------------
+ * "What's in context right now" — the working-tier + pinned memories the agent
+ * always carries, with a live token-budget accounting so the owner can see (and
+ * trust) exactly what shapes every reply, and whether the core has overflowed.
+ *
+ * GET /api/memory/context?agentId=
+ *
+ * Owner-only. Anonymous → empty/zeroed context.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { computeContext, WORKING_TOKEN_BUDGET } from '../_lib/memory-store.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;
+}
+
+const EMPTY = {
+ entries: [],
+ tokens: 0,
+ budget: WORKING_TOKEN_BUDGET,
+ overBudget: false,
+ counts: { total: 0, working: 0, recall: 0, archival: 0, embedded: 0 },
+};
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+
+ const auth = await resolveAuth(req);
+ if (!auth) return json(res, 200, EMPTY);
+
+ const [row] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row || row.user_id !== auth.userId) return json(res, 200, EMPTY);
+
+ const ctx = await computeContext(agentId);
+ return json(res, 200, ctx);
+});
diff --git a/api/memory/curate.js b/api/memory/curate.js
new file mode 100644
index 000000000..08d6f981c
--- /dev/null
+++ b/api/memory/curate.js
@@ -0,0 +1,182 @@
+/**
+ * Memory curation (P2 — Memory Studio)
+ * ------------------------------------
+ * The trust surface: pin to the working core, retier, adjust salience, edit,
+ * merge duplicates, and forget — all owner-only, all persisted.
+ *
+ * POST /api/memory/curate { agentId, op, ... }
+ * op = 'pin' { memoryId } → tier=working, pinned=true
+ * op = 'unpin' { memoryId } → pinned=false, tier=recall
+ * op = 'tier' { memoryId, tier } → working|recall|archival
+ * op = 'salience' { memoryId, salience } → 0..1
+ * op = 'edit' { memoryId, content?, tags? } → re-embeds + re-mines
+ * op = 'merge' { memoryIds:[target, ...dupes] } → fold dupes into target
+ * op = 'forget' { memoryId } → delete
+ *
+ * CSRF-gated.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { MEMORY_TIERS, decorateMemory } from '../_lib/memory-store.js';
+
+const RETURN_COLS = `id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at`;
+
+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;
+ const op = body.op;
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ if (!op) return error(res, 400, 'validation_error', 'op required');
+
+ const [agentRow] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ switch (op) {
+ case 'pin':
+ return updateOne(res, agentId, body.memoryId, sql`pinned = true, tier = 'working'`);
+ case 'unpin':
+ return updateOne(res, agentId, body.memoryId, sql`pinned = false, tier = 'recall'`);
+ case 'tier': {
+ if (!MEMORY_TIERS.includes(body.tier)) return error(res, 400, 'validation_error', 'invalid tier');
+ const pinExpr = body.tier === 'working' ? sql`pinned = true` : sql`pinned = pinned`;
+ return updateOne(res, agentId, body.memoryId, sql`tier = ${body.tier}, ${pinExpr}`);
+ }
+ case 'salience': {
+ const s = Number(body.salience);
+ if (!Number.isFinite(s) || s < 0 || s > 1) return error(res, 400, 'validation_error', 'salience must be 0..1');
+ return updateOne(res, agentId, body.memoryId, sql`salience = ${s}`);
+ }
+ case 'edit':
+ return handleEdit(res, agentId, body);
+ case 'merge':
+ return handleMerge(res, agentId, body);
+ case 'forget': {
+ if (!body.memoryId) return error(res, 400, 'validation_error', 'memoryId required');
+ const [row] = await sql`
+ DELETE FROM agent_memories WHERE id = ${body.memoryId} AND agent_id = ${agentId} RETURNING id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+ return json(res, 200, { ok: true, forgot: row.id });
+ }
+ default:
+ return error(res, 400, 'validation_error', `unknown op: ${op}`);
+ }
+});
+
+async function updateOne(res, agentId, memoryId, setExpr) {
+ if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');
+ const [row] = await sql`
+ UPDATE agent_memories SET ${setExpr}, updated_at = now()
+ WHERE id = ${memoryId} AND agent_id = ${agentId}
+ RETURNING id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+ return json(res, 200, { entry: decorateMemory(row) });
+}
+
+async function handleEdit(res, agentId, body) {
+ if (!body.memoryId) return error(res, 400, 'validation_error', 'memoryId required');
+ const hasContent = typeof body.content === 'string';
+ const hasTags = Array.isArray(body.tags);
+ if (!hasContent && !hasTags) return error(res, 400, 'validation_error', 'content or tags required');
+
+ const content = hasContent ? body.content.slice(0, 10000) : null;
+ const tags = hasTags ? body.tags.map((t) => String(t).slice(0, 100)).slice(0, 30) : null;
+
+ // Changing content invalidates the vector + extracted entities — null them so
+ // the lazy read-path re-embeds and re-mines.
+ const [row] = await sql`
+ UPDATE agent_memories SET
+ content = COALESCE(${content}, content),
+ tags = COALESCE(${tags}::text[], tags),
+ embedding = CASE WHEN ${content}::text IS NOT NULL AND content IS DISTINCT FROM ${content}
+ THEN NULL ELSE embedding END,
+ entities_extracted = CASE WHEN ${content}::text IS NOT NULL AND content IS DISTINCT FROM ${content}
+ THEN false ELSE entities_extracted END,
+ updated_at = now()
+ WHERE id = ${body.memoryId} AND agent_id = ${agentId}
+ RETURNING id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+ // Editing tags also changes the entity surface — re-mine on next graph read.
+ if (hasTags) {
+ await sql`UPDATE agent_memories SET entities_extracted = false WHERE id = ${body.memoryId}`;
+ }
+ return json(res, 200, { entry: decorateMemory(row) });
+}
+
+async function handleMerge(res, agentId, body) {
+ const ids = Array.isArray(body.memoryIds) ? body.memoryIds.filter(Boolean) : [];
+ if (ids.length < 2) return error(res, 400, 'validation_error', 'merge needs at least 2 memoryIds');
+ const [targetId, ...dupeIds] = ids;
+
+ const rows = await sql`
+ SELECT id, content, tags, salience, type FROM agent_memories
+ WHERE id = ANY(${ids}) AND agent_id = ${agentId}
+ `;
+ if (rows.length < 2) return error(res, 404, 'not_found', 'memories not found');
+
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ const target = byId.get(targetId);
+ if (!target) return error(res, 404, 'not_found', 'target memory not found');
+
+ // Fold: union the distinct contents (keep target first), union tags, take the
+ // max salience. Reset the vector + entities so the merged memory re-indexes.
+ const seenContent = new Set();
+ const contents = [];
+ for (const id of ids) {
+ const r = byId.get(id);
+ if (!r) continue;
+ const c = String(r.content || '').trim();
+ if (c && !seenContent.has(c)) { seenContent.add(c); contents.push(c); }
+ }
+ const mergedContent = contents.join('\n\n').slice(0, 10000);
+ const mergedTags = [...new Set(rows.flatMap((r) => r.tags || []))].slice(0, 30);
+ const mergedSalience = Math.max(...rows.map((r) => r.salience || 0));
+
+ const presentDupes = dupeIds.filter((id) => byId.has(id));
+ const [updated] = await sql`
+ UPDATE agent_memories SET
+ content = ${mergedContent},
+ tags = ${mergedTags},
+ salience = ${mergedSalience},
+ embedding = NULL,
+ entities_extracted = false,
+ updated_at = now()
+ WHERE id = ${targetId} AND agent_id = ${agentId}
+ RETURNING id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
+ (embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ created_at, updated_at, last_accessed_at, expires_at
+ `;
+ if (presentDupes.length) {
+ await sql`DELETE FROM agent_memories WHERE id = ANY(${presentDupes}) AND agent_id = ${agentId}`;
+ }
+ return json(res, 200, { entry: decorateMemory(updated), merged: presentDupes.length });
+}
diff --git a/api/memory/graph.js b/api/memory/graph.js
new file mode 100644
index 000000000..1a9c37731
--- /dev/null
+++ b/api/memory/graph.js
@@ -0,0 +1,53 @@
+/**
+ * Memory knowledge graph (P2 — Memory Studio)
+ * -------------------------------------------
+ * The Zep/Graphiti-style temporal knowledge graph: entities (mints, tickers,
+ * wallets, people, strategies, topics) the agent's memories mention, plus
+ * co-occurrence edges. Lazily mines any not-yet-processed memories on read.
+ *
+ * GET /api/memory/graph?agentId= — full graph (nodes + edges)
+ * GET /api/memory/graph?agentId=&entityId= — memories mentioning one entity
+ *
+ * Owner-only. Anonymous → empty graph.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { buildGraph, memoriesForEntity } from '../_lib/memory-store.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;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const entityId = url.searchParams.get('entityId');
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+
+ const auth = await resolveAuth(req);
+ if (!auth) return json(res, 200, { nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
+
+ const [row] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row || row.user_id !== auth.userId) {
+ return json(res, 200, { nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
+ }
+
+ if (entityId) {
+ const memories = await memoriesForEntity(agentId, entityId);
+ return json(res, 200, { memories });
+ }
+
+ const graph = await buildGraph(agentId);
+ return json(res, 200, graph);
+});
diff --git a/api/memory/search.js b/api/memory/search.js
new file mode 100644
index 000000000..d724d3878
--- /dev/null
+++ b/api/memory/search.js
@@ -0,0 +1,96 @@
+/**
+ * Memory semantic search (P2 — Memory Studio)
+ * -------------------------------------------
+ * The mem0 search() surface over the tiered store. Embeds the query in each
+ * stored vector space and returns ranked memories with real cosine scores; falls
+ * back to substring + salience when no embedding provider is configured.
+ *
+ * GET /api/memory/search?agentId=&q=&topK=&minScore=&tier=working,recall — recall
+ * (used by the Brain Memory node; cookie auth, no CSRF, side effects are
+ * only the agent-owner's own access counters)
+ * POST /api/memory/search { agentId, query, topK, minScore, tiers, type } — studio
+ *
+ * Owner-only. Anonymous GET returns an empty result set (keeps embed consoles clean).
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { searchMemories } from '../_lib/memory-store.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 ownsAgent(agentId, userId) {
+ if (!agentId || !userId) return false;
+ const [row] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ return !!row && row.user_id === userId;
+}
+
+function parseTiers(raw) {
+ if (!raw) return null;
+ const list = (Array.isArray(raw) ? raw : String(raw).split(','))
+ .map((s) => String(s).trim())
+ .filter(Boolean);
+ return list.length ? list : null;
+}
+
+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 (req.method === 'GET') {
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const query = url.searchParams.get('q') || url.searchParams.get('query') || '';
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ // Anonymous / non-owner → empty (no leak, no console noise on public embeds).
+ if (!auth || !(await ownsAgent(agentId, auth.userId))) return json(res, 200, { results: [] });
+
+ const out = await searchMemories(agentId, query, {
+ topK: clampInt(url.searchParams.get('topK'), 8, 1, 50),
+ minScore: clampFloat(url.searchParams.get('minScore'), 0.25, 0, 1),
+ tiers: parseTiers(url.searchParams.get('tier')),
+ type: url.searchParams.get('type') || undefined,
+ });
+ return json(res, 200, out);
+ }
+
+ // POST — studio search (CSRF-gated).
+ 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');
+ if (!(await ownsAgent(agentId, auth.userId))) return error(res, 403, 'forbidden', 'not your agent');
+
+ const out = await searchMemories(agentId, String(body.query || ''), {
+ topK: clampInt(body.topK, 8, 1, 50),
+ minScore: clampFloat(body.minScore, 0.25, 0, 1),
+ tiers: parseTiers(body.tiers),
+ type: body.type || undefined,
+ });
+ return json(res, 200, out);
+});
+
+function clampInt(v, dflt, min, max) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return dflt;
+ return Math.min(max, Math.max(min, Math.round(n)));
+}
+function clampFloat(v, dflt, min, max) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return dflt;
+ return Math.min(max, Math.max(min, n));
+}
diff --git a/src/agent-memory.js b/src/agent-memory.js
index 56f3aab0f..228c874b4 100644
--- a/src/agent-memory.js
+++ b/src/agent-memory.js
@@ -134,6 +134,17 @@ export class AgentMemory {
* @returns {Promise<MemoryEntry[]>}
*/
async recall(queryText, { type, limit = 10, minScore = 0.75 } = {}) {
+ // Backend-confirmed agents recall through the real tiered store
+ // (api/memory/search): server-side embeddings + semantic search across
+ // EVERY persisted memory — not just what this device cached. This is the
+ // path the Brain's Memory node (P1) relies on for real recall. Any
+ // failure (offline, unconfigured provider) falls through to the local
+ // cosine/substring engine below, so recall never hard-fails.
+ if (this.backendSync && this.agentId) {
+ const remote = await this._recallServer(queryText, { type, limit }).catch(() => null);
+ if (remote && remote.length) return remote;
+ }
+
if (!this.embedFn) return this.query({ type, limit });
const now = Date.now();
@@ -176,6 +187,36 @@ export class AgentMemory {
return combined.slice(0, limit);
}
+ /**
+ * Recall via the server's tiered semantic store (api/memory/search). Returns
+ * decorated memory entries ranked by real cosine similarity (with a lexical
+ * fallback server-side), or null on any failure so the caller degrades to the
+ * local engine. GET + cookie auth — no CSRF needed, owner-scoped server-side.
+ * @param {string} queryText
+ * @param {{ type?: string, limit?: number }} [opts]
+ * @returns {Promise<MemoryEntry[]|null>}
+ */
+ async _recallServer(queryText, { type, limit = 10 } = {}) {
+ const q = String(queryText || '').trim();
+ if (!q) return null;
+ const params = new URLSearchParams({ agentId: this.agentId, q, topK: String(limit) });
+ if (type) params.set('type', type);
+ const resp = await fetch(`/api/memory/search?${params}`, { credentials: 'include' });
+ if (!resp.ok) return null;
+ const { results } = await resp.json();
+ if (!Array.isArray(results)) return null;
+ return results.map((r) => ({
+ id: r.id,
+ type: r.type,
+ content: r.content,
+ tags: r.tags || [],
+ salience: r.salience,
+ score: r.score ?? null,
+ tier: r.tier,
+ createdAt: r.createdAt,
+ }));
+ }
+
/**
* Remove a memory by id.
* @param {string} id
diff --git a/src/studio/memory/memory-client.js b/src/studio/memory/memory-client.js
new file mode 100644
index 000000000..3449020fa
--- /dev/null
+++ b/src/studio/memory/memory-client.js
@@ -0,0 +1,119 @@
+/**
+ * Memory Studio — API client (P2)
+ * ===============================
+ * Thin, typed wrapper over the real memory API surface. Every call goes through
+ * the shared `apiFetch` (CSRF + session cookie handled). This is the surface the
+ * Memory Studio UI binds to — and the same endpoints P1's Brain Memory node and
+ * P4's trade history coordinate against.
+ *
+ * Endpoints
+ * GET /api/agent-memory?agentId= — list (tier/pinned/embedder-aware)
+ * POST /api/agent-memory — add / upsert a memory
+ * POST /api/memory/search — semantic search (mem0 search())
+ * GET /api/memory/context?agentId= — working set + token budget
+ * GET /api/memory/graph?agentId= — entity knowledge graph
+ * GET /api/memory/graph?agentId=&entityId= — memories mentioning an entity
+ * POST /api/memory/curate — pin/tier/salience/edit/merge/forget
+ */
+
+import { apiFetch } from '../../api.js';
+
+function uuid() {
+ return crypto.randomUUID ? crypto.randomUUID()
+ : 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
+ const r = (Math.random() * 16) | 0;
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
+ });
+}
+
+export class MemoryClient {
+ constructor(agentId) {
+ this.agentId = agentId;
+ }
+
+ async _json(resp) {
+ if (!resp.ok) {
+ const body = await resp.json().catch(() => ({}));
+ throw new Error(body?.error_description || body?.error?.message || body?.error || `HTTP ${resp.status}`);
+ }
+ return resp.json();
+ }
+
+ /** List all memories for the agent (newest first). */
+ async list({ limit = 500, type } = {}) {
+ const params = new URLSearchParams({ agentId: this.agentId, limit: String(limit) });
+ if (type) params.set('type', type);
+ const resp = await apiFetch(`/api/agent-memory?${params}`);
+ const { entries } = await this._json(resp);
+ return entries || [];
+ }
+
+ /** Add a memory. Returns the created/updated entry. */
+ async add(entry) {
+ const payload = {
+ id: entry.id || uuid(),
+ type: entry.type || 'project',
+ content: entry.content,
+ tags: entry.tags || [],
+ salience: entry.salience ?? 0.5,
+ tier: entry.tier,
+ pinned: entry.pinned === true,
+ context: entry.context || {},
+ };
+ const resp = await apiFetch('/api/agent-memory', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: this.agentId, entry: payload }),
+ });
+ const { entry: saved } = await this._json(resp);
+ return saved;
+ }
+
+ /** Semantic search across the tiered store. */
+ async search(query, { topK = 12, minScore = 0.25, tiers, type } = {}) {
+ const resp = await apiFetch('/api/memory/search', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: this.agentId, query, topK, minScore, tiers, type }),
+ });
+ return this._json(resp);
+ }
+
+ /** The working set in context now + token budget. */
+ async context() {
+ const resp = await apiFetch(`/api/memory/context?agentId=${encodeURIComponent(this.agentId)}`);
+ return this._json(resp);
+ }
+
+ /** The entity knowledge graph (nodes + co-occurrence edges). */
+ async graph() {
+ const resp = await apiFetch(`/api/memory/graph?agentId=${encodeURIComponent(this.agentId)}`);
+ return this._json(resp);
+ }
+
+ /** Memories that mention one entity (graph drilldown / trade-aware queries). */
+ async entityMemories(entityId) {
+ const params = new URLSearchParams({ agentId: this.agentId, entityId });
+ const resp = await apiFetch(`/api/memory/graph?${params}`);
+ const { memories } = await this._json(resp);
+ return memories || [];
+ }
+
+ /** Curation ops. */
+ async curate(op, payload = {}) {
+ const resp = await apiFetch('/api/memory/curate', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: this.agentId, op, ...payload }),
+ });
+ return this._json(resp);
+ }
+
+ pin(memoryId) { return this.curate('pin', { memoryId }); }
+ unpin(memoryId) { return this.curate('unpin', { memoryId }); }
+ setTier(memoryId, tier) { return this.curate('tier', { memoryId, tier }); }
+ setSalience(memoryId, salience) { return this.curate('salience', { memoryId, salience }); }
+ edit(memoryId, fields) { return this.curate('edit', { memoryId, ...fields }); }
+ merge(memoryIds) { return this.curate('merge', { memoryIds }); }
+ forget(memoryId) { return this.curate('forget', { memoryId }); }
+}
diff --git a/src/studio/memory/memory-graph.js b/src/studio/memory/memory-graph.js
new file mode 100644
index 000000000..375582999
--- /dev/null
+++ b/src/studio/memory/memory-graph.js
@@ -0,0 +1,240 @@
+/**
+ * Memory Studio — knowledge graph renderer (P2)
+ * =============================================
+ * A dependency-free canvas force-directed graph of the agent's memory entities.
+ * Nodes are coins/tickers/wallets/people/strategies/topics; edges are
+ * co-occurrence within a memory. Click a node to drill into the memories that
+ * formed it. Honors prefers-reduced-motion (settles instantly, no idle anim).
+ */
+
+const KIND_COLOR = {
+ mint: '#8b5cf6',
+ ticker: '#22d3ee',
+ wallet: '#f59e0b',
+ person: '#ec4899',
+ strategy: '#4ade80',
+ topic: '#94a3b8',
+};
+
+const KIND_GLYPH = {
+ mint: '◎',
+ ticker: '$',
+ wallet: '⬡',
+ person: '@',
+ strategy: '★',
+ topic: '#',
+};
+
+export class MemoryGraph {
+ constructor(canvas, { onSelect } = {}) {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d');
+ this.onSelect = onSelect || (() => {});
+ this.nodes = [];
+ this.edges = [];
+ this.selected = null;
+ this.hover = null;
+ this._raf = null;
+ this._alpha = 0;
+ this._dpr = Math.min(window.devicePixelRatio || 1, 2);
+ this._reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+
+ this._onResize = () => this._resize();
+ window.addEventListener('resize', this._onResize);
+ canvas.addEventListener('pointermove', (e) => this._onPointerMove(e));
+ canvas.addEventListener('pointerleave', () => { this.hover = null; this.canvas.style.cursor = 'default'; });
+ canvas.addEventListener('click', (e) => this._onClick(e));
+ this._resize();
+ }
+
+ destroy() {
+ cancelAnimationFrame(this._raf);
+ window.removeEventListener('resize', this._onResize);
+ }
+
+ _resize() {
+ const rect = this.canvas.getBoundingClientRect();
+ this.w = Math.max(rect.width, 1);
+ this.h = Math.max(rect.height, 1);
+ this.canvas.width = this.w * this._dpr;
+ this.canvas.height = this.h * this._dpr;
+ this.ctx.setTransform(this._dpr, 0, 0, this._dpr, 0, 0);
+ this._draw();
+ }
+
+ setData({ nodes, edges }) {
+ const prev = new Map(this.nodes.map((n) => [n.id, n]));
+ const maxMentions = Math.max(1, ...nodes.map((n) => n.mentions || 1));
+ this.nodes = nodes.map((n) => {
+ const old = prev.get(n.id);
+ return {
+ ...n,
+ r: 6 + 10 * Math.sqrt((n.mentions || 1) / maxMentions),
+ x: old?.x ?? this.w / 2 + (Math.random() - 0.5) * this.w * 0.6,
+ y: old?.y ?? this.h / 2 + (Math.random() - 0.5) * this.h * 0.6,
+ vx: 0,
+ vy: 0,
+ };
+ });
+ this._index = new Map(this.nodes.map((n) => [n.id, n]));
+ this.edges = edges
+ .map((e) => ({ ...e, s: this._index.get(e.source), t: this._index.get(e.target) }))
+ .filter((e) => e.s && e.t);
+ this._alpha = 1;
+ this._run();
+ }
+
+ _run() {
+ cancelAnimationFrame(this._raf);
+ const step = () => {
+ this._tick();
+ this._draw();
+ if (this._alpha > 0.01 && !this._reduced) {
+ this._raf = requestAnimationFrame(step);
+ }
+ };
+ if (this._reduced) {
+ for (let i = 0; i < 220; i++) this._tick(); // settle synchronously
+ this._draw();
+ } else {
+ this._raf = requestAnimationFrame(step);
+ }
+ }
+
+ _tick() {
+ const cx = this.w / 2;
+ const cy = this.h / 2;
+ const nodes = this.nodes;
+ // Repulsion (O(n²) — capped node count keeps this cheap).
+ for (let i = 0; i < nodes.length; i++) {
+ const a = nodes[i];
+ a.fx = (cx - a.x) * 0.002; // center gravity
+ a.fy = (cy - a.y) * 0.002;
+ for (let j = 0; j < nodes.length; j++) {
+ if (i === j) continue;
+ const b = nodes[j];
+ let dx = a.x - b.x;
+ let dy = a.y - b.y;
+ let d2 = dx * dx + dy * dy || 0.01;
+ const f = 900 / d2;
+ a.fx += dx * f;
+ a.fy += dy * f;
+ }
+ }
+ // Attraction along edges.
+ for (const e of this.edges) {
+ const dx = e.t.x - e.s.x;
+ const dy = e.t.y - e.s.y;
+ const dist = Math.sqrt(dx * dx + dy * dy) || 0.01;
+ const k = 0.0008 * Math.min(e.weight, 6) * (dist - 90);
+ const fx = dx * k;
+ const fy = dy * k;
+ e.s.fx += fx; e.s.fy += fy;
+ e.t.fx -= fx; e.t.fy -= fy;
+ }
+ const damp = 0.82;
+ for (const n of nodes) {
+ n.vx = (n.vx + n.fx) * damp;
+ n.vy = (n.vy + n.fy) * damp;
+ n.x += n.vx * this._alpha;
+ n.y += n.vy * this._alpha;
+ n.x = Math.max(n.r, Math.min(this.w - n.r, n.x));
+ n.y = Math.max(n.r, Math.min(this.h - n.r, n.y));
+ }
+ this._alpha *= 0.985;
+ }
+
+ _draw() {
+ const ctx = this.ctx;
+ ctx.clearRect(0, 0, this.w, this.h);
+ if (!this.nodes.length) return;
+
+ const sel = this.selected;
+ const neighbors = new Set();
+ if (sel) {
+ for (const e of this.edges) {
+ if (e.s.id === sel) neighbors.add(e.t.id);
+ if (e.t.id === sel) neighbors.add(e.s.id);
+ }
+ }
+
+ // Edges.
+ for (const e of this.edges) {
+ const active = sel && (e.s.id === sel || e.t.id === sel);
+ ctx.strokeStyle = active ? 'rgba(139,92,246,0.55)' : 'rgba(255,255,255,0.07)';
+ ctx.lineWidth = active ? 1.6 : 0.8;
+ ctx.beginPath();
+ ctx.moveTo(e.s.x, e.s.y);
+ ctx.lineTo(e.t.x, e.t.y);
+ ctx.stroke();
+ }
+
+ // Nodes.
+ for (const n of this.nodes) {
+ const dim = sel && n.id !== sel && !neighbors.has(n.id);
+ const color = KIND_COLOR[n.kind] || '#94a3b8';
+ ctx.globalAlpha = dim ? 0.25 : 1;
+ ctx.beginPath();
+ ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
+ ctx.fillStyle = color;
+ ctx.fill();
+ if (n.id === sel || n.id === this.hover) {
+ ctx.lineWidth = 2;
+ ctx.strokeStyle = '#fff';
+ ctx.stroke();
+ }
+ // Label for larger / focused nodes.
+ if (n.r > 10 || n.id === this.hover || n.id === sel) {
+ ctx.globalAlpha = dim ? 0.3 : 0.92;
+ ctx.fillStyle = '#fff';
+ ctx.font = '11px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ const label = n.label.length > 16 ? n.label.slice(0, 15) + '…' : n.label;
+ ctx.fillText(label, n.x, n.y + n.r + 12);
+ }
+ ctx.globalAlpha = 1;
+ }
+ }
+
+ _nodeAt(x, y) {
+ // Topmost (last drawn) wins.
+ for (let i = this.nodes.length - 1; i >= 0; i--) {
+ const n = this.nodes[i];
+ const dx = x - n.x;
+ const dy = y - n.y;
+ if (dx * dx + dy * dy <= (n.r + 4) * (n.r + 4)) return n;
+ }
+ return null;
+ }
+
+ _localPoint(e) {
+ const rect = this.canvas.getBoundingClientRect();
+ return { x: e.clientX - rect.left, y: e.clientY - rect.top };
+ }
+
+ _onPointerMove(e) {
+ const { x, y } = this._localPoint(e);
+ const n = this._nodeAt(x, y);
+ const id = n?.id || null;
+ if (id !== this.hover) {
+ this.hover = id;
+ this.canvas.style.cursor = id ? 'pointer' : 'default';
+ if (this._alpha <= 0.01) this._draw();
+ }
+ }
+
+ _onClick(e) {
+ const { x, y } = this._localPoint(e);
+ const n = this._nodeAt(x, y);
+ this.select(n ? n.id : null);
+ this.onSelect(n || null);
+ }
+
+ select(id) {
+ this.selected = id;
+ this._draw();
+ }
+
+ static color(kind) { return KIND_COLOR[kind] || '#94a3b8'; }
+ static glyph(kind) { return KIND_GLYPH[kind] || '#'; }
+}
diff --git a/src/studio/memory/memory-mount.js b/src/studio/memory/memory-mount.js
new file mode 100644
index 000000000..20e3c4d66
--- /dev/null
+++ b/src/studio/memory/memory-mount.js
@@ -0,0 +1,31 @@
+/**
+ * Memory Studio — mount bootstrap (P2)
+ * ====================================
+ * Binds the Memory Studio to the Agent Studio shell's Memory tab on
+ * `studio-shell:ready`. Mirrors P1's brain-mount: idempotent and
+ * order-independent (handles both event-after-subscribe and already-ready).
+ *
+ * The agent-studio page loads this alongside the shell:
+ * <script type="module" src="/src/studio/memory/memory-mount.js"></script>
+ */
+
+import { studio } from '../agent-studio-store.js';
+import { mountMemoryStudio } from './memory-studio.js';
+
+const SELECTOR = '[data-studio-mount="memory"]';
+
+function mount() {
+ const panel = document.querySelector(SELECTOR);
+ if (!panel || panel.dataset.memoryMounted) return false;
+ mountMemoryStudio(panel, { studio });
+ return true;
+}
+
+document.addEventListener('studio-shell:ready', mount, { once: false });
+
+if (!mount()) {
+ let tries = 0;
+ const t = setInterval(() => {
+ if (mount() || ++tries > 60) clearInterval(t); // ~6s ceiling
+ }, 100);
+}
diff --git a/src/studio/memory/memory-studio.js b/src/studio/memory/memory-studio.js
new file mode 100644
index 000000000..fac3cca6e
--- /dev/null
+++ b/src/studio/memory/memory-studio.js
@@ -0,0 +1,868 @@
+/**
+ * Memory Studio — controller (P2)
+ * ===============================
+ * The visual memory surface: watch memories form, curate them, and trust them.
+ * Mounts into the Agent Studio shell's Memory tab and wires:
+ * • Timeline — a live, scrollable stream of memories forming over time, with
+ * pin / edit / merge / forget / salience / tier curation.
+ * • Graph — the temporal knowledge graph (entities + co-occurrence edges),
+ * with per-entity drilldown + "memory replay" (how the agent's
+ * understanding of a coin evolved over time).
+ * • In context — the working set + live token budget: exactly what the agent
+ * carries into every reply.
+ * • Recall — real semantic search (mem0 search()) with scores + trade-aware
+ * quick queries.
+ *
+ * Every write flows through the real API and emits `studio.emit('memory:change')`
+ * + a market event so the Brain (P1) and the live avatar react.
+ *
+ * Mount: import { mountMemoryStudio } from './memory/memory-studio.js';
+ * mountMemoryStudio(container, { studio });
+ */
+
+import { MemoryClient } from './memory-client.js';
+import { MemoryGraph } from './memory-graph.js';
+import { fetchConnector, synthesizeMemorySeed, saveMemoryToAgent } from '../../memory-seed.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function relTime(ts) {
+ if (!ts) return '';
+ const d = Date.now() - ts;
+ if (d < 0) return 'just now';
+ if (d < 60000) return 'just now';
+ if (d < 3600000) return Math.floor(d / 60000) + 'm ago';
+ if (d < 86400000) return Math.floor(d / 3600000) + 'h ago';
+ if (d < 2592000000) return Math.floor(d / 86400000) + 'd ago';
+ return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+const TYPE_LABEL = { user: 'User', feedback: 'Feedback', project: 'Project', reference: 'Reference' };
+const TIERS = [
+ { key: 'working', label: 'Working', hint: 'Always in context — the core.' },
+ { key: 'recall', label: 'Recall', hint: 'Recent, searchable.' },
+ { key: 'archival', label: 'Archival', hint: 'Long-term, semantic.' },
+];
+const KIND_LABEL = { mint: 'Coins', ticker: 'Tickers', wallet: 'Wallets', person: 'People', strategy: 'Strategies', topic: 'Topics' };
+
+export function mountMemoryStudio(container, { studio }) {
+ if (container.dataset.memoryMounted) return;
+ container.dataset.memoryMounted = '1';
+ container.querySelector('.studio-empty')?.remove();
+ return new MemoryStudio(container, studio);
+}
+
+class MemoryStudio {
+ constructor(el, studio) {
+ this.el = el;
+ this.studio = studio;
+ this.agentId = studio.agent?.id;
+ this.client = new MemoryClient(this.agentId);
+
+ this.state = {
+ view: 'timeline',
+ loading: true,
+ error: null,
+ memories: [],
+ context: null,
+ graph: null,
+ filter: { type: '', tier: '', q: '' },
+ selection: new Set(),
+ mergeMode: false,
+ search: null, // { query, results, provider, scored }
+ entity: null, // { node, memories, replay }
+ renderLimit: 60,
+ };
+ this._knownIds = new Set();
+ this._graph = null;
+
+ this._render();
+ this._load();
+ }
+
+ // ── Data ────────────────────────────────────────────────────────────────
+
+ async _load() {
+ this.state.loading = true;
+ this._renderBody();
+ try {
+ const [memories, context] = await Promise.all([
+ this.client.list(),
+ this.client.context().catch(() => null),
+ ]);
+ this.state.memories = memories;
+ this.state.context = context;
+ this.state.loading = false;
+ this.state.error = null;
+ memories.forEach((m) => this._knownIds.add(m.id));
+ this._renderQuick();
+ } catch (err) {
+ this.state.loading = false;
+ this.state.error = err.message || 'Could not load memories.';
+ }
+ this._renderBody();
+ }
+
+ async _refreshContext() {
+ this.state.context = await this.client.context().catch(() => this.state.context);
+ if (this.state.view === 'context') this._renderBody();
+ this._renderQuick();
+ }
+
+ _emitChange(detail) {
+ try { this.studio.emit('memory:change', detail || {}); } catch {}
+ }
+
+ // ── Shell ─────────────────────────────────────────────────────────────────
+
+ _render() {
+ this.el.innerHTML = `
+ <div class="mem">
+ <header class="mem-top">
+ <form class="mem-recall" data-recall-form role="search">
+ <svg class="mem-recall-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 21l-4.3-4.3M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
+ <input class="mem-recall-input" data-search type="search" autocomplete="off"
+ placeholder="Recall — ask what your agent knows…" aria-label="Search memories" />
+ <button class="mem-btn mem-btn-accent" type="submit" data-do-search>Recall</button>
+ </form>
+ <div class="mem-quick" data-quick aria-label="Quick recalls"></div>
+ <div class="mem-toolbar">
+ <nav class="mem-views" role="tablist" aria-label="Memory views">
+ <button class="mem-view active" role="tab" data-view="timeline" aria-selected="true">Timeline</button>
+ <button class="mem-view" role="tab" data-view="graph" aria-selected="false">Graph</button>
+ <button class="mem-view" role="tab" data-view="context" aria-selected="false">In context</button>
+ </nav>
+ <div class="mem-actions">
+ <button class="mem-btn mem-btn-ghost" data-action="seed" title="Synthesize memory from your accounts">Seed</button>
+ <button class="mem-btn" data-action="add" title="Add a memory">+ Memory</button>
+ </div>
+ </div>
+ </header>
+ <div class="mem-subbar" data-subbar></div>
+ <div class="mem-body" data-body tabindex="0"></div>
+ <div class="mem-merge-bar" data-merge-bar hidden>
+ <span data-merge-count>0 selected</span>
+ <button class="mem-btn mem-btn-sm" data-action="merge-commit">Merge into oldest</button>
+ <button class="mem-btn mem-btn-sm mem-btn-ghost" data-action="merge-cancel">Cancel</button>
+ </div>
+ <div class="mem-toast" data-toast hidden></div>
+ </div>`;
+ this._bind();
+ this._renderSubbar();
+ }
+
+ _q(sel) { return this.el.querySelector(sel); }
+
+ _bind() {
+ this.el.querySelector('[data-recall-form]').addEventListener('submit', (e) => {
+ e.preventDefault();
+ this._runSearch(this._q('[data-search]').value.trim());
+ });
+ this._q('[data-search]').addEventListener('input', (e) => {
+ if (!e.target.value.trim() && this.state.search) {
+ this.state.search = null;
+ this._renderBody();
+ }
+ });
+ this.el.querySelectorAll('[data-view]').forEach((b) =>
+ b.addEventListener('click', () => this._selectView(b.dataset.view)));
+ this.el.querySelector('.mem-actions').addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action]');
+ if (!btn) return;
+ if (btn.dataset.action === 'add') this._openAddForm();
+ if (btn.dataset.action === 'seed') this._openSeed();
+ });
+ this._q('[data-merge-bar]').addEventListener('click', (e) => {
+ const a = e.target.closest('[data-action]')?.dataset.action;
+ if (a === 'merge-commit') this._commitMerge();
+ if (a === 'merge-cancel') this._exitMergeMode();
+ });
+ // Delegated curation + interactions on the body. Bound on the persistent
+ // body element so they survive inner re-renders.
+ const body = this._q('[data-body]');
+ body.addEventListener('click', (e) => this._onBodyClick(e));
+ body.addEventListener('scroll', () => this._onScroll());
+ body.addEventListener('change', (e) => {
+ const act = e.target.closest('[data-act]');
+ const id = e.target.closest('[data-id]')?.dataset.id;
+ if (act && id && act.dataset.act === 'tier') this._setTier(id, e.target.value);
+ });
+ body.addEventListener('input', (e) => {
+ const act = e.target.closest('[data-act="salience"]');
+ const id = e.target.closest('[data-id]')?.dataset.id;
+ if (!act || !id) return;
+ const val = Number(e.target.value) / 100;
+ const label = e.target.parentElement.querySelector('.mem-sal-val');
+ if (label) label.textContent = val.toFixed(2);
+ clearTimeout(this._salTimer);
+ this._salTimer = setTimeout(() => this._setSalience(id, val), 350);
+ });
+ }
+
+ _selectView(view) {
+ this.state.view = view;
+ this.state.search = null;
+ this.state.entity = null;
+ this.el.querySelectorAll('[data-view]').forEach((b) => {
+ const on = b.dataset.view === view;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-selected', String(on));
+ });
+ this._renderSubbar();
+ this._renderBody();
+ }
+
+ // ── Quick recalls (trade-aware) ─────────────────────────────────────────────
+
+ _renderQuick() {
+ const host = this._q('[data-quick]');
+ if (!host) return;
+ const chips = [
+ { q: 'lessons from losing trades', label: 'Lessons from losses' },
+ { q: 'rules my agent follows', label: 'Rules it follows' },
+ { q: 'winning trades', label: 'Wins' },
+ { q: 'watchlist', label: 'Watchlist' },
+ ];
+ host.innerHTML = chips
+ .map((c) => `<button class="mem-chip" data-quick-q="${esc(c.q)}">${esc(c.label)}</button>`)
+ .join('');
+ host.querySelectorAll('[data-quick-q]').forEach((b) =>
+ b.addEventListener('click', () => {
+ this._q('[data-search]').value = b.dataset.quickQ;
+ this._runSearch(b.dataset.quickQ);
+ }));
+ }
+
+ // ── Subbar (per view) ──────────────────────────────────────────────────────
+
+ _renderSubbar() {
+ const host = this._q('[data-subbar]');
+ if (this.state.view === 'timeline') {
+ const f = this.state.filter;
+ const typePills = ['', 'user', 'feedback', 'project', 'reference']
+ .map((t) => `<button class="mem-pill ${f.type === t ? 'active' : ''}" data-filter-type="${t}">${t ? TYPE_LABEL[t] : 'All types'}</button>`)
+ .join('');
+ const tierPills = ['', ...TIERS.map((t) => t.key)]
+ .map((t) => `<button class="mem-pill ${f.tier === t ? 'active' : ''}" data-filter-tier="${t}">${t ? TIERS.find((x) => x.key === t).label : 'All tiers'}</button>`)
+ .join('');
+ host.innerHTML = `
+ <div class="mem-filters">${typePills}</div>
+ <div class="mem-filters">${tierPills}</div>
+ <button class="mem-pill mem-pill-ghost ${this.state.mergeMode ? 'active' : ''}" data-action="merge-toggle" title="Select duplicates to merge">⛙ Merge</button>`;
+ host.querySelectorAll('[data-filter-type]').forEach((b) => b.addEventListener('click', () => {
+ this.state.filter.type = b.dataset.filterType; this.state.renderLimit = 60; this._renderSubbar(); this._renderBody();
+ }));
+ host.querySelectorAll('[data-filter-tier]').forEach((b) => b.addEventListener('click', () => {
+ this.state.filter.tier = b.dataset.filterTier; this.state.renderLimit = 60; this._renderSubbar(); this._renderBody();
+ }));
+ host.querySelector('[data-action="merge-toggle"]').addEventListener('click', () => this._toggleMergeMode());
+ host.hidden = false;
+ } else if (this.state.view === 'context') {
+ host.innerHTML = `<p class="mem-subbar-note">This is the working core — exactly what your agent carries into every reply. Pin memories to add them; the token budget keeps the core small and trustworthy.</p>`;
+ host.hidden = false;
+ } else {
+ host.hidden = true;
+ host.innerHTML = '';
+ }
+ }
+
+ // ── Body dispatch ────────────────────────────────────────────────────────
+
+ _renderBody() {
+ const host = this._q('[data-body]');
+ if (this.state.loading) return void (host.innerHTML = this._skeleton());
+ if (this.state.error) return void (host.innerHTML = this._errorState(this.state.error));
+ if (this.state.search) return void this._renderSearch(host);
+ if (this.state.entity) return void this._renderEntity(host);
+ if (this.state.view === 'graph') return void this._renderGraph(host);
+ if (this.state.view === 'context') return void this._renderContext(host);
+ return void this._renderTimeline(host);
+ }
+
+ _skeleton() {
+ return `<div class="mem-skel">${'<div class="mem-skel-row"></div>'.repeat(5)}</div>`;
+ }
+
+ _errorState(msg) {
+ return `<div class="mem-empty"><div class="mem-empty-glyph">⚠</div><h3>Couldn’t load memory</h3><p>${esc(msg)}</p><button class="mem-btn" data-action="retry">Try again</button></div>`;
+ }
+
+ // ── Timeline ──────────────────────────────────────────────────────────────
+
+ _filteredMemories() {
+ const f = this.state.filter;
+ return this.state.memories.filter((m) => {
+ if (f.type && m.type !== f.type) return false;
+ if (f.tier && (m.tier || 'recall') !== f.tier) return false;
+ return true;
+ }).sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
+ }
+
+ _renderTimeline(host) {
+ const all = this._filteredMemories();
+ if (!this.state.memories.length) return void (host.innerHTML = this._firstRun());
+ if (!all.length) {
+ host.innerHTML = `<div class="mem-empty"><div class="mem-empty-glyph">⊘</div><h3>No memories match</h3><p>Clear the filters to see the full stream.</p></div>`;
+ return;
+ }
+ const slice = all.slice(0, this.state.renderLimit);
+ const more = all.length - slice.length;
+ host.innerHTML = `
+ <ol class="mem-stream" aria-label="Memory timeline">
+ ${slice.map((m) => this._card(m)).join('')}
+ </ol>
+ ${more > 0 ? `<div class="mem-more">Showing ${slice.length} of ${all.length} — scroll for ${more} more</div>` : ''}`;
+ // Mark newly arrived for entrance animation, then clear the flag.
+ host.querySelectorAll('.mem-card--new').forEach((c) => {
+ requestAnimationFrame(() => c.classList.remove('mem-card--new'));
+ });
+ }
+
+ _card(m) {
+ const isNew = !this._knownIds.has(m.id);
+ const sal = Math.round((m.salience || 0) * 100);
+ const tier = m.tier || 'recall';
+ const selected = this.state.selection.has(m.id);
+ const tags = (m.tags || []).filter((t) => t !== 'studio' && t !== 'chat');
+ return `
+ <li class="mem-card mem-card--${esc(m.type)} ${isNew ? 'mem-card--new' : ''} ${selected ? 'mem-card--sel' : ''}" data-id="${esc(m.id)}">
+ ${this.state.mergeMode ? `<input type="checkbox" class="mem-card-check" data-act="select" ${selected ? 'checked' : ''} aria-label="Select for merge" />` : ''}
+ <div class="mem-card-rail" data-tier="${esc(tier)}" title="${esc(TIERS.find((t) => t.key === tier)?.hint || '')}"></div>
+ <div class="mem-card-main">
+ <div class="mem-card-head">
+ <span class="mem-badge" data-type="${esc(m.type)}">${esc(TYPE_LABEL[m.type] || m.type)}</span>
+ <span class="mem-tier-tag" data-tier="${esc(tier)}">${esc(TIERS.find((t) => t.key === tier)?.label || tier)}</span>
+ ${m.pinned ? '<span class="mem-pin-on" title="Pinned to working core">★</span>' : ''}
+ ${m.hasEmbedding ? '<span class="mem-embed-dot" title="Embedded — semantically searchable"></span>' : '<span class="mem-embed-dot pending" title="Embedding pending"></span>'}
+ <span class="mem-card-time">${esc(relTime(m.createdAt))}</span>
+ </div>
+ <div class="mem-card-content" data-act="expand">${esc(m.content)}</div>
+ <div class="mem-card-foot">
+ <div class="mem-tags">${tags.map((t) => `<span class="mem-tag" data-tag="${esc(t)}">${esc(t)}</span>`).join('')}</div>
+ <div class="mem-sal">
+ <input class="mem-sal-range" type="range" min="0" max="100" value="${sal}" data-act="salience" aria-label="Salience" />
+ <span class="mem-sal-val">${(m.salience || 0).toFixed(2)}</span>
+ </div>
+ </div>
+ <div class="mem-card-tools">
+ <button class="mem-tool" data-act="${m.pinned ? 'unpin' : 'pin'}" title="${m.pinned ? 'Unpin from core' : 'Pin to working core'}">${m.pinned ? '★ Pinned' : '☆ Pin'}</button>
+ <select class="mem-tool-select" data-act="tier" aria-label="Tier">
+ ${TIERS.map((t) => `<option value="${t.key}" ${t.key === tier ? 'selected' : ''}>${t.label}</option>`).join('')}
+ </select>
+ <button class="mem-tool" data-act="edit" title="Edit">Edit</button>
+ <button class="mem-tool mem-tool-danger" data-act="forget" title="Forget">Forget</button>
+ ${m.accessCount ? `<span class="mem-recalls" title="Times recalled">↺ ${m.accessCount}</span>` : ''}
+ </div>
+ </div>
+ </li>`;
+ }
+
+ _firstRun() {
+ return `
+ <div class="mem-first">
+ <div class="mem-first-glyph">◍</div>
+ <h3>Your agent has no memories yet</h3>
+ <p>Memory is what turns a chatbot into a companion that knows you — and a trader that remembers every snipe, win, loss, and rule. Give it something to remember.</p>
+ <div class="mem-tier-legend">
+ ${TIERS.map((t) => `<div class="mem-tier-card" data-tier="${t.key}"><strong>${t.label}</strong><span>${t.hint}</span></div>`).join('')}
+ </div>
+ <div class="mem-first-cta">
+ <button class="mem-btn mem-btn-accent" data-action="seed">Seed from your accounts</button>
+ <button class="mem-btn mem-btn-ghost" data-action="add">Add a memory manually</button>
+ </div>
+ </div>`;
+ }
+
+ // ── Graph ──────────────────────────────────────────────────────────────────
+
+ async _renderGraph(host) {
+ host.innerHTML = `
+ <div class="mem-graph-wrap">
+ <canvas class="mem-graph-canvas" data-graph-canvas></canvas>
+ <div class="mem-graph-legend">
+ ${Object.entries(KIND_LABEL).map(([k, label]) =>
+ `<span class="mem-legend-item"><i style="background:${MemoryGraph.color(k)}"></i>${esc(label)}</span>`).join('')}
+ </div>
+ <div class="mem-graph-empty" data-graph-empty hidden>
+ <p>No entities yet. As your agent remembers coins, wallets, people and strategies, they’ll appear here — linked by what shows up together.</p>
+ </div>
+ </div>`;
+ const canvas = host.querySelector('[data-graph-canvas]');
+ if (this._graph) this._graph.destroy();
+ this._graph = new MemoryGraph(canvas, { onSelect: (node) => this._onGraphSelect(node) });
+
+ try {
+ const graph = this.state.graph || (this.state.graph = await this.client.graph());
+ if (!graph.nodes?.length) {
+ host.querySelector('[data-graph-empty]').hidden = false;
+ return;
+ }
+ this._graph.setData(graph);
+ } catch (err) {
+ host.querySelector('[data-graph-empty]').hidden = false;
+ host.querySelector('[data-graph-empty]').innerHTML = `<p>Couldn’t build the graph: ${esc(err.message)}</p>`;
+ }
+ }
+
+ async _onGraphSelect(node) {
+ if (!node) return;
+ const memories = await this.client.entityMemories(node.id).catch(() => []);
+ this.state.entity = { node, memories, replay: false };
+ this._renderBody();
+ }
+
+ _renderEntity(host) {
+ const { node, memories, replay } = this.state.entity;
+ const ordered = replay
+ ? [...memories].sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))
+ : [...memories].sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
+ const isCoin = node.kind === 'mint' || node.kind === 'ticker';
+ host.innerHTML = `
+ <div class="mem-entity">
+ <div class="mem-entity-head">
+ <button class="mem-back" data-act="entity-back">← Back</button>
+ <span class="mem-entity-kind" style="--c:${MemoryGraph.color(node.kind)}">${esc(KIND_LABEL[node.kind] || node.kind)}</span>
+ <h3>${esc(node.label)}</h3>
+ <span class="mem-entity-stat">${node.mentions} mention${node.mentions === 1 ? '' : 's'}</span>
+ ${isCoin ? `<button class="mem-btn mem-btn-sm ${replay ? 'mem-btn-accent' : 'mem-btn-ghost'}" data-act="entity-replay">${replay ? '▶ Replaying' : '⟳ Replay'}</button>` : ''}
+ </div>
+ ${replay ? `<p class="mem-entity-replay-note">Watch how your agent’s understanding of <strong>${esc(node.label)}</strong> formed — oldest memory first.</p>` : ''}
+ ${ordered.length
+ ? `<ol class="mem-stream mem-stream-compact">${ordered.map((m, i) => this._replayCard(m, replay ? i + 1 : null)).join('')}</ol>`
+ : '<div class="mem-empty"><p>No memories reference this entity yet.</p></div>'}
+ </div>`;
+ }
+
+ _replayCard(m, step) {
+ return `
+ <li class="mem-card mem-card--${esc(m.type)}" data-id="${esc(m.id)}">
+ <div class="mem-card-rail" data-tier="${esc(m.tier || 'recall')}"></div>
+ <div class="mem-card-main">
+ <div class="mem-card-head">
+ ${step ? `<span class="mem-step">${step}</span>` : ''}
+ <span class="mem-badge" data-type="${esc(m.type)}">${esc(TYPE_LABEL[m.type] || m.type)}</span>
+ <span class="mem-card-time">${esc(relTime(m.createdAt))}</span>
+ </div>
+ <div class="mem-card-content">${esc(m.content)}</div>
+ </div>
+ </li>`;
+ }
+
+ // ── In context ──────────────────────────────────────────────────────────────
+
+ _renderContext(host) {
+ const ctx = this.state.context;
+ if (!ctx) { host.innerHTML = this._skeleton(); this._refreshContext(); return; }
+ const pct = Math.min(100, Math.round((ctx.tokens / ctx.budget) * 100));
+ const c = ctx.counts || {};
+ host.innerHTML = `
+ <div class="mem-ctx">
+ <div class="mem-ctx-budget ${ctx.overBudget ? 'over' : ''}">
+ <div class="mem-ctx-budget-top">
+ <span>Working core</span>
+ <span class="mem-ctx-tokens">${ctx.tokens} / ${ctx.budget} tokens</span>
+ </div>
+ <div class="mem-ctx-bar"><div class="mem-ctx-fill" style="width:${pct}%"></div></div>
+ ${ctx.overBudget ? '<p class="mem-ctx-warn">Over budget — unpin or archive low-value memories so the core stays sharp.</p>' : ''}
+ </div>
+ <div class="mem-ctx-counts">
+ <div class="mem-count"><b>${c.total ?? 0}</b><span>total</span></div>
+ <div class="mem-count" data-tier="working"><b>${c.working ?? 0}</b><span>working</span></div>
+ <div class="mem-count" data-tier="recall"><b>${c.recall ?? 0}</b><span>recall</span></div>
+ <div class="mem-count" data-tier="archival"><b>${c.archival ?? 0}</b><span>archival</span></div>
+ <div class="mem-count"><b>${c.embedded ?? 0}</b><span>embedded</span></div>
+ </div>
+ <h4 class="mem-ctx-title">In context right now</h4>
+ ${ctx.entries.length
+ ? `<ol class="mem-stream mem-stream-compact">${ctx.entries.map((m) => this._card(m)).join('')}</ol>`
+ : '<div class="mem-empty"><p>Nothing pinned to the working core yet. Pin your agent’s identity, goals, and key rules so they’re always present.</p></div>'}
+ </div>`;
+ }
+
+ // ── Search / recall ──────────────────────────────────────────────────────────
+
+ async _runSearch(query) {
+ if (!query) return;
+ this.state.search = { query, results: [], provider: false, scored: 0, loading: true };
+ this._renderBody();
+ try {
+ const out = await this.client.search(query, { topK: 15, minScore: 0.2 });
+ this.state.search = { query, ...out, loading: false };
+ } catch (err) {
+ this.state.search = { query, results: [], error: err.message, loading: false };
+ }
+ this._renderBody();
+ }
+
+ _renderSearch(host) {
+ const s = this.state.search;
+ if (s.loading) { host.innerHTML = this._skeleton(); return; }
+ const provNote = s.provider
+ ? `<span class="mem-search-note">semantic · ${s.scored} scored</span>`
+ : '<span class="mem-search-note">keyword match (no embedding provider configured)</span>';
+ host.innerHTML = `
+ <div class="mem-search-head">
+ <button class="mem-back" data-act="search-back">← Back</button>
+ <h3>Recall: “${esc(s.query)}”</h3>
+ ${provNote}
+ </div>
+ ${s.error ? `<div class="mem-empty"><p>${esc(s.error)}</p></div>`
+ : s.results.length
+ ? `<ol class="mem-stream">${s.results.map((m) => this._searchCard(m)).join('')}</ol>`
+ : `<div class="mem-empty"><div class="mem-empty-glyph">∅</div><h3>Nothing recalled</h3><p>Your agent has no memory matching that yet.</p></div>`}`;
+ }
+
+ _searchCard(m) {
+ const scoreTag = m.match === 'semantic' && m.score != null
+ ? `<span class="mem-score" title="cosine similarity">${(m.score * 100).toFixed(0)}%</span>`
+ : '<span class="mem-score mem-score-lex">keyword</span>';
+ return `
+ <li class="mem-card mem-card--${esc(m.type)}" data-id="${esc(m.id)}">
+ <div class="mem-card-rail" data-tier="${esc(m.tier || 'recall')}"></div>
+ <div class="mem-card-main">
+ <div class="mem-card-head">
+ <span class="mem-badge" data-type="${esc(m.type)}">${esc(TYPE_LABEL[m.type] || m.type)}</span>
+ ${scoreTag}
+ <span class="mem-card-time">${esc(relTime(m.createdAt))}</span>
+ </div>
+ <div class="mem-card-content">${esc(m.content)}</div>
+ </div>
+ </li>`;
+ }
+
+ // ── Body interactions ──────────────────────────────────────────────────────
+
+ _onScroll() {
+ if (this.state.view !== 'timeline' || this.state.search || this.state.entity) return;
+ const host = this._q('[data-body]');
+ if (host.scrollTop + host.clientHeight >= host.scrollHeight - 200) {
+ const total = this._filteredMemories().length;
+ if (this.state.renderLimit < total) {
+ this.state.renderLimit += 60;
+ this._renderTimeline(host);
+ }
+ }
+ }
+
+ async _onBodyClick(e) {
+ const actionBtn = e.target.closest('[data-action]');
+ if (actionBtn) {
+ const a = actionBtn.dataset.action;
+ if (a === 'retry') return this._load();
+ if (a === 'seed') return this._openSeed();
+ if (a === 'add') return this._openAddForm();
+ if (a === 'search-back') { this.state.search = null; return this._renderBody(); }
+ if (a === 'entity-back') { this.state.entity = null; return this._renderBody(); }
+ }
+ const act = e.target.closest('[data-act]');
+ if (!act) return;
+ const card = e.target.closest('[data-id]');
+ const id = card?.dataset.id;
+ const op = act.dataset.act;
+
+ if (op === 'entity-back') { this.state.entity = null; return this._renderBody(); }
+ if (op === 'search-back') { this.state.search = null; return this._renderBody(); }
+ if (op === 'entity-replay') {
+ this.state.entity.replay = !this.state.entity.replay;
+ return this._renderBody();
+ }
+ if (op === 'expand') { card.querySelector('.mem-card-content').classList.toggle('expanded'); return; }
+ if (op === 'tag') { this._q('[data-search]').value = act.dataset.tag; return this._runSearch(act.dataset.tag); }
+ if (!id) return;
+
+ if (op === 'select') return this._toggleSelect(id, card);
+ if (op === 'pin') return this._mutate(id, () => this.client.pin(id), 'Pinned to working core');
+ if (op === 'unpin') return this._mutate(id, () => this.client.unpin(id), 'Unpinned');
+ if (op === 'forget') return this._forget(id, card);
+ if (op === 'edit') return this._inlineEdit(id, card);
+ }
+
+ // ── Mutations ────────────────────────────────────────────────────────────
+
+ _localUpdate(entry) {
+ if (!entry) return;
+ const i = this.state.memories.findIndex((m) => m.id === entry.id);
+ if (i >= 0) this.state.memories[i] = { ...this.state.memories[i], ...entry };
+ }
+
+ async _mutate(id, fn, toast) {
+ try {
+ const { entry } = await fn();
+ this._localUpdate(entry);
+ this._emitChange({ op: 'curate', id });
+ this.studio.emitMarket?.({ type: 'memory:saved' });
+ if (toast) this._toast(toast);
+ this._renderBody();
+ this._refreshContext();
+ } catch (err) {
+ this._toast(err.message || 'Update failed', true);
+ }
+ }
+
+ async _forget(id, card) {
+ if (card) card.classList.add('mem-card--leaving');
+ try {
+ await this.client.forget(id);
+ this.state.memories = this.state.memories.filter((m) => m.id !== id);
+ this.state.graph = null; // graph derived from memories — invalidate
+ this._knownIds.delete(id);
+ this._emitChange({ op: 'forget', id });
+ setTimeout(() => { this._renderBody(); this._refreshContext(); }, 180);
+ } catch (err) {
+ if (card) card.classList.remove('mem-card--leaving');
+ this._toast(err.message || 'Could not forget', true);
+ }
+ }
+
+ async _setSalience(id, value) {
+ try {
+ const { entry } = await this.client.setSalience(id, value);
+ this._localUpdate(entry);
+ this._emitChange({ op: 'salience', id });
+ } catch (err) { this._toast(err.message, true); }
+ }
+
+ async _setTier(id, tier) {
+ await this._mutate(id, () => this.client.setTier(id, tier), `Moved to ${tier}`);
+ }
+
+ _inlineEdit(id, card) {
+ const mem = this.state.memories.find((m) => m.id === id);
+ if (!mem) return;
+ const main = card.querySelector('.mem-card-main');
+ const tags = (mem.tags || []).join(', ');
+ main.innerHTML = `
+ <div class="mem-edit">
+ <textarea class="mem-edit-content" rows="4">${esc(mem.content)}</textarea>
+ <input class="mem-edit-tags" type="text" value="${esc(tags)}" placeholder="tags, comma separated" />
+ <div class="mem-edit-tools">
+ <button class="mem-btn mem-btn-sm" data-edit-save>Save</button>
+ <button class="mem-btn mem-btn-sm mem-btn-ghost" data-edit-cancel>Cancel</button>
+ </div>
+ </div>`;
+ main.querySelector('[data-edit-cancel]').addEventListener('click', () => this._renderBody());
+ main.querySelector('[data-edit-save]').addEventListener('click', async () => {
+ const content = main.querySelector('.mem-edit-content').value.trim();
+ const newTags = main.querySelector('.mem-edit-tags').value.split(',').map((t) => t.trim()).filter(Boolean);
+ if (!content) return;
+ try {
+ const { entry } = await this.client.edit(id, { content, tags: newTags });
+ this._localUpdate(entry);
+ this.state.graph = null;
+ this._emitChange({ op: 'edit', id });
+ this._toast('Memory updated — re-indexing');
+ this._renderBody();
+ } catch (err) { this._toast(err.message, true); }
+ });
+ }
+
+ // ── Merge mode ──────────────────────────────────────────────────────────
+
+ _toggleMergeMode() {
+ this.state.mergeMode = !this.state.mergeMode;
+ if (!this.state.mergeMode) this.state.selection.clear();
+ this._renderSubbar();
+ this._renderBody();
+ this._updateMergeBar();
+ }
+ _exitMergeMode() { this.state.mergeMode = false; this.state.selection.clear(); this._renderSubbar(); this._renderBody(); this._updateMergeBar(); }
+
+ _toggleSelect(id, card) {
+ if (this.state.selection.has(id)) this.state.selection.delete(id);
+ else this.state.selection.add(id);
+ card?.classList.toggle('mem-card--sel', this.state.selection.has(id));
+ this._updateMergeBar();
+ }
+
+ _updateMergeBar() {
+ const bar = this._q('[data-merge-bar]');
+ const n = this.state.selection.size;
+ bar.hidden = !this.state.mergeMode || n < 1;
+ this._q('[data-merge-count]').textContent = `${n} selected`;
+ }
+
+ async _commitMerge() {
+ const ids = [...this.state.selection];
+ if (ids.length < 2) return this._toast('Select at least two memories', true);
+ // Target = oldest (the original); fold the rest into it.
+ const ordered = ids
+ .map((id) => this.state.memories.find((m) => m.id === id))
+ .filter(Boolean)
+ .sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))
+ .map((m) => m.id);
+ try {
+ const { entry, merged } = await this.client.merge(ordered);
+ const removed = new Set(ordered.slice(1));
+ this.state.memories = this.state.memories.filter((m) => !removed.has(m.id));
+ this._localUpdate(entry);
+ this.state.graph = null;
+ this._emitChange({ op: 'merge', id: entry.id });
+ this._toast(`Merged ${merged + 1} memories`);
+ this._exitMergeMode();
+ } catch (err) { this._toast(err.message, true); }
+ }
+
+ // ── Add form ────────────────────────────────────────────────────────────────
+
+ _openAddForm() {
+ const host = this._q('[data-body]');
+ host.scrollTop = 0;
+ // A transient composer pinned above the stream.
+ let composer = this.el.querySelector('.mem-composer');
+ if (composer) { composer.querySelector('textarea')?.focus(); return; }
+ composer = document.createElement('div');
+ composer.className = 'mem-composer';
+ composer.innerHTML = `
+ <div class="mem-composer-row">
+ <select class="mem-composer-type" aria-label="Type">
+ ${Object.entries(TYPE_LABEL).map(([k, l]) => `<option value="${k}" ${k === 'project' ? 'selected' : ''}>${l}</option>`).join('')}
+ </select>
+ <select class="mem-composer-tier" aria-label="Tier">
+ ${TIERS.map((t) => `<option value="${t.key}" ${t.key === 'recall' ? 'selected' : ''}>${t.label}</option>`).join('')}
+ </select>
+ <label class="mem-composer-pin"><input type="checkbox" class="mem-composer-pinned" /> Pin</label>
+ </div>
+ <textarea class="mem-composer-content" rows="3" placeholder="What should your agent remember? (a rule, a preference, a lesson from a trade…)"></textarea>
+ <input class="mem-composer-tags" type="text" placeholder="tags, comma separated" />
+ <div class="mem-composer-tools">
+ <button class="mem-btn mem-btn-sm" data-composer-save>Remember it</button>
+ <button class="mem-btn mem-btn-sm mem-btn-ghost" data-composer-cancel>Cancel</button>
+ </div>`;
+ host.prepend(composer);
+ composer.querySelector('textarea').focus();
+ composer.querySelector('[data-composer-cancel]').addEventListener('click', () => composer.remove());
+ composer.querySelector('[data-composer-save]').addEventListener('click', async () => {
+ const content = composer.querySelector('.mem-composer-content').value.trim();
+ if (!content) return;
+ const pinned = composer.querySelector('.mem-composer-pinned').checked;
+ const entry = {
+ type: composer.querySelector('.mem-composer-type').value,
+ tier: composer.querySelector('.mem-composer-tier').value,
+ pinned,
+ content,
+ tags: composer.querySelector('.mem-composer-tags').value.split(',').map((t) => t.trim()).filter(Boolean),
+ salience: pinned ? 0.85 : 0.6,
+ };
+ composer.querySelector('[data-composer-save]').disabled = true;
+ await this._addMemory(entry);
+ composer.remove();
+ });
+ }
+
+ async _addMemory(entry) {
+ try {
+ const saved = await this.client.add(entry);
+ if (saved) {
+ this.state.memories.unshift(saved);
+ this.state.graph = null;
+ this._emitChange({ op: 'add', id: saved.id });
+ this.studio.emitMarket?.({ type: 'memory:saved' });
+ this._learned(saved);
+ }
+ if (this.state.view !== 'timeline') this._selectView('timeline');
+ else this._renderBody();
+ this._refreshContext();
+ } catch (err) { this._toast(err.message || 'Could not save', true); }
+ }
+
+ // ── Seed from connectors ──────────────────────────────────────────────────────
+
+ _openSeed() {
+ if (this.el.querySelector('.mem-seed-modal')) return;
+ const modal = document.createElement('div');
+ modal.className = 'mem-seed-modal';
+ modal.innerHTML = `
+ <div class="mem-seed-card" role="dialog" aria-label="Seed memory">
+ <div class="mem-seed-head"><h3>Seed memory from your accounts</h3><button class="mem-seed-x" data-seed-close aria-label="Close">×</button></div>
+ <p class="mem-seed-sub">Pull a real identity from GitHub, X, and Farcaster, synthesize it with Claude, and save it as your agent’s pinned working memory.</p>
+ <div class="mem-seed-conns">
+ ${['github', 'x', 'farcaster'].map((n) => `
+ <div class="mem-seed-conn">
+ <label>${n === 'github' ? 'GitHub' : n === 'x' ? 'X' : 'Farcaster'}</label>
+ <input data-seed-input="${n}" type="text" placeholder="${n === 'farcaster' ? 'username or fid' : 'handle'}" autocomplete="off" />
+ <span class="mem-seed-dot" data-seed-dot="${n}"></span>
+ </div>`).join('')}
+ </div>
+ <button class="mem-btn mem-btn-accent mem-btn-full" data-seed-go>Fetch & synthesize</button>
+ <div class="mem-seed-out" data-seed-out hidden></div>
+ <div class="mem-seed-tools" data-seed-save-tools hidden>
+ <button class="mem-btn mem-btn-sm" data-seed-save>Save as pinned memory</button>
+ <span class="mem-seed-notice" data-seed-notice></span>
+ </div>
+ </div>`;
+ this.el.appendChild(modal);
+ modal.addEventListener('click', (e) => { if (e.target === modal) modal.remove(); });
+ modal.querySelector('[data-seed-close]').addEventListener('click', () => modal.remove());
+
+ let seedMarkdown = '';
+ modal.querySelector('[data-seed-go]').addEventListener('click', async () => {
+ const connectors = {};
+ const names = ['github', 'x', 'farcaster'];
+ const go = modal.querySelector('[data-seed-go]');
+ go.disabled = true; go.textContent = 'Fetching…';
+ await Promise.all(names.map(async (n) => {
+ const handle = modal.querySelector(`[data-seed-input="${n}"]`).value.trim();
+ const dot = modal.querySelector(`[data-seed-dot="${n}"]`);
+ if (!handle) return;
+ dot.className = 'mem-seed-dot loading';
+ try { connectors[n] = await fetchConnector(n, handle); dot.className = 'mem-seed-dot ok'; }
+ catch { dot.className = 'mem-seed-dot err'; }
+ }));
+ const out = modal.querySelector('[data-seed-out]');
+ out.hidden = false;
+ if (!Object.values(connectors).some(Boolean)) {
+ out.innerHTML = '<span class="mem-seed-fail">No connector returned data. Check the handles or that the connectors are configured.</span>';
+ go.disabled = false; go.textContent = 'Fetch & synthesize';
+ return;
+ }
+ go.textContent = 'Synthesizing…';
+ try {
+ const result = await synthesizeMemorySeed(connectors);
+ seedMarkdown = result.memory_seed || '';
+ out.textContent = seedMarkdown;
+ modal.querySelector('[data-seed-save-tools]').hidden = false;
+ } catch (err) {
+ out.innerHTML = `<span class="mem-seed-fail">${esc(err.message)}</span>`;
+ } finally {
+ go.disabled = false; go.textContent = 'Fetch & synthesize';
+ }
+ });
+ modal.querySelector('[data-seed-save]').addEventListener('click', async () => {
+ if (!seedMarkdown) return;
+ const notice = modal.querySelector('[data-seed-notice]');
+ const btn = modal.querySelector('[data-seed-save]');
+ btn.disabled = true; notice.textContent = 'Saving…';
+ try {
+ await saveMemoryToAgent(this.agentId, seedMarkdown, {
+ type: 'user', tags: ['identity', 'seed'], salience: 0.95,
+ context: { source: 'memory_seed_synthesis', tier: 'working' },
+ });
+ notice.textContent = 'Saved.';
+ this._toast('Identity seeded into working memory');
+ modal.remove();
+ await this._load();
+ this._selectView('timeline');
+ } catch (err) {
+ notice.textContent = err.message;
+ btn.disabled = false;
+ }
+ });
+ }
+
+ // ── Delight: toast + "your agent learned" nudge ──────────────────────────────
+
+ _toast(msg, isError = false) {
+ const t = this._q('[data-toast]');
+ t.textContent = msg;
+ t.hidden = false;
+ t.className = `mem-toast ${isError ? 'mem-toast-err' : ''} show`;
+ clearTimeout(this._toastTimer);
+ this._toastTimer = setTimeout(() => { t.classList.remove('show'); setTimeout(() => { t.hidden = true; }, 300); }, 2600);
+ }
+
+ _learned(mem) {
+ const title = String(mem.content || '').split('\n')[0].slice(0, 60);
+ this._toast(`✦ Your agent learned: “${title}${title.length >= 60 ? '…' : ''}”`);
+ }
+}
diff --git a/vercel.json b/vercel.json
index d48741843..42160763d 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1,7 +1,7 @@
{
"buildCommand": "npm run build:vercel",
"outputDirectory": "dist",
- "installCommand": "npm install --prefer-offline --no-audit --no-fund",
+ "installCommand": "npm ci --no-audit --no-fund",
"env": {
"NODE_OPTIONS": "--no-deprecation"
},