{"_id":"@aigentic/neural","_rev":"2-17c56f572678493bbf73b9e742124119","name":"@aigentic/neural","dist-tags":{"alpha":"3.0.0-alpha.9","latest":"3.0.0-alpha.9"},"versions":{"3.0.0-alpha.9":{"name":"@aigentic/neural","version":"3.0.0-alpha.9","keywords":["ai","agents","ai-agents","multi-agent","multi-agent-systems","agentic","agentic-ai","agentic-systems","claude-flow","ruflo","claude","claude-code","anthropic","neural","neural-network","neural-networks","sona","self-optimizing","self-improving","adaptive-learning","continual-learning","lifelong-learning","online-learning","reinforcement-learning","rl","deep-rl","ppo","proximal-policy-optimization","dqn","deep-q-network","a2c","advantage-actor-critic","q-learning","sarsa","decision-transformer","curiosity-driven","exploration","policy-gradient","value-function","lora","low-rank-adaptation","ewc","elastic-weight-consolidation","catastrophic-forgetting","flash-attention","fast-attention","mixture-of-experts","moe","expert-routing","trajectory","trajectory-learning","experience-replay","pattern-recognition","pattern-matching","pattern-extraction","pattern-evolution","reasoning","reasoning-bank","reasoning-traces","self-consistency","ensemble","embeddings","vector-embeddings","vector-search","hnsw","semantic-search","cosine-similarity","@aigentic/agentdb","memory","knowledge-distillation","model-compression","quantization","fine-tuning","transfer-learning","meta-learning","mcp","model-context-protocol","llm","llm-agents","agent-orchestration","agent-coordination","ml","machine-learning","typescript","esm","wasm","open-source"],"author":{"url":"https://github.com/ruvnet","name":"ruvnet"},"license":"MIT","_id":"@aigentic/neural@3.0.0-alpha.9","maintainers":[{"name":"aigentic","email":"engineering@aigentic.net"}],"homepage":"https://github.com/ruvnet/ruflo","bugs":{"url":"https://github.com/ruvnet/ruflo/issues"},"dist":{"shasum":"ab392481d4fc77b02be5f68ab5de1e1deff26241","tarball":"https://registry.npmjs.org/@aigentic/neural/-/neural-3.0.0-alpha.9.tgz","fileCount":2,"integrity":"sha512-o3vwBHo1IYyqeQSZso5GF9fJ9xMwjGgf9g6yn4Z/SH03b/TzDkz7TaUWrIabWWw8LdqDXc+NvOalbtkClBPheA==","signatures":[{"sig":"MEUCIQCTo13MptgOzX9IXacXgz1byjnNigs9YT9AvtE5pZZdSgIgVlwvq/nBsKSqvN+7qH1moSWo/+45X/PjrphqEYy3glE=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":12122},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","exports":{".":"./dist/index.js"},"scripts":{"test":"vitest run","build":"tsc"},"_npmUser":{"name":"aigentic","email":"engineering@aigentic.net"},"repository":{"url":"git+https://github.com/ruvnet/ruflo.git","type":"git","directory":"v3/@claude-flow/neural"},"_npmVersion":"11.12.0","description":"Self-Optimizing Neural Architecture (SONA) for Claude Flow — adaptive learning, trajectory tracking, pattern reuse, 7 RL algorithms (PPO/A2C/DQN/Q-Learning/SARSA/Decision Transformer/Curiosity), Flash Attention, MoE routing, LoRA, EWC++ for continual lear","directories":{},"_nodeVersion":"22.22.1","dependencies":{"@aigentic/sona":"^0.1.7","@aigentic/memory":"^3.0.0-alpha.16"},"publishConfig":{"tag":"v3alpha","access":"public"},"_hasShrinkwrap":false,"optionalDependencies":{"@aigentic/agentdb":"^3.0.0-alpha.15"},"_npmOperationalInternal":{"tmp":"tmp/neural_3.0.0-alpha.9_1779262086636_0.6321609985157477","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2026-05-20T07:28:06.531Z","modified":"2026-09-13T15:30:31.415Z","3.0.0-alpha.9":"2026-05-20T07:28:06.788Z"},"bugs":{"url":"https://github.com/ruvnet/ruflo/issues"},"author":{"url":"https://github.com/ruvnet","name":"ruvnet"},"license":"MIT","homepage":"https://github.com/ruvnet/ruflo","keywords":["ai","agents","ai-agents","multi-agent","multi-agent-systems","agentic","agentic-ai","agentic-systems","claude-flow","ruflo","claude","claude-code","anthropic","neural","neural-network","neural-networks","sona","self-optimizing","self-improving","adaptive-learning","continual-learning","lifelong-learning","online-learning","reinforcement-learning","rl","deep-rl","ppo","proximal-policy-optimization","dqn","deep-q-network","a2c","advantage-actor-critic","q-learning","sarsa","decision-transformer","curiosity-driven","exploration","policy-gradient","value-function","lora","low-rank-adaptation","ewc","elastic-weight-consolidation","catastrophic-forgetting","flash-attention","fast-attention","mixture-of-experts","moe","expert-routing","trajectory","trajectory-learning","experience-replay","pattern-recognition","pattern-matching","pattern-extraction","pattern-evolution","reasoning","reasoning-bank","reasoning-traces","self-consistency","ensemble","embeddings","vector-embeddings","vector-search","hnsw","semantic-search","cosine-similarity","@aigentic/agentdb","memory","knowledge-distillation","model-compression","quantization","fine-tuning","transfer-learning","meta-learning","mcp","model-context-protocol","llm","llm-agents","agent-orchestration","agent-coordination","ml","machine-learning","typescript","esm","wasm","open-source"],"repository":{"url":"git+https://github.com/ruvnet/ruflo.git","type":"git","directory":"v3/@claude-flow/neural"},"description":"Self-Optimizing Neural Architecture (SONA) for Claude Flow — adaptive learning, trajectory tracking, pattern reuse, 7 RL algorithms (PPO/A2C/DQN/Q-Learning/SARSA/Decision Transformer/Curiosity), Flash Attention, MoE routing, LoRA, EWC++ for continual lear","maintainers":[{"email":"engineering@aigentic.net","name":"aiggy"}],"readme":"# @claude-flow/neural\n\n[![npm version](https://img.shields.io/npm/v/@claude-flow/neural.svg)](https://www.npmjs.com/package/@claude-flow/neural)\n[![npm downloads](https://img.shields.io/npm/dm/@claude-flow/neural.svg)](https://www.npmjs.com/package/@claude-flow/neural)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)\n\n> Self-Optimizing Neural Architecture (SONA) for Claude Flow V3 — adaptive learning, trajectory tracking, pattern reuse, and 7 RL algorithms in a single package.\n\n## What this is\n\nA 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.\n\n## Install\n\n```bash\nnpm install @claude-flow/neural\n```\n\n> **Note (2026-05-16):** `@claude-flow/neural@3.0.0-alpha.9+` pins\n> `@ruvector/sona` to the exact known-good `0.1.5` because\n> `@ruvector/sona@0.1.6` shipped as an empty publish (README +\n> `package.json` only — no `index.js`, no native bins). Prior alpha.8\n> used `\"latest\"` and broke on every fresh install. The pin will\n> stay until `@ruvector/sona@0.1.7+` ships with content.\n\n## Standalone use (without the Ruflo CLI)\n\n```typescript\n// route a task across 8 specialized experts (MoE) — no other deps\nimport { getMoERouter } from '@claude-flow/neural';\n\nconst router = getMoERouter();\nawait router.initialize();\n\nconst decision = await router.route(\n  new Float32Array(384).fill(0.1),   // task embedding\n  { task: 'optimize-query', complexity: 0.7 },\n);\nconsole.log(decision.expert, decision.confidence);\n// → 'performance', 0.83  (or whichever expert wins)\n```\n\n## Quick start (recommended)\n\n`NeuralLearningSystem` is the high-level entry point — it wires `SONAManager`, `ReasoningBank`, and `PatternLearner` together so callers don't have to:\n\n```typescript\nimport { createNeuralLearningSystem } from '@claude-flow/neural';\n\nconst sys = createNeuralLearningSystem('balanced');\nawait sys.initialize();\n\n// Track a task\nconst id = sys.beginTask('Refactor auth middleware', 'code');\n\n// Record steps as the agent works (Float32Array embeddings)\nsys.recordStep(id, 'analyzed-imports', 0.8, embedding1);\nsys.recordStep(id, 'extracted-helpers',  0.9, embedding2);\n\n// Complete — fires distillation + pattern extraction automatically\nawait sys.completeTask(id, /* qualityScore */ 0.85);\n\n// Retrieve relevant memories for the next similar task\nconst memories = await sys.retrieveMemories(queryEmbedding, /* k */ 3);\nconst patterns = await sys.findPatterns(queryEmbedding, 3);\n\n// Periodic learning sweep (consolidation + EWC)\nawait sys.triggerLearning();\n\nconsole.log(sys.getStats());\n// → { sona: NeuralStats, reasoningBank: { ... }, patternLearner: { ... } }\n```\n\n## Lower-level API: SONA Manager\n\nFor callers that want to manage trajectories and patterns directly:\n\n```typescript\nimport { createSONAManager, type Trajectory } from '@claude-flow/neural';\n\nconst sona = createSONAManager('balanced');\nawait sona.initialize();\n\n// domain ∈ 'code' | 'creative' | 'reasoning' | 'chat' | 'math' | 'general'\nconst trajectoryId = sona.beginTrajectory('code-review-task', 'code');\n\nsona.recordStep(trajectoryId, 'analyze-code',     0.8, stateEmbedding);\nsona.recordStep(trajectoryId, 'generate-feedback', 0.9, nextStateEmbedding);\n\nconst trajectory: Trajectory = sona.completeTrajectory(trajectoryId, 0.85);\n\n// Query patterns\nconst matches = await sona.findSimilarPatterns(contextEmbedding, /* k */ 3);\n\n// Trigger consolidation manually\nawait sona.triggerLearning('manual');\nsona.consolidateEWC();\n```\n\n## Learning modes\n\n| Mode | Adaptation | Quality | Memory | Use case |\n|------|-----------:|--------:|-------:|----------|\n| **real-time** | <0.5ms | 70%+ | 25 MB | Production, low-latency |\n| **balanced** (default) | <18ms | 75%+ | 50 MB | General purpose |\n| **research** | <100ms | 95%+ | 100 MB | Deep exploration |\n| **edge** | <1ms | 80%+ | 5 MB | Resource-constrained |\n| **batch** | <50ms | 85%+ | 75 MB | High-throughput |\n\n```typescript\nawait sys.setMode('research'); // or directly: await sona.setMode('research')\n```\n\n## ReasoningBank + PatternLearner (separately accessible)\n\n`NeuralLearningSystem` composes them; you can also use them standalone:\n\n```typescript\nimport {\n  createReasoningBank,\n  createPatternLearner,\n  createSONALearningEngine,\n} from '@claude-flow/neural';\n\nconst bank = createReasoningBank();\nawait bank.storeTrajectory(trajectory);\nawait bank.judge(trajectory);\nconst distilled = await bank.distill(trajectory);\n\nconst learner = createPatternLearner();\nlearner.extractPattern(trajectory, distilled);\nconst matches = await learner.findMatches(queryEmbedding, 5);\n\nconst engine = createSONALearningEngine();\nconst adapted = await engine.adapt(input, /* domain */ 'code');\n```\n\n## RL algorithms (7 included)\n\nImports use the `Algorithm` suffix where applicable:\n\n```typescript\nimport {\n  PPOAlgorithm,         createPPO,         DEFAULT_PPO_CONFIG,\n  A2CAlgorithm,         createA2C,         DEFAULT_A2C_CONFIG,\n  DQNAlgorithm,         createDQN,         DEFAULT_DQN_CONFIG,\n  QLearning,            createQLearning,   DEFAULT_QLEARNING_CONFIG,\n  SARSAAlgorithm,       createSARSA,       DEFAULT_SARSA_CONFIG,\n  DecisionTransformer,  createDecisionTransformer, DEFAULT_DT_CONFIG,\n  CuriosityModule,      createCuriosity,   DEFAULT_CURIOSITY_CONFIG,\n} from '@claude-flow/neural';\n\nconst ppo = createPPO({ learningRate: 0.0003, epsilon: 0.2, valueCoef: 0.5 });\nconst dqn = createDQN({ learningRate: 0.001, gamma: 0.99, epsilon: 0.1, targetUpdateFreq: 100 });\n\n// Generic factory — pick algorithm by name\nimport { createAlgorithm, getDefaultConfig } from '@claude-flow/neural';\nconst algo = createAlgorithm('ppo', getDefaultConfig('ppo'));\n```\n\n## LoRA configuration\n\n```typescript\nconst config = sona.getLoRAConfig();\n// { rank: 4, alpha: 8, dropout: 0.05, targetModules: ['q_proj','v_proj','k_proj','o_proj'], microLoRA: false }\n\nconst weights = sona.initializeLoRAWeights('code-generation');\n```\n\n## EWC++ (Elastic Weight Consolidation)\n\nPrevents catastrophic forgetting when adapting to new domains:\n\n```typescript\nconst config = sona.getEWCConfig();\n// { lambda: 2000, decay: 0.9, fisherSamples: 100, minFisher: 1e-8, online: true }\n\n// After learning a new task, consolidate before moving on\nsona.consolidateEWC();\n```\n\n## Event system\n\n```typescript\nsys.addEventListener((event) => {\n  switch (event.type) {\n    case 'trajectory_started':  console.log(`Started: ${event.trajectoryId}`); break;\n    case 'trajectory_completed': console.log(`Quality: ${event.qualityScore}`); break;\n    case 'pattern_matched':     console.log(`Pattern ${event.patternId} matched`); break;\n    case 'learning_triggered':  console.log(`Learning: ${event.reason}`); break;\n    case 'mode_changed':        console.log(`${event.fromMode} → ${event.toMode}`); break;\n  }\n});\n```\n\n## Performance targets\n\n| Metric | Target | Typical |\n|--------|--------|---------|\n| Adaptation latency | <0.05 ms | 0.02 ms |\n| Pattern retrieval | <1 ms | 0.5 ms |\n| Learning step | <10 ms | 5 ms |\n| Quality improvement | +55% | +40–60% |\n| Memory overhead | <50 MB | 25–75 MB |\n\n## TypeScript types\n\n```typescript\nimport type {\n  // Core\n  SONAMode, SONAModeConfig, ModeOptimizations,\n  Trajectory, TrajectoryStep, TrajectoryVerdict, DistilledMemory,\n  Pattern, PatternMatch, PatternEvolution,\n\n  // RL\n  RLAlgorithm, RLConfig,\n  PPOConfig, DQNConfig, A2CConfig, QLearningConfig, SARSAConfig,\n  DecisionTransformerConfig, CuriosityConfig,\n\n  // Neural\n  LoRAConfig, LoRAWeights, EWCConfig, EWCState,\n  NeuralStats, NeuralEvent, NeuralEventListener,\n} from '@claude-flow/neural';\n```\n\n## Integration with `@claude-flow/cli`\n\nThe 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`.\n\nIf you're building a Ruflo plugin that wants neural learning, depend on `@claude-flow/neural` directly rather than reaching into cli internals.\n\n## Dependencies\n\n- [`@claude-flow/memory`](../memory) — vector memory for patterns\n- `@ruvector/sona` — SONA learning engine\n\n## Related packages\n\n- [`@claude-flow/memory`](../memory) — memory backend\n- [`@claude-flow/cli`](../cli) — primary consumer + MCP tool surface\n- [`@claude-flow/cli-core`](../cli-core) — lite path (no neural; for plugin scripts)\n\n## License\n\nMIT\n","readmeFilename":"README.md"}