🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ai-team): semantic memory via Cognitum embeddings, ordered listing, funnel logging, anon rate limit (0.4.0) (#4527)
rUvdafd38a4fe37
diff --git a/plugins/ruflo-ai-team/.claude-plugin/plugin.json b/plugins/ruflo-ai-team/.claude-plugin/plugin.jsonindex 28816bd232..c2a12fe2cb 100644--- a/plugins/ruflo-ai-team/.claude-plugin/plugin.json+++ b/plugins/ruflo-ai-team/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-ai-team","description": "Give Claude a tenant-isolated AI team that divides work, coordinates progress, recalls approved context, and returns evidence-backed results.",- "version": "0.3.5",+ "version": "0.4.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"diff --git a/plugins/ruflo-ai-team/CHANGELOG.md b/plugins/ruflo-ai-team/CHANGELOG.mdindex 1b57463487..a56973eeb6 100644--- a/plugins/ruflo-ai-team/CHANGELOG.md+++ b/plugins/ruflo-ai-team/CHANGELOG.md@@ -2,6 +2,13 @@Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-ai-team`.+## 0.4.0 — 2026-10-26+- feat: `memory_search` ranks by meaning through Cognitum's managed `/v1/embeddings` (`cognitum-embed`, 384-dim) when `RUFLO_AI_TEAM_EMBEDDINGS_KEY` is set; vectors are stored with each memory (only if the text is unchanged), never returned to callers, and an outage or a missing key falls back to the labelled lexical index, so a search never fails because embeddings did+- feat: memory listing reads newest first, so a team with more than 1000 memories keeps the latest; needs the composite index in `deploy/firestore.indexes.json`, and without it the read falls back to the old unordered query rather than erroring+- feat: the workflow funnel (team created, run started, run completed, memory written, memory searched) is logged as one structured line per success with a hashed tenant and no content+- feat: unauthenticated requests are limited per client (default 600 a minute, `RUFLO_AI_TEAM_ANON_RPM`); OAuth callers and `/health` are never throttled, and the client key is the last `X-Forwarded-For` entry because Cloud Run appends the real address there+- chore: the privacy page discloses that memory text is sent to Cognitum's embeddings service when semantic search is on+## 0.3.5 — 2026-10-24- feat: the guard also screens `team_create` and `team_update` (team name, objective and roles are shared, retained text like task and memory writes); read tools stay unguarded- feat: `/team-remember` and `/team-board` commands (memory store/search and the board view)diff --git a/plugins/ruflo-ai-team/README.md b/plugins/ruflo-ai-team/README.mdindex a97c9ed24f..46d6570b2a 100644--- a/plugins/ruflo-ai-team/README.md+++ b/plugins/ruflo-ai-team/README.md@@ -62,7 +62,11 @@ The anonymous methods return only static definitions: tool schemas, prompt text,Cross-origin (browser) reads are limited to an explicit allowlist. By default it covers `https://chatgpt.com`, `https://chat.openai.com` and `https://claude.ai`; set `ALLOWED_ORIGINS` (comma-separated origins) to replace it. The request origin is echoed back only when it is on the list, with `Vary: Origin`. No `access-control-allow-origin` header is sent for any other origin. ChatGPT and Claude call the endpoint server-to-server and the board UI makes no network requests, so the allowlist governs browser-based MCP clients only. Requests without an `Origin` header are unaffected.-Memory search reports `lexical-degraded` unless a compatible native RuVector binding passes the startup probe. The pinned `@ruvector/core` 0.1.32 package with its 0.1.30 optional native binding fails that probe in local validation with a dimension mismatch. Do not set `RUFLO_AI_TEAM_VECTOR=native` in production until a compatible binary is verified.+Memory search is semantic when `RUFLO_AI_TEAM_EMBEDDINGS_KEY` (a Cognitum API key with the `embeddings:run` scope) is set: memory text and queries are embedded through `POST https://api.cognitum.one/v1/embeddings` (`cognitum-embed`, 384-dim), the vector is stored with the memory, and the response says `"backend": "cognitum-embed"`. The embeddings URL must be an https `cognitum.one` host. If the key is missing or the API is down, search answers from the labelled `lexical-degraded` index instead of failing; a response with `unindexed` set means some memories were not embedded yet and the next search continues. Listing memories newest first with a team filter uses the composite index in `deploy/firestore.indexes.json`; without it the service falls back to an unordered read.++Unauthenticated requests (discovery, legal pages) are limited per client to `RUFLO_AI_TEAM_ANON_RPM` (default 600) a minute; OAuth callers and `/health` are not throttled. Each first-class workflow step logs one `ai_team_activation` line with a hashed tenant, for a log-based funnel metric.++Without an embeddings key, memory search reports `lexical-degraded` unless a compatible native RuVector binding passes the startup probe. The pinned `@ruvector/core` 0.1.32 package with its 0.1.30 optional native binding fails that probe in local validation with a dimension mismatch. Do not set `RUFLO_AI_TEAM_VECTOR=native` in production until a compatible binary is verified.## Local verificationdiff --git a/plugins/ruflo-ai-team/deploy/cloud-run.yaml b/plugins/ruflo-ai-team/deploy/cloud-run.yamlindex 84f5fa758c..98dd31bdbe 100644--- a/plugins/ruflo-ai-team/deploy/cloud-run.yaml+++ b/plugins/ruflo-ai-team/deploy/cloud-run.yaml@@ -13,7 +13,7 @@ spec:timeoutSeconds: 60serviceAccountName: ruflo-ai-team@PROJECT_ID.iam.gserviceaccount.comcontainers:- - image: REGION-docker.pkg.dev/PROJECT_ID/ruflo/ruflo-ai-team:0.3.4+ - image: REGION-docker.pkg.dev/PROJECT_ID/ruflo/ruflo-ai-team:0.4.0ports: [{ containerPort: 8080 }]resources:limits: { cpu: "1", memory: 1Gi }@@ -22,5 +22,10 @@ spec:- { name: RUFLO_AI_TEAM_STORE, value: "firestore" }- { name: RUFLO_AI_TEAM_OAUTH_ISSUER, value: "https://auth.cognitum.one" }- { name: RUFLO_AI_TEAM_OAUTH_AUDIENCE, value: "https://team.ruv.io/mcp" }+ # Semantic memory search. Without the key the service stays on the labelled+ # lexical fallback. The key needs the embeddings:run scope and belongs to the service.+ - name: RUFLO_AI_TEAM_EMBEDDINGS_KEY+ valueFrom: { secretKeyRef: { name: ruflo-ai-team-embeddings-key, key: latest, optional: true } }+ # Optional: RUFLO_AI_TEAM_ANON_RPM (default 600) caps unauthenticated requests per client per minute.# Optional: ALLOWED_ORIGINS replaces the browser CORS allowlist# (default: https://chatgpt.com,https://chat.openai.com,https://claude.ai).diff --git a/plugins/ruflo-ai-team/deploy/firestore.indexes.json b/plugins/ruflo-ai-team/deploy/firestore.indexes.jsonnew file mode 100644index 0000000000..6f0749d59a--- /dev/null+++ b/plugins/ruflo-ai-team/deploy/firestore.indexes.json@@ -0,0 +1,19 @@+{+ "indexes": [+ {+ "collectionGroup": "memories",+ "queryScope": "COLLECTION",+ "fields": [+ {+ "fieldPath": "teamId",+ "order": "ASCENDING"+ },+ {+ "fieldPath": "createdAt",+ "order": "DESCENDING"+ }+ ]+ }+ ],+ "fieldOverrides": []+}\ No newline at end of filediff --git a/plugins/ruflo-ai-team/package-lock.json b/plugins/ruflo-ai-team/package-lock.jsonindex 173f16b722..5c0d7ee540 100644--- a/plugins/ruflo-ai-team/package-lock.json+++ b/plugins/ruflo-ai-team/package-lock.json@@ -1,6 +1,6 @@{"name": "@ruflo/ai-team-service",- "version": "0.3.4",+ "version": "0.4.0","lockfileVersion": 3,"requires": true,"packages": {diff --git a/plugins/ruflo-ai-team/package.json b/plugins/ruflo-ai-team/package.jsonindex 3da8f0d3a7..0a6e2b64b7 100644--- a/plugins/ruflo-ai-team/package.json+++ b/plugins/ruflo-ai-team/package.json@@ -1,6 +1,6 @@{"name": "@ruflo/ai-team-service",- "version": "0.3.4",+ "version": "0.4.0","private": true,"type": "module","description": "Multi-tenant MCP control plane and Claude plugin for coordinated AI teams.",diff --git a/plugins/ruflo-ai-team/src/embedder.mjs b/plugins/ruflo-ai-team/src/embedder.mjsnew file mode 100644index 0000000000..8cf751c399--- /dev/null+++ b/plugins/ruflo-ai-team/src/embedder.mjs@@ -0,0 +1,67 @@+// Semantic embeddings through Cognitum's managed /v1/embeddings (ADR-218): OpenAI-shaped,+// 384-dim, `embeddings:run` scope. The key belongs to this service, never to a tenant, and is+// read from the environment only. Failures never reach a tool caller: the vector memory falls+// back to the labelled lexical index, and this client backs off after an error.++export const EMBEDDING_MODEL = 'cognitum-embed';+export const EMBEDDING_DIMENSIONS = 384;+const DEFAULT_URL = 'https://api.cognitum.one/v1/embeddings';+const MAX_BATCH = 64;+const MAX_TEXT = 8000;++export class EmbedError extends Error { constructor(message) { super(message); this.name = 'EmbedError'; } }++const unit = (vector) => {+ let norm = 0; for (const n of vector) norm += n * n;+ norm = Math.sqrt(norm) || 1;+ return Float32Array.from(vector, (n) => n / norm);+};++export class CognitumEmbedder {+ #apiKey; #url; #fetch; #now; #cooldownMs; #timeoutMs; #blockedUntil = 0;+ constructor({ apiKey, url = DEFAULT_URL, fetchImpl = fetch, now = Date.now, cooldownMs = 30_000, timeoutMs = 5000 } = {}) {+ if (!apiKey) throw new EmbedError('embeddings key is required');+ this.#apiKey = apiKey; this.#url = url; this.#fetch = fetchImpl; this.#now = now; this.#cooldownMs = cooldownMs; this.#timeoutMs = timeoutMs;+ this.model = EMBEDDING_MODEL; this.dimensions = EMBEDDING_DIMENSIONS;+ }+ get available() { return this.#now() >= this.#blockedUntil; }+ async embed(texts) {+ if (!this.available) throw new EmbedError('embeddings temporarily unavailable');+ const out = [];+ try {+ for (let i = 0; i < texts.length; i += MAX_BATCH) out.push(...await this.#batch(texts.slice(i, i + MAX_BATCH)));+ } catch (error) {+ this.#blockedUntil = this.#now() + this.#cooldownMs;+ // Deliberately a fresh message: the underlying error may carry request details.+ throw new EmbedError(`embeddings request failed (${error instanceof EmbedError ? error.message : error?.name || 'error'})`);+ }+ return out;+ }+ async #batch(texts) {+ const response = await this.#fetch(this.#url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${this.#apiKey}` },+ body: JSON.stringify({ model: this.model, input: texts.map((t) => String(t).slice(0, MAX_TEXT)) }),+ signal: AbortSignal.timeout(this.#timeoutMs),+ });+ if (!response.ok) throw new EmbedError(`status ${response.status}`);+ const data = (await response.json())?.data;+ if (!Array.isArray(data) || data.length !== texts.length) throw new EmbedError('unexpected response shape');+ return [...data].sort((a, b) => a.index - b.index).map((row) => {+ const v = row?.embedding;+ if (!Array.isArray(v) || v.length !== this.dimensions || !v.every(Number.isFinite)) throw new EmbedError('invalid embedding');+ return unit(v);+ });+ }+}++export function embedderFromEnv(env = process.env) {+ const apiKey = env.RUFLO_AI_TEAM_EMBEDDINGS_KEY;+ if (!apiKey) return null;+ const raw = env.RUFLO_AI_TEAM_EMBEDDINGS_URL || DEFAULT_URL;+ const url = new URL(raw);+ const loopback = url.hostname === '127.0.0.1' || url.hostname === 'localhost';+ if (url.protocol !== 'https:' && !loopback) throw new EmbedError('embeddings URL must use https');+ if (!loopback && url.hostname !== 'cognitum.one' && !url.hostname.endsWith('.cognitum.one')) throw new EmbedError('embeddings URL host must be a cognitum.one host');+ return new CognitumEmbedder({ apiKey, url: url.toString() });+}diff --git a/plugins/ruflo-ai-team/src/public-pages.mjs b/plugins/ruflo-ai-team/src/public-pages.mjsindex ff4d4a338b..6d184ad690 100644--- a/plugins/ruflo-ai-team/src/public-pages.mjs+++ b/plugins/ruflo-ai-team/src/public-pages.mjs@@ -1,4 +1,4 @@const page = (title, body) => `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style>body{font:16px/1.55 system-ui;max-width:760px;margin:48px auto;padding:0 20px;color:#172033}h1{color:#0a7181}a{color:#076b9b}</style><h1>${title}</h1>${body}`;-export const privacyPage = () => page('RuFlo AI Team Privacy', '<p>Tenant team data is used only to provide the service. Team, run, task, memory, and evidence content may include personal data that a user chooses to provide. OAuth credentials stay in transport headers and are not stored in tool inputs or outputs. Tenant records, memories, and vectors are isolated by verified OAuth identity.</p><p>Service data may be retained for longer than 30 days so teams can resume work and review evidence. To request access, correction, or deletion, contact <a href="mailto:[email protected]">[email protected]</a>. Data is not sold or used to train general-purpose models.</p>');+export const privacyPage = () => page('RuFlo AI Team Privacy', '<p>Tenant team data is used only to provide the service. Team, run, task, memory, and evidence content may include personal data that a user chooses to provide. OAuth credentials stay in transport headers and are not stored in tool inputs or outputs. Tenant records, memories, and vectors are isolated by verified OAuth identity.</p><p>When semantic search is enabled, the text of a memory you store, and each search query, is sent to Cognitum\'s embeddings service to compute a numeric vector. That service runs on Cognitum infrastructure with a self-hosted model; this service stores only the resulting vector alongside your memory and does not share it with other tenants.</p><p>Service data may be retained for longer than 30 days so teams can resume work and review evidence. To request access, correction, or deletion, contact <a href="mailto:[email protected]">[email protected]</a>. Data is not sold or used to train general-purpose models.</p>');export const termsPage = () => page('RuFlo AI Team Terms', '<p>RuFlo AI Team coordinates AI-assisted work. Users remain responsible for reviewing outputs and authorizing consequential actions. The initial service does not send external messages, deploy software, purchase goods, or execute arbitrary shell commands.</p>');export const supportPage = () => page('RuFlo AI Team Support', '<p>For help, email <a href="mailto:[email protected]">[email protected]</a> or open an issue at <a href="https://github.com/ruvnet/ruflo/issues">github.com/ruvnet/ruflo/issues</a>.</p>');diff --git a/plugins/ruflo-ai-team/src/rate-limit.mjs b/plugins/ruflo-ai-team/src/rate-limit.mjsnew file mode 100644index 0000000000..0f312e0d52--- /dev/null+++ b/plugins/ruflo-ai-team/src/rate-limit.mjs@@ -0,0 +1,25 @@+// Fixed-window limiter for unauthenticated traffic only. It protects the public discovery and+// legal endpoints from scraping; it is not a usage limit and never applies to OAuth callers.+export class AnonRateLimiter {+ #hits = new Map();+ constructor({ perMinute = 120, maxKeys = 10_000, now = Date.now } = {}) { this.perMinute = perMinute; this.maxKeys = maxKeys; this.now = now; }+ get size() { return this.#hits.size; }+ take(key) {+ const t = this.now(); let entry = this.#hits.get(key);+ if (!entry || t - entry.start >= 60_000) {+ entry = { start: t, count: 0 };+ this.#hits.delete(key); this.#hits.set(key, entry);+ // Oldest windows go first, so a flood of distinct keys cannot grow memory without bound.+ while (this.#hits.size > this.maxKeys) this.#hits.delete(this.#hits.keys().next().value);+ }+ entry.count++;+ return entry.count <= this.perMinute ? { ok: true } : { ok: false, retryAfter: Math.max(1, Math.ceil((entry.start + 60_000 - t) / 1000)) };+ }+}++// Cloud Run appends the connecting client's address to X-Forwarded-For, so only the LAST entry is+// trustworthy; anything the caller put in front of it is attacker-controlled.+export function clientKey(req) {+ const forwarded = String(req.headers['x-forwarded-for'] || '').split(',').map((s) => s.trim()).filter(Boolean);+ return forwarded.length ? forwarded[forwarded.length - 1] : req.socket?.remoteAddress || 'unknown';+}diff --git a/plugins/ruflo-ai-team/src/server.mjs b/plugins/ruflo-ai-team/src/server.mjsindex aee0c815b9..6ead473483 100644--- a/plugins/ruflo-ai-team/src/server.mjs+++ b/plugins/ruflo-ai-team/src/server.mjs@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import { createServer } from 'node:http';import { readFileSync } from 'node:fs';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';@@ -8,6 +9,7 @@ import { storeFromEnv } from './store.mjs';import { vectorMemoryFromEnv } from './vector-memory.mjs';import { TEAM_TEMPLATES, templateById } from './templates.mjs';import { fenced, scanStoredText } from './untrusted.mjs';+import { AnonRateLimiter, clientKey } from './rate-limit.mjs';import { privacyPage, supportPage, termsPage } from './public-pages.mjs';export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;@@ -45,7 +47,15 @@ async function readBody(req) {return Buffer.concat(chunks).toString('utf8');}-export async function createAiTeamService({ store, vectorMemory, verifyToken, port, allowedOrigins: allowedOriginsOption } = {}) {+// First successful use of each step in the team workflow. Logged as one structured line (Cloud+// Logging picks up stdout JSON), so a log-based metric can chart the funnel. The tenant is a+// one-way hash and no names, objectives or memory text are ever included.+const ACTIVATION_STAGES = Object.freeze({ team_create: 'team_created', run_create: 'run_started', run_complete: 'run_completed', memory_remember: 'memory_written', memory_search: 'memory_searched' });+const stdoutLog = (entry) => console.log(JSON.stringify(entry));++export async function createAiTeamService({ store, vectorMemory, verifyToken, port, allowedOrigins: allowedOriginsOption, log = stdoutLog, anonRpm = Number(process.env.RUFLO_AI_TEAM_ANON_RPM || 600) } = {}) {+ const limiter = new AnonRateLimiter({ perMinute: anonRpm });+ const tooMany = (res, key) => { const r = limiter.take(key); if (r.ok) return false; res.writeHead(429, { 'content-type': 'application/json', 'retry-after': String(r.retryAfter) }).end('{"error":"rate_limited"}'); return true; };const allowedOrigins = allowedOriginsOption ? parseAllowedOrigins(allowedOriginsOption.join(',')) : parseAllowedOrigins(process.env.ALLOWED_ORIGINS);store ||= await storeFromEnv();vectorMemory ||= await vectorMemoryFromEnv(store);@@ -58,6 +68,18 @@ export async function createAiTeamService({ store, vectorMemory, verifyToken, poconst buildMcp = (auth) => {const mcp = new McpServer({ name: 'ruflo-ai-team', version: VERSION }, { capabilities: { tools: {}, resources: {}, prompts: {} } });+ const tenantHash = auth.tenantId ? createHash('sha256').update(String(auth.tenantId)).digest('hex').slice(0, 16) : null;+ // Funnel logging wraps registration once, so each tool keeps its plain registration call.+ const registerTool = mcp.tool.bind(mcp);+ mcp.tool = (name, ...rest) => {+ const handler = rest.pop(); const stage = ACTIVATION_STAGES[name];+ rest.push(async (args) => {+ const result = await handler(args);+ if (stage && tenantHash && !result?.isError && !/^\{"error"/.test(result?.content?.[0]?.text ?? '')) log({ severity: 'INFO', event: 'ai_team_activation', stage, tool: name, tenant: tenantHash });+ return result;+ });+ return registerTool(name, ...rest);+ };const scoped = (scope, fn) => async (args) => hasScope(auth, scope) ? fn(args) : denied(scope);mcp.tool('team_templates_list', 'Lists first-party AI-team playbooks and their roles. Requires team:read. Does not create or run a team.', {}, READ('List team templates'), scoped(SCOPES.read, async () => text({ templates: TEAM_TEMPLATES })));mcp.tool('team_create', 'Creates a tenant-local AI-team record from a reviewed goal and optional playbook. Requires team:write. Does not start agents, contact external services, or incur model charges.', {@@ -109,8 +131,8 @@ export async function createAiTeamService({ store, vectorMemory, verifyToken, po}, WRITE('Update team task', true), scoped(SCOPES.write, async ({taskId,...patch}) => { const value=await store.updateTask(auth.tenantId,taskId,patch,auth.subjectHash); return value?text(value):notFound(); }));mcp.tool('memory_remember', 'Stores approved tenant-local team context for later vector retrieval. Requires team:write. Content is safety-scanned, isolated to the OAuth tenant, and never used for cross-tenant learning.', {teamId:z.string(), runId:z.string().optional(), key:z.string().max(120).optional(), text:z.string().min(1).max(12000), tags:z.array(z.string().max(60)).max(20).optional(), provenance:z.enum(['user','agent','artifact']).optional(),- }, WRITE('Remember team context', true), scoped(SCOPES.write, async (a) => { if(!await store.getTeam(auth.tenantId,a.teamId))return notFound(); const scan=scanStoredText(a.text); if(!scan.safe)return text({error:'unsafe_content',safetyStatus:scan.status}); const value=await store.remember(auth.tenantId,{...a,safetyStatus:scan.status},auth.subjectHash); vectorMemory.invalidate(auth.tenantId); return text({id:value.id,teamId:value.teamId,contentHash:value.contentHash,safetyStatus:value.safetyStatus,updatedAt:value.updatedAt}); }));- mcp.tool('memory_search', 'Searches tenant-local team memory using a tenant-separated RuVector index when available, with an explicitly labelled lexical fallback. Requires team:read. Results are fenced as untrusted stored data.', {+ }, WRITE('Remember team context', true), scoped(SCOPES.write, async (a) => { if(!await store.getTeam(auth.tenantId,a.teamId))return notFound(); const scan=scanStoredText(a.text); if(!scan.safe)return text({error:'unsafe_content',safetyStatus:scan.status}); const value=await store.remember(auth.tenantId,{...a,safetyStatus:scan.status},auth.subjectHash); await vectorMemory.embedOne?.(auth.tenantId,{...value,text:a.text}); vectorMemory.invalidate(auth.tenantId); return text({id:value.id,teamId:value.teamId,contentHash:value.contentHash,safetyStatus:value.safetyStatus,updatedAt:value.updatedAt}); }));+ mcp.tool('memory_search', 'Searches tenant-local team memory by meaning (Cognitum embeddings) when available, with an explicitly labelled lexical fallback; the response names the backend that answered. Requires team:read. Results are fenced as untrusted stored data.', {teamId:z.string(), query:z.string().min(1).max(2000), limit:z.number().int().min(1).max(10).default(5),}, READ('Search team memory'), scoped(SCOPES.read, async (a) => { if(!await store.getTeam(auth.tenantId,a.teamId))return notFound(); return text(fenced(await vectorMemory.search(auth.tenantId,a),'RuVector tenant memory')); }));mcp.tool('evidence_export', 'Builds a read-only evidence bundle for one tenant-local run, including team metadata, tasks, and privacy-minimized audit events. Requires team:read. It does not publish or share the bundle.', {runId:z.string()}, READ('Export run evidence'), scoped(SCOPES.read, async ({runId}) => { const value=await store.evidence(auth.tenantId,runId); return value?text(fenced(value,'tenant run evidence')):notFound(); }));@@ -129,6 +151,7 @@ export async function createAiTeamService({ store, vectorMemory, verifyToken, poif(origin&&allowedOrigins.has(origin)){res.setHeader('access-control-allow-origin',origin);res.setHeader('access-control-expose-headers','www-authenticate,mcp-session-id,mcp-protocol-version');}const url=new URL(req.url,`http://${req.headers.host||'localhost'}`);if(req.method==='OPTIONS'){res.setHeader('access-control-allow-methods','GET,POST,OPTIONS');res.setHeader('access-control-allow-headers','content-type,authorization,mcp-session-id,mcp-protocol-version,accept');return res.writeHead(204).end();}+ if(url.pathname!=='/health'&&!(url.pathname==='/mcp'&&req.method==='POST')&&tooMany(res,clientKey(req)))return;if(url.pathname==='/health')return res.writeHead(200,{'content-type':'application/json'}).end(JSON.stringify({ok:true,service:'ruflo-ai-team',version:VERSION}));if(url.pathname==='/.well-known/oauth-protected-resource/mcp'||url.pathname==='/.well-known/oauth-protected-resource')return res.writeHead(200,{'content-type':'application/json','cache-control':'no-store'}).end(JSON.stringify(protectedResourceMetadata({resource:url.pathname.endsWith('/mcp')?`${publicUrl}/mcp`:publicUrl,issuer})));if(req.method==='GET'&&url.pathname==='/privacy')return res.writeHead(200,{'content-type':'text/html;charset=utf-8'}).end(privacyPage());@@ -145,6 +168,7 @@ export async function createAiTeamService({ store, vectorMemory, verifyToken, poconst publicDiscovery=new Set(['initialize','ping','tools/list','resources/list','prompts/list']);let auth=await authenticate(req,authConfig,verifyToken);if(auth.mode==='denied'&&(publicDiscovery.has(parsed?.method)||publicUiRead))auth={mode:'anonymous',scopes:[]};+ if(auth.mode!=='oauth'&&tooMany(res,clientKey(req)))return;if(auth.mode==='denied')return res.writeHead(401,{'content-type':'application/json','www-authenticate':challengeHeader(metadataUrl,{error:auth.error,description:auth.description,scope:SCOPES.read})}).end(JSON.stringify({error:auth.error,error_description:auth.description}));if(needsAuth&&auth.mode!=='oauth'){const scope=called?TOOL_SCOPES[called]:SCOPES.read;return res.writeHead(401,{'content-type':'application/json','www-authenticate':challengeHeader(metadataUrl,{error:'invalid_token',description:'OAuth authorization is required for tenant data',scope})}).end(JSON.stringify({error:'invalid_token'}));}if(called&&TOOL_SCOPES[called]&&!hasScope(auth,TOOL_SCOPES[called]))return res.writeHead(403,{'content-type':'application/json','www-authenticate':challengeHeader(metadataUrl,{error:'insufficient_scope',description:`${TOOL_SCOPES[called]} is required`,scope:TOOL_SCOPES[called]})}).end(JSON.stringify({error:'insufficient_scope'}));diff --git a/plugins/ruflo-ai-team/src/store.mjs b/plugins/ruflo-ai-team/src/store.mjsindex e466b95d14..fa8e75c01f 100644--- a/plugins/ruflo-ai-team/src/store.mjs+++ b/plugins/ruflo-ai-team/src/store.mjs@@ -50,7 +50,14 @@ export class InMemoryStore {contentHash: createHash('sha256').update(input.text).digest('hex'), safetyStatus: input.safetyStatus || 'accepted', embeddingModel: 'feature-hash-256', embeddingVersion: '1', createdAt, updatedAt: timestamp };bucket.memories.set(id, clone(value)); this.#audit(bucket, actor, 'memory.remembered', id); return clone(value);}- async listMemories(tenantId, { teamId } = {}) { return [...this.#bucket(tenantId).memories.values()].filter((x) => !teamId || x.teamId === teamId).map(clone); }+ async listMemories(tenantId, { teamId, limit = 1000 } = {}) { return [...this.#bucket(tenantId).memories.values()].filter((x) => !teamId || x.teamId === teamId).sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0)).slice(0, limit).map(clone); }+ // Attaches a vector only if the text it was computed from is still the stored text.+ async setEmbedding(tenantId, id, { vector, model, contentHash }) {+ const current = this.#bucket(tenantId).memories.get(id);+ if (!current || current.contentHash !== contentHash) return false;+ current.embedding = Array.from(vector); current.embeddingModel = model; current.embeddingVersion = '1';+ return true;+ }async usage(tenantId) {const b = this.#bucket(tenantId); return { teams: b.teams.size, runs: b.runs.size, tasks: b.tasks.size, memories: b.memories.size, limits: { teams: 1, agentsPerTeam: 3, monthlyTasks: 100, runBudgetUnits: 100 } };}@@ -99,7 +106,15 @@ export class FirestoreStore {async listTasks(t,runId) { const snap=await this.#tenant(t).collection('tasks').where('runId','==',runId).limit(200).get(); return snap.docs.map(d=>d.data()); }async updateTask(t,id,p,a='-') { const c=await this.#get(t,'tasks',id); if(!c||(await this.#get(t,'runs',c.runId))?.status==='complete')return null; const v={...c,...p,id,updatedAt:now()}; await this.#put(t,'tasks',v); await this.#audit(t,a,'task.updated',id); return v; }async remember(t,i,a='-') { const timestamp=now(); const id=i.key||`mem_${randomUUID()}`; const previous=await this.#get(t,'memories',id); const v={id,teamId:i.teamId,runId:i.runId||null,text:i.text,tags:i.tags||[],provenance:i.provenance||'user',actorHash:a,contentHash:createHash('sha256').update(i.text).digest('hex'),safetyStatus:i.safetyStatus||'accepted',embeddingModel:'feature-hash-256',embeddingVersion:'1',createdAt:previous?.createdAt??timestamp,updatedAt:timestamp}; await this.#put(t,'memories',v); await this.#audit(t,a,'memory.remembered',v.id); return v; }- async listMemories(t,{teamId}={}) { let query=this.#tenant(t).collection('memories'); if(teamId)query=query.where('teamId','==',teamId); const snap=await query.limit(1000).get(); return snap.docs.map(d=>d.data()); }+ async listMemories(t,{teamId,limit=1000}={}) {+ // Newest first, so a capped read drops the oldest rather than an arbitrary slice. With a team+ // filter this is a composite index (teamId, createdAt desc); until it is deployed the read+ // falls back to the unordered query instead of failing the tool call (FAILED_PRECONDITION).+ const base=this.#tenant(t).collection('memories'); const scoped=teamId?base.where('teamId','==',teamId):base;+ try { return (await scoped.orderBy('createdAt','desc').limit(limit).get()).docs.map(d=>d.data()); }+ catch(error){ if(error?.code!==9)throw error; return (await scoped.limit(limit).get()).docs.map(d=>d.data()); }+ }+ async setEmbedding(t,id,{vector,model,contentHash}) { const ref=this.#tenant(t).collection('memories').doc(id); return this.db.runTransaction(async tx=>{ const snap=await tx.get(ref); if(!snap.exists||snap.data().contentHash!==contentHash)return false; tx.update(ref,{embedding:Array.from(vector),embeddingModel:model,embeddingVersion:'1'}); return true; }); }async usage(t) { const [teams,runs,tasks,memories]=await Promise.all(['teams','runs','tasks','memories'].map(k=>this.#list(t,k))); return {teams:teams.length,runs:runs.length,tasks:tasks.length,memories:memories.length,limits:{teams:1,agentsPerTeam:3,monthlyTasks:100,runBudgetUnits:100}}; }async evidence(t,runId) { const run=await this.#get(t,'runs',runId); if(!run)return null; const tasks=await this.listTasks(t,runId); const targets=new Set([runId,run.teamId,...tasks.map(task=>task.id)]); const ids=[...targets]; const chunks=[]; for(let i=0;i<ids.length;i+=30)chunks.push(ids.slice(i,i+30)); // Firestore 'in' takes at most 30 valuesconst audit=(await Promise.all(chunks.map(async c=>(await this.#tenant(t).collection('audit').where('targetId','in',c).limit(1000).get()).docs.map(d=>d.data())))).flat().sort((a,b)=>a.at<b.at?-1:a.at>b.at?1:0);diff --git a/plugins/ruflo-ai-team/src/vector-memory.mjs b/plugins/ruflo-ai-team/src/vector-memory.mjsindex 9282c4f2a5..d99bc83636 100644--- a/plugins/ruflo-ai-team/src/vector-memory.mjs+++ b/plugins/ruflo-ai-team/src/vector-memory.mjs@@ -1,4 +1,5 @@import { createHash } from 'node:crypto';+import { EMBEDDING_MODEL, EMBEDDING_DIMENSIONS, embedderFromEnv } from './embedder.mjs';export function featureVector(text, dimensions = 256) {const vector = new Float32Array(dimensions);@@ -13,10 +14,12 @@ export function featureVector(text, dimensions = 256) {return vector;}+// Stored vectors are an index detail: never return them to a tool caller.+const publicMemory = ({ embedding: _embedding, ...memory }) => memory;const cosine = (a, b) => { let total = 0; for (let i = 0; i < a.length; i++) total += a[i] * b[i]; return total; };export class TenantVectorMemory {- constructor(store, { dimensions = 256, VectorDb, maxIndexes = 64 } = {}) { this.store=store; this.dimensions=dimensions; this.VectorDb=VectorDb; this.maxIndexes=maxIndexes; this.indexes=new Map(); this.generation=0; }+ constructor(store, { dimensions = 256, VectorDb, maxIndexes = 64, embedder = null, maxEmbedPerBuild = 128 } = {}) { this.embedder=embedder; this.maxEmbedPerBuild=maxEmbedPerBuild; this.store=store; this.dimensions=dimensions; this.VectorDb=VectorDb; this.maxIndexes=maxIndexes; this.indexes=new Map(); this.generation=0; }#rememberIndex(key, value, generation) {// A mutation during asynchronous construction must keep this snapshot uncached.if (generation !== this.generation) return value;@@ -25,10 +28,37 @@ export class TenantVectorMemory {while (this.indexes.size > this.maxIndexes) this.indexes.delete(this.indexes.keys().next().value);return value;}+ // Embeds what is missing (bounded per build) and persists each vector so a cold start or a+ // second instance does not pay for it again. Returns null when the embeddings service fails,+ // so the caller falls back to the labelled lexical index rather than a half-semantic one.+ async #semanticItems(tenantId, memories) {+ const usable = (m) => m.embeddingModel === EMBEDDING_MODEL && Array.isArray(m.embedding) && m.embedding.length === EMBEDDING_DIMENSIONS;+ const items = memories.filter(usable).map((m) => ({ m, v: Float32Array.from(m.embedding) }));+ const missing = memories.filter((m) => !usable(m));+ const batch = missing.slice(0, this.maxEmbedPerBuild);+ if (batch.length) {+ let vectors;+ try { vectors = await this.embedder.embed(batch.map((m) => m.text)); } catch { return null; }+ for (let i = 0; i < batch.length; i++) {+ items.push({ m: batch[i], v: vectors[i] });+ // Best effort: a failed write only costs a re-embed next time.+ try { await this.store.setEmbedding?.(tenantId, batch[i].id, { vector: vectors[i], model: EMBEDDING_MODEL, contentHash: batch[i].contentHash }); } catch { /* ignore */ }+ }+ }+ return { items, unindexed: missing.length - batch.length };+ }async #index(tenantId, teamId) {const key=`${tenantId}:${teamId||'*'}`; if(this.indexes.has(key))return this.indexes.get(key);const generation=this.generation;const memories=await this.store.listMemories(tenantId,{teamId});+ if (this.embedder?.available) {+ const semantic=await this.#semanticItems(tenantId,memories);+ if (semantic) {+ const value={kind:EMBEDDING_MODEL,degraded:semantic.unindexed>0,unindexed:semantic.unindexed,items:semantic.items};+ // A partial index is not cached, so the next search continues embedding the rest.+ return semantic.unindexed>0?value:this.#rememberIndex(key,value,generation);+ }+ }if (this.VectorDb) {const db=new this.VectorDb({dimensions:this.dimensions,maxElements:Math.max(1000,memories.length+100)});for(const m of memories) await db.insert({id:m.id,vector:featureVector(m.text,this.dimensions)});@@ -36,27 +66,42 @@ export class TenantVectorMemory {}const value={kind:'lexical-degraded',degraded:true,items:memories.map(m=>({m,v:featureVector(m.text,this.dimensions)}))}; return this.#rememberIndex(key,value,generation);}+ // Best-effort embed-on-write so the first search after a write does not pay for it.+ async embedOne(tenantId, memory) {+ if (!this.embedder?.available) return false;+ try {+ const [vector] = await this.embedder.embed([memory.text]);+ return await this.store.setEmbedding?.(tenantId, memory.id, { vector, model: EMBEDDING_MODEL, contentHash: memory.contentHash }) ?? false;+ } catch { return false; }+ }invalidate(tenantId) { this.generation++; for(const key of this.indexes.keys())if(key.startsWith(`${tenantId}:`))this.indexes.delete(key); }async search(tenantId,{teamId,query,limit=5}) {- const idx=await this.#index(tenantId,teamId); const vector=featureVector(query,this.dimensions);+ const idx=await this.#index(tenantId,teamId);+ if(idx.kind===EMBEDDING_MODEL){+ let queryVector=null; try{ [queryVector]=await this.embedder.embed([query]); }catch{ /* fall through to lexical */ }+ if(queryVector)return {backend:idx.kind,degraded:idx.degraded,...(idx.unindexed?{unindexed:idx.unindexed}:{}),results:idx.items.map(x=>({score:cosine(queryVector,x.v),memory:publicMemory(x.m)})).sort((a,b)=>b.score-a.score).slice(0,limit)};+ return this.#lexical(await this.store.listMemories(tenantId,{teamId}),query,limit);+ }+ const vector=featureVector(query,this.dimensions);if(idx.kind==='ruvector-native') return {backend:idx.kind,degraded:idx.degraded,results:(await idx.db.search({vector,k:limit})).map(r=>({score:r.score,memory:idx.items.get(r.id)})).filter(x=>x.memory)};- return {backend:idx.kind,degraded:idx.degraded,results:idx.items.map(x=>({score:cosine(vector,x.v),memory:x.m})).sort((a,b)=>b.score-a.score).slice(0,limit)};+ return {backend:idx.kind,degraded:idx.degraded,results:idx.items.map(x=>({score:cosine(vector,x.v),memory:publicMemory(x.m)})).sort((a,b)=>b.score-a.score).slice(0,limit)};}+ #lexical(memories,query,limit){ const vector=featureVector(query,this.dimensions); return {backend:'lexical-degraded',degraded:true,results:memories.map(m=>({score:cosine(vector,featureVector(m.text,this.dimensions)),memory:publicMemory(m)})).sort((a,b)=>b.score-a.score).slice(0,limit)}; }}-export async function vectorMemoryFromEnv(store) {+export async function vectorMemoryFromEnv(store, { embedder = embedderFromEnv() } = {}) {// Native acceleration is opt-in. Some platform bindings create a persistent// database at the process working directory even when no storage path is// requested. Defaulting to the portable backend prevents accidental shared// state and keeps every deployment honest about its degraded search mode.- if (process.env.RUFLO_AI_TEAM_VECTOR !== 'native') return new TenantVectorMemory(store);+ if (process.env.RUFLO_AI_TEAM_VECTOR !== 'native') return new TenantVectorMemory(store,{embedder});try {const module = await import('@ruvector/core'); const VectorDb = module.VectorDb || module.default?.VectorDb; if(!VectorDb)throw new Error('VectorDb export missing');// Package wrappers and native optional dependencies can drift independently.// Prove this exact binary accepts our configured dimension before advertising it.const probe = new VectorDb({dimensions:256,maxElements:2}); const id='__ruflo_probe__';await probe.insert({id,vector:new Float32Array(256)}); await probe.search({vector:new Float32Array(256),k:1}); await probe.delete(id);- return new TenantVectorMemory(store,{VectorDb});+ return new TenantVectorMemory(store,{VectorDb,embedder});}- catch { return new TenantVectorMemory(store); }+ catch { return new TenantVectorMemory(store,{embedder}); }}diff --git a/plugins/ruflo-ai-team/test/activation-ratelimit.node.mjs b/plugins/ruflo-ai-team/test/activation-ratelimit.node.mjsnew file mode 100644index 0000000000..2c69e0d3f0--- /dev/null+++ b/plugins/ruflo-ai-team/test/activation-ratelimit.node.mjs@@ -0,0 +1,72 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAiTeamService } from '../src/server.mjs';+import { InMemoryStore } from '../src/store.mjs';+import { TenantVectorMemory } from '../src/vector-memory.mjs';+import { AnonRateLimiter } from '../src/rate-limit.mjs';++const verifyToken = async (token, _j, o) => {+ if (token === 'bad') throw new Error('bad signature');+ return { payload: { iss: 'https://auth.cognitum.one', aud: o.audience, sub: `${token}-user`, tenant_id: token, scope: 'team:read team:write team:run' } };+};+async function fixture(extra = {}) {+ const store = new InMemoryStore(); const events = [];+ const service = await createAiTeamService({ store, vectorMemory: new TenantVectorMemory(store), verifyToken, port: 0, log: (e) => events.push(e), ...extra });+ const port = await service.listen(0);+ return { ...service, events, base: `http://127.0.0.1:${port}` };+}+const rpc = async (base, body, token, headers = {}) => {+ const r = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers }, body: JSON.stringify(body) });+ const raw = await r.text(); const line = raw.split('\n').find((x) => x.startsWith('data: '));+ return { status: r.status, retryAfter: r.headers.get('retry-after'), body: line || raw.startsWith('{') ? JSON.parse(line ? line.slice(6) : raw) : raw };+};+const call = (base, name, args, token = 'acme') => rpc(base, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, token);+const val = (r) => JSON.parse(r.body.result.content[0].text);++test('the funnel is logged once per stage with a hashed tenant and no content', async (t) => {+ const f = await fixture(); t.after(() => f.server.close());+ const team = val(await call(f.base, 'team_create', { name: 'Secret Project', objective: 'private goal' }));+ const run = val(await call(f.base, 'run_create', { teamId: team.id, objective: 'ship it' }));+ const task = val(await call(f.base, 'task_create', { runId: run.id, title: 't', description: 'd', assigneeRole: 'r' }));+ await call(f.base, 'task_update', { taskId: task.id, status: 'complete' });+ await call(f.base, 'run_complete', { runId: run.id });+ const stages = f.events.filter((e) => e.event === 'ai_team_activation').map((e) => e.stage);+ assert.deepEqual(stages, ['team_created', 'run_started', 'run_completed']);+ const all = JSON.stringify(f.events);+ assert.ok(!all.includes('acme') && !all.includes('Secret Project') && !all.includes('private goal'), 'no tenant id or content in the log');+ assert.match(f.events[0].tenant, /^[0-9a-f]{16}$/);+});++test('failed or refused calls are not counted as activation', async (t) => {+ const f = await fixture(); t.after(() => f.server.close());+ await call(f.base, 'run_create', { teamId: 'team_nope', objective: 'x' });+ await call(f.base, 'team_create', { name: 'n', objective: 'o', templateId: 'no-such-template' });+ assert.deepEqual(f.events.filter((e) => e.event === 'ai_team_activation'), []);+});++test('anonymous discovery is rate limited per client, authenticated calls are not', async (t) => {+ const f = await fixture({ anonRpm: 5 }); t.after(() => f.server.close());+ const list = (ip) => rpc(f.base, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, null, { 'x-forwarded-for': ip });+ const codes = []; for (let i = 0; i < 8; i++) codes.push((await list('203.0.113.9')).status);+ assert.deepEqual(codes.slice(0, 5), [200, 200, 200, 200, 200]);+ assert.ok(codes.slice(5).every((c) => c === 429));+ const blocked = await list('203.0.113.9'); assert.ok(Number(blocked.retryAfter) >= 1);+ assert.equal((await list('198.51.100.7')).status, 200, 'another client is unaffected');+ for (let i = 0; i < 20; i++) assert.equal((await call(f.base, 'team_list', {}, 'acme')).status, 200, 'OAuth calls are never throttled here');+ assert.equal((await fetch(`${f.base}/health`)).status, 200, 'health checks are never throttled');+});++test('a spoofed leading X-Forwarded-For entry does not buy a fresh bucket', async (t) => {+ const f = await fixture({ anonRpm: 3 }); t.after(() => f.server.close());+ const codes = [];+ for (let i = 0; i < 6; i++) codes.push((await rpc(f.base, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, null, { 'x-forwarded-for': `10.0.0.${i}, 203.0.113.50` })).status);+ assert.deepEqual(codes, [200, 200, 200, 429, 429, 429]);+});++test('limiter: window resets, and its table stays bounded', () => {+ let now = 0; const limiter = new AnonRateLimiter({ perMinute: 2, maxKeys: 3, now: () => now });+ assert.equal(limiter.take('a').ok, true); assert.equal(limiter.take('a').ok, true); assert.equal(limiter.take('a').ok, false);+ now += 61_000; assert.equal(limiter.take('a').ok, true);+ for (const k of ['b', 'c', 'd', 'e']) limiter.take(k);+ assert.ok(limiter.size <= 3);+});diff --git a/plugins/ruflo-ai-team/test/firestore-store.node.mjs b/plugins/ruflo-ai-team/test/firestore-store.node.mjsindex 17e3b3aede..1c1c698ff3 100644--- a/plugins/ruflo-ai-team/test/firestore-store.node.mjs+++ b/plugins/ruflo-ai-team/test/firestore-store.node.mjs@@ -4,13 +4,14 @@ import { FirestoreStore, InMemoryStore } from '../src/store.mjs';// Minimal Firestore double. Like the real thing it applies limit() AFTER ordering,// and with no orderBy returns documents in document-id order, not creation order.-function fakeFirestore() {+function fakeFirestore({ noCompositeIndex = false } = {}) {const data = new Map();const query = (path, filters = [], order = null, max = Infinity) => ({where: (field, op, value) => query(path, [...filters, { field, op, value }], order, max),orderBy: (field, dir = 'asc') => query(path, filters, { field, dir }, max),limit: (n) => query(path, filters, order, n),async get() {+ if (noCompositeIndex && order && filters.length) throw Object.assign(new Error('9 FAILED_PRECONDITION: The query requires an index.'), { code: 9 });let rows = [...(data.get(path)?.entries() ?? [])].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, v]) => v);for (const f of filters) {if (f.op === '==') rows = rows.filter((r) => r[f.field] === f.value);@@ -66,3 +67,36 @@ test('both stores list runs newest first', async () => {const b = await mem.createRun('t', { teamId: team.id, objective: 'b', budgetUnits: 1 });assert.deepEqual((await mem.listRuns('t')).map((r) => r.id), [b.id, a.id]);});++async function seedMemories(store, n) {+ const team = await store.createTeam('t1', { name: 'T', objective: 'o', roles: [] });+ const ids = [];+ for (let i = 0; i < n; i++) {+ const m = await store.remember('t1', { teamId: team.id, text: `memory ${i}`, key: `m${String(i).padStart(3, '0')}` });+ // Backdate so creation order is the opposite of document-id order for half the rows.+ await store.db.collection('ruflo_ai_team_tenants').doc('t1').collection('memories').doc(m.id).set({ ...m, createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, i)).toISOString() });+ ids.push(m.id);+ }+ return { team, ids };+}++test('listMemories keeps the newest memories when a team has more than the cap', async () => {+ const store = new FirestoreStore(fakeFirestore());+ const { team, ids } = await seedMemories(store, 12);+ const listed = await store.listMemories('t1', { teamId: team.id, limit: 5 });+ assert.deepEqual(listed.map((m) => m.id), ids.slice(-5).reverse(), 'newest five, newest first');+});++test('listMemories still answers when the composite index is not deployed yet', async () => {+ const store = new FirestoreStore(fakeFirestore({ noCompositeIndex: true }));+ const { team } = await seedMemories(store, 12);+ const listed = await store.listMemories('t1', { teamId: team.id, limit: 5 });+ assert.equal(listed.length, 5, 'falls back to an unordered read instead of failing the tool call');+});++test('listMemories without a team filter needs no composite index', async () => {+ const store = new FirestoreStore(fakeFirestore({ noCompositeIndex: true }));+ const { ids } = await seedMemories(store, 12);+ const listed = await store.listMemories('t1', { limit: 5 });+ assert.deepEqual(listed.map((m) => m.id), ids.slice(-5).reverse());+});diff --git a/plugins/ruflo-ai-team/test/semantic-memory.node.mjs b/plugins/ruflo-ai-team/test/semantic-memory.node.mjsnew file mode 100644index 0000000000..1c6a331851--- /dev/null+++ b/plugins/ruflo-ai-team/test/semantic-memory.node.mjs@@ -0,0 +1,153 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { CognitumEmbedder, embedderFromEnv } from '../src/embedder.mjs';+import { TenantVectorMemory } from '../src/vector-memory.mjs';+import { InMemoryStore } from '../src/store.mjs';++const DIMS = 384;+// Concept axes: words in the same group embed to the same direction, so "release broke"+// is close to "deploy failure" with zero shared tokens (a keyword hash cannot see that).+const CONCEPTS = [['deploy', 'release', 'ship', 'rollout'], ['failure', 'broke', 'crash', 'outage'], ['invoice', 'billing', 'payment']];+function conceptVector(text) {+ const v = new Array(DIMS).fill(0);+ for (const token of String(text).toLowerCase().match(/[a-z]+/g) || []) CONCEPTS.forEach((group, axis) => { if (group.includes(token)) v[axis] += 1; });+ const norm = Math.hypot(...v) || 1;+ return v.map((x) => x / norm);+}+function fakeFetch({ calls = [], fail = false, shape } = {}) {+ return async (url, init) => {+ const body = JSON.parse(init.body);+ calls.push({ url, headers: init.headers, body });+ if (fail) throw new Error('network down');+ const inputs = Array.isArray(body.input) ? body.input : [body.input];+ const data = inputs.map((t, index) => ({ index, embedding: conceptVector(t) }));+ return new Response(JSON.stringify(shape ? shape(data) : { data, usage: { total_tokens: 1 } }), { status: 200, headers: { 'content-type': 'application/json' } });+ };+}+const embedder = (opts = {}) => new CognitumEmbedder({ apiKey: 'cog_test_key', url: 'https://api.cognitum.one/v1/embeddings', fetchImpl: fakeFetch(opts), ...opts.config });++async function seeded(emb) {+ const store = new InMemoryStore();+ const team = await store.createTeam('t1', { name: 'n', objective: 'o', roles: ['a'] });+ await store.remember('t1', { teamId: team.id, text: 'deploy failure last friday rolled back', key: 'm1' });+ await store.remember('t1', { teamId: team.id, text: 'invoice payment terms are net 30', key: 'm2' });+ return { store, team, memory: new TenantVectorMemory(store, { embedder: emb }) };+}++test('semantic search finds a memory that shares no tokens with the query', async () => {+ const { team, memory } = await seeded(embedder());+ const out = await memory.search('t1', { teamId: team.id, query: 'release broke', limit: 2 });+ assert.equal(out.backend, 'cognitum-embed');+ assert.equal(out.degraded, false);+ assert.equal(out.results[0].memory.id, 'm1');+ assert.ok(out.results[0].score > 0.9 && out.results[1].score < 0.1);+});++test('without a key the lexical fallback is used and labelled', async () => {+ const { team, memory } = await seeded(null);+ const out = await memory.search('t1', { teamId: team.id, query: 'release broke' });+ assert.equal(out.backend, 'lexical-degraded');+ assert.equal(out.degraded, true);+});++test('an embeddings outage degrades to lexical instead of failing the search', async () => {+ const { team, memory } = await seeded(embedder({ fail: true }));+ const out = await memory.search('t1', { teamId: team.id, query: 'deploy failure' });+ assert.equal(out.backend, 'lexical-degraded');+ assert.equal(out.degraded, true);+ assert.equal(out.results[0].memory.id, 'm1');+});++test('vectors are persisted once and never returned to the caller', async () => {+ const calls = [];+ const { team, memory, store } = await seeded(embedder({ calls }));+ const first = await memory.search('t1', { teamId: team.id, query: 'release broke' });+ assert.ok(!('embedding' in first.results[0].memory), 'embedding must not leak into results');+ const stored = (await store.listMemories('t1', { teamId: team.id })).find((m) => m.id === 'm1');+ assert.equal(stored.embeddingModel, 'cognitum-embed');+ assert.equal(stored.embedding.length, DIMS);+ memory.invalidate('t1');+ calls.length = 0;+ await memory.search('t1', { teamId: team.id, query: 'ship crash' });+ assert.equal(calls.length, 1, 'only the query is embedded; stored memories already have vectors');+ assert.equal(calls[0].body.input.length === 1 || typeof calls[0].body.input === 'string', true);+});++test('editing a memory drops its stale vector', async () => {+ const { store, team } = await seeded(embedder());+ const memory = new TenantVectorMemory(store, { embedder: embedder() });+ await memory.search('t1', { teamId: team.id, query: 'x' });+ await store.remember('t1', { teamId: team.id, text: 'invoice billing moved', key: 'm1' });+ const edited = (await store.listMemories('t1', { teamId: team.id })).find((m) => m.id === 'm1');+ assert.equal(edited.embedding, undefined);+ assert.equal(edited.embeddingModel, 'feature-hash-256');+});++test('setEmbedding refuses a vector computed for text that has since changed', async () => {+ const store = new InMemoryStore();+ const team = await store.createTeam('t1', { name: 'n', objective: 'o', roles: ['a'] });+ const old = await store.remember('t1', { teamId: team.id, text: 'old text', key: 'k' });+ await store.remember('t1', { teamId: team.id, text: 'new text', key: 'k' });+ const ok = await store.setEmbedding('t1', 'k', { vector: conceptVector('old'), model: 'cognitum-embed', contentHash: old.contentHash });+ assert.equal(ok, false);+ assert.equal((await store.listMemories('t1'))[0].embedding, undefined);+});++test('request carries the bearer key, model and bounded batches; the key never appears in errors', async () => {+ const calls = [];+ const emb = embedder({ calls });+ const out = await emb.embed(['a', 'b']);+ assert.equal(out.length, 2);+ assert.equal(calls[0].headers.authorization, 'Bearer cog_test_key');+ assert.equal(calls[0].body.model, 'cognitum-embed');+ const bad = embedder({ fail: true });+ await assert.rejects(() => bad.embed(['a']), (e) => { assert.ok(!String(e.message).includes('cog_test_key')); return true; });+});++test('malformed responses are rejected', async () => {+ for (const shape of [() => ({}), (d) => ({ data: d.slice(0, 0) }), (d) => ({ data: d.map((x) => ({ ...x, embedding: x.embedding.slice(0, 10) })) }), (d) => ({ data: d.map((x) => ({ ...x, embedding: x.embedding.map(() => NaN) })) })]) {+ await assert.rejects(() => embedder({ shape }).embed(['a']));+ }+});++test('after a failure the embedder backs off instead of hammering the API', async () => {+ const calls = []; let clock = 1000;+ const emb = embedder({ calls, fail: true, config: { now: () => clock, cooldownMs: 30_000 } });+ await assert.rejects(() => emb.embed(['a']));+ assert.equal(emb.available, false);+ await assert.rejects(() => emb.embed(['a']));+ assert.equal(calls.length, 1);+ clock += 31_000;+ assert.equal(emb.available, true);+});++test('embedderFromEnv: no key means off; only Cognitum https hosts (or loopback) are accepted', () => {+ assert.equal(embedderFromEnv({}), null);+ assert.ok(embedderFromEnv({ RUFLO_AI_TEAM_EMBEDDINGS_KEY: 'k' }));+ assert.throws(() => embedderFromEnv({ RUFLO_AI_TEAM_EMBEDDINGS_KEY: 'k', RUFLO_AI_TEAM_EMBEDDINGS_URL: 'https://evil.example/v1/embeddings' }), /host/i);+ assert.throws(() => embedderFromEnv({ RUFLO_AI_TEAM_EMBEDDINGS_KEY: 'k', RUFLO_AI_TEAM_EMBEDDINGS_URL: 'http://api.cognitum.one/v1/embeddings' }), /https/i);+ assert.throws(() => embedderFromEnv({ RUFLO_AI_TEAM_EMBEDDINGS_KEY: 'k', RUFLO_AI_TEAM_EMBEDDINGS_URL: 'https://cognitum.one.evil.example/x' }), /host/i);+ assert.ok(embedderFromEnv({ RUFLO_AI_TEAM_EMBEDDINGS_KEY: 'k', RUFLO_AI_TEAM_EMBEDDINGS_URL: 'http://127.0.0.1:9/v1/embeddings' }));+});++test('memory_remember embeds on write and memory_search answers semantically end to end', async (t) => {+ const { createAiTeamService } = await import('../src/server.mjs');+ const store = new InMemoryStore();+ const calls = [];+ const vectorMemory = new TenantVectorMemory(store, { embedder: embedder({ calls }) });+ const verifyToken = async (_t, _j, o) => ({ payload: { iss: 'https://auth.cognitum.one', aud: o.audience, sub: 'u', tenant_id: 'tt', scope: 'team:read team:write team:run' } });+ const service = await createAiTeamService({ store, vectorMemory, verifyToken, port: 0 });+ const port = await service.listen(0); t.after(() => service.server.close());+ const base = `http://127.0.0.1:${port}`;+ const call = async (name, args) => {+ const r = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: 'Bearer x' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }) });+ const raw = await r.text(); const line = raw.split('\n').find((x) => x.startsWith('data: '));+ return JSON.parse(JSON.parse(line ? line.slice(6) : raw).result.content[0].text);+ };+ const team = await call('team_create', { name: 'n', objective: 'o' });+ await call('memory_remember', { teamId: team.id, key: 'a', text: 'deploy failure last friday' });+ assert.equal(calls.length, 1, 'embedded once on write');+ const found = await call('memory_search', { teamId: team.id, query: 'release broke' });+ assert.match(JSON.stringify(found), /cognitum-embed/);+ assert.equal(calls.length, 2, 'search embeds only the query');+});