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

fix(cli,ruflo-intelligence): neural_train reports empty, neural_predict has a similarity floor, nested subcommands dispatch at any depth, built-in registry fallback is honest (#4156, #4157)

rae13e393d273
diff --git a/plugins/ruflo-intelligence/.claude-plugin/plugin.json b/plugins/ruflo-intelligence/.claude-plugin/plugin.json
index f6a8dd6c2c..fe219abde3 100644
--- a/plugins/ruflo-intelligence/.claude-plugin/plugin.json
+++ b/plugins/ruflo-intelligence/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-intelligence",
"description": "User-facing surface for Ruflo's self-learning system: 6 neural_* + 10 hooks_intelligence_* + 6 routing/meta hooks + 3 hooks_model-* + 4 SONA/MicroLoRA tools (29 total). Implements the 4-step pipeline (RETRIEVE β†’ JUDGE β†’ DISTILL β†’ CONSOLIDATE) and IPFS-based cross-project pattern transfer.",
- "version": "0.4.4",
+ "version": "0.4.5",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-intelligence/CHANGELOG.md b/plugins/ruflo-intelligence/CHANGELOG.md
index 4daa8ad665..89f64eaee2 100644
--- a/plugins/ruflo-intelligence/CHANGELOG.md
+++ b/plugins/ruflo-intelligence/CHANGELOG.md
@@ -2,6 +2,9 @@
Newest first. One `## <version> β€” <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history.
+## 0.4.5 β€” 2026-10-14
+- fix: neural-train step 6 passes `data` (neural_train only learns from it and now answers `success: false, status: "empty"` without it), and step 8 says `neural_patterns`/`neural_predict` do not see what trajectories, SONA and the ReasoningBank learned (a separate store; check it with `hooks_intelligence_pattern-search` / `hooks_intelligence_stats`) and that `neural_predict` applies a similarity floor (#4156); intelligence-transfer uses the top-level `transfer-store` command (the nested `hooks transfer store <sub>` only printed help) and warns that the built-in genesis registry is an offline placeholder, not signed or popular data (#4157; thanks @ronmikailov)
+
## 0.4.4 β€” 2026-10-12
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
diff --git a/plugins/ruflo-intelligence/scripts/smoke.sh b/plugins/ruflo-intelligence/scripts/smoke.sh
index 5896b047e1..ccb82530e8 100755
--- a/plugins/ruflo-intelligence/scripts/smoke.sh
+++ b/plugins/ruflo-intelligence/scripts/smoke.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Structural smoke test for ruflo-intelligence v0.4.4.
+# Structural smoke test for ruflo-intelligence v0.4.5.
# Per ADR-0001 Β§6 Verification: 13 contract checks + 3 doc invariants.
# Offline-safe; no live MCP calls.
set -u
@@ -27,10 +27,10 @@ grep -qE "IPFS.+pattern|pattern.+IPFS|Pinata" "$ROOT/README.md" \
&& ok || bad "README missing IPFS / Pinata transfer docs"
# 1. plugin.json bump + new keywords
-step "1. plugin.json declares 0.4.4 with new keywords"
+step "1. plugin.json declares 0.4.5 with new keywords"
v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.4.4" ]]; then
- bad "expected 0.4.4, got '$v'"
+if [[ "$v" != "0.4.5" ]]; then
+ bad "expected 0.4.5, got '$v'"
else
miss=""
for k in microlora ewc attention moe pattern-transfer model-routing; do
diff --git a/plugins/ruflo-intelligence/skills/intelligence-transfer/SKILL.md b/plugins/ruflo-intelligence/skills/intelligence-transfer/SKILL.md
index 5b9dab732b..522a57e023 100644
--- a/plugins/ruflo-intelligence/skills/intelligence-transfer/SKILL.md
+++ b/plugins/ruflo-intelligence/skills/intelligence-transfer/SKILL.md
@@ -12,7 +12,7 @@ Two different mechanisms live under "transfer". Pick by where the patterns are.
| Where the patterns are | Mechanism | Needs network |
|---|---|---|
| Another project on this machine | `hooks_transfer` (MCP) or `hooks transfer from-project` (CLI) | no |
-| The shared pattern marketplace (IPFS registry) | `hooks transfer store list|search|download|publish` (CLI) | yes |
+| The shared pattern marketplace (IPFS registry) | `transfer-store list|search|download|publish` (CLI) | yes |
`hooks_transfer` takes `{ sourcePath, filter?, minConfidence? }` and nothing else. It reads the source project's memory store and copies the patterns that pass `minConfidence` (default 0.7). It has no `store`, `load` or CID action; earlier versions of this skill said it did, and it does not.
@@ -32,11 +32,15 @@ The source path is read as data. Do not point it at a directory you do not contr
## Browse and download from the marketplace
```bash
-npx @claude-flow/cli@latest hooks transfer store list --featured
-npx @claude-flow/cli@latest hooks transfer store search --query routing --verified
-npx @claude-flow/cli@latest hooks transfer store download --name PATTERN_NAME --verify
+npx @claude-flow/cli@latest transfer-store list --featured
+npx @claude-flow/cli@latest transfer-store search --query routing --verified
+npx @claude-flow/cli@latest transfer-store download --name PATTERN_NAME --verify
```
+Use the top-level `transfer-store` command. In ruflo 3.56.9 and earlier the nested form `hooks transfer store <sub>` only printed the `store` help and exited 0 without running the subcommand (#4157).
+
+**Offline fallback is not live data.** If the output says `[Discovery] Using built-in genesis registry` (or `OFFLINE MODE`), no registry could be reached and the CLI is showing one built-in placeholder entry (`source: "builtin-fallback"`, `trustLevel: unverified`, no download counts or rating). It is not a signed or popular pattern. Older versions labelled that entry `verified` with invented counts and a `lastUpdated` equal to the current time; do not trust those fields from ruflo 3.56.9 or earlier.
+
Downloads verify a checksum by default. Add `--import` only after you have looked at the downloaded file. The same registry is also reachable from MCP via `transfer_store-search`, `transfer_store-info` and `transfer_store-download`.
## Publish to the marketplace
@@ -48,7 +52,7 @@ Publishing is public and not reversible. Do all of this first:
3. Credentials come from the environment: `PINATA_API_KEY` and `PINATA_API_SECRET` (the upload path reads those two, not a JWT). If they are unset the command fails with a clear error; do not ask the user to paste them into the chat.
```bash
-npx @claude-flow/cli@latest hooks transfer store publish \
+npx @claude-flow/cli@latest transfer-store publish \
--input patterns.cfp --name my-patterns --description "What these patterns capture" \
--categories routing --tags routing,coordination --anonymize strict
```
diff --git a/plugins/ruflo-intelligence/skills/neural-train/SKILL.md b/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
index 934b0c7226..2060feec86 100644
--- a/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
+++ b/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
@@ -2,7 +2,7 @@
name: neural-train
description: Train SONA + MicroLoRA neural patterns from successful task completions; runs the DISTILL + CONSOLIDATE phases of the 4-step pipeline
argument-hint: "[--pattern coordination|optimization|prediction|security|testing] [--epochs N]"
-allowed-tools: mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_status mcp__plugin_ruflo-core_ruflo__neural_patterns mcp__plugin_ruflo-core_ruflo__neural_predict mcp__plugin_ruflo-core_ruflo__neural_optimize mcp__plugin_ruflo-core_ruflo__neural_compress mcp__plugin_ruflo-core_ruflo__hooks_pretrain mcp__plugin_ruflo-core_ruflo__hooks_build-agents mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-start mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn mcp__plugin_ruflo-core_ruflo__hooks_intelligence-reset mcp__plugin_ruflo-core_ruflo__ruvllm_sona_create mcp__plugin_ruflo-core_ruflo__ruvllm_sona_adapt mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_create mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_adapt mcp__plugin_ruflo-core_ruflo__agentdb_consolidate Bash
+allowed-tools: mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_status mcp__plugin_ruflo-core_ruflo__neural_patterns mcp__plugin_ruflo-core_ruflo__neural_predict mcp__plugin_ruflo-core_ruflo__neural_optimize mcp__plugin_ruflo-core_ruflo__neural_compress mcp__plugin_ruflo-core_ruflo__hooks_pretrain mcp__plugin_ruflo-core_ruflo__hooks_build-agents mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-start mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-search mcp__plugin_ruflo-core_ruflo__hooks_intelligence_stats mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn mcp__plugin_ruflo-core_ruflo__hooks_intelligence-reset mcp__plugin_ruflo-core_ruflo__ruvllm_sona_create mcp__plugin_ruflo-core_ruflo__ruvllm_sona_adapt mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_create mcp__plugin_ruflo-core_ruflo__ruvllm_microlora_adapt mcp__plugin_ruflo-core_ruflo__agentdb_consolidate Bash
---
# Neural Training
@@ -22,9 +22,9 @@ Train and consolidate neural patterns. Implements the **DISTILL** and **CONSOLID
3. **Record steps** β€” for each significant action, `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step`.
4. **End trajectory** β€” `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end` with `{ trajectoryId, success: true|false, feedback? }` (the tool takes a boolean `success`, not a verdict string).
5. **Learn from the trajectory** β€” `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_learn` (optionally `{ trajectoryIds: [...] }`). It runs a distill + EWC++ consolidation cycle; `consolidate` defaults to true.
-6. **Train patterns** β€” `mcp__plugin_ruflo-core_ruflo__neural_train` with `{ modelType: "moe", epochs: 10 }` (`modelType` is required: `moe|transformer|classifier|embedding`). The CLI form is `neural train --pattern coordination --epochs 10`.
+6. **Train patterns** β€” `mcp__plugin_ruflo-core_ruflo__neural_train` with `{ modelType: "classifier", data: [{ "text": "<what the task was>", "label": "<outcome or lesson>" }] }` (`modelType` is required: `moe|transformer|classifier|embedding`). It only learns from the `data` you pass: it does not read trajectories, SONA or the ReasoningBank, and without `data` it answers `success: false, status: "empty"` (ruflo 3.56.9 and earlier reported `status: "ready"` with `patternsStored: 0`). The CLI form is `neural train --pattern coordination --epochs 10`.
7. **Store patterns** β€” `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-store`.
-8. **Verify** β€” `mcp__plugin_ruflo-core_ruflo__neural_patterns` to confirm.
+8. **Verify** β€” `mcp__plugin_ruflo-core_ruflo__neural_patterns` with `{ action: "list" }` lists only what `neural_train` stored. What steps 2-5 and 7 learned (trajectories, SONA, ReasoningBank, `hooks_intelligence_pattern-store`) is a separate store: check it with `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_pattern-search` or `hooks_intelligence_stats`, not `neural_patterns` or `neural_predict`. `neural_predict` returns a match only above a cosine-similarity floor (default 0.5, `minSimilarity` to change it) and an empty `predictions` list otherwise.
## SONA adaptation (single-domain, <0.05ms)
diff --git a/v3/@claude-flow/cli/__tests__/command-resolution-depth-4157.test.ts b/v3/@claude-flow/cli/__tests__/command-resolution-depth-4157.test.ts
new file mode 100644
index 0000000000..fa6286a133
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/command-resolution-depth-4157.test.ts
@@ -0,0 +1,66 @@
+/**
+ * #4157: `hooks transfer store search -q routing` printed the `store` help and exited 0.
+ * The dispatcher descended only two subcommand levels below a top-level command, so a
+ * third level (hooks > transfer > store > search) never ran. Resolution now walks the
+ * whole command path.
+ */
+import { describe, expect, it } from 'vitest';
+import { resolveTargetCommand } from '../src/command-resolution.js';
+import { CommandParser } from '../src/parser.js';
+import type { Command } from '../src/types.js';
+
+const leaf = (name: string, aliases?: string[]): Command => ({ name, description: name, aliases, action: async () => ({ success: true }) });
+const group = (name: string, subs: Command[]): Command => ({ name, description: name, subcommands: subs, action: async () => ({ success: true }) });
+
+describe('resolveTargetCommand', () => {
+ const search = leaf('search', ['find']);
+ const tree = group('hooks', [group('transfer', [group('store', [search, leaf('list')]), leaf('from-project')]), leaf('route')]);
+
+ it('reaches a leaf three levels below the top-level command (parser path form)', () => {
+ const { target, args } = resolveTargetCommand(tree, ['hooks', 'transfer', 'store', 'search'], ['routing']);
+ expect(target).toBe(search);
+ expect(args).toEqual(['routing']);
+ });
+
+ it('matches aliases at depth', () => {
+ expect(resolveTargetCommand(tree, ['hooks', 'transfer', 'store', 'find'], []).target).toBe(search);
+ });
+
+ it('still resolves one and two levels', () => {
+ expect(resolveTargetCommand(tree, ['hooks', 'route'], []).target.name).toBe('route');
+ expect(resolveTargetCommand(tree, ['hooks', 'transfer', 'store'], []).target.name).toBe('store');
+ });
+
+ it('walks the positional form when the path only names the top-level command', () => {
+ const { target, args } = resolveTargetCommand(tree, ['hooks'], ['transfer', 'store', 'list', 'extra']);
+ expect(target.name).toBe('list');
+ expect(args).toEqual(['extra']);
+ });
+
+ it('stops at the deepest command that matches and keeps the rest as arguments', () => {
+ const { target, args } = resolveTargetCommand(tree, ['hooks'], ['transfer', 'nope', 'x']);
+ expect(target.name).toBe('transfer');
+ expect(args).toEqual(['nope', 'x']);
+ });
+
+ it('leaves a command without subcommands untouched', () => {
+ const { target, args } = resolveTargetCommand(leaf('status'), ['status'], ['a', 'b']);
+ expect(target.name).toBe('status');
+ expect(args).toEqual(['a', 'b']);
+ });
+});
+
+describe('the real pattern store under hooks > transfer (#4157)', () => {
+ it('dispatches `hooks transfer store search -q routing` to the search subcommand', async () => {
+ // hooks.ts nests the real storeCommand as hooks > transfer > store; build the same shape
+ // without importing hooks.ts (it pulls in the whole CLI).
+ const { storeCommand } = await import('../src/commands/transfer-store.js');
+ const hooks = group('hooks', [group('transfer', [storeCommand])]);
+ const parser = new CommandParser({ allowUnknownFlags: true });
+ parser.registerCommand(hooks);
+ const parsed = parser.parse(['hooks', 'transfer', 'store', 'search', '-q', 'routing']);
+ const { target } = resolveTargetCommand(hooks, parsed.command, parsed.positional);
+ expect(target.name).toBe('search');
+ expect(target).toBe(storeCommand.subcommands!.find((c) => c.name === 'search'));
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/neural-train-empty-and-floor-4156.test.ts b/v3/@claude-flow/cli/__tests__/neural-train-empty-and-floor-4156.test.ts
new file mode 100644
index 0000000000..3fa312c21a
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/neural-train-empty-and-floor-4156.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #4156: neural_train without data stored nothing yet reported status "ready", and
+ * neural_predict returned confidence 1 for a single stored pattern whatever the match.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let dir: string;
+let prevCwd: string;
+beforeEach(() => {
+ prevCwd = process.cwd();
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-4156-'));
+ process.chdir(dir);
+});
+afterEach(() => {
+ process.chdir(prevCwd);
+ rmSync(dir, { recursive: true, force: true });
+});
+
+async function tool(name: string) {
+ const { neuralTools } = await import('../src/mcp-tools/neural-tools.js');
+ const found = neuralTools.find((t) => t.name === name);
+ if (!found) throw new Error(`no tool ${name}`);
+ return found.handler as (input: Record<string, unknown>) => Promise<Record<string, any>>;
+}
+
+describe('neural_train with nothing to learn from (#4156)', () => {
+ it('does not report success or "ready" when no data is passed', async () => {
+ const train = await tool('neural_train');
+ const result = await train({ modelType: 'moe', epochs: 10 });
+ expect(result.success).toBe(false);
+ expect(result.status).toBe('empty');
+ expect(result.patternsStored).toBe(0);
+ expect(String(result.error)).toMatch(/data/i);
+ expect(String(result.error)).toMatch(/hooks_intelligence|separate/i);
+ });
+
+ it('does not report success for an empty data array either', async () => {
+ const train = await tool('neural_train');
+ const result = await train({ modelType: 'classifier', data: [] });
+ expect(result.success).toBe(false);
+ expect(result.status).toBe('empty');
+ });
+
+ it('still trains when data is given', async () => {
+ const train = await tool('neural_train');
+ const result = await train({ modelType: 'classifier', data: [{ text: 'route payment webhook retries', label: 'payments' }] });
+ expect(result.success).toBe(true);
+ expect(result.status).toBe('ready');
+ expect(result.patternsStored).toBe(1);
+ });
+});
+
+describe('neural_predict similarity floor (#4156)', () => {
+ it('does not return a confident prediction for an unrelated input against a single stored pattern', async () => {
+ const train = await tool('neural_train');
+ const predict = await tool('neural_predict');
+ await train({ modelType: 'classifier', data: [{ text: 'route payment webhook retries', label: 'payments' }] });
+ const result = await predict({ input: 'qzx wvut gardening compost schedule for spring tomatoes' });
+ expect(result.success).toBe(true);
+ expect(result.predictions).toEqual([]);
+ expect(result.topPrediction).toBeNull();
+ expect(typeof result.bestSimilarity).toBe('number');
+ expect(String(result._note)).toMatch(/similarity/i);
+ });
+
+ it('still returns the match when the input is the stored text', async () => {
+ const train = await tool('neural_train');
+ const predict = await tool('neural_predict');
+ await train({ modelType: 'classifier', data: [{ text: 'route payment webhook retries', label: 'payments' }] });
+ const result = await predict({ input: 'route payment webhook retries' });
+ expect(result.predictions.length).toBe(1);
+ expect(result.topSimilarity).toBeGreaterThan(0.9);
+ });
+
+ it('lets a caller lower the floor explicitly', async () => {
+ const train = await tool('neural_train');
+ const predict = await tool('neural_predict');
+ await train({ modelType: 'classifier', data: [{ text: 'route payment webhook retries', label: 'payments' }] });
+ const result = await predict({ input: 'qzx wvut gardening compost schedule for spring tomatoes', minSimilarity: -1 });
+ expect(result.predictions.length).toBe(1);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/transfer-store-builtin-fallback-4157.test.ts b/v3/@claude-flow/cli/__tests__/transfer-store-builtin-fallback-4157.test.ts
new file mode 100644
index 0000000000..278939b204
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/transfer-store-builtin-fallback-4157.test.ts
@@ -0,0 +1,38 @@
+/**
+ * #4157: when registry discovery falls back to the built-in entry, the result must say so.
+ * It used to present a placeholder signature as a verified pattern with invented download
+ * counts, a rating, and a lastUpdated stamped with the current time on every call.
+ */
+import { describe, expect, it } from 'vitest';
+import { PatternDiscovery } from '../src/transfer/store/discovery.js';
+
+describe('built-in fallback registry (#4157)', () => {
+ const registry = (new PatternDiscovery() as unknown as { getGenesisRegistry(cid: string): any }).getGenesisRegistry('bafy-test');
+ const entry = registry.patterns[0];
+
+ it('is labelled as a built-in fallback, not live registry data', () => {
+ expect(registry.source).toBe('builtin-fallback');
+ expect(entry.source).toBe('builtin-fallback');
+ });
+
+ it('does not claim verification on a placeholder signature', () => {
+ expect(entry.verified).toBe(false);
+ expect(entry.trustLevel).toBe('unverified');
+ expect(String(entry.signature ?? '')).not.toMatch(/placeholder|genesis-pattern-signature/);
+ expect(registry.authors[0].verified).toBe(false);
+ });
+
+ it('does not invent popularity or freshness', () => {
+ expect(entry.downloads).toBe(0);
+ expect(entry.rating).toBe(0);
+ expect(entry.ratingCount).toBe(0);
+ expect(registry.totalDownloads).toBe(0);
+ const again = (new PatternDiscovery() as unknown as { getGenesisRegistry(cid: string): any }).getGenesisRegistry('bafy-test');
+ expect(again.patterns[0].lastUpdated).toBe(entry.lastUpdated); // a fixed date, not "now"
+ expect(entry.lastUpdated).toBe(entry.createdAt);
+ });
+
+ it('carries no registry signature it did not compute', () => {
+ expect(registry.registrySignature).toBeUndefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/command-resolution.ts b/v3/@claude-flow/cli/src/command-resolution.ts
new file mode 100644
index 0000000000..a398014ea5
--- /dev/null
+++ b/v3/@claude-flow/cli/src/command-resolution.ts
@@ -0,0 +1,40 @@
+/**
+ * Resolve which (sub)command an invocation targets.
+ *
+ * The parser reports the matched command path (for example
+ * ['hooks', 'transfer', 'store', 'search']) and the remaining positional arguments.
+ * Resolution walks the whole path through each command's `subcommands`, so a command
+ * can sit at any depth. #4157: it used to stop two levels below the top-level command,
+ * so `hooks transfer store search` ran the `store` help instead of `search`.
+ */
+import type { Command } from './types.js';
+
+const matches = (sc: Command, name: string): boolean => sc.name === name || !!sc.aliases?.includes(name);
+
+export function resolveTargetCommand(
+ command: Command,
+ commandPath: string[],
+ positional: string[],
+): { target: Command; args: string[] } {
+ let target = command;
+
+ if (commandPath.length > 1 && command.subcommands) {
+ // The parser already removed the path from `positional`.
+ for (const name of commandPath.slice(1)) {
+ const next = target.subcommands?.find((sc) => matches(sc, name));
+ if (!next) break;
+ target = next;
+ }
+ return { target, args: positional };
+ }
+
+ // Positional form: the path only named the top-level command.
+ let args = positional;
+ while (args.length > 0 && target.subcommands) {
+ const next = target.subcommands.find((sc) => matches(sc, args[0]));
+ if (!next) break;
+ target = next;
+ args = args.slice(1);
+ }
+ return { target, args };
+}
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index 4728becc99..775ddda413 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -19,6 +19,7 @@ import { dirname, join } from 'path';
import type { Command, CommandContext, CommandResult, V3Config, CLIError } from './types.js';
import { CommandParser, commandParser } from './parser.js';
import { OutputFormatter, output } from './output.js';
+import { resolveTargetCommand } from './command-resolution.js';
import { commands, commandsByCategory, getCommandsByCategory, commandRegistry, getCommand, getCommandAsync, getCommandNames, getLazyCommandNames, hasCommand } from './commands/index.js';
import { suggestCommand } from './suggest.js';
import { runStartupUpdateCheck } from './update/index.js';
@@ -283,60 +284,11 @@ export class CLI {
process.exit(1);
}
- // Handle subcommand (supports nested subcommands)
- let targetCommand = command;
- let subcommandArgs = positional;
-
- // Process command path (e.g., ['hooks', 'worker', 'list'])
- // Note: When parser includes subcommand in commandPath, positional already excludes it
- if (commandPath.length > 1 && command.subcommands) {
- const subcommandName = commandPath[1];
- const subcommand = command.subcommands.find(
- sc => sc.name === subcommandName || sc.aliases?.includes(subcommandName)
- );
-
- if (subcommand) {
- targetCommand = subcommand;
- // Parser already extracted subcommand from positional, so use as-is
- subcommandArgs = positional;
-
- // Check for nested subcommand (level 2)
- if (commandPath.length > 2 && subcommand.subcommands) {
- const nestedName = commandPath[2];
- const nestedSubcommand = subcommand.subcommands.find(
- sc => sc.name === nestedName || sc.aliases?.includes(nestedName)
- );
- if (nestedSubcommand) {
- targetCommand = nestedSubcommand;
- // Parser already extracted nested subcommand too
- subcommandArgs = positional;
- }
- }
- }
- } else if (positional.length > 0 && command.subcommands) {
- // Check if first positional is a subcommand
- const subcommandName = positional[0];
- const subcommand = command.subcommands.find(
- sc => sc.name === subcommandName || sc.aliases?.includes(subcommandName)
- );
-
- if (subcommand) {
- targetCommand = subcommand;
- subcommandArgs = positional.slice(1);
-
- // Check for nested subcommand (level 2 from positional)
- if (subcommandArgs.length > 0 && subcommand.subcommands) {
- const nestedName = subcommandArgs[0];
- const nestedSubcommand = subcommand.subcommands.find(
- sc => sc.name === nestedName || sc.aliases?.includes(nestedName)
- );
- if (nestedSubcommand) {
- targetCommand = nestedSubcommand;
- subcommandArgs = subcommandArgs.slice(1);
- }
- }
- }
- }
+ // Handle subcommands at any depth (#4157): walk the parsed command path, or the
+ // positional arguments when the path only names the top-level command.
+ const resolved = resolveTargetCommand(command, commandPath, positional);
+ const targetCommand = resolved.target;
+ const subcommandArgs = resolved.args;
// Validate flags
const validationErrors = this.parser.validateFlags(flags, targetCommand);
diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
index 071a07084f..69b71eae26 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts
@@ -503,8 +503,25 @@ export const neuralTools: MCPTool[] = [
}
}
+ // #4156: nothing stored means nothing was trained. Reporting success and "ready" made
+ // callers (the neural-train skill) believe the pattern store had been filled.
+ if (patternsStored === 0) {
+ model.status = 'untrained';
+ model.accuracy = 0;
+ saveNeuralStore(store);
+ return {
+ success: false,
+ status: 'empty',
+ modelId,
+ type: modelType,
+ patternsStored: 0,
+ totalPatterns: Object.keys(store.patterns).length,
+ error: 'neural_train stored nothing: pass `data` (an array of strings or {text, label} entries). It does not read trajectories, SONA or the ReasoningBank: those (hooks_intelligence_*) are a separate store that neural_predict and neural_patterns do not see.',
+ };
+ }
+
model.status = 'ready';
- model.accuracy = patternsStored > 0 ? 1.0 : 0; // accuracy = data stored, not simulated
+ model.accuracy = 1.0; // accuracy = data stored, not simulated
model.trainedAt = new Date().toISOString();
saveNeuralStore(store);
@@ -536,6 +553,7 @@ export const neuralTools: MCPTool[] = [
modelId: { type: 'string', description: 'Model ID to use' },
input: { type: 'string', description: 'Input text or data' },
topK: { type: 'number', description: 'Number of top predictions' },
+ minSimilarity: { type: 'number', description: 'Minimum cosine similarity for a stored pattern to count as a match (default 0.5). A softmax over a single candidate is always 1.0, so without a floor any input matched the only stored pattern with confidence 1' },
},
required: ['input'],
},
@@ -547,6 +565,7 @@ export const neuralTools: MCPTool[] = [
const modelId = input.modelId as string;
const inputText = input.input as string;
const topK = (input.topK as number) || 3;
+ const minSimilarity = typeof input.minSimilarity === 'number' ? input.minSimilarity : 0.5;
// Find model or use default
const model = modelId ? store.models[modelId] : Object.values(store.models).find(m => m.status === 'ready');
@@ -568,10 +587,11 @@ export const neuralTools: MCPTool[] = [
// to 1, and we surface enough metadata to trust the result.
const storedPatterns = Object.values(store.patterns);
let predictions: Array<{ label: string; confidence: number; patternId: string; cosineSimilarity: number }>;
+ let bestSimilarity: number | null = null;
if (storedPatterns.length > 0) {
// Step 1: k-NN with cosine
- const scored = storedPatterns
+ let scored = storedPatterns
.map(p => {
const sim = cosineSimilarity(embedding, p.embedding);
return {
@@ -580,8 +600,10 @@ export const neuralTools: MCPTool[] = [
cosineSimilarity: sim,
};
})
- .sort((a, b) => b.cosineSimilarity - a.cosineSimilarity)
- .slice(0, topK);
+ .sort((a, b) => b.cosineSimilarity - a.cosineSimilarity);
+ bestSimilarity = scored[0]?.cosineSimilarity ?? null;
+ // #4156: only patterns that reach the similarity floor are candidates.
+ scored = scored.filter((c) => c.cosineSimilarity >= minSimilarity).slice(0, topK);
// Step 2: temperature-softmax over the top-K so confidence sums to 1.
// Temperature 0.1 sharpens differences between similar candidates.
@@ -621,8 +643,11 @@ export const neuralTools: MCPTool[] = [
embedding: embedding.slice(0, 8), // Preview of embedding
embeddingDims: embedding.length,
latency,
+ ...(bestSimilarity !== null ? { bestSimilarity: Number(bestSimilarity.toFixed(4)), minSimilarity } : {}),
...(storedPatterns.length === 0 ? {
_note: 'No patterns stored. Train with neural_train(modelType, trainingData) before predicting.',
+ } : predictions.length === 0 ? {
+ _note: `No stored pattern reached the similarity floor (best ${bestSimilarity === null ? 'n/a' : bestSimilarity.toFixed(3)}, floor ${minSimilarity}); pass minSimilarity to lower it.`,
} : {}),
};
},
diff --git a/v3/@claude-flow/cli/src/transfer/store/discovery.ts b/v3/@claude-flow/cli/src/transfer/store/discovery.ts
index 8771c1a762..b20fa8bf91 100644
--- a/v3/@claude-flow/cli/src/transfer/store/discovery.ts
+++ b/v3/@claude-flow/cli/src/transfer/store/discovery.ts
@@ -316,9 +316,12 @@ export class PatternDiscovery {
* Get built-in genesis registry (always available offline)
*/
private getGenesisRegistry(cid: string): PatternRegistry {
+ // #4157: this is an offline placeholder, so it claims nothing it cannot back: no
+ // verification, no signature, no popularity numbers, and fixed (not "now") dates.
return {
+ source: 'builtin-fallback',
version: '1.0.0',
- updatedAt: new Date().toISOString(),
+ updatedAt: '2026-01-08T18:42:31.126Z',
ipnsName: 'k51qzi5uqu5dj0w8q1xvqn8ql2g4p7x8qpk9vz3xm1y2n3o4p5q6r7s8t9u0v',
previousCid: undefined,
@@ -335,25 +338,24 @@ export class PatternDiscovery {
author: {
id: 'claude-flow-team',
displayName: 'Claude Flow Team',
- verified: true,
+ verified: false,
patterns: 1,
- totalDownloads: 1000,
+ totalDownloads: 0,
},
license: 'MIT',
categories: ['routing', 'coordination'],
tags: ['genesis', 'foundational', 'routing', 'swarm', 'coordination', 'multi-agent', 'hello-world'],
language: 'typescript',
framework: 'claude-flow',
- downloads: 1000,
- rating: 5.0,
- ratingCount: 42,
- lastUpdated: new Date().toISOString(),
+ downloads: 0,
+ rating: 0,
+ ratingCount: 0,
+ lastUpdated: '2026-01-08T18:42:31.126Z',
createdAt: '2026-01-08T18:42:31.126Z',
minClaudeFlowVersion: '3.0.0',
- verified: true,
- trustLevel: 'verified',
- signature: 'ed25519:genesis-pattern-signature',
- publicKey: 'ed25519:claude-flow-team-key',
+ verified: false,
+ trustLevel: 'unverified',
+ source: 'builtin-fallback',
},
],
@@ -369,23 +371,20 @@ export class PatternDiscovery {
{
id: 'claude-flow-team',
displayName: 'Claude Flow Team',
- publicKey: 'ed25519:claude-flow-team-key',
- verified: true,
+ verified: false,
patterns: 1,
- totalDownloads: 1000,
+ totalDownloads: 0,
},
],
totalPatterns: 1,
- totalDownloads: 1000,
+ totalDownloads: 0,
totalAuthors: 1,
featured: ['seraphine-genesis-v1'],
trending: ['seraphine-genesis-v1'],
newest: ['seraphine-genesis-v1'],
- registrySignature: crypto.randomBytes(32).toString('hex'),
- registryPublicKey: 'ed25519:claude-flow-registry-key',
};
}
diff --git a/v3/@claude-flow/cli/src/transfer/store/types.ts b/v3/@claude-flow/cli/src/transfer/store/types.ts
index 33342c38ca..92d960f060 100644
--- a/v3/@claude-flow/cli/src/transfer/store/types.ts
+++ b/v3/@claude-flow/cli/src/transfer/store/types.ts
@@ -45,6 +45,9 @@ export interface PatternEntry {
trustLevel: TrustLevel;
signature?: string;
publicKey?: string;
+
+ /** Where the entry came from. 'builtin-fallback' = the offline placeholder, not live registry data (#4157). */
+ source?: 'registry' | 'builtin-fallback';
}
/**
@@ -76,6 +79,8 @@ export interface PatternCategory {
* Stored on IPFS with IPNS pointer for updates
*/
export interface PatternRegistry {
+ /** 'builtin-fallback' when discovery could not reach a registry and used the offline placeholder (#4157). */
+ source?: 'registry' | 'builtin-fallback';
// Registry metadata
version: string;
updatedAt: string;