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: reader/writer store mismatches β€” metrics, backup, swarm status (#2797 #2798 #2799)

ruv310ab5f16184
diff --git a/v3/@claude-flow/cli/__tests__/hooks-metrics-swarm-backup-2797-2798-2799.test.ts b/v3/@claude-flow/cli/__tests__/hooks-metrics-swarm-backup-2797-2798-2799.test.ts
new file mode 100644
index 0000000000..17fe01483b
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hooks-metrics-swarm-backup-2797-2798-2799.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Regression guards for the 2026-07-27 "clean exit, no real work reflected"
+ * batch β€” three reader/writer-mismatch bugs reported by vidaunited:
+ *
+ * #2797 β€” hooks metrics Pattern Learning always 0 (pattern reader filtered
+ * on a key/type shape no writer produces)
+ * #2798 β€” memory backup silent no-op under CLAUDE_FLOW_ENCRYPT_AT_REST
+ * (better-sqlite3 online backup can't open the RFE1 blob)
+ * #2799 β€” swarm status always Total 0 agents (read .swarm/agents/ that
+ * no writer creates, while agent spawn writes swarm-activity.json)
+ *
+ * All three exercised via real execFileSync against bin/cli.js in temp cwds.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, existsSync, readdirSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomBytes } from 'node:crypto';
+
+const CLI = join(__dirname, '..', 'bin', 'cli.js');
+
+function run(args: string[], cwd: string, env: NodeJS.ProcessEnv = {}): { stdout: string; exit: number } {
+ try {
+ const stdout = execFileSync('node', [CLI, ...args], {
+ cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, ...env },
+ });
+ return { stdout, exit: 0 };
+ } catch (err) {
+ const e = err as { status?: number; stdout?: Buffer; stderr?: Buffer };
+ return { stdout: (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? ''), exit: e.status ?? -1 };
+ }
+}
+
+describe('#2797 hooks metrics Pattern Learning counts real writes', () => {
+ it('Pattern Learning total is non-zero after a store-results post-task', () => {
+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-2797-'));
+ try {
+ run(['memory', 'init'], wd);
+ run(['hooks', 'post-task', '-i', 't1', '--success', 'true', '-q', '0.95', '--task', 'some task', '--agent', 'coder', '--store-results'], wd);
+ const { stdout } = run(['hooks', 'metrics', '--format', 'json'], wd);
+ const data = JSON.parse(stdout.slice(stdout.indexOf('{')));
+ expect(data.patterns.total).toBeGreaterThan(0);
+ } finally {
+ try { rmSync(wd, { recursive: true, force: true }); } catch { /* */ }
+ }
+ }, 60_000);
+});
+
+describe('#2798 memory backup falls back to byte-copy under encryption', () => {
+ it('produces a snapshot when CLAUDE_FLOW_ENCRYPT_AT_REST=1 (RFE1 blob)', () => {
+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-2798-'));
+ const key = randomBytes(32).toString('hex');
+ const env = { CLAUDE_FLOW_ENCRYPT_AT_REST: '1', CLAUDE_FLOW_ENCRYPTION_KEY: key };
+ try {
+ run(['memory', 'init'], wd, env);
+ run(['memory', 'store', '--key', 'k', '--value', 'encrypted note'], wd, env);
+ // Confirm the source really is the encrypted RFE1 blob (not native SQLite).
+ const header = readFileSync(join(wd, '.swarm', 'memory.db')).subarray(0, 4).toString('latin1');
+ expect(header).toBe('RFE1');
+ const { stdout } = run(['memory', 'backup'], wd, env);
+ expect(stdout).toMatch(/Backed up β†’/);
+ const backups = existsSync(join(wd, '.swarm', 'backups'))
+ ? readdirSync(join(wd, '.swarm', 'backups')).filter((f) => /^memory-.*\.db$/.test(f))
+ : [];
+ expect(backups.length).toBeGreaterThan(0);
+ } finally {
+ try { rmSync(wd, { recursive: true, force: true }); } catch { /* */ }
+ }
+ }, 60_000);
+});
+
+describe('#2799 swarm status reflects spawned agents', () => {
+ it('swarm status agent total matches agent spawn count (via swarm-activity.json)', () => {
+ const wd = mkdtempSync(join(tmpdir(), 'ruflo-2799-'));
+ try {
+ run(['swarm', 'init', '--topology', 'mesh', '--max-agents', '5'], wd);
+ for (const a of ['coder', 'reviewer', 'researcher', 'tester']) {
+ run(['agent', 'spawn', '--type', a, '--name', `x-${a}`], wd);
+ }
+ const status = run(['swarm', 'status'], wd).stdout;
+ // The Agents section's Total must now be 4, not 0. Match the "Total | 4"
+ // row in the agents table (allow ANSI/box chars around it).
+ expect(status).toMatch(/Total\D+4/);
+ // Sanity: the activity file the fix reads was actually written.
+ const activityPath = join(wd, '.claude-flow', 'metrics', 'swarm-activity.json');
+ if (existsSync(activityPath)) {
+ const activity = JSON.parse(readFileSync(activityPath, 'utf-8'));
+ expect(activity.swarm.agent_count).toBe(4);
+ }
+ } finally {
+ try { rmSync(wd, { recursive: true, force: true }); } catch { /* */ }
+ }
+ }, 60_000);
+});
diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.ts
index f44a972c1f..adfc853f65 100644
--- a/v3/@claude-flow/cli/src/commands/swarm.ts
+++ b/v3/@claude-flow/cli/src/commands/swarm.ts
@@ -54,6 +54,29 @@ function getSwarmStatus(swarmId?: string) {
}
}
+ // #2799 β€” `agent spawn` never writes `.swarm/agents/*.json`; it records
+ // the count in `.claude-flow/metrics/swarm-activity.json` (via
+ // updateSwarmActivityMetrics in commands/agent.ts). So when the agents
+ // dir is empty, reconcile against that authoritative activity file
+ // instead of reporting Total 0 while `agent list` shows N agents.
+ if (totalAgents === 0) {
+ try {
+ const activityPath = path.join(process.cwd(), '.claude-flow', 'metrics', 'swarm-activity.json');
+ if (fs.existsSync(activityPath)) {
+ const activity = JSON.parse(fs.readFileSync(activityPath, 'utf-8'));
+ const count = Math.max(0, Number((activity?.swarm?.agent_count)) || 0);
+ if (count > 0) {
+ totalAgents = count;
+ // swarm-activity.json tracks a count, not per-agent status; treat
+ // a coordination-active swarm's agents as active, else idle.
+ activeAgents = activity?.swarm?.coordination_active ? count : 0;
+ }
+ }
+ } catch {
+ // Ignore β€” fall back to 0
+ }
+ }
+
// Get session count
let sessionCount = 0;
if (fs.existsSync(sessionDir)) {
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 a79e70f8e8..9f7461a036 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -470,6 +470,9 @@ interface MemoryEntry {
key: string;
value: unknown;
metadata?: Record<string, unknown>;
+ // #2797 β€” the post-task dual-write persists `namespace: 'patterns'`
+ // on routing-decision entries; the pattern counter reads it.
+ namespace?: string;
storedAt: string;
accessCount: number;
lastAccessed: string;
@@ -522,11 +525,22 @@ function getIntelligenceStatsFromMemory(): {
(typeof e.value === 'object' && e.value !== null && (e.value as Record<string, unknown>).success === true)
);
- // Count patterns
+ // Count patterns (#2797). The original filter matched only
+ // `key.includes('pattern')` / `metadata.type==='pattern'` /
+ // `learned-*`, but NO writer in the codebase ever produces that
+ // shape β€” so Pattern Learning was permanently 0. The post-task
+ // dual-write (#2786 fix-2) persists learned patterns as
+ // `routing-decision:*` entries in the `patterns` namespace with
+ // `metadata.type: 'routing-decision'`. Those ARE the learned
+ // patterns the metric is meant to count, so include them: any entry
+ // whose namespace is `patterns`, plus the original shapes for
+ // forward-compatibility with a future explicit `pattern` writer.
const patternEntries = entries.filter(e =>
e.key.includes('pattern') ||
e.metadata?.type === 'pattern' ||
- e.key.startsWith('learned-')
+ e.key.startsWith('learned-') ||
+ e.namespace === 'patterns' ||
+ e.metadata?.type === 'routing-decision'
);
// Categorize patterns
diff --git a/v3/@claude-flow/cli/src/services/memory-backup.ts b/v3/@claude-flow/cli/src/services/memory-backup.ts
index 44ae4d9a57..d7093c42ef 100644
--- a/v3/@claude-flow/cli/src/services/memory-backup.ts
+++ b/v3/@claude-flow/cli/src/services/memory-backup.ts
@@ -71,6 +71,44 @@ export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupRe
db.close();
} catch (e) {
try { db?.close(); } catch { /* */ }
+ // #2798 β€” under CLAUDE_FLOW_ENCRYPT_AT_REST the source is an RFE1
+ // blob, not native SQLite, so better-sqlite3's online-backup API
+ // throws "file is not a database" and the run was silently recorded
+ // as skipped (users with encryption had ZERO backups behind a green
+ // status). The online-backup API only exists to avoid tearing a live
+ // WAL-mode DB; that concern doesn't apply to the encrypted file (sql.js
+ // rewrites it wholesale per flush), so a plain byte copy is a valid
+ // snapshot. Fall back to it before giving up.
+ try {
+ fs.copyFileSync(dbPath, destPath);
+ const copiedBytes = fs.statSync(destPath).size;
+ if (copiedBytes > 0) {
+ // Fall through to rotation/offsite/return below via a flag path.
+ // (Mirror the success path's tail by re-using the same code.)
+ const keep = typeof opts.keep === 'number' && opts.keep > 0 ? opts.keep : 7;
+ const rotatedAway: string[] = [];
+ try {
+ const snaps = fs.readdirSync(destDir).filter(f => /^memory-.*\.db$/.test(f)).sort();
+ while (snaps.length > keep) {
+ const old = snaps.shift()!;
+ try { fs.rmSync(path.join(destDir, old), { force: true }); rotatedAway.push(old); } catch { /* */ }
+ }
+ } catch { /* */ }
+ let gcsUri: string | undefined;
+ if (opts.gcs) {
+ try {
+ const { execFileSync } = await import('child_process');
+ const dest = opts.gcs.replace(/\/+$/, '') + '/' + path.basename(destPath);
+ execFileSync('gcloud', ['storage', 'cp', destPath, dest], { stdio: ['ignore', 'ignore', 'inherit'] });
+ gcsUri = dest;
+ } catch { /* offsite failed β€” local snapshot stands */ }
+ }
+ if (opts.verbose) {
+ console.log(`memory DB backed up (byte-copy, encrypted-at-rest) β†’ ${destPath} (${Math.round(copiedBytes / 1024)} KB)`);
+ }
+ return { backedUp: true, path: destPath, sizeBytes: copiedBytes, rotatedAway, gcsUri };
+ }
+ } catch { /* byte-copy also failed β€” report the original error */ }
return { backedUp: false, skipped: `backup failed: ${(e as Error)?.message ?? e}` };
}