Merge pull request #1365 from ruvnet/fix/implement-stubs-and-broken

feat: stub remediation — real consensus, RL, WASM, HNSW cleanup (v3.5.22)
This commit is contained in:
rUv authored and GitHub committed 2026-03-17 12:40:40 -04:00
commit 3a8b30e0e4
18 files changed
+2142 -189

No files matched your search

+4 -2
View File
@@ -66,9 +66,11 @@ async function main() {
try { hookInput = JSON.parse(stdinData); } catch (e) { /* ignore parse errors */ }
}
// Merge stdin data into prompt resolution: prefer stdin fields, then env, then argv
// Merge stdin data into prompt resolution: prefer stdin fields, then env vars.
// NEVER fall back to argv args — shell glob expansion of braces in bash output
// creates junk files (#1342). Use env vars or stdin only.
const prompt = hookInput.prompt || hookInput.command || hookInput.toolInput
|| process.env.PROMPT || process.env.TOOL_INPUT_command || args.join(' ') || '';
|| process.env.PROMPT || process.env.TOOL_INPUT_command || '';
const handlers = {
'route': () => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
"version": "3.5.21",
"version": "3.5.22",
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ruflo",
"version": "3.5.21",
"version": "3.5.22",
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
"version": "3.5.21",
"version": "3.5.22",
"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",
File diff suppressed because it is too large. Load diff
+11 -4
View File
@@ -83,7 +83,8 @@ const trainCommand: Command = {
if (initResult.success) {
wasmFeatures = initResult.features;
spinner.setText(`RuVector initialized: ${wasmFeatures.join(', ')}`);
const backendLabel = initResult.backend === 'wasm' ? 'WASM' : 'JS fallback';
spinner.setText(`RuVector initialized [${backendLabel}]: ${wasmFeatures.join(', ')}`);
} else {
output.writeln(output.warning(`WASM init failed: ${initResult.error} - falling back`));
}
@@ -318,7 +319,9 @@ const trainCommand: Command = {
// Add WASM-specific metrics
if (useWasm && wasmFeatures.length > 0) {
const backendUsed = ruvectorStats?.backend || 'unknown';
tableData.push(
{ metric: 'Backend', value: backendUsed === 'wasm' ? 'WASM (native)' : 'JS (fallback)' },
{ metric: 'WASM Features', value: wasmFeatures.slice(0, 3).join(', ') },
{ metric: 'LoRA Adaptations', value: String(adaptations) },
{ metric: 'Avg Loss', value: (totalLoss / Math.max(1, epochs)).toFixed(4) }
@@ -362,7 +365,11 @@ const trainCommand: Command = {
output.writeln(output.success(`✓ ${patternsRecorded} patterns saved to ${persistence.patternsFile}`));
if (useWasm && wasmFeatures.length > 0) {
output.writeln(output.highlight(`✓ RuVector WASM: ${wasmFeatures.join(', ')}`));
const backendUsed = ruvectorStats?.backend || 'unknown';
const backendMsg = backendUsed === 'wasm'
? `RuVector WASM backend: ${wasmFeatures.join(', ')}`
: `RuVector JS fallback (install @ruvector/learning-wasm for native speed): ${wasmFeatures.join(', ')}`;
output.writeln(output.highlight(`✓ ${backendMsg}`));
}
return {
@@ -448,10 +455,10 @@ const statusCommand: Command = {
: 'Not initialized',
},
{
component: 'RuVector WASM',
component: 'RuVector Training',
status: ruvectorStats.initialized ? output.success('Active') : output.dim('Not loaded'),
details: ruvectorStats.initialized
? `MicroLoRA: ${ruvectorStats.totalAdaptations} adapts`
? `${ruvectorStats.backend === 'wasm' ? 'WASM' : 'JS fallback'} | MicroLoRA: ${ruvectorStats.totalAdaptations} adapts`
: 'Call neural train to initialize',
},
{
+3
View File
@@ -568,6 +568,9 @@ export {
getReasoningBank,
clearIntelligence,
benchmarkAdaptation,
// RL loop API
endTrajectoryWithVerdict,
distillLearning,
// Pattern persistence API
getAllPatterns,
getPatternsByType,
@@ -38,12 +38,42 @@ interface SyncState {
pendingChanges: number;
}
interface CoordConsensusProposal {
proposalId: string;
type: string;
proposal: unknown;
proposedBy: string;
proposedAt: string;
votes: Record<string, boolean>;
status: string;
strategy: string;
term?: number;
quorumPreset?: string;
byzantineVoters?: string[];
}
interface CoordConsensusResult {
proposalId: string;
result: string;
votes: { for: number; against: number };
decidedAt: string;
strategy: string;
term?: number;
byzantineDetected?: string[];
}
interface CoordConsensusState {
pending: CoordConsensusProposal[];
history: CoordConsensusResult[];
}
interface CoordinationStore {
topology: TopologyConfig;
loadBalance: LoadBalanceConfig;
sync: SyncState;
nodes: Record<string, { id: string; status: string; load: number; lastHeartbeat: string }>;
version: string;
consensus?: CoordConsensusState;
}
function getCoordDir(): string {
@@ -421,61 +451,242 @@ export const coordinationTools: MCPTool[] = [
},
{
name: 'coordination_consensus',
description: 'Manage consensus protocol',
description: 'Manage consensus protocol with BFT, Raft, or Quorum strategies',
category: 'coordination',
inputSchema: {
type: 'object',
properties: {
action: { type: 'string', enum: ['status', 'propose', 'vote', 'commit'], description: 'Action to perform' },
proposal: { type: 'object', description: 'Proposal data' },
proposal: { type: 'object', description: 'Proposal data (for propose)' },
proposalId: { type: 'string', description: 'Proposal ID (for vote/commit/status)' },
vote: { type: 'string', enum: ['accept', 'reject'], description: 'Vote' },
voterId: { type: 'string', description: 'Voter node ID' },
strategy: { type: 'string', enum: ['bft', 'raft', 'quorum'], description: 'Consensus strategy (default: raft)' },
quorumPreset: { type: 'string', enum: ['unanimous', 'majority', 'supermajority'], description: 'Quorum threshold preset (default: majority)' },
term: { type: 'number', description: 'Term number (for raft strategy)' },
},
},
handler: async (input) => {
const store = loadCoordStore();
const action = (input.action as string) || 'status';
const strategy = (input.strategy as string) || 'raft';
const nodeCount = Object.keys(store.nodes).length || 1;
// Initialize consensus storage in the coordination store if missing
if (!store.consensus) {
store.consensus = { pending: [], history: [] };
}
const consensus = store.consensus;
function calcRequired(strat: string, total: number, preset?: string): number {
if (total <= 0) return 1;
if (strat === 'bft') return Math.floor((total * 2) / 3) + 1;
if (strat === 'quorum') {
if (preset === 'unanimous') return total;
if (preset === 'supermajority') return Math.floor((total * 2) / 3) + 1;
}
return Math.floor(total / 2) + 1;
}
if (action === 'status') {
const nodeCount = Object.keys(store.nodes).length;
const quorum = Math.floor(nodeCount / 2) + 1;
if (input.proposalId) {
// Status for specific proposal
const p = consensus.pending.find(x => x.proposalId === input.proposalId);
if (p) {
const votesFor = Object.values(p.votes).filter(v => v).length;
const votesAgainst = Object.values(p.votes).filter(v => !v).length;
return {
success: true,
proposalId: p.proposalId,
strategy: p.strategy,
status: p.status,
votesFor,
votesAgainst,
required: calcRequired(p.strategy, nodeCount, p.quorumPreset),
totalNodes: nodeCount,
resolved: false,
};
}
const h = consensus.history.find(x => x.proposalId === input.proposalId);
if (h) return { success: true, ...h, resolved: true, historical: true };
return { success: false, error: 'Proposal not found' };
}
const quorum = calcRequired(strategy, nodeCount);
return {
success: true,
algorithm: store.topology.consensusAlgorithm,
strategy,
nodes: nodeCount,
quorum,
pendingProposals: consensus.pending.length,
resolvedProposals: consensus.history.length,
status: nodeCount >= quorum ? 'operational' : 'degraded',
};
}
if (action === 'propose') {
const proposalId = `proposal-${Date.now()}`;
const proposalId = `proposal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const quorumPreset = (input.quorumPreset as string) || 'majority';
const term = (input.term as number) || 1;
const required = calcRequired(strategy, nodeCount, quorumPreset);
// Raft: one pending proposal per term
if (strategy === 'raft') {
const existing = consensus.pending.find(p => p.strategy === 'raft' && p.term === term);
if (existing) {
return {
success: false,
error: `Raft term ${term} already has pending proposal: ${existing.proposalId}`,
existingProposalId: existing.proposalId,
};
}
}
consensus.pending.push({
proposalId,
type: 'coordination',
proposal: input.proposal,
proposedBy: (input.voterId as string) || 'system',
proposedAt: new Date().toISOString(),
votes: {},
status: 'pending',
strategy,
term: strategy === 'raft' ? term : undefined,
quorumPreset: strategy === 'quorum' ? quorumPreset : undefined,
byzantineVoters: strategy === 'bft' ? [] : undefined,
});
saveCoordStore(store);
return {
success: true,
action: 'proposed',
proposalId,
proposal: input.proposal,
strategy,
status: 'pending',
requiredVotes: Math.floor(Object.keys(store.nodes).length / 2) + 1,
required,
totalNodes: nodeCount,
term: strategy === 'raft' ? term : undefined,
};
}
if (action === 'vote') {
const p = consensus.pending.find(x => x.proposalId === input.proposalId);
if (!p) return { success: false, error: 'Proposal not found or already resolved' };
const voterId = input.voterId as string;
if (!voterId) return { success: false, error: 'voterId is required' };
const voteValue = input.vote === 'accept';
const pStrategy = p.strategy || 'raft';
const required = calcRequired(pStrategy, nodeCount, p.quorumPreset);
// Double-vote prevention
if (voterId in p.votes) {
if (pStrategy === 'bft' && p.votes[voterId] !== voteValue) {
if (!p.byzantineVoters) p.byzantineVoters = [];
if (!p.byzantineVoters.includes(voterId)) p.byzantineVoters.push(voterId);
delete p.votes[voterId];
saveCoordStore(store);
return {
success: false,
byzantineDetected: true,
message: `Byzantine behavior: voter ${voterId} attempted conflicting vote. Vote invalidated.`,
byzantineVoters: p.byzantineVoters,
};
}
return { success: false, error: `Voter ${voterId} has already voted on this proposal` };
}
// BFT cross-proposal conflict check
if (pStrategy === 'bft') {
for (const other of consensus.pending) {
if (other.proposalId === p.proposalId) continue;
if (voterId in other.votes && other.votes[voterId] !== voteValue) {
if (!p.byzantineVoters) p.byzantineVoters = [];
if (!p.byzantineVoters.includes(voterId)) p.byzantineVoters.push(voterId);
saveCoordStore(store);
return {
success: false,
byzantineDetected: true,
message: `Byzantine behavior: voter ${voterId} cast conflicting votes across proposals.`,
byzantineVoters: p.byzantineVoters,
};
}
}
}
p.votes[voterId] = voteValue;
const votesFor = Object.values(p.votes).filter(v => v).length;
const votesAgainst = Object.values(p.votes).filter(v => !v).length;
// Resolution check
let resolved = false;
let result: string | undefined;
if (votesFor >= required) {
resolved = true;
result = 'approved';
} else if (votesAgainst >= required) {
resolved = true;
result = 'rejected';
} else if (pStrategy === 'quorum' && p.quorumPreset === 'unanimous' && votesAgainst > 0) {
resolved = true;
result = 'rejected';
}
if (resolved && result) {
p.status = result;
consensus.history.push({
proposalId: p.proposalId,
result,
votes: { for: votesFor, against: votesAgainst },
decidedAt: new Date().toISOString(),
strategy: pStrategy,
term: p.term,
byzantineDetected: p.byzantineVoters?.length ? p.byzantineVoters : undefined,
});
consensus.pending = consensus.pending.filter(x => x.proposalId !== p.proposalId);
}
saveCoordStore(store);
return {
success: true,
action: 'voted',
proposalId: p.proposalId,
voterId,
vote: input.vote,
timestamp: new Date().toISOString(),
strategy: pStrategy,
votesFor,
votesAgainst,
required,
totalNodes: nodeCount,
resolved,
result: resolved ? result : undefined,
status: p.status,
};
}
if (action === 'commit') {
return {
success: true,
action: 'committed',
committedAt: new Date().toISOString(),
};
// Commit is a no-op confirmation for already-resolved proposals
if (input.proposalId) {
const h = consensus.history.find(x => x.proposalId === input.proposalId);
if (h) {
return {
success: true,
action: 'committed',
proposalId: input.proposalId,
result: h.result,
committedAt: new Date().toISOString(),
};
}
return { success: false, error: 'Proposal not found in resolved history. Vote must reach quorum first.' };
}
return { success: false, error: 'proposalId is required for commit' };
}
return { success: false, error: 'Unknown action' };
@@ -31,6 +31,9 @@ interface HiveState {
updatedAt: string;
}
type ConsensusStrategy = 'bft' | 'raft' | 'quorum';
type QuorumPreset = 'unanimous' | 'majority' | 'supermajority';
interface ConsensusProposal {
proposalId: string;
type: string;
@@ -39,6 +42,11 @@ interface ConsensusProposal {
proposedAt: string;
votes: Record<string, boolean>;
status: 'pending' | 'approved' | 'rejected';
strategy: ConsensusStrategy;
term?: number; // Raft: term number
quorumPreset?: QuorumPreset; // Quorum: threshold preset
byzantineVoters?: string[]; // BFT: detected Byzantine voters
timeoutAt?: string; // Raft: timeout for re-proposal
}
interface ConsensusResult {
@@ -47,6 +55,99 @@ interface ConsensusResult {
result: 'approved' | 'rejected';
votes: { for: number; against: number };
decidedAt: string;
strategy: ConsensusStrategy;
term?: number;
byzantineDetected?: string[];
}
/**
* Calculate required votes for a given strategy and total node count.
*/
function calculateRequiredVotes(
strategy: ConsensusStrategy,
totalNodes: number,
quorumPreset: QuorumPreset = 'majority',
): number {
if (totalNodes <= 0) return 1;
switch (strategy) {
case 'bft':
// BFT: requires 2/3 + 1 of total nodes
return Math.floor((totalNodes * 2) / 3) + 1;
case 'raft':
// Raft: simple majority
return Math.floor(totalNodes / 2) + 1;
case 'quorum':
switch (quorumPreset) {
case 'unanimous':
return totalNodes;
case 'supermajority':
return Math.floor((totalNodes * 2) / 3) + 1;
case 'majority':
default:
return Math.floor(totalNodes / 2) + 1;
}
default:
return Math.floor(totalNodes / 2) + 1;
}
}
/**
* Detect Byzantine behavior: a voter who has cast conflicting votes
* across proposals in the same round (same type, overlapping time).
* Here we check if the voter already voted differently on this proposal
* (which shouldn't happen if we block double-votes, so this checks
* cross-proposal conflicting votes for same type within the pending set).
*/
function detectByzantineVoters(
pending: ConsensusProposal[],
currentProposal: ConsensusProposal,
voterId: string,
newVote: boolean,
): boolean {
// Check if voter cast opposite votes on proposals of the same type
for (const p of pending) {
if (p.proposalId === currentProposal.proposalId) continue;
if (p.type !== currentProposal.type) continue;
if (voterId in p.votes && p.votes[voterId] !== newVote) {
return true; // Conflicting vote detected
}
}
return false;
}
/**
* Try to resolve a proposal based on its strategy.
* Returns 'approved', 'rejected', or null if still pending.
*/
function tryResolveProposal(
proposal: ConsensusProposal,
totalNodes: number,
): 'approved' | 'rejected' | null {
const votesFor = Object.values(proposal.votes).filter(v => v).length;
const votesAgainst = Object.values(proposal.votes).filter(v => !v).length;
const required = calculateRequiredVotes(
proposal.strategy,
totalNodes,
proposal.quorumPreset,
);
if (votesFor >= required) return 'approved';
if (votesAgainst >= required) return 'rejected';
// For quorum with 'unanimous', also reject if any vote is against
if (proposal.strategy === 'quorum' && proposal.quorumPreset === 'unanimous' && votesAgainst > 0) {
return 'rejected';
}
// Check if it's impossible to reach quorum (remaining potential votes can't tip it)
const totalVotes = Object.keys(proposal.votes).length;
const remaining = totalNodes - totalVotes;
if (votesFor + remaining < required && votesAgainst + remaining < required) {
// Deadlock: neither side can win -- reject
return 'rejected';
}
return null;
}
function getHiveDir(): string {
@@ -366,7 +467,7 @@ export const hiveMindTools: MCPTool[] = [
},
{
name: 'hive-mind_consensus',
description: 'Propose or vote on consensus',
description: 'Propose or vote on consensus with BFT, Raft, or Quorum strategies',
category: 'hive-mind',
inputSchema: {
type: 'object',
@@ -377,15 +478,42 @@ export const hiveMindTools: MCPTool[] = [
value: { description: 'Proposal value (for propose)' },
vote: { type: 'boolean', description: 'Vote (true=for, false=against)' },
voterId: { type: 'string', description: 'Voter agent ID' },
strategy: { type: 'string', enum: ['bft', 'raft', 'quorum'], description: 'Consensus strategy (default: raft)' },
quorumPreset: { type: 'string', enum: ['unanimous', 'majority', 'supermajority'], description: 'Quorum threshold preset (for quorum strategy, default: majority)' },
term: { type: 'number', description: 'Term number (for raft strategy)' },
timeoutMs: { type: 'number', description: 'Timeout in ms for raft re-proposal (default: 30000)' },
},
required: ['action'],
},
handler: async (input) => {
const state = loadHiveState();
const action = input.action as string;
const strategy = (input.strategy as ConsensusStrategy) || 'raft';
const totalNodes = state.workers.length || 1;
if (action === 'propose') {
const proposalId = `proposal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const quorumPreset = (input.quorumPreset as QuorumPreset) || 'majority';
const term = (input.term as number) || (state.queen?.term ?? 1);
const timeoutMs = (input.timeoutMs as number) || 30000;
// Raft: check if there's already a pending proposal for this term
if (strategy === 'raft') {
const existingTermProposal = state.consensus.pending.find(
p => p.strategy === 'raft' && p.term === term && p.status === 'pending',
);
if (existingTermProposal) {
return {
action,
error: `Raft term ${term} already has a pending proposal: ${existingTermProposal.proposalId}. Wait for resolution or use a higher term.`,
existingProposalId: existingTermProposal.proposalId,
term,
};
}
}
const required = calculateRequiredVotes(strategy, totalNodes, quorumPreset);
const proposal: ConsensusProposal = {
proposalId,
type: (input.type as string) || 'general',
@@ -394,6 +522,11 @@ export const hiveMindTools: MCPTool[] = [
proposedAt: new Date().toISOString(),
votes: {},
status: 'pending',
strategy,
term: strategy === 'raft' ? term : undefined,
quorumPreset: strategy === 'quorum' ? quorumPreset : undefined,
byzantineVoters: strategy === 'bft' ? [] : undefined,
timeoutAt: strategy === 'raft' ? new Date(Date.now() + timeoutMs).toISOString() : undefined,
};
state.consensus.pending.push(proposal);
@@ -403,45 +536,136 @@ export const hiveMindTools: MCPTool[] = [
action,
proposalId,
type: proposal.type,
strategy,
status: 'pending',
requiredVotes: Math.ceil(state.workers.length / 2) + 1,
required,
totalNodes,
term: proposal.term,
quorumPreset: proposal.quorumPreset,
timeoutAt: proposal.timeoutAt,
};
}
if (action === 'vote') {
const proposal = state.consensus.pending.find(p => p.proposalId === input.proposalId);
if (!proposal) {
return { action, error: 'Proposal not found' };
return { action, error: 'Proposal not found or already resolved' };
}
const voterId = input.voterId as string;
proposal.votes[voterId] = input.vote as boolean;
if (!voterId) {
return { action, error: 'voterId is required for voting' };
}
const voteValue = input.vote as boolean;
const proposalStrategy = proposal.strategy || 'raft';
const required = calculateRequiredVotes(
proposalStrategy,
totalNodes,
proposal.quorumPreset,
);
// Prevent double-voting
if (voterId in proposal.votes) {
const previousVote = proposal.votes[voterId];
if (previousVote === voteValue) {
return {
action,
error: `Voter ${voterId} has already cast the same vote on this proposal`,
proposalId: proposal.proposalId,
existingVote: previousVote,
};
}
// Conflicting vote from same voter
if (proposalStrategy === 'bft') {
// BFT: detect as Byzantine behavior
if (!proposal.byzantineVoters) proposal.byzantineVoters = [];
if (!proposal.byzantineVoters.includes(voterId)) {
proposal.byzantineVoters.push(voterId);
}
// Remove their vote entirely -- Byzantine voter is excluded
delete proposal.votes[voterId];
saveHiveState(state);
return {
action,
proposalId: proposal.proposalId,
voterId,
byzantineDetected: true,
message: `Byzantine behavior detected: voter ${voterId} attempted conflicting vote. Vote invalidated.`,
byzantineVoters: proposal.byzantineVoters,
status: proposal.status,
};
}
if (proposalStrategy === 'raft') {
// Raft: only one vote per node per term, reject the change
return {
action,
error: `Raft: voter ${voterId} already voted in term ${proposal.term}. Cannot change vote.`,
proposalId: proposal.proposalId,
term: proposal.term,
};
}
// Quorum: reject double-vote
return {
action,
error: `Voter ${voterId} has already voted on this proposal`,
proposalId: proposal.proposalId,
};
}
// BFT: check for cross-proposal Byzantine behavior
if (proposalStrategy === 'bft') {
const isByzantine = detectByzantineVoters(
state.consensus.pending,
proposal,
voterId,
voteValue,
);
if (isByzantine) {
if (!proposal.byzantineVoters) proposal.byzantineVoters = [];
if (!proposal.byzantineVoters.includes(voterId)) {
proposal.byzantineVoters.push(voterId);
}
saveHiveState(state);
return {
action,
proposalId: proposal.proposalId,
voterId,
byzantineDetected: true,
message: `Byzantine behavior detected: voter ${voterId} cast conflicting votes across proposals of same type. Vote rejected.`,
byzantineVoters: proposal.byzantineVoters,
status: proposal.status,
};
}
}
// Record the vote
proposal.votes[voterId] = voteValue;
// Check if we have majority
const votesFor = Object.values(proposal.votes).filter(v => v).length;
const votesAgainst = Object.values(proposal.votes).filter(v => !v).length;
const majority = Math.ceil(state.workers.length / 2) + 1;
if (votesFor >= majority) {
proposal.status = 'approved';
// Try to resolve
const resolution = tryResolveProposal(proposal, totalNodes);
let resolved = false;
if (resolution !== null) {
resolved = true;
proposal.status = resolution;
state.consensus.history.push({
proposalId: proposal.proposalId,
type: proposal.type,
result: 'approved',
result: resolution,
votes: { for: votesFor, against: votesAgainst },
decidedAt: new Date().toISOString(),
strategy: proposalStrategy,
term: proposal.term,
byzantineDetected: proposal.byzantineVoters?.length ? proposal.byzantineVoters : undefined,
});
state.consensus.pending = state.consensus.pending.filter(p => p.proposalId !== proposal.proposalId);
} else if (votesAgainst >= majority) {
proposal.status = 'rejected';
state.consensus.history.push({
proposalId: proposal.proposalId,
type: proposal.type,
result: 'rejected',
votes: { for: votesFor, against: votesAgainst },
decidedAt: new Date().toISOString(),
});
state.consensus.pending = state.consensus.pending.filter(p => p.proposalId !== proposal.proposalId);
state.consensus.pending = state.consensus.pending.filter(
p => p.proposalId !== proposal.proposalId,
);
}
saveHiveState(state);
@@ -450,10 +674,17 @@ export const hiveMindTools: MCPTool[] = [
action,
proposalId: proposal.proposalId,
voterId,
vote: input.vote,
vote: voteValue,
strategy: proposalStrategy,
votesFor,
votesAgainst,
required,
totalNodes,
resolved,
result: resolved ? resolution : undefined,
status: proposal.status,
term: proposal.term,
byzantineVoters: proposal.byzantineVoters?.length ? proposal.byzantineVoters : undefined,
};
}
@@ -463,23 +694,44 @@ export const hiveMindTools: MCPTool[] = [
// Check history
const historical = state.consensus.history.find(h => h.proposalId === input.proposalId);
if (historical) {
return { action, ...historical, historical: true };
return { action, ...historical, historical: true, resolved: true };
}
return { action, error: 'Proposal not found' };
}
const votesFor = Object.values(proposal.votes).filter(v => v).length;
const votesAgainst = Object.values(proposal.votes).filter(v => !v).length;
const proposalStrategy = proposal.strategy || 'raft';
const required = calculateRequiredVotes(
proposalStrategy,
totalNodes,
proposal.quorumPreset,
);
// Raft: check timeout
let timedOut = false;
if (proposalStrategy === 'raft' && proposal.timeoutAt) {
timedOut = new Date().getTime() > new Date(proposal.timeoutAt).getTime();
}
return {
action,
proposalId: proposal.proposalId,
type: proposal.type,
strategy: proposalStrategy,
status: proposal.status,
votesFor,
votesAgainst,
totalVotes: Object.keys(proposal.votes).length,
requiredMajority: Math.ceil(state.workers.length / 2) + 1,
required,
totalNodes,
resolved: false,
term: proposal.term,
quorumPreset: proposal.quorumPreset,
byzantineVoters: proposal.byzantineVoters?.length ? proposal.byzantineVoters : undefined,
timedOut,
timeoutAt: proposal.timeoutAt,
hint: timedOut ? `Raft timeout reached. Re-propose with term ${(proposal.term || 1) + 1}.` : undefined,
};
}
@@ -489,8 +741,16 @@ export const hiveMindTools: MCPTool[] = [
pending: state.consensus.pending.map(p => ({
proposalId: p.proposalId,
type: p.type,
strategy: p.strategy || 'raft',
proposedAt: p.proposedAt,
totalVotes: Object.keys(p.votes).length,
required: calculateRequiredVotes(
p.strategy || 'raft',
totalNodes,
p.quorumPreset,
),
term: p.term,
status: p.status,
})),
recentHistory: state.consensus.history.slice(-5),
};
@@ -402,6 +402,7 @@ export const memoryTools: MCPTool[] = [
key,
namespace,
deleted: result.deleted,
hnswIndexInvalidated: result.deleted,
backend: 'sql.js + HNSW',
};
} catch (error) {
@@ -512,6 +512,75 @@ export class EWCConsolidator {
this.globalFisher = new Array(this.config.dimensions).fill(0);
}
/**
* Update Fisher matrix from pattern confidence changes.
* Called by SONA after distillLearning to track which patterns
* are important and should be protected from forgetting.
*
* Uses online averaging: F_new = alpha * F_old + (1-alpha) * F_current
*
* @param confidenceChanges - Array of {id, embedding, oldConf, newConf}
*/
updateFisherFromConfidences(
confidenceChanges: { id: string; embedding: number[]; oldConf: number; newConf: number }[]
): void {
if (confidenceChanges.length === 0) return;
const alpha = this.config.fisherDecayRate;
const currentFisher = new Array(this.config.dimensions).fill(0);
let sampleCount = 0;
for (const change of confidenceChanges) {
if (!change.embedding || change.embedding.length === 0) continue;
const confDelta = Math.abs(change.newConf - change.oldConf);
if (confDelta === 0) continue;
sampleCount++;
const len = Math.min(change.embedding.length, this.config.dimensions);
// Squared gradient proxy: embedding scaled by confidence change magnitude
for (let i = 0; i < len; i++) {
const grad = change.embedding[i] * confDelta;
currentFisher[i] += grad * grad;
}
}
if (sampleCount > 0) {
for (let i = 0; i < this.config.dimensions; i++) {
currentFisher[i] /= sampleCount;
}
}
// Online EMA: F_new = alpha * F_old + (1-alpha) * F_current
for (let i = 0; i < this.config.dimensions; i++) {
this.globalFisher[i] = alpha * this.globalFisher[i] + (1 - alpha) * currentFisher[i];
}
this.saveToDisk();
}
/**
* Compute consolidation penalty for a proposed confidence update.
* Used by SONA to check whether a pattern update would cause forgetting.
*
* @param oldConfidence - Current confidence value
* @param newConfidence - Proposed new confidence value
* @returns Penalty value (higher = more forgetting risk)
*/
computeConfidencePenalty(oldConfidence: number, newConfidence: number): number {
// Use the global Fisher to estimate penalty for scalar confidence change
// Average Fisher value represents overall importance
let avgFisher = 0;
for (let i = 0; i < this.globalFisher.length; i++) {
avgFisher += this.globalFisher[i];
}
avgFisher = this.globalFisher.length > 0 ? avgFisher / this.globalFisher.length : 0;
const diff = newConfidence - oldConfidence;
return (this.config.lambda / 2) * avgFisher * diff * diff;
}
/**
* Clear all patterns and history (full reset)
*/
@@ -158,6 +158,7 @@ class LocalSonaCoordinator {
private signalCount: number = 0;
private trajectories: { steps: TrajectoryStep[]; verdict: string; timestamp: number }[] = [];
private adaptationTimes: number[] = [];
private currentTrajectorySteps: TrajectoryStep[] = [];
constructor(config: SonaConfig) {
this.config = config;
@@ -221,6 +222,198 @@ class LocalSonaCoordinator {
return this.adaptationTimes.reduce((a, b) => a + b, 0) / this.adaptationTimes.length;
}
/**
* Add a step to the current in-progress trajectory
*/
addTrajectoryStep(step: TrajectoryStep): void {
this.currentTrajectorySteps.push(step);
// Prevent unbounded growth
if (this.currentTrajectorySteps.length > this.config.maxTrajectorySize) {
this.currentTrajectorySteps.shift();
}
}
/**
* End the current trajectory with a verdict and apply RL updates.
* Reward mapping: success=1.0, partial=0.5, failure=-0.5
*
* For successful/partial trajectories, boosts confidence of similar patterns
* in the ReasoningBank. For failures, reduces confidence scores.
*/
async endTrajectory(
verdict: 'success' | 'failure' | 'partial',
bank: LocalReasoningBank
): Promise<{ reward: number; patternsUpdated: number }> {
const rewardMap: Record<string, number> = {
success: 1.0,
partial: 0.5,
failure: -0.5
};
const reward = rewardMap[verdict] ?? 0;
// Record the completed trajectory
const completedTrajectory = {
steps: [...this.currentTrajectorySteps],
verdict,
timestamp: Date.now()
};
this.recordTrajectory(completedTrajectory);
// Update pattern confidences based on reward
let patternsUpdated = 0;
const allPatterns = bank.getAll();
for (const step of this.currentTrajectorySteps) {
if (!step.embedding || step.embedding.length === 0) continue;
// Find patterns similar to this trajectory step
const similar = bank.findSimilar(step.embedding, {
k: 3,
threshold: 0.3
});
for (const match of similar) {
const pattern = bank.get(match.id);
if (!pattern) continue;
// Adjust confidence: positive reward boosts, negative reduces
const delta = reward * 0.1; // small step per update
const newConfidence = Math.max(0.0, Math.min(1.0, pattern.confidence + delta));
pattern.confidence = newConfidence;
pattern.usageCount++;
pattern.lastUsedAt = Date.now();
patternsUpdated++;
}
}
// Clear current trajectory
this.currentTrajectorySteps = [];
return { reward, patternsUpdated };
}
/**
* Distill learning from recent successful trajectories.
* Applies LoRA-style confidence updates and integrates EWC++ consolidation.
*
* For each successful trajectory step with high confidence,
* increases the pattern's stored confidence by loraLearningRate * reward.
* Before applying updates, checks EWC penalty to prevent catastrophic forgetting.
*/
async distillLearning(bank: LocalReasoningBank): Promise<{
patternsDistilled: number;
ewcPenalty: number;
}> {
let patternsDistilled = 0;
let totalEwcPenalty = 0;
// Get recent successful trajectories
const recentSuccessful = this.trajectories.filter(
t => t.verdict === 'success' || t.verdict === 'partial'
).slice(-10); // last 10 successful
if (recentSuccessful.length === 0) {
return { patternsDistilled: 0, ewcPenalty: 0 };
}
// Try to get EWC consolidator
let ewcConsolidator: import('./ewc-consolidation.js').EWCConsolidator | null = null;
try {
const ewcModule = await import('./ewc-consolidation.js');
ewcConsolidator = await ewcModule.getEWCConsolidator({
lambda: this.config.ewcLambda
});
} catch {
// EWC not available, proceed without consolidation protection
}
const rewardMap: Record<string, number> = {
success: 1.0,
partial: 0.5
};
// Collect confidence changes for EWC Fisher update
const confidenceChanges: { id: string; oldConf: number; newConf: number; embedding: number[] }[] = [];
for (const trajectory of recentSuccessful) {
const reward = rewardMap[trajectory.verdict] ?? 0;
for (const step of trajectory.steps) {
if (!step.embedding || step.embedding.length === 0) continue;
const similar = bank.findSimilar(step.embedding, {
k: 3,
threshold: 0.4
});
for (const match of similar) {
const pattern = bank.get(match.id);
if (!pattern) continue;
// Only distill from high-confidence matches
if (match.confidence < 0.5) continue;
const oldConfidence = pattern.confidence;
// Check EWC penalty before applying update
if (ewcConsolidator) {
const oldWeights = [oldConfidence];
const proposedConfidence = Math.min(1.0, oldConfidence + this.config.loraLearningRate * reward);
const newWeights = [proposedConfidence];
const penalty = ewcConsolidator.getPenalty(oldWeights, newWeights);
totalEwcPenalty += penalty;
// If penalty is too high, reduce the update magnitude
if (penalty > this.config.ewcLambda) {
const dampedDelta = (this.config.loraLearningRate * reward) / (1 + penalty);
pattern.confidence = Math.max(0.0, Math.min(1.0, oldConfidence + dampedDelta));
} else {
pattern.confidence = proposedConfidence;
}
} else {
// No EWC: apply full LoRA update
pattern.confidence = Math.max(0.0, Math.min(1.0,
oldConfidence + this.config.loraLearningRate * reward
));
}
pattern.lastUsedAt = Date.now();
patternsDistilled++;
confidenceChanges.push({
id: pattern.id,
oldConf: oldConfidence,
newConf: pattern.confidence,
embedding: pattern.embedding
});
}
}
}
// Update EWC Fisher matrix with confidence changes
if (ewcConsolidator && confidenceChanges.length > 0) {
for (const change of confidenceChanges) {
// Use confidence delta as gradient proxy
const gradient = change.embedding.map(
e => e * Math.abs(change.newConf - change.oldConf)
);
ewcConsolidator.recordGradient(change.id, gradient, true);
}
}
// Persist updated patterns
bank.flushToDisk();
return { patternsDistilled, ewcPenalty: totalEwcPenalty };
}
/**
* Get current trajectory steps (for inspection)
*/
getCurrentTrajectorySteps(): TrajectoryStep[] {
return [...this.currentTrajectorySteps];
}
/**
* Get statistics
*/
@@ -607,6 +800,10 @@ export async function recordStep(step: TrajectoryStep): Promise<boolean> {
timestamp: step.timestamp || Date.now()
});
// Add to current trajectory for RL tracking
const stepWithEmbedding = { ...step, embedding };
sonaCoordinator!.addTrajectoryStep(stepWithEmbedding);
// Store in ReasoningBank for retrieval
if (reasoningBank) {
reasoningBank.store({
@@ -619,6 +816,18 @@ export async function recordStep(step: TrajectoryStep): Promise<boolean> {
});
}
// When a 'result' step arrives, end the trajectory and run RL loop
if (step.type === 'result' && reasoningBank) {
// Determine verdict from metadata or default to 'partial'
const verdict = (step.metadata?.verdict as 'success' | 'failure' | 'partial') || 'partial';
await sonaCoordinator!.endTrajectory(verdict, reasoningBank);
// Distill learning from recent successful trajectories
await sonaCoordinator!.distillLearning(reasoningBank);
globalStats.lastAdaptation = Date.now();
}
globalStats.trajectoriesRecorded++;
savePersistedStats();
return true;
@@ -646,6 +855,16 @@ export async function recordTrajectory(
timestamp: Date.now()
});
// Apply RL: update pattern confidences based on verdict
if (reasoningBank) {
// Load steps into the coordinator for endTrajectory processing
for (const step of steps) {
sonaCoordinator!.addTrajectoryStep(step);
}
await sonaCoordinator!.endTrajectory(verdict, reasoningBank);
await sonaCoordinator!.distillLearning(reasoningBank);
}
globalStats.trajectoriesRecorded++;
globalStats.lastAdaptation = Date.now();
savePersistedStats();
@@ -748,6 +967,56 @@ export function getReasoningBank(): LocalReasoningBank | null {
return reasoningBank;
}
/**
* End the current trajectory with a verdict and apply RL updates.
* This is the public API for the SONA RL loop.
*
* @param verdict - 'success' (reward=1.0), 'partial' (0.5), or 'failure' (-0.5)
* @returns Update statistics or null if not initialized
*/
export async function endTrajectoryWithVerdict(
verdict: 'success' | 'failure' | 'partial'
): Promise<{ reward: number; patternsUpdated: number } | null> {
if (!sonaCoordinator || !reasoningBank) {
const init = await initializeIntelligence();
if (!init.success) return null;
}
try {
const result = await sonaCoordinator!.endTrajectory(verdict, reasoningBank!);
globalStats.lastAdaptation = Date.now();
savePersistedStats();
return result;
} catch {
return null;
}
}
/**
* Distill learning from recent successful trajectories.
* Applies LoRA-style confidence updates with EWC++ consolidation protection.
*
* @returns Distillation statistics or null if not initialized
*/
export async function distillLearning(): Promise<{
patternsDistilled: number;
ewcPenalty: number;
} | null> {
if (!sonaCoordinator || !reasoningBank) {
const init = await initializeIntelligence();
if (!init.success) return null;
}
try {
const result = await sonaCoordinator!.distillLearning(reasoningBank!);
globalStats.lastAdaptation = Date.now();
savePersistedStats();
return result;
} catch {
return null;
}
}
/**
* Clear intelligence state
*/
@@ -639,6 +639,16 @@ export function clearHNSWIndex(): void {
hnswIndex = null;
}
/**
* Invalidate the in-memory HNSW cache so the next search rebuilds from DB.
* Call this after deleting entries that had embeddings to prevent ghost
* vectors from appearing in search results.
*/
export function rebuildSearchIndex(): void {
hnswIndex = null;
hnswInitializing = false;
}
// ============================================================================
// INT8 VECTOR QUANTIZATION (4x memory reduction)
// ============================================================================
@@ -2573,10 +2583,16 @@ export async function deleteEntry(options: {
};
}
// Capture the entry ID for HNSW cleanup
const entryId = String(checkResult[0].values[0][0]);
// Delete the entry (soft delete by setting status to 'deleted')
// Also null out the embedding to clean up vector data from SQLite
db.run(`
UPDATE memory_entries
SET status = 'deleted', updated_at = strftime('%s', 'now') * 1000
SET status = 'deleted',
embedding = NULL,
updated_at = strftime('%s', 'now') * 1000
WHERE key = '${key.replace(/'/g, "''")}'
AND namespace = '${namespace.replace(/'/g, "''")}'
AND status = 'active'
@@ -2592,6 +2608,18 @@ export async function deleteEntry(options: {
db.close();
// Clean up in-memory HNSW index so ghost vectors don't appear in searches.
// Remove the entry from the HNSW entries map and invalidate the index.
// The next search will rebuild the HNSW index from the remaining DB rows.
if (hnswIndex?.entries) {
hnswIndex.entries.delete(entryId);
saveHNSWMetadata();
// Invalidate the HNSW index so it rebuilds from DB on next search.
// We can't surgically remove a vector from the HNSW graph, so we
// clear the entire index; it will be lazily rebuilt from SQLite.
rebuildSearchIndex();
}
return {
success: true,
deleted: true,
@@ -2625,6 +2653,7 @@ export default {
listEntries,
getEntry,
deleteEntry,
rebuildSearchIndex,
MEMORY_SCHEMA_V3,
getInitialMetadata
};
+12
View File
@@ -165,6 +165,18 @@ export async function isRuvectorAvailable(): Promise<boolean> {
}
}
/**
* Check if @ruvector/learning-wasm is available and loadable
*/
export async function isWasmBackendAvailable(): Promise<boolean> {
try {
const wasm = await import('@ruvector/learning-wasm');
return typeof wasm.WasmMicroLoRA === 'function' && typeof wasm.initSync === 'function';
} catch {
return false;
}
}
/**
* Get ruvector version if available
*/
@@ -65,6 +65,16 @@ let totalSonaLearns = 0;
let totalSonaSearches = 0;
let lastBenchmark: BenchmarkResult[] | null = null;
// Backend tracking
let activeBackend: 'wasm' | 'js-fallback' = 'js-fallback';
/**
* Get which backend is active for training
*/
export function getActiveBackend(): 'wasm' | 'js-fallback' {
return activeBackend;
}
export interface TrainingConfig {
dim?: number; // Embedding dimension (max 256)
learningRate?: number; // Learning rate
@@ -95,11 +105,195 @@ export interface TrainingResult {
}
/**
* Initialize the RuVector training system
* Pure-JS fallback implementations for when WASM is unavailable.
* These provide the same API surface with basic linear algebra.
*/
class JsMicroLoRA implements Pick<WasmMicroLoRA, 'adapt_array' | 'adapt_count' | 'param_count' | 'forward_array' | 'forward_count' | 'adapt_with_reward' | 'delta_norm' | 'dim' | 'reset' | 'free'> {
private _dim: number;
private _alpha: number;
private _lr: number;
private _adaptCount = 0n;
private _forwardCount = 0n;
private _deltaNorm = 0;
private _A: Float32Array; // Low-rank A (rank x dim)
private _B: Float32Array; // Low-rank B (dim x rank)
private readonly RANK = 2;
constructor(dim: number, alpha: number, lr: number) {
this._dim = dim;
this._alpha = alpha;
this._lr = lr;
this._A = new Float32Array(this.RANK * dim);
this._B = new Float32Array(dim * this.RANK);
// Xavier initialization
const scale = Math.sqrt(2 / (dim + this.RANK));
for (let i = 0; i < this._A.length; i++) this._A[i] = (Math.random() - 0.5) * scale;
for (let i = 0; i < this._B.length; i++) this._B[i] = (Math.random() - 0.5) * scale;
}
adapt_array(gradient: Float32Array): void {
// Simple gradient update on low-rank matrices
let norm = 0;
for (let i = 0; i < Math.min(gradient.length, this._A.length); i++) {
const delta = -this._lr * gradient[i % gradient.length] * this._alpha;
this._A[i] += delta;
norm += delta * delta;
}
this._deltaNorm = Math.sqrt(norm);
this._adaptCount++;
}
adapt_count(): bigint { return this._adaptCount; }
param_count(): number { return this._A.length + this._B.length; }
forward_array(input: Float32Array): Float32Array {
const output = new Float32Array(this._dim);
// y = x + alpha * B @ A @ x (simplified low-rank)
for (let i = 0; i < this._dim; i++) {
output[i] = input[i];
let sum = 0;
for (let r = 0; r < this.RANK; r++) {
let dot = 0;
for (let j = 0; j < this._dim; j++) {
dot += this._A[r * this._dim + j] * input[j];
}
sum += this._B[i * this.RANK + r] * dot;
}
output[i] += this._alpha * sum;
}
this._forwardCount++;
return output;
}
forward_count(): bigint { return this._forwardCount; }
adapt_with_reward(improvement: number): void {
const scale = improvement * this._lr * this._alpha;
let norm = 0;
for (let i = 0; i < this._A.length; i++) {
const delta = scale * (Math.random() - 0.5);
this._A[i] += delta;
norm += delta * delta;
}
this._deltaNorm = Math.sqrt(norm);
this._adaptCount++;
}
delta_norm(): number { return this._deltaNorm; }
dim(): number { return this._dim; }
reset(): void {
this._A.fill(0);
this._B.fill(0);
this._adaptCount = 0n;
this._forwardCount = 0n;
this._deltaNorm = 0;
}
free(): void { /* no-op for JS */ }
}
class JsScopedLoRA implements Pick<WasmScopedLoRA, 'adapt_array' | 'adapt_count' | 'forward_array' | 'forward_count' | 'adapt_with_reward' | 'delta_norm' | 'total_adapt_count' | 'total_forward_count' | 'set_category_fallback' | 'reset_all' | 'reset_scope' | 'free'> {
private adapters: Map<number, JsMicroLoRA> = new Map();
private _dim: number;
private _alpha: number;
private _lr: number;
private _fallback = false;
constructor(dim: number, alpha: number, lr: number) {
this._dim = dim;
this._alpha = alpha;
this._lr = lr;
}
private getAdapter(opType: number): JsMicroLoRA {
if (!this.adapters.has(opType)) {
if (this._fallback && opType > 0 && this.adapters.has(0)) {
return this.adapters.get(0)!;
}
this.adapters.set(opType, new JsMicroLoRA(this._dim, this._alpha, this._lr));
}
return this.adapters.get(opType)!;
}
adapt_array(opType: number, gradient: Float32Array): void { this.getAdapter(opType).adapt_array(gradient); }
adapt_count(opType: number): bigint { return this.getAdapter(opType).adapt_count(); }
forward_array(opType: number, input: Float32Array): Float32Array { return this.getAdapter(opType).forward_array(input); }
forward_count(opType: number): bigint { return this.getAdapter(opType).forward_count(); }
adapt_with_reward(opType: number, improvement: number): void { this.getAdapter(opType).adapt_with_reward(improvement); }
delta_norm(opType: number): number { return this.getAdapter(opType).delta_norm(); }
set_category_fallback(enabled: boolean): void { this._fallback = enabled; }
total_adapt_count(): bigint {
let total = 0n;
for (const a of this.adapters.values()) total += a.adapt_count();
return total;
}
total_forward_count(): bigint {
let total = 0n;
for (const a of this.adapters.values()) total += a.forward_count();
return total;
}
reset_all(): void { this.adapters.clear(); }
reset_scope(opType: number): void { this.adapters.delete(opType); }
free(): void { this.adapters.clear(); }
}
class JsTrajectoryBuffer implements Pick<WasmTrajectoryBuffer, 'record' | 'is_empty' | 'total_count' | 'success_rate' | 'mean_improvement' | 'best_improvement' | 'high_quality_count' | 'variance' | 'reset' | 'free'> {
private entries: { improvement: number }[] = [];
private capacity: number;
constructor(capacity: number, _dim: number) {
this.capacity = capacity;
}
record(_embedding: Float32Array, _opType: number, _attType: number, executionMs: number, baselineMs: number): void {
const improvement = baselineMs > 0 ? (baselineMs - executionMs) / baselineMs : 0;
if (this.entries.length >= this.capacity) this.entries.shift();
this.entries.push({ improvement });
}
is_empty(): boolean { return this.entries.length === 0; }
total_count(): bigint { return BigInt(this.entries.length); }
success_rate(): number {
if (this.entries.length === 0) return 0;
return this.entries.filter(e => e.improvement > 0).length / this.entries.length;
}
mean_improvement(): number {
if (this.entries.length === 0) return 0;
return this.entries.reduce((s, e) => s + e.improvement, 0) / this.entries.length;
}
best_improvement(): number {
if (this.entries.length === 0) return 0;
return Math.max(...this.entries.map(e => e.improvement));
}
high_quality_count(threshold: number): number {
return this.entries.filter(e => e.improvement > threshold).length;
}
variance(): number {
if (this.entries.length < 2) return 0;
const mean = this.mean_improvement();
return this.entries.reduce((s, e) => s + (e.improvement - mean) ** 2, 0) / (this.entries.length - 1);
}
reset(): void { this.entries = []; }
free(): void { this.entries = []; }
}
/**
* Initialize the RuVector training system.
* Attempts to load @ruvector/learning-wasm for WASM-accelerated training.
* Falls back to a pure-JS implementation if WASM is unavailable.
*/
export async function initializeTraining(config: TrainingConfig = {}): Promise<{
success: boolean;
features: string[];
backend: 'wasm' | 'js-fallback';
error?: string;
}> {
const features: string[] = [];
@@ -107,13 +301,13 @@ export async function initializeTraining(config: TrainingConfig = {}): Promise<{
const lr = config.learningRate || 0.01;
const alpha = config.alpha || 0.1;
// --- Attempt WASM backend first ---
let wasmLoaded = false;
try {
// Initialize MicroLoRA with direct WASM loading (Node.js compatible)
const fs = await import('fs');
const { createRequire } = await import('module');
const require = createRequire(import.meta.url);
// Load WASM file directly instead of using fetch
const wasmPath = require.resolve('@ruvector/learning-wasm/ruvector_learning_wasm_bg.wasm');
const wasmBuffer = fs.readFileSync(wasmPath);
@@ -121,21 +315,43 @@ export async function initializeTraining(config: TrainingConfig = {}): Promise<{
learningWasm.initSync({ module: wasmBuffer });
microLoRA = new learningWasm.WasmMicroLoRA(dim, alpha, lr);
features.push(`MicroLoRA (${dim}-dim, <1μs adaptation)`);
features.push(`MicroLoRA/WASM (${dim}-dim, <1μs adaptation)`);
// Initialize ScopedLoRA for per-operator learning
scopedLoRA = new learningWasm.WasmScopedLoRA(dim, alpha, lr);
scopedLoRA.set_category_fallback(true);
features.push('ScopedLoRA (17 operators)');
features.push('ScopedLoRA/WASM (17 operators)');
// Initialize trajectory buffer
trajectoryBuffer = new learningWasm.WasmTrajectoryBuffer(
config.trajectoryCapacity || 10000,
dim
);
features.push('TrajectoryBuffer');
features.push('TrajectoryBuffer/WASM');
// Initialize attention mechanisms
activeBackend = 'wasm';
wasmLoaded = true;
} catch (wasmError) {
// WASM not available - fall back to JS implementation
const reason = wasmError instanceof Error ? wasmError.message : String(wasmError);
console.warn(`[ruvector] WASM backend unavailable (${reason}), using JS fallback`);
microLoRA = new JsMicroLoRA(dim, alpha, lr) as unknown as WasmMicroLoRA;
features.push(`MicroLoRA/JS (${dim}-dim, JS fallback)`);
scopedLoRA = new JsScopedLoRA(dim, alpha, lr) as unknown as WasmScopedLoRA;
(scopedLoRA as any).set_category_fallback(true);
features.push('ScopedLoRA/JS (17 operators)');
trajectoryBuffer = new JsTrajectoryBuffer(
config.trajectoryCapacity || 10000,
dim
) as unknown as WasmTrajectoryBuffer;
features.push('TrajectoryBuffer/JS');
activeBackend = 'js-fallback';
}
// --- Attention mechanisms (optional, independent of WASM) ---
try {
const attention: any = await import('@ruvector/attention');
if (config.useFlashAttention !== false) {
@@ -153,14 +369,12 @@ export async function initializeTraining(config: TrainingConfig = {}): Promise<{
features.push('HyperbolicAttention');
}
// Initialize optimizer and loss
optimizer = new attention.AdamWOptimizer(lr, 0.9, 0.999, 1e-8, 0.01);
features.push('AdamW Optimizer');
contrastiveLoss = new attention.InfoNceLoss(0.07);
features.push('InfoNCE Loss');
// Curriculum scheduler
if (config.totalSteps) {
curriculum = new attention.CurriculumScheduler(
config.totalSteps,
@@ -169,43 +383,37 @@ export async function initializeTraining(config: TrainingConfig = {}): Promise<{
features.push('Curriculum Learning');
}
// Hard negative mining - use string for MiningStrategy enum due to NAPI binding quirk
try {
hardMiner = new attention.HardNegativeMiner(5, 'semi_hard');
features.push('Hard Negative Mining');
} catch {
// Mining not available, continue without it
}
} catch (attentionError) {
// @ruvector/attention not available - attention features skipped
const reason = attentionError instanceof Error ? attentionError.message : String(attentionError);
console.warn(`[ruvector] @ruvector/attention unavailable (${reason}), attention features disabled`);
}
// Initialize SONA (optional, backward compatible)
if (config.useSona !== false) {
try {
const sona = await import('@ruvector/sona');
const sonaRank = config.sonaRank || 4;
// SonaEngine constructor: (dim, rank, alpha, learningRate) - TypeScript types are wrong
// @ts-expect-error - SonaEngine accepts 4 positional args but types say 1
sonaEngine = new sona.SonaEngine(dim, sonaRank, alpha, lr) as SonaEngineInstance;
sonaAvailable = true;
features.push(`SONA (${dim}-dim, rank-${sonaRank}, 624k learn/s)`);
} catch (sonaError) {
// SONA not available, continue without it (backward compatible)
sonaAvailable = false;
// Only log if explicitly requested
if (config.useSona === true) {
console.warn('SONA requested but not available:', sonaError);
}
// --- SONA (optional, backward compatible) ---
if (config.useSona !== false) {
try {
const sona = await import('@ruvector/sona');
const sonaRank = config.sonaRank || 4;
// @ts-expect-error - SonaEngine accepts 4 positional args but types say 1
sonaEngine = new sona.SonaEngine(dim, sonaRank, alpha, lr) as SonaEngineInstance;
sonaAvailable = true;
features.push(`SONA (${dim}-dim, rank-${sonaRank}, 624k learn/s)`);
} catch (sonaError) {
sonaAvailable = false;
if (config.useSona === true) {
console.warn('SONA requested but not available:', sonaError);
}
}
initialized = true;
return { success: true, features };
} catch (error) {
return {
success: false,
features,
error: error instanceof Error ? error.message : String(error),
};
}
initialized = true;
return { success: true, features, backend: activeBackend };
}
/**
@@ -589,6 +797,7 @@ export function sonaFlush(): void {
*/
export function getTrainingStats(): {
initialized: boolean;
backend: 'wasm' | 'js-fallback';
totalAdaptations: number;
totalForwards: number;
microLoraStats?: {
@@ -607,6 +816,7 @@ export function getTrainingStats(): {
} {
const stats: ReturnType<typeof getTrainingStats> = {
initialized,
backend: activeBackend,
totalAdaptations,
totalForwards,
};
@@ -660,6 +870,7 @@ export function resetTraining(): void {
totalForwards = 0;
totalSonaLearns = 0;
totalSonaSearches = 0;
activeBackend = 'js-fallback';
}
/**
@@ -11,7 +11,7 @@
*/
import { EventEmitter } from 'events';
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } from 'fs';
import { join } from 'path';
import {
HeadlessWorkerExecutor,
@@ -453,10 +453,17 @@ export class WorkerDaemon extends EventEmitter {
try {
// Execute worker logic with timeout (P1 fix)
// Pass cleanup callback to kill orphan child processes on timeout (#1117)
const output = await this.runWithTimeout(
() => this.runWorkerLogic(workerConfig),
this.config.workerTimeoutMs,
`Worker ${workerConfig.type} timed out after ${this.config.workerTimeoutMs / 1000}s`
`Worker ${workerConfig.type} timed out after ${this.config.workerTimeoutMs / 1000}s`,
() => {
// On timeout, cancel any headless execution to prevent orphan processes
if (this.headlessExecutor) {
this.headlessExecutor.cancelAll();
}
}
);
const durationMs = Date.now() - startTime;
@@ -512,23 +519,44 @@ export class WorkerDaemon extends EventEmitter {
/**
* Run a function with timeout (P1 fix)
* @param fn - The async function to execute
* @param timeoutMs - Timeout in milliseconds
* @param timeoutMessage - Error message on timeout
* @param onTimeout - Optional cleanup callback invoked when timeout fires (#1117: kills orphan processes)
*/
private async runWithTimeout<T>(
fn: () => Promise<T>,
timeoutMs: number,
timeoutMessage: string
timeoutMessage: string,
onTimeout?: () => void
): Promise<T> {
return new Promise<T>((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
// Kill orphan child processes before rejecting (#1117)
if (onTimeout) {
try {
onTimeout();
} catch {
// Ignore cleanup errors
}
}
reject(new Error(timeoutMessage));
}, timeoutMs);
fn()
.then((result) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(result);
})
.catch((error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(error);
});
@@ -896,8 +924,7 @@ export class WorkerDaemon extends EventEmitter {
// Also write to log file
try {
const logFile = join(this.config.logDir, 'daemon.log');
const fs = require('fs');
fs.appendFileSync(logFile, logMessage + '\n');
appendFileSync(logFile, logMessage + '\n');
} catch {
// Ignore log write errors
}
@@ -0,0 +1,184 @@
# ADR-064: Stub Remediation & Full Implementation — v3.5.22
**Date:** 2026-03-17
**Status:** In Progress
**Context:** Deep capability audit (ADR-063) identified stub implementations and broken features. This ADR documents the remediation plan and tracks which items were already functional vs genuinely needing fixes.
## Audit Correction
The ADR-063 audit flagged several items as "stub" or "missing" that are in fact **fully implemented**. The audit ran in Docker where some capabilities were degraded due to pruned dependencies, leading to false negatives.
### Already Implemented (No Changes Needed)
| Item | Finding | Evidence |
|------|---------|----------|
| **Session restore --latest** | Fully implemented with MCP integration | `session.ts:274-432` — interactive selector when no ID given |
| **Workflow persistence** | Saves to `.claude-flow/workflows/store.json` | `workflow-tools.ts:52-78` — `loadWorkflowStore()`/`saveWorkflowStore()` |
| **Daemon scheduler** | Working process management with PID files | `daemon.ts:234-458` — detached process, signal handling |
| **Flash Attention JS** | CPU-optimized block-wise implementation | `flash-attention.ts:67-150` — top-K sparse, fused softmax-matmul |
| **MCP path resolution** | Properly sanitized with `process.cwd()` | `session-tools.ts:34-39` — path sanitization regex |
| **Hook handler stdin** | Correct timeout + pause cleanup | `hook-handler.cjs:40-58` — graceful degradation |
### Genuinely Needs Implementation (7 Items)
| Priority | Item | Current State | Target |
|----------|------|---------------|--------|
| **P0** | @ruvector/learning-wasm integration | Not wired in CLI | Wire `@ruvector/learning-wasm@0.1.29` into neural commands |
| **P0** | Consensus vote counting | Proposals queued but no quorum validation | BFT 2/3 majority, Raft leader election, configurable quorum |
| **P1** | Memory delete HNSW cleanup | SQL row deleted, vector remains | Delete embedding row + rebuild search index |
| **P1** | SONA reinforcement learning | Signal recording only | Trajectory → reward → weight update loop |
| **P1** | EWC++ consolidation execution | Algorithm defined, not executed | Fisher matrix computation + penalty application |
| **P2** | Coverage hooks test integration | Returns 0% always | Read lcov.info / jest coverage-summary.json from disk |
| **P2** | Intelligence stats → neural bridge | Stats counter disconnected | Read from ReasoningBank `.claude-flow/neural/patterns.json` |
## Implementation Plan
### P0-1: @ruvector/learning-wasm Integration
Wire the published `@ruvector/learning-wasm@0.1.29` package into the CLI:
```
neural train → ruvector.initTraining() with WASM backend
neural predict → ruvector.predict() with Flash Attention
neural optimize → ruvector.quantize() for Int8
```
**Files:** `src/commands/neural.ts`, `src/ruvector/index.ts`
**Test:** `neural train --wasm` should use WASM backend, report >2x speedup
### P0-2: Consensus Protocol Implementation
Replace stub vote recording with real consensus algorithms:
**BFT (Byzantine Fault Tolerance):**
- Require 2f+1 votes where f = floor((n-1)/3)
- Validate vote signatures (hash-based)
- Detect conflicting votes from same agent
**Raft (Leader Election):**
- Term-based leader election
- Log replication to followers
- Heartbeat timeout triggers new election
**Quorum:**
- Configurable quorum threshold (default: majority)
- Timeout-based auto-resolution
**File:** `src/mcp-tools/hive-mind-tools.ts`
**Test:** Create proposal → submit votes → verify quorum reached/rejected
### P1-1: Memory Delete HNSW Cleanup
When deleting a memory entry:
1. Delete SQL row (existing)
2. Delete embedding from vector store
3. Mark HNSW index as dirty for rebuild on next search
**File:** `src/memory/memory-initializer.ts`
**Test:** Store entry → search finds it → delete → search no longer finds it
### P1-2: SONA Reinforcement Learning Loop
Implement the 4-step intelligence pipeline for real:
1. **RETRIEVE**: Find similar patterns via ReasoningBank (existing)
2. **JUDGE**: Score trajectory outcome (success/failure/partial)
3. **DISTILL**: Compute LoRA weight delta from successful trajectories
4. **CONSOLIDATE**: Apply EWC++ penalty to prevent catastrophic forgetting
**Implementation:**
- `recordTrajectoryStep()` → accumulate steps with outcomes
- `endTrajectory(verdict)` → compute reward signal
- `distillLearning()` → update pattern confidence scores based on outcomes
- `consolidate()` → apply EWC++ Fisher penalty
**Files:** `src/memory/intelligence.ts`, `src/memory/ewc-consolidation.ts`
**Test:** Train patterns → use them → record outcome → confidence scores change
### P1-3: EWC++ Consolidation Execution
The Fisher Information Matrix and consolidation formula are defined but not executed.
**Implementation:**
- After each successful trajectory, compute diagonal Fisher approximation
- Store Fisher values per pattern dimension
- On consolidation, apply penalty: `L_total = L_new + (lambda/2) * sum(F_i * (theta_i - theta_old_i)^2)`
- Persist Fisher matrices to `.swarm/ewc-fisher.json`
**File:** `src/memory/ewc-consolidation.ts`
**Test:** Train → consolidate → retrain different domain → verify original patterns preserved
### P2-1: Coverage Hooks Test Integration
Read real coverage data from common test tools:
**Supported formats:**
- `coverage/coverage-summary.json` (Jest/Istanbul)
- `coverage/lcov.info` (lcov)
- `.nyc_output/` (NYC)
**Implementation:**
- `coverage-gaps` reads coverage files, computes per-file gaps
- `coverage-route` uses coverage data to prioritize test-related tasks
- Falls back to "no coverage data found" message (not 0%)
**File:** `src/commands/hooks.ts` (coverage-gaps, coverage-route, coverage-suggest)
### P2-2: Intelligence Stats → Neural Bridge
Connect `hooks intelligence stats` to ReasoningBank data:
- Read pattern count from `.claude-flow/neural/patterns.json`
- Read trajectory count from `.claude-flow/neural/stats.json`
- Read SONA adaptation metrics from intelligence system
**File:** `src/commands/hooks.ts` (intelligence stats handler)
## Non-Functional Bug Fixes (8 Items)
| Issue | Fix | File |
|-------|-----|------|
| #1335 Daemon scheduler | Verify interval comparison uses consistent timestamps | `daemon.ts` |
| #1122 Memory delete HNSW | See P1-1 above | `memory-initializer.ts` |
| #1117 Orphan processes | Kill child process on timeout rejection | `src/utils/` |
| #1116 daemon.log 0 bytes | Use `import('fs')` instead of `require('fs')` in ESM | `daemon.ts` |
| #1113 Scheduling intervals | Fix interval multiplier calculation | `daemon.ts` |
| #1333 MCP from / | Already fixed — path sanitization is correct | N/A |
| #1342 Post-bash junk files | Quote/escape tool output in hook args | `hook-handler.cjs` |
| #1331 stdin hang | Already fixed — timeout + pause cleanup works | N/A |
## Dependencies
| Package | Version | Purpose |
|---------|---------|---------|
| `@ruvector/learning-wasm` | 0.1.29 | MicroLoRA, Flash Attention WASM, Int8 quantization |
| `@claude-flow/memory` | 3.0.0-alpha.12 | AgentDB + ControllerRegistry |
## Success Criteria
1. `neural train --wasm` uses WASM backend and reports >2x speedup
2. `hive-mind consensus` validates votes with real quorum logic
3. `memory delete` removes both SQL row and embedding vector
4. `neural train` → `neural predict` → `hooks post-task` → confidence scores update
5. `coverage-gaps` reads real coverage files (or reports "no data" instead of 0%)
6. `hooks intelligence stats` shows real pattern/trajectory counts
7. All 8 bug fixes verified
8. Build clean, all 301+ command endpoints functional
## Consequences
### Positive
- Eliminates all known stub implementations
- WASM integration unlocks real Flash Attention and Int8 quantization performance
- Consensus protocols become functional for multi-agent coordination
- RL loop makes the learning system genuinely adaptive
### Negative
- `@ruvector/learning-wasm` adds ~2MB to package size
- Consensus overhead adds latency to hive-mind operations
- Real RL requires more computation than stub signal recording
### Risks
- WASM module may not load in all environments (fallback to JS required)
- Consensus with slow/unreachable agents needs timeout handling
- EWC++ Fisher matrices grow with pattern count — need size limits
+1 -1
View File
@@ -1789,7 +1789,7 @@
}
},
"@claude-flow/cli": {
"version": "3.5.21",
"version": "3.5.22",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {