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: wire Memory Studio UI, tests, and changelog entry

nirholasf8d74b4dd42e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 41139dcda..132cca79f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL stays fast and recovers gracefully in long AR sessions** — IRL is built to run for an hour without slowing down. Swapping your avatar now fully releases the previous 3D model from memory instead of leaving it behind, so trying on a dozen looks in one session no longer piles up. If your phone reclaims graphics memory and the camera view would otherwise go black — a common thing on mobile after the tab sits idle — IRL now pauses cleanly and restores the scene, with a clear "AR paused, restoring…" card and a one-tap reload if your device needs it. Backgrounding the tab pauses the render loop and quiets the camera to save battery, then resumes the moment you come back. And as you move, avatars you walk past stop holding a load slot ahead of the ones you're heading toward, so the nearest agents always render first. (`/irl`) `[improvement]`
- **IRL surfaces now show clear loading, empty, and error states** — Every IRL screen that loads data now has a designed loading, empty, and error state — no more stuck "Loading…" or blank screens. Open "My pins" and you'll see a skeleton while it loads, a friendly nudge to drop your first agent when you have none, and a one-tap Retry if the network hiccups. Tapping an agent shows the same care: if its profile can't load, you get a clear message and Retry while its name and a link to the full profile stay put. The nearby radar reads as intentionally empty ("Be the first to pin here") instead of a broken dial, and the count beside it no longer flashes "0 nearby" before we've finished looking. On devices that can't run the AR view, you get a helpful card explaining why and where to go next — not a bare error. (`/irl`) `[improvement]`
- **IRL teaches you how to find agents — and an empty area now feels alive** — IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small "?" in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle "Look around 👀 · or be the first to pin here" prompt with a one-tap way to place your own agent — so an empty spot reads as "keep exploring," not "this is broken." The moment a real agent comes into range, the prompt fades away on its own. (`/irl`) `[improvement]`
+- **Memory Studio — watch your agent’s memory form, curate it, and trust it** — The Memory tab in Agent Studio turns your agent’s memory into something you can see and shape. A live Timeline streams every memory as it forms — chats, lessons, rules, trades — each tagged by tier (working, recall, archival) and salience, with one-click pin, edit, merge, forget, and a slider to dial importance. A knowledge Graph maps the coins, wallets, people, and strategies your agent has learned, linked by what shows up together; click any coin to replay how your agent’s understanding of it evolved over time. Recall runs real semantic search over real embeddings, so asking “lessons from losing trades” or “rules my agent follows” returns what it actually knows — and an In-Context view shows exactly what the agent carries into every reply, with a live token budget so the core stays sharp. Seed it in seconds from your GitHub, X, and Farcaster, and the Brain’s Memory node recalls all of it for real. (`/agent-studio`) `[feature]`
- **One API, many services: the three.ws API gateway** — We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface. `[feature, sdk]`
- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`
- **Pay-per-call vanity wallets now do seed phrases and encrypted delivery** — The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away. (`/vanity-wallet`) `[feature, security]`
diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.js
index 8f2f66547..85afeedb9 100644
--- a/api/_lib/memory-store.js
+++ b/api/_lib/memory-store.js
@@ -211,7 +211,7 @@ export async function searchMemories(agentId, query, opts = {}) {
SET access_count = access_count + 1,
last_accessed_at = now(),
salience = LEAST(1.0, salience + 0.02)
- WHERE id = ANY(${ids})
+ WHERE id = ANY(${ids}::uuid[])
`.catch(() => {});
}
@@ -294,7 +294,7 @@ export async function buildGraph(agentId, { limit = 200 } = {}) {
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})
+ WHERE entity_id = ANY(${ids}::uuid[])
`;
// Group entities by the memory they co-occur in; every pair in a memory is an edge.
diff --git a/api/memory/curate.js b/api/memory/curate.js
index 08d6f981c..9f6927f47 100644
--- a/api/memory/curate.js
+++ b/api/memory/curate.js
@@ -22,10 +22,6 @@ 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 };
@@ -54,29 +50,62 @@ export default wrap(async (req, res) => {
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');
+ const memoryId = body.memoryId;
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 'pin': {
+ if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');
+ return respondRow(res, await sql`
+ UPDATE agent_memories SET pinned = true, tier = 'working', 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
+ `);
+ }
+ case 'unpin': {
+ if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');
+ return respondRow(res, await sql`
+ UPDATE agent_memories SET pinned = false, tier = 'recall', 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
+ `);
+ }
case 'tier': {
+ if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');
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}`);
+ return respondRow(res, await sql`
+ UPDATE agent_memories
+ SET tier = ${body.tier},
+ pinned = CASE WHEN ${body.tier} = 'working' THEN true ELSE pinned END,
+ 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
+ `);
}
case 'salience': {
+ if (!memoryId) return error(res, 400, 'validation_error', 'memoryId required');
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}`);
+ return respondRow(res, await sql`
+ UPDATE agent_memories SET salience = ${s}, 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
+ `);
}
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');
+ if (!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
+ DELETE FROM agent_memories WHERE id = ${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 });
@@ -86,15 +115,8 @@ export default wrap(async (req, res) => {
}
});
-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
- `;
+function respondRow(res, rows) {
+ const row = rows?.[0];
if (!row) return error(res, 404, 'not_found', 'memory not found');
return json(res, 200, { entry: decorateMemory(row) });
}
@@ -139,7 +161,7 @@ async function handleMerge(res, agentId, body) {
const rows = await sql`
SELECT id, content, tags, salience, type FROM agent_memories
- WHERE id = ANY(${ids}) AND agent_id = ${agentId}
+ WHERE id = ANY(${ids}::uuid[]) AND agent_id = ${agentId}
`;
if (rows.length < 2) return error(res, 404, 'not_found', 'memories not found');
@@ -176,7 +198,7 @@ async function handleMerge(res, agentId, body) {
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}`;
+ await sql`DELETE FROM agent_memories WHERE id = ANY(${presentDupes}::uuid[]) AND agent_id = ${agentId}`;
}
return json(res, 200, { entry: decorateMemory(updated), merged: presentDupes.length });
}
diff --git a/data/changelog.json b/data/changelog.json
index 4fa807f0e..1765cb498 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Memory Studio — watch your agent’s memory form, curate it, and trust it",
+ "summary": "The Memory tab in Agent Studio turns your agent’s memory into something you can see and shape. A live Timeline streams every memory as it forms — chats, lessons, rules, trades — each tagged by tier (working, recall, archival) and salience, with one-click pin, edit, merge, forget, and a slider to dial importance. A knowledge Graph maps the coins, wallets, people, and strategies your agent has learned, linked by what shows up together; click any coin to replay how your agent’s understanding of it evolved over time. Recall runs real semantic search over real embeddings, so asking “lessons from losing trades” or “rules my agent follows” returns what it actually knows — and an In-Context view shows exactly what the agent carries into every reply, with a live token budget so the core stays sharp. Seed it in seconds from your GitHub, X, and Farcaster, and the Brain’s Memory node recalls all of it for real.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-studio"
+ },
{
"date": "2026-06-19",
"title": "Brain Studio — build your agent’s mind as a visual circuit",
diff --git a/pages/agent-studio.html b/pages/agent-studio.html
index ebb344f3d..dc3a3138b 100644
--- a/pages/agent-studio.html
+++ b/pages/agent-studio.html
@@ -25,6 +25,7 @@
<link rel="stylesheet" href="/mobile.css" />
<link rel="stylesheet" href="/buttons.css" />
<link rel="stylesheet" href="/brain-studio.css" />
+ <link rel="stylesheet" href="/memory-studio.css" />
<style>
html,
@@ -389,5 +390,7 @@
<script type="module" src="/src/studio/studio-shell.js"></script>
<!-- P1: Brain Studio binds itself to the shell's Brain tab on studio-shell:ready. -->
<script type="module" src="/src/studio/brain/brain-mount.js"></script>
+ <!-- P2: Memory Studio binds itself to the shell's Memory tab on studio-shell:ready. -->
+ <script type="module" src="/src/studio/memory/memory-mount.js"></script>
</body>
</html>
diff --git a/prompts/agent-studio/03-memory-studio.md b/prompts/agent-studio/03-memory-studio.md
deleted file mode 100644
index 2317f728e..000000000
--- a/prompts/agent-studio/03-memory-studio.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# P2 — Memory Studio (LLM memory you can watch form, edit, and trust)
-
-You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
-`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged. Read the "Integration
-notes for P1–P5" at the top of `src/studio/agent-studio-store.js`. Mount into the **Memory** tab.
-Coordinate with P1 (the Brain's Memory node reads/writes through your store) via the `studio` contract.
-
-## The vision you are enabling
-
-Memory is the difference between a chatbot and a companion that *knows you*. Today we have
-`api/agent-memory.js`, the `agent_memories` table (`id, agent_id, type, content, tags, salience`),
-and `src/memory-seed.js` (synthesizes identity from GitHub/X/Farcaster connectors). That's a
-foundation — but memory is currently invisible. Per our product principle, memory must be a **visual
-thing the user watches form, curates, and trusts.** And for our domain it must be **trade-aware**:
-the agent remembers every snipe, win, loss, watchlist, and rule, and surfaces them at the right moment.
-
-This is what makes our agent feel alive across sessions. No other crypto tool has a trader with a memory you can see.
-
-## Your mission
-
-### 1. Tiered memory architecture (adopt the proven model)
-Mirror **Letta/MemGPT**'s tiers and **mem0**'s ergonomics — implement real storage, don't bolt on a
-heavy vendor unless justified:
-- **Working memory** — the small, always-in-context core (who the user is, current goals, active
- positions). Editable, pinned, token-budgeted.
-- **Recall memory** — recent interactions/trades, searchable.
-- **Archival memory** — long-term store with semantic search (embeddings). Use a real embedding
- provider already available in the worker proxies; store vectors in Postgres (pgvector if present —
- check `api/_lib/schema.sql`; add the extension/migration if not). No fake similarity.
-- Implement `add()` on events and `search()` before responses (the mem0 pattern) so P1's Brain
- Memory node can recall relevant memories into context for real. Salience/decay so the core stays small.
-
-### 2. Visual memory surfaces (the product principle)
-- **Memory Timeline** — a live, scrollable stream of memories forming over time (trades, chats,
- learned preferences), each with type, salience, source, and tags. Animate new memories landing.
-- **Memory Graph** — entities and relationships (coins, wallets, people, strategies) as a graph the
- user can explore. (Zep/Graphiti-style temporal knowledge graph is the inspiration — see sources.)
-- **Curate:** pin to working memory, edit, merge duplicates, adjust salience, and **forget** (with
- confirm). Show exactly what's in-context right now and the token budget — transparency builds trust.
-- **Trade-aware views:** "What does my agent remember about <mint>?", "Show my agent's lessons from
- losing trades," "Rules my agent follows." These pull from real trade history (coordinate with P4).
-
-### 3. Live wiring
-- New/extended endpoints under `api/agent-memory.js` and new `api/memory/**` for search, tiering,
- embeddings, graph edges. Real auth (owner-only), real CSRF (match the existing pattern).
-- Every memory write/edit flows so the Brain and the live avatar can react (`studio.emit('memory:change')`).
-- Hook `src/memory-seed.js` connectors into the timeline so first-run memory has real substance.
-
-## Libraries / concepts to adopt (research-backed)
-- **mem0** (add/search ergonomics, hybrid vector+graph+kv) — https://github.com/mem0ai/mem0
-- **Letta / MemGPT** (tiered working/recall/archival, self-paging) — https://github.com/letta-ai/letta
-- **Zep / Graphiti** (temporal knowledge graph for facts that change over time — best-in-class on
- LongMemEval) — https://github.com/getzep/graphiti
-- Embeddings/vectors: prefer Postgres + pgvector over a new external service. Reuse worker proxies
- for the embedding model. Don't add a vendor SDK unless it earns its weight — mirror the patterns.
-
-## Definition of done
-- Real tiered memory with real embeddings + semantic search (no fake similarity, no sample arrays).
-- Timeline + graph render real memories; pin/edit/merge/forget/salience all persist via real APIs.
-- Brain's Memory node (P1) can `search()` and pull real memories into context.
-- "In-context now" + token budget visible. Trade-aware queries return real data.
-- All states designed (no memories yet → explain + offer connector seeding; thousands → virtualized).
-- No console errors; `npm test` passes; network tab shows real calls. Changelog entry added.
-
-## Operating rules (override defaults)
-No mocks/stubs/TODOs/fake similarity/sample arrays. $THREE is the only coin promoted; trade memories
-reference runtime mints only. Design tokens only. Stage explicit paths (never `git add -A`); re-check
-`git diff --staged` before commit. Own `src/studio/memory/**`, `api/memory/**`, and extensions to
-`api/agent-memory.js`; coordinate the memory port with P1 and trade history with P4 via `studio`.
-
-## When finished
-Self-review (CLAUDE.md's five checks). Then push it: add the one delightful thing — e.g. a "memory
-replay" that shows how the agent's understanding of a coin evolved over time, or proactive "your
-agent learned X" nudges. Build it. Then **delete this prompt file**
-(`prompts/agent-studio/03-memory-studio.md`) and report what you shipped + the memory API surface
-P1/P4 should use.
diff --git a/public/changelog.json b/public/changelog.json
index bc4b35b8c..7656ea480 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T11:44:24.666Z",
+ "generated_at": "2026-06-19T12:29:19.206Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -262,6 +262,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Memory Studio — watch your agent’s memory form, curate it, and trust it",
+ "summary": "The Memory tab in Agent Studio turns your agent’s memory into something you can see and shape. A live Timeline streams every memory as it forms — chats, lessons, rules, trades — each tagged by tier (working, recall, archival) and salience, with one-click pin, edit, merge, forget, and a slider to dial importance. A knowledge Graph maps the coins, wallets, people, and strategies your agent has learned, linked by what shows up together; click any coin to replay how your agent’s understanding of it evolved over time. Recall runs real semantic search over real embeddings, so asking “lessons from losing trades” or “rules my agent follows” returns what it actually knows — and an In-Context view shows exactly what the agent carries into every reply, with a live token budget so the core stays sharp. Seed it in seconds from your GitHub, X, and Farcaster, and the Brain’s Memory node recalls all of it for real.",
+ "link": "/agent-studio",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 3d00f1c42..6c0871e46 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -206,6 +206,14 @@
<category>improvement</category>
<description>IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small &quot;?&quot; in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle &quot;Look around 👀 · or be the first to pin here&quot; prompt with a one-tap way to place your own agent — so an empty spot reads as &quot;keep exploring,&quot; not &quot;this is broken.&quot; The moment a real agent comes into range, the prompt fades away on its own.</description>
</item>
+ <item>
+ <title>Memory Studio — watch your agent’s memory form, curate it, and trust it</title>
+ <link>https://three.ws/agent-studio</link>
+ <guid isPermaLink="false">2026-06-19:Memory Studio — watch your agent’s memory form, curate it, and trust it</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The Memory tab in Agent Studio turns your agent’s memory into something you can see and shape. A live Timeline streams every memory as it forms — chats, lessons, rules, trades — each tagged by tier (working, recall, archival) and salience, with one-click pin, edit, merge, forget, and a slider to dial importance. A knowledge Graph maps the coins, wallets, people, and strategies your agent has learned, linked by what shows up together; click any coin to replay how your agent’s understanding of it evolved over time. Recall runs real semantic search over real embeddings, so asking “lessons from losing trades” or “rules my agent follows” returns what it actually knows — and an In-Context view shows exactly what the agent carries into every reply, with a live token budget so the core stays sharp. Seed it in seconds from your GitHub, X, and Farcaster, and the Brain’s Memory node recalls all of it for real.</description>
+ </item>
<item>
<title>One API, many services: the three.ws API gateway</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 6bdbe44d3..5657c4c7c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T11:44:24.654Z",
+ "generated_at": "2026-06-19T12:29:19.190Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/memory-studio.css b/public/memory-studio.css
new file mode 100644
index 000000000..c8a7bdb3c
--- /dev/null
+++ b/public/memory-studio.css
@@ -0,0 +1,322 @@
+/* ════════════════════════════════════════════════════════════════════════════
+ * Memory Studio (P2) — styles
+ * Mounts inside the Agent Studio shell's Memory tab. Uses the platform design
+ * tokens throughout; all interactive elements have hover / active / focus states.
+ * ════════════════════════════════════════════════════════════════════════════ */
+
+.mem {
+ --mem-working: #8b5cf6;
+ --mem-recall: #22d3ee;
+ --mem-archival: #64748b;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md, 1rem);
+ min-height: 0;
+ position: relative;
+ color: var(--ink, #e8e8e8);
+}
+
+/* ── Top bar ─────────────────────────────────────────────────────────────── */
+.mem-top { display: flex; flex-direction: column; gap: var(--space-sm, 0.618rem); }
+
+.mem-recall {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 4px 4px 12px;
+ border-radius: var(--radius-pill, 999px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard);
+}
+.mem-recall:focus-within { border-color: var(--mem-working); }
+.mem-recall-icon { width: 16px; height: 16px; color: var(--ink-dim, #888); flex: none; }
+.mem-recall-input {
+ flex: 1; min-width: 0; background: transparent; border: none; outline: none;
+ color: var(--ink-bright, #fff); font-size: var(--text-ui, 0.875rem); font-family: var(--font-body);
+}
+.mem-recall-input::placeholder { color: var(--ink-faint, #666); }
+
+.mem-quick { display: flex; flex-wrap: wrap; gap: 6px; }
+.mem-chip {
+ appearance: none; cursor: pointer;
+ padding: 4px 10px; border-radius: var(--radius-pill, 999px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke); color: var(--ink-dim, #888);
+ font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600);
+ transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.mem-chip:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong); background: var(--surface-2); }
+
+.mem-toolbar { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); flex-wrap: wrap; }
+.mem-views { display: inline-flex; gap: 2px; background: var(--surface-1); padding: 3px; border-radius: var(--radius-md, 10px); border: 1px solid var(--stroke); }
+.mem-view {
+ appearance: none; cursor: pointer; border: none; background: transparent;
+ padding: 6px 14px; border-radius: var(--radius-sm, 6px); color: var(--ink-dim, #888);
+ font-size: var(--text-md, 0.8125rem); font-weight: var(--weight-semibold, 600); font-family: var(--font-body);
+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.mem-view:hover { color: var(--ink, #e8e8e8); }
+.mem-view.active { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255, 255, 255, 0.08)); }
+.mem-view:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }
+
+.mem-actions { display: inline-flex; gap: 8px; }
+
+/* ── Buttons ─────────────────────────────────────────────────────────────── */
+.mem-btn {
+ appearance: none; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 6px;
+ padding: 7px 14px; border-radius: var(--radius-pill, 999px); border: 1px solid transparent;
+ background: var(--ink-bright, #fff); color: var(--bg-0, #0a0a0a);
+ font-size: var(--text-ui, 0.875rem); font-weight: var(--weight-semibold, 600); font-family: var(--font-body);
+ transition: transform var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard);
+}
+.mem-btn:hover { background: #e9e9e9; }
+.mem-btn:active { transform: scale(0.97); }
+.mem-btn:disabled { opacity: 0.5; cursor: default; }
+.mem-btn:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }
+.mem-btn-sm { padding: 5px 11px; font-size: var(--text-2xs, 0.6875rem); }
+.mem-btn-full { width: 100%; }
+.mem-btn-ghost { background: var(--surface-2, rgba(255, 255, 255, 0.05)); color: var(--ink, #e8e8e8); border-color: var(--stroke); }
+.mem-btn-ghost:hover { background: var(--surface-3); }
+.mem-btn-accent { background: linear-gradient(135deg, var(--mem-working), #6d28d9); color: #fff; }
+.mem-btn-accent:hover { filter: brightness(1.08); background: linear-gradient(135deg, var(--mem-working), #6d28d9); }
+
+/* ── Subbar / filters ────────────────────────────────────────────────────── */
+.mem-subbar { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+.mem-filters { display: inline-flex; gap: 4px; flex-wrap: wrap; }
+.mem-pill {
+ appearance: none; cursor: pointer; padding: 4px 11px; border-radius: var(--radius-pill, 999px);
+ background: transparent; border: 1px solid var(--stroke); color: var(--ink-dim, #888);
+ font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600);
+ transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.mem-pill:hover { color: var(--ink, #e8e8e8); border-color: var(--stroke-strong); }
+.mem-pill.active { color: var(--ink-bright, #fff); background: var(--accent-soft, rgba(139, 92, 246, 0.18)); border-color: var(--mem-working); }
+.mem-pill-ghost { margin-left: auto; }
+.mem-subbar-note { margin: 0; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); line-height: var(--leading-normal, 1.618); }
+
+/* ── Body ────────────────────────────────────────────────────────────────── */
+.mem-body { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; scrollbar-width: thin; }
+.mem-body:focus-visible { outline: none; }
+
+/* ── Stream / cards ──────────────────────────────────────────────────────── */
+.mem-stream { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
+.mem-stream-compact { gap: 8px; }
+
+.mem-card {
+ position: relative; display: flex; gap: 0;
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px); overflow: hidden;
+ transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-base, 220ms) var(--ease-out), opacity var(--duration-base) var(--ease-out), box-shadow var(--duration-fast) var(--ease-standard);
+}
+.mem-card:hover { border-color: var(--stroke-strong, rgba(255, 255, 255, 0.16)); }
+.mem-card--sel { border-color: var(--mem-working); box-shadow: 0 0 0 1px var(--mem-working); }
+.mem-card--new { animation: mem-card-in var(--duration-slow, 320ms) var(--ease-out); }
+@keyframes mem-card-in { from { opacity: 0; transform: translateY(-8px) scale(0.99); } to { opacity: 1; transform: none; } }
+.mem-card--leaving { opacity: 0; transform: translateX(12px); }
+
+.mem-card-check { margin: 12px 0 0 12px; accent-color: var(--mem-working); }
+.mem-card-rail { width: 3px; flex: none; background: var(--mem-recall); }
+.mem-card-rail[data-tier='working'] { background: var(--mem-working); }
+.mem-card-rail[data-tier='recall'] { background: var(--mem-recall); }
+.mem-card-rail[data-tier='archival'] { background: var(--mem-archival); }
+.mem-card-main { flex: 1; min-width: 0; padding: 11px 13px; display: flex; flex-direction: column; gap: 8px; }
+
+.mem-card-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.mem-badge {
+ font-size: 10px; font-weight: var(--weight-bold, 700); text-transform: uppercase; letter-spacing: 0.04em;
+ padding: 2px 7px; border-radius: var(--radius-sm, 6px);
+ background: var(--surface-3, rgba(255, 255, 255, 0.08)); color: var(--ink-dim, #888);
+}
+.mem-badge[data-type='user'] { color: #93c5fd; background: rgba(59, 130, 246, 0.14); }
+.mem-badge[data-type='feedback'] { color: #fca5a5; background: rgba(239, 68, 68, 0.14); }
+.mem-badge[data-type='project'] { color: #86efac; background: rgba(34, 197, 94, 0.14); }
+.mem-badge[data-type='reference'] { color: #c4b5fd; background: rgba(139, 92, 246, 0.14); }
+.mem-tier-tag {
+ font-size: 10px; font-weight: var(--weight-semibold, 600); padding: 1px 7px; border-radius: var(--radius-pill, 999px);
+ border: 1px solid var(--stroke);
+}
+.mem-tier-tag[data-tier='working'] { color: var(--mem-working); border-color: rgba(139, 92, 246, 0.4); }
+.mem-tier-tag[data-tier='recall'] { color: var(--mem-recall); border-color: rgba(34, 211, 238, 0.4); }
+.mem-tier-tag[data-tier='archival'] { color: #94a3b8; border-color: rgba(100, 116, 139, 0.4); }
+.mem-pin-on { color: #fbbf24; font-size: 12px; }
+.mem-embed-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80); box-shadow: 0 0 6px rgba(74, 222, 128, 0.6); }
+.mem-embed-dot.pending { background: var(--ink-faint, #555); box-shadow: none; animation: mem-pulse 1.6s ease-in-out infinite; }
+@keyframes mem-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
+.mem-card-time { margin-left: auto; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-faint, #666); white-space: nowrap; }
+.mem-recalls { font-size: var(--text-2xs); color: var(--ink-faint); }
+.mem-step { display: inline-grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; background: var(--mem-working); color: #fff; font-size: 10px; font-weight: 700; }
+
+.mem-card-content {
+ font-size: var(--text-md, 0.8125rem); line-height: var(--leading-normal, 1.55); color: var(--ink, #e8e8e8);
+ white-space: pre-wrap; word-break: break-word;
+ display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer;
+}
+.mem-card-content.expanded { -webkit-line-clamp: unset; }
+
+.mem-card-foot { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
+.mem-tags { display: flex; gap: 5px; flex-wrap: wrap; flex: 1; min-width: 0; }
+.mem-tag {
+ cursor: pointer; font-size: 10px; color: var(--ink-dim, #888); padding: 1px 7px;
+ border-radius: var(--radius-pill, 999px); background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.mem-tag:hover { color: var(--ink-bright, #fff); background: var(--surface-3); }
+.mem-sal { display: inline-flex; align-items: center; gap: 7px; }
+.mem-sal-range { width: 88px; accent-color: var(--mem-working); cursor: pointer; }
+.mem-sal-val { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); font-variant-numeric: tabular-nums; min-width: 28px; }
+
+.mem-card-tools { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+.mem-tool, .mem-tool-select {
+ appearance: none; cursor: pointer; font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600);
+ padding: 4px 9px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03)); color: var(--ink-dim, #888); font-family: var(--font-body);
+ transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.mem-tool:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong); background: var(--surface-2); }
+.mem-tool-danger:hover { color: var(--danger, #f87171); border-color: rgba(248, 113, 113, 0.4); }
+.mem-tool-select { padding: 4px 6px; }
+
+/* ── Inline edit / composer ──────────────────────────────────────────────── */
+.mem-edit, .mem-composer { display: flex; flex-direction: column; gap: 8px; }
+.mem-composer {
+ background: var(--surface-2, rgba(255, 255, 255, 0.05)); border: 1px solid var(--mem-working);
+ border-radius: var(--radius-md, 10px); padding: 12px; margin-bottom: 12px;
+ animation: mem-card-in var(--duration-base) var(--ease-out);
+}
+.mem-composer-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.mem-composer-pin { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs); color: var(--ink-dim); }
+.mem-edit-content, .mem-edit-tags, .mem-composer-content, .mem-composer-tags,
+.mem-composer-type, .mem-composer-tier {
+ background: var(--surface-1, rgba(0, 0, 0, 0.3)); border: 1px solid var(--stroke); border-radius: var(--radius-sm, 6px);
+ color: var(--ink-bright, #fff); font-family: var(--font-body); font-size: var(--text-md, 0.8125rem); padding: 7px 9px; outline: none;
+}
+.mem-edit-content, .mem-composer-content { resize: vertical; width: 100%; box-sizing: border-box; }
+.mem-edit-content:focus, .mem-edit-tags:focus, .mem-composer-content:focus, .mem-composer-tags:focus { border-color: var(--mem-working); }
+.mem-edit-tools, .mem-composer-tools, .mem-edit-tools { display: flex; gap: 8px; }
+
+/* ── Empty / first-run ───────────────────────────────────────────────────── */
+.mem-empty, .mem-first { text-align: center; max-width: 460px; margin: clamp(20px, 6vh, 60px) auto; color: var(--ink-dim, #888); }
+.mem-empty-glyph, .mem-first-glyph {
+ font-size: 40px; margin-bottom: var(--space-sm); opacity: 0.7; color: var(--mem-working);
+}
+.mem-empty h3, .mem-first h3 { margin: 0 0 6px; font-family: var(--font-display); font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); }
+.mem-empty p, .mem-first p { margin: 0 0 var(--space-md); font-size: var(--text-md, 0.8125rem); line-height: var(--leading-normal, 1.618); }
+.mem-tier-legend { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: var(--space-md) 0; text-align: left; }
+.mem-tier-card { padding: 10px; border-radius: var(--radius-md); border: 1px solid var(--stroke); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; }
+.mem-tier-card[data-tier='working'] { border-color: rgba(139, 92, 246, 0.35); }
+.mem-tier-card[data-tier='recall'] { border-color: rgba(34, 211, 238, 0.3); }
+.mem-tier-card strong { color: var(--ink-bright, #fff); font-size: var(--text-md); }
+.mem-tier-card span { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); }
+.mem-first-cta { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
+.mem-more { text-align: center; padding: 14px; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-faint, #666); }
+
+/* ── Skeleton ────────────────────────────────────────────────────────────── */
+.mem-skel { display: flex; flex-direction: column; gap: 10px; }
+.mem-skel-row {
+ height: 80px; border-radius: var(--radius-md, 10px);
+ background: linear-gradient(110deg, rgba(255, 255, 255, 0.03) 30%, rgba(255, 255, 255, 0.07) 50%, rgba(255, 255, 255, 0.03) 70%);
+ background-size: 220% 100%; animation: mem-shimmer 1.4s ease-in-out infinite;
+}
+@keyframes mem-shimmer { to { background-position: -220% 0; } }
+
+/* ── Graph ───────────────────────────────────────────────────────────────── */
+.mem-graph-wrap { position: relative; height: clamp(380px, 60vh, 680px); border-radius: var(--radius-md, 10px); border: 1px solid var(--stroke); overflow: hidden; background: radial-gradient(120% 90% at 50% 0%, rgba(139, 92, 246, 0.06), transparent 60%), var(--surface-1); }
+.mem-graph-canvas { width: 100%; height: 100%; display: block; }
+.mem-graph-legend { position: absolute; left: 12px; top: 12px; display: flex; flex-wrap: wrap; gap: 10px; padding: 8px 11px; border-radius: var(--radius-md); background: rgba(0, 0, 0, 0.45); backdrop-filter: blur(var(--blur-sm, 8px)); border: 1px solid var(--stroke); }
+.mem-legend-item { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); }
+.mem-legend-item i { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }
+.mem-graph-empty { position: absolute; inset: 0; display: grid; place-items: center; text-align: center; padding: 24px; color: var(--ink-dim, #888); }
+.mem-graph-empty p { max-width: 340px; font-size: var(--text-md); line-height: var(--leading-normal); }
+
+/* ── Entity drilldown ────────────────────────────────────────────────────── */
+.mem-entity-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: var(--space-md); }
+.mem-back { appearance: none; cursor: pointer; background: none; border: none; color: var(--ink-dim, #888); font-size: var(--text-md); font-family: var(--font-body); padding: 2px 0; transition: color var(--duration-fast) var(--ease-standard); }
+.mem-back:hover { color: var(--ink-bright, #fff); }
+.mem-entity-kind { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; padding: 2px 8px; border-radius: var(--radius-pill); color: var(--c); border: 1px solid color-mix(in srgb, var(--c) 40%, transparent); }
+.mem-entity-head h3 { margin: 0; font-family: var(--font-display); font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); word-break: break-all; }
+.mem-entity-stat { font-size: var(--text-2xs); color: var(--ink-dim); }
+.mem-entity-replay-note { font-size: var(--text-md); color: var(--ink-dim); margin: 0 0 var(--space-md); }
+
+/* ── In context ──────────────────────────────────────────────────────────── */
+.mem-ctx { display: flex; flex-direction: column; gap: var(--space-md); }
+.mem-ctx-budget { padding: 14px; border-radius: var(--radius-md); border: 1px solid var(--stroke); background: var(--surface-1); }
+.mem-ctx-budget.over { border-color: rgba(251, 191, 36, 0.5); }
+.mem-ctx-budget-top { display: flex; justify-content: space-between; font-size: var(--text-md, 0.8125rem); color: var(--ink, #e8e8e8); margin-bottom: 8px; }
+.mem-ctx-tokens { color: var(--ink-dim, #888); font-variant-numeric: tabular-nums; }
+.mem-ctx-bar { height: 8px; border-radius: var(--radius-pill); background: var(--surface-3, rgba(255, 255, 255, 0.08)); overflow: hidden; }
+.mem-ctx-fill { height: 100%; border-radius: var(--radius-pill); background: linear-gradient(90deg, var(--mem-working), var(--mem-recall)); transition: width var(--duration-slow, 320ms) var(--ease-out); }
+.mem-ctx-budget.over .mem-ctx-fill { background: linear-gradient(90deg, #f59e0b, #f87171); }
+.mem-ctx-warn { margin: 8px 0 0; font-size: var(--text-2xs, 0.6875rem); color: var(--warn, #fbbf24); }
+.mem-ctx-counts { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; }
+.mem-count { padding: 10px; border-radius: var(--radius-md); border: 1px solid var(--stroke); background: var(--surface-1); text-align: center; display: flex; flex-direction: column; gap: 2px; }
+.mem-count b { font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }
+.mem-count span { font-size: 10px; color: var(--ink-dim, #888); text-transform: uppercase; letter-spacing: 0.04em; }
+.mem-count[data-tier='working'] b { color: var(--mem-working); }
+.mem-count[data-tier='recall'] b { color: var(--mem-recall); }
+.mem-ctx-title { margin: 4px 0 0; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); text-transform: uppercase; letter-spacing: 0.05em; }
+
+/* ── Search results ──────────────────────────────────────────────────────── */
+.mem-search-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: var(--space-md); }
+.mem-search-head h3 { margin: 0; font-family: var(--font-display); font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); }
+.mem-search-note { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-faint, #666); }
+.mem-score { font-size: 10px; font-weight: 700; padding: 2px 7px; border-radius: var(--radius-pill); background: rgba(139, 92, 246, 0.18); color: #c4b5fd; font-variant-numeric: tabular-nums; }
+.mem-score-lex { background: var(--surface-3); color: var(--ink-dim); }
+
+/* ── Merge bar ───────────────────────────────────────────────────────────── */
+.mem-merge-bar {
+ position: sticky; bottom: 0; display: flex; align-items: center; gap: 10px; justify-content: center;
+ padding: 10px; border-radius: var(--radius-md); border: 1px solid var(--mem-working);
+ background: rgba(20, 16, 32, 0.9); backdrop-filter: blur(var(--blur-sm, 8px));
+ font-size: var(--text-md); color: var(--ink-bright, #fff);
+ animation: mem-card-in var(--duration-base) var(--ease-out);
+}
+
+/* ── Seed modal ──────────────────────────────────────────────────────────── */
+.mem-seed-modal { position: fixed; inset: 0; z-index: 60; display: grid; place-items: center; padding: var(--space-md); background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(var(--blur-sm, 8px)); animation: mem-fade var(--duration-base) var(--ease-out); }
+@keyframes mem-fade { from { opacity: 0; } to { opacity: 1; } }
+.mem-seed-card { width: min(520px, 100%); max-height: 86vh; overflow-y: auto; background: var(--surface-1, #14151c); border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16)); border-radius: var(--radius-lg, 14px); padding: var(--space-lg, 1.618rem); box-shadow: var(--shadow-2); }
+.mem-seed-head { display: flex; align-items: center; justify-content: space-between; }
+.mem-seed-head h3 { margin: 0; font-family: var(--font-display); font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); }
+.mem-seed-x { appearance: none; cursor: pointer; background: none; border: none; color: var(--ink-dim); font-size: 24px; line-height: 1; padding: 0 4px; }
+.mem-seed-x:hover { color: var(--ink-bright, #fff); }
+.mem-seed-sub { font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); line-height: var(--leading-normal); margin: 6px 0 var(--space-md); }
+.mem-seed-conns { display: flex; flex-direction: column; gap: 10px; margin-bottom: var(--space-md); }
+.mem-seed-conn { display: grid; grid-template-columns: 90px 1fr 14px; align-items: center; gap: 10px; }
+.mem-seed-conn label { font-size: var(--text-md); color: var(--ink, #e8e8e8); }
+.mem-seed-conn input { background: var(--surface-2, rgba(0, 0, 0, 0.3)); border: 1px solid var(--stroke); border-radius: var(--radius-sm); color: var(--ink-bright, #fff); padding: 7px 9px; font-family: var(--font-body); outline: none; }
+.mem-seed-conn input:focus { border-color: var(--mem-working); }
+.mem-seed-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--surface-3); }
+.mem-seed-dot.loading { background: var(--warn, #fbbf24); animation: mem-pulse 1s ease-in-out infinite; }
+.mem-seed-dot.ok { background: var(--success, #4ade80); }
+.mem-seed-dot.err { background: var(--danger, #f87171); }
+.mem-seed-out { margin-top: var(--space-md); padding: 12px; border-radius: var(--radius-md); background: var(--surface-2, rgba(0, 0, 0, 0.3)); border: 1px solid var(--stroke); font-size: var(--text-md, 0.8125rem); color: var(--ink, #e8e8e8); white-space: pre-wrap; max-height: 240px; overflow-y: auto; line-height: var(--leading-normal); }
+.mem-seed-fail { color: var(--danger, #f87171); }
+.mem-seed-tools { display: flex; align-items: center; gap: 10px; margin-top: var(--space-md); }
+.mem-seed-notice { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); }
+
+/* ── Toast ───────────────────────────────────────────────────────────────── */
+.mem-toast {
+ position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%) translateY(12px);
+ padding: 9px 16px; border-radius: var(--radius-pill, 999px); background: rgba(20, 16, 32, 0.95);
+ border: 1px solid var(--mem-working); color: var(--ink-bright, #fff); font-size: var(--text-md, 0.8125rem);
+ box-shadow: var(--shadow-2); opacity: 0; pointer-events: none; z-index: 40;
+ transition: opacity var(--duration-base) var(--ease-out), transform var(--duration-base) var(--ease-out);
+}
+.mem-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
+.mem-toast-err { border-color: var(--danger, #f87171); }
+
+/* ── Responsive ──────────────────────────────────────────────────────────── */
+@media (max-width: 640px) {
+ .mem-tier-legend { grid-template-columns: 1fr; }
+ .mem-ctx-counts { grid-template-columns: repeat(3, 1fr); }
+ .mem-toolbar { flex-direction: column; align-items: stretch; }
+ .mem-views { justify-content: center; }
+ .mem-actions { justify-content: flex-end; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .mem-card--new, .mem-composer, .mem-merge-bar, .mem-seed-modal { animation: none; }
+ .mem-skel-row, .mem-embed-dot.pending, .mem-seed-dot.loading { animation: none; }
+ .mem-ctx-fill, .mem-toast { transition: none; }
+}
diff --git a/src/studio/memory/memory-studio.js b/src/studio/memory/memory-studio.js
index fac3cca6e..3e2f1da0b 100644
--- a/src/studio/memory/memory-studio.js
+++ b/src/studio/memory/memory-studio.js
@@ -201,6 +201,8 @@ class MemoryStudio {
}
_selectView(view) {
+ // Tear down the graph sim (RAF + window/canvas listeners) when leaving it.
+ if (view !== 'graph' && this._graph) { this._graph.destroy(); this._graph = null; }
this.state.view = view;
this.state.search = null;
this.state.entity = null;
@@ -313,10 +315,12 @@ class MemoryStudio {
${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.
+ // Mark newly arrived for entrance animation, then remember them so they
+ // only animate once (a filter re-render won't re-trigger the entrance).
host.querySelectorAll('.mem-card--new').forEach((c) => {
requestAnimationFrame(() => c.classList.remove('mem-card--new'));
});
+ slice.forEach((m) => this._knownIds.add(m.id));
}
_card(m) {
diff --git a/tests/memory-endpoints.test.js b/tests/memory-endpoints.test.js
new file mode 100644
index 000000000..7ae86c354
--- /dev/null
+++ b/tests/memory-endpoints.test.js
@@ -0,0 +1,175 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' } }));
+
+const searchMemories = vi.fn();
+const computeContext = vi.fn();
+const buildGraph = vi.fn();
+const memoriesForEntity = vi.fn();
+vi.mock('../api/_lib/memory-store.js', () => ({
+ searchMemories: (...a) => searchMemories(...a),
+ computeContext: (...a) => computeContext(...a),
+ buildGraph: (...a) => buildGraph(...a),
+ memoriesForEntity: (...a) => memoriesForEntity(...a),
+ decorateMemory: (row) => ({ id: row.id, tier: row.tier, pinned: row.pinned }),
+ MEMORY_TIERS: ['working', 'recall', 'archival'],
+ WORKING_TOKEN_BUDGET: 2000,
+}));
+
+const { default: searchHandler } = await import('../api/memory/search.js');
+const { default: curateHandler } = await import('../api/memory/curate.js');
+const { default: graphHandler } = await import('../api/memory/graph.js');
+
+function mkReq({ method = 'GET', url = '/api/memory/search', headers = {}, body = null } = {}) {
+ return {
+ method, url, headers: { ...headers },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') this._endCb = cb;
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+let sqlQueue = [];
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset().mockImplementation(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []));
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+ searchMemories.mockReset().mockResolvedValue({ results: [], provider: true, scored: 0 });
+ computeContext.mockReset();
+ buildGraph.mockReset().mockResolvedValue({ nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
+ memoriesForEntity.mockReset().mockResolvedValue([]);
+});
+
+describe('GET /api/memory/search', () => {
+ it('anonymous → empty results, never searches', async () => {
+ const res = mkRes();
+ await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=hi' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ results: [] });
+ expect(searchMemories).not.toHaveBeenCalled();
+ });
+
+ it('400 without agentId', async () => {
+ const res = mkRes();
+ await searchHandler(mkReq({ url: '/api/memory/search?q=hi' }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('owner GET searches and returns results', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ sqlQueue.push([{ user_id: 'u1' }]); // ownership
+ searchMemories.mockResolvedValue({ results: [{ id: 'm1', match: 'semantic' }], provider: true, scored: 1 });
+ const res = mkRes();
+ await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=sell' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).results).toHaveLength(1);
+ expect(searchMemories).toHaveBeenCalledWith('a1', 'sell', expect.any(Object));
+ });
+
+ it('non-owner GET → empty', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ sqlQueue.push([{ user_id: 'someone-else' }]);
+ const res = mkRes();
+ await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=x' }), res);
+ expect(parse(res)).toEqual({ results: [] });
+ });
+});
+
+describe('POST /api/memory/curate', () => {
+ beforeEach(() => getSessionUserMock.mockResolvedValue({ id: 'u1' }));
+
+ it('401 without auth', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('403 when not owner', async () => {
+ sqlQueue.push([{ user_id: 'other' }]);
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('pin updates the memory and returns the entry', async () => {
+ sqlQueue.push([{ user_id: 'u1' }]); // ownership
+ sqlQueue.push([{ id: 'm1', tier: 'working', pinned: true }]); // update
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).entry).toMatchObject({ id: 'm1', pinned: true });
+ });
+
+ it('rejects an invalid tier', async () => {
+ sqlQueue.push([{ user_id: 'u1' }]);
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'tier', memoryId: 'm1', tier: 'bogus' } }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('merge needs at least two ids', async () => {
+ sqlQueue.push([{ user_id: 'u1' }]);
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'merge', memoryIds: ['only-one'] } }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('forget deletes the memory', async () => {
+ sqlQueue.push([{ user_id: 'u1' }]); // ownership
+ sqlQueue.push([{ id: 'm1' }]); // delete returning
+ const res = mkRes();
+ await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'forget', memoryId: 'm1' } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ ok: true, forgot: 'm1' });
+ });
+});
+
+describe('GET /api/memory/graph', () => {
+ it('owner gets the graph', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ sqlQueue.push([{ user_id: 'u1' }]);
+ buildGraph.mockResolvedValue({ nodes: [{ id: 'e1' }], edges: [], stats: { entities: 1, edges: 0 } });
+ const res = mkRes();
+ await graphHandler(mkReq({ url: '/api/memory/graph?agentId=a1' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).nodes).toHaveLength(1);
+ });
+
+ it('entity drilldown returns memories', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ sqlQueue.push([{ user_id: 'u1' }]);
+ memoriesForEntity.mockResolvedValue([{ id: 'm1' }]);
+ const res = mkRes();
+ await graphHandler(mkReq({ url: '/api/memory/graph?agentId=a1&entityId=e1' }), res);
+ expect(parse(res).memories).toHaveLength(1);
+ expect(memoriesForEntity).toHaveBeenCalledWith('a1', 'e1');
+ });
+});
diff --git a/tests/memory-entities.test.js b/tests/memory-entities.test.js
new file mode 100644
index 000000000..40bf6153e
--- /dev/null
+++ b/tests/memory-entities.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import { extractEntities, ENTITY_KINDS } from '../api/_lib/memory-entities.js';
+
+describe('memory entity extraction', () => {
+ it('extracts cashtags as uppercase tickers', () => {
+ const ents = extractEntities('Bought more $three and $sol today');
+ const tickers = ents.filter((e) => e.kind === 'ticker').map((e) => e.label);
+ expect(tickers).toContain('THREE');
+ expect(tickers).toContain('SOL');
+ });
+
+ it('extracts @handles as people', () => {
+ const ents = extractEntities('chatting with @satoshi about the launch');
+ expect(ents.find((e) => e.kind === 'person' && e.label === '@satoshi')).toBeTruthy();
+ });
+
+ it('classifies a base58 address as a mint when the memory is trade-flavored', () => {
+ const mint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+ const ents = extractEntities(`sniped the token ${mint}`, ['snipe']);
+ expect(ents.find((e) => e.kind === 'mint' && e.label === mint)).toBeTruthy();
+ });
+
+ it('classifies a bare base58 address as a wallet without trade context', () => {
+ // Clearly-synthetic base58 (matches the 32–44 char pattern, real to no one).
+ const addr = 'WaLLeTsynthetic1111111111111111111111111111';
+ const ents = extractEntities(`sent funds to ${addr}`);
+ expect(ents.find((e) => e.kind === 'wallet' && e.label === addr)).toBeTruthy();
+ });
+
+ it('pulls structured context fields (mint, symbol, wallet)', () => {
+ const ents = extractEntities('position update', ['trade'], {
+ mint: 'THREEsynthetic1111111111111111111111111111',
+ symbol: 'three',
+ wallet: '0xabc0000000000000000000000000000000000def',
+ });
+ expect(ents.find((e) => e.kind === 'mint')).toBeTruthy();
+ expect(ents.find((e) => e.kind === 'ticker' && e.label === 'THREE')).toBeTruthy();
+ expect(ents.find((e) => e.kind === 'wallet')).toBeTruthy();
+ });
+
+ it('flags strategy memories', () => {
+ const ents = extractEntities('Rule: always set a stop-loss at -20%', ['rule']);
+ expect(ents.find((e) => e.kind === 'strategy')).toBeTruthy();
+ });
+
+ it('turns meaningful tags into topics but drops studio/chat/seed noise', () => {
+ const ents = extractEntities('note', ['watchlist', 'studio', 'chat', 'seed']);
+ const topics = ents.filter((e) => e.kind === 'topic').map((e) => e.label);
+ expect(topics).toContain('watchlist');
+ expect(topics).not.toContain('studio');
+ expect(topics).not.toContain('chat');
+ });
+
+ it('deduplicates repeated entities and only emits known kinds', () => {
+ const ents = extractEntities('$THREE $THREE $three');
+ expect(ents.filter((e) => e.kind === 'ticker')).toHaveLength(1);
+ for (const e of ents) expect(ENTITY_KINDS).toContain(e.kind);
+ });
+
+ it('extracts EVM addresses as wallets', () => {
+ const ents = extractEntities('treasury 0x1234567890abcdef1234567890ABCDEF12345678');
+ expect(ents.find((e) => e.kind === 'wallet')).toBeTruthy();
+ });
+});
diff --git a/tests/memory-store.test.js b/tests/memory-store.test.js
new file mode 100644
index 000000000..e529be9f0
--- /dev/null
+++ b/tests/memory-store.test.js
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+// `sql` is a tagged template — mock it as a fn returning queued FIFO results.
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+// Control embedding configuration / vectors per test.
+const embeddingsConfigured = vi.fn(() => true);
+const defaultIngestEmbedderTag = vi.fn(() => 'nvidia/nv-embedqa-e5-v5@1024');
+const embedPassages = vi.fn();
+const scoreRowsBySpace = vi.fn();
+vi.mock('../api/_lib/embeddings.js', () => ({
+ embeddingsConfigured: (...a) => embeddingsConfigured(...a),
+ defaultIngestEmbedderTag: (...a) => defaultIngestEmbedderTag(...a),
+ embedPassages: (...a) => embedPassages(...a),
+ scoreRowsBySpace: (...a) => scoreRowsBySpace(...a),
+}));
+
+const {
+ searchMemories,
+ computeContext,
+ buildGraph,
+ estimateTokens,
+ defaultTier,
+ WORKING_TOKEN_BUDGET,
+} = await import('../api/_lib/memory-store.js');
+
+let sqlQueue = [];
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset();
+ sqlMock.mockImplementation(() => {
+ if (!sqlQueue.length) throw new Error('unexpected sql call — no queued response');
+ return Promise.resolve(sqlQueue.shift());
+ });
+ embeddingsConfigured.mockReturnValue(true);
+ defaultIngestEmbedderTag.mockReturnValue('nvidia/nv-embedqa-e5-v5@1024');
+ embedPassages.mockReset();
+ scoreRowsBySpace.mockReset();
+});
+function queueSql(...r) { sqlQueue.push(...r); }
+
+describe('estimateTokens / defaultTier', () => {
+ it('estimates ~4 chars per token', () => {
+ expect(estimateTokens('12345678')).toBe(2);
+ });
+ it('assigns working when pinned, archival for low-salience reference', () => {
+ expect(defaultTier({ pinned: true })).toBe('working');
+ expect(defaultTier({ type: 'reference', salience: 0.2 })).toBe('archival');
+ expect(defaultTier({ salience: 0.6, type: 'project' })).toBe('recall');
+ });
+});
+
+describe('searchMemories', () => {
+ it('ranks by real cosine score and bumps access', async () => {
+ // 1) ensureEmbeddings: no rows need embedding
+ queueSql([]);
+ // 2) candidate rows fetch
+ queueSql([
+ { id: 'a', type: 'project', content: 'stop loss rule', tags: [], context: {}, salience: 0.5, tier: 'recall', embedder: 'nvidia/nv-embedqa-e5-v5@1024', embedding: [0.1, 0.2], created_at: new Date() },
+ { id: 'b', type: 'project', content: 'unrelated', tags: [], context: {}, salience: 0.5, tier: 'recall', embedder: 'nvidia/nv-embedqa-e5-v5@1024', embedding: [0.9, 0.1], created_at: new Date() },
+ ]);
+ // 3) access bump UPDATE (fire-and-forget — still consumes a queued result)
+ queueSql([]);
+
+ scoreRowsBySpace.mockResolvedValue({
+ scored: [
+ { id: 'a', type: 'project', content: 'stop loss rule', tags: [], context: {}, salience: 0.5, tier: 'recall', created_at: new Date(), score: 0.91 },
+ { id: 'b', type: 'project', content: 'unrelated', tags: [], context: {}, salience: 0.5, tier: 'recall', created_at: new Date(), score: 0.12 },
+ ],
+ needsReembed: [],
+ });
+
+ const out = await searchMemories('agent1', 'when do I sell', { topK: 5, minScore: 0.5 });
+ expect(out.provider).toBe(true);
+ expect(out.results).toHaveLength(1); // only 'a' clears minScore
+ expect(out.results[0].id).toBe('a');
+ expect(out.results[0].match).toBe('semantic');
+ expect(out.results[0].score).toBeCloseTo(0.91, 2);
+ });
+
+ it('falls back to substring + salience when no provider', async () => {
+ embeddingsConfigured.mockReturnValue(false);
+ // ensureEmbeddings short-circuits (no sql). Then candidate fetch:
+ queueSql([
+ { id: 'a', type: 'project', content: 'remember the watchlist', tags: [], context: {}, salience: 0.8, tier: 'recall', embedder: null, embedding: null, created_at: new Date() },
+ { id: 'b', type: 'project', content: 'nothing', tags: [], context: {}, salience: 0.9, tier: 'recall', embedder: null, embedding: null, created_at: new Date() },
+ ]);
+ // access bump
+ queueSql([]);
+
+ const out = await searchMemories('agent1', 'watchlist', { topK: 5 });
+ expect(out.provider).toBe(false);
+ expect(out.results).toHaveLength(1);
+ expect(out.results[0].id).toBe('a');
+ expect(out.results[0].match).toBe('lexical');
+ });
+
+ it('returns empty for a blank query without touching the db', async () => {
+ const out = await searchMemories('agent1', ' ', {});
+ expect(out.results).toEqual([]);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('computeContext', () => {
+ it('sums tokens of the working set and flags over-budget', async () => {
+ const big = 'x'.repeat(WORKING_TOKEN_BUDGET * 4 + 40); // > budget tokens
+ queueSql([
+ { id: 'w', type: 'user', content: big, tags: [], context: {}, salience: 1, tier: 'working', pinned: true, created_at: new Date() },
+ ]);
+ queueSql([{ total: 3, working: 1, recall: 1, archival: 1, embedded: 1 }]);
+
+ const ctx = await computeContext('agent1');
+ expect(ctx.entries).toHaveLength(1);
+ expect(ctx.budget).toBe(WORKING_TOKEN_BUDGET);
+ expect(ctx.overBudget).toBe(true);
+ expect(ctx.counts.total).toBe(3);
+ });
+});
+
+describe('buildGraph', () => {
+ it('derives co-occurrence edges from shared memories', async () => {
+ // ensureEntities: no unprocessed rows
+ queueSql([]);
+ // entities
+ queueSql([
+ { id: 'e1', kind: 'mint', label: 'MintA', normalized: 'minta', salience: 0.6, mention_count: 3, first_seen_at: new Date(), last_seen_at: new Date(), meta: {} },
+ { id: 'e2', kind: 'ticker', label: 'AAA', normalized: 'aaa', salience: 0.6, mention_count: 2, first_seen_at: new Date(), last_seen_at: new Date(), meta: {} },
+ ]);
+ // links — both entities appear in memory m1 → one edge
+ queueSql([
+ { entity_id: 'e1', memory_id: 'm1' },
+ { entity_id: 'e2', memory_id: 'm1' },
+ ]);
+
+ const g = await buildGraph('agent1');
+ expect(g.nodes).toHaveLength(2);
+ expect(g.edges).toHaveLength(1);
+ expect(g.edges[0]).toMatchObject({ weight: 1 });
+ const pair = [g.edges[0].source, g.edges[0].target].sort();
+ expect(pair).toEqual(['e1', 'e2']);
+ });
+
+ it('returns an empty graph when there are no entities', async () => {
+ queueSql([]); // ensureEntities
+ queueSql([]); // entities
+ const g = await buildGraph('agent1');
+ expect(g).toEqual({ nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
+ });
+});