🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(cli): declare @ruvector/rvagent-wasm optional; count only new patterns (#3979)
RuFlo5c00b076ef19
diff --git a/v3/@claude-flow/cli/__tests__/agent-wasm-not-installed-3979.test.ts b/v3/@claude-flow/cli/__tests__/agent-wasm-not-installed-3979.test.tsnew file mode 100644index 0000000000..33177853d8--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/agent-wasm-not-installed-3979.test.ts@@ -0,0 +1,59 @@+// #3979 item 1: `ruflo mcp exec -t wasm_gallery_list` on a global install failed with+// Failed to initialize @ruvector/rvagent-wasm: Error [ERR_MODULE_NOT_FOUND]: Cannot find package ...+// because (a) the package is imported by dist/src/ruvector/agent-wasm.js but was not+// declared in the CLI's package.json, so `npm i -g ruflo` never installed it, and+// (b) when it is missing the error is a raw module-resolution trace rather than a+// plain "not installed" message with the fix. Both are checked here.++import { describe, it, expect, vi, afterEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const pkg = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf8'));++afterEach(() => {+ vi.resetModules();+ vi.doUnmock('@ruvector/rvagent-wasm');+});++describe('@ruvector/rvagent-wasm packaging (#3979 item 1)', () => {+ it('is declared as an optional dependency so a global install fetches it', () => {+ expect(pkg.optionalDependencies?.['@ruvector/rvagent-wasm']).toBeTruthy();+ // Optional, never a hard dependency: ruflo must still install and run without it.+ expect(pkg.dependencies?.['@ruvector/rvagent-wasm']).toBeUndefined();+ });+});++describe('initAgentWasm() when @ruvector/rvagent-wasm is missing (#3979 item 1)', () => {+ it('says the package is not installed and how to install it, instead of a raw resolution trace', async () => {+ vi.doMock('@ruvector/rvagent-wasm', () => {+ throw Object.assign(new Error("Cannot find package '@ruvector/rvagent-wasm' imported from /x/agent-wasm.js"), {+ code: 'ERR_MODULE_NOT_FOUND',+ });+ });+ const mod = await import('../src/ruvector/agent-wasm.js');++ const err = await mod.initAgentWasm().then(() => null, (e: unknown) => e as Error);+ expect(err).toBeInstanceOf(Error);+ expect(err!.message).toMatch(/@ruvector\/rvagent-wasm is not installed/);+ expect(err!.message).toMatch(/npm install/);+ expect(err!.message).not.toMatch(/ERR_MODULE_NOT_FOUND|Cannot find package/);+ });++ it('still reports a genuine initialization failure as one', async () => {+ vi.doMock('@ruvector/rvagent-wasm', () => ({+ WasmAgent: class {},+ initSync: () => {+ throw new Error('wasm bytes rejected');+ },+ }));+ const mod = await import('../src/ruvector/agent-wasm.js');++ const err = await mod.initAgentWasm().then(() => null, (e: unknown) => e as Error);+ expect(err).toBeInstanceOf(Error);+ // Either the package resolves here and init fails (Failed to initialize ...),+ // or it is genuinely absent in this checkout (not installed). It must never+ // be reported as the wrong one of the two.+ expect(err!.message).toMatch(/Failed to initialize @ruvector\/rvagent-wasm|@ruvector\/rvagent-wasm is not installed/);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/patterns-learned-dedup-3979.test.ts b/v3/@claude-flow/cli/__tests__/patterns-learned-dedup-3979.test.tsnew file mode 100644index 0000000000..517ed0bbac--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/patterns-learned-dedup-3979.test.ts@@ -0,0 +1,95 @@+// #3979 item 4: the Learning page's "patterns learned" always equalled+// "trajectories": recordTrajectory() bumped globalStats.patternsLearned for+// every successful step, even when LocalReasoningBank.store() merged the step+// into an existing pattern (same content). The metric read as learning while it+// was really a step count. It must count only patterns that were actually added.++import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// Steps carry their own embeddings, but keep any embedding the module does+// generate deterministic so this file does not depend on a model cache.+vi.mock('../src/memory/memory-bridge.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../src/memory/memory-bridge.js')>();+ return { ...actual, bridgeGenerateEmbedding: vi.fn(async () => null) };+});+vi.mock('../src/memory/memory-initializer.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../src/memory/memory-initializer.js')>();+ return {+ ...actual,+ generateEmbedding: vi.fn(async () => ({+ embedding: [1, 0, 0],+ dimensions: 3,+ model: 'mock-deterministic',+ backend: 'mock' as const,+ })),+ };+});++// Scope CWD to this file only (vitest shares the process across files).+const SCRATCH = mkdtempSync(join(tmpdir(), 'intel-3979-'));+let originalCwd: string;++beforeAll(() => {+ originalCwd = process.cwd();+ process.chdir(SCRATCH);+ mkdirSync(join(SCRATCH, '.claude-flow'), { recursive: true });+});++afterAll(() => {+ try { process.chdir(originalCwd); } catch { /* best-effort */ }+ try { rmSync(SCRATCH, { recursive: true, force: true }); } catch { /* best-effort */ }+});++beforeEach(async () => {+ const intel = await import('../src/memory/intelligence.js');+ intel.clearIntelligence();+ try { rmSync(join(SCRATCH, '.claude-flow', 'neural'), { recursive: true, force: true }); } catch { /* none */ }+ await intel.initializeIntelligence();+});++function step(content: string, embedding: number[]) {+ return { type: 'action' as const, content, embedding, metadata: {}, timestamp: Date.now() };+}++describe('patterns learned counts new patterns, not successful steps (#3979 item 4)', () => {+ it('does not count a repeated identical step as a new pattern', async () => {+ const intel = await import('../src/memory/intelligence.js');++ await intel.recordTrajectory([step('run the unit tests', [1, 0, 0])], 'success');+ const afterFirst = intel.getIntelligenceStats().patternsLearned;+ // The metric is max(bank size, running counter). Repeat enough times that+ // an unconditional counter bump would overtake the bank size.+ for (let i = 0; i < 12; i++) {+ await intel.recordTrajectory([step('run the unit tests', [1, 0, 0])], 'success');+ }+ const afterRepeats = intel.getIntelligenceStats().patternsLearned;++ // Twelve identical successes merge into the existing pattern.+ expect(afterRepeats).toBe(afterFirst);+ // The bank holds one pattern for that content, not thirteen.+ const bank = intel.getReasoningBank()!;+ const hits = bank.findSimilar([1, 0, 0], { k: 50, threshold: 0 }).filter((p) => p.content === 'run the unit tests');+ expect(hits).toHaveLength(1);+ });++ it('still counts each genuinely different step', async () => {+ const intel = await import('../src/memory/intelligence.js');+ const before = intel.getIntelligenceStats().patternsLearned;++ await intel.recordTrajectory([step('open the config file', [1, 0, 0])], 'success');+ await intel.recordTrajectory([step('commit the change', [0, 1, 0])], 'success');+ await intel.recordTrajectory([step('push the branch', [0, 0, 1])], 'success');++ expect(intel.getIntelligenceStats().patternsLearned - before).toBe(3);+ });++ it('does not count failed trajectories', async () => {+ const intel = await import('../src/memory/intelligence.js');+ const before = intel.getIntelligenceStats().patternsLearned;+ await intel.recordTrajectory([step('a step that failed', [0, 1, 0])], 'failure');+ expect(intel.getIntelligenceStats().patternsLearned).toBe(before);+ });+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 57cb06ccfa..fe542f2e82 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -135,6 +135,7 @@"@metaharness/radio": "~0.1.0","@metaharness/turn-credit": "~0.1.0","@napi-rs/keyring": "1.3.0",+ "@ruvector/rvagent-wasm": "^0.1.0","agentdb": "^3.0.0-alpha.20","agentic-flow": "^3.0.0-alpha.1","better-sqlite3": "^12.9.0",diff --git a/v3/@claude-flow/cli/src/memory/intelligence.ts b/v3/@claude-flow/cli/src/memory/intelligence.tsindex 7b86efef14..5a22dc4585 100644--- a/v3/@claude-flow/cli/src/memory/intelligence.ts+++ b/v3/@claude-flow/cli/src/memory/intelligence.ts@@ -557,8 +557,12 @@ class LocalReasoningBank {* Deduplicates by content: if a pattern with the same content already* exists, the existing entry is updated (bumped usageCount, higher* confidence wins, refreshed lastUsedAt) instead of adding a duplicate.+ *+ * Returns true only when a NEW pattern was added (#3979 item 4): callers that+ * keep a "patterns learned" counter must not count a merge or an update of an+ * existing pattern as a newly learned one.*/- store(pattern: Omit<StoredPattern, 'usageCount' | 'createdAt' | 'lastUsedAt'> & Partial<StoredPattern>): void {+ store(pattern: Omit<StoredPattern, 'usageCount' | 'createdAt' | 'lastUsedAt'> & Partial<StoredPattern>): boolean {const now = Date.now();const stored: StoredPattern = {...pattern,@@ -578,6 +582,9 @@ class LocalReasoningBank {if (idx >= 0) {this.patternList[idx] = stored;}+ this.patterns.set(pattern.id, stored);+ this.saveToDisk();+ return false;} else {// Check for content-duplicate before inserting a new entryconst contentDupe = this.patternList.find(p => p.content === pattern.content);@@ -591,7 +598,7 @@ class LocalReasoningBank {// Keep the Map in sync with the mutated objectthis.patterns.set(contentDupe.id, contentDupe);this.saveToDisk();- return;+ return false;}// Evict oldest if at capacity@@ -608,6 +615,7 @@ class LocalReasoningBank {// Trigger persistence (debounced)this.saveToDisk();+ return true;}/**@@ -1164,7 +1172,7 @@ export async function recordTrajectory(if (verdict === 'success') {for (const step of enrichedSteps) {if (step.embedding && step.embedding.length > 0) {- reasoningBank.store({+ const added = reasoningBank.store({id: `pattern-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,type: step.type,content: step.content,@@ -1173,7 +1181,10 @@ export async function recordTrajectory(metadata: step.metadata || {},createdAt: Date.now(),});- globalStats.patternsLearned++;+ // #3979 item 4: count only patterns that were actually added. A step+ // whose content already exists is merged into that pattern, so the+ // counter no longer climbs once per successful step.+ if (added) globalStats.patternsLearned++;}}}diff --git a/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts b/v3/@claude-flow/cli/src/ruvector/agent-wasm.tsindex 673d2a299d..0928d4b3b1 100644--- a/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts+++ b/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts@@ -61,6 +61,19 @@ export interface ToolResult {let _wasmReady = false;+/** Shown wherever the optional @ruvector/rvagent-wasm package cannot be loaded. */+export const AGENT_WASM_NOT_INSTALLED_MESSAGE =+ '@ruvector/rvagent-wasm is not installed.\n' ++ 'Install it with: npm install @ruvector/rvagent-wasm (or npm install -g @ruvector/rvagent-wasm for a global ruflo)';++/** True when err is the module-resolution failure for @ruvector/rvagent-wasm itself. */+function isMissingAgentWasm(err: unknown): boolean {+ const e = err as { code?: unknown; message?: unknown } | null;+ const code = typeof e?.code === 'string' ? e.code : '';+ const message = typeof e?.message === 'string' ? e.message : String(err);+ return (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') && message.includes('@ruvector/rvagent-wasm');+}+/*** Check if @ruvector/rvagent-wasm is installed and loadable.*/@@ -88,6 +101,11 @@ export async function initAgentWasm(): Promise<void> {mod.initSync(wasmBytes);_wasmReady = true;} catch (err) {+ // #3979 item 1: a missing optional package is "not installed", with the fix,+ // not a raw ERR_MODULE_NOT_FOUND trace dressed up as an initialization failure.+ if (isMissingAgentWasm(err)) {+ throw new Error(AGENT_WASM_NOT_INSTALLED_MESSAGE);+ }throw new Error(`Failed to initialize @ruvector/rvagent-wasm: ${err}`);}}diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex c8973b44ff..fbed05905d 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -228,6 +228,9 @@ importers:'@napi-rs/keyring':specifier: 1.3.0version: 1.3.0+ '@ruvector/rvagent-wasm':+ specifier: ^0.1.0+ version: 0.1.0agentdb:specifier: ^3.0.0-alpha.20version: 3.0.0-alpha.20(@types/[email protected])([email protected])@@ -5806,6 +5809,12 @@ packages:'@ruvector/ruvllm-linux-x64-gnu': 2.0.1'@ruvector/ruvllm-win32-x64-msvc': 2.0.1+ /@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]@@ -13566,7 +13575,6 @@ packages:optional: truedev: false-resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}engines: {node: '>=10.0.0'}