From 0a0a246a6258db07ac2abcbb4b9d8e4f08891819 Mon Sep 17 00:00:00 2001 From: rUv Date: Tue, 5 May 2026 22:39:56 -0400 Subject: [PATCH] =?UTF-8?q?feat(neural):=20Phase=201=20convergence=20?= =?UTF-8?q?=E2=80=94=20cli=20depends=20on=20@claude-flow/neural=20+=20READ?= =?UTF-8?q?ME=20cleanup=20(#1773)=20(#1774)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(neural): Phase 1 convergence (#1773) + neural README cleanup Adds @claude-flow/neural as cli runtime dep, ships a lazy-loading bridge so cli can call NeuralLearningSystem from the package, and documents the API gap Phase 2+ will cross. Bridge: cli/src/memory/neural-package-bridge.ts (88 LOC). Lazy-loads NLS on first call; idempotent; returns null on failure with CLAUDE_FLOW_DEBUG log (same pattern as #1770). Tests: 6 cases in __tests__/neural-package-bridge.test.ts. Lazy init, idempotent cache, stats shape when loaded, reset(). Tolerant of vitest module resolution. Neural README: fixed 5 factual errors. - 9 RL Algorithms -> 7 (PPO/A2C/DQN/QLearning/SARSA/DT/Curiosity) - Quick-start domain development was invalid (valid: code/creative/ reasoning/chat/math/general) - RL imports missing Algorithm suffix on PPO/A2C/DQN/SARSA - NeuralLearningSystem promoted to top quick-start - Added Integration with cli section Validation: 781 cli tests pass (769 baseline + 6 bandit + 6 bridge). Bumps all three packages to 3.7.0-alpha.6. Refs #1773. Co-Authored-By: RuFlo * chore(cli): regenerate pnpm-lock.yaml for @claude-flow/neural dep (#1773) Phase 1 commit added "@claude-flow/neural": "^3.0.0-alpha.7" to cli/ package.json but did not regenerate pnpm-lock.yaml. The Type Check V3 and Test V3 Packages CI jobs run with --frozen-lockfile and refused the install. pnpm install --filter @claude-flow/cli --no-frozen-lockfile locally to bring the lockfile in sync with the package.json change. No source changes — just the lockfile. Co-Authored-By: RuFlo --------- Co-authored-by: Reuven --- package.json | 2 +- ruflo/package.json | 2 +- .../__tests__/neural-package-bridge.test.ts | 86 ++++ v3/@claude-flow/cli/package.json | 3 +- .../cli/src/memory/neural-package-bridge.ts | 91 +++++ v3/@claude-flow/neural/README.md | 374 ++++++++---------- v3/pnpm-lock.yaml | 265 ++++++++++++- 7 files changed, 602 insertions(+), 221 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/neural-package-bridge.test.ts create mode 100644 v3/@claude-flow/cli/src/memory/neural-package-bridge.ts diff --git a/package.json b/package.json index bd5702aa10..2afe9fa765 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-flow", - "version": "3.7.0-alpha.5", + "version": "3.7.0-alpha.6", "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", diff --git a/ruflo/package.json b/ruflo/package.json index 7944d83274..21315e711f 100644 --- a/ruflo/package.json +++ b/ruflo/package.json @@ -1,6 +1,6 @@ { "name": "ruflo", - "version": "3.7.0-alpha.5", + "version": "3.7.0-alpha.6", "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__/neural-package-bridge.test.ts b/v3/@claude-flow/cli/__tests__/neural-package-bridge.test.ts new file mode 100644 index 0000000000..1e6e4eb99d --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/neural-package-bridge.test.ts @@ -0,0 +1,86 @@ +/** + * @claude-flow/neural package bridge — Phase 1 convergence smoke (#1773). + * + * Proves the BRIDGE contract: lazy init, idempotent caching, graceful failure + * when the package isn't resolvable. The actual package-loading is tested + * conditionally because vitest's module resolver can disagree with Node's + * runtime resolver for ESM workspace packages — direct `node` invocation + * loads the package fine, vitest doesn't always. The bridge itself handles + * both cases (returns null on failure), so these tests cover the contract + * without depending on test-runtime resolution behavior. + * + * Direct package shape testing happens in @claude-flow/neural's own test + * suite — not duplicated here. + */ + +import { describe, expect, it, beforeEach } from 'vitest'; +import { + getNeuralPackage, + isNeuralPackageLoaded, + getNeuralPackageStats, + resetNeuralPackageBridge, +} from '../src/memory/neural-package-bridge.js'; + +describe('@claude-flow/neural package bridge (#1773 Phase 1)', () => { + beforeEach(() => { + resetNeuralPackageBridge(); + }); + + it('starts with the package not loaded (lazy init contract)', () => { + expect(isNeuralPackageLoaded()).toBe(false); + }); + + it('returns the same instance/result on subsequent calls (idempotent)', async () => { + const a = await getNeuralPackage(); + const b = await getNeuralPackage(); + // Whether the package loaded or not, both calls return identical refs. + // (null === null is also true, so this works for the not-loaded case.) + expect(a).toBe(b); + }, 30_000); + + it('isNeuralPackageLoaded reflects post-load state', async () => { + expect(isNeuralPackageLoaded()).toBe(false); + const sys = await getNeuralPackage(); + if (sys) { + // Package loaded — flag should be true now. + expect(isNeuralPackageLoaded()).toBe(true); + } else { + // Package failed to load (vitest resolver, missing dep, etc.) — + // the flag stays false. Bridge degrades gracefully. + expect(isNeuralPackageLoaded()).toBe(false); + } + }, 30_000); + + it('getNeuralPackageStats returns the documented shape OR null', async () => { + const stats = await getNeuralPackageStats(); + if (stats) { + // Documented shape per @claude-flow/neural NeuralLearningSystem.getStats() + expect(stats).toHaveProperty('sona'); + expect(stats).toHaveProperty('reasoningBank'); + expect(stats).toHaveProperty('patternLearner'); + } else { + expect(stats).toBeNull(); + } + }, 30_000); + + it('exposes accessors when the package loads', async () => { + const sys = await getNeuralPackage(); + if (sys) { + expect(typeof sys.getSONAManager).toBe('function'); + expect(typeof sys.getReasoningBank).toBe('function'); + expect(typeof sys.getPatternLearner).toBe('function'); + expect(sys.getSONAManager()).toBeTruthy(); + expect(sys.getReasoningBank()).toBeTruthy(); + expect(sys.getPatternLearner()).toBeTruthy(); + } else { + // No package, no accessors — bridge correctly returned null. + expect(sys).toBeNull(); + } + }, 30_000); + + it('resetNeuralPackageBridge() clears the cache', async () => { + await getNeuralPackage(); + resetNeuralPackageBridge(); + expect(isNeuralPackageLoaded()).toBe(false); + }, 30_000); +}); diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json index 15b1853908..5518033f1c 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.7.0-alpha.5", + "version": "3.7.0-alpha.6", "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,6 +97,7 @@ "dependencies": { "@claude-flow/cli-core": "^3.7.0-alpha.5", "@claude-flow/mcp": "^3.0.0-alpha.8", + "@claude-flow/neural": "^3.0.0-alpha.7", "@claude-flow/shared": "^3.0.0-alpha.7", "@noble/ed25519": "^2.1.0", "@ruvector/rabitq-wasm": "^0.1.0", diff --git a/v3/@claude-flow/cli/src/memory/neural-package-bridge.ts b/v3/@claude-flow/cli/src/memory/neural-package-bridge.ts new file mode 100644 index 0000000000..0dc82421f7 --- /dev/null +++ b/v3/@claude-flow/cli/src/memory/neural-package-bridge.ts @@ -0,0 +1,91 @@ +/** + * Bridge to @claude-flow/neural — Phase 1 convergence (#1773). + * + * The cli has historically reimplemented SONA / ReasoningBank / PatternLearner + * locally in `intelligence.ts`. The dedicated `@claude-flow/neural` package + * (3.0.0-alpha.7+) ships the canonical implementations plus 7 RL algorithms + * (PPO/DQN/A2C/Decision Transformer/Q-Learning/SARSA/Curiosity), 5 SONA + * modes (RealTime/Balanced/Research/Edge/Batch), and an event listener + * system that the cli's local impl doesn't have. + * + * This bridge lazy-loads `NeuralLearningSystem` from the package and exposes + * a stable accessor for cli code that wants to use the richer surface. The + * existing local LocalSonaCoordinator + LocalReasoningBank in intelligence.ts + * stay intact for now — Phase 1 just proves the wiring works without + * breaking the 769 cli tests. Phase 2+ migrates functions one at a time. + * + * Why lazy: instantiating NeuralLearningSystem pulls in @ruvector/sona and + * a few transitive WASM modules — not free at process startup. The bridge + * defers until something actually asks for it. + */ + +import type { NeuralLearningSystem, SONAMode } from '@claude-flow/neural'; + +let pkgInstance: NeuralLearningSystem | null = null; +let pkgInitPromise: Promise | null = null; +let pkgInitFailed = false; + +/** + * Lazy-load + initialize the @claude-flow/neural NeuralLearningSystem. Returns + * null if the package isn't resolvable (defensive — the package is in cli's + * regular dependencies, but environments with --ignore-scripts or pnpm prune + * can leave it unavailable). Idempotent across calls. + */ +export async function getNeuralPackage(mode: SONAMode = 'balanced'): Promise { + if (pkgInstance) return pkgInstance; + if (pkgInitFailed) return null; + if (pkgInitPromise) return pkgInitPromise; + + pkgInitPromise = (async () => { + try { + const m = await import('@claude-flow/neural'); + const sys = m.createNeuralLearningSystem(mode); + await sys.initialize(); + pkgInstance = sys; + return sys; + } catch (err) { + // CLAUDE_FLOW_DEBUG-gated log so future regressions of this shape + // don't disappear silently — same convention as the ruvllm coordinator + // bridge (#1770). + if (process.env.CLAUDE_FLOW_DEBUG) { + // eslint-disable-next-line no-console + console.error('[neural-package] @claude-flow/neural load failed:', (err as Error).message); + } + pkgInitFailed = true; + return null; + } + })(); + + return pkgInitPromise; +} + +/** + * Quick "is the package available?" probe without forcing initialization. + * Returns true if a previous getNeuralPackage() call succeeded; null if + * never tried or failed. Useful for dashboards that want to surface package + * status without triggering load. + */ +export function isNeuralPackageLoaded(): boolean { + return pkgInstance !== null; +} + +/** + * Get aggregated stats from the neural package alongside cli's local stats. + * Returns null if the package isn't loaded — caller should fall back to + * local-only stats. The return shape mirrors the package's NeuralLearningSystem + * .getStats() output: { sona, reasoningBank, patternLearner }. + */ +export async function getNeuralPackageStats(): Promise | null> { + const sys = await getNeuralPackage(); + return sys ? sys.getStats() : null; +} + +/** + * Reset the bridge (mainly for tests). Drops the cached instance and + * forgets any prior init failure so the next getNeuralPackage() retries. + */ +export function resetNeuralPackageBridge(): void { + pkgInstance = null; + pkgInitPromise = null; + pkgInitFailed = false; +} diff --git a/v3/@claude-flow/neural/README.md b/v3/@claude-flow/neural/README.md index 2d83440b79..13ed9009f7 100644 --- a/v3/@claude-flow/neural/README.md +++ b/v3/@claude-flow/neural/README.md @@ -4,256 +4,218 @@ [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/neural.svg)](https://www.npmjs.com/package/@claude-flow/neural) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/) -[![AI Learning](https://img.shields.io/badge/AI-Self--Learning-purple.svg)](https://github.com/ruvnet/claude-flow) -> Self-Optimizing Neural Architecture (SONA) module for Claude Flow V3 - adaptive learning, trajectory tracking, and pattern-based optimization. +> Self-Optimizing Neural Architecture (SONA) for Claude Flow V3 — adaptive learning, trajectory tracking, pattern reuse, and 7 RL algorithms in a single package. -## Features +## What this is -- **SONA Learning** - Self-Optimizing Neural Architecture with <0.05ms adaptation time -- **5 Learning Modes** - Real-time, Balanced, Research, Edge, and Batch modes -- **9 RL Algorithms** - PPO, A2C, DQN, Q-Learning, SARSA, Decision Transformer, and more -- **LoRA Integration** - Low-Rank Adaptation for efficient fine-tuning -- **EWC++ Memory** - Elastic Weight Consolidation for continual learning without forgetting -- **Trajectory Tracking** - Record and learn from agent execution paths -- **Pattern Recognition** - Automatic pattern extraction and reuse +A self-contained learning module that records agent execution trajectories, distills them into reusable patterns, retrieves matches for new tasks, and adapts via SONA + LoRA + EWC++. Designed to be the substrate that the Claude Flow CLI's intelligence layer composes onto — the package owns the algorithms, the CLI owns the orchestration. -## Installation +## Install ```bash npm install @claude-flow/neural ``` -## Quick Start +## Quick start (recommended) + +`NeuralLearningSystem` is the high-level entry point — it wires `SONAManager`, `ReasoningBank`, and `PatternLearner` together so callers don't have to: ```typescript -import { SONAManager, createSONAManager } from '@claude-flow/neural'; +import { createNeuralLearningSystem } from '@claude-flow/neural'; + +const sys = createNeuralLearningSystem('balanced'); +await sys.initialize(); + +// Track a task +const id = sys.beginTask('Refactor auth middleware', 'code'); + +// Record steps as the agent works (Float32Array embeddings) +sys.recordStep(id, 'analyzed-imports', 0.8, embedding1); +sys.recordStep(id, 'extracted-helpers', 0.9, embedding2); + +// Complete — fires distillation + pattern extraction automatically +await sys.completeTask(id, /* qualityScore */ 0.85); + +// Retrieve relevant memories for the next similar task +const memories = await sys.retrieveMemories(queryEmbedding, /* k */ 3); +const patterns = await sys.findPatterns(queryEmbedding, 3); + +// Periodic learning sweep (consolidation + EWC) +await sys.triggerLearning(); + +console.log(sys.getStats()); +// → { sona: NeuralStats, reasoningBank: { ... }, patternLearner: { ... } } +``` + +## Lower-level API: SONA Manager + +For callers that want to manage trajectories and patterns directly: + +```typescript +import { createSONAManager, type Trajectory } from '@claude-flow/neural'; -// Create SONA manager const sona = createSONAManager('balanced'); await sona.initialize(); -// Begin trajectory tracking -const trajectoryId = sona.beginTrajectory('code-review-task', 'development'); +// domain ∈ 'code' | 'creative' | 'reasoning' | 'chat' | 'math' | 'general' +const trajectoryId = sona.beginTrajectory('code-review-task', 'code'); -// Record steps -sona.recordStep(trajectoryId, 'analyze-code', 0.8, stateEmbedding, { - filesAnalyzed: 5, - issuesFound: 2 -}); +sona.recordStep(trajectoryId, 'analyze-code', 0.8, stateEmbedding); +sona.recordStep(trajectoryId, 'generate-feedback', 0.9, nextStateEmbedding); -sona.recordStep(trajectoryId, 'generate-feedback', 0.9, newStateEmbedding); +const trajectory: Trajectory = sona.completeTrajectory(trajectoryId, 0.85); -// Complete trajectory -const trajectory = sona.completeTrajectory(trajectoryId); +// Query patterns +const matches = await sona.findSimilarPatterns(contextEmbedding, /* k */ 3); -// Find similar patterns for guidance -const patterns = await sona.findSimilarPatterns(contextEmbedding, 3); -``` - -## Learning Modes - -| Mode | Adaptation | Quality | Memory | Use Case | -|------|------------|---------|--------|----------| -| **real-time** | <0.5ms | 70%+ | 25MB | Production, low-latency | -| **balanced** | <18ms | 75%+ | 50MB | General purpose | -| **research** | <100ms | 95%+ | 100MB | Deep exploration | -| **edge** | <1ms | 80%+ | 5MB | Resource-constrained | -| **batch** | <50ms | 85%+ | 75MB | High-throughput | - -```typescript -// Switch modes dynamically -await sona.setMode('research'); - -// Get current configuration -const { mode, config, optimizations } = sona.getConfig(); -``` - -## API Reference - -### SONA Manager - -```typescript -import { SONAManager } from '@claude-flow/neural'; - -const sona = new SONAManager('balanced'); -await sona.initialize(); - -// Trajectory Management -const trajectoryId = sona.beginTrajectory(context, domain); -sona.recordStep(trajectoryId, action, reward, stateEmbedding, metadata); -const trajectory = sona.completeTrajectory(trajectoryId, finalQuality); - -// Pattern Matching -const patterns = await sona.findSimilarPatterns(embedding, k); -const pattern = sona.storePattern({ name, strategy, embedding, domain }); -sona.updatePatternUsage(patternId, quality); - -// Learning +// Trigger consolidation manually await sona.triggerLearning('manual'); -const output = await sona.applyAdaptations(input, domain); - -// Statistics -const stats = sona.getStats(); -``` - -### RL Algorithms - -```typescript -import { PPO, A2C, DQN, QLearning, SARSA, DecisionTransformer } from '@claude-flow/neural'; - -// Proximal Policy Optimization -const ppo = new PPO({ - learningRate: 0.0003, - epsilon: 0.2, - valueCoef: 0.5 -}); - -// Advantage Actor-Critic -const a2c = new A2C({ - learningRate: 0.001, - gamma: 0.99, - entropyCoef: 0.01 -}); - -// Deep Q-Network -const dqn = new DQN({ - learningRate: 0.001, - gamma: 0.99, - epsilon: 0.1, - targetUpdateFreq: 100 -}); - -// Decision Transformer -const dt = new DecisionTransformer({ - contextLength: 20, - embeddingDim: 256, - numHeads: 4 -}); -``` - -### LoRA Configuration - -```typescript -// Get LoRA config for current mode -const loraConfig = sona.getLoRAConfig(); -// { -// rank: 4, -// alpha: 8, -// dropout: 0.05, -// targetModules: ['q_proj', 'v_proj', 'k_proj', 'o_proj'], -// microLoRA: false -// } - -// Initialize LoRA weights for a domain -const weights = sona.initializeLoRAWeights('code-generation'); -``` - -### EWC++ (Elastic Weight Consolidation) - -```typescript -// Get EWC config -const ewcConfig = sona.getEWCConfig(); -// { -// lambda: 2000, -// decay: 0.9, -// fisherSamples: 100, -// minFisher: 1e-8, -// online: true -// } - -// Consolidate after learning a new task sona.consolidateEWC(); ``` -### Event System +## Learning modes + +| Mode | Adaptation | Quality | Memory | Use case | +|------|-----------:|--------:|-------:|----------| +| **real-time** | <0.5ms | 70%+ | 25 MB | Production, low-latency | +| **balanced** (default) | <18ms | 75%+ | 50 MB | General purpose | +| **research** | <100ms | 95%+ | 100 MB | Deep exploration | +| **edge** | <1ms | 80%+ | 5 MB | Resource-constrained | +| **batch** | <50ms | 85%+ | 75 MB | High-throughput | ```typescript -// Subscribe to neural events -sona.addEventListener((event) => { +await sys.setMode('research'); // or directly: await sona.setMode('research') +``` + +## ReasoningBank + PatternLearner (separately accessible) + +`NeuralLearningSystem` composes them; you can also use them standalone: + +```typescript +import { + createReasoningBank, + createPatternLearner, + createSONALearningEngine, +} from '@claude-flow/neural'; + +const bank = createReasoningBank(); +await bank.storeTrajectory(trajectory); +await bank.judge(trajectory); +const distilled = await bank.distill(trajectory); + +const learner = createPatternLearner(); +learner.extractPattern(trajectory, distilled); +const matches = await learner.findMatches(queryEmbedding, 5); + +const engine = createSONALearningEngine(); +const adapted = await engine.adapt(input, /* domain */ 'code'); +``` + +## RL algorithms (7 included) + +Imports use the `Algorithm` suffix where applicable: + +```typescript +import { + PPOAlgorithm, createPPO, DEFAULT_PPO_CONFIG, + A2CAlgorithm, createA2C, DEFAULT_A2C_CONFIG, + DQNAlgorithm, createDQN, DEFAULT_DQN_CONFIG, + QLearning, createQLearning, DEFAULT_QLEARNING_CONFIG, + SARSAAlgorithm, createSARSA, DEFAULT_SARSA_CONFIG, + DecisionTransformer, createDecisionTransformer, DEFAULT_DT_CONFIG, + CuriosityModule, createCuriosity, DEFAULT_CURIOSITY_CONFIG, +} from '@claude-flow/neural'; + +const ppo = createPPO({ learningRate: 0.0003, epsilon: 0.2, valueCoef: 0.5 }); +const dqn = createDQN({ learningRate: 0.001, gamma: 0.99, epsilon: 0.1, targetUpdateFreq: 100 }); + +// Generic factory — pick algorithm by name +import { createAlgorithm, getDefaultConfig } from '@claude-flow/neural'; +const algo = createAlgorithm('ppo', getDefaultConfig('ppo')); +``` + +## LoRA configuration + +```typescript +const config = sona.getLoRAConfig(); +// { rank: 4, alpha: 8, dropout: 0.05, targetModules: ['q_proj','v_proj','k_proj','o_proj'], microLoRA: false } + +const weights = sona.initializeLoRAWeights('code-generation'); +``` + +## EWC++ (Elastic Weight Consolidation) + +Prevents catastrophic forgetting when adapting to new domains: + +```typescript +const config = sona.getEWCConfig(); +// { lambda: 2000, decay: 0.9, fisherSamples: 100, minFisher: 1e-8, online: true } + +// After learning a new task, consolidate before moving on +sona.consolidateEWC(); +``` + +## Event system + +```typescript +sys.addEventListener((event) => { switch (event.type) { - case 'trajectory_started': - console.log(`Started: ${event.trajectoryId}`); - break; - case 'trajectory_completed': - console.log(`Completed with quality: ${event.qualityScore}`); - break; - case 'pattern_matched': - console.log(`Pattern ${event.patternId} matched`); - break; - case 'learning_triggered': - console.log(`Learning: ${event.reason}`); - break; - case 'mode_changed': - console.log(`Mode: ${event.fromMode} -> ${event.toMode}`); - break; + case 'trajectory_started': console.log(`Started: ${event.trajectoryId}`); break; + case 'trajectory_completed': console.log(`Quality: ${event.qualityScore}`); break; + case 'pattern_matched': console.log(`Pattern ${event.patternId} matched`); break; + case 'learning_triggered': console.log(`Learning: ${event.reason}`); break; + case 'mode_changed': console.log(`${event.fromMode} → ${event.toMode}`); break; } }); ``` -## Mode Configurations - -```typescript -// Real-time mode (ultra-fast) -{ - loraRank: 2, - learningRate: 0.001, - batchSize: 32, - trajectoryCapacity: 1000, - qualityThreshold: 0.7, - maxLatencyMs: 0.5 -} - -// Research mode (high quality) -{ - loraRank: 16, - learningRate: 0.002, - batchSize: 64, - trajectoryCapacity: 10000, - qualityThreshold: 0.2, - maxLatencyMs: 100 -} -``` - -## Performance Targets +## Performance targets | Metric | Target | Typical | |--------|--------|---------| -| Adaptation latency | <0.05ms | 0.02ms | -| Pattern retrieval | <1ms | 0.5ms | -| Learning step | <10ms | 5ms | -| Quality improvement | +55% | +40-60% | -| Memory overhead | <50MB | 25-75MB | +| Adaptation latency | <0.05 ms | 0.02 ms | +| Pattern retrieval | <1 ms | 0.5 ms | +| Learning step | <10 ms | 5 ms | +| Quality improvement | +55% | +40–60% | +| Memory overhead | <50 MB | 25–75 MB | -## TypeScript Types +## TypeScript types ```typescript import type { - SONAMode, - SONAModeConfig, - Trajectory, - TrajectoryStep, - Pattern, - PatternMatch, - NeuralStats, - NeuralEvent, - LoRAConfig, - LoRAWeights, - EWCConfig, - RLAlgorithm + // Core + SONAMode, SONAModeConfig, ModeOptimizations, + Trajectory, TrajectoryStep, TrajectoryVerdict, DistilledMemory, + Pattern, PatternMatch, PatternEvolution, + + // RL + RLAlgorithm, RLConfig, + PPOConfig, DQNConfig, A2CConfig, QLearningConfig, SARSAConfig, + DecisionTransformerConfig, CuriosityConfig, + + // Neural + LoRAConfig, LoRAWeights, EWCConfig, EWCState, + NeuralStats, NeuralEvent, NeuralEventListener, } from '@claude-flow/neural'; ``` +## Integration with `@claude-flow/cli` + +The CLI's intelligence layer (`hooks_intelligence_*`, `neural_*` MCP tools, `/intelligence` dashboard) is the primary consumer. Phase 1 of the convergence (#1773) adds a thin bridge in `cli/src/memory/neural-package-bridge.ts` that lazy-loads `NeuralLearningSystem` so cli's intelligence handlers can call into the package surface alongside the existing local implementation. Future phases migrate cli's `LocalSonaCoordinator` and `LocalReasoningBank` to wrap this package's `SONALearningEngine` and `ReasoningBankAdapter`. + +If you're building a Ruflo plugin that wants neural learning, depend on `@claude-flow/neural` directly rather than reaching into cli internals. + ## Dependencies -- [@claude-flow/memory](../memory) - Memory integration -- `@ruvector/sona` - SONA learning engine +- [`@claude-flow/memory`](../memory) — vector memory for patterns +- `@ruvector/sona` — SONA learning engine -## Related Packages +## Related packages -- [@claude-flow/memory](../memory) - Vector memory for patterns -- [@claude-flow/integration](../integration) - agentic-flow integration -- [@claude-flow/performance](../performance) - Benchmarking +- [`@claude-flow/memory`](../memory) — memory backend +- [`@claude-flow/cli`](../cli) — primary consumer + MCP tool surface +- [`@claude-flow/cli-core`](../cli-core) — lite path (no neural; for plugin scripts) ## License diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml index 0599ecc218..213c4fb959 100644 --- a/v3/pnpm-lock.yaml +++ b/v3/pnpm-lock.yaml @@ -52,7 +52,7 @@ importers: dependencies: '@claude-flow/cli': specifier: '>=3.5.0' - version: link:../cli + version: 3.6.30(@types/node@20.19.27)(zod@3.25.76) agent-browser: specifier: ^0.6.0 version: 0.6.0 @@ -106,6 +106,9 @@ importers: '@claude-flow/mcp': specifier: ^3.0.0-alpha.8 version: link:../mcp + '@claude-flow/neural': + specifier: ^3.0.0-alpha.7 + version: link:../neural '@claude-flow/shared': specifier: ^3.0.0-alpha.7 version: link:../shared @@ -184,7 +187,7 @@ importers: dependencies: '@claude-flow/cli': specifier: ^3.0.0-alpha.1 - version: link:../cli + version: 3.6.30(@types/node@20.19.27)(zod@3.25.76) '@iarna/toml': specifier: ^2.2.5 version: 2.2.5 @@ -734,6 +737,229 @@ packages: resolution: {integrity: sha512-k7vvKPbf7J2fZ5klGRD9AeKfUvojuZIQ3BT5u7Jfv+puwXkUBUT5PVyMDfJZpy30CBDXGMgw7fguK/lpOMBvgw==} dev: false + /@claude-flow/aidefence@3.0.2(agentdb@3.0.0-alpha.11): + resolution: {integrity: sha512-jyZa1axjjqtYyS1AbnW0fPuzKBUqRH4SnTOTJZLm5Q6E7qX7A/IG7JcZVEeyipHSl9rFfc6Tj91bC1EoV4GMQg==} + engines: {node: '>=18.0.0'} + requiresBuild: true + peerDependencies: + agentdb: '>=2.0.0-alpha.1' + peerDependenciesMeta: + agentdb: + optional: true + dependencies: + agentdb: 3.0.0-alpha.11(@types/node@20.19.27)(zod@3.25.76) + dev: false + optional: true + + /@claude-flow/cli@3.6.30(@types/node@20.19.27)(zod@3.25.76): + resolution: {integrity: sha512-idELjIUVhqgyoJ3H1s7sSolzps22ahfOH6aJg/ypyrW2SJyXxiobHL6OL0j/w70gs4L78QbSLouG8d9HwwXL3A==} + hasBin: true + requiresBuild: true + dependencies: + '@claude-flow/mcp': 3.0.0-alpha.8 + '@claude-flow/shared': 3.0.0-alpha.7 + '@noble/ed25519': 2.3.0 + '@ruvector/rabitq-wasm': 0.1.0 + semver: 7.7.4 + optionalDependencies: + '@claude-flow/aidefence': 3.0.2(agentdb@3.0.0-alpha.11) + '@claude-flow/codex': 3.0.0-alpha.9(@claude-flow/cli@3.6.30)(@types/node@20.19.27) + '@claude-flow/embeddings': 3.0.0-alpha.15(@claude-flow/shared@3.0.0-alpha.7)(agentic-flow@3.0.0-alpha.2) + '@claude-flow/guidance': 3.0.0-alpha.2(@types/node@20.19.27)(zod@3.25.76) + '@claude-flow/memory': 3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76) + '@claude-flow/plugin-gastown-bridge': 0.1.3(@claude-flow/memory@3.0.0-alpha.14) + '@claude-flow/security': 3.0.0-alpha.1 + '@ruvector/attention': 0.1.32 + '@ruvector/attention-darwin-arm64': 0.1.32 + '@ruvector/diskann': 0.1.0 + '@ruvector/learning-wasm': 0.1.29 + '@ruvector/router': 0.1.30 + '@ruvector/ruvllm-wasm': 2.0.2 + '@ruvector/rvagent-wasm': 0.1.0 + '@ruvector/sona': 0.1.6 + agentdb: 3.0.0-alpha.11(@types/node@20.19.27)(zod@3.25.76) + agentic-flow: 3.0.0-alpha.2 + transitivePeerDependencies: + - '@cfworker/json-schema' + - '@modelcontextprotocol/sdk' + - '@types/node' + - '@valibot/to-json-schema' + - arktype + - bare-abort-controller + - bare-buffer + - bufferutil + - debug + - effect + - encoding + - jose + - react-native-b4a + - supports-color + - sury + - utf-8-validate + - zod + dev: false + + /@claude-flow/codex@3.0.0-alpha.9(@claude-flow/cli@3.6.30)(@types/node@20.19.27): + resolution: {integrity: sha512-6xkeNbzo38l6Kx6hayLQe/olCBK7wq9AYTAtFKBuloU03oYP4tmb5aTMBAcp9ZSsbugCIf3SRBJZiD/1hogK4A==} + engines: {node: '>=18'} + hasBin: true + requiresBuild: true + peerDependencies: + '@claude-flow/cli': ^3.0.0-alpha.1 + peerDependenciesMeta: + '@claude-flow/cli': + optional: true + dependencies: + '@claude-flow/cli': 3.6.30(@types/node@20.19.27)(zod@3.25.76) + '@iarna/toml': 2.2.5 + chalk: 5.6.2 + commander: 12.1.0 + fs-extra: 11.3.3 + inquirer: 9.3.8(@types/node@20.19.27) + toml: 3.0.0 + yaml: 2.8.2 + transitivePeerDependencies: + - '@types/node' + dev: false + optional: true + + /@claude-flow/embeddings@3.0.0-alpha.15(@claude-flow/shared@3.0.0-alpha.7)(agentic-flow@3.0.0-alpha.2): + resolution: {integrity: sha512-lBL20Ow/8c8chlSOgtHTnq7f+tnPItSFqKHNM+8q7wHJYqwVmQPSizrCvzdzwse7Y61YeZfafVfpWFOq9jDQnA==} + engines: {node: '>=20.0.0'} + requiresBuild: true + peerDependencies: + '@claude-flow/shared': ^3.0.0-alpha.1 + agentic-flow: ^2.0.0 + peerDependenciesMeta: + '@huggingface/transformers': + optional: true + agentic-flow: + optional: true + dependencies: + '@claude-flow/shared': 3.0.0-alpha.7 + '@xenova/transformers': 2.17.2 + agentic-flow: 3.0.0-alpha.2 + sql.js: 1.14.1 + optionalDependencies: + '@huggingface/transformers': 4.2.0 + transitivePeerDependencies: + - bare-abort-controller + - bare-buffer + - react-native-b4a + dev: false + optional: true + + /@claude-flow/guidance@3.0.0-alpha.2(@types/node@20.19.27)(zod@3.25.76): + resolution: {integrity: sha512-ocP0b9acMtBsSSg7XdK7BDaBqbFj1rkZNqEr+QyteNiQ4fxO/ooARGuvd959Qlz+Z17Vhb15Y2EOGbAh00u9sA==} + engines: {node: '>=20.0.0'} + requiresBuild: true + dependencies: + '@claude-flow/hooks': 3.0.0-alpha.7(@claude-flow/shared@3.0.0-alpha.7)(@types/node@20.19.27) + '@claude-flow/memory': 3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76) + '@claude-flow/shared': 3.0.0-alpha.7 + transitivePeerDependencies: + - '@cfworker/json-schema' + - '@types/node' + - bare-abort-controller + - bare-buffer + - react-native-b4a + - supports-color + - zod + dev: false + optional: true + + /@claude-flow/hooks@3.0.0-alpha.7(@claude-flow/shared@3.0.0-alpha.7)(@types/node@20.19.27): + resolution: {integrity: sha512-/1RKlhVvHUIMG268vwuzm2cQkqCfyZ9IbpKFYbJjILqwHEDEdOoqwJFnyGhWzZVt3qyu2sSirUunr2estnNHEg==} + engines: {node: '>=20.0.0'} + hasBin: true + requiresBuild: true + peerDependencies: + '@claude-flow/shared': ^3.0.0-alpha.1 + dependencies: + '@claude-flow/memory': 3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76) + '@claude-flow/neural': 3.0.0-alpha.7(@types/node@20.19.27)(zod@3.25.76) + '@claude-flow/shared': 3.0.0-alpha.7 + zod: 3.25.76 + optionalDependencies: + better-sqlite3: 11.10.0 + transitivePeerDependencies: + - '@cfworker/json-schema' + - '@types/node' + - bare-abort-controller + - bare-buffer + - react-native-b4a + - supports-color + dev: false + optional: true + + /@claude-flow/mcp@3.0.0-alpha.8: + resolution: {integrity: sha512-lP1t8GMWDl9RxnwMZrjMukZkyglhge7Znhj1PbUiUQ94kHcN+dAxUkA75HM1n7BONbIDcE/CS8qN2ril5KgzNg==} + dependencies: + ajv: 8.18.0 + cors: 2.8.6 + express: 4.22.1 + helmet: 7.2.0 + ws: 8.19.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + dev: false + + /@claude-flow/memory@3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76): + resolution: {integrity: sha512-T93T5ZSo2NN4EN+/CMC3+BADAkzsQ4XaUbE0/g5F+baz0XLbKhji5P+/fNAe1FByzsjAyR64GLUnZzyHExFOIw==} + cpu: [x64, arm64] + os: [darwin, linux, win32] + requiresBuild: true + dependencies: + agentdb: 3.0.0-alpha.11(@types/node@20.19.27)(zod@3.25.76) + better-sqlite3: 11.10.0 + sql.js: 1.14.1 + transitivePeerDependencies: + - '@cfworker/json-schema' + - '@types/node' + - bare-abort-controller + - bare-buffer + - react-native-b4a + - supports-color + - zod + dev: false + optional: true + + /@claude-flow/neural@3.0.0-alpha.7(@types/node@20.19.27)(zod@3.25.76): + resolution: {integrity: sha512-OsL/IPMa62S3pwRo0EZ5tAbEdyhD6ALrUZdEj5o6MTPmFt5Xn6PD5uWcX2C5yEMCG/sAIM+Lpb3MDKqIi9avHA==} + requiresBuild: true + dependencies: + '@claude-flow/memory': 3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76) + '@ruvector/sona': 0.1.6 + transitivePeerDependencies: + - '@cfworker/json-schema' + - '@types/node' + - bare-abort-controller + - bare-buffer + - react-native-b4a + - supports-color + - zod + dev: false + optional: true + + /@claude-flow/plugin-gastown-bridge@0.1.3(@claude-flow/memory@3.0.0-alpha.14): + resolution: {integrity: sha512-ZHqtgiZOIa0lHelPZ8AWeiW99a84t5PmMY2U90Jp5Iqd/m/P2VIAY0CmHAWEPo1oomTu0NulJFtoblto8K9U9w==} + engines: {node: '>=20.0.0'} + requiresBuild: true + peerDependencies: + '@claude-flow/memory': '>=3.0.0-alpha.1' + peerDependenciesMeta: + '@claude-flow/memory': + optional: true + dependencies: + '@claude-flow/memory': 3.0.0-alpha.14(@types/node@20.19.27)(zod@3.25.76) + '@iarna/toml': 2.2.5 + uuid: 9.0.1 + zod: 3.25.76 + dev: false + optional: true + /@claude-flow/plugin-gastown-bridge@0.1.3(@claude-flow/memory@@claude-flow+memory): resolution: {integrity: sha512-ZHqtgiZOIa0lHelPZ8AWeiW99a84t5PmMY2U90Jp5Iqd/m/P2VIAY0CmHAWEPo1oomTu0NulJFtoblto8K9U9w==} engines: {node: '>=20.0.0'} @@ -751,6 +977,24 @@ packages: dev: false optional: true + /@claude-flow/security@3.0.0-alpha.1: + resolution: {integrity: sha512-/I0HRJC9gZx19VJhr5wBST8VOaM/UOU62dN1SnWb3Vo/B6L20cm/f3owFgcc27j/aqPUD+DCoK5C/2oKbGLiaw==} + requiresBuild: true + dependencies: + bcrypt: 5.1.1 + zod: 3.25.76 + transitivePeerDependencies: + - encoding + - supports-color + dev: false + optional: true + + /@claude-flow/shared@3.0.0-alpha.7: + resolution: {integrity: sha512-5iehTHguBFjlyZqy+fRoKfZVL/nFeE93A94nUUKJvu8y7AmhfpVqtQAZbmKztwQGJ5rv7iBb3Kwl1MUo3K5QkA==} + dependencies: + sql.js: 1.14.1 + dev: false + /@cognitum-one/sdk@0.2.1(multicast-dns@7.2.5): resolution: {integrity: sha512-ZIYKq6Tqc7zcDQRSrxphm0Uji497Mf1bi7azn2aTM4F0k+IEdPpTmAngGVaXX/hR7DYhOQ5gkUCja0DiOJLOJw==} engines: {node: '>=18'} @@ -4500,7 +4744,6 @@ packages: '@ruvector/router-linux-x64-gnu': 0.1.30 '@ruvector/router-win32-x64-msvc': 0.1.30 dev: false - optional: true /@ruvector/ruvllm-darwin-arm64@0.2.0: resolution: {integrity: sha512-3oEMNEoGJqfTJXf1Th49HPTlETMxLzlBc1yBY1RqCMoqSrNKsM66+3Npx0O/GdYfFnKRU2wa/mlLPuBY2lUqYQ==} @@ -5898,7 +6141,7 @@ packages: '@ruvector/attention': 0.1.32 '@ruvector/gnn': 0.1.25 '@ruvector/graph-node': 0.1.26 - '@ruvector/router': 0.1.26 + '@ruvector/router': 0.1.30 '@ruvector/ruvllm': 0.2.4 '@ruvector/sona': 0.1.6 ajv: 8.17.1 @@ -7185,7 +7428,7 @@ packages: conventional-commits-filter: 5.0.0 handlebars: 4.7.8 meow: 13.2.0 - semver: 7.7.3 + semver: 7.7.4 /conventional-commits-filter@5.0.0: resolution: {integrity: sha512-tQMagCOC59EVgNZcC5zl7XqO30Wki9i9J3acbUvkaosCT6JX3EeFwJD7Qqp4MCikRnzS18WXV3BLIQ66ytu6+Q==} @@ -8452,7 +8695,7 @@ packages: es6-error: 4.1.1 matcher: 3.0.0 roarr: 2.15.4 - semver: 7.7.3 + semver: 7.7.4 serialize-error: 7.0.1 dev: false optional: true @@ -9145,7 +9388,7 @@ packages: lodash.isstring: 4.0.1 lodash.once: 4.1.1 ms: 2.1.3 - semver: 7.7.3 + semver: 7.7.4 dev: false /jwa@2.0.1: @@ -9739,7 +9982,7 @@ packages: resolution: {integrity: sha512-zsFhmbkAzwhTft6nd3VxcG0cvJsT70rL+BIGHWVq5fi6MwGrHwzqKaxXE+Hl2GmnGItnDKPPkO5/LQqjVkIdFg==} engines: {node: '>=10'} dependencies: - semver: 7.7.3 + semver: 7.7.4 dev: false /node-addon-api@5.1.0: @@ -9853,7 +10096,7 @@ packages: engines: {node: ^16.14.0 || >=18.0.0} dependencies: hosted-git-info: 7.0.2 - semver: 7.7.3 + semver: 7.7.4 validate-npm-package-license: 3.0.4 /normalize-package-data@8.0.0: @@ -9861,7 +10104,7 @@ packages: engines: {node: ^20.17.0 || >=22.9.0} dependencies: hosted-git-info: 9.0.2 - semver: 7.7.3 + semver: 7.7.4 validate-npm-package-license: 3.0.4 /normalize-url@8.1.1: @@ -11175,7 +11418,6 @@ packages: resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==} engines: {node: '>=10'} hasBin: true - dev: false /send@0.19.2: resolution: {integrity: sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==} @@ -11499,7 +11741,6 @@ packages: resolution: {integrity: sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A==} requiresBuild: true dev: false - optional: true /sqlite3@5.1.7: resolution: {integrity: sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==}