Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

feat: ruvector WASM integration + real semantic embeddings (#1374)

rUve0d4703eb27c
diff --git a/package-lock.json b/package-lock.json
index d42873dbc1..6a610e0b17 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,15 +1,15 @@
{
"name": "claude-flow",
- "version": "3.5.19",
+ "version": "3.5.28",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-flow",
- "version": "3.5.19",
- "hasInstallScript": true,
+ "version": "3.5.28",
"license": "MIT",
"dependencies": {
+ "@ruvector/ruvllm-wasm": "^2.0.0",
"semver": "^7.6.0",
"zod": "^3.22.4"
},
@@ -4426,6 +4426,12 @@
"node": ">= 18"
}
},
+ "node_modules/@ruvector/ruvllm-wasm": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@ruvector/ruvllm-wasm/-/ruvllm-wasm-2.0.0.tgz",
+ "integrity": "sha512-9wCN+RhipGVs6j7npEMeU6iEtiyVDCveqg50frB/xth0cQBF57u7XZ7ctpcnSQmHWZjkNcIa0dhx8i8Tr6I36A==",
+ "license": "MIT"
+ },
"node_modules/@ruvector/ruvllm-win32-x64-msvc": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@ruvector/ruvllm-win32-x64-msvc/-/ruvllm-win32-x64-msvc-0.2.0.tgz",
diff --git a/package.json b/package.json
index 6629c6966b..f955f85822 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.5.23",
+ "version": "3.5.28",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
@@ -54,6 +54,7 @@
"v3:security": "npm run security:audit && npm run security:test"
},
"dependencies": {
+ "@ruvector/ruvllm-wasm": "^2.0.0",
"semver": "^7.6.0",
"zod": "^3.22.4"
},
diff --git a/ruflo/package.json b/ruflo/package.json
index 7019ee14fd..6b70a3a066 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.5.23",
+ "version": "3.5.28",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/agent-wasm.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/agent-wasm.test.ts
new file mode 100644
index 0000000000..e9868b478a
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/agent-wasm.test.ts
@@ -0,0 +1,356 @@
+/**
+ * Tests for @ruvector/rvagent-wasm integration module
+ *
+ * Mocks the WASM module since it may not be installed in CI.
+ * Tests the integration layer: lifecycle, tool execution, gallery, RVF.
+ */
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+// ── Mock fs and module for initAgentWasm ─────────────────────
+
+vi.mock('node:fs', () => ({
+ readFileSync: vi.fn().mockReturnValue(new Uint8Array([0])),
+}));
+
+vi.mock('node:module', () => ({
+ createRequire: vi.fn().mockReturnValue({
+ resolve: vi.fn().mockReturnValue('/fake/rvagent_wasm_bg.wasm'),
+ }),
+}));
+
+// ── Mock @ruvector/rvagent-wasm ──────────────────────────────
+
+const mockToolResult = { success: true, output: 'wrote 10 bytes to test.ts' };
+
+class MockWasmAgent {
+ _model: string;
+ _turnCount = 0;
+ _fileCount = 0;
+ constructor(configJson: string) {
+ const cfg = JSON.parse(configJson);
+ this._model = cfg.model ?? 'default';
+ }
+ prompt = vi.fn().mockResolvedValue('Hello from WASM agent');
+ set_model_provider = vi.fn();
+ reset = vi.fn();
+ free = vi.fn();
+ get_state = vi.fn().mockReturnValue({ messages: [], turn_count: 0, stopped: false });
+ get_todos = vi.fn().mockReturnValue([]);
+ get_tools = vi.fn().mockReturnValue(['read_file', 'write_file', 'edit_file', 'write_todos', 'list_files']);
+ execute_tool = vi.fn().mockResolvedValue(mockToolResult);
+ model() { return this._model; }
+ name() { return undefined; }
+ turn_count() { return this._turnCount; }
+ file_count() { return this._fileCount; }
+ is_stopped() { return false; }
+}
+
+const mockTemplates = [
+ { id: 'coder', name: 'Coder Agent', description: 'Coding assistant', category: 'development', tags: ['code'], version: '1.0.0', author: 'RuVector', builtin: true },
+ { id: 'tester', name: 'Testing Agent', description: 'QA agent', category: 'testing', tags: ['test'], version: '1.0.0', author: 'RuVector', builtin: true },
+];
+
+const mockTemplateDetail = {
+ ...mockTemplates[0],
+ tools: [{ name: 'read_file', description: 'Read', parameters: [{ name: 'path', type: 'string', required: true }], returns: 'content' }],
+ prompts: [{ name: 'coder', system_prompt: 'You are an expert coder.', version: '1.0.0' }],
+ skills: [{ name: 'refactor', description: 'Refactor', trigger: '/refactor', content: 'Improve code' }],
+ mcp_tools: [],
+ capabilities: [],
+};
+
+class MockWasmGallery {
+ list = vi.fn().mockReturnValue(mockTemplates);
+ get = vi.fn().mockImplementation((id: string) => id === 'coder' ? mockTemplateDetail : undefined);
+ search = vi.fn().mockReturnValue([{ ...mockTemplates[0], relevance: 0.7 }]);
+ count = vi.fn().mockReturnValue(2);
+ getCategories = vi.fn().mockReturnValue({ development: 1, testing: 1 });
+ free = vi.fn();
+}
+
+class MockWasmMcpServer {
+ handle_request = vi.fn().mockResolvedValue('{"jsonrpc":"2.0","id":1,"result":{}}');
+ free = vi.fn();
+ constructor(_agent: any) {}
+}
+
+class MockWasmRvfBuilder {
+ _prompts: string[] = [];
+ _tools: string[] = [];
+ _skills: string[] = [];
+ addPrompt(json: string) { this._prompts.push(json); }
+ addTool(json: string) { this._tools.push(json); }
+ addSkill(json: string) { this._skills.push(json); }
+ addPrompts = vi.fn();
+ addTools = vi.fn();
+ addSkills = vi.fn();
+ addCapabilities = vi.fn();
+ addMcpTools = vi.fn();
+ setOrchestrator = vi.fn();
+ build = vi.fn().mockReturnValue(new Uint8Array([0x52, 0x56, 0x46, 0x01]));
+ free = vi.fn();
+}
+
+vi.mock('@ruvector/rvagent-wasm', () => ({
+ default: vi.fn().mockResolvedValue(undefined),
+ initSync: vi.fn(),
+ WasmAgent: MockWasmAgent,
+ WasmGallery: MockWasmGallery,
+ WasmMcpServer: MockWasmMcpServer,
+ WasmRvfBuilder: MockWasmRvfBuilder,
+ JsModelProvider: vi.fn(),
+}));
+
+// ── Import after mocking ─────────────────────────────────────
+
+import {
+ isAgentWasmAvailable,
+ initAgentWasm,
+ createWasmAgent,
+ promptWasmAgent,
+ executeWasmTool,
+ getWasmAgent,
+ listWasmAgents,
+ terminateWasmAgent,
+ getWasmAgentState,
+ getWasmAgentTools,
+ getWasmAgentTodos,
+ exportWasmState,
+ createWasmMcpServer,
+ listGalleryTemplates,
+ getGalleryCount,
+ getGalleryCategories,
+ searchGalleryTemplates,
+ getGalleryTemplate,
+ createAgentFromTemplate,
+ buildRvfContainer,
+ buildRvfFromTemplate,
+} from '../../src/ruvector/agent-wasm.js';
+
+// ── Tests ────────────────────────────────────────────────────
+
+describe('agent-wasm integration', () => {
+ describe('detection and init', () => {
+ it('detects module availability', async () => {
+ expect(await isAgentWasmAvailable()).toBe(true);
+ });
+
+ it('initializes WASM (idempotent)', async () => {
+ await expect(initAgentWasm()).resolves.toBeUndefined();
+ await expect(initAgentWasm()).resolves.toBeUndefined();
+ });
+ });
+
+ describe('agent lifecycle', () => {
+ let agentId: string;
+
+ afterEach(() => {
+ if (agentId) terminateWasmAgent(agentId);
+ });
+
+ it('creates agent with defaults', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ expect(info.id).toMatch(/^wasm-agent-/);
+ expect(info.state).toBe('idle');
+ expect(info.model).toBe('anthropic:claude-sonnet-4-20250514');
+ expect(info.fileCount).toBe(0);
+ expect(info.isStopped).toBe(false);
+ });
+
+ it('creates agent with custom config', async () => {
+ const info = await createWasmAgent({ model: 'custom-model', maxTurns: 10 });
+ agentId = info.id;
+ expect(info.model).toBe('custom-model');
+ expect(info.config.maxTurns).toBe(10);
+ });
+
+ it('lists agents', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ const agents = listWasmAgents();
+ expect(agents.some(a => a.id === agentId)).toBe(true);
+ });
+
+ it('gets agent by id', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ expect(getWasmAgent(agentId)).not.toBeNull();
+ expect(getWasmAgent(agentId)!.id).toBe(agentId);
+ });
+
+ it('returns null for unknown agent', () => {
+ expect(getWasmAgent('nonexistent')).toBeNull();
+ });
+
+ it('terminates agent', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ expect(terminateWasmAgent(agentId)).toBe(true);
+ expect(getWasmAgent(agentId)).toBeNull();
+ agentId = ''; // prevent double-terminate
+ });
+
+ it('returns false for terminating nonexistent', () => {
+ expect(terminateWasmAgent('nonexistent')).toBe(false);
+ });
+ });
+
+ describe('prompting', () => {
+ let agentId: string;
+
+ afterEach(() => { terminateWasmAgent(agentId); });
+
+ it('sends prompt and gets response', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ const result = await promptWasmAgent(agentId, 'Hello');
+ expect(result).toBe('Hello from WASM agent');
+ });
+
+ it('throws for unknown agent', async () => {
+ await expect(promptWasmAgent('nope', 'test')).rejects.toThrow('WASM agent not found');
+ });
+ });
+
+ describe('tool execution', () => {
+ let agentId: string;
+
+ afterEach(() => { terminateWasmAgent(agentId); });
+
+ it('executes tool with flat format', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ const result = await executeWasmTool(agentId, { tool: 'write_file', path: 'test.ts', content: 'const x = 1;' });
+ expect(result.success).toBe(true);
+ });
+
+ it('throws for unknown agent', async () => {
+ await expect(executeWasmTool('nope', { tool: 'list_files' })).rejects.toThrow('WASM agent not found');
+ });
+ });
+
+ describe('agent state accessors', () => {
+ let agentId: string;
+
+ afterEach(() => { terminateWasmAgent(agentId); });
+
+ it('returns state, tools, todos', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+
+ const state = getWasmAgentState(agentId);
+ expect(state).toBeDefined();
+
+ const tools = getWasmAgentTools(agentId);
+ expect(tools).toContain('read_file');
+
+ const todos = getWasmAgentTodos(agentId);
+ expect(Array.isArray(todos)).toBe(true);
+ });
+
+ it('exports full state as JSON', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ const exported = exportWasmState(agentId);
+ const parsed = JSON.parse(exported);
+ expect(parsed).toHaveProperty('agentState');
+ expect(parsed).toHaveProperty('tools');
+ expect(parsed).toHaveProperty('todos');
+ expect(parsed).toHaveProperty('info');
+ });
+
+ it('throws for unknown agent', () => {
+ expect(() => getWasmAgentState('nope')).toThrow('WASM agent not found');
+ expect(() => getWasmAgentTools('nope')).toThrow('WASM agent not found');
+ expect(() => getWasmAgentTodos('nope')).toThrow('WASM agent not found');
+ expect(() => exportWasmState('nope')).toThrow('WASM agent not found');
+ });
+ });
+
+ describe('MCP server bridge', () => {
+ let agentId: string;
+
+ afterEach(() => { terminateWasmAgent(agentId); });
+
+ it('creates handler and processes requests', async () => {
+ const info = await createWasmAgent();
+ agentId = info.id;
+ const handler = await createWasmMcpServer(agentId);
+ expect(typeof handler).toBe('function');
+ const resp = await handler('{"jsonrpc":"2.0","id":1,"method":"tools/list"}');
+ expect(resp).toContain('jsonrpc');
+ });
+
+ it('throws for unknown agent', async () => {
+ await expect(createWasmMcpServer('nope')).rejects.toThrow('WASM agent not found');
+ });
+ });
+
+ describe('gallery templates', () => {
+ it('lists templates', async () => {
+ const templates = await listGalleryTemplates();
+ expect(templates).toHaveLength(2);
+ expect(templates[0].id).toBe('coder');
+ });
+
+ it('counts templates', async () => {
+ expect(await getGalleryCount()).toBe(2);
+ });
+
+ it('gets categories', async () => {
+ const cats = await getGalleryCategories();
+ expect(cats.development).toBe(1);
+ expect(cats.testing).toBe(1);
+ });
+
+ it('searches templates', async () => {
+ const results = await searchGalleryTemplates('code');
+ expect(results).toHaveLength(1);
+ expect(results[0].relevance).toBeGreaterThan(0);
+ });
+
+ it('gets template detail', async () => {
+ const detail = await getGalleryTemplate('coder');
+ expect(detail).not.toBeNull();
+ expect(detail!.prompts).toHaveLength(1);
+ expect(detail!.tools).toHaveLength(1);
+ });
+
+ it('returns null for unknown template', async () => {
+ expect(await getGalleryTemplate('nonexistent')).toBeNull();
+ });
+
+ it('creates agent from template', async () => {
+ const info = await createAgentFromTemplate('coder');
+ expect(info.id).toMatch(/^wasm-agent-/);
+ terminateWasmAgent(info.id);
+ });
+
+ it('throws for unknown template', async () => {
+ await expect(createAgentFromTemplate('nonexistent')).rejects.toThrow('Gallery template not found');
+ });
+ });
+
+ describe('RVF container operations', () => {
+ it('builds container with prompts/tools/skills', async () => {
+ const container = await buildRvfContainer({
+ prompts: [{ name: 'test', system_prompt: 'You are a test.', version: '1.0.0' }],
+ tools: [{ name: 'read_file', description: 'Read', parameters: [{ name: 'path', type: 'string', required: true }], returns: 'content' }],
+ skills: [{ name: 'refactor', description: 'Refactor', trigger: '/refactor', content: 'Improve code' }],
+ });
+ expect(container).toBeInstanceOf(Uint8Array);
+ expect(container[0]).toBe(0x52); // 'R'
+ });
+
+ it('builds container from gallery template', async () => {
+ const container = await buildRvfFromTemplate('coder');
+ expect(container).toBeInstanceOf(Uint8Array);
+ });
+
+ it('throws for unknown template', async () => {
+ await expect(buildRvfFromTemplate('nonexistent')).rejects.toThrow('Gallery template not found');
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/ruvllm-wasm.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/ruvllm-wasm.test.ts
new file mode 100644
index 0000000000..6d653ad6d9
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/ruvllm-wasm.test.ts
@@ -0,0 +1,407 @@
+/**
+ * Tests for ruvllm-wasm integration module.
+ * Mocks @ruvector/ruvllm-wasm since it may not be installed in CI.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// ── Mock WASM module ─────────────────────────────────────────
+
+const mockHnswRouter = {
+ addPattern: vi.fn().mockReturnValue(true),
+ route: vi.fn().mockReturnValue([{ name: 'test', score: 0.95 }]),
+ setEfSearch: vi.fn(),
+ clear: vi.fn(),
+ toJson: vi.fn().mockReturnValue('{}'),
+ dimensions: 64,
+};
+
+const mockSonaConfig = {
+ hiddenDim: 64,
+ learningRate: 0.01,
+ emaDecay: 0.99,
+ ewcLambda: 0.01,
+ microLoraRank: 2,
+ patternCapacity: 100,
+};
+
+const mockSonaInstant = {
+ instantAdapt: vi.fn(),
+ recordPattern: vi.fn(),
+ suggestAction: vi.fn().mockReturnValue('optimize'),
+ stats: vi.fn().mockReturnValue({ adaptations: 1 }),
+ toJson: vi.fn().mockReturnValue('{"adaptations":1}'),
+ reset: vi.fn(),
+};
+
+const mockLoraConfig = {
+ inputDim: 64,
+ outputDim: 32,
+ rank: 2,
+ alpha: 1.0,
+};
+
+const mockLora = {
+ apply: vi.fn().mockReturnValue(new Float32Array(32)),
+ adapt: vi.fn(),
+ applyUpdates: vi.fn(),
+ stats: vi.fn().mockReturnValue({ rank: 2 }),
+ reset: vi.fn(),
+ toJson: vi.fn().mockReturnValue('{"rank":2}'),
+ getConfig: vi.fn().mockReturnValue(mockLoraConfig),
+ pendingUpdates: vi.fn().mockReturnValue(0),
+};
+
+const mockAdaptFeedback = {
+ quality: 0,
+ learningRate: 0,
+ success: true,
+};
+
+const mockKvCacheConfig = { tailLength: 4, maxTokens: 2048, numKvHeads: 8, headDim: 64 };
+const mockKvCache = {
+ append: vi.fn(),
+ stats: vi.fn().mockReturnValue({}),
+ clear: vi.fn(),
+ tokenCount: 0,
+};
+
+const mockGenerateConfig = {
+ maxTokens: 100,
+ temperature: 0.7,
+ topP: 0.9,
+ topK: 40,
+ repetitionPenalty: 1.1,
+ addStopSequence: vi.fn(),
+ clearStopSequences: vi.fn(),
+ toJson: vi.fn().mockReturnValue('{"maxTokens":100}'),
+};
+
+const mockBufferPool = {
+ prewarmAll: vi.fn(),
+ statsJson: vi.fn().mockReturnValue('{"hitRate":0.95}'),
+ hitRate: 0.95,
+ clear: vi.fn(),
+};
+
+const mockInferenceArena = {
+ reset: vi.fn(),
+ used: 1024,
+ capacity: 8192,
+ remaining: 7168,
+};
+
+const mockChatMessage = {
+ system: vi.fn().mockReturnValue({ role: 'system', content: 'test' }),
+ user: vi.fn().mockReturnValue({ role: 'user', content: 'test' }),
+ assistant: vi.fn().mockReturnValue({ role: 'assistant', content: 'test' }),
+};
+
+const mockChatTemplate = {
+ format: vi.fn().mockReturnValue('<formatted>'),
+ name: 'llama3',
+};
+
+vi.mock('@ruvector/ruvllm-wasm', () => ({
+ default: vi.fn(),
+ initSync: vi.fn(),
+ RuvLLMWasm: vi.fn().mockImplementation(() => ({
+ initialize: vi.fn(),
+ isInitialized: true,
+ getPoolStats: vi.fn().mockReturnValue('{}'),
+ reset: vi.fn(),
+ })),
+ HnswRouterWasm: vi.fn().mockImplementation(() => mockHnswRouter),
+ SonaConfigWasm: vi.fn().mockImplementation(() => ({ ...mockSonaConfig })),
+ SonaInstantWasm: vi.fn().mockImplementation(() => mockSonaInstant),
+ MicroLoraConfigWasm: vi.fn().mockImplementation(() => ({ ...mockLoraConfig })),
+ AdaptFeedbackWasm: vi.fn().mockImplementation(() => ({ ...mockAdaptFeedback })),
+ MicroLoraWasm: vi.fn().mockImplementation(() => mockLora),
+ KvCacheConfigWasm: vi.fn().mockImplementation(() => ({ ...mockKvCacheConfig })),
+ KvCacheWasm: Object.assign(vi.fn().mockImplementation(() => mockKvCache), {
+ withDefaults: vi.fn().mockReturnValue(mockKvCache),
+ }),
+ GenerateConfig: class {
+ maxTokens = 100;
+ temperature = 0.7;
+ topP = 0.9;
+ topK = 40;
+ repetitionPenalty = 1.1;
+ addStopSequence = mockGenerateConfig.addStopSequence;
+ clearStopSequences = mockGenerateConfig.clearStopSequences;
+ toJson = mockGenerateConfig.toJson;
+ },
+ BufferPoolWasm: { withCapacity: vi.fn().mockReturnValue(mockBufferPool) },
+ InferenceArenaWasm: Object.assign(vi.fn().mockImplementation(() => mockInferenceArena), {
+ forModel: vi.fn().mockReturnValue(mockInferenceArena),
+ }),
+ ChatMessageWasm: mockChatMessage,
+ ChatTemplateWasm: {
+ llama3: vi.fn().mockReturnValue(mockChatTemplate),
+ mistral: vi.fn().mockReturnValue(mockChatTemplate),
+ chatml: vi.fn().mockReturnValue(mockChatTemplate),
+ phi: vi.fn().mockReturnValue(mockChatTemplate),
+ gemma: vi.fn().mockReturnValue(mockChatTemplate),
+ custom: vi.fn().mockReturnValue(mockChatTemplate),
+ detectFromModelId: vi.fn().mockReturnValue(mockChatTemplate),
+ },
+ getVersion: vi.fn().mockReturnValue('2.0.1'),
+ isReady: vi.fn().mockReturnValue(true),
+}));
+
+// Mock fs and module for Node.js init
+vi.mock('node:fs', () => ({
+ readFileSync: vi.fn().mockReturnValue(Buffer.from('fake wasm bytes')),
+}));
+vi.mock('node:module', () => ({
+ createRequire: vi.fn().mockReturnValue({
+ resolve: vi.fn().mockReturnValue('/fake/path/ruvllm_wasm_bg.wasm'),
+ }),
+}));
+
+// ── Tests ────────────────────────────────────────────────────
+
+describe('ruvllm-wasm integration', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('isRuvllmWasmAvailable', () => {
+ it('should return true when module is available', async () => {
+ const { isRuvllmWasmAvailable } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const available = await isRuvllmWasmAvailable();
+ expect(available).toBe(true);
+ });
+ });
+
+ describe('getRuvllmStatus', () => {
+ it('should return status with version', async () => {
+ const { getRuvllmStatus } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const status = await getRuvllmStatus();
+ expect(status.available).toBe(true);
+ expect(status.version).toBe('2.0.1');
+ });
+ });
+
+ describe('createHnswRouter', () => {
+ it('should create router with dimensions and maxPatterns', async () => {
+ const { createHnswRouter } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const router = await createHnswRouter({ dimensions: 64, maxPatterns: 10 });
+ expect(router).toBeDefined();
+ expect(router.patternCount()).toBe(0);
+ });
+
+ it('should add patterns successfully', async () => {
+ const { createHnswRouter } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const router = await createHnswRouter({ dimensions: 64, maxPatterns: 10 });
+ const ok = router.addPattern({
+ name: 'test-pattern',
+ embedding: new Float32Array(64),
+ metadata: { type: 'test' },
+ });
+ expect(ok).toBe(true);
+ expect(router.patternCount()).toBe(1);
+ });
+
+ it('should enforce HNSW_MAX_SAFE_PATTERNS limit', async () => {
+ const { createHnswRouter, HNSW_MAX_SAFE_PATTERNS } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const router = await createHnswRouter({ dimensions: 64, maxPatterns: 20 });
+ // Add up to the limit
+ for (let i = 0; i < HNSW_MAX_SAFE_PATTERNS; i++) {
+ router.addPattern({ name: `p${i}`, embedding: new Float32Array(64) });
+ }
+ // Next should throw
+ expect(() => router.addPattern({ name: 'overflow', embedding: new Float32Array(64) }))
+ .toThrow(/pattern limit reached/);
+ });
+
+ it('should route queries', async () => {
+ const { createHnswRouter } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const router = await createHnswRouter({ dimensions: 64, maxPatterns: 10 });
+ const results = router.route(new Float32Array(64), 3);
+ expect(results).toHaveLength(1);
+ expect(results[0].name).toBe('test');
+ });
+
+ it('should clear patterns', async () => {
+ const { createHnswRouter } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const router = await createHnswRouter({ dimensions: 64, maxPatterns: 10 });
+ router.addPattern({ name: 'p1', embedding: new Float32Array(64) });
+ expect(router.patternCount()).toBe(1);
+ router.clear();
+ expect(router.patternCount()).toBe(0);
+ });
+ });
+
+ describe('createSonaInstant', () => {
+ it('should create with default config', async () => {
+ const { createSonaInstant } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const sona = await createSonaInstant();
+ expect(sona).toBeDefined();
+ expect(sona.adapt).toBeTypeOf('function');
+ });
+
+ it('should adapt with quality signal', async () => {
+ const { createSonaInstant } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const sona = await createSonaInstant({ hiddenDim: 32 });
+ sona.adapt(0.85);
+ expect(mockSonaInstant.instantAdapt).toHaveBeenCalledWith(0.85);
+ });
+
+ it('should record patterns', async () => {
+ const { createSonaInstant } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const sona = await createSonaInstant();
+ sona.recordPattern([0.1, 0.2, 0.3], true);
+ expect(mockSonaInstant.recordPattern).toHaveBeenCalledWith([0.1, 0.2, 0.3], true);
+ });
+
+ it('should suggest actions', async () => {
+ const { createSonaInstant } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const sona = await createSonaInstant();
+ const action = sona.suggestAction('test context');
+ expect(action).toBe('optimize');
+ });
+
+ it('should return stats as JSON', async () => {
+ const { createSonaInstant } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const sona = await createSonaInstant();
+ const stats = sona.stats();
+ expect(stats).toBe('{"adaptations":1}');
+ });
+ });
+
+ describe('createMicroLora', () => {
+ it('should create with config', async () => {
+ const { createMicroLora } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const lora = await createMicroLora({ inputDim: 64, outputDim: 32, rank: 2 });
+ expect(lora).toBeDefined();
+ });
+
+ it('should apply transform', async () => {
+ const { createMicroLora } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const lora = await createMicroLora({ inputDim: 64, outputDim: 32 });
+ const input = new Float32Array(64);
+ const output = lora.apply(input);
+ expect(mockLora.apply).toHaveBeenCalledWith(input);
+ expect(output).toBeInstanceOf(Float32Array);
+ });
+
+ it('should adapt with feedback', async () => {
+ const { createMicroLora } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const lora = await createMicroLora({ inputDim: 64, outputDim: 32 });
+ lora.adapt(0.9, 0.01, true);
+ expect(mockLora.adapt).toHaveBeenCalled();
+ });
+
+ it('should report pending updates', async () => {
+ const { createMicroLora } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const lora = await createMicroLora({ inputDim: 64, outputDim: 32 });
+ expect(lora.pendingUpdates()).toBe(0);
+ });
+ });
+
+ describe('formatChat', () => {
+ it('should format with preset template', async () => {
+ const { formatChat } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const result = await formatChat(
+ [{ role: 'system', content: 'You are helpful.' }, { role: 'user', content: 'Hi' }],
+ 'llama3',
+ );
+ expect(result).toBe('<formatted>');
+ });
+
+ it('should format with model ID auto-detection', async () => {
+ const { formatChat } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const result = await formatChat(
+ [{ role: 'user', content: 'Hello' }],
+ { modelId: 'meta-llama/Llama-3-8B' },
+ );
+ expect(result).toBe('<formatted>');
+ });
+
+ it('should format with custom template', async () => {
+ const { formatChat } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const result = await formatChat(
+ [{ role: 'user', content: 'Test' }],
+ { custom: '{{role}}: {{content}}' },
+ );
+ expect(result).toBe('<formatted>');
+ });
+
+ it('should reject unknown preset', async () => {
+ const { formatChat } = await import('../../src/ruvector/ruvllm-wasm.js');
+ await expect(formatChat([{ role: 'user', content: 'Hi' }], 'unknown' as any))
+ .rejects.toThrow(/Unknown template preset/);
+ });
+ });
+
+ describe('createKvCache', () => {
+ it('should create with defaults', async () => {
+ const { createKvCache } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const cache = await createKvCache();
+ expect(cache).toBeDefined();
+ expect(cache.tokenCount()).toBe(0);
+ });
+
+ it('should create with config', async () => {
+ const { createKvCache } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const cache = await createKvCache({ maxTokens: 4096, headDim: 128 });
+ expect(cache).toBeDefined();
+ });
+
+ it('should append and clear', async () => {
+ const { createKvCache } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const cache = await createKvCache();
+ cache.append(new Float32Array(8), new Float32Array(8));
+ expect(mockKvCache.append).toHaveBeenCalled();
+ cache.clear();
+ expect(mockKvCache.clear).toHaveBeenCalled();
+ });
+ });
+
+ describe('createGenerateConfig', () => {
+ it('should create config JSON', async () => {
+ const { createGenerateConfig } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const config = await createGenerateConfig({ maxTokens: 100, temperature: 0.7 });
+ expect(config).toContain('maxTokens');
+ });
+
+ it('should handle stop sequences', async () => {
+ const { createGenerateConfig } = await import('../../src/ruvector/ruvllm-wasm.js');
+ await createGenerateConfig({ stopSequences: ['<|end|>', '\n\n'] });
+ expect(mockGenerateConfig.addStopSequence).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ describe('createBufferPool', () => {
+ it('should create with capacity', async () => {
+ const { createBufferPool } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const pool = await createBufferPool(1024);
+ expect(pool).toBeDefined();
+ expect(pool.hitRate()).toBe(0.95);
+ });
+
+ it('should prewarm buffers', async () => {
+ const { createBufferPool } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const pool = await createBufferPool(1024);
+ pool.prewarm(10);
+ expect(mockBufferPool.prewarmAll).toHaveBeenCalledWith(10);
+ });
+ });
+
+ describe('createInferenceArena', () => {
+ it('should create with raw capacity', async () => {
+ const { createInferenceArena } = await import('../../src/ruvector/ruvllm-wasm.js');
+ const arena = await createInferenceArena({ capacity: 8192 });
+ expect(arena).toBeDefined();
+ expect(arena.capacity()).toBe(8192);
+ expect(arena.remaining()).toBe(7168);
+ });
+ });
+
+ describe('HNSW_MAX_SAFE_PATTERNS', () => {
+ it('should be 1024', async () => {
+ const { HNSW_MAX_SAFE_PATTERNS } = await import('../../src/ruvector/ruvllm-wasm.js');
+ expect(HNSW_MAX_SAFE_PATTERNS).toBe(1024);
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvllm-tools.test.ts b/v3/@claude-flow/cli/__tests__/ruvllm-tools.test.ts
new file mode 100644
index 0000000000..01de3fa833
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvllm-tools.test.ts
@@ -0,0 +1,184 @@
+/**
+ * Tests for ruvllm-wasm MCP tools.
+ * Mocks the integration module to test tool handlers in isolation.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the integration module
+const mockRouter = {
+ addPattern: vi.fn().mockReturnValue(true),
+ route: vi.fn().mockReturnValue([{ name: 'test', score: 0.9 }]),
+ clear: vi.fn(),
+ patternCount: vi.fn().mockReturnValue(1),
+ toJson: vi.fn().mockReturnValue('{}'),
+};
+
+const mockSona = {
+ adapt: vi.fn(),
+ recordPattern: vi.fn(),
+ suggestAction: vi.fn().mockReturnValue('optimize'),
+ stats: vi.fn().mockReturnValue('{"adaptations":1}'),
+ reset: vi.fn(),
+ toJson: vi.fn().mockReturnValue('{}'),
+};
+
+const mockLora = {
+ apply: vi.fn().mockReturnValue(new Float32Array(32)),
+ adapt: vi.fn(),
+ applyUpdates: vi.fn(),
+ stats: vi.fn().mockReturnValue('{"rank":2}'),
+ reset: vi.fn(),
+ toJson: vi.fn().mockReturnValue('{}'),
+ pendingUpdates: vi.fn().mockReturnValue(0),
+};
+
+vi.mock('../src/ruvector/ruvllm-wasm.js', () => ({
+ isRuvllmWasmAvailable: vi.fn().mockResolvedValue(true),
+ initRuvllmWasm: vi.fn().mockResolvedValue(undefined),
+ getRuvllmStatus: vi.fn().mockResolvedValue({ available: true, initialized: true, version: '2.0.1' }),
+ createHnswRouter: vi.fn().mockResolvedValue(mockRouter),
+ createSonaInstant: vi.fn().mockResolvedValue(mockSona),
+ createMicroLora: vi.fn().mockResolvedValue(mockLora),
+ formatChat: vi.fn().mockResolvedValue('<|begin|>system\nHello<|end|>'),
+ createGenerateConfig: vi.fn().mockResolvedValue('{"maxTokens":100}'),
+ createKvCache: vi.fn().mockResolvedValue({ append: vi.fn(), clear: vi.fn(), stats: vi.fn(), tokenCount: vi.fn() }),
+ createBufferPool: vi.fn().mockResolvedValue({ prewarm: vi.fn(), stats: vi.fn(), hitRate: vi.fn(), clear: vi.fn() }),
+ createInferenceArena: vi.fn().mockResolvedValue({ reset: vi.fn(), used: vi.fn(), capacity: vi.fn(), remaining: vi.fn() }),
+ HNSW_MAX_SAFE_PATTERNS: 11,
+}));
+
+import { ruvllmWasmTools } from '../src/mcp-tools/ruvllm-tools.js';
+
+function findTool(name: string) {
+ const tool = ruvllmWasmTools.find(t => t.name === name);
+ if (!tool) throw new Error(`Tool not found: ${name}`);
+ return tool;
+}
+
+describe('ruvllm-wasm MCP tools', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should export 10 tools', () => {
+ expect(ruvllmWasmTools).toHaveLength(10);
+ });
+
+ describe('ruvllm_status', () => {
+ it('should return status', async () => {
+ const tool = findTool('ruvllm_status');
+ const result = await tool.handler({}) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.available).toBe(true);
+ expect(data.version).toBe('2.0.1');
+ });
+ });
+
+ describe('ruvllm_hnsw_create', () => {
+ it('should create router and return ID', async () => {
+ const tool = findTool('ruvllm_hnsw_create');
+ const result = await tool.handler({ dimensions: 64, maxPatterns: 10 }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ expect(data.routerId).toMatch(/^hnsw-/);
+ });
+ });
+
+ describe('ruvllm_hnsw_add', () => {
+ it('should add pattern to router', async () => {
+ // First create
+ const createTool = findTool('ruvllm_hnsw_create');
+ const createResult = await createTool.handler({ dimensions: 64, maxPatterns: 10 }) as any;
+ const routerId = JSON.parse(createResult.content[0].text).routerId;
+
+ const addTool = findTool('ruvllm_hnsw_add');
+ const result = await addTool.handler({ routerId, name: 'test', embedding: Array(64).fill(0) }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ });
+
+ it('should error on unknown router', async () => {
+ const tool = findTool('ruvllm_hnsw_add');
+ const result = await tool.handler({ routerId: 'nonexistent', name: 'test', embedding: [] }) as any;
+ expect(result.isError).toBe(true);
+ });
+ });
+
+ describe('ruvllm_hnsw_route', () => {
+ it('should route query', async () => {
+ const createTool = findTool('ruvllm_hnsw_create');
+ const createResult = await createTool.handler({ dimensions: 64, maxPatterns: 10 }) as any;
+ const routerId = JSON.parse(createResult.content[0].text).routerId;
+
+ const routeTool = findTool('ruvllm_hnsw_route');
+ const result = await routeTool.handler({ routerId, query: Array(64).fill(0) }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.results).toBeDefined();
+ });
+ });
+
+ describe('ruvllm_sona_create', () => {
+ it('should create SONA instance', async () => {
+ const tool = findTool('ruvllm_sona_create');
+ const result = await tool.handler({ hiddenDim: 32 }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ expect(data.sonaId).toMatch(/^sona-/);
+ });
+ });
+
+ describe('ruvllm_sona_adapt', () => {
+ it('should adapt with quality signal', async () => {
+ const createTool = findTool('ruvllm_sona_create');
+ const createResult = await createTool.handler({}) as any;
+ const sonaId = JSON.parse(createResult.content[0].text).sonaId;
+
+ const adaptTool = findTool('ruvllm_sona_adapt');
+ const result = await adaptTool.handler({ sonaId, quality: 0.85 }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ });
+ });
+
+ describe('ruvllm_microlora_create', () => {
+ it('should create MicroLoRA', async () => {
+ const tool = findTool('ruvllm_microlora_create');
+ const result = await tool.handler({ inputDim: 64, outputDim: 32, rank: 2 }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ expect(data.loraId).toMatch(/^lora-/);
+ });
+ });
+
+ describe('ruvllm_microlora_adapt', () => {
+ it('should adapt with feedback', async () => {
+ const createTool = findTool('ruvllm_microlora_create');
+ const createResult = await createTool.handler({ inputDim: 64, outputDim: 32 }) as any;
+ const loraId = JSON.parse(createResult.content[0].text).loraId;
+
+ const adaptTool = findTool('ruvllm_microlora_adapt');
+ const result = await adaptTool.handler({ loraId, quality: 0.9 }) as any;
+ const data = JSON.parse(result.content[0].text);
+ expect(data.success).toBe(true);
+ });
+ });
+
+ describe('ruvllm_chat_format', () => {
+ it('should format with preset', async () => {
+ const tool = findTool('ruvllm_chat_format');
+ const result = await tool.handler({
+ messages: [{ role: 'user', content: 'Hi' }],
+ template: 'llama3',
+ }) as any;
+ expect(result.content[0].text).toContain('system');
+ });
+ });
+
+ describe('ruvllm_generate_config', () => {
+ it('should create config', async () => {
+ const tool = findTool('ruvllm_generate_config');
+ const result = await tool.handler({ maxTokens: 100, temperature: 0.7 }) as any;
+ expect(result.content[0].text).toContain('maxTokens');
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/wasm-agent-tools.test.ts b/v3/@claude-flow/cli/__tests__/wasm-agent-tools.test.ts
new file mode 100644
index 0000000000..f56e892086
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/wasm-agent-tools.test.ts
@@ -0,0 +1,141 @@
+/**
+ * Tests for WASM Agent MCP Tools
+ *
+ * Validates all 10 MCP tool handlers work correctly.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+// ── Mock the agent-wasm module ───────────────────────────────
+
+const mockAgentInfo = {
+ id: 'wasm-agent-1-test',
+ state: 'idle' as const,
+ config: {},
+ model: 'test-model',
+ turnCount: 0,
+ fileCount: 0,
+ isStopped: false,
+ createdAt: '2026-03-17T00:00:00.000Z',
+};
+
+vi.mock('../src/ruvector/agent-wasm.js', () => ({
+ isAgentWasmAvailable: vi.fn().mockResolvedValue(true),
+ initAgentWasm: vi.fn().mockResolvedValue(undefined),
+ createWasmAgent: vi.fn().mockResolvedValue({ ...mockAgentInfo }),
+ promptWasmAgent: vi.fn().mockResolvedValue('Agent response'),
+ executeWasmTool: vi.fn().mockResolvedValue({ success: true, output: 'ok' }),
+ getWasmAgent: vi.fn().mockReturnValue({ ...mockAgentInfo }),
+ listWasmAgents: vi.fn().mockReturnValue([{ ...mockAgentInfo }]),
+ terminateWasmAgent: vi.fn().mockReturnValue(true),
+ getWasmAgentState: vi.fn().mockReturnValue({ messages: [], turn_count: 0 }),
+ getWasmAgentTools: vi.fn().mockReturnValue(['read_file', 'write_file']),
+ getWasmAgentTodos: vi.fn().mockReturnValue([]),
+ exportWasmState: vi.fn().mockReturnValue('{"state":"exported"}'),
+ createWasmMcpServer: vi.fn().mockResolvedValue(vi.fn().mockResolvedValue('{}')),
+ listGalleryTemplates: vi.fn().mockResolvedValue([{ id: 'coder', name: 'Coder Agent' }]),
+ getGalleryCount: vi.fn().mockResolvedValue(6),
+ getGalleryCategories: vi.fn().mockResolvedValue({ development: 2 }),
+ searchGalleryTemplates: vi.fn().mockResolvedValue([{ id: 'coder', name: 'Coder Agent', relevance: 0.7 }]),
+ getGalleryTemplate: vi.fn().mockResolvedValue({ id: 'coder', prompts: [], tools: [], skills: [] }),
+ createAgentFromTemplate: vi.fn().mockResolvedValue({ ...mockAgentInfo, id: 'wasm-agent-2-tpl' }),
+ buildRvfContainer: vi.fn().mockResolvedValue(new Uint8Array([0x52, 0x56, 0x46, 0x01])),
+ buildRvfFromTemplate: vi.fn().mockResolvedValue(new Uint8Array([0x52, 0x56, 0x46, 0x01])),
+}));
+
+import { wasmAgentTools } from '../src/mcp-tools/wasm-agent-tools.js';
+
+// ── Helper ───────────────────────────────────────────────────
+
+function findTool(name: string) {
+ const tool = wasmAgentTools.find(t => t.name === name);
+ if (!tool) throw new Error(`Tool not found: ${name}`);
+ return tool;
+}
+
+async function callTool(name: string, args: Record<string, unknown> = {}) {
+ return findTool(name).handler(args);
+}
+
+function parseResult(result: { content: Array<{ type: string; text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+// ── Tests ────────────────────────────────────────────────────
+
+describe('wasm-agent-tools MCP', () => {
+ it('exports 10 tools', () => {
+ expect(wasmAgentTools).toHaveLength(10);
+ });
+
+ it('all tools have required fields', () => {
+ for (const tool of wasmAgentTools) {
+ expect(tool.name).toBeTruthy();
+ expect(tool.description).toBeTruthy();
+ expect(tool.inputSchema).toBeDefined();
+ expect(typeof tool.handler).toBe('function');
+ }
+ });
+
+ describe('wasm_agent_create', () => {
+ it('creates with config', async () => {
+ const data = parseResult(await callTool('wasm_agent_create', { instructions: 'Test' }));
+ expect(data.success).toBe(true);
+ expect(data.agent.id).toBe('wasm-agent-1-test');
+ });
+
+ it('creates from template', async () => {
+ const data = parseResult(await callTool('wasm_agent_create', { template: 'coder' }));
+ expect(data.success).toBe(true);
+ expect(data.source).toBe('gallery');
+ });
+ });
+
+ it('wasm_agent_prompt returns response', async () => {
+ const result = await callTool('wasm_agent_prompt', { agentId: 'test', input: 'Hello' });
+ expect(result.content[0].text).toBe('Agent response');
+ });
+
+ it('wasm_agent_tool executes tool', async () => {
+ const result = await callTool('wasm_agent_tool', { agentId: 'test', toolName: 'read_file', toolInput: { path: 'x' } });
+ const text = result.content[0].text;
+ expect(text).toContain('success');
+ });
+
+ it('wasm_agent_list lists agents', async () => {
+ const data = parseResult(await callTool('wasm_agent_list'));
+ expect(data.count).toBe(1);
+ });
+
+ it('wasm_agent_terminate terminates', async () => {
+ const data = parseResult(await callTool('wasm_agent_terminate', { agentId: 'test' }));
+ expect(data.success).toBe(true);
+ });
+
+ it('wasm_agent_files lists files', async () => {
+ const result = await callTool('wasm_agent_files', { agentId: 'test' });
+ expect(result.content[0].text).toContain('read_file');
+ });
+
+ it('wasm_agent_export exports state', async () => {
+ const result = await callTool('wasm_agent_export', { agentId: 'test' });
+ expect(result.content[0].text).toBe('{"state":"exported"}');
+ });
+
+ it('wasm_gallery_list lists templates', async () => {
+ const data = parseResult(await callTool('wasm_gallery_list'));
+ expect(data.count).toBe(1);
+ expect(data.templates[0].id).toBe('coder');
+ });
+
+ it('wasm_gallery_search finds templates', async () => {
+ const data = parseResult(await callTool('wasm_gallery_search', { query: 'code' }));
+ expect(data.count).toBe(1);
+ });
+
+ it('wasm_gallery_create creates from template', async () => {
+ const data = parseResult(await callTool('wasm_gallery_create', { template: 'coder' }));
+ expect(data.success).toBe(true);
+ expect(data.template).toBe('coder');
+ });
+});
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 778eeea088..96b27ec529 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.5.23",
+ "version": "3.5.28",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
@@ -97,11 +97,14 @@
"@claude-flow/guidance": "^3.0.0-alpha.1",
"@claude-flow/memory": "^3.0.0-alpha.11",
"@claude-flow/plugin-gastown-bridge": "^0.1.3",
- "agentic-flow": "^3.0.0-alpha.1",
"@ruvector/attention": "^0.1.4",
"@ruvector/learning-wasm": "^0.1.29",
"@ruvector/router": "^0.1.27",
- "@ruvector/sona": "^0.1.5"
+ "@ruvector/rvagent-wasm": "^0.1.0",
+ "@ruvector/ruvllm-wasm": "^2.0.2",
+ "@ruvector/sona": "^0.1.5",
+ "agentic-flow": "^3.0.0-alpha.1",
+ "ruvector": "^0.2.16"
},
"publishConfig": {
"access": "public",
diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.ts
index 0523ffab48..3da2974de2 100644
--- a/v3/@claude-flow/cli/src/mcp-client.ts
+++ b/v3/@claude-flow/cli/src/mcp-client.ts
@@ -37,6 +37,9 @@ import { coordinationTools } from './mcp-tools/coordination-tools.js';
import { browserTools } from './mcp-tools/browser-tools.js';
// Phase 6: AgentDB v3 controller tools
import { agentdbTools } from './mcp-tools/agentdb-tools.js';
+// RuVector WASM tools
+import { ruvllmWasmTools } from './mcp-tools/ruvllm-tools.js';
+import { wasmAgentTools } from './mcp-tools/wasm-agent-tools.js';
/**
* MCP Tool Registry
@@ -79,6 +82,9 @@ registerTools([
...browserTools,
// Phase 6: AgentDB v3 controller tools
...agentdbTools,
+ // RuVector WASM tools
+ ...ruvllmWasmTools,
+ ...wasmAgentTools,
]);
/**
diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.ts
index fbecc6e3d6..965b0c1389 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts
@@ -21,3 +21,5 @@ export { transferTools } from './transfer-tools.js';
export { securityTools } from './security-tools.js';
export { embeddingsTools } from './embeddings-tools.js';
export { claimsTools } from './claims-tools.js';
+export { wasmAgentTools } from './wasm-agent-tools.js';
+export { ruvllmWasmTools } from './ruvllm-tools.js';
diff --git a/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts
new file mode 100644
index 0000000000..99c7d4a3f9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts
@@ -0,0 +1,281 @@
+/**
+ * RuVector LLM WASM MCP Tools
+ *
+ * Exposes @ruvector/ruvllm-wasm operations via MCP protocol.
+ * All tools gracefully degrade when the WASM package is not installed.
+ */
+
+import type { MCPTool } from './types.js';
+import type { ChatMessage } from '../ruvector/ruvllm-wasm.js';
+
+async function loadRuvllmWasm() {
+ return import('../ruvector/ruvllm-wasm.js');
+}
+
+export const ruvllmWasmTools: MCPTool[] = [
+ {
+ name: 'ruvllm_status',
+ description: 'Get ruvllm-wasm availability and initialization status.',
+ inputSchema: { type: 'object' as const, properties: {} },
+ handler: async () => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const status = await mod.getRuvllmStatus();
+ return { content: [{ type: 'text', text: JSON.stringify(status, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_hnsw_create',
+ description: 'Create a WASM HNSW router for semantic pattern routing. Max ~11 patterns (v2.0.1 limit).',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ dimensions: { type: 'number', description: 'Embedding dimensions (e.g., 64, 128, 384)' },
+ maxPatterns: { type: 'number', description: 'Max patterns capacity (limit ~11 in v2.0.1)' },
+ efSearch: { type: 'number', description: 'HNSW ef search parameter (higher = more accurate, slower)' },
+ },
+ required: ['dimensions', 'maxPatterns'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const router = await mod.createHnswRouter({
+ dimensions: args.dimensions as number,
+ maxPatterns: args.maxPatterns as number,
+ efSearch: args.efSearch as number | undefined,
+ });
+ // Store router in module-level registry
+ const id = `hnsw-${Date.now().toString(36)}`;
+ hnswRouters.set(id, router);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, routerId: id, dimensions: args.dimensions, maxPatterns: args.maxPatterns }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_hnsw_add',
+ description: 'Add a pattern to an HNSW router. Embedding must match router dimensions.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ routerId: { type: 'string', description: 'HNSW router ID from ruvllm_hnsw_create' },
+ name: { type: 'string', description: 'Pattern name/label' },
+ embedding: { type: 'array', description: 'Float array embedding vector' },
+ metadata: { type: 'object', description: 'Optional metadata object' },
+ },
+ required: ['routerId', 'name', 'embedding'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const router = hnswRouters.get(args.routerId as string);
+ if (!router) return { content: [{ type: 'text', text: JSON.stringify({ error: `Router not found: ${args.routerId}` }) }], isError: true };
+ const embedding = new Float32Array(args.embedding as number[]);
+ const ok = router.addPattern({
+ name: args.name as string,
+ embedding,
+ metadata: args.metadata as Record<string, unknown>,
+ });
+ return { content: [{ type: 'text', text: JSON.stringify({ success: ok, patternCount: router.patternCount() }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_hnsw_route',
+ description: 'Route a query embedding to nearest patterns in HNSW index.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ routerId: { type: 'string', description: 'HNSW router ID' },
+ query: { type: 'array', description: 'Query embedding vector' },
+ k: { type: 'number', description: 'Number of nearest neighbors (default: 3)' },
+ },
+ required: ['routerId', 'query'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const router = hnswRouters.get(args.routerId as string);
+ if (!router) return { content: [{ type: 'text', text: JSON.stringify({ error: `Router not found: ${args.routerId}` }) }], isError: true };
+ const query = new Float32Array(args.query as number[]);
+ const results = router.route(query, (args.k as number) ?? 3);
+ return { content: [{ type: 'text', text: JSON.stringify({ results }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_sona_create',
+ description: 'Create a SONA instant adaptation loop (<1ms adaptation cycles).',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ hiddenDim: { type: 'number', description: 'Hidden dimension (default: 64)' },
+ learningRate: { type: 'number', description: 'Learning rate (default: 0.01)' },
+ patternCapacity: { type: 'number', description: 'Max stored patterns' },
+ },
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const sona = await mod.createSonaInstant({
+ hiddenDim: args.hiddenDim as number | undefined,
+ learningRate: args.learningRate as number | undefined,
+ patternCapacity: args.patternCapacity as number | undefined,
+ });
+ const id = `sona-${Date.now().toString(36)}`;
+ sonaInstances.set(id, sona);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, sonaId: id }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_sona_adapt',
+ description: 'Run SONA instant adaptation with a quality signal.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ sonaId: { type: 'string', description: 'SONA instance ID' },
+ quality: { type: 'number', description: 'Quality signal (0.0-1.0)' },
+ },
+ required: ['sonaId', 'quality'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const sona = sonaInstances.get(args.sonaId as string);
+ if (!sona) return { content: [{ type: 'text', text: JSON.stringify({ error: `SONA not found: ${args.sonaId}` }) }], isError: true };
+ sona.adapt(args.quality as number);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, stats: sona.stats() }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_microlora_create',
+ description: 'Create a MicroLoRA adapter (ultra-lightweight LoRA, ranks 1-4).',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ inputDim: { type: 'number', description: 'Input dimension' },
+ outputDim: { type: 'number', description: 'Output dimension' },
+ rank: { type: 'number', description: 'LoRA rank (1-4, default: 2)' },
+ alpha: { type: 'number', description: 'LoRA alpha scaling (default: 1.0)' },
+ },
+ required: ['inputDim', 'outputDim'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const lora = await mod.createMicroLora({
+ inputDim: args.inputDim as number,
+ outputDim: args.outputDim as number,
+ rank: args.rank as number | undefined,
+ alpha: args.alpha as number | undefined,
+ });
+ const id = `lora-${Date.now().toString(36)}`;
+ loraInstances.set(id, lora);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, loraId: id }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_microlora_adapt',
+ description: 'Adapt MicroLoRA weights with quality feedback.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ loraId: { type: 'string', description: 'MicroLoRA instance ID' },
+ quality: { type: 'number', description: 'Quality signal (0.0-1.0)' },
+ learningRate: { type: 'number', description: 'Learning rate (default: 0.01)' },
+ success: { type: 'boolean', description: 'Whether the adaptation was successful (default: true)' },
+ },
+ required: ['loraId', 'quality'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const lora = loraInstances.get(args.loraId as string);
+ if (!lora) return { content: [{ type: 'text', text: JSON.stringify({ error: `MicroLoRA not found: ${args.loraId}` }) }], isError: true };
+ lora.adapt(
+ args.quality as number,
+ args.learningRate as number | undefined,
+ args.success as boolean | undefined,
+ );
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, stats: lora.stats() }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_chat_format',
+ description: 'Format chat messages using a template (llama3, mistral, chatml, phi, gemma, or auto-detect).',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ messages: {
+ type: 'array',
+ description: 'Array of {role, content} message objects',
+ },
+ template: { type: 'string', description: 'Template preset (llama3, mistral, chatml, phi, gemma) or model ID for auto-detection' },
+ },
+ required: ['messages', 'template'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const messages = args.messages as ChatMessage[];
+ const templateStr = args.template as string;
+
+ const presets = ['llama3', 'mistral', 'chatml', 'phi', 'gemma'];
+ const template = presets.includes(templateStr)
+ ? templateStr as any
+ : { modelId: templateStr };
+
+ const formatted = await mod.formatChat(messages, template);
+ return { content: [{ type: 'text', text: formatted }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'ruvllm_generate_config',
+ description: 'Create a generation config (maxTokens, temperature, topP, etc.) as JSON.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ maxTokens: { type: 'number', description: 'Max tokens to generate' },
+ temperature: { type: 'number', description: 'Sampling temperature (note: f32 precision)' },
+ topP: { type: 'number', description: 'Top-p sampling' },
+ topK: { type: 'number', description: 'Top-k sampling' },
+ repetitionPenalty: { type: 'number', description: 'Repetition penalty' },
+ stopSequences: { type: 'array', description: 'Stop sequences' },
+ },
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const mod = await loadRuvllmWasm();
+ const config = await mod.createGenerateConfig(args as any);
+ return { content: [{ type: 'text', text: config }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+];
+
+// ── Instance Registries ──────────────────────────────────────
+
+const hnswRouters = new Map<string, Awaited<ReturnType<typeof import('../ruvector/ruvllm-wasm.js').createHnswRouter>>>();
+const sonaInstances = new Map<string, Awaited<ReturnType<typeof import('../ruvector/ruvllm-wasm.js').createSonaInstant>>>();
+const loraInstances = new Map<string, Awaited<ReturnType<typeof import('../ruvector/ruvllm-wasm.js').createMicroLora>>>();
diff --git a/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts
new file mode 100644
index 0000000000..5f7d5f61f9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts
@@ -0,0 +1,223 @@
+/**
+ * WASM Agent MCP Tools
+ *
+ * Exposes @ruvector/rvagent-wasm operations via MCP protocol.
+ * All tools gracefully degrade when the WASM package is not installed.
+ */
+
+import type { MCPTool } from './types.js';
+
+async function loadAgentWasm() {
+ const mod = await import('../ruvector/agent-wasm.js');
+ return mod;
+}
+
+export const wasmAgentTools: MCPTool[] = [
+ {
+ name: 'wasm_agent_create',
+ description: 'Create a sandboxed WASM agent with virtual filesystem (no OS access). Optionally use a gallery template.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ template: { type: 'string', description: 'Gallery template name (coder, researcher, tester, reviewer, security, swarm)' },
+ model: { type: 'string', description: 'Model identifier (default: anthropic:claude-sonnet-4-20250514)' },
+ instructions: { type: 'string', description: 'System instructions for the agent' },
+ maxTurns: { type: 'number', description: 'Max conversation turns (default: 50)' },
+ },
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ if (args.template) {
+ const info = await wasm.createAgentFromTemplate(args.template as string);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, agent: info, source: 'gallery' }, null, 2) }] };
+ }
+ const info = await wasm.createWasmAgent({
+ model: args.model as string,
+ instructions: args.instructions as string,
+ maxTurns: args.maxTurns as number,
+ });
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, agent: info }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_prompt',
+ description: 'Send a prompt to a WASM agent and get a response.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ agentId: { type: 'string', description: 'WASM agent ID' },
+ input: { type: 'string', description: 'User prompt to send' },
+ },
+ required: ['agentId', 'input'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const result = await wasm.promptWasmAgent(args.agentId as string, args.input as string);
+ return { content: [{ type: 'text', text: result }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_tool',
+ description: 'Execute a tool on a WASM agent sandbox. Tools: read_file, write_file, edit_file, write_todos, list_files. Use flat format: {tool, path, content, ...}.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ agentId: { type: 'string', description: 'WASM agent ID' },
+ toolName: { type: 'string', description: 'Tool name (read_file, write_file, edit_file, write_todos, list_files)' },
+ toolInput: { type: 'object', description: 'Tool parameters (flat: {path, content, old_string, new_string, todos})' },
+ },
+ required: ['agentId', 'toolName'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ // Flat format: {tool: 'write_file', path: '...', content: '...'}
+ const toolCall = {
+ tool: args.toolName as string,
+ ...((args.toolInput as Record<string, unknown>) ?? {}),
+ };
+ const result = await wasm.executeWasmTool(args.agentId as string, toolCall);
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_list',
+ description: 'List all active WASM agents.',
+ inputSchema: { type: 'object' as const, properties: {} },
+ handler: async () => {
+ try {
+ const wasm = await loadAgentWasm();
+ const agents = wasm.listWasmAgents();
+ return { content: [{ type: 'text', text: JSON.stringify({ agents, count: agents.length }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_terminate',
+ description: 'Terminate a WASM agent and free resources.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ agentId: { type: 'string', description: 'WASM agent ID' },
+ },
+ required: ['agentId'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const ok = wasm.terminateWasmAgent(args.agentId as string);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: ok }) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_files',
+ description: 'Get a WASM agent\'s available tools and info.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ agentId: { type: 'string', description: 'WASM agent ID' },
+ },
+ required: ['agentId'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const tools = wasm.getWasmAgentTools(args.agentId as string);
+ const info = wasm.getWasmAgent(args.agentId as string);
+ return { content: [{ type: 'text', text: JSON.stringify({ tools, fileCount: info?.fileCount ?? 0, turnCount: info?.turnCount ?? 0 }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_agent_export',
+ description: 'Export a WASM agent\'s full state (config, filesystem, conversation) as JSON.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ agentId: { type: 'string', description: 'WASM agent ID' },
+ },
+ required: ['agentId'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const state = wasm.exportWasmState(args.agentId as string);
+ return { content: [{ type: 'text', text: state }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_gallery_list',
+ description: 'List all available WASM agent gallery templates (Coder, Researcher, Tester, Reviewer, Security, Swarm).',
+ inputSchema: { type: 'object' as const, properties: {} },
+ handler: async () => {
+ try {
+ const wasm = await loadAgentWasm();
+ const templates = await wasm.listGalleryTemplates();
+ return { content: [{ type: 'text', text: JSON.stringify({ templates, count: templates.length }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_gallery_search',
+ description: 'Search WASM agent gallery templates by query.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ query: { type: 'string', description: 'Search query' },
+ },
+ required: ['query'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const results = await wasm.searchGalleryTemplates(args.query as string);
+ return { content: [{ type: 'text', text: JSON.stringify({ results, count: results.length }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+ {
+ name: 'wasm_gallery_create',
+ description: 'Create a WASM agent from a gallery template.',
+ inputSchema: {
+ type: 'object' as const,
+ properties: {
+ template: { type: 'string', description: 'Template name (coder, researcher, tester, reviewer, security, swarm)' },
+ },
+ required: ['template'],
+ },
+ handler: async (args: Record<string, unknown>) => {
+ try {
+ const wasm = await loadAgentWasm();
+ const info = await wasm.createAgentFromTemplate(args.template as string);
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, agent: info, template: args.template }, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: JSON.stringify({ error: String(err) }) }], isError: true };
+ }
+ },
+ },
+];
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index 38f98f3627..d13713f9b1 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -1585,6 +1585,44 @@ export async function loadEmbeddingModel(options?: {
};
}
+ // Fallback: Check for ruvector ONNX embedder (bundled MiniLM-L6-v2 since v0.2.15)
+ // v0.2.16: LoRA B=0 fix makes AdaptiveEmbedder safe (identity when untrained)
+ // Note: isReady() returns false until first embed() call (lazy init), so we
+ // skip the isReady() gate and verify with a probe embed instead.
+ const ruvector = await import('ruvector').catch(() => null);
+
+ if (ruvector?.initOnnxEmbedder) {
+ try {
+ await ruvector.initOnnxEmbedder();
+
+ // Fallback: OptimizedOnnxEmbedder (raw ONNX, lazy-inits on first embed)
+ const onnxEmb = ruvector.getOptimizedOnnxEmbedder?.();
+ if (onnxEmb?.embed) {
+ // Probe embed to trigger lazy ONNX init and verify it works
+ const probe = await onnxEmb.embed('test');
+ if (probe && probe.length > 0 && (Array.isArray(probe) ? probe.some((v: number) => v !== 0) : true)) {
+ if (verbose) {
+ console.log(`Loading ruvector ONNX embedder (all-MiniLM-L6-v2, ${probe.length}d)...`);
+ }
+ embeddingModelState = {
+ loaded: true,
+ model: (text: string) => onnxEmb.embed(text),
+ tokenizer: null,
+ dimensions: probe.length || 384
+ };
+ return {
+ success: true,
+ dimensions: probe.length || 384,
+ modelName: 'ruvector/onnx',
+ loadTime: Date.now() - startTime
+ };
+ }
+ }
+ } catch {
+ // ruvector ONNX init failed, continue to next fallback
+ }
+ }
+
// Legacy fallback: Check for agentic-flow core embeddings
const agenticFlow = await import('agentic-flow').catch(() => null);
@@ -1659,12 +1697,17 @@ export async function generateEmbedding(text: string): Promise<{
if (state.model && typeof (state.model as any) === 'function') {
try {
const output = await (state.model as any)(text, { pooling: 'mean', normalize: true });
- const embedding = Array.from(output.data as Float32Array);
- return {
- embedding,
- dimensions: embedding.length,
- model: 'onnx'
- };
+ // Handle both @xenova/transformers (output.data) and ruvector (plain array) formats
+ const embedding = output?.data
+ ? Array.from(output.data as Float32Array)
+ : Array.isArray(output) ? output : null;
+ if (embedding) {
+ return {
+ embedding,
+ dimensions: embedding.length,
+ model: 'onnx'
+ };
+ }
} catch {
// Fall through to fallback
}
diff --git a/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts b/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts
new file mode 100644
index 0000000000..1e8e12be20
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts
@@ -0,0 +1,387 @@
+/**
+ * RuVector Agent WASM Integration
+ *
+ * Wraps @ruvector/rvagent-wasm for sandboxed AI agent execution.
+ * Provides WasmAgent lifecycle, gallery templates, RVF container building,
+ * and MCP server bridge β€” all running in WASM without OS access.
+ *
+ * Published API (v0.1.0): WasmAgent, WasmGallery, WasmMcpServer,
+ * WasmRvfBuilder, JsModelProvider, initSync.
+ *
+ * @module @claude-flow/cli/ruvector/agent-wasm
+ */
+
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+
+// ── Types ────────────────────────────────────────────────────
+
+export interface WasmAgentConfig {
+ model?: string;
+ instructions?: string;
+ maxTurns?: number;
+}
+
+export interface WasmAgentInfo {
+ id: string;
+ state: 'idle' | 'running' | 'error';
+ config: WasmAgentConfig;
+ model: string;
+ turnCount: number;
+ fileCount: number;
+ isStopped: boolean;
+ createdAt: string;
+}
+
+export interface GalleryTemplate {
+ id: string;
+ name: string;
+ description: string;
+ category: string;
+ tags: string[];
+ version: string;
+ author: string;
+ builtin: boolean;
+}
+
+export interface GalleryTemplateDetail extends GalleryTemplate {
+ tools: Array<{ name: string; description: string; parameters: unknown[]; returns: string }>;
+ prompts: Array<{ name: string; system_prompt: string; version: string }>;
+ skills: Array<{ name: string; description: string; trigger: string; content: string }>;
+ mcp_tools: Array<{ name: string; description: string; input_schema: unknown; group: string }>;
+ capabilities: Array<{ name: string; rights: string[]; scope: string; delegation_depth: number }>;
+}
+
+export interface ToolResult {
+ success: boolean;
+ output: string;
+}
+
+// ── WASM Module Detection & Init ─────────────────────────────
+
+let _wasmReady = false;
+
+/**
+ * Check if @ruvector/rvagent-wasm is installed and loadable.
+ */
+export async function isAgentWasmAvailable(): Promise<boolean> {
+ try {
+ const mod = await import('@ruvector/rvagent-wasm');
+ return typeof mod.WasmAgent === 'function';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Initialize the WASM module for Node.js. Safe to call multiple times.
+ * Uses initSync with file-loaded WASM bytes (browser fetch doesn't work in Node).
+ */
+export async function initAgentWasm(): Promise<void> {
+ if (_wasmReady) return;
+ try {
+ const mod = await import('@ruvector/rvagent-wasm');
+ // In Node.js, load WASM bytes from disk and use initSync
+ const require_ = createRequire(import.meta.url);
+ const wasmPath = require_.resolve('@ruvector/rvagent-wasm/rvagent_wasm_bg.wasm');
+ const wasmBytes = readFileSync(wasmPath);
+ mod.initSync(wasmBytes);
+ _wasmReady = true;
+ } catch (err) {
+ throw new Error(`Failed to initialize @ruvector/rvagent-wasm: ${err}`);
+ }
+}
+
+// ── Agent Registry ───────────────────────────────────────────
+
+const agents = new Map<string, { agent: any; info: WasmAgentInfo }>();
+let nextId = 1;
+
+function generateId(): string {
+ return `wasm-agent-${nextId++}-${Date.now().toString(36)}`;
+}
+
+// ── Agent Lifecycle ──────────────────────────────────────────
+
+/**
+ * Create a new sandboxed WASM agent.
+ */
+export async function createWasmAgent(config: WasmAgentConfig = {}): Promise<WasmAgentInfo> {
+ await initAgentWasm();
+ const mod = await import('@ruvector/rvagent-wasm');
+
+ const configJson = JSON.stringify({
+ model: config.model ?? 'anthropic:claude-sonnet-4-20250514',
+ instructions: config.instructions ?? 'You are a helpful coding assistant.',
+ max_turns: config.maxTurns ?? 50,
+ });
+
+ const agent = new mod.WasmAgent(configJson);
+ const id = generateId();
+
+ const info: WasmAgentInfo = {
+ id,
+ state: 'idle',
+ config,
+ model: agent.model(),
+ turnCount: agent.turn_count(),
+ fileCount: agent.file_count(),
+ isStopped: agent.is_stopped(),
+ createdAt: new Date().toISOString(),
+ };
+
+ agents.set(id, { agent, info });
+ return info;
+}
+
+/**
+ * Send a prompt to a WASM agent. Requires a model provider to be set.
+ */
+export async function promptWasmAgent(agentId: string, input: string): Promise<string> {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+
+ entry.info.state = 'running';
+ try {
+ const result = await entry.agent.prompt(input);
+ entry.info.state = 'idle';
+ syncAgentInfo(entry);
+ return result;
+ } catch (err) {
+ entry.info.state = 'error';
+ throw err;
+ }
+}
+
+/**
+ * Execute a tool directly on a WASM agent's sandbox.
+ * Tool format: {tool: 'write_file', path: '...', content: '...'} (flat, snake_case).
+ * Available tools: read_file, write_file, edit_file, write_todos, list_files.
+ */
+const VALID_WASM_TOOLS = ['read_file', 'write_file', 'edit_file', 'write_todos', 'list_files'];
+
+export async function executeWasmTool(agentId: string, toolCall: Record<string, unknown>): Promise<ToolResult> {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+ // Validate tool name to prevent WASM panics on unknown tools
+ const toolName = toolCall.tool as string;
+ if (toolName && !VALID_WASM_TOOLS.includes(toolName)) {
+ return { success: false, output: `Unknown tool: ${toolName}. Available: ${VALID_WASM_TOOLS.join(', ')}` };
+ }
+ const result = await entry.agent.execute_tool(JSON.stringify(toolCall));
+ syncAgentInfo(entry);
+ return result as ToolResult;
+}
+
+function syncAgentInfo(entry: { agent: any; info: WasmAgentInfo }): void {
+ try {
+ entry.info.turnCount = entry.agent.turn_count();
+ entry.info.fileCount = entry.agent.file_count();
+ entry.info.isStopped = entry.agent.is_stopped();
+ } catch { /* best-effort */ }
+}
+
+/**
+ * Get agent info.
+ */
+export function getWasmAgent(agentId: string): WasmAgentInfo | null {
+ const entry = agents.get(agentId);
+ if (!entry) return null;
+ syncAgentInfo(entry);
+ return entry.info;
+}
+
+/**
+ * List all active WASM agents.
+ */
+export function listWasmAgents(): WasmAgentInfo[] {
+ return Array.from(agents.values()).map(e => {
+ syncAgentInfo(e);
+ return e.info;
+ });
+}
+
+/**
+ * Terminate a WASM agent and free resources.
+ */
+export function terminateWasmAgent(agentId: string): boolean {
+ const entry = agents.get(agentId);
+ if (!entry) return false;
+ try { entry.agent.free(); } catch { /* already freed */ }
+ agents.delete(agentId);
+ return true;
+}
+
+/**
+ * Get agent state (messages, turn count, etc.)
+ */
+export function getWasmAgentState(agentId: string): unknown {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+ return entry.agent.get_state();
+}
+
+/**
+ * Get agent tools list.
+ */
+export function getWasmAgentTools(agentId: string): string[] {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+ return entry.agent.get_tools();
+}
+
+/**
+ * Get agent todos.
+ */
+export function getWasmAgentTodos(agentId: string): unknown[] {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+ return entry.agent.get_todos();
+}
+
+/**
+ * Export the full agent state as JSON (for persistence).
+ */
+export function exportWasmState(agentId: string): string {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+ return JSON.stringify({
+ agentState: entry.agent.get_state(),
+ tools: entry.agent.get_tools(),
+ todos: entry.agent.get_todos(),
+ info: entry.info,
+ });
+}
+
+// ── MCP Server Bridge ────────────────────────────────────────
+
+/**
+ * Create a WASM-based MCP server for an agent.
+ * Returns a handler function for JSON-RPC requests.
+ *
+ * Note: WasmMcpServer may have stability issues in v0.1.0 for
+ * certain agent configurations. Use with a fully configured agent.
+ */
+export async function createWasmMcpServer(agentId: string): Promise<(jsonRpc: string) => Promise<string>> {
+ const entry = agents.get(agentId);
+ if (!entry) throw new Error(`WASM agent not found: ${agentId}`);
+
+ const mod = await import('@ruvector/rvagent-wasm');
+ const server = new mod.WasmMcpServer(entry.agent);
+
+ return (jsonRpc: string) => server.handle_request(jsonRpc);
+}
+
+// ── Gallery Templates ────────────────────────────────────────
+
+let _gallery: any | null = null;
+
+async function getGallery(): Promise<any> {
+ if (_gallery) return _gallery;
+ await initAgentWasm();
+ const mod = await import('@ruvector/rvagent-wasm');
+ _gallery = new mod.WasmGallery();
+ return _gallery;
+}
+
+/**
+ * List all available gallery templates.
+ * Returns objects directly (Gallery.list() returns parsed objects in v0.1.0).
+ */
+export async function listGalleryTemplates(): Promise<GalleryTemplate[]> {
+ const gallery = await getGallery();
+ return gallery.list();
+}
+
+/**
+ * Get gallery template count.
+ */
+export async function getGalleryCount(): Promise<number> {
+ const gallery = await getGallery();
+ return gallery.count();
+}
+
+/**
+ * Get gallery categories with counts.
+ */
+export async function getGalleryCategories(): Promise<Record<string, number>> {
+ const gallery = await getGallery();
+ return gallery.getCategories();
+}
+
+/**
+ * Search gallery templates by query. Returns results with relevance scores.
+ */
+export async function searchGalleryTemplates(query: string): Promise<Array<GalleryTemplate & { relevance: number }>> {
+ const gallery = await getGallery();
+ return gallery.search(query);
+}
+
+/**
+ * Get a gallery template by id.
+ * Wraps in try/catch because WasmGallery.get() panics on unknown IDs in v0.1.0.
+ */
+export async function getGalleryTemplate(id: string): Promise<GalleryTemplateDetail | null> {
+ const gallery = await getGallery();
+ try {
+ return gallery.get(id) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Create an agent from a gallery template.
+ */
+export async function createAgentFromTemplate(templateId: string): Promise<WasmAgentInfo> {
+ const template = await getGalleryTemplate(templateId);
+ if (!template) throw new Error(`Gallery template not found: ${templateId}`);
+
+ const systemPrompt = template.prompts?.[0]?.system_prompt;
+ return createWasmAgent({
+ instructions: systemPrompt ?? `You are a ${template.name}.`,
+ model: undefined, // Use default
+ });
+}
+
+// ── RVF Container Operations ─────────────────────────────────
+
+/**
+ * Build an RVF container with prompts, tools, and skills.
+ * Uses the high-level RVF builder API (addPrompt, addTool, addSkill).
+ */
+export async function buildRvfContainer(opts: {
+ prompts?: Array<{ name: string; system_prompt: string; version: string }>;
+ tools?: Array<{ name: string; description: string; parameters: unknown[]; returns: string }>;
+ skills?: Array<{ name: string; description: string; trigger: string; content: string }>;
+}): Promise<Uint8Array> {
+ await initAgentWasm();
+ const mod = await import('@ruvector/rvagent-wasm');
+ const builder = new mod.WasmRvfBuilder();
+
+ for (const p of opts.prompts ?? []) {
+ builder.addPrompt(JSON.stringify(p));
+ }
+ for (const t of opts.tools ?? []) {
+ builder.addTool(JSON.stringify(t));
+ }
+ for (const s of opts.skills ?? []) {
+ builder.addSkill(JSON.stringify(s));
+ }
+
+ return builder.build();
+}
+
+/**
+ * Build an RVF container from a gallery template.
+ */
+export async function buildRvfFromTemplate(templateId: string): Promise<Uint8Array> {
+ const template = await getGalleryTemplate(templateId);
+ if (!template) throw new Error(`Gallery template not found: ${templateId}`);
+
+ return buildRvfContainer({
+ prompts: template.prompts,
+ tools: template.tools,
+ skills: template.skills,
+ });
+}
diff --git a/v3/@claude-flow/cli/src/ruvector/index.ts b/v3/@claude-flow/cli/src/ruvector/index.ts
index 77ae23e995..beaf9fcab5 100644
--- a/v3/@claude-flow/cli/src/ruvector/index.ts
+++ b/v3/@claude-flow/cli/src/ruvector/index.ts
@@ -153,6 +153,60 @@ export {
type RouterConfig,
} from './semantic-router.js';
+// ── RuVector LLM WASM (inference utilities) ─────────────────
+export {
+ isRuvllmWasmAvailable,
+ initRuvllmWasm,
+ getRuvllmStatus,
+ createHnswRouter,
+ createSonaInstant,
+ createMicroLora,
+ formatChat,
+ createKvCache,
+ createGenerateConfig,
+ createBufferPool,
+ createInferenceArena,
+ HNSW_MAX_SAFE_PATTERNS,
+ type HnswRouterConfig,
+ type HnswPattern,
+ type HnswRouteResult,
+ type SonaConfig,
+ type MicroLoraConfig,
+ type ChatMessage,
+ type GenerateOptions,
+ type RuvllmStatus,
+} from './ruvllm-wasm.js';
+
+// ── Agent WASM (sandboxed agent runtime) ────────────────────
+export {
+ isAgentWasmAvailable,
+ initAgentWasm,
+ createWasmAgent,
+ promptWasmAgent,
+ executeWasmTool,
+ getWasmAgent,
+ listWasmAgents,
+ terminateWasmAgent,
+ getWasmAgentState,
+ getWasmAgentTools,
+ getWasmAgentTodos,
+ exportWasmState,
+ createWasmMcpServer,
+ listGalleryTemplates,
+ getGalleryCount,
+ getGalleryCategories,
+ searchGalleryTemplates,
+ getGalleryTemplate,
+ createAgentFromTemplate,
+ buildRvfContainer,
+ buildRvfFromTemplate,
+ type WasmAgentConfig,
+ type WasmAgentInfo,
+ type GalleryTemplate,
+ type GalleryTemplateDetail,
+ type ToolResult,
+} from './agent-wasm.js';
+
/**
* Check if ruvector packages are available
*/
diff --git a/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts b/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts
new file mode 100644
index 0000000000..cd0d45039a
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts
@@ -0,0 +1,480 @@
+/**
+ * RuVector LLM WASM Integration
+ *
+ * Wraps @ruvector/ruvllm-wasm for browser-native LLM inference utilities.
+ * Provides HNSW routing, SONA instant adaptation, MicroLoRA fine-tuning,
+ * chat template formatting, KV cache management, and inference arena.
+ *
+ * Published API (v2.0.2): RuvLLMWasm, ChatTemplateWasm, ChatMessageWasm,
+ * GenerateConfig, HnswRouterWasm, SonaInstantWasm, MicroLoraWasm,
+ * KvCacheWasm, BufferPoolWasm, InferenceArenaWasm.
+ *
+ * v2.0.2 fixes:
+ * - HNSW supports 1000+ patterns (fixed connect_node ordering)
+ * - MicroLoRA adapt() now takes (input: Float32Array, feedback: AdaptFeedbackWasm)
+ *
+ * Remaining quirks:
+ * - Stats objects return WASM pointers β€” use .toJson() or named accessors
+ * - GenerateConfig float precision loss (f32 roundtrip)
+ * - MicroLoRA apply() hardcoded to 768 dims regardless of config
+ *
+ * @module @claude-flow/cli/ruvector/ruvllm-wasm
+ */
+
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+
+// ── Types ────────────────────────────────────────────────────
+
+export interface HnswRouterConfig {
+ dimensions: number;
+ maxPatterns: number;
+ efSearch?: number;
+}
+
+export interface HnswPattern {
+ name: string;
+ embedding: Float32Array;
+ metadata?: Record<string, unknown>;
+}
+
+export interface HnswRouteResult {
+ name: string;
+ score: number;
+ metadata?: Record<string, unknown>;
+}
+
+export interface SonaConfig {
+ hiddenDim?: number;
+ learningRate?: number;
+ emaDecay?: number;
+ ewcLambda?: number;
+ microLoraRank?: number;
+ patternCapacity?: number;
+}
+
+export interface MicroLoraConfig {
+ inputDim: number;
+ outputDim: number;
+ rank?: number;
+ alpha?: number;
+}
+
+export interface ChatMessage {
+ role: 'system' | 'user' | 'assistant';
+ content: string;
+}
+
+export interface GenerateOptions {
+ maxTokens?: number;
+ temperature?: number;
+ topP?: number;
+ topK?: number;
+ repetitionPenalty?: number;
+ stopSequences?: string[];
+}
+
+export interface RuvllmStatus {
+ available: boolean;
+ initialized: boolean;
+ version: string | null;
+}
+
+// ── WASM Module Detection & Init ─────────────────────────────
+
+let _wasmReady = false;
+
+/**
+ * Check if @ruvector/ruvllm-wasm is installed and loadable.
+ */
+export async function isRuvllmWasmAvailable(): Promise<boolean> {
+ try {
+ const mod = await import('@ruvector/ruvllm-wasm');
+ return typeof mod.RuvLLMWasm === 'function';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Initialize the WASM module for Node.js. Safe to call multiple times.
+ * Uses initSync with object form: { module: bytes } (raw bytes deprecated).
+ */
+export async function initRuvllmWasm(): Promise<void> {
+ if (_wasmReady) return;
+ try {
+ const mod = await import('@ruvector/ruvllm-wasm');
+ const require_ = createRequire(import.meta.url);
+ const wasmPath = require_.resolve('@ruvector/ruvllm-wasm/ruvllm_wasm_bg.wasm');
+ const wasmBytes = readFileSync(wasmPath);
+ // MUST use object form β€” initSync(bytes) is deprecated
+ mod.initSync({ module: wasmBytes });
+ _wasmReady = true;
+ } catch (err) {
+ throw new Error(`Failed to initialize @ruvector/ruvllm-wasm: ${err}`);
+ }
+}
+
+/**
+ * Get ruvllm-wasm status.
+ */
+export async function getRuvllmStatus(): Promise<RuvllmStatus> {
+ const available = await isRuvllmWasmAvailable();
+ if (!available) {
+ return { available: false, initialized: false, version: null };
+ }
+ try {
+ const mod = await import('@ruvector/ruvllm-wasm');
+ // version is a standalone function, not on RuvLLMWasm class
+ const version = typeof mod.getVersion === 'function' ? mod.getVersion() : null;
+ return { available: true, initialized: _wasmReady, version };
+ } catch {
+ return { available: true, initialized: _wasmReady, version: null };
+ }
+}
+
+// ── HNSW Router ──────────────────────────────────────────────
+
+/**
+ * Maximum safe pattern count for HNSW router.
+ * v2.0.2 supports 1000+ patterns (fixed connect_node ordering).
+ */
+export const HNSW_MAX_SAFE_PATTERNS = 1024;
+
+/**
+ * Create a WASM HNSW router for semantic routing.
+ * Returns an object with add/route/clear methods.
+ *
+ * Enforces HNSW_MAX_SAFE_PATTERNS limit (1024 in v2.0.2).
+ */
+export async function createHnswRouter(config: HnswRouterConfig): Promise<{
+ addPattern: (pattern: HnswPattern) => boolean;
+ route: (query: Float32Array, k?: number) => HnswRouteResult[];
+ clear: () => void;
+ patternCount: () => number;
+ toJson: () => string;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const router = new mod.HnswRouterWasm(config.dimensions, config.maxPatterns);
+ if (config.efSearch) {
+ router.setEfSearch(config.efSearch);
+ }
+
+ let count = 0;
+
+ return {
+ addPattern(pattern: HnswPattern): boolean {
+ if (count >= HNSW_MAX_SAFE_PATTERNS) {
+ throw new Error(
+ `HNSW pattern limit reached (${HNSW_MAX_SAFE_PATTERNS}).`
+ );
+ }
+ const metadataJson = JSON.stringify(pattern.metadata ?? {});
+ // addPattern requires 3 args: (embedding, name, metadata_json)
+ const ok = router.addPattern(pattern.embedding, pattern.name, metadataJson);
+ if (ok) count++;
+ return ok;
+ },
+ route(query: Float32Array, k = 3): HnswRouteResult[] {
+ return router.route(query, k);
+ },
+ clear(): void {
+ router.clear();
+ count = 0;
+ },
+ patternCount(): number {
+ return count;
+ },
+ toJson(): string {
+ return router.toJson();
+ },
+ };
+}
+
+// ── SONA Instant Adaptation ──────────────────────────────────
+
+/**
+ * Create a SONA instant adaptation loop (<1ms adaptation).
+ * v2.0.1: requires SonaConfigWasm object, not raw number.
+ */
+export async function createSonaInstant(config: SonaConfig = {}): Promise<{
+ adapt: (quality: number) => void;
+ recordPattern: (embedding: number[], success: boolean) => void;
+ suggestAction: (context: string) => string | undefined;
+ stats: () => string;
+ reset: () => void;
+ toJson: () => string;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const sonaConfig = new mod.SonaConfigWasm();
+ if (config.hiddenDim !== undefined) sonaConfig.hiddenDim = config.hiddenDim;
+ if (config.learningRate !== undefined) sonaConfig.learningRate = config.learningRate;
+ if (config.emaDecay !== undefined) sonaConfig.emaDecay = config.emaDecay;
+ if (config.ewcLambda !== undefined) sonaConfig.ewcLambda = config.ewcLambda;
+ if (config.microLoraRank !== undefined) sonaConfig.microLoraRank = config.microLoraRank;
+ if (config.patternCapacity !== undefined) sonaConfig.patternCapacity = config.patternCapacity;
+
+ const sona = new mod.SonaInstantWasm(sonaConfig);
+
+ return {
+ adapt(quality: number): void {
+ sona.instantAdapt(quality);
+ },
+ recordPattern(embedding: number[], success: boolean): void {
+ sona.recordPattern(embedding, success);
+ },
+ suggestAction(context: string): string | undefined {
+ return sona.suggestAction(context);
+ },
+ stats(): string {
+ return sona.toJson();
+ },
+ reset(): void {
+ sona.reset();
+ },
+ toJson(): string {
+ return sona.toJson();
+ },
+ };
+}
+
+// ── MicroLoRA ────────────────────────────────────────────────
+
+/**
+ * Create a MicroLoRA adapter (ultra-lightweight LoRA, ranks 1-4).
+ * v2.0.2: .adapt(input, feedback) takes Float32Array + AdaptFeedbackWasm.
+ */
+export async function createMicroLora(config: MicroLoraConfig): Promise<{
+ apply: (input: Float32Array) => Float32Array;
+ adapt: (quality: number, learningRate?: number, success?: boolean) => void;
+ applyUpdates: (gradients: Float32Array) => void;
+ stats: () => string;
+ reset: () => void;
+ toJson: () => string;
+ pendingUpdates: () => number;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const loraConfig = new mod.MicroLoraConfigWasm();
+ loraConfig.inputDim = config.inputDim;
+ loraConfig.outputDim = config.outputDim;
+ loraConfig.rank = config.rank ?? 2;
+ loraConfig.alpha = config.alpha ?? 1.0;
+
+ const lora = new mod.MicroLoraWasm(loraConfig);
+
+ return {
+ apply(input: Float32Array): Float32Array {
+ return lora.apply(input);
+ },
+ adapt(quality: number, learningRate = 0.01, success = true): void {
+ // v2.0.2: adapt(input, feedback) β€” two args
+ const feedback = new mod.AdaptFeedbackWasm();
+ feedback.quality = quality;
+ feedback.learningRate = learningRate;
+ // Note: feedback.success not on prototype in v2.0.2, set via property
+ try { (feedback as any).success = success; } catch { /* v2.0.2 quirk */ }
+ // Create a dummy input vector matching the configured inputDim
+ const input = new Float32Array(config.inputDim);
+ lora.adapt(input, feedback);
+ },
+ applyUpdates(gradients: Float32Array): void {
+ lora.applyUpdates(gradients);
+ },
+ stats(): string {
+ return lora.toJson();
+ },
+ reset(): void {
+ lora.reset();
+ },
+ toJson(): string {
+ return lora.toJson();
+ },
+ pendingUpdates(): number {
+ return lora.pendingUpdates();
+ },
+ };
+}
+
+// ── Chat Template Formatting ─────────────────────────────────
+
+type TemplatePreset = 'llama3' | 'mistral' | 'chatml' | 'phi' | 'gemma';
+
+/**
+ * Format chat messages using a chat template.
+ * Supports presets (llama3, mistral, chatml, phi, gemma) and auto-detection.
+ */
+export async function formatChat(
+ messages: ChatMessage[],
+ template: TemplatePreset | { custom: string } | { modelId: string },
+): Promise<string> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ // Build template
+ let tmpl: any;
+ if (typeof template === 'string') {
+ const presets: Record<string, () => any> = {
+ llama3: () => mod.ChatTemplateWasm.llama3(),
+ mistral: () => mod.ChatTemplateWasm.mistral(),
+ chatml: () => mod.ChatTemplateWasm.chatml(),
+ phi: () => mod.ChatTemplateWasm.phi(),
+ gemma: () => mod.ChatTemplateWasm.gemma(),
+ };
+ const factory = presets[template];
+ if (!factory) throw new Error(`Unknown template preset: ${template}. Use: ${Object.keys(presets).join(', ')}`);
+ tmpl = factory();
+ } else if ('custom' in template) {
+ tmpl = mod.ChatTemplateWasm.custom(template.custom);
+ } else if ('modelId' in template) {
+ tmpl = mod.ChatTemplateWasm.detectFromModelId(template.modelId);
+ }
+
+ // Build messages
+ const wasmMessages = messages.map(m => {
+ switch (m.role) {
+ case 'system': return mod.ChatMessageWasm.system(m.content);
+ case 'user': return mod.ChatMessageWasm.user(m.content);
+ case 'assistant': return mod.ChatMessageWasm.assistant(m.content);
+ default: throw new Error(`Unknown role: ${m.role}`);
+ }
+ });
+
+ return tmpl.format(wasmMessages);
+}
+
+// ── KV Cache ─────────────────────────────────────────────────
+
+/**
+ * Create a KV cache for token management.
+ */
+export async function createKvCache(opts?: {
+ tailLength?: number;
+ maxTokens?: number;
+ numKvHeads?: number;
+ headDim?: number;
+}): Promise<{
+ append: (keys: Float32Array, values: Float32Array) => void;
+ stats: () => string;
+ clear: () => void;
+ tokenCount: () => number;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ let cache: any;
+ if (opts) {
+ const config = new mod.KvCacheConfigWasm();
+ if (opts.tailLength !== undefined) config.tailLength = opts.tailLength;
+ if (opts.maxTokens !== undefined) config.maxTokens = opts.maxTokens;
+ if (opts.numKvHeads !== undefined) config.numKvHeads = opts.numKvHeads;
+ if (opts.headDim !== undefined) config.headDim = opts.headDim;
+ cache = new mod.KvCacheWasm(config);
+ } else {
+ cache = mod.KvCacheWasm.withDefaults();
+ }
+
+ return {
+ append(keys: Float32Array, values: Float32Array): void {
+ cache.append(keys, values);
+ },
+ stats(): string {
+ // Use toJson if available, otherwise stringify
+ try { return JSON.stringify(cache.stats()); } catch { return '{}'; }
+ },
+ clear(): void {
+ cache.clear();
+ },
+ tokenCount(): number {
+ return cache.tokenCount;
+ },
+ };
+}
+
+// ── Generate Config ──────────────────────────────────────────
+
+/**
+ * Create a generation config object.
+ * Note: f32 precision loss is expected (0.7 β†’ 0.699999...).
+ */
+export async function createGenerateConfig(opts: GenerateOptions = {}): Promise<string> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const config = new mod.GenerateConfig();
+ if (opts.maxTokens !== undefined) config.maxTokens = opts.maxTokens;
+ if (opts.temperature !== undefined) config.temperature = opts.temperature;
+ if (opts.topP !== undefined) config.topP = opts.topP;
+ if (opts.topK !== undefined) config.topK = opts.topK;
+ if (opts.repetitionPenalty !== undefined) config.repetitionPenalty = opts.repetitionPenalty;
+ for (const seq of opts.stopSequences ?? []) {
+ config.addStopSequence(seq);
+ }
+
+ return config.toJson();
+}
+
+// ── Buffer Pool ──────────────────────────────────────────────
+
+/**
+ * Create a buffer pool for inference memory management.
+ */
+export async function createBufferPool(capacity: number): Promise<{
+ prewarm: (count: number) => void;
+ stats: () => string;
+ hitRate: () => number;
+ clear: () => void;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const pool = mod.BufferPoolWasm.withCapacity(capacity);
+
+ return {
+ prewarm(count: number): void {
+ pool.prewarmAll(count);
+ },
+ stats(): string {
+ return pool.statsJson();
+ },
+ hitRate(): number {
+ return pool.hitRate;
+ },
+ clear(): void {
+ pool.clear();
+ },
+ };
+}
+
+// ── Inference Arena ──────────────────────────────────────────
+
+/**
+ * Create an inference arena for model memory allocation.
+ */
+export async function createInferenceArena(
+ opts: { capacity: number } | { hiddenDim: number; vocabSize: number; batchSize: number },
+): Promise<{
+ reset: () => void;
+ used: () => number;
+ capacity: () => number;
+ remaining: () => number;
+}> {
+ await initRuvllmWasm();
+ const mod = await import('@ruvector/ruvllm-wasm');
+
+ const arena = 'capacity' in opts
+ ? new mod.InferenceArenaWasm(opts.capacity)
+ : mod.InferenceArenaWasm.forModel(opts.hiddenDim, opts.vocabSize, opts.batchSize);
+
+ return {
+ reset(): void { arena.reset(); },
+ used(): number { return arena.used; },
+ capacity(): number { return arena.capacity; },
+ remaining(): number { return arena.remaining; },
+ };
+}
diff --git a/v3/@claude-flow/cli/src/types/optional-modules.d.ts b/v3/@claude-flow/cli/src/types/optional-modules.d.ts
index 0b4f565e9c..5449d3e87a 100644
--- a/v3/@claude-flow/cli/src/types/optional-modules.d.ts
+++ b/v3/@claude-flow/cli/src/types/optional-modules.d.ts
@@ -114,6 +114,30 @@ declare module 'ruvector' {
export const VectorDB: any;
export const VectorDb: any;
export function isWasm(): boolean;
+
+ // ONNX Embedder (ruvector >= 0.2.15, bundled MiniLM-L6-v2)
+ export function initOnnxEmbedder(): Promise<void>;
+ export function isOnnxAvailable(): boolean;
+ export function getOptimizedOnnxEmbedder(): OptimizedOnnxEmbedder | null;
+
+ export interface OptimizedOnnxEmbedder {
+ embed(text: string): Promise<number[]>;
+ embedBatch(texts: string[]): Promise<number[][]>;
+ isReady(): boolean;
+ getDimension(): number;
+ similarity(a: number[], b: number[]): number;
+ }
+
+ // AdaptiveEmbedder (ruvector >= 0.2.16, LoRA B=0 fix β€” identity when untrained)
+ export class AdaptiveEmbedder {
+ constructor(options?: { useEpisodic?: boolean });
+ embed(text: string): Promise<number[]>;
+ embedBatch(texts: string[]): Promise<number[][]>;
+ isReady(): boolean;
+ getDimension(): number;
+ similarity(a: number[], b: number[]): number;
+ adapt(quality: number): void;
+ }
}
declare module '@ruvector/core' {
@@ -121,6 +145,231 @@ declare module '@ruvector/core' {
export default core;
}
+declare module '@ruvector/rvagent-wasm' {
+ /** Initialize the WASM module (browser β€” uses fetch for .wasm file). */
+ export default function init(): Promise<void>;
+
+ /** Initialize the WASM module synchronously (Node.js β€” pass bytes from fs). */
+ export function initSync(bytes: BufferSource): void;
+
+ /** Browser/Node sandboxed AI agent with virtual filesystem. */
+ export class WasmAgent {
+ constructor(config_json: string);
+ prompt(input: string): Promise<string>;
+ set_model_provider(callback: Function): void;
+ reset(): void;
+ free(): void;
+ get_state(): unknown;
+ get_todos(): unknown[];
+ get_tools(): string[];
+ execute_tool(tool_json: string): Promise<{ success: boolean; output: string }>;
+ model(): string;
+ name(): string | undefined;
+ turn_count(): number;
+ file_count(): number;
+ is_stopped(): boolean;
+ }
+
+ /** JavaScript model provider callback wrapper. */
+ export class JsModelProvider {
+ constructor(callback: Function);
+ }
+
+ /** JSON-RPC 2.0 MCP server in WASM. */
+ export class WasmMcpServer {
+ constructor(agent: WasmAgent);
+ handle_request(json_rpc: string): Promise<string>;
+ free(): void;
+ }
+
+ /** Pre-built agent template gallery (6 templates). */
+ export class WasmGallery {
+ constructor();
+ list(): Array<{
+ id: string; name: string; description: string;
+ category: string; tags: string[]; version: string;
+ author: string; builtin: boolean;
+ }>;
+ get(id: string): unknown | undefined;
+ search(query: string): Array<{
+ id: string; name: string; description: string;
+ category: string; tags: string[]; relevance: number;
+ }>;
+ count(): number;
+ getCategories(): Record<string, number>;
+ listByCategory(category: string): unknown[];
+ addCustom(json: string): boolean;
+ removeCustom(id: string): boolean;
+ exportCustom(): string;
+ importCustom(json: string): boolean;
+ configure(json: string): boolean;
+ getConfig(): unknown;
+ setActive(id: string): boolean;
+ getActive(): unknown | undefined;
+ loadRvf(data: Uint8Array): boolean;
+ free(): void;
+ }
+
+ /** RVF binary container builder. */
+ export class WasmRvfBuilder {
+ constructor();
+ addPrompt(json: string): void;
+ addPrompts(json: string): void;
+ addTool(json: string): void;
+ addTools(json: string): void;
+ addSkill(json: string): void;
+ addSkills(json: string): void;
+ addCapabilities(json: string): void;
+ addMcpTools(json: string): void;
+ setOrchestrator(json: string): void;
+ build(): Uint8Array;
+ free(): void;
+ }
+}
+
+declare module '@ruvector/ruvllm-wasm' {
+ export default function init(): Promise<void>;
+
+ /** Initialize WASM synchronously (Node.js). Must use object form: initSync({ module: bytes }) */
+ export function initSync(opts: { module: BufferSource }): void;
+
+ export class RuvLLMWasm {
+ constructor();
+ initialize(): void;
+ initializeWithConfig(config: KvCacheConfigWasm): void;
+ isInitialized: boolean;
+ getPoolStats(): string;
+ reset(): void;
+ // NOTE: version() is NOT on RuvLLMWasm β€” use standalone getVersion()
+ }
+ export class ChatMessageWasm {
+ static system(content: string): ChatMessageWasm;
+ static user(content: string): ChatMessageWasm;
+ static assistant(content: string): ChatMessageWasm;
+ role: string;
+ content: string;
+ }
+ export class ChatTemplateWasm {
+ static llama3(): ChatTemplateWasm;
+ static mistral(): ChatTemplateWasm;
+ static chatml(): ChatTemplateWasm;
+ static phi(): ChatTemplateWasm;
+ static gemma(): ChatTemplateWasm;
+ static custom(template: string): ChatTemplateWasm;
+ static detectFromModelId(model_id: string): ChatTemplateWasm;
+ format(messages: ChatMessageWasm[]): string;
+ name: string;
+ }
+ export class GenerateConfig {
+ constructor();
+ maxTokens: number;
+ temperature: number;
+ topP: number;
+ topK: number;
+ repetitionPenalty: number;
+ addStopSequence(seq: string): void;
+ clearStopSequences(): void;
+ toJson(): string;
+ static fromJson(json: string): GenerateConfig;
+ }
+ export class HnswRouterWasm {
+ constructor(dimensions: number, max_patterns: number);
+ /** Requires 3 args: (embedding, name, metadata_json). Panics at ~12+ patterns in v2.0.1. */
+ addPattern(embedding: Float32Array, name: string, metadata: string): boolean;
+ route(query: Float32Array, k: number): any[];
+ setEfSearch(ef: number): void;
+ clear(): void;
+ toJson(): string;
+ static fromJson(json: string): HnswRouterWasm;
+ dimensions: number;
+ }
+ /** Configuration for SonaInstantWasm. Required since v2.0.1 (replaces raw number). */
+ export class SonaConfigWasm {
+ constructor();
+ hiddenDim: number;
+ learningRate: number;
+ emaDecay: number;
+ ewcLambda: number;
+ microLoraRank: number;
+ patternCapacity: number;
+ toJson(): string;
+ }
+ export class SonaInstantWasm {
+ /** v2.0.1: requires SonaConfigWasm, not raw number */
+ constructor(config: SonaConfigWasm);
+ instantAdapt(quality: number): void;
+ recordPattern(embedding: number[], success: boolean): void;
+ suggestAction(context: string): string | undefined;
+ stats(): any;
+ toJson(): string;
+ static fromJson(json: string): SonaInstantWasm;
+ reset(): void;
+ }
+ export class KvCacheConfigWasm {
+ constructor();
+ tailLength: number;
+ maxTokens: number;
+ numKvHeads: number;
+ headDim: number;
+ }
+ export class KvCacheWasm {
+ constructor(config: KvCacheConfigWasm);
+ static withDefaults(): KvCacheWasm;
+ append(keys: Float32Array, values: Float32Array): void;
+ stats(): any;
+ clear(): void;
+ tokenCount: number;
+ }
+ /** Configuration for MicroLoraWasm. */
+ export class MicroLoraConfigWasm {
+ constructor();
+ inputDim: number;
+ outputDim: number;
+ rank: number;
+ alpha: number;
+ }
+ /** Feedback for MicroLoraWasm.adapt(). */
+ export class AdaptFeedbackWasm {
+ constructor();
+ quality: number;
+ learningRate: number;
+ success: boolean;
+ }
+ export class MicroLoraWasm {
+ constructor(config: MicroLoraConfigWasm);
+ /** Transform input through LoRA adapter */
+ apply(input: Float32Array): Float32Array;
+ /** Adapt weights β€” v2.0.2: takes (input, feedback), v2.0.1: takes (feedback) */
+ adapt(input: Float32Array, feedback: AdaptFeedbackWasm): void;
+ adapt(feedback: AdaptFeedbackWasm): void;
+ applyUpdates(gradients: Float32Array): void;
+ stats(): any;
+ reset(): void;
+ toJson(): string;
+ getConfig(): MicroLoraConfigWasm;
+ pendingUpdates(): number;
+ }
+ export class InferenceArenaWasm {
+ constructor(capacity: number);
+ static forModel(hidden_dim: number, vocab_size: number, batch_size: number): InferenceArenaWasm;
+ reset(): void;
+ used: number;
+ capacity: number;
+ remaining: number;
+ }
+ export class BufferPoolWasm {
+ constructor();
+ static withCapacity(max: number): BufferPoolWasm;
+ prewarmAll(count: number): void;
+ statsJson(): string;
+ hitRate: number;
+ clear(): void;
+ }
+ export function getVersion(): string;
+ export function isReady(): boolean;
+ export function detectChatTemplate(model_id: string): ChatTemplateWasm;
+}
+
declare module '@xenova/transformers' {
const transformers: any;
export default transformers;
diff --git a/v3/implementation/adrs/ADR-017-ruvector-integration.md b/v3/implementation/adrs/ADR-017-ruvector-integration.md
index abb85f1abd..44907978df 100644
--- a/v3/implementation/adrs/ADR-017-ruvector-integration.md
+++ b/v3/implementation/adrs/ADR-017-ruvector-integration.md
@@ -1528,6 +1528,72 @@ All builds pass successfully:
---
+---
+
+## WASM Package Integrations (2026-03-17)
+
+In addition to the original `ruvector` (core) package, two WASM packages have been integrated as optional dependencies, extending the RuVector integration surface to cover sandboxed agent runtimes and browser-native LLM inference.
+
+### @ruvector/rvagent-wasm v0.1.0 (ADR-059)
+
+Sandboxed AI agent runtime compiled to WebAssembly. See ADR-059 for full details.
+
+| Component | Description |
+|-----------|-------------|
+| `WasmAgent` | LLM agent with virtual filesystem (no OS access) |
+| `WasmGallery` | 6 pre-built agent templates (Coder, Researcher, Tester, Reviewer, Security, Swarm) |
+| `WasmMcpServer` | JSON-RPC 2.0 MCP server running entirely in WASM |
+| `WasmRvfBuilder` | RVF binary container format for multi-agent packaging |
+
+**Integration module**: `src/ruvector/agent-wasm.ts` (22 exports)
+**MCP tools**: `src/mcp-tools/wasm-agent-tools.ts` (10 tools)
+
+### @ruvector/ruvllm-wasm v2.0.1
+
+Browser-native LLM inference runtime with WASM-accelerated intelligence components. Provides native WASM implementations of several capabilities previously only available via JavaScript approximations.
+
+| Component | Description | Replaces/Enhances |
+|-----------|-------------|-------------------|
+| `RuvLLMWasm` | Core inference runtime (init, reset, version) | New capability |
+| `HnswRouterWasm` | WASM-native HNSW for semantic routing | Enhances ADR-028 HNSW search |
+| `SonaInstantWasm` | <1ms adaptation with WASM performance | Enhances SONA (ADR-028) |
+| `MicroLoraWasm` | Ultra-lightweight LoRA adaptation (ranks 1-4, <10KB) | Enhances LoRA adapter |
+| `ChatTemplateWasm` | Chat formatting (Llama3, Mistral, ChatML, Phi, Gemma, Qwen) | New capability |
+| `KvCacheWasm` | KV cache management for inference | Enhances ADR-028 KV cache |
+| `BufferPoolWasm` | Memory pool with prewarm and hit-rate tracking | New capability |
+| `InferenceArenaWasm` | Bump allocator for inference workloads | New capability |
+| `GenerateConfig` | Generation configuration (temp, top-p/k, repetition penalty) | New capability |
+
+**Node.js init pattern**: Uses `initSync({ module: bytes })` (not browser `init()` which requires Fetch API).
+
+**Resolved (v2.0.1)**: `HnswRouterWasm.addPattern()` `.ln()` bug fixed β€” replaced `wasm_random()` with integer-based geometric distribution in `select_layer()`. Published as v2.0.1.
+
+**Integration module**: `src/ruvector/ruvllm-wasm.ts` (planned)
+**MCP tools**: `src/mcp-tools/ruvllm-tools.ts` (planned)
+
+### Package Dependency Summary
+
+```json
+"optionalDependencies": {
+ "ruvector": "^1.0.0",
+ "@ruvector/rvagent-wasm": "^0.1.0",
+ "@ruvector/ruvllm-wasm": "^2.0.1",
+ "@ruvector/sona": "^0.1.5"
+}
+```
+
+### Cross-ADR Impact
+
+| ADR | Impact |
+|-----|--------|
+| ADR-028 (Neural Attention) | HNSW, SONA, KV Cache now available as native WASM via ruvllm-wasm |
+| ADR-059 (rvagent-wasm) | Full integration documented |
+| ADR-006 (Unified Memory) | HNSW search can use WasmHNSW backend |
+| ADR-026 (Agent Booster) | WASM agents provide Tier-0 sandboxed execution |
+
+---
+
**Status:** βœ… Complete (All Features Implemented)
**Completed:** 2026-01-07
+**Updated:** 2026-03-17 (WASM package integrations added)
**Total Lines:** Route (678) + Analyze (2114) = 2792 lines
diff --git a/v3/implementation/adrs/ADR-028-neural-attention-mechanisms.md b/v3/implementation/adrs/ADR-028-neural-attention-mechanisms.md
index aadb32104a..b20cf92c7b 100644
--- a/v3/implementation/adrs/ADR-028-neural-attention-mechanisms.md
+++ b/v3/implementation/adrs/ADR-028-neural-attention-mechanisms.md
@@ -921,7 +921,62 @@ npx @claude-flow/cli@latest attention cache clear
---
-**Status:** Proposed
+---
+
+## WASM-Native Implementations (2026-03-17 Update)
+
+The `@ruvector/[email protected]` package now provides native WASM implementations of several attention and intelligence components described in this ADR. These run at near-native speed without GPU requirements.
+
+### Available WASM Components
+
+| This ADR Concept | ruvllm-wasm Class | Status |
+|------------------|-------------------|--------|
+| HNSW Search (150x-12,500x) | `HnswRouterWasm` | Published, working (v2.0.1) |
+| SONA Adaptation (<0.05ms) | `SonaInstantWasm` | Published, working |
+| KV Cache Management | `KvCacheWasm` | Published, working |
+| LoRA Adaptation | `MicroLoraWasm` | Published, working (ranks 1-4, <10KB) |
+| Memory Pool / Buffer | `BufferPoolWasm` | Published, working |
+| Inference Arena | `InferenceArenaWasm` | Published, working |
+
+### WASM vs JavaScript Performance
+
+| Component | JS Implementation | WASM Implementation | Expected Speedup |
+|-----------|-------------------|---------------------|------------------|
+| HNSW Search | `FlashAttention` (JS) | `HnswRouterWasm` | 5-50x |
+| SONA Adapt | `SemanticRouter` (JS) | `SonaInstantWasm` | 10-100x |
+| LoRA Train | `LoRAAdapter` (JS) | `MicroLoraWasm` | 3-10x |
+| KV Cache | Manual `Map<>` | `KvCacheWasm` | 2-5x |
+
+### Integration Pattern
+
+```typescript
+// Detection and fallback
+import { isRuvllmWasmAvailable, initRuvllmWasm } from '../ruvector/ruvllm-wasm.js';
+
+if (await isRuvllmWasmAvailable()) {
+ await initRuvllmWasm();
+ // Use WASM-native HNSW, SONA, LoRA
+} else {
+ // Fallback to existing JS implementations
+}
+```
+
+### Known Issues (v2.0.0)
+
+- ~~`HnswRouterWasm.addPattern()` bug~~ β€” Fixed in v2.0.1 (integer-based geometric distribution replaces `wasm_random()`).
+- Stats objects return WASM pointer objects (`{__wbg_ptr: number}`) β€” use `.toJson()` or named accessors.
+- `initSync` requires object form: `initSync({ module: bytes })` (not raw bytes).
+
+### References
+
+- ADR-017: RuVector Integration Architecture (updated 2026-03-17 with WASM packages)
+- ADR-059: @ruvector/rvagent-wasm Integration
+- Package: `@ruvector/[email protected]` on npm
+
+---
+
+**Status:** Proposed (WASM implementations partially available)
**Priority:** High
-**Estimated Effort:** 5 weeks
+**Estimated Effort:** 5 weeks (reduced with WASM components)
**Dependencies:** ADR-006 (Memory), ADR-017 (RuVector)
+**Updated:** 2026-03-17
diff --git a/v3/package-lock.json b/v3/package-lock.json
index 041688c41c..c10621d0d1 100644
--- a/v3/package-lock.json
+++ b/v3/package-lock.json
@@ -1789,7 +1789,7 @@
}
},
"@claude-flow/cli": {
- "version": "3.5.22",
+ "version": "3.5.28",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
@@ -1817,8 +1817,11 @@
"@ruvector/attention": "^0.1.4",
"@ruvector/learning-wasm": "^0.1.29",
"@ruvector/router": "^0.1.27",
+ "@ruvector/ruvllm-wasm": "^2.0.2",
+ "@ruvector/rvagent-wasm": "^0.1.0",
"@ruvector/sona": "^0.1.5",
- "agentic-flow": "^3.0.0-alpha.1"
+ "agentic-flow": "^3.0.0-alpha.1",
+ "ruvector": "^0.2.16"
}
},
"@claude-flow/cli/node_modules/@ruvector/graph-node": {
@@ -1918,6 +1921,50 @@
"node": ">=18.0.0"
}
},
+ "@claude-flow/cli/node_modules/@ruvector/ruvllm": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/@ruvector/ruvllm/-/ruvllm-2.5.2.tgz",
+ "integrity": "sha512-ZyQD0ZMOZ5XqiFR+v2zQMZ9R9qc+H5qmYzegSH3CpGks4qRAv1ry/fHckXIFpg6iSRZrNd32D3aMRYSUGU+z/g==",
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "chalk": "^4.1.2",
+ "commander": "^12.0.0",
+ "ora": "^5.4.1"
+ },
+ "bin": {
+ "ruvllm": "bin/cli.js"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "optionalDependencies": {
+ "@ruvector/ruvllm-darwin-arm64": "2.3.0",
+ "@ruvector/ruvllm-darwin-x64": "2.3.0",
+ "@ruvector/ruvllm-linux-arm64-gnu": "2.3.0",
+ "@ruvector/ruvllm-linux-x64-gnu": "2.3.0",
+ "@ruvector/ruvllm-win32-x64-msvc": "2.3.0"
+ }
+ },
+ "@claude-flow/cli/node_modules/@ruvector/ruvllm/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"@claude-flow/cli/node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -1997,6 +2044,18 @@
"node": ">=18.0.0"
}
},
+ "@claude-flow/cli/node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
"@claude-flow/cli/node_modules/body-parser": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
@@ -2022,6 +2081,54 @@
"url": "https://opencollective.com/express"
}
},
+ "@claude-flow/cli/node_modules/brace-expansion": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "@claude-flow/cli/node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "@claude-flow/cli/node_modules/cli-cursor": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz",
+ "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "restore-cursor": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"@claude-flow/cli/node_modules/content-disposition": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
@@ -2122,6 +2229,28 @@
"node": ">= 0.8"
}
},
+ "@claude-flow/cli/node_modules/glob": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
+ "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
+ "license": "ISC",
+ "optional": true,
+ "dependencies": {
+ "foreground-child": "^3.1.0",
+ "jackspeak": "^3.1.2",
+ "minimatch": "^9.0.4",
+ "minipass": "^7.1.2",
+ "package-json-from-dist": "^1.0.0",
+ "path-scurry": "^1.11.1"
+ },
+ "bin": {
+ "glob": "dist/esm/bin.mjs"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"@claude-flow/cli/node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
@@ -2139,6 +2268,63 @@
"url": "https://opencollective.com/express"
}
},
+ "@claude-flow/cli/node_modules/is-interactive": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz",
+ "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "@claude-flow/cli/node_modules/is-unicode-supported": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
+ "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "@claude-flow/cli/node_modules/log-symbols": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
+ "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "chalk": "^4.1.0",
+ "is-unicode-supported": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "@claude-flow/cli/node_modules/log-symbols/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"@claude-flow/cli/node_modules/media-typer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
@@ -2189,6 +2375,42 @@
"url": "https://opencollective.com/express"
}
},
+ "@claude-flow/cli/node_modules/mimic-fn": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "@claude-flow/cli/node_modules/minimatch": {
+ "version": "9.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
+ "license": "ISC",
+ "optional": true,
+ "dependencies": {
+ "brace-expansion": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "@claude-flow/cli/node_modules/minipass": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+ "license": "BlueOak-1.0.0",
+ "optional": true,
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
"@claude-flow/cli/node_modules/negotiator": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@@ -2199,6 +2421,143 @@
"node": ">= 0.6"
}
},
+ "@claude-flow/cli/node_modules/onetime": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "mimic-fn": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "@claude-flow/cli/node_modules/ora": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",
+ "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "bl": "^4.1.0",
+ "chalk": "^4.1.0",
+ "cli-cursor": "^3.1.0",
+ "cli-spinners": "^2.5.0",
+ "is-interactive": "^1.0.0",
+ "is-unicode-supported": "^0.1.0",
+ "log-symbols": "^4.1.0",
+ "strip-ansi": "^6.0.0",
+ "wcwidth": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "@claude-flow/cli/node_modules/ora/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "@claude-flow/cli/node_modules/restore-cursor": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz",
+ "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "onetime": "^5.1.0",
+ "signal-exit": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "@claude-flow/cli/node_modules/ruvector": {
+ "version": "0.2.16",
+ "resolved": "https://registry.npmjs.org/ruvector/-/ruvector-0.2.16.tgz",
+ "integrity": "sha512-hTaFjQ1YSgksL1K3+od3fd+geMAWaAwHdi+cHTds8anPCkEOxvHsBj3Wiy1psM6+Q1ZbcrJVG8ek8utHHafiOw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.0.0",
+ "@ruvector/attention": "^0.1.3",
+ "@ruvector/core": "^0.1.25",
+ "@ruvector/gnn": "^0.1.22",
+ "@ruvector/sona": "^0.1.4",
+ "chalk": "^4.1.2",
+ "commander": "^11.1.0",
+ "glob": "^10.3.10",
+ "ora": "^5.4.1"
+ },
+ "bin": {
+ "ruvector": "bin/cli.js"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "@ruvector/rvf": "^0.1.0"
+ },
+ "peerDependencies": {
+ "@ruvector/router": ">=0.1.0",
+ "@ruvector/ruvllm": ">=2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@ruvector/router": {
+ "optional": true
+ },
+ "@ruvector/ruvllm": {
+ "optional": true
+ }
+ }
+ },
+ "@claude-flow/cli/node_modules/ruvector/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "@claude-flow/cli/node_modules/ruvector/node_modules/commander": {
+ "version": "11.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",
+ "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=16"
+ }
+ },
"@claude-flow/cli/node_modules/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
@@ -9018,6 +9377,13 @@
"node": ">= 18"
}
},
+ "node_modules/@ruvector/ruvllm-wasm": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@ruvector/ruvllm-wasm/-/ruvllm-wasm-2.0.2.tgz",
+ "integrity": "sha512-jVu+t710JvEzU6UZZvKrTp+dWsm3hKzOqB+yxrcqFsVaccVfeKyQuvCx13qVENvuntbnfslryErn9QbydH76yQ==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/@ruvector/ruvllm-win32-x64-msvc": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@ruvector/ruvllm-win32-x64-msvc/-/ruvllm-win32-x64-msvc-0.2.0.tgz",
@@ -9194,6 +9560,13 @@
"node": ">=8"
}
},
+ "node_modules/@ruvector/rvagent-wasm": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/@ruvector/rvagent-wasm/-/rvagent-wasm-0.1.0.tgz",
+ "integrity": "sha512-zhcnU7XfBEfDwkDFscehq6qGU/TW4LNr287xHHXCuNsaTBPlb8YSnkuMNWg6BBIK/X+UdWAsyYESN5jbNQEaBQ==",
+ "license": "MIT OR Apache-2.0",
+ "optional": true
+ },
"node_modules/@ruvector/rvf": {
"version": "0.1.9",
"resolved": "https://registry.npmjs.org/@ruvector/rvf/-/rvf-0.1.9.tgz",
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index 13b084339e..be92610a1c 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -58,7 +58,7 @@ importers:
version: 0.6.0
agentic-flow:
specifier: ^2.0.3
+ version: 2.0.3(@types/[email protected])([email protected])
zod:
specifier: ^3.22.4
version: 3.25.76
@@ -140,12 +140,21 @@ importers:
'@ruvector/router':
specifier: ^0.1.27
version: 0.1.28
+ '@ruvector/ruvllm-wasm':
+ specifier: ^2.0.2
+ version: 2.0.2
+ '@ruvector/rvagent-wasm':
+ specifier: ^0.1.0
+ version: 0.1.0
'@ruvector/sona':
specifier: ^0.1.5
version: 0.1.5
agentic-flow:
specifier: ^3.0.0-alpha.1
version: 3.0.0-alpha.1
+ ruvector:
+ specifier: ^0.2.16
+ version: 0.2.16(@ruvector/[email protected])([email protected])
devDependencies:
typescript:
specifier: ^5.3.0
@@ -220,7 +229,7 @@ importers:
version: 2.17.2
agentic-flow:
specifier: ^2.0.0
+ version: 2.0.3(@types/[email protected])([email protected])
sql.js:
specifier: ^1.13.0
version: 1.13.0
@@ -293,7 +302,7 @@ importers:
dependencies:
agentic-flow:
specifier: ^2.0.0-alpha
optionalDependencies:
agent-booster:
specifier: ^0.2.2
@@ -3806,6 +3815,12 @@ packages:
dev: false
optional: true
+ /@ruvector/[email protected]:
+ resolution: {integrity: sha512-jVu+t710JvEzU6UZZvKrTp+dWsm3hKzOqB+yxrcqFsVaccVfeKyQuvCx13qVENvuntbnfslryErn9QbydH76yQ==}
+ requiresBuild: true
+ dev: false
+ optional: true
+
/@ruvector/[email protected]:
resolution: {integrity: sha512-ksm+AZVqkkYLVq2Rbc7Rx+gSH7egFWlcH3E5dQpro98Oslc7jUH+uNDRjDVUS3lZXchV+Ot5WPLM4pClRxFm9w==}
engines: {node: '>= 18'}
@@ -3831,6 +3846,12 @@ packages:
'@ruvector/ruvllm-win32-x64-msvc': 0.2.0
dev: false
+ /@ruvector/[email protected]:
+ resolution: {integrity: sha512-zhcnU7XfBEfDwkDFscehq6qGU/TW4LNr287xHHXCuNsaTBPlb8YSnkuMNWg6BBIK/X+UdWAsyYESN5jbNQEaBQ==}
+ requiresBuild: true
+ dev: false
+ optional: true
+
/@ruvector/[email protected]:
resolution: {integrity: sha512-vll3WJwDn3oOfy1PB10IG7/f3zBpFiMNHL2/2tdJmeRR8La/rSPJ0ZH5MDIsfleiVtaWzh9bvVCtVkZ6uo2jeg==}
cpu: [arm64]
@@ -5015,7 +5036,7 @@ packages:
jsonwebtoken: 9.0.3
marked-terminal: 6.2.0([email protected])
ora: 7.0.1
+ ruvector: 0.1.95([email protected])
ruvector-attention-wasm: 0.1.0
sql.js: 1.13.0
zod: 3.25.76
@@ -5053,7 +5074,7 @@ packages:
- supports-color
dev: false
resolution: {integrity: sha512-bUqO5o2VpWomh2xGOHdQoX00CGrPcIAH6zDCt5oa0SeJWAO+bbB7SiElb1TxwcrJQKe96HkiSh2T8z4vFypsxg==}
engines: {node: '>=18.0.0'}
hasBin: true
@@ -5061,7 +5082,7 @@ packages:
dependencies:
'@modelcontextprotocol/sdk': 1.27.1([email protected])
'@opentelemetry/api': 1.9.0
- '@ruvector/attention': 0.1.4
+ '@ruvector/attention': 0.1.31
'@ruvector/gnn': 0.1.25
'@ruvector/graph-node': 0.1.26
'@ruvector/router': 0.1.26
@@ -5076,7 +5097,7 @@ packages:
jsonwebtoken: 9.0.3
marked-terminal: 6.2.0([email protected])
ora: 7.0.1
+ ruvector: 0.1.100([email protected])
ruvector-attention-wasm: 0.1.0
sql.js: 1.14.0
zod: 3.25.76
@@ -5108,13 +5129,12 @@ packages:
- bluebird
- encoding
- express
- - hono
- marked
- react-native-b4a
- supports-color
dev: false
resolution: {integrity: sha512-03CUdFgrqw8Mplkvlz66YCKQBSD+l+r8ox4hTZmx56nvkJU8ltKMQJ9h9nz7kvxEbDz2PeZO+SqT45qHNEWRcg==}
engines: {node: '>=18.0.0'}
hasBin: true
@@ -5137,7 +5157,7 @@ packages:
jsonwebtoken: 9.0.3
marked-terminal: 6.2.0([email protected])
ora: 7.0.1
+ ruvector: 0.1.100([email protected])
ruvector-attention-wasm: 0.1.0
sql.js: 1.14.0
zod: 3.25.76
@@ -5166,7 +5186,6 @@ packages:
- bare-buffer
- encoding
- express
- - hono
- marked
- react-native-b4a
- supports-color
@@ -5311,7 +5330,7 @@ packages:
dev: false
optional: true
resolution: {integrity: sha512-lbBEr7LiOq0lcBFnxrTZEGfXp9KzPsiNtIkWDIve0y+LMW+ZUKl8FNraT0Lwcc7zcKMQoqCfvZksvyEFG+E0Fg==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
@@ -5336,7 +5355,7 @@ packages:
'@types/react-dom': 19.2.3(@types/[email protected])
'@vitejs/plugin-react-swc': 4.2.2([email protected])
'@xenova/transformers': 2.17.2
+ agentdb: 2.0.0-alpha.3.4(@types/[email protected])([email protected])([email protected])
agentic-payments: 0.1.13([email protected])
autoprefixer: 10.4.23([email protected])
axios: 1.13.2
@@ -5372,7 +5391,6 @@ packages:
- debug
- effect
- encoding
- - hono
- jiti
- jose
- less
@@ -5391,7 +5409,7 @@ packages:
- utf-8-validate
dev: false
resolution: {integrity: sha512-yqrcwWG+RztVKx4w9bvIiAymXEZn93GiTsF6qhYv2gOTQyhIl+VKwY9MLuQKz+Nr5wibTJ4EPm1Cib43usvNNA==}
engines: {node: '>=18.0.0'}
hasBin: true
@@ -5414,7 +5432,7 @@ packages:
glob: 13.0.0
gun: 0.2020.1241
http-proxy-middleware: 3.0.5
+ ruvector: 0.1.95([email protected])
ruvector-onnx-embeddings-wasm: 0.1.2
tiktoken: 1.0.22
ulid: 3.0.2
@@ -5424,7 +5442,7 @@ packages:
optionalDependencies:
'@ruvector/attention': 0.1.31
'@ruvector/sona': 0.1.5
+ agentdb: 2.0.0-alpha.3.7(@types/[email protected])([email protected])([email protected])
better-sqlite3: 11.10.0
onnxruntime-node: 1.24.2
sharp: 0.32.6
@@ -5441,7 +5459,6 @@ packages:
- debug
- effect
- encoding
- - hono
- jose
- marked
- react-native-b4a
@@ -5963,7 +5980,7 @@ packages:
content-type: 1.0.5
debug: 4.4.3
http-errors: 2.0.1
- iconv-lite: 0.7.1
+ iconv-lite: 0.7.2
on-finished: 2.4.1
qs: 6.14.1
raw-body: 3.0.2
@@ -6292,7 +6309,7 @@ packages:
engines: {node: '>=20'}
dependencies:
string-width: 7.2.0
- strip-ansi: 7.1.2
+ strip-ansi: 7.2.0
wrap-ansi: 9.0.2
@@ -6694,6 +6711,7 @@ packages:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+ requiresBuild: true
resolution: {integrity: sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==}
@@ -7632,6 +7650,7 @@ packages:
resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
hasBin: true
dependencies:
foreground-child: 3.3.1
@@ -7652,7 +7671,7 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
- deprecated: Glob versions prior to v9 are no longer supported
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
dependencies:
fs.realpath: 1.0.0
inflight: 1.0.6
@@ -8759,6 +8778,7 @@ packages:
resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}
engines: {node: '>=6'}
+ requiresBuild: true
dev: false
@@ -10251,12 +10271,12 @@ packages:
- zod
dev: false
resolution: {integrity: sha512-uDKYhgPE7H3cyPPGdPuP8DhKd3CASouSpfk4+ghjH1HtCGWTlU6jMvGQJaYMMs2N3HpsnB47a7NcozXHR4csXA==}
engines: {node: '>=14.0.0'}
hasBin: true
dependencies:
- '@modelcontextprotocol/sdk': 1.25.1([email protected])([email protected])
+ '@modelcontextprotocol/sdk': 1.27.1([email protected])
'@ruvector/attention': 0.1.31
'@ruvector/core': 0.1.30
'@ruvector/gnn': 0.1.25
@@ -10269,12 +10289,44 @@ packages:
- '@cfworker/json-schema'
- bare-abort-controller
- bare-buffer
- - hono
- react-native-b4a
- supports-color
- zod
dev: false
+ resolution: {integrity: sha512-hTaFjQ1YSgksL1K3+od3fd+geMAWaAwHdi+cHTds8anPCkEOxvHsBj3Wiy1psM6+Q1ZbcrJVG8ek8utHHafiOw==}
+ engines: {node: '>=18.0.0'}
+ hasBin: true
+ requiresBuild: true
+ peerDependencies:
+ '@ruvector/router': '>=0.1.0'
+ '@ruvector/ruvllm': '>=2.0.0'
+ peerDependenciesMeta:
+ '@ruvector/router':
+ optional: true
+ '@ruvector/ruvllm':
+ optional: true
+ dependencies:
+ '@modelcontextprotocol/sdk': 1.27.1([email protected])
+ '@ruvector/attention': 0.1.31
+ '@ruvector/core': 0.1.30
+ '@ruvector/gnn': 0.1.25
+ '@ruvector/router': 0.1.28
+ '@ruvector/sona': 0.1.5
+ chalk: 4.1.2
+ commander: 11.1.0
+ glob: 10.5.0
+ ora: 5.4.1
+ optionalDependencies:
+ '@ruvector/rvf': 0.1.9
+ transitivePeerDependencies:
+ - '@cfworker/json-schema'
+ - supports-color
+ - zod
+ dev: false
+ optional: true
+
resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
dependencies:
@@ -10740,7 +10792,7 @@ packages:
dependencies:
eastasianwidth: 0.2.0
emoji-regex: 10.6.0
- strip-ansi: 7.1.2
+ strip-ansi: 7.2.0
dev: false
@@ -10749,7 +10801,7 @@ packages:
dependencies:
emoji-regex: 10.6.0
get-east-asian-width: 1.4.0
- strip-ansi: 7.1.2
+ strip-ansi: 7.2.0
resolution: {integrity: sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw==}
@@ -10782,6 +10834,7 @@ packages:
engines: {node: '>=12'}
dependencies:
ansi-regex: 6.2.2
+ dev: false
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}