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(hooks): honest routing scores, honest MoE metrics, real transfer (#2869)

rUv48d532b47e3a
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 1ec82f23e3..5dd7954ff0 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -1713,19 +1713,21 @@ const transferFromProjectCommand: Command = {
// Call MCP tool for transfer
const result = await callMCPTool<{
+ success: boolean;
+ message?: string;
sourcePath: string;
transferred: {
total: number;
byType: Record<string, number>;
- };
- skipped: {
+ } | number;
+ skipped?: {
lowConfidence: number;
duplicates: number;
conflicts: number;
};
- stats: {
- avgConfidence: number;
- avgAge: string;
+ stats?: {
+ avgConfidence: number | null;
+ avgAgeDays: number | null;
};
}>('hooks_transfer', {
sourcePath,
@@ -1734,6 +1736,17 @@ const transferFromProjectCommand: Command = {
mergeStrategy: 'keep-highest-confidence',
});
+ // #2859 β€” the handler reports success:false (no destination write
+ // happened) when the source has no matching patterns at all. Surface
+ // that honestly instead of claiming a transfer occurred.
+ if (!result.success || typeof result.transferred === 'number') {
+ spinner.fail(result.message ?? 'No patterns transferred');
+ if (ctx.flags.format === 'json') {
+ output.printJson(result);
+ }
+ return { success: false, exitCode: 1, data: result };
+ }
+
spinner.succeed(`Transferred ${result.transferred.total} patterns`);
if (ctx.flags.format === 'json') {
@@ -1750,9 +1763,9 @@ const transferFromProjectCommand: Command = {
],
data: [
{ category: 'Total Transferred', count: output.success(String(result.transferred.total)) },
- { category: 'Skipped (Low Confidence)', count: result.skipped.lowConfidence },
- { category: 'Skipped (Duplicates)', count: result.skipped.duplicates },
- { category: 'Skipped (Conflicts)', count: result.skipped.conflicts }
+ { category: 'Skipped (Low Confidence)', count: result.skipped?.lowConfidence ?? 0 },
+ { category: 'Skipped (Duplicates)', count: result.skipped?.duplicates ?? 0 },
+ { category: 'Skipped (Conflicts)', count: result.skipped?.conflicts ?? 0 }
]
});
@@ -1768,11 +1781,19 @@ const transferFromProjectCommand: Command = {
});
}
- output.writeln();
- output.printList([
- `Avg Confidence: ${(result.stats.avgConfidence * 100).toFixed(1)}%`,
- `Avg Age: ${result.stats.avgAge}`
- ]);
+ // #2865-style honesty: omit stats that have no real measured value
+ // rather than showing a fabricated number.
+ const statLines: string[] = [];
+ if (result.stats?.avgConfidence != null) {
+ statLines.push(`Avg Confidence: ${(result.stats.avgConfidence * 100).toFixed(1)}%`);
+ }
+ if (result.stats?.avgAgeDays != null) {
+ statLines.push(`Avg Age: ${result.stats.avgAgeDays.toFixed(1)} days`);
+ }
+ if (statLines.length > 0) {
+ output.writeln();
+ output.printList(statLines);
+ }
return { success: true, data: result };
} catch (error) {
@@ -2585,9 +2606,17 @@ const intelligenceCommand: Command = {
moe: {
enabled: enableMoe,
status: String(mcpMoe?.status ?? (hasLocalData ? 'active' : 'idle')),
- expertsActive: Number(mcpMoe?.expertsActive ?? (hasLocalData ? 8 : 0)),
- routingAccuracy: Number(mcpMoe?.routingAccuracy ?? (hasLocalData ? 0.82 : 0)),
- loadBalance: Number(mcpMoe?.loadBalance ?? (hasLocalData ? 0.9 : 0)),
+ // #2865 β€” these three previously fell back to hardcoded
+ // hasLocalData ? <constant> : 0 whenever the MCP tool didn't
+ // report a real value, so "Routing Accuracy: 82.0%" displayed
+ // on every project with local neural data regardless of actual
+ // routing quality (measured 49% on a real store). None of these
+ // three has a cheap, honest local substitute the way
+ // `hooks metrics`' routingAccuracy falls back to averageConfidence,
+ // so they are null (unmeasured) rather than a fabricated number.
+ expertsActive: mcpMoe?.expertsActive == null ? null : Number(mcpMoe.expertsActive),
+ routingAccuracy: mcpMoe?.routingAccuracy == null ? null : Number(mcpMoe.routingAccuracy),
+ loadBalance: mcpMoe?.loadBalance == null ? null : Number(mcpMoe.loadBalance),
},
hnsw: {
enabled: enableHnsw,
@@ -2689,9 +2718,11 @@ const intelligenceCommand: Command = {
],
data: [
{ metric: 'Status', value: formatIntelligenceStatus(moe.status) },
- { metric: 'Active Experts', value: moe.expertsActive ?? 0 },
- { metric: 'Routing Accuracy', value: `${((moe.routingAccuracy ?? 0) * 100).toFixed(1)}%` },
- { metric: 'Load Balance', value: `${((moe.loadBalance ?? 0) * 100).toFixed(1)}%` }
+ // #2865 β€” omit rather than show a fabricated 0/0.0% when the
+ // MCP tool hasn't reported a real value for these.
+ ...(moe.expertsActive == null ? [] : [{ metric: 'Active Experts', value: moe.expertsActive }]),
+ ...(moe.routingAccuracy == null ? [] : [{ metric: 'Routing Accuracy', value: `${(moe.routingAccuracy * 100).toFixed(1)}%` }]),
+ ...(moe.loadBalance == null ? [] : [{ metric: 'Load Balance', value: `${(moe.loadBalance * 100).toFixed(1)}%` }]),
]
});
} else {
diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
index 0b59a10cfd..b2caf8baa2 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -1130,12 +1130,18 @@ export const hooksRoute: MCPTool = {
let confidence: number;
let matchedPattern = '';
+ // Both static and learned patterns are gated on the same similarity
+ // score. Learned patterns additionally require support/reliability as a
+ // quality guard, but do NOT need a higher score bar β€” a learned pattern
+ // that outscores every static candidate must not lose to one anyway
+ // (#2864: a 25pp higher threshold made a top-scoring learned-researcher
+ // match at 0.57 lose to a static match at 0.52, discarding the learned
+ // store's output on the majority of routes).
const eligibleSemantic = semanticResult.find((match) => {
if (match.score <= 0.4) return false;
const learned = match.intent.startsWith('learned-') || match.metadata.source === 'learned';
if (!learned) return true;
- return match.score >= 0.65
- && Number(match.metadata.support ?? 0) >= 2
+ return Number(match.metadata.support ?? 0) >= 2
&& Number(match.metadata.reliability ?? 0) >= 0.75;
});
if (eligibleSemantic) {
@@ -2008,18 +2014,21 @@ export const hooksTransfer: MCPTool = {
// Fall back to empty store
}
- const sourceEntries = Object.values(sourceStore.entries);
-
- // Count patterns by type from source
- const byType: Record<string, number> = {
- 'file-patterns': sourceEntries.filter(e => e.key.includes('file') || e.metadata?.type === 'file-pattern').length,
- 'task-routing': sourceEntries.filter(e => e.key.includes('routing') || e.metadata?.type === 'routing').length,
- 'command-risk': sourceEntries.filter(e => e.key.includes('command') || e.metadata?.type === 'command-risk').length,
- 'agent-success': sourceEntries.filter(e => e.key.includes('agent') || e.metadata?.type === 'agent-success').length,
+ const classifyType = (key: string, metadata?: Record<string, unknown>): string | null => {
+ if (key.includes('file') || metadata?.type === 'file-pattern') return 'file-patterns';
+ if (key.includes('routing') || metadata?.type === 'routing') return 'task-routing';
+ if (key.includes('command') || metadata?.type === 'command-risk') return 'command-risk';
+ if (key.includes('agent') || metadata?.type === 'agent-success') return 'agent-success';
+ return null;
};
+ const candidates = Object.entries(sourceStore.entries)
+ .map(([key, entry]) => ({ key, entry, type: classifyType(key, entry.metadata) }))
+ .filter((c): c is { key: string; entry: MemoryEntry; type: string } => c.type !== null)
+ .filter(c => !filter || c.type.includes(filter));
+
// If source has no patterns, report honestly instead of substituting demo data
- if (Object.values(byType).every(v => v === 0)) {
+ if (candidates.length === 0) {
return {
success: false,
message: 'No patterns found in source project',
@@ -2028,29 +2037,71 @@ export const hooksTransfer: MCPTool = {
};
}
- if (filter) {
- Object.keys(byType).forEach(key => {
- if (!key.includes(filter)) delete byType[key];
- });
+ // #2859 β€” this used to count source patterns, then invent skip counts
+ // as fixed percentages of that count and a fixed avgConfidence/avgAge,
+ // without ever reading or writing the destination store. An operator
+ // could believe state moved between projects when nothing changed.
+ // Perform a real merge: skip entries below the confidence threshold,
+ // skip exact duplicates, skip real conflicts (destination already has
+ // a different value for that key β€” never silently overwritten), and
+ // actually write whatever remains into this project's own memory store.
+ const destStore = loadMemoryStore();
+ const byType: Record<string, number> = {};
+ let lowConfidence = 0;
+ let duplicates = 0;
+ let conflicts = 0;
+ let transferredCount = 0;
+ let confidenceSum = 0;
+ let confidenceCount = 0;
+ let ageSumMs = 0;
+ let ageCount = 0;
+ const now = Date.now();
+
+ for (const { key, entry, type } of candidates) {
+ const confidenceRaw = entry.metadata?.confidence ?? entry.metadata?.reliability;
+ const confidence = typeof confidenceRaw === 'number' ? confidenceRaw : undefined;
+ if (confidence !== undefined && confidence < minConfidence) {
+ lowConfidence++;
+ continue;
+ }
+
+ const existing = destStore.entries[key];
+ if (existing) {
+ const same = JSON.stringify(existing.value) === JSON.stringify(entry.value);
+ if (same) { duplicates++; continue; }
+ conflicts++;
+ continue;
+ }
+
+ destStore.entries[key] = entry;
+ transferredCount++;
+ byType[type] = (byType[type] ?? 0) + 1;
+ if (confidence !== undefined) { confidenceSum += confidence; confidenceCount++; }
+ const storedAtMs = Date.parse(entry.storedAt ?? '');
+ if (!Number.isNaN(storedAtMs)) { ageSumMs += now - storedAtMs; ageCount++; }
}
- const total = Object.values(byType).reduce((a, b) => a + b, 0);
+ if (transferredCount > 0) {
+ const memDir = resolve(MEMORY_DIR);
+ if (!existsSync(memDir)) mkdirSync(memDir, { recursive: true });
+ writeFileSync(getMemoryPath(), JSON.stringify(destStore, null, 2), 'utf-8');
+ }
return {
success: true,
sourcePath,
transferred: {
- total,
+ total: transferredCount,
byType,
},
skipped: {
- lowConfidence: Math.floor(total * 0.15),
- duplicates: Math.floor(total * 0.08),
- conflicts: Math.floor(total * 0.03),
+ lowConfidence,
+ duplicates,
+ conflicts,
},
stats: {
- avgConfidence: 0.82 + (minConfidence > 0.8 ? 0.1 : 0),
- avgAge: '3 days',
+ avgConfidence: confidenceCount > 0 ? Number((confidenceSum / confidenceCount).toFixed(3)) : null,
+ avgAgeDays: ageCount > 0 ? Number((ageSumMs / ageCount / 86_400_000).toFixed(1)) : null,
},
dataSource: 'source-project',
};