Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(rag): T3.1 audit gap-closure + T3.2 re-embed migration unit tests
nirholas937c3e152f9a
diff --git a/scripts/reembed-widget-knowledge.mjs b/scripts/reembed-widget-knowledge.mjsindex 426b10896..34a8ac214 100644--- a/scripts/reembed-widget-knowledge.mjs+++ b/scripts/reembed-widget-knowledge.mjs@@ -35,6 +35,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url';const __dirname = dirname(fileURLToPath(import.meta.url));const root = resolve(__dirname, '..');+// Env loading happens inside main() (not at import time) so the exported+// functions stay side-effect-free for unit tests.function loadEnvFile(path) {let raw;try {@@ -50,8 +52,6 @@ function loadEnvFile(path) {process.env[k] = v.replace(/^["']|["']$/g, '');}}-loadEnvFile(resolve(root, '.env.local'));-loadEnvFile(resolve(root, '.env'));const { NIM_EMBED_TAG, embedderConfigured, embedPassages } = await import('../api/_lib/embeddings.js'@@ -198,6 +198,9 @@ export function summarizePlan(plan, { batch = DEFAULT_BATCH, throttleMs = DEFAUL}async function main() {+ loadEnvFile(resolve(root, '.env.local'));+ loadEnvFile(resolve(root, '.env'));+const args = parseCliArgs(process.argv.slice(2));const targetTag = NIM_EMBED_TAG;diff --git a/tasks/nvidia-nim/PLAN.md b/tasks/nvidia-nim/PLAN.mdindex 61cba6050..64dd73687 100644--- a/tasks/nvidia-nim/PLAN.md+++ b/tasks/nvidia-nim/PLAN.md@@ -50,7 +50,7 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)### Phase 3 — Widget RAG back online- [x] **T3.1** [30-embeddings-multiprovider.md](30-embeddings-multiprovider.md) — multi-provider embeddings, vector-space tagging (NIM free primary, OpenAI backstop, per-doc-set tag; same-space query routing + cross-space refusal; 47 tests green — see Worklog 2026-06-11)-- [ ] **T3.2** [31-reembed-migration.md](31-reembed-migration.md) — re-embed migration script + run (+ optional reranker)+- [~] **T3.2** [31-reembed-migration.md](31-reembed-migration.md) — re-embed migration script + run (+ optional reranker) (script + 15 unit tests done, dry-run executed against prod: 0 legacy rows; real run is a post-T3.1-deploy formality — see Worklog 2026-06-11)- [ ] **T3.3** [32-rag-verify.md](32-rag-verify.md) — RAG verified end-to-end in prod + changelog### Phase 4 — Expansion lanes (after 1–3)@@ -100,6 +100,48 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)## Worklog (append-only; newest at top)+- **2026-06-11** — **T3.1 audit of `771c84b4` + gap closure; T3.2 re-embed script done+ (dry-run executed; prod run pending the T3.1 deploy).**+ **Audit verdict:** `771c84b4` implemented free-first embeddings on a *different* surface —+ `/api/agents/:id/embed` (the AgentMemory.recall embedder; NIM `baai/bge-m3` → paid Voyage)+ — and touched none of T3.1's actual targets (`api/_lib/embeddings.js`, the widget+ knowledge schema/search). Live-probed its model choice with the restored key:+ `baai/bge-m3` is invocable on this account (200, 1024-dim — the catalog "presence ≠+ invocable" trap did NOT bite), works without `input_type` (symmetric) and its 8192-token+ context fits that endpoint's 8192-char contract, so the model stands. **One real trap the+ commit left open, now closed:** it returns `model` in the response, but the caller ignored+ it — `src/agent-memory.js` persists embeddings to localStorage, so a provider failover+ (bge-m3 ↔ voyage-3-lite, both 1024-dim) silently cross-compared spaces. Now+ `_makeEmbedFn` (src/agent-identity.js) passes `{vector, model}` through, entries carry+ `embeddingModel`, `recall()` only cosine-compares same-model entries (mismatches fall to+ the substring path), persisted pre-tagging entries default explicitly to `voyage-3-lite`,+ and `cosineSim` refuses mismatched dims and zero vectors (was NaN). +5 recall tests in+ `tests/src/agent-memory.test.js`. The widget-lane T3.1 work itself (see entry below) was+ written this session and swept into `0e19dec7`/`f1587ba9`/`923bbb30` by the concurrent+ committer — verified committed byte-identical. **Live-verified the widget lane end-to-end**+ with the real key: e5-v5 passage+query embeds (1024-dim; right chunk scores 0.529 for a+ France query, others ≤0.16), cross-space refusal of a synthetic legacy row, the 512-token+ over-length 400 → truncation retry against the live endpoint, and the reranker+ (`nvidia/rerank-qa-mistral-4b` → correct full-permutation order).+ **T3.2 script** (`scripts/reembed-widget-knowledge.mjs`, landed in `f1587ba9` + an+ import-side-effect fix here): uses the same access layer as the API (`api/_lib/db.js` ++ `embedPassages`); surveys and classifies every doc (`done`/`flip`/`migrate`/`skip`+reason);+ batch 64 (≤512 probed ceiling), throttled, exponential backoff on 429/5xx/network only+ (never hard 4xx/config errors); resume-safe + idempotent via the per-row `embedder` tag;+ the doc tag flips only after a verified zero-remaining count — atomic per set, and since+ retrieval routes per-chunk tag, mid-migration reads are also correct in both spaces.+ Required `--dry-run` prints per-doc actions + chunk/token/request/credit/time estimates+ and writes nothing. New `tests/reembed-widget-knowledge.test.js` (15 cases against an+ in-memory fake of the two tables): classify matrix, pending-only embeds, crash-mid-set+ leaves the tag unflipped + a resume completes only the remainder, idempotent re-run embeds+ nothing, backoff retry/give-up matrix, write-free dry-run. **Dry-run executed against the+ prod Neon DB: 0 docs / 0 chunks** — the prod corpus is empty today, so the post-deploy+ prod run (the unchecked half of T3.2) is a formality; also confirmed both `embedder`+ columns already exist in prod. **Reranker decision: kept**, implemented behind+ `KNOWLEDGE_RERANK_ENABLED=1` (default OFF, strictly fail-open); the task's "measure top-3+ relevance on a real widget corpus" is impossible with zero stored docs — measure in T3.3+ once a corpus exists, before enabling the flag in prod. Full `tests/api` suite green (120+ files / 1991 tests) plus the targeted new suites (145 tests).- **2026-06-11** — **T3.1 (multi-provider embeddings + vector-space tagging) — DONE,audited & tests green.** Widget RAG was silently broken (OpenAI-only embedder, prod keyover quota); the retrieval lane is now free-first via NIM and, critically, can never mixdiff --git a/tests/reembed-widget-knowledge.test.js b/tests/reembed-widget-knowledge.test.jsnew file mode 100644index 000000000..e28c2a5b4--- /dev/null+++ b/tests/reembed-widget-knowledge.test.js@@ -0,0 +1,335 @@+// Unit tests for scripts/reembed-widget-knowledge.mjs — the T3.2 migration+// that moves stored widget knowledge chunks into the free NIM embedding+// space. Runs the script's exported functions against an in-memory fake of+// the widget_knowledge_docs/_chunks tables, pinning the safety properties:+// idempotent resume via the per-row embedder tag, atomic per-set tag flip,+// 429 backoff, and a write-free dry-run plan.++import { describe, it, expect, vi } from 'vitest';++import {+ parseCliArgs,+ classifyDoc,+ planMigration,+ migrateDoc,+ withBackoff,+ summarizePlan,+} from '../scripts/reembed-widget-knowledge.mjs';++const TARGET = 'nvidia/nv-embedqa-e5-v5@1024';+const LEGACY = 'text-embedding-3-small@256';++// ── In-memory fake of the two tables, routed on the SQL text ────────────────++function makeFakeDb({ docs = [], chunks = [] } = {}) {+ const state = {+ docs: docs.map((d) => ({ ...d })),+ chunks: chunks.map((c) => ({ ...c })),+ writes: 0,+ };++ const sql = async (strings, ...params) => {+ const text = strings.join('?').replace(/\s+/g, ' ');++ if (text.includes('select d.id, d.widget_id')) {+ // planMigration survey: params [targetTag, targetTag, widgetId, widgetId]+ const [targetTag, , widgetId] = params;+ return state.docs+ .filter((d) => widgetId == null || d.widget_id === widgetId)+ .map((d) => {+ const mine = state.chunks.filter((c) => c.doc_id === d.id);+ const pending = mine.filter((c) => c.embedder !== targetTag);+ return {+ id: d.id,+ widget_id: d.widget_id,+ title: d.title,+ status: d.status,+ doc_embedder: d.embedder,+ total_chunks: mine.length,+ pending_chunks: pending.length,+ pending_tokens: pending.reduce((s, c) => s + (c.token_count || 0), 0),+ };+ });+ }++ if (text.includes('select id, content from widget_knowledge_chunks')) {+ const [docId, targetTag, limit] = params;+ return state.chunks+ .filter((c) => c.doc_id === docId && c.embedder !== targetTag)+ .sort((a, b) => a.chunk_index - b.chunk_index)+ .slice(0, limit)+ .map((c) => ({ id: c.id, content: c.content }));+ }++ if (text.includes('update widget_knowledge_chunks')) {+ const [vecJson, targetTag, id] = params;+ const row = state.chunks.find((c) => c.id === id);+ row.embedding = JSON.parse(vecJson);+ row.embedder = targetTag;+ state.writes++;+ return [];+ }++ if (text.includes('select count(*)::int as remaining')) {+ const [docId, targetTag] = params;+ const remaining = state.chunks.filter(+ (c) => c.doc_id === docId && c.embedder !== targetTag,+ ).length;+ return [{ remaining }];+ }++ if (text.includes('update widget_knowledge_docs set embedder')) {+ const [targetTag, docId] = params;+ state.docs.find((d) => d.id === docId).embedder = targetTag;+ state.writes++;+ return [];+ }++ throw new Error(`fake db: unrecognized query: ${text.slice(0, 80)}`);+ };++ return { sql, state };+}++function legacyChunk(id, docId, index) {+ return {+ id,+ doc_id: docId,+ chunk_index: index,+ content: `chunk ${index} content`,+ embedding: [0.1, 0.2],+ token_count: 10,+ embedder: LEGACY,+ };+}++const fakeEmbed = vi.fn(async (texts) => texts.map(() => Float64Array.from([1, 0, 0])));+const noSleep = vi.fn(async () => {});++describe('parseCliArgs', () => {+ it('parses the supported flags and applies safe defaults', () => {+ expect(parseCliArgs([])).toEqual({ dryRun: false, widget: null, batch: 64, throttleMs: 400 });+ expect(parseCliArgs(['--dry-run', '--widget', 'wdgt_x', '--batch', '8', '--throttle-ms', '0']))+ .toEqual({ dryRun: true, widget: 'wdgt_x', batch: 8, throttleMs: 0 });+ });++ it('rejects unknown flags instead of silently ignoring them', () => {+ expect(() => parseCliArgs(['--nuke'])).toThrow(/unknown argument/);+ });++ it('clamps batch size to the probed 512-input ceiling', () => {+ expect(parseCliArgs(['--batch', '4096']).batch).toBe(512);+ });+});++describe('classifyDoc', () => {+ it('skips non-ready docs with a reason', () => {+ expect(classifyDoc({ status: 'failed', total_chunks: 3, pending_chunks: 3 }, TARGET))+ .toEqual({ action: 'skip', reason: 'status=failed' });+ });++ it('skips empty docs', () => {+ expect(classifyDoc({ status: 'ready', total_chunks: 0, pending_chunks: 0 }, TARGET).action)+ .toBe('skip');+ });++ it('recognizes fully migrated sets (idempotent re-run)', () => {+ expect(+ classifyDoc(+ { status: 'ready', total_chunks: 3, pending_chunks: 0, doc_embedder: TARGET },+ TARGET,+ ).action,+ ).toBe('done');+ });++ it('flips the stale doc tag when all chunks migrated but a crash skipped the flip', () => {+ expect(+ classifyDoc(+ { status: 'ready', total_chunks: 3, pending_chunks: 0, doc_embedder: LEGACY },+ TARGET,+ ).action,+ ).toBe('flip');+ });++ it('migrates docs with pending chunks', () => {+ expect(+ classifyDoc(+ { status: 'ready', total_chunks: 3, pending_chunks: 2, doc_embedder: LEGACY },+ TARGET,+ ).action,+ ).toBe('migrate');+ });+});++describe('planMigration + summarizePlan (dry-run path)', () => {+ it('surveys without writing and produces honest counts and estimates', async () => {+ const { sql, state } = makeFakeDb({+ docs: [+ { id: 'wkd_a', widget_id: 'w1', title: 'A', status: 'ready', embedder: LEGACY },+ { id: 'wkd_b', widget_id: 'w1', title: 'B', status: 'ready', embedder: TARGET },+ { id: 'wkd_c', widget_id: 'w2', title: 'C', status: 'failed', embedder: LEGACY },+ ],+ chunks: [+ legacyChunk(1, 'wkd_a', 0),+ legacyChunk(2, 'wkd_a', 1),+ { ...legacyChunk(3, 'wkd_b', 0), embedder: TARGET },+ legacyChunk(4, 'wkd_c', 0),+ ],+ });++ const plan = await planMigration(sql, { targetTag: TARGET });+ const totals = summarizePlan(plan, { batch: 64, throttleMs: 0 });++ expect(totals).toMatchObject({ docs: 3, migrate: 1, done: 1, skip: 1, flip: 0 });+ // Skipped docs still report pending chunks in the survey, but only the+ // 'migrate' doc contributes work; the failed doc is listed with a reason.+ expect(plan.find((d) => d.id === 'wkd_c')).toMatchObject({+ action: 'skip',+ reason: 'status=failed',+ });+ expect(state.writes).toBe(0); // dry-run writes NOTHING+ });++ it('scopes to a single widget when asked', async () => {+ const { sql } = makeFakeDb({+ docs: [+ { id: 'wkd_a', widget_id: 'w1', title: 'A', status: 'ready', embedder: LEGACY },+ { id: 'wkd_b', widget_id: 'w2', title: 'B', status: 'ready', embedder: LEGACY },+ ],+ chunks: [legacyChunk(1, 'wkd_a', 0), legacyChunk(2, 'wkd_b', 0)],+ });+ const plan = await planMigration(sql, { targetTag: TARGET, widgetId: 'w2' });+ expect(plan.map((d) => d.id)).toEqual(['wkd_b']);+ });+});++describe('migrateDoc — idempotent, resume-safe, atomic per set', () => {+ it('re-embeds only pending chunks and flips the doc tag at the end', async () => {+ const { sql, state } = makeFakeDb({+ docs: [{ id: 'wkd_a', widget_id: 'w1', title: 'A', status: 'ready', embedder: LEGACY }],+ chunks: [+ legacyChunk(1, 'wkd_a', 0),+ { ...legacyChunk(2, 'wkd_a', 1), embedder: TARGET, embedding: [9, 9, 9] }, // already migrated+ legacyChunk(3, 'wkd_a', 2),+ ],+ });+ fakeEmbed.mockClear();++ const result = await migrateDoc(+ { sql, embedBatchFn: fakeEmbed, sleep: noSleep },+ { id: 'wkd_a' },+ { targetTag: TARGET, batch: 64, throttleMs: 0 },+ );++ expect(result).toEqual({ migrated: 2, flipped: true });+ // Only the 2 pending chunks were embedded — the migrated row was untouched.+ expect(fakeEmbed).toHaveBeenCalledTimes(1);+ expect(fakeEmbed.mock.calls[0][0]).toEqual(['chunk 0 content', 'chunk 2 content']);+ expect(state.chunks.find((c) => c.id === 2).embedding).toEqual([9, 9, 9]);+ expect(state.chunks.every((c) => c.embedder === TARGET)).toBe(true);+ expect(state.docs[0].embedder).toBe(TARGET);+ });++ it('a crash mid-set leaves the doc tag unflipped and a re-run completes the rest', async () => {+ const { sql, state } = makeFakeDb({+ docs: [{ id: 'wkd_a', widget_id: 'w1', title: 'A', status: 'ready', embedder: LEGACY }],+ chunks: [legacyChunk(1, 'wkd_a', 0), legacyChunk(2, 'wkd_a', 1)],+ });++ // Batch size 1 → two embed calls; the second one dies hard (non-retryable).+ const dyingEmbed = vi+ .fn()+ .mockResolvedValueOnce([Float64Array.from([1, 0, 0])])+ .mockRejectedValue(Object.assign(new Error('invalid key'), { status: 401 }));++ await expect(+ migrateDoc(+ { sql, embedBatchFn: dyingEmbed, sleep: noSleep },+ { id: 'wkd_a' },+ { targetTag: TARGET, batch: 1, throttleMs: 0 },+ ),+ ).rejects.toThrow('invalid key');++ // First chunk migrated, second untouched, set tag NOT flipped — retrieval+ // keeps routing each chunk in its own (correct) space meanwhile.+ expect(state.chunks.find((c) => c.id === 1).embedder).toBe(TARGET);+ expect(state.chunks.find((c) => c.id === 2).embedder).toBe(LEGACY);+ expect(state.docs[0].embedder).toBe(LEGACY);++ // Resume: a fresh run embeds ONLY the remaining chunk, then flips.+ const resumeEmbed = vi.fn(async (texts) => texts.map(() => Float64Array.from([0, 1, 0])));+ const result = await migrateDoc(+ { sql, embedBatchFn: resumeEmbed, sleep: noSleep },+ { id: 'wkd_a' },+ { targetTag: TARGET, batch: 1, throttleMs: 0 },+ );+ expect(result).toEqual({ migrated: 1, flipped: true });+ expect(resumeEmbed).toHaveBeenCalledTimes(1);+ expect(resumeEmbed.mock.calls[0][0]).toEqual(['chunk 1 content']);+ expect(state.docs[0].embedder).toBe(TARGET);+ });++ it('re-running over a fully migrated set embeds nothing (idempotent)', async () => {+ const { sql } = makeFakeDb({+ docs: [{ id: 'wkd_a', widget_id: 'w1', title: 'A', status: 'ready', embedder: TARGET }],+ chunks: [{ ...legacyChunk(1, 'wkd_a', 0), embedder: TARGET }],+ });+ const embed = vi.fn();+ const result = await migrateDoc(+ { sql, embedBatchFn: embed, sleep: noSleep },+ { id: 'wkd_a' },+ { targetTag: TARGET, batch: 64, throttleMs: 0 },+ );+ expect(result).toEqual({ migrated: 0, flipped: true });+ expect(embed).not.toHaveBeenCalled();+ });+});++describe('withBackoff — free-tier rate-limit handling', () => {+ it('backs off exponentially on 429 and then succeeds', async () => {+ const sleep = vi.fn(async () => {});+ const fn = vi+ .fn()+ .mockRejectedValueOnce(Object.assign(new Error('rate limited'), { status: 429 }))+ .mockRejectedValueOnce(Object.assign(new Error('rate limited'), { status: 429 }))+ .mockResolvedValue('ok');++ const out = await withBackoff(fn, { sleep, baseMs: 100 });+ expect(out).toBe('ok');+ expect(fn).toHaveBeenCalledTimes(3);+ expect(sleep).toHaveBeenCalledTimes(2);+ // Exponential: second delay ≥ 2× base, both within jitter bounds.+ expect(sleep.mock.calls[0][0]).toBeGreaterThanOrEqual(100);+ expect(sleep.mock.calls[1][0]).toBeGreaterThanOrEqual(200);+ });++ it('retries network-level failures (no status)', async () => {+ const fn = vi+ .fn()+ .mockRejectedValueOnce(new Error('fetch failed'))+ .mockResolvedValue('ok');+ expect(await withBackoff(fn, { sleep: noSleep, baseMs: 1 })).toBe('ok');+ });++ it('does NOT retry hard 4xx or configuration errors', async () => {+ const bad = vi.fn().mockRejectedValue(Object.assign(new Error('bad key'), { status: 401 }));+ await expect(withBackoff(bad, { sleep: noSleep })).rejects.toThrow('bad key');+ expect(bad).toHaveBeenCalledTimes(1);++ const unconfigured = vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('no key'), { code: 'no_embedder' }));+ await expect(withBackoff(unconfigured, { sleep: noSleep })).rejects.toThrow('no key');+ expect(unconfigured).toHaveBeenCalledTimes(1);+ });++ it('gives up after the attempt budget', async () => {+ const always429 = vi+ .fn()+ .mockRejectedValue(Object.assign(new Error('rate limited'), { status: 429 }));+ await expect(withBackoff(always429, { sleep: noSleep, attempts: 3, baseMs: 1 })).rejects.toThrow(+ 'rate limited',+ );+ expect(always429).toHaveBeenCalledTimes(3);+ });+});diff --git a/tests/src/agent-memory.test.js b/tests/src/agent-memory.test.jsindex 0110e8481..d1a024f08 100644--- a/tests/src/agent-memory.test.js+++ b/tests/src/agent-memory.test.js@@ -296,3 +296,100 @@ describe('AgentMemory.forget() / clear()', () => {expect(mem.query()).toHaveLength(0);});});++// ── recall() — vector-space safety ───────────────────────────────────────────+//+// The platform embed endpoint is a provider chain, so the embedding model can+// change between calls (and across sessions for localStorage-persisted+// entries). recall() must only cosine-compare entries embedded by the SAME+// model as the query — vectors from different models are different spaces and+// produce plausible-looking garbage similarities.++describe('AgentMemory.recall() — same-space rule', () => {+ const flushEmbeds = () => new Promise((r) => setTimeout(r, 0));++ it('cosine-matches entries embedded by the same model as the query', async () => {+ const embedFn = vi.fn(async (text) => ({+ vector: text.includes('solana') ? [1, 0] : [0, 1],+ model: 'baai/bge-m3',+ }));+ const mem = new AgentMemory('agent-1', { embedFn });+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'solana wallet integration notes' });+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'unrelated themes' });+ await flushEmbeds();++ const hits = await mem.recall('solana question', { minScore: 0.5 });+ expect(hits).toHaveLength(1);+ expect(hits[0].content).toBe('solana wallet integration notes');+ });++ it('never cosine-compares entries from a different model — substring fallback instead', async () => {+ let model = 'voyage-3-lite';+ // Identical vectors every call: a cross-space comparison would score a+ // perfect 1.0 — exactly the garbage match the rule must prevent.+ const embedFn = vi.fn(async () => ({ vector: [1, 0], model }));+ const mem = new AgentMemory('agent-1', { embedFn });+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'completely unrelated topic' });+ await flushEmbeds();++ model = 'baai/bge-m3'; // provider failed over between add() and recall()+ const hits = await mem.recall('quarterly report', { minScore: 0 });+ // Not vector-matched (different space) and no substring match → no hit.+ expect(hits).toHaveLength(0);++ // The entry is still reachable through the substring path.+ const substringHits = await mem.recall('unrelated', { minScore: 0 });+ expect(substringHits).toHaveLength(1);+ });++ it('treats persisted pre-tagging entries as voyage-3-lite (the legacy embedder)', async () => {+ // Seed localStorage with an entry shaped exactly like the old code wrote+ // it: embedding present, no embeddingModel field.+ localStorage.setItem(+ 'agent_memory_agent-1',+ JSON.stringify([+ {+ id: 'legacy-1',+ type: MEMORY_TYPES.PROJECT,+ content: 'legacy entry about pricing',+ tags: [],+ context: {},+ salience: 0.5,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ expiresAt: null,+ embedding: [1, 0],+ },+ ]),+ );++ // Same model as the legacy endpoint → still cosine-comparable.+ const voyageFn = vi.fn(async () => ({ vector: [1, 0], model: 'voyage-3-lite' }));+ const memSame = new AgentMemory('agent-1', { embedFn: voyageFn });+ const sameSpace = await memSame.recall('anything at all', { minScore: 0.5 });+ expect(sameSpace.map((e) => e.id)).toEqual(['legacy-1']);++ // Different model → the perfect-looking vector match must NOT count.+ const nimFn = vi.fn(async () => ({ vector: [1, 0], model: 'baai/bge-m3' }));+ const memCross = new AgentMemory('agent-1', { embedFn: nimFn });+ const crossSpace = await memCross.recall('anything at all', { minScore: 0 });+ expect(crossSpace).toHaveLength(0);+ });++ it('supports custom embedFns returning bare vectors (one consistent unnamed space)', async () => {+ const embedFn = vi.fn(async (text) => (text.includes('alpha') ? [1, 0] : [0, 1]));+ const mem = new AgentMemory('agent-1', { embedFn });+ mem.add({ type: MEMORY_TYPES.PROJECT, content: 'alpha release checklist' });+ await flushEmbeds();++ const hits = await mem.recall('alpha launch', { minScore: 0.5 });+ expect(hits).toHaveLength(1);+ });++ it('cosineSim refuses mismatched dimensions and zero vectors', async () => {+ const { cosineSim } = await import('../../src/agent-memory.js');+ expect(cosineSim([1, 0, 0], [1, 0])).toBe(0); // different dims = different spaces+ expect(cosineSim([0, 0], [1, 1])).toBe(0); // no direction, not NaN+ expect(cosineSim([1, 0], [1, 0])).toBeCloseTo(1, 6);+ });+});