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(intelligence): 4-issue bug cluster β€” Opus 4.8 + uptime + MCP orphan + Q-encoder

ruv455152da0367
diff --git a/.claude/helpers/statusline.cjs b/.claude/helpers/statusline.cjs
index d90f2da223..d2b3f971bc 100644
--- a/.claude/helpers/statusline.cjs
+++ b/.claude/helpers/statusline.cjs
@@ -259,7 +259,7 @@ function getModelName() {
const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
if (ts > latest) { latest = ts; modelId = id; }
}
- if (modelId.includes('opus')) return 'Opus 4.7';
+ if (modelId.includes('opus')) return 'Opus 4.8';
if (modelId.includes('sonnet')) return 'Sonnet 4.6';
if (modelId.includes('haiku')) return 'Haiku 4.5';
return modelId.split('-').slice(1, 3).join(' ');
@@ -275,7 +275,7 @@ function getModelName() {
const settings = getSettings();
if (settings && settings.model) {
const m = settings.model;
- if (m.includes('opus')) return 'Opus 4.7';
+ if (m.includes('opus')) return 'Opus 4.8';
if (m.includes('sonnet')) return 'Sonnet 4.6';
if (m.includes('haiku')) return 'Haiku 4.5';
}
diff --git a/v3/@claude-flow/cli/__tests__/agent-execute-models.test.ts b/v3/@claude-flow/cli/__tests__/agent-execute-models.test.ts
index 7d619202f0..1294730e6e 100644
--- a/v3/@claude-flow/cli/__tests__/agent-execute-models.test.ts
+++ b/v3/@claude-flow/cli/__tests__/agent-execute-models.test.ts
@@ -13,8 +13,11 @@ describe('#1906 β€” agent_execute model aliases resolve to current Claude 4.x id
it('sonnet β†’ claude-sonnet-4-6', () => {
expect(resolveAnthropicModel('sonnet')).toBe('claude-sonnet-4-6');
});
- it('opus β†’ claude-opus-4-7', () => {
- expect(resolveAnthropicModel('opus')).toBe('claude-opus-4-7');
+ it('opus β†’ claude-opus-4-8 (#2232 alias bump)', () => {
+ expect(resolveAnthropicModel('opus')).toBe('claude-opus-4-8');
+ });
+ it('opus-4.7 reaches the prior pin', () => {
+ expect(resolveAnthropicModel('opus-4.7')).toBe('claude-opus-4-7');
});
it('inherit β†’ the default (sonnet 4.6)', () => {
expect(resolveAnthropicModel('inherit')).toBe('claude-sonnet-4-6');
diff --git a/v3/@claude-flow/cli/__tests__/model-resolution-2232.test.ts b/v3/@claude-flow/cli/__tests__/model-resolution-2232.test.ts
new file mode 100644
index 0000000000..dc7571de2b
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/model-resolution-2232.test.ts
@@ -0,0 +1,44 @@
+// Regression tests for #2232 β€” Opus 4.8 alias + literal-id silent downgrade.
+//
+// Before the fix:
+// - `opus` mapped to `claude-opus-4-7` (a version behind).
+// - executeAgentTask used `MODEL_MAP[x] || DEFAULT` directly, so any literal
+// `claude-*` id silently collapsed to Sonnet 4.6.
+//
+// After the fix:
+// - `opus` β†’ `claude-opus-4-8`, `opus-4.7` reachable for the prior pin.
+// - Resolution funnels through `resolveAnthropicModel`, which passes literal
+// ids through unchanged.
+
+import { describe, it, expect } from 'vitest';
+import { resolveAnthropicModel, DEFAULT_ANTHROPIC_MODEL } from '../src/mcp-tools/agent-execute-core.js';
+
+describe('model resolution (#2232)', () => {
+ it('maps the `opus` alias to the current Opus (4.8)', () => {
+ expect(resolveAnthropicModel('opus')).toBe('claude-opus-4-8');
+ });
+
+ it('keeps the prior Opus pin reachable via `opus-4.7`', () => {
+ expect(resolveAnthropicModel('opus-4.7')).toBe('claude-opus-4-7');
+ });
+
+ it('maps `sonnet` and `haiku` aliases to current ids', () => {
+ expect(resolveAnthropicModel('sonnet')).toBe('claude-sonnet-4-6');
+ expect(resolveAnthropicModel('haiku')).toBe('claude-haiku-4-5-20251001');
+ });
+
+ it('passes a literal Anthropic model id through unchanged (no silent Sonnet fallback)', () => {
+ expect(resolveAnthropicModel('claude-opus-4-8')).toBe('claude-opus-4-8');
+ expect(resolveAnthropicModel('claude-opus-4-8')).not.toBe(DEFAULT_ANTHROPIC_MODEL);
+ expect(resolveAnthropicModel('claude-opus-4-7')).toBe('claude-opus-4-7');
+ });
+
+ it('strips the `anthropic:` prefix', () => {
+ expect(resolveAnthropicModel('anthropic:claude-opus-4-8')).toBe('claude-opus-4-8');
+ });
+
+ it('falls back to DEFAULT only when the input is undefined / empty', () => {
+ expect(resolveAnthropicModel(undefined)).toBe(DEFAULT_ANTHROPIC_MODEL);
+ expect(resolveAnthropicModel('')).toBe(DEFAULT_ANTHROPIC_MODEL);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/parent-death-watchdog-2234.test.ts b/v3/@claude-flow/cli/__tests__/parent-death-watchdog-2234.test.ts
new file mode 100644
index 0000000000..e06eea063e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/parent-death-watchdog-2234.test.ts
@@ -0,0 +1,98 @@
+// Regression tests for #2234 β€” parent-death watchdog so `ruflo mcp start`
+// doesn't orphan and accumulate ~1 GB of stale MCP servers when Claude Code
+// restarts.
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { installParentDeathWatchdog } from '../src/runtime/parent-death-watchdog.js';
+
+describe('parent-death watchdog (#2234)', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('fires the orphan hook + exits when ppid transitions to 1', async () => {
+ vi.useFakeTimers();
+ let ppid = 5000;
+ const exit = vi.fn();
+ const onOrphaned = vi.fn();
+ const wd = installParentDeathWatchdog({
+ intervalMs: 100,
+ ppidGetter: () => ppid,
+ exit,
+ onOrphaned,
+ });
+
+ // Still parented to Claude Code β†’ no action.
+ await vi.advanceTimersByTimeAsync(150);
+ expect(onOrphaned).not.toHaveBeenCalled();
+ expect(exit).not.toHaveBeenCalled();
+
+ // Parent dies β†’ reparented to launchd/init.
+ ppid = 1;
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(onOrphaned).toHaveBeenCalledTimes(1);
+ expect(exit).toHaveBeenCalledWith(0);
+ wd.stop();
+ });
+
+ it('never fires when the process started with ppid=1 (already daemonised)', async () => {
+ vi.useFakeTimers();
+ const exit = vi.fn();
+ const onOrphaned = vi.fn();
+ const wd = installParentDeathWatchdog({
+ intervalMs: 50,
+ ppidGetter: () => 1, // initial AND current ppid is init
+ exit,
+ onOrphaned,
+ });
+
+ await vi.advanceTimersByTimeAsync(300);
+
+ expect(onOrphaned).not.toHaveBeenCalled();
+ expect(exit).not.toHaveBeenCalled();
+ wd.stop();
+ });
+
+ it('only triggers once (idempotent on rapid re-checks)', async () => {
+ const exit = vi.fn();
+ const onOrphaned = vi.fn();
+ let ppid = 4242;
+ const wd = installParentDeathWatchdog({
+ intervalMs: 999_999, // disable the timer; use manual checks
+ ppidGetter: () => ppid,
+ exit,
+ onOrphaned,
+ });
+
+ ppid = 1;
+ await wd.checkOnce();
+ await wd.checkOnce();
+ await wd.checkOnce();
+ expect(onOrphaned).toHaveBeenCalledTimes(1);
+ expect(exit).toHaveBeenCalledTimes(1);
+ wd.stop();
+ });
+
+ it('exit code 1 when the orphan hook throws', async () => {
+ const exit = vi.fn();
+ const wd = installParentDeathWatchdog({
+ intervalMs: 999_999,
+ ppidGetter: () => 1,
+ exit,
+ onOrphaned: () => { throw new Error('cleanup failed'); },
+ });
+ // ppidGetter returns 1 immediately, but initialPpid was also 1 β†’ wouldn't
+ // fire normally. Force it via a separate watchdog with transition:
+ wd.stop();
+ let ppid = 999;
+ const wd2 = installParentDeathWatchdog({
+ intervalMs: 999_999,
+ ppidGetter: () => ppid,
+ exit,
+ onOrphaned: () => { throw new Error('boom'); },
+ });
+ ppid = 1;
+ await wd2.checkOnce();
+ expect(exit).toHaveBeenCalledWith(1);
+ wd2.stop();
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/q-state-encoder-2239.test.ts b/v3/@claude-flow/cli/__tests__/q-state-encoder-2239.test.ts
new file mode 100644
index 0000000000..744f17132e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/q-state-encoder-2239.test.ts
@@ -0,0 +1,88 @@
+// Regression tests for #2239 β€” Q-state encoder discarded the keyword block.
+//
+// The previous 31-bit truncating fold collapsed four routing-keyword-distinct
+// tasks (`test/review/architect/optimize the new module now`) to ONE Q-state.
+// After the FNV-1a fold and encoder-version=2 migration, keyword-distinct
+// tasks must produce distinct state keys, and a persisted v1 model must
+// reset its Q-table on load (keys are not comparable across encoder versions).
+
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { QLearningRouter } from '../src/ruvector/q-learning-router.js';
+
+const r = new QLearningRouter();
+const stateKey = (s: string) => r.getStateKey(s);
+
+describe('Q-state encoder (#2239)', () => {
+ it('produces distinct state keys for the reporter\'s six keyword-distinct tasks', () => {
+ const tasks = [
+ 'implement the new module now',
+ 'test the new module now',
+ 'review the new module now',
+ 'architect the new module now',
+ 'research the new module now',
+ 'optimize the new module now',
+ ];
+ const keys = tasks.map(stateKey);
+ expect(new Set(keys).size).toBe(tasks.length); // no collapse to one Q-state
+ });
+
+ it('still produces the SAME key for the SAME input (deterministic)', () => {
+ expect(stateKey('test this module')).toBe(stateKey('test this module'));
+ });
+
+ it('produces a `fstate_…` shape', () => {
+ expect(stateKey('refactor the API')).toMatch(/^fstate_[0-9a-z]+$/);
+ });
+});
+
+describe('encoder-version migration (#2239)', () => {
+ it('resets the Q-table on encoder-version mismatch (v1 persisted β†’ v2 current)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'q-mig-'));
+ const modelPath = join(dir, 'q-learning-model.json');
+ // A v1 persisted model with one fake state β€” v1 keys are not portable.
+ writeFileSync(modelPath, JSON.stringify({
+ version: '1.0.0',
+ // encoderVersion missing β†’ treated as 1
+ config: { numActions: 8 },
+ qTable: { 'fstate_legacy': { qValues: [99, 99, 99, 99, 99, 99, 99, 99], visits: 50 } },
+ stats: { stepCount: 100, updateCount: 50, avgTDError: 0.1, epsilon: 0.5 },
+ metadata: { savedAt: new Date(0).toISOString(), totalExperiences: 100 },
+ }));
+
+ const router = new QLearningRouter({ modelPath });
+ const loaded = await router.loadModel(modelPath);
+ expect(loaded).toBe(true);
+
+ // The legacy state must NOT survive (its key was computed by the old fold).
+ const exported = router.export();
+ expect(Object.keys(exported)).not.toContain('fstate_legacy');
+
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('a v2 persisted model loads its Q-table intact', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'q-v2-'));
+ const modelPath = join(dir, 'q-learning-model.json');
+ // Compute a real v2 key from the live encoder.
+ const seed = new QLearningRouter();
+ const realKey = seed.getStateKey('keep this entry across restart');
+
+ writeFileSync(modelPath, JSON.stringify({
+ version: '1.0.0',
+ encoderVersion: 2,
+ config: { numActions: 8 },
+ qTable: { [realKey]: { qValues: [1, 2, 3, 4, 5, 6, 7, 8], visits: 7 } },
+ stats: { stepCount: 0, updateCount: 0, avgTDError: 0, epsilon: 0.5 },
+ metadata: { savedAt: new Date().toISOString(), totalExperiences: 0 },
+ }));
+
+ const router = new QLearningRouter({ modelPath });
+ expect(await router.loadModel(modelPath)).toBe(true);
+ expect(Object.keys(router.export())).toContain(realKey);
+
+ rmSync(dir, { recursive: true, force: true });
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/system-uptime-2235.test.ts b/v3/@claude-flow/cli/__tests__/system-uptime-2235.test.ts
new file mode 100644
index 0000000000..a33ea2a7fe
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/system-uptime-2235.test.ts
@@ -0,0 +1,27 @@
+// Regression test for #2235(B) β€” system_status.uptime was reading a persisted
+// metrics.startTime (the file's creation timestamp) instead of the live process
+// uptime, so a freshly-spawned MCP server reported ~8.8 days of uptime.
+
+import { describe, it, expect } from 'vitest';
+import { systemTools } from '../src/mcp-tools/system-tools.js';
+
+const statusTool = systemTools.find((t) => t.name === 'system_status')!;
+
+describe('system_status.uptime (#2235 B)', () => {
+ it('reports the live process uptime, not a persisted/stale value', async () => {
+ const r = (await statusTool.handler({ verbose: false })) as { uptime: number; uptimeFormatted: string };
+ // The vitest process itself has been running for at most a few minutes;
+ // a stale persisted-startTime bug would yield values in the millions of
+ // ms (hours/days). Cap generously to allow CI slowness.
+ expect(r.uptime).toBeGreaterThanOrEqual(0);
+ expect(r.uptime).toBeLessThan(60 * 60 * 1000); // < 1 hour
+ expect(typeof r.uptimeFormatted).toBe('string');
+ });
+
+ it('produces a non-decreasing uptime across two reads (live counter, not file mtime)', async () => {
+ const a = (await statusTool.handler({})) as { uptime: number };
+ await new Promise((res) => setTimeout(res, 25));
+ const b = (await statusTool.handler({})) as { uptime: number };
+ expect(b.uptime).toBeGreaterThanOrEqual(a.uptime);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.ts
index fcf23c78b8..8f11b12763 100644
--- a/v3/@claude-flow/cli/src/commands/mcp.ts
+++ b/v3/@claude-flow/cli/src/commands/mcp.ts
@@ -9,6 +9,7 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { select, confirm } from '../prompt.js';
+import { installParentDeathWatchdog } from '../runtime/parent-death-watchdog.js';
import {
MCPServerManager,
createMCPServerManager,
@@ -185,6 +186,17 @@ const startCommand: Command = {
// Start the server
const status = await manager.start();
+ // #2234 β€” exit cleanly if Claude Code (our parent) exits and we get
+ // reparented to launchd/init (ppid === 1). Otherwise the node stdio
+ // server lingers as an orphan, accumulating ~50 MB per restart, and an
+ // arbitrary stale orphan can later win the stdio handshake and serve
+ // pre-fix code from the user's npx cache.
+ installParentDeathWatchdog({
+ onOrphaned: async () => {
+ try { await manager.stop(); } catch { /* best-effort */ }
+ },
+ });
+
output.writeln();
output.printTable({
columns: [
diff --git a/v3/@claude-flow/cli/src/init/settings-generator.ts b/v3/@claude-flow/cli/src/init/settings-generator.ts
index b847c131d0..7bd50ddd90 100644
--- a/v3/@claude-flow/cli/src/init/settings-generator.ts
+++ b/v3/@claude-flow/cli/src/init/settings-generator.ts
@@ -85,7 +85,7 @@ export function generateSettings(options: InitOptions): object {
shell: platform.shell,
},
modelPreferences: {
- default: 'claude-opus-4-7',
+ default: 'claude-opus-4-8',
routing: 'claude-haiku-4-5-20251001',
},
agentTeams: {
diff --git a/v3/@claude-flow/cli/src/init/statusline-generator.ts b/v3/@claude-flow/cli/src/init/statusline-generator.ts
index 2cb3163b5a..26643f4a59 100644
--- a/v3/@claude-flow/cli/src/init/statusline-generator.ts
+++ b/v3/@claude-flow/cli/src/init/statusline-generator.ts
@@ -286,7 +286,7 @@ function getModelName() {
const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
if (ts > latest) { latest = ts; modelId = id; }
}
- if (modelId.includes('opus')) return 'Opus 4.7';
+ if (modelId.includes('opus')) return 'Opus 4.8';
if (modelId.includes('sonnet')) return 'Sonnet 4.6';
if (modelId.includes('haiku')) return 'Haiku 4.5';
return modelId.split('-').slice(1, 3).join(' ');
@@ -302,7 +302,7 @@ function getModelName() {
const settings = getSettings();
if (settings && settings.model) {
const m = settings.model;
- if (m.includes('opus')) return 'Opus 4.7';
+ if (m.includes('opus')) return 'Opus 4.8';
if (m.includes('sonnet')) return 'Sonnet 4.6';
if (m.includes('haiku')) return 'Haiku 4.5';
}
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
index d22c56df6f..78421de4b4 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
@@ -16,7 +16,7 @@ const STORAGE_DIR = '.claude-flow';
const AGENT_DIR = 'agents';
const AGENT_FILE = 'store.json';
-type ClaudeModel = 'haiku' | 'sonnet' | 'opus' | 'inherit';
+type ClaudeModel = 'haiku' | 'sonnet' | 'opus' | 'opus-4.7' | 'inherit';
export interface AgentRecord {
agentId: string;
@@ -54,9 +54,9 @@ function saveAgentStore(store: AgentStore): void {
writeFileSync(getAgentPath(), JSON.stringify(store, null, 2), 'utf-8');
}
-// #1906 β€” these were stuck on Claude-3.x ids that the Anthropic API now
-// 404s. Current model ids (Claude 4.x family):
-// Opus 4.7 β†’ claude-opus-4-7
+// #1906/#2232 β€” Current model ids (Claude 4.x family):
+// Opus 4.8 β†’ claude-opus-4-8 (current, the `opus` alias)
+// Opus 4.7 β†’ claude-opus-4-7 (prior pin, reachable via `opus-4.7`)
// Sonnet 4.6 β†’ claude-sonnet-4-6
// Haiku 4.5 β†’ claude-haiku-4-5-20251001
// `inherit` and the various defaults below all map to Sonnet 4.6.
@@ -64,7 +64,8 @@ export const DEFAULT_ANTHROPIC_MODEL = 'claude-sonnet-4-6';
const MODEL_MAP: Record<string, string> = {
haiku: 'claude-haiku-4-5-20251001',
sonnet: 'claude-sonnet-4-6',
- opus: 'claude-opus-4-7',
+ opus: 'claude-opus-4-8',
+ 'opus-4.7': 'claude-opus-4-7',
inherit: DEFAULT_ANTHROPIC_MODEL,
};
@@ -436,7 +437,9 @@ export async function executeAgentTask(input: AgentExecuteInput): Promise<AgentE
if (!agent) return { success: false, agentId: input.agentId, error: 'Agent not found' };
if (agent.status === 'terminated') return { success: false, agentId: input.agentId, error: 'Agent has been terminated' };
- const anthropicModel = MODEL_MAP[agent.model || 'sonnet'] || DEFAULT_ANTHROPIC_MODEL;
+ // #2232 β€” Single source of truth so literal claude-* ids pass through
+ // instead of silently collapsing to Sonnet via the old MODEL_MAP[]||DEFAULT fold.
+ const anthropicModel = resolveAnthropicModel(agent.model || 'sonnet');
const systemPrompt = input.systemPrompt ||
`You are a ${agent.agentType} agent operating as part of a Ruflo swarm. ` +
`Agent ID: ${input.agentId}. Domain: ${agent.domain ?? 'general'}. ` +
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
index 5239d6d6a8..e65a62113d 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
@@ -22,7 +22,7 @@ const AGENT_FILE = 'store.json';
const HIVE_AGENT_FILE = 'agents.json';
// Model types matching Claude Agent SDK
-type ClaudeModel = 'haiku' | 'sonnet' | 'opus' | 'inherit';
+type ClaudeModel = 'haiku' | 'sonnet' | 'opus' | 'opus-4.7' | 'inherit';
interface AgentRecord {
agentId: string;
@@ -159,7 +159,7 @@ async function determineAgentModel(
tier?: 1 | 2 | 3;
}> {
// 1. Explicit model in config
- if (config.model && ['haiku', 'sonnet', 'opus', 'inherit'].includes(config.model as string)) {
+ if (config.model && ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'].includes(config.model as string)) {
return { model: config.model as ClaudeModel, routedBy: 'explicit' };
}
@@ -229,8 +229,8 @@ export const agentTools: MCPTool[] = [
domain: { type: 'string', description: 'Agent domain' },
model: {
type: 'string',
- enum: ['haiku', 'sonnet', 'opus', 'inherit'],
- description: 'Claude model to use (haiku=fast/cheap, sonnet=balanced, opus=most capable)'
+ enum: ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'],
+ description: 'Claude model alias (haiku=fast/cheap, sonnet=balanced, opus=current Opus 4.8, opus-4.7=prior Opus pin)'
},
task: { type: 'string', description: 'Task description for intelligent model routing' },
},
diff --git a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts
index 4540bed490..8abadc8aad 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts
@@ -112,7 +112,10 @@ export const systemTools: MCPTool[] = [
},
handler: async (input) => {
const metrics = loadMetrics();
- const uptime = Date.now() - new Date(metrics.startTime).getTime();
+ // #2235(B) β€” live process uptime, not the persisted metrics.startTime
+ // (which is the file's creation timestamp and survived across restarts,
+ // making system_status report stale ~8.8-day uptime on a fresh server).
+ const uptime = Math.floor(process.uptime() * 1000);
const status = {
status: metrics.health >= 0.8 ? 'healthy' : metrics.health >= 0.5 ? 'degraded' : 'unhealthy',
@@ -252,7 +255,7 @@ export const systemTools: MCPTool[] = [
} catch { /* tracker not available β€” fall back to stored value */ }
return store.requests;
})(),
- uptime: Date.now() - new Date(store.startTime).getTime(),
+ uptime: Math.floor(process.uptime() * 1000), // #2235(B) β€” live process uptime
lastCheck: new Date().toISOString(),
};
diff --git a/v3/@claude-flow/cli/src/runtime/parent-death-watchdog.ts b/v3/@claude-flow/cli/src/runtime/parent-death-watchdog.ts
new file mode 100644
index 0000000000..979b2b76cc
--- /dev/null
+++ b/v3/@claude-flow/cli/src/runtime/parent-death-watchdog.ts
@@ -0,0 +1,91 @@
+/**
+ * Parent-death watchdog (#2234).
+ *
+ * `ruflo mcp start` runs as a double-forked grandchild of Claude Code (`npx -y
+ * ruflo … mcp start` β†’ `npm exec …` β†’ `node … mcp start`). When Claude Code
+ * exits, only the `npm exec` shim is terminated; the `node` server reparents to
+ * `launchd`/`init` (`ppid === 1`) and silently lingers β€” leaving ~50 MB and an
+ * open database handle per restart. Over a week this accumulates to ~20
+ * orphaned servers (~1 GB), and an arbitrary stale one can win the next stdio
+ * handshake, transparently serving superseded code.
+ *
+ * Cheap, robust fix: poll `process.ppid`. When it becomes 1 (and didn't start
+ * there), our original parent has exited β€” we're orphaned. Run the cleanup
+ * hook and exit cleanly.
+ *
+ * @module runtime/parent-death-watchdog
+ */
+
+export interface ParentDeathWatchdogOptions {
+ /** Poll interval in ms. Default 2000. */
+ intervalMs?: number;
+ /**
+ * Cleanup hook fired when orphaning is detected. May be async. After it
+ * resolves (or throws), the process exits with code 0 (success) / 1 (error).
+ * Defaults to `process.exit(0)` directly.
+ */
+ onOrphaned?: () => void | Promise<void>;
+ /** Override `process.ppid` getter (tests). */
+ ppidGetter?: () => number;
+ /** Override `process.exit` (tests). */
+ exit?: (code: number) => void;
+}
+
+export interface ParentDeathWatchdog {
+ stop(): void;
+ /** Manually trigger the orphan check (used by tests). */
+ checkOnce(): Promise<void>;
+}
+
+/**
+ * Install a parent-death watchdog. Safe to call once per process; calling
+ * twice replaces the previous interval.
+ */
+export function installParentDeathWatchdog(opts: ParentDeathWatchdogOptions = {}): ParentDeathWatchdog {
+ const intervalMs = opts.intervalMs ?? 2000;
+ const get = opts.ppidGetter ?? (() => process.ppid);
+ const exit = opts.exit ?? ((code: number) => process.exit(code));
+ const onOrphaned = opts.onOrphaned;
+
+ const initialPpid = get();
+ let triggered = false;
+ let timer: NodeJS.Timeout | undefined;
+
+ const triggerOrphaned = async (): Promise<void> => {
+ if (triggered) return;
+ triggered = true;
+ if (timer) {
+ clearInterval(timer);
+ timer = undefined;
+ }
+ try {
+ if (onOrphaned) await onOrphaned();
+ exit(0);
+ } catch {
+ exit(1);
+ }
+ };
+
+ const checkOnce = async (): Promise<void> => {
+ // Only trigger when we *transition* to ppid=1; if we already started there
+ // (process launched directly under launchd/init) it isn't an orphan event.
+ const ppid = get();
+ if (ppid === 1 && initialPpid !== 1) await triggerOrphaned();
+ };
+
+ timer = setInterval(() => {
+ void checkOnce();
+ }, intervalMs);
+ // Don't keep the event loop alive on the watchdog alone.
+ if (typeof (timer as NodeJS.Timeout).unref === 'function') (timer as NodeJS.Timeout).unref();
+
+ return {
+ stop() {
+ if (timer) {
+ clearInterval(timer);
+ timer = undefined;
+ }
+ },
+ checkOnce,
+ };
+}
diff --git a/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts b/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts
index 01883adf69..a809009507 100644
--- a/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts
+++ b/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts
@@ -108,6 +108,15 @@ interface CacheEntry {
*/
interface PersistedModel {
version: string;
+ /**
+ * State-key encoder version. v1 was the 31-bit truncating fold that
+ * silently discarded the keyword block (features 0–31). v2 is a lossless
+ * 32-bit FNV-1a fold over the full quantized vector. See #2239.
+ *
+ * On version mismatch, the qTable is reset (keys are computed with the old
+ * encoder and would never be matched by new lookups); stats/epsilon are kept.
+ */
+ encoderVersion?: number;
config: Partial<QLearningRouterConfig>;
qTable: Record<string, { qValues: number[]; visits: number }>;
stats: {
@@ -122,6 +131,9 @@ interface PersistedModel {
};
}
+/** Current state-key encoder version (see PersistedModel.encoderVersion). */
+const ENCODER_VERSION = 2;
+
/**
* Default configuration
*/
@@ -255,8 +267,18 @@ export class QLearningRouter {
return false;
}
- // Import Q-table
- this.import(model.qTable);
+ // #2239 β€” Encoder-version migration guard. v1 state keys were computed
+ // by a fold that silently dropped the keyword block, so they cannot be
+ // matched by v2 lookups. Skip the qTable import on mismatch (keep
+ // stats/epsilon so learning curve survives a restart).
+ const persistedEncoder = model.encoderVersion ?? 1;
+ if (persistedEncoder === ENCODER_VERSION) {
+ this.import(model.qTable);
+ } else {
+ console.warn(
+ `[Q-Learning] Encoder version mismatch (persisted=${persistedEncoder}, current=${ENCODER_VERSION}); resetting Q-table (see #2239).`,
+ );
+ }
// Restore stats
this.stepCount = model.stats.stepCount || 0;
@@ -286,6 +308,7 @@ export class QLearningRouter {
const model: PersistedModel = {
version: '1.0.0',
+ encoderVersion: ENCODER_VERSION, // #2239
config: {
learningRate: this.config.learningRate,
gamma: this.config.gamma,
@@ -709,6 +732,15 @@ export class QLearningRouter {
return `state_${hash}`;
}
+ /**
+ * Public state-key encoder (#2239). This is exactly what `route()` uses
+ * to look up Q-values, so testing it directly is testing the binding the
+ * Q-learner actually sees.
+ */
+ getStateKey(context: string): string {
+ return this.hashStateOptimized(context);
+ }
+
/**
* Optimized state hashing using feature extraction
* Creates a more semantic representation of the task context
@@ -785,10 +817,17 @@ export class QLearningRouter {
/**
* Convert feature vector to state key
- * Uses locality-sensitive hashing for similar contexts
+ * Uses locality-sensitive hashing for similar contexts.
+ *
+ * #2239 β€” the previous fold was `((hash << 4) ^ q[i]) & 0x7fffffff` over 16
+ * 4-bit groups: each group i landed at bit 4Β·(15βˆ’i), so groups 0–7 (= the
+ * entire keyword block, features 0–31) shifted past the 31-bit mask and were
+ * discarded. Keyword-distinct tasks collapsed to one Q-state. We now use a
+ * 32-bit FNV-1a hash, which mixes every quantized group losslessly into the
+ * state key. Encoder version bumped to 2; see PersistedModel.encoderVersion.
*/
private featureVectorToKey(features: Float32Array): string {
- // Quantize features to create discrete state
+ // Quantize features into 4-bit groups (16 groups for a 64-dim vector).
const quantized: number[] = [];
for (let i = 0; i < features.length; i += 4) {
let bucket = 0;
@@ -800,13 +839,13 @@ export class QLearningRouter {
quantized.push(bucket);
}
- // Create hash from quantized values
- let hash = 0;
+ // 32-bit FNV-1a over the quantized array β€” every group contributes.
+ let hash = 0x811c9dc5 | 0; // FNV offset basis
for (let i = 0; i < quantized.length; i++) {
- hash = ((hash << 4) ^ quantized[i]) & 0x7fffffff;
+ hash ^= quantized[i] & 0xff;
+ hash = Math.imul(hash, 0x01000193); // FNV prime
}
-
- return `fstate_${hash.toString(36)}`;
+ return `fstate_${(hash >>> 0).toString(36)}`;
}
/**