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

feat: ship adaptive swarm and resolve top runtime issues (#2848)

rUv9cf769ccceed
diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjs
index 999d58b413..5850af830b 100644
--- a/scripts/audit-env-var-precedence.mjs
+++ b/scripts/audit-env-var-precedence.mjs
@@ -74,6 +74,8 @@ const KNOWN_ESCAPE_HATCHES = new Set([
'RUFLO_AI_BUDGET_DISABLE', // #2663 — hard kill switch for the repository-supervisor AI-cost fuse (services/global-ai-budget.ts). Ops-level "disable this whole subsystem" toggle, same pattern as RUFLO_AI_DEDUP_DISABLE above
'RUFLO_METAHARNESS_SKIP_LOCAL', // plugins/ruflo-metaharness/scripts/_invoke.mjs — CI seam that forces the invoke shim off the local vendored metaharness and onto the pinned-cache resolver. Plugin script has no CLI-flag surface (invoked internally by MCP tools)
'RUFLO_HELPERS_LOCKED', // v3.30.0 — env-level opt-out for the .claude/helpers/ auto-refresh (init/helper-refresh.ts). Sibling to the `.LOCKED` marker file; helper-refresh runs from a hook, not a user-typed CLI command — no per-invocation flag surface. See CLAUDE.md "Concurrent-session helper corruption" for rationale
+ 'CLAUDE_FLOW_DISABLE_NATIVE_ROUTER', // Test/lock-constrained MCP escape hatch: forces hooks routing onto the deterministic pure-JS backend. The router is process-lifetime state, not owned by one CLI invocation.
+ 'RUFLO_FLYWHEEL_ALLOW_BUILTIN_ANCHOR', // Explicit compatibility escape hatch for pre-ADR-331 downstream behavior. Intentionally env-only and visibly unsafe-by-choice; normal CLI/MCP use supplies a project anchor path + hash.
// ── Embedding substrate toggles (3.25.x — opt-in tier + fail-closed ops flag) ─
'RUFLO_REQUIRE_REAL_EMBEDDINGS', // Fail-closed "no stubs" strict mode — deploy/CI ops toggle, not a per-invocation CLI flag (ADR-176)
diff --git a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
index a8aa2cd428..8c12a8070d 100644
--- a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
+++ b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
@@ -53,6 +53,18 @@ describe('ensureDaemonRunning', () => {
expect(spawned).toBe(0);
});
+ it('does not treat a Claude Code-only .claude directory as Ruflo initialization (#2834)', () => {
+ delete process.env.RUFLO_DAEMON_AUTOSTART;
+ const cwd = mkdtempSync(join(tmpdir(), 'claude-only-'));
+ mkdirSync(join(cwd, '.claude'), { recursive: true });
+ writeFileSync(join(cwd, '.claude', 'settings.json'), '{}');
+ let spawned = 0;
+ const r = ensureDaemonRunning(cwd, { isAlive: () => false, spawnFn: () => { spawned++; } });
+ expect(r).toEqual({ started: false, reason: 'not a ruflo project' });
+ expect(spawned).toBe(0);
+ expect(existsSync(join(cwd, '.claude-flow'))).toBe(false);
+ });
+
it('respects a project-local claude-flow.config.json opt-out (survives env vars not propagating)', () => {
// The real-world gap this closes: a non-interactive shell never sources
// ~/.bashrc (its own top-of-file `case $- in *i*) ;; *) return;; esac`
diff --git a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts
index e388dd2c8b..688918bdf3 100644
--- a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts
+++ b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts
@@ -26,6 +26,7 @@ function acceptedReceipt(key = keys(), now = 1_700_000_000_000) {
safetyEnvelopeRef: 'sha256:safety',
corpusVersion: 'corpus-v1',
corpusHash: 'sha256:corpus',
+ anchorRef: 'sha256:project-anchor',
baselineScore: 0.5,
candidateScore: 0.65,
heldOutDeltas: [0.1, 0.12, 0.2, 0.08, 0.15, 0.11],
@@ -62,6 +63,10 @@ describe('flywheel receipt protocol', () => {
tampered.payload.candidatePolicy.alpha = 0.31;
expect(verifyFlywheelReceipt(tampered, new Set([key.publicKeyPem])).valid).toBe(false);
+ const anchorTampered = structuredClone(receipt);
+ anchorTampered.payload.anchorRef = 'sha256:different-project-anchor';
+ expect(verifyFlywheelReceipt(anchorTampered, new Set([key.publicKeyPem])).valid).toBe(false);
+
const second = acceptedReceipt(key, 1_700_000_000_001).receipt;
expect(second.payload.candidateId).toBe(receipt.payload.candidateId);
expect(second.payload.evaluationRunId).not.toBe(receipt.payload.evaluationRunId);
diff --git a/v3/@claude-flow/cli/__tests__/harness-project-anchor.test.ts b/v3/@claude-flow/cli/__tests__/harness-project-anchor.test.ts
new file mode 100644
index 0000000000..c638b4d8f1
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/harness-project-anchor.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import {
+ loadEffectiveFlywheelAnchor,
+ PROJECT_ANCHOR_MANIFEST_SCHEMA,
+ PROJECT_ANCHOR_SCHEMA,
+} from '../src/services/harness-project-anchor.js';
+import { humanEvalHash, type HumanEvalTask } from '../src/services/harness-frozen-eval.js';
+
+const tasks: HumanEvalTask[] = [
+ { id: 'a', q: 'authentication middleware', labels: ['auth'] },
+ { id: 'b', q: 'database migration', labels: ['migration'] },
+ { id: 'c', q: 'dashboard component', labels: ['dashboard'] },
+ { id: 'd', q: 'integration regression', labels: ['regression'] },
+];
+
+function foreignProject(): string {
+ const root = mkdtempSync(join(tmpdir(), 'flywheel-anchor-'));
+ writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'downstream-app' }));
+ return root;
+}
+
+describe('loadEffectiveFlywheelAnchor', () => {
+ it('fails closed for a foreign project without its own benchmark (#2840)', () => {
+ expect(() => loadEffectiveFlywheelAnchor(foreignProject())).toThrow(/project-local flywheel anchor required/);
+ });
+
+ it('loads a project-contained explicit anchor and binds its hash', () => {
+ const root = foreignProject();
+ const path = join(root, 'anchor.json');
+ writeFileSync(path, JSON.stringify({ schemaVersion: PROJECT_ANCHOR_SCHEMA, version: 'app-v1', tasks }));
+ const hash = humanEvalHash(tasks);
+ const selected = loadEffectiveFlywheelAnchor(root, { anchorPath: path, anchorHash: hash });
+ expect(selected).toMatchObject({ version: 'app-v1', anchorRef: hash, source: 'project' });
+ expect(selected.tasks).toHaveLength(4);
+ });
+
+ it('rejects anchor drift', () => {
+ const root = foreignProject();
+ const path = join(root, 'anchor.json');
+ writeFileSync(path, JSON.stringify({ schemaVersion: PROJECT_ANCHOR_SCHEMA, tasks }));
+ expect(() => loadEffectiveFlywheelAnchor(root, {
+ anchorPath: path,
+ anchorHash: `sha256:${'0'.repeat(64)}`,
+ })).toThrow(/hash mismatch/);
+ });
+
+ it('discovers a manifest and resolves its path relative to the manifest', () => {
+ const root = foreignProject();
+ const evalDir = join(root, '.claude', 'eval');
+ mkdirSync(evalDir, { recursive: true });
+ writeFileSync(join(evalDir, 'app-anchor.json'), JSON.stringify({ schemaVersion: PROJECT_ANCHOR_SCHEMA, tasks }));
+ writeFileSync(join(evalDir, 'flywheel-anchor.manifest.json'), JSON.stringify({
+ schemaVersion: PROJECT_ANCHOR_MANIFEST_SCHEMA,
+ path: 'app-anchor.json',
+ sha256: humanEvalHash(tasks),
+ }));
+ const selected = loadEffectiveFlywheelAnchor(root);
+ expect(selected.anchorRef).toBe(humanEvalHash(tasks));
+ expect(selected.source).toBe('project');
+ });
+
+ it('rejects project-escaping paths', () => {
+ const root = foreignProject();
+ expect(() => loadEffectiveFlywheelAnchor(root, {
+ anchorPath: '../outside.json',
+ anchorHash: `sha256:${'0'.repeat(64)}`,
+ })).toThrow();
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/learned-routing-live.test.ts b/v3/@claude-flow/cli/__tests__/learned-routing-live.test.ts
new file mode 100644
index 0000000000..2368368947
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/learned-routing-live.test.ts
@@ -0,0 +1,82 @@
+/**
+ * End-to-end regression for #2819: a long-lived MCP process must observe
+ * labelled outcomes immediately, without a process restart.
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+let projectRoot: string;
+let originalCwd: string;
+let originalDisableBridge: string | undefined;
+let originalDisableNativeRouter: string | undefined;
+
+beforeAll(() => {
+ originalCwd = process.cwd();
+ originalDisableBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ originalDisableNativeRouter = process.env.CLAUDE_FLOW_DISABLE_NATIVE_ROUTER;
+ projectRoot = mkdtempSync(path.join(tmpdir(), 'ruflo-routing-live-'));
+ mkdirSync(path.join(projectRoot, '.claude-flow'), { recursive: true });
+ process.chdir(projectRoot);
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ process.env.CLAUDE_FLOW_DISABLE_NATIVE_ROUTER = '1';
+ vi.resetModules();
+ vi.doMock('../src/memory/memory-bridge.js', () => ({
+ bridgeRouteTask: vi.fn(async () => null),
+ bridgeRecordFeedback: vi.fn(async () => ({ success: true, controller: 'test', updated: 1 })),
+ bridgeRecordCausalEdge: vi.fn(async () => ({ success: true })),
+ }));
+ vi.doMock('../src/memory/intelligence.js', () => ({
+ recordTrajectory: vi.fn(async () => ({ success: true })),
+ }));
+ vi.doMock('../src/memory/graph-edge-writer.js', () => ({
+ insertGraphEdge: vi.fn(async () => undefined),
+ }));
+});
+
+afterAll(() => {
+ process.chdir(originalCwd);
+ vi.doUnmock('../src/memory/memory-bridge.js');
+ vi.doUnmock('../src/memory/intelligence.js');
+ vi.doUnmock('../src/memory/graph-edge-writer.js');
+ if (originalDisableBridge === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = originalDisableBridge;
+ if (originalDisableNativeRouter === undefined) delete process.env.CLAUDE_FLOW_DISABLE_NATIVE_ROUTER;
+ else process.env.CLAUDE_FLOW_DISABLE_NATIVE_ROUTER = originalDisableNativeRouter;
+ rmSync(projectRoot, { recursive: true, force: true });
+});
+
+describe('live learned routing (#2819)', () => {
+ it('invalidates the in-process router and uses newly supported evidence', async () => {
+ const { hooksPostTask, hooksRoute } = await import('../src/mcp-tools/hooks-tools.js');
+ const task = 'zephyrometer quuxology';
+
+ // Warm the singleton before learning; this is the state that used to stay
+ // unchanged until the MCP server restarted.
+ const before = await hooksRoute.handler({ task }) as Record<string, unknown>;
+
+ for (const taskId of ['learn-live-1', 'learn-live-2']) {
+ const recorded = await hooksPostTask.handler({
+ taskId,
+ task,
+ agent: 'researcher',
+ agentRole: 'researcher',
+ success: true,
+ quality: 0.98,
+ storeDecisions: false,
+ }) as { success?: boolean };
+ expect(recorded.success).not.toBe(false);
+ }
+
+ const after = await hooksRoute.handler({ task }) as {
+ selectedAgent?: string;
+ recommendedAgent?: string;
+ matchedPattern?: string;
+ primaryAgent?: { type?: string };
+ };
+ expect(after.matchedPattern).toBe('learned-researcher');
+ expect(after.selectedAgent ?? after.recommendedAgent ?? after.primaryAgent?.type).toBe('researcher');
+ expect(after).not.toEqual(before);
+ }, 30_000);
+});
diff --git a/v3/@claude-flow/cli/__tests__/learned-routing.test.ts b/v3/@claude-flow/cli/__tests__/learned-routing.test.ts
new file mode 100644
index 0000000000..f9330add1a
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/learned-routing.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildLearnedRoutingPatterns,
+ type LearnedRoutingOutcome,
+} from '../src/services/learned-routing.js';
+
+const outcome = (
+ agent: string,
+ keywords: string[],
+ quality = 0.9,
+ success = true,
+): LearnedRoutingOutcome => ({
+ task: keywords.join(' '),
+ agent,
+ success,
+ quality,
+ keywords,
+ timestamp: '2026-07-29T00:00:00.000Z',
+});
+
+describe('buildLearnedRoutingPatterns', () => {
+ it('ranks supported agent-specific terms and removes shared noise (#2839)', () => {
+ const patterns = buildLearnedRoutingPatterns([
+ outcome('coder', ['implement', 'dashboard', 'shared', 'using']),
+ outcome('coder', ['implement', 'component', 'shared', 'using']),
+ outcome('tester', ['test', 'coverage', 'shared', 'using']),
+ outcome('tester', ['test', 'regression', 'shared', 'using']),
+ ]);
+ expect(patterns['learned-coder'].keywords).toContain('implement');
+ expect(patterns['learned-tester'].keywords).toContain('test');
+ expect(patterns['learned-coder'].keywords).not.toContain('shared');
+ expect(patterns['learned-tester'].keywords).not.toContain('using');
+ });
+
+ it('does not learn from one-off, failed, or low-quality outcomes', () => {
+ const patterns = buildLearnedRoutingPatterns([
+ outcome('researcher', ['research'], 0.95),
+ outcome('coder', ['implement'], 0.2),
+ outcome('tester', ['test'], 0.95, false),
+ ]);
+ expect(patterns).toEqual({});
+ });
+
+ it('allows later repeated evidence to displace early insertion noise', () => {
+ const patterns = buildLearnedRoutingPatterns([
+ outcome('reviewer', ['early-noise', 'security']),
+ outcome('reviewer', ['security', 'audit']),
+ outcome('reviewer', ['security', 'review']),
+ outcome('reviewer', ['security', 'vulnerability']),
+ ], { maxKeywords: 2 });
+ expect(patterns['learned-reviewer'].keywords[0]).toBe('security');
+ expect(patterns['learned-reviewer'].keywords).not.toContain('early-noise');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/memory-vector-lifecycle-2815.test.ts b/v3/@claude-flow/cli/__tests__/memory-vector-lifecycle-2815.test.ts
new file mode 100644
index 0000000000..56e0360ebd
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-vector-lifecycle-2815.test.ts
@@ -0,0 +1,86 @@
+/**
+ * Regression coverage for #2815: HNSW vectors are secondary indexes over
+ * the authoritative (namespace,key) memory row. Upsert and delete therefore
+ * have to invalidate every historical vector for that logical key, including
+ * duplicates left by older releases.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+let root: string;
+const originalRoot = process.env.CLAUDE_FLOW_MEMORY_PATH;
+const originalDisableBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'ruflo-memory-2815-'));
+ process.env.CLAUDE_FLOW_MEMORY_PATH = root;
+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';
+ vi.resetModules();
+});
+
+afterEach(() => {
+ vi.resetModules();
+ if (originalRoot === undefined) delete process.env.CLAUDE_FLOW_MEMORY_PATH;
+ else process.env.CLAUDE_FLOW_MEMORY_PATH = originalRoot;
+ if (originalDisableBridge === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;
+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = originalDisableBridge;
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('memory vector lifecycle (#2815)', () => {
+ it('upsert and delete remove every historical vector for a logical key', async () => {
+ const memory = await import('../src/memory/memory-initializer.js');
+ const initialized = await memory.initializeMemoryDatabase({
+ force: true,
+ migrate: false,
+ });
+ expect(initialized.success).toBe(true);
+
+ const first = await memory.storeEntry({
+ key: 'routing-policy',
+ namespace: 'patterns',
+ value: 'first policy observation',
+ upsert: true,
+ });
+ expect(first.success).toBe(true);
+
+ // Reproduce the stale metadata state created by older versions: several
+ // vector IDs resolve to the same logical memory key. The invalidation
+ // primitive must remove all of them rather than stopping at the first.
+ const vectors = new Map([
+ ['current', { id: 'current', key: 'routing-policy', namespace: 'patterns', content: 'current' }],
+ ['historical-a', { id: 'historical-a', key: 'routing-policy', namespace: 'patterns', content: 'stale A' }],
+ ['historical-b', { id: 'historical-b', key: 'routing-policy', namespace: 'patterns', content: 'stale B' }],
+ ['other', { id: 'other', key: 'other-key', namespace: 'patterns', content: 'keep' }],
+ ]);
+ expect(
+ memory.removeHNSWEntriesByLogicalKey(vectors, 'routing-policy', 'patterns'),
+ ).toBe(3);
+ expect([...vectors.keys()]).toEqual(['other']);
+
+ const replacement = await memory.storeEntry({
+ key: 'routing-policy',
+ namespace: 'patterns',
+ value: 'replacement policy observation',
+ upsert: true,
+ });
+ expect(replacement.success).toBe(true);
+ const active = await memory.listEntries({
+ namespace: 'patterns',
+ includeContent: true,
+ });
+ expect(active.total).toBe(1);
+ expect(active.entries[0]?.content).toBe('replacement policy observation');
+
+ const deleted = await memory.deleteEntry({
+ key: 'routing-policy',
+ namespace: 'patterns',
+ });
+ expect(deleted.success).toBe(true);
+ expect(deleted.deleted).toBe(true);
+ const remaining = await memory.listEntries({ namespace: 'patterns' });
+ expect(remaining.total).toBe(0);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/pheromone-adaptive.test.ts b/v3/@claude-flow/cli/__tests__/pheromone-adaptive.test.ts
new file mode 100644
index 0000000000..ebb5172320
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/pheromone-adaptive.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createApscState,
+ isApscAgentEligible,
+ recordApscSignal,
+} from '../src/services/pheromone-adaptive.js';
+
+function signal(agentId: string, role: string, taskSuccess: number) {
+ return { agentId, role, taskSuccess, normalizedLatency: taskSuccess ? 0.1 : 1, consensusAlignment: taskSuccess };
+}
+
+describe('Adaptive Pheromone Swarm Consensus', () => {
+ it('is dry-run by default and never changes eligibility', () => {
+ let state = createApscState({ minSamples: 1, minActiveAgents: 1, pruningFactor: 1 });
+ for (const id of ['a', 'b', 'c', 'd']) {
+ state = recordApscSignal(state, signal(id, 'coder', id === 'd' ? 0 : 1)).state;
+ }
+ const result = recordApscSignal(state, signal('d', 'coder', 0));
+ expect(['would-suspend', 'keep']).toContain(result.decision.action);
+ expect(result.state.agents.d.status).toBe('active');
+ expect(isApscAgentEligible(result.state, 'd')).toBe(true);
+ });
+
+ it('suspends a mature low performer without crossing the quorum floor', () => {
+ let state = createApscState({
+ dryRun: false,
+ minSamples: 1,
+ minActiveAgents: 3,
+ maxSuspendFraction: 0.5,
+ pruningFactor: 0.95,
+ emaDecay: 0,
+ explorationRate: 0,
+ });
+ let last;
+ for (const id of ['a', 'b', 'c', 'd']) {
+ last = recordApscSignal(state, signal(id, 'coder', id === 'd' ? 0 : 1));
+ state = last.state;
+ }
+ expect(last!.decision.action).toBe('suspend');
+ expect(last!.decision.activeAgents).toBe(3);
+ expect(isApscAgentEligible(state, 'd')).toBe(false);
+ });
+
+ it('never suspends protected coordination roles', () => {
+ let state = createApscState({
+ dryRun: false,
+ minSamples: 1,
+ minActiveAgents: 1,
+ maxSuspendFraction: 1,
+ pruningFactor: 1,
+ emaDecay: 0,
+ explorationRate: 0,
+ });
+ for (const id of ['lead', 'a', 'b']) {
+ state = recordApscSignal(state, signal(id, id === 'lead' ? 'coordinator' : 'coder', id === 'lead' ? 0 : 1)).state;
+ }
+ const result = recordApscSignal(state, signal('lead', 'coordinator', 0));
+ expect(result.decision.reason).toMatch(/protected role/);
+ expect(result.state.agents.lead.status).toBe('active');
+ });
+
+ it('reactivates recovered agents', () => {
+ let state = createApscState({
+ dryRun: false,
+ minSamples: 1,
+ minActiveAgents: 1,
+ maxSuspendFraction: 1,
+ pruningFactor: 1,
+ reactivationThreshold: 0.75,
+ emaDecay: 0,
+ explorationRate: 0,
+ });
+ for (const id of ['a', 'b', 'c']) state = recordApscSignal(state, signal(id, 'coder', id === 'c' ? 0 : 1)).state;
+ expect(state.agents.c.status).toBe('suspended');
+ const recovered = recordApscSignal(state, signal('c', 'coder', 1));
+ expect(recovered.decision.action).toBe('reactivate');
+ expect(recovered.state.agents.c.status).toBe('active');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts b/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts
index 034e2e50ed..aec451359c 100644
--- a/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts
+++ b/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts
@@ -768,10 +768,10 @@ describe('WorkerDaemon resource thresholds', () => {
if (savedIdle === undefined) delete process.env[IDLE_ENV]; else process.env[IDLE_ENV] = savedIdle;
});
- it('defaults ttlMs to 12h and idleShutdownMs to 0 (opt-in)', () => {
+ it('defaults ttlMs to 12h and idleShutdownMs to 30m (#2834)', () => {
const config = new WorkerDaemon(tempDir).getStatus().config;
expect(config.ttlMs).toBe(12 * 60 * 60 * 1000);
- expect(config.idleShutdownMs).toBe(0);
+ expect(config.idleShutdownMs).toBe(30 * 60 * 1000);
});
it('honors RUFLO_DAEMON_TTL_SECS env override (seconds → ms)', () => {
diff --git a/v3/@claude-flow/cli/scripts/benchmark-pheromone-adaptive.mjs b/v3/@claude-flow/cli/scripts/benchmark-pheromone-adaptive.mjs
new file mode 100644
index 0000000000..d3fcf8d36c
--- /dev/null
+++ b/v3/@claude-flow/cli/scripts/benchmark-pheromone-adaptive.mjs
@@ -0,0 +1,92 @@
+#!/usr/bin/env node
+/**
+ * Reproducible ADR-330 benchmark.
+ *
+ * This does not repeat the external paper's claims. It measures Ruflo's local
+ * implementation on a declared synthetic convergence workload and fails when
+ * safety or latency bounds regress.
+ */
+import { performance } from 'node:perf_hooks';
+import {
+ createApscState,
+ recordApscSignal,
+} from '../dist/src/services/pheromone-adaptive.js';
+
+const config = {
+ dryRun: false,
+ emaDecay: 0.5,
+ pruningFactor: 0.8,
+ minActiveAgents: 6,
+ minSamples: 3,
+ maxSuspendFraction: 0.25,
+ explorationRate: 0,
+};
+const agents = Array.from({ length: 12 }, (_, index) => ({
+ id: index === 0 ? 'lead' : `agent-${index}`,
+ role: index === 0 ? 'coordinator' : 'coder',
+ strong: index < 8,
+}));
+const signalFor = (agent) => ({
+ agentId: agent.id,
+ role: agent.role,
+ taskSuccess: agent.strong ? 0.95 : 0.1,
+ normalizedLatency: agent.strong ? 0.15 : 0.9,
+ consensusAlignment: agent.strong ? 0.9 : 0.2,
+});
+
+let state = createApscState(config);
+const durations = [];
+for (let round = 0; round < 6; round++) {
+ for (const agent of agents) {
+ const started = performance.now();
+ state = recordApscSignal(state, signalFor(agent), 1_800_000_000_000 + round).state;
+ durations.push(performance.now() - started);
+ }
+}
+
+// Throughput pass over an already-mature state.
+for (let iteration = 0; iteration < 20_000; iteration++) {
+ const agent = agents[iteration % agents.length];
+ const started = performance.now();
+ state = recordApscSignal(state, signalFor(agent), 1_800_000_100_000 + iteration).state;
+ durations.push(performance.now() - started);
+}
+
+durations.sort((a, b) => a - b);
+const p95Ms = durations[Math.floor(durations.length * 0.95)] ?? 0;
+const active = Object.values(state.agents).filter((agent) => agent.status === 'active');
+const suspended = Object.values(state.agents).filter((agent) => agent.status === 'suspended');
+const rawMean = (rows) => rows.reduce((sum, row) => sum + row.rawScore, 0) / Math.max(1, rows.length);
+const baselineMean = rawMean(Object.values(state.agents));
+const activeMean = rawMean(active);
+const report = {
+ schemaVersion: 'ruflo.apsc-benchmark/v1',
+ workload: {
+ agents: agents.length,
+ strongAgents: agents.filter((agent) => agent.strong).length,
+ weakAgents: agents.filter((agent) => !agent.strong).length,
+ warmupRounds: 6,
+ measuredUpdates: 20_000,
+ },
+ config: state.config,
+ result: {
+ activeAgents: active.length,
+ suspendedAgents: suspended.length,
+ activeReduction: suspended.length / agents.length,
+ baselineMeanScore: baselineMean,
+ admittedMeanScore: activeMean,
+ admittedScoreLift: activeMean - baselineMean,
+ protectedLeadActive: state.agents.lead?.status === 'active',
+ quorumPreserved: active.length >= state.config.minActiveAgents,
+ updateP95Ms: p95Ms,
+ },
+ claimBoundary: 'Synthetic Ruflo implementation benchmark; external TPSC percentages are not claimed.',
+};
+
+console.log(JSON.stringify(report, null, 2));
+
+if (!report.result.protectedLeadActive) throw new Error('protected role was suspended');
+if (!report.result.quorumPreserved) throw new Error('active-agent floor was crossed');
+if (report.result.activeReduction < 0.25) throw new Error('synthetic pruning target was not reached');
+if (report.result.admittedScoreLift <= 0) throw new Error('admitted-agent quality did not improve');
+if (report.result.updateP95Ms >= 5) throw new Error(`APSC update p95 ${report.result.updateP95Ms}ms exceeds 5ms`);
diff --git a/v3/@claude-flow/cli/src/commands/agent.ts b/v3/@claude-flow/cli/src/commands/agent.ts
index a6d410bccb..118a9533db 100644
--- a/v3/@claude-flow/cli/src/commands/agent.ts
+++ b/v3/@claude-flow/cli/src/commands/agent.ts
@@ -560,6 +560,71 @@ const metricsCommand: Command = {
? `${Math.round(Object.values(typeCounts).reduce((a, d) => a + d.success, 0) / tasksCompleted * 100)}%`
: 'N/A';
+ // ADR-330: expose the learned scheduling signal where operators already
+ // inspect agent metrics. Old/non-APSC installs simply omit this section.
+ let pheromone: {
+ active: boolean;
+ dryRun: boolean;
+ threshold: number;
+ agents: Array<{
+ agentId: string;
+ role: string;
+ pheromoneScore: number;
+ rawScore: number;
+ samples: number;
+ eligibility: string;
+ }>;
+ } | undefined;
+ const swarmStatePath = join(process.cwd(), '.claude-flow', 'swarm', 'swarm-state.json');
+ if (existsSync(swarmStatePath)) {
+ try {
+ const store = JSON.parse(readFileSync(swarmStatePath, 'utf-8')) as {
+ swarms?: Record<string, {
+ topology?: string;
+ status?: string;
+ updatedAt?: string;
+ config?: {
+ apscState?: {
+ threshold?: number;
+ config?: { dryRun?: boolean };
+ agents?: Record<string, {
+ agentId: string;
+ role: string;
+ emaScore: number;
+ rawScore: number;
+ samples: number;
+ status: string;
+ }>;
+ };
+ };
+ }>;
+ };
+ const current = Object.values(store.swarms ?? {})
+ .filter((swarm) => swarm.status === 'running' && swarm.topology === 'pheromone-adaptive')
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))[0];
+ const apsc = current?.config?.apscState;
+ if (apsc) {
+ const agents = Object.values(apsc.agents ?? {})
+ .filter((agent) => !agentId || agent.agentId === agentId)
+ .sort((a, b) => a.agentId.localeCompare(b.agentId))
+ .map((agent) => ({
+ agentId: agent.agentId,
+ role: agent.role,
+ pheromoneScore: agent.emaScore,
+ rawScore: agent.rawScore,
+ samples: agent.samples,
+ eligibility: agent.status === 'suspended' ? 'suspended' : 'eligible',
+ }));
+ pheromone = {
+ active: true,
+ dryRun: apsc.config?.dryRun !== false,
+ threshold: apsc.threshold ?? 0.5,
+ agents,
+ };
+ }
+ } catch { /* malformed/legacy swarm state — preserve existing metrics */ }
+ }
+
const metrics = {
period,
summary: {
@@ -574,7 +639,8 @@ const metricsCommand: Command = {
performance: {
memoryVectors: `${vectorCount} vectors`,
searchBackend: vectorCount > 0 ? 'HNSW-indexed' : 'none'
- }
+ },
+ pheromone,
};
if (ctx.flags.format === 'json') {
@@ -624,6 +690,21 @@ const metricsCommand: Command = {
`Backend: ${output.success(metrics.performance.searchBackend)}`
]);
+ if (metrics.pheromone) {
+ output.writeln();
+ output.writeln(output.bold(`Pheromone Scheduling (${metrics.pheromone.dryRun ? 'dry run' : 'live'})`));
+ output.printTable({
+ columns: [
+ { key: 'agentId', header: 'Agent', width: 20 },
+ { key: 'role', header: 'Role', width: 18 },
+ { key: 'pheromoneScore', header: 'EMA Score', width: 12, align: 'right' },
+ { key: 'samples', header: 'Samples', width: 9, align: 'right' },
+ { key: 'eligibility', header: 'Eligibility', width: 12 },
+ ],
+ data: metrics.pheromone.agents,
+ });
+ }
+
return { success: true, data: metrics };
}
};
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 45139d321a..2bb163006a 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -2056,6 +2056,26 @@ const postTaskCommand: Command = {
description: 'Agent that executed the task',
type: 'string'
},
+ {
+ name: 'agent-role',
+ description: 'Stable agent role used for role-aware pheromone comparison (for example coder, tester, coordinator)',
+ type: 'string'
+ },
+ {
+ name: 'duration',
+ description: 'Observed task duration in milliseconds for latency fitness',
+ type: 'number'
+ },
+ {
+ name: 'latency-budget-ms',
+ description: 'Expected task duration in milliseconds; paired with --duration to normalize latency fitness',
+ type: 'number'
+ },
+ {
+ name: 'consensus-alignment',
+ description: 'Consensus alignment score from 0 to 1',
+ type: 'number'
+ },
{
name: 'task',
short: 't',
@@ -2111,6 +2131,10 @@ const postTaskCommand: Command = {
success,
quality: ctx.flags.quality,
agent: ctx.flags.agent,
+ agentRole: ctx.flags.agentRole,
+ duration: ctx.flags.duration,
+ latencyBudgetMs: ctx.flags.latencyBudgetMs,
+ consensusAlignment: ctx.flags.consensusAlignment,
// #2785: forward the task description so routing outcomes actually persist
// (hooks_post-task requires taskText + agent to write the outcome row that
// hooks_metrics reads via getIntelligenceStatsFromMemory)
diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.ts
index a69ba8968c..11ef263ff1 100644
--- a/v3/@claude-flow/cli/src/commands/metaharness.ts
+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts
@@ -115,11 +115,15 @@ async function dispatchFlywheel(
receiptPublicKeyPem: publicKeyPath ? readFileSync(resolve(publicKeyPath), 'utf8') : undefined,
maxConcurrency: Number(flywheelFlag(flags, 'maxConcurrency', 2)),
evaluationTimeoutMs: Number(flywheelFlag(flags, 'timeoutMs', 120_000)),
+ anchorPath: flywheelFlag<string>(flags, 'anchorPath'),
+ anchorHash: flywheelFlag<string>(flags, 'anchorHash'),
+ anchorManifestPath: flywheelFlag<string>(flags, 'anchorManifest'),
});
}
} else if (operation === 'receipts') {
data = listFlywheelReceipts(projectRoot).map(({ receipt, state }) => ({
receiptId: receipt.payload.receiptId,
+ anchorRef: receipt.payload.anchorRef,
candidateId: receipt.payload.candidateId,
baselineRef: receipt.payload.baselineRef,
decision: receipt.payload.decision,
diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.ts
index adfc853f65..9123e2274b 100644
--- a/v3/@claude-flow/cli/src/commands/swarm.ts
+++ b/v3/@claude-flow/cli/src/commands/swarm.ts
@@ -253,7 +253,8 @@ const TOPOLOGIES = [
{ value: 'ring', label: 'Ring', hint: 'Circular communication pattern' },
{ value: 'star', label: 'Star', hint: 'Central coordinator with spoke agents' },
{ value: 'hybrid', label: 'Hybrid', hint: 'Hierarchical mesh for maximum flexibility' },
- { value: 'hierarchical-mesh', label: 'Hierarchical Mesh', hint: 'V3 15-agent queen + peer communication (recommended)' }
+ { value: 'hierarchical-mesh', label: 'Hierarchical Mesh', hint: 'V3 15-agent queen + peer communication (recommended)' },
+ { value: 'pheromone-adaptive', label: 'Pheromone Adaptive', hint: 'Role-aware dynamic eligibility with quorum safety (ADR-330)' }
];
// Swarm strategies
@@ -308,6 +309,19 @@ const initCommand: Command = {
type: 'boolean',
default: false
},
+ {
+ name: 'apsc-live',
+ description: 'Apply APSC suspension decisions (default is calibration-only dry run)',
+ type: 'boolean',
+ default: false
+ },
+ { name: 'apsc-alpha', description: 'Task-success score weight', type: 'number', default: 0.5 },
+ { name: 'apsc-beta', description: 'Latency score weight', type: 'number', default: 0.2 },
+ { name: 'apsc-gamma', description: 'Consensus-alignment score weight', type: 'number', default: 0.3 },
+ { name: 'apsc-pruning-factor', description: 'Fraction of adaptive threshold below which agents are eligible for suspension', type: 'number', default: 0.6 },
+ { name: 'apsc-reactivation-threshold', description: 'Fraction of adaptive threshold required for recovery', type: 'number', default: 0.75 },
+ { name: 'apsc-min-active-agents', description: 'Hard quorum floor', type: 'number', default: 3 },
+ { name: 'apsc-min-samples', description: 'Warm-up observations before pruning', type: 'number', default: 3 },
{
// #2768 — dream-cycle SubagentPermissionDelegate. Ships a per-role
// capability manifest to `.swarm/permissions.jsonl` + an append-only
@@ -357,7 +371,7 @@ const initCommand: Command = {
autoScaling?: boolean;
};
}>('swarm_init', {
- topology: topology as 'hierarchical' | 'mesh' | 'adaptive' | 'collective' | 'hierarchical-mesh',
+ topology: topology as 'hierarchical' | 'mesh' | 'adaptive' | 'collective' | 'hierarchical-mesh' | 'pheromone-adaptive',
maxAgents,
config: {
communicationProtocol: 'message-bus',
@@ -365,6 +379,18 @@ const initCommand: Command = {
failureHandling: 'retry',
loadBalancing: true,
autoScaling: ctx.flags.autoScale ?? true,
+ ...(topology === 'pheromone-adaptive' ? {
+ apsc: {
+ alpha: Number(ctx.flags.apscAlpha ?? 0.5),
+ beta: Number(ctx.flags.apscBeta ?? 0.2),
+ gamma: Number(ctx.flags.apscGamma ?? 0.3),
+ pruningFactor: Number(ctx.flags.apscPruningFactor ?? 0.6),
+ reactivationThreshold: Number(ctx.flags.apscReactivationThreshold ?? 0.75),
+ minActiveAgents: Number(ctx.flags.apscMinActiveAgents ?? 3),
+ minSamples: Number(ctx.flags.apscMinSamples ?? 3),
+ dryRun: ctx.flags.apscLive !== true,
+ },
+ } : {}),
},
metadata: {
v3Mode,
@@ -395,7 +421,10 @@ const initCommand: Command = {
{ property: 'Max Agents', value: result.config.maxAgents },
{ property: 'Auto Scale', value: result.config.autoScaling ? 'Enabled' : 'Disabled' },
{ property: 'Protocol', value: result.config.communicationProtocol || 'N/A' },
- { property: 'V3 Mode', value: v3Mode ? 'Enabled' : 'Disabled' }
+ { property: 'V3 Mode', value: v3Mode ? 'Enabled' : 'Disabled' },
+ ...(topology === 'pheromone-adaptive'
+ ? [{ property: 'APSC Mode', value: ctx.flags.apscLive === true ? 'Live' : 'Dry run' }]
+ : [])
]
});
@@ -985,15 +1014,42 @@ const compressMessageCommand: Command = {
},
};
+const pheromoneCommand: Command = {
+ name: 'pheromone',
+ description: 'Inspect or update ADR-330 pheromone-adaptive scheduling state',
+ options: [
+ { name: 'agent-id', description: 'Agent identifier; omit to show status', type: 'string' },
+ { name: 'role', description: 'Agent role for role-local normalization', type: 'string' },
+ { name: 'task-success', description: 'Task success in [0,1]', type: 'number' },
+ { name: 'normalized-latency', description: 'Latency divided by budget in [0,1]', type: 'number' },
+ { name: 'consensus-alignment', description: 'Consensus alignment in [0,1]', type: 'number' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const agentId = ctx.flags.agentId as string | undefined;
+ const data = agentId
+ ? await callMCPTool<Record<string, unknown>>('swarm_pheromone_update', {
+ agentId,
+ role: String(ctx.flags.role ?? 'worker'),
+ taskSuccess: Number(ctx.flags.taskSuccess ?? 1),
+ normalizedLatency: Number(ctx.flags.normalizedLatency ?? 0),
+ consensusAlignment: Number(ctx.flags.consensusAlignment ?? 1),
+ })
+ : await callMCPTool<Record<string, unknown>>('swarm_pheromone_status', {});
+ output.writeln(JSON.stringify(data, null, 2));
+ return { success: data.active !== false, data };
+ },
+};
+
export const swarmCommand: Command = {
name: 'swarm',
description: 'Swarm coordination commands',
- subcommands: [initCommand, startCommand, statusCommand, stopCommand, scaleCommand, coordinateCommand, compressMessageCommand],
+ subcommands: [initCommand, startCommand, statusCommand, stopCommand, scaleCommand, coordinateCommand, compressMessageCommand, pheromoneCommand],
options: [],
examples: [
{ command: 'claude-flow swarm init --v3-mode', description: 'Initialize V3 swarm' },
{ command: 'claude-flow swarm start -o "Build API" -s development', description: 'Start development swarm' },
- { command: 'claude-flow swarm coordinate --agents 15', description: 'V3 coordination' }
+ { command: 'claude-flow swarm coordinate --agents 15', description: 'V3 coordination' },
+ { command: 'claude-flow swarm pheromone', description: 'Inspect pheromone-adaptive scheduling state' }
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
output.writeln();
@@ -1008,7 +1064,8 @@ export const swarmCommand: Command = {
`${output.highlight('status')} - Show swarm status`,
`${output.highlight('stop')} - Stop swarm execution`,
`${output.highlight('scale')} - Scale swarm agent count`,
- `${output.highlight('coordinate')} - V3 15-agent coordination`
+ `${output.highlight('coordinate')} - V3 15-agent coordination`,
+ `${output.highlight('pheromone')} - Inspect/update adaptive pheromone state`
]);
return { success: true };
diff --git a/v3/@claude-flow/cli/src/config-adapter.ts b/v3/@claude-flow/cli/src/config-adapter.ts
index b59be06ea4..a096781f70 100644
--- a/v3/@claude-flow/cli/src/config-adapter.ts
+++ b/v3/@claude-flow/cli/src/config-adapter.ts
@@ -164,6 +164,7 @@ function normalizeTopology(
case 'hierarchical-mesh':
return topology;
case 'adaptive':
+ case 'pheromone-adaptive':
return 'hybrid';
default:
return 'hierarchical';
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index 1c0e6a2a12..4c058a22bd 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -214,7 +214,9 @@ export class CLI {
try {
const { ensureDaemonRunning } = await import('./services/daemon-autostart.js');
const d = ensureDaemonRunning(process.cwd());
- if (d.started && this.output.isVerbose()) this.output.printDebug('Started background daemon (auto)');
+ if (d.started) {
+ this.output.printInfo(`Started Ruflo background daemon for ${process.cwd()} (stop: ruflo daemon stop)`);
+ }
} catch { /* silent */ }
}
}
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 8f0add7ca3..47f791be3b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
@@ -10,6 +10,7 @@ import { join } from 'node:path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier, validateText, validateAgentSpawn } from './validate-input.js';
import { executeAgentTask } from './agent-execute-core.js';
+import { pheromoneAgentEligibility } from './swarm-tools.js';
// Storage paths
const STORAGE_DIR = '.claude-flow';
@@ -465,6 +466,15 @@ export const agentTools: MCPTool[] = [
if (!vId.valid) return { success: false, error: `Input validation failed: ${vId.error}` };
const vP = validateText(input.prompt as string, 'prompt');
if (!vP.valid) return { success: false, error: `Input validation failed: ${vP.error}` };
+ const pheromone = pheromoneAgentEligibility(input.agentId as string);
+ if (!pheromone.eligible) {
+ return {
+ success: false,
+ agentId: input.agentId,
+ suspended: true,
+ error: pheromone.reason,
+ };
+ }
// Delegate to the shared core (also used by the workflow runtime).
return executeAgentTask({
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 9f7461a036..03bb2d690b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -9,6 +9,11 @@ import { dirname, join, resolve } from 'path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier, validateText, validatePath } from './validate-input.js';
import { checkCommandLoop, recordCommandOutcome } from './tool-loop-guardrail.js';
+import {
+ buildLearnedRoutingPatterns,
+ type LearnedRoutingOutcome,
+ type LearnedRoutingPattern,
+} from '../services/learned-routing.js';
// Real vector search functions - lazy loaded to avoid circular imports
let searchEntriesFn: ((options: {
@@ -198,13 +203,14 @@ const ROUTING_STOPWORDS = new Set([
'some','such','same','new','now','here','there','where','how','what','which','who',
]);
-interface RoutingOutcome {
- task: string;
- agent: string;
- success: boolean;
- quality: number;
+type RoutingOutcome = LearnedRoutingOutcome;
+
+interface RoutingPattern {
keywords: string[];
- timestamp: string;
+ agents: string[];
+ source?: 'static' | 'learned';
+ support?: number;
+ reliability?: number;
}
function extractKeywords(text: string): string[] {
@@ -232,6 +238,13 @@ function saveRoutingOutcomes(outcomes: RoutingOutcome[]): void {
// Cap at 500 entries to bound file size
const capped = outcomes.slice(-500);
writeFileSync(ROUTING_OUTCOMES_PATH, JSON.stringify({ outcomes: capped }, null, 2));
+ // A long-lived MCP process must observe the new label on the next route.
+ // The prior singleton cache made the learned store inert until restart.
+ semanticRouter = null;
+ nativeVectorDb = null;
+ semanticRouterInitialized = false;
+ routerBackend = 'none';
+ TASK_PATTERN_EMBEDDINGS.clear();
} catch { /* non-critical */ }
}
@@ -240,29 +253,15 @@ function saveRoutingOutcomes(outcomes: RoutingOutcome[]): void {
* Returns patterns in the same shape as TASK_PATTERNS so they can be
* merged into both the native HNSW and pure-JS semantic routers.
*/
-function loadLearnedPatterns(): Record<string, { keywords: string[]; agents: string[] }> {
- const outcomes = loadRoutingOutcomes();
- const byAgent: Record<string, Set<string>> = {};
- for (const o of outcomes) {
- if (!o.success || !o.agent || !o.keywords?.length) continue;
- if (!byAgent[o.agent]) byAgent[o.agent] = new Set();
- for (const kw of o.keywords) byAgent[o.agent].add(kw);
- }
- const patterns: Record<string, { keywords: string[]; agents: string[] }> = {};
- for (const [agent, kwSet] of Object.entries(byAgent)) {
- patterns[`learned-${agent}`] = {
- keywords: [...kwSet].slice(0, 50),
- agents: [agent],
- };
- }
- return patterns;
+function loadLearnedPatterns(): Record<string, LearnedRoutingPattern> {
+ return buildLearnedRoutingPatterns(loadRoutingOutcomes());
}
/**
* Merge static TASK_PATTERNS with runtime-learned patterns.
* Static patterns take precedence (learned patterns won't overwrite them).
*/
-function getMergedTaskPatterns(): Record<string, { keywords: string[]; agents: string[] }> {
+function getMergedTaskPatterns(): Record<string, RoutingPattern> {
const merged = { ...TASK_PATTERNS };
const learned = loadLearnedPatterns();
for (const [key, pattern] of Object.entries(learned)) {
@@ -275,7 +274,7 @@ function getMergedTaskPatterns(): Record<string, { keywords: string[]; agents: s
// ── Static task patterns (used by both native and pure-JS routers) ───
-const TASK_PATTERNS: Record<string, { keywords: string[]; agents: string[] }> = {
+const TASK_PATTERNS: Record<string, RoutingPattern> = {
'security-task': {
keywords: ['authentication', 'security', 'auth', 'password', 'encryption', 'vulnerability', 'cve', 'audit'],
agents: ['security-architect', 'security-auditor', 'reviewer'],
@@ -339,7 +338,9 @@ async function getSemanticRouter() {
// STEP 1: Try native VectorDb from @ruvector/router (HNSW-backed)
// Note: Native VectorDb uses a persistent database file which can have lock issues
// in concurrent environments. We try it first but fall back gracefully to pure JS.
- try {
+ // Deterministic/test and lock-constrained environments may force the
+ // pure-JS router; production continues to prefer the native backend.
+ if (process.env.CLAUDE_FLOW_DISABLE_NATIVE_ROUTER !== '1') try {
// Use createRequire for ESM compatibility with native modules
const { createRequire } = await import('module');
const require = createRequire(import.meta.url);
@@ -380,9 +381,15 @@ async function getSemanticRouter() {
const { SemanticRouter } = await import('../ruvector/semantic-router.js');
semanticRouter = new SemanticRouter({ dimension: 384 });
- for (const [patternName, { keywords, agents }] of Object.entries(getMergedTaskPatterns())) {
+ for (const [patternName, { keywords, agents, source, support, reliability }] of Object.entries(getMergedTaskPatterns())) {
const embeddings = keywords.map(kw => generateSimpleEmbedding(kw));
- semanticRouter.addIntentWithEmbeddings(patternName, embeddings, { agents, keywords });
+ semanticRouter.addIntentWithEmbeddings(patternName, embeddings, {
+ agents,
+ keywords,
+ source: source ?? 'static',
+ support,
+ reliability,
+ });
// Cache embeddings for keywords
keywords.forEach((kw, i) => {
@@ -1075,6 +1082,9 @@ export const hooksRoute: MCPTool = {
score: 1 - r.score, // Native uses distance (lower is better), convert to similarity
metadata: {
agents: pattern?.agents || (patternName.startsWith('learned-') ? [patternName.slice(8)] : ['coder']),
+ source: pattern?.source ?? (patternName.startsWith('learned-') ? 'learned' : 'static'),
+ support: pattern?.support,
+ reliability: pattern?.reliability,
},
};
});
@@ -1097,8 +1107,16 @@ export const hooksRoute: MCPTool = {
let confidence: number;
let matchedPattern = '';
- if (semanticResult.length > 0 && semanticResult[0].score > 0.4) {
- const topMatch = semanticResult[0];
+ const eligibleSemantic = semanticResult.find((match) => {
+ if (match.score <= 0.4) return false;
+ const learned = match.intent.startsWith('learned-') || match.metadata.source === 'learned';
+ if (!learned) return true;
+ return match.score >= 0.65
+ && Number(match.metadata.support ?? 0) >= 2
+ && Number(match.metadata.reliability ?? 0) >= 0.75;
+ });
+ if (eligibleSemantic) {
+ const topMatch = eligibleSemantic;
agents = (topMatch.metadata.agents as string[]) || ['coder', 'researcher'];
confidence = topMatch.score;
matchedPattern = topMatch.intent;
@@ -1381,6 +1399,10 @@ export const hooksPostTask: MCPTool = {
agent: { type: 'string', description: 'Agent that completed the task' },
quality: { type: 'number', description: 'Quality score (0-1)' },
task: { type: 'string', description: 'Task description text (used for learning keyword extraction)' },
+ duration: { type: 'number', description: 'Observed task duration in milliseconds (used by pheromone-adaptive topology)' },
+ latencyBudgetMs: { type: 'number', description: 'Latency budget used to normalize duration (default 60000ms)' },
+ consensusAlignment: { type: 'number', description: 'Agreement with accepted swarm consensus in [0,1] (default quality)' },
+ agentRole: { type: 'string', description: 'Role for role-local pheromone normalization (default agent)' },
storeDecisions: { type: 'boolean', description: 'Also store routing decision in memory DB' },
// ADR-147 P2: nested-subagent spawn-tree capture
parentAgentId: { type: 'string', description: 'ID of the parent agent (from Claude Code\'s parent_agent_id OTel span tag / x-claude-code-parent-agent-id header). Omit for top-level work.' },
@@ -1533,6 +1555,22 @@ export const hooksPostTask: MCPTool = {
} catch { /* non-critical */ }
}
+ let pheromone: unknown;
+ if (agent) {
+ try {
+ const { recordSwarmPheromoneSignal } = await import('./swarm-tools.js');
+ const observedDuration = Math.max(0, Number(params.duration ?? (Date.now() - startTime)));
+ const latencyBudgetMs = Math.max(1, Number(params.latencyBudgetMs ?? 60_000));
+ pheromone = recordSwarmPheromoneSignal({
+ agentId: agent,
+ role: String(params.agentRole ?? agent),
+ taskSuccess: success ? 1 : 0,
+ normalizedLatency: Math.max(0, Math.min(1, observedDuration / latencyBudgetMs)),
+ consensusAlignment: Math.max(0, Math.min(1, Number(params.consensusAlignment ?? quality))),
+ });
+ } catch { /* no active APSC swarm or optional path unavailable */ }
+ }
+
const duration = Date.now() - startTime;
// Persist to auto-memory-store for statusline visibility
@@ -1571,6 +1609,7 @@ export const hooksPostTask: MCPTool = {
outcomePersisted,
},
quality,
+ pheromone,
feedback: feedbackResult ? {
recorded: feedbackResult.success,
controller: feedbackResult.controller,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
index e18483eb83..f503c3c56a 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -1228,6 +1228,7 @@ export const memoryTools: MCPTool[] = [
handler: async (input) => {
await ensureInitialized();
const { listEntries, deleteEntry } = await getMemoryFunctions();
+ const startedAt = Date.now();
const dryRun = input.dryRun !== false; // default true
const namespace = input.namespace ? String(input.namespace) : undefined;
if (namespace) { const v = validateIdentifier(namespace, 'namespace'); if (!v.valid) throw new Error(v.error); }
@@ -1241,6 +1242,7 @@ export const memoryTools: MCPTool[] = [
});
let freedBytes = 0;
let deleted = 0;
+ let vectorsRemoved = 0;
if (!dryRun) {
for (const e of expired) {
try { await deleteEntry({ key: e.key, namespace: e.namespace }); freedBytes += (e.size as number) || 0; deleted++; }
@@ -1249,11 +1251,21 @@ export const memoryTools: MCPTool[] = [
} else {
freedBytes = expired.reduce((s, e) => s + ((e.size as number) || 0), 0);
}
+ if (!dryRun) {
+ const { reconcileHNSWIndex } = await import('../memory/memory-initializer.js');
+ vectorsRemoved = await reconcileHNSWIndex();
+ }
+ const formatted = freedBytes < 1024
+ ? `${freedBytes} B`
+ : freedBytes < 1024 * 1024
+ ? `${(freedBytes / 1024).toFixed(1)} KiB`
+ : `${(freedBytes / (1024 * 1024)).toFixed(1)} MiB`;
return {
dryRun,
candidates: { expired: expired.length, stale: 0, lowQuality: 0, total: expired.length },
- deleted: { entries: dryRun ? 0 : deleted, vectors: 0, patterns: 0 },
- freed: { bytes: freedBytes },
+ deleted: { entries: dryRun ? 0 : deleted, vectors: vectorsRemoved, patterns: 0 },
+ freed: { bytes: freedBytes, formatted },
+ duration: Date.now() - startedAt,
note: dryRun ? 'dry run — re-run with dryRun:false to delete' : undefined,
};
},
diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
index 270f2471ab..98faf3c5d5 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
@@ -634,6 +634,9 @@ export const metaharnessTools: MCPTool[] = [
confirm: { type: 'boolean', description: 'Required for promote; never inferred', default: false },
maxConcurrency: { type: 'number', description: 'ADR-324 hard local candidate-evaluation concurrency cap (1-8)', default: 2 },
timeoutMs: { type: 'number', description: 'Abort concurrent evaluation after this wall-clock limit', default: 120000 },
+ anchorPath: { type: 'string', description: 'Project-contained human-labelled anchor JSON; requires anchorHash' },
+ anchorHash: { type: 'string', description: 'Pinned sha256 of canonical anchor tasks; requires anchorPath' },
+ anchorManifestPath: { type: 'string', description: 'Project-contained anchor manifest path (default .claude/eval/flywheel-anchor.manifest.json)' },
approvalIds: { type: 'array', items: { type: 'string' }, description: 'Scoped ADR-324 approval IDs for privileged promotion' },
},
required: ['operation'],
@@ -655,6 +658,7 @@ export const metaharnessTools: MCPTool[] = [
if (operation === 'receipts') {
const data = listFlywheelReceipts(projectRoot).map(({ receipt, state }) => ({
receiptId: receipt.payload.receiptId,
+ anchorRef: receipt.payload.anchorRef,
candidateId: receipt.payload.candidateId,
baselineRef: receipt.payload.baselineRef,
decision: receipt.payload.decision,
@@ -682,6 +686,9 @@ export const metaharnessTools: MCPTool[] = [
receiptPublicKeyPem: publicKeyPath ? readFileSync(publicKeyPath, 'utf8') : undefined,
maxConcurrency: Number(input.maxConcurrency ?? 2),
evaluationTimeoutMs: Number(input.timeoutMs ?? 120_000),
+ anchorPath: input.anchorPath ? String(input.anchorPath) : undefined,
+ anchorHash: input.anchorHash ? String(input.anchorHash) : undefined,
+ anchorManifestPath: input.anchorManifestPath ? String(input.anchorManifestPath) : undefined,
});
return { success: data.ran, data, degraded: false, exitCode: data.ran ? 0 : 1 };
}
diff --git a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts
index 8e9895ff3b..ea7d5cd506 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts
@@ -5,14 +5,35 @@
* Replaces previous stub implementations with real state tracking.
*/
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import {
+ closeSync,
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { join } from 'node:path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier } from './validate-input.js';
+import {
+ createApscState,
+ isApscAgentEligible,
+ normalizeApscConfig,
+ recordApscSignal,
+ type ApscDecision,
+ type ApscSignal,
+ type ApscState,
+} from '../services/pheromone-adaptive.js';
// Swarm state persistence
const SWARM_DIR = '.claude-flow/swarm';
const SWARM_STATE_FILE = 'swarm-state.json';
+const SWARM_STATE_LOCK = 'swarm-state.lock';
+const SWARM_LOCK_STALE_MS = 10_000;
interface SwarmState {
swarmId: string;
@@ -133,14 +154,96 @@ export function loadSwarmStore(): SwarmStore {
export function saveSwarmStore(store: SwarmStore): void {
ensureSwarmDir();
- writeFileSync(getSwarmStatePath(), JSON.stringify(store, null, 2), 'utf-8');
+ const target = getSwarmStatePath();
+ const temporary = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ writeFileSync(temporary, JSON.stringify(store, null, 2), { encoding: 'utf-8', mode: 0o600 });
+ renameSync(temporary, target);
+ } catch (error) {
+ try { unlinkSync(temporary); } catch { /* already renamed or never created */ }
+ throw error;
+ }
+}
+
+function withSwarmStoreLock<T>(operation: () => T): T {
+ ensureSwarmDir();
+ const lockPath = join(getSwarmDir(), SWARM_STATE_LOCK);
+ let descriptor: number | undefined;
+ const waiter = new Int32Array(new SharedArrayBuffer(4));
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ descriptor = openSync(lockPath, 'wx', 0o600);
+ break;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ try {
+ if (Date.now() - statSync(lockPath).mtimeMs > SWARM_LOCK_STALE_MS) {
+ unlinkSync(lockPath);
+ continue;
+ }
+ } catch { /* another writer released it */ }
+ Atomics.wait(waiter, 0, 0, 10);
+ }
+ }
+ if (descriptor === undefined) throw new Error('swarm state is busy; retry the outcome update');
+ try {
+ return operation();
+ } finally {
+ try { closeSync(descriptor); } catch { /* best effort */ }
+ try { unlinkSync(lockPath); } catch { /* best effort */ }
+ }
}
// Input validation
const VALID_TOPOLOGIES = new Set([
- 'hierarchical', 'mesh', 'hierarchical-mesh', 'ring', 'star', 'hybrid', 'adaptive',
+ 'hierarchical', 'mesh', 'hierarchical-mesh', 'ring', 'star', 'hybrid', 'adaptive', 'pheromone-adaptive',
]);
+function latestRunningSwarm(store: SwarmStore): SwarmState | undefined {
+ return Object.values(store.swarms)
+ .filter((swarm) => swarm.status === 'running')
+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0];
+}
+
+function apscStateOf(swarm: SwarmState | undefined): ApscState | undefined {
+ if (!swarm || swarm.topology !== 'pheromone-adaptive') return undefined;
+ const state = swarm.config.apscState as ApscState | undefined;
+ return state?.schemaVersion ? state : undefined;
+}
+
+/** Shared by hooks_post-task so outcome labels immediately drive APSC. */
+export function recordSwarmPheromoneSignal(
+ signal: ApscSignal,
+): { active: false; reason: string } | { active: true; swarmId: string; decision: ApscDecision } {
+ return withSwarmStoreLock(() => {
+ const store = loadSwarmStore();
+ const swarm = latestRunningSwarm(store);
+ const current = apscStateOf(swarm);
+ if (!swarm || !current) return { active: false, reason: 'no running pheromone-adaptive swarm' };
+ const result = recordApscSignal(current, signal);
+ swarm.config.apscState = result.state;
+ swarm.updatedAt = new Date().toISOString();
+ saveSwarmStore(store);
+ return { active: true, swarmId: swarm.swarmId, decision: result.decision };
+ });
+}
+
+/** Scheduling gate used by agent_execute. Dry-run topologies remain eligible. */
+export function pheromoneAgentEligibility(agentId: string): {
+ eligible: boolean;
+ active: boolean;
+ reason?: string;
+} {
+ const current = apscStateOf(latestRunningSwarm(loadSwarmStore()));
+ if (!current) return { eligible: true, active: false };
+ const eligible = isApscAgentEligible(current, agentId);
+ return {
+ eligible,
+ active: true,
+ reason: eligible ? undefined : 'agent suspended by pheromone-adaptive scheduling gate',
+ };
+}
+
export const swarmTools: MCPTool[] = [
{
name: 'swarm_init',
@@ -149,7 +252,7 @@ export const swarmTools: MCPTool[] = [
inputSchema: {
type: 'object',
properties: {
- topology: { type: 'string', description: 'Swarm topology type (hierarchical, mesh, hierarchical-mesh, ring, star, hybrid, adaptive)' },
+ topology: { type: 'string', description: 'Swarm topology type (hierarchical, mesh, hierarchical-mesh, ring, star, hybrid, adaptive, pheromone-adaptive)' },
maxAgents: { type: 'number', description: 'Maximum number of agents (1-50)' },
strategy: { type: 'string', description: 'Agent strategy (specialized, balanced, adaptive)' },
config: { type: 'object', description: 'Additional swarm configuration' },
@@ -177,6 +280,18 @@ export const swarmTools: MCPTool[] = [
error: `Invalid topology: ${topology}. Valid: ${[...VALID_TOPOLOGIES].join(', ')}`,
};
}
+ let apscState: ApscState | undefined;
+ if (topology === 'pheromone-adaptive') {
+ try {
+ const apscConfig = normalizeApscConfig((config.apsc ?? {}) as Partial<ApscState['config']>);
+ if (apscConfig.minActiveAgents > maxAgents) {
+ return { success: false, error: 'APSC minActiveAgents cannot exceed maxAgents' };
+ }
+ apscState = createApscState(apscConfig);
+ } catch (error) {
+ return { success: false, error: `Invalid APSC config: ${(error as Error).message}` };
+ }
+ }
const swarmId = `swarm-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const now = new Date().toISOString();
@@ -195,12 +310,14 @@ export const swarmTools: MCPTool[] = [
communicationProtocol: (config.communicationProtocol as string) || 'message-bus',
autoScaling: (config.autoScaling as boolean) ?? true,
consensusMechanism: (config.consensusMechanism as string) || 'majority',
+ ...(apscState ? { apscState } : {}),
},
createdAt: now,
updatedAt: now,
- // #1799 — record host PID so subsequent loads can detect orphans
- // when this process exits without a graceful swarm_shutdown.
- pid: process.pid,
+ // A normal CLI invocation exits immediately after creating this
+ // coordination record; its PID is therefore not the swarm lifetime.
+ // Long-lived hosts may opt into PID ownership explicitly.
+ pid: config.trackHostProcess === true ? process.pid : undefined,
};
const store = loadSwarmStore();
@@ -216,6 +333,60 @@ export const swarmTools: MCPTool[] = [
initializedAt: now,
config: swarmState.config,
persisted: true,
+ apsc: apscState ? {
+ dryRun: apscState.config.dryRun,
+ minActiveAgents: apscState.config.minActiveAgents,
+ minSamples: apscState.config.minSamples,
+ } : undefined,
+ };
+ },
+ },
+ {
+ name: 'swarm_pheromone_update',
+ description: 'Record a normalized per-agent task outcome for a running pheromone-adaptive swarm. Use when a static agent pool is wrong because repeated task evidence should update role-aware EMA fitness and produce a bounded keep/suspend/reactivate decision; native Task has no persistent swarm eligibility gate.',
+ category: 'swarm',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentId: { type: 'string', description: 'Stable tracked agent identifier' },
+ role: { type: 'string', description: 'Agent role used for role-local normalization' },
+ taskSuccess: { type: 'number', description: 'Observed task success in [0,1]' },
+ normalizedLatency: { type: 'number', description: 'Latency divided by the configured budget, clamped to [0,1]' },
+ consensusAlignment: { type: 'number', description: 'Agreement with the accepted consensus in [0,1]' },
+ },
+ required: ['agentId', 'role', 'taskSuccess', 'normalizedLatency', 'consensusAlignment'],
+ },
+ handler: async (input) => {
+ try {
+ return recordSwarmPheromoneSignal({
+ agentId: String(input.agentId),
+ role: String(input.role),
+ taskSuccess: Number(input.taskSuccess),
+ normalizedLatency: Number(input.normalizedLatency),
+ consensusAlignment: Number(input.consensusAlignment),
+ });
+ } catch (error) {
+ return { active: false, reason: (error as Error).message };
+ }
+ },
+ },
+ {
+ name: 'swarm_pheromone_status',
+ description: 'Inspect the threshold, safety configuration, per-agent EMA scores, and scheduling eligibility of the active pheromone-adaptive swarm. Use when aggregate swarm status is wrong because calibration requires the exact APSC threshold and per-agent evidence before switching from dry-run to live suspension.',
+ category: 'swarm',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ const store = loadSwarmStore();
+ const swarm = latestRunningSwarm(store);
+ const state = apscStateOf(swarm);
+ if (!swarm || !state) return { active: false, reason: 'no running pheromone-adaptive swarm' };
+ return {
+ active: true,
+ swarmId: swarm.swarmId,
+ threshold: state.threshold,
+ round: state.round,
+ config: state.config,
+ agents: Object.values(state.agents).sort((a, b) => a.agentId.localeCompare(b.agentId)),
};
},
},
@@ -249,6 +420,7 @@ export const swarmTools: MCPTool[] = [
agentCount: swarm.agents.length,
taskCount: swarm.tasks.length,
config: swarm.config,
+ apsc: apscStateOf(swarm),
createdAt: swarm.createdAt,
updatedAt: swarm.updatedAt,
};
@@ -276,6 +448,7 @@ export const swarmTools: MCPTool[] = [
agentCount: latest.agents.length,
taskCount: latest.tasks.length,
config: latest.config,
+ apsc: apscStateOf(latest),
createdAt: latest.createdAt,
updatedAt: latest.updatedAt,
totalSwarms: swarmIds.length,
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index 368f7730ea..15a26b2cad 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -542,7 +542,7 @@ CREATE TABLE IF NOT EXISTS metadata (
// Uses @ruvector/core from agentic-flow for WASM-accelerated HNSW
// ============================================================================
-interface HNSWEntry {
+export interface HNSWEntry {
id: string;
key: string;
namespace: string;
@@ -723,6 +723,69 @@ function saveHNSWMetadata(): void {
}
}
+export function removeHNSWEntriesByLogicalKey(
+ entries: Map<string, HNSWEntry>,
+ key: string,
+ namespace: string,
+): number {
+ let removed = 0;
+ for (const [id, entry] of entries) {
+ if (entry.key === key && (entry.namespace ?? 'default') === namespace) {
+ entries.delete(id);
+ removed++;
+ }
+ }
+ return removed;
+}
+
+function removeHNSWEntriesByKey(key: string, namespace: string): number {
+ if (!hnswIndex?.entries) return 0;
+ const removed = removeHNSWEntriesByLogicalKey(hnswIndex.entries, key, namespace);
+ if (removed > 0) {
+ saveHNSWMetadata();
+ rebuildSearchIndex();
+ }
+ return removed;
+}
+
+/**
+ * Remove HNSW metadata whose authoritative SQLite row is no longer active.
+ * Persistent graph nodes may remain physically allocated, but without metadata
+ * they cannot resolve into search results; the next rebuild repopulates only
+ * active rows. Returns the number of searchable vectors invalidated.
+ */
+export async function reconcileHNSWIndex(dbPath?: string): Promise<number> {
+ if (!hnswIndex?.entries) return 0;
+ const effectivePath = dbPath
+ ? path.resolve(dbPath)
+ : path.join(getMemoryRoot(), 'memory.db');
+ if (!fs.existsSync(effectivePath)) return 0;
+ try {
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
+ const db = new SQL.Database(readFileMaybeEncrypted(effectivePath, null));
+ const rows = db.exec(`SELECT id FROM memory_entries WHERE status = 'active'`);
+ const active = new Set(
+ (rows[0]?.values ?? []).map((row) => String(row[0])),
+ );
+ db.close();
+ let removed = 0;
+ for (const id of hnswIndex.entries.keys()) {
+ if (!active.has(id)) {
+ hnswIndex.entries.delete(id);
+ removed++;
+ }
+ }
+ if (removed > 0) {
+ saveHNSWMetadata();
+ rebuildSearchIndex();
+ }
+ return removed;
+ } catch {
+ return 0;
+ }
+}
+
/**
* Add entry to HNSW index (with automatic persistence)
*/
@@ -2736,6 +2799,9 @@ export async function storeEntry(options: {
// Keep HNSW index in sync with bridge-stored entries
if (bridgeResult.rawEmbedding && bridgeResult.success) {
const ns = options.namespace || 'default';
+ // Upsert/resurrection may allocate a new row id. Remove every older
+ // vector for the logical (namespace,key), not merely the newest id.
+ removeHNSWEntriesByKey(options.key, ns);
await addToHNSWIndex(bridgeResult.id, bridgeResult.rawEmbedding, {
id: bridgeResult.id,
key: options.key,
@@ -2869,6 +2935,7 @@ export async function storeEntry(options: {
// Add to HNSW index for faster future searches
if (embeddingJson) {
const embResult = JSON.parse(embeddingJson) as number[];
+ if (upsert) removeHNSWEntriesByKey(key, namespace);
await addToHNSWIndex(id, embResult, {
id,
key,
@@ -3533,15 +3600,7 @@ export async function deleteEntry(options: {
// #1122: Bridge path must also invalidate the in-memory HNSW index.
// Without this, deleted vectors remain as ghost entries in search results.
if (bridgeResult.deleted && hnswIndex?.entries) {
- // Remove the entry from the HNSW entries map by key+namespace composite
- for (const [id, entry] of hnswIndex.entries) {
- if ((entry as any)?.key === options.key && ((entry as any)?.namespace ?? 'default') === (options.namespace ?? 'default')) {
- hnswIndex.entries.delete(id);
- break;
- }
- }
- saveHNSWMetadata();
- rebuildSearchIndex();
+ removeHNSWEntriesByKey(options.key, options.namespace ?? 'default');
}
return bridgeResult;
}
@@ -3622,9 +3681,6 @@ 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(`
@@ -3650,14 +3706,7 @@ export async function deleteEntry(options: {
// 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();
- }
+ if (hnswIndex?.entries) removeHNSWEntriesByKey(key, namespace);
return {
success: true,
diff --git a/v3/@claude-flow/cli/src/services/daemon-autostart.ts b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
index 03a85a217c..c551b8a8fb 100644
--- a/v3/@claude-flow/cli/src/services/daemon-autostart.ts
+++ b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
@@ -8,8 +8,9 @@
* - single-instance: only starts when no live daemon holds the pidfile, and
* the spawned `daemon start` independently enforces single-instance via its
* own lock + checkExistingDaemon() — so a race spawns at most one survivor,
- * - bounded lifetime: the daemon self-terminates on TTL/idle (12h default,
- * RUFLO_DAEMON_TTL_SECS) — auto-start never means "runs forever",
+ * - bounded lifetime: the daemon self-terminates on TTL/idle (12h hard TTL,
+ * 30m idle default; RUFLO_DAEMON_TTL_SECS / RUFLO_DAEMON_IDLE_SECS) —
+ * auto-start never means "runs forever",
* - opt-out: RUFLO_DAEMON_AUTOSTART=0|false|no disables it entirely, OR a
* project-local `daemon.autostart: false` in claude-flow.config.json —
* the file-based opt-out exists because the env var only reaches a
@@ -89,8 +90,10 @@ export function ensureDaemonRunning(
): EnsureResult {
try {
if (autostartDisabled(projectRoot)) return { started: false, reason: 'disabled (RUFLO_DAEMON_AUTOSTART=0 or project config)' };
- // Only in an initialized project (avoid scaffolding a daemon in a random dir).
- if (!fs.existsSync(path.join(projectRoot, '.claude-flow')) && !fs.existsSync(path.join(projectRoot, '.claude'))) {
+ // `.claude/` belongs to Claude Code and is present in many repositories
+ // that have never initialized Ruflo. Only Ruflo's own state directory is
+ // an authorization signal for spawning a detached background process.
+ if (!fs.existsSync(path.join(projectRoot, '.claude-flow'))) {
return { started: false, reason: 'not a ruflo project' };
}
const alive = (opts.isAlive ?? isDaemonAlive)(projectRoot);
diff --git a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts b/v3/@claude-flow/cli/src/services/flywheel-receipt.ts
index 5853a5d779..a9bbaedd78 100644
--- a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts
+++ b/v3/@claude-flow/cli/src/services/flywheel-receipt.ts
@@ -78,6 +78,8 @@ export interface FlywheelReceiptPayload {
gateVersion: string;
policySchemaVersion: string;
safetyEnvelopeRef: string;
+ /** Hash-pinned human relevance anchor used for this evaluation (#2840). */
+ anchorRef?: string;
requestedProposer: 'auto' | ProposerName;
effectiveProposer: ProposerName;
proposerSubstitution?: string;
@@ -110,6 +112,7 @@ export interface CreateReceiptInput {
gateVersion?: string;
policySchemaVersion?: string;
safetyEnvelopeRef: string;
+ anchorRef?: string;
requestedProposer?: 'auto' | ProposerName;
effectiveProposer?: ProposerName;
proposerSubstitution?: string;
@@ -332,6 +335,7 @@ export function createFlywheelReceipt(input: CreateReceiptInput): FlywheelEvalua
gateVersion: input.gateVersion ?? statistics.ruleVersion,
policySchemaVersion: input.policySchemaVersion ?? 'ruflo.retrieval-policy/v1',
safetyEnvelopeRef: input.safetyEnvelopeRef,
+ ...(input.anchorRef ? { anchorRef: input.anchorRef } : {}),
requestedProposer: input.requestedProposer ?? 'local',
effectiveProposer: input.effectiveProposer ?? 'local',
...(input.proposerSubstitution ? { proposerSubstitution: input.proposerSubstitution } : {}),
diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
index 2eefef56f2..4081816b03 100644
--- a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
+++ b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
@@ -12,10 +12,9 @@ import {
type FlywheelDeps,
type FlywheelResult,
type RetrievalConfig,
- type AnchorTask,
} from './harness-flywheel.js';
import { runFlywheelGeneration, checkServedChampionDrift, type GenerationResult, type GenerationDeps } from './harness-flywheel-generations.js';
-import { loadFrozenHumanEval } from './harness-frozen-eval.js';
+import { loadEffectiveFlywheelAnchor } from './harness-project-anchor.js';
import {
proposeFlywheelCandidates,
type DarwinInvoker,
@@ -25,20 +24,6 @@ import {
import { sha256Ref } from './flywheel-receipt.js';
import { evaluatePolicyRequest } from './policy-runtime.js';
-/** The human-labeled ADR-081 anchor — the never-regress relevance set. */
-const ANCHOR: AnchorTask[] = [
- ['how was the Opus model alias fixed', ['opus 4.8', 'opus alias', 'opus model alias', '#2232']],
- ['self-learning wiring task-completed pretrain', ['self-learning', 'adr-074', 'self learning', '#2245', 'task-completed']],
- ['deterministic codemod engine var-to-const', ['deterministic tier-1 codemod', 'adr-143', 'codemod', 'var-to-const']],
- ['MCP server orphan leak parent-death', ['mcp orphan', 'mcp servers orphan', 'parent-death', '#2234', 'orphan on every claude']],
- ['unified learning stats aggregator', ['unified learning-stats', 'adr-075', 'unified learning stats']],
- ['structured distillation 4-field schema', ['structured distillation', 'adr-076', '4-field schema']],
- ['SQL injection migrate.ts table identifier', ['sql injection', 'shell injection', 'migrate.ts', 'agentdb', 'cve']],
- ['recall@k HNSW benchmark harness', ['hnsw', 'memory-recall', 'benchmark suite', 'recall@k', 'benchmark intelligence']],
- ['Q-learning encoder keyword block', ['q-state encoder', 'route q-state', 'keyword block', '#2239', 'q-encoder']],
- ['security hardening crypto random IDs', ['cwe-347', 'crypto.randomuuid', 'security fix', 'random id', 'crypto random']],
-].map(([q, labels], i) => ({ id: `q${String(i).padStart(2, '0')}`, input: { id: `q${String(i).padStart(2, '0')}`, q: q as string }, expected: labels as string[] }));
-
/**
* The ADR-322 retrieval safety envelope.
*
@@ -105,6 +90,9 @@ export async function runFlywheelWorker(
allowSubstitutionPromotion?: boolean;
maxConcurrency?: number;
evaluationTimeoutMs?: number;
+ anchorPath?: string;
+ anchorHash?: string;
+ anchorManifestPath?: string;
} = {},
): Promise<FlywheelResult> {
try {
@@ -131,6 +119,11 @@ export async function runFlywheelWorker(
...((applier.activeChampion(projectRoot)?.params as Partial<RetrievalConfig>) ?? {}),
};
const safetyEnvelope = retrievalSafetyEnvelope(opts.safetyEnvelopeRef);
+ const anchor = loadEffectiveFlywheelAnchor(projectRoot, {
+ anchorPath: opts.anchorPath ?? process.env.RUFLO_FLYWHEEL_ANCHOR_PATH,
+ anchorHash: opts.anchorHash ?? process.env.RUFLO_FLYWHEEL_ANCHOR_HASH,
+ manifestPath: opts.anchorManifestPath ?? process.env.RUFLO_FLYWHEEL_ANCHOR_MANIFEST,
+ });
// CLI flag opts.proposer takes precedence over RUFLO_FLYWHEEL_PROPOSER.
const proposerMode = opts.proposer
?? ((process.env.RUFLO_FLYWHEEL_PROPOSER as ProposerMode | undefined) ?? 'auto');
@@ -166,7 +159,8 @@ export async function runFlywheelWorker(
const r = await tool.handler({ action: 'search', query, mode: 'hybrid', limit: 5, rerank: false, ...cfg }) as { results?: Array<{ id?: string; name?: string }> };
return (r.results || []).slice(0, 5).map((m) => ({ id: m?.id ?? '', name: m?.name ?? '' }));
},
- anchorTasks: ANCHOR,
+ anchorTasks: anchor.tasks,
+ anchorRef: anchor.anchorRef,
activeParams: () => baseline,
sample: opts.sample ?? 40,
now: opts.now,
@@ -198,23 +192,37 @@ export async function runFlywheelWorker(
*/
export async function runFlywheelGenerationWorker(
projectRoot: string,
- opts: { sample?: number; optInOverride?: boolean; now?: number } = {},
+ opts: {
+ sample?: number;
+ optInOverride?: boolean;
+ now?: number;
+ anchorPath?: string;
+ anchorHash?: string;
+ anchorManifestPath?: string;
+ } = {},
): Promise<GenerationResult> {
try {
if (!(opts.optInOverride ?? harnessLoopOptedIn())) return { ran: false, reason: 'opt-in required (RUFLO_HARNESS_LOOP=1)', generation: 0 };
const neural = await import('../mcp-tools/neural-tools.js');
const tool = neural.neuralTools.find((t) => t.name === 'neural_patterns');
if (!tool) return { ran: false, reason: 'neural_patterns tool unavailable', generation: 0 };
- // Load the FROZEN, hashed, public human eval set (throws if it has drifted).
- const frozen = loadFrozenHumanEval();
+ const anchor = loadEffectiveFlywheelAnchor(projectRoot, {
+ anchorPath: opts.anchorPath ?? process.env.RUFLO_FLYWHEEL_ANCHOR_PATH,
+ anchorHash: opts.anchorHash ?? process.env.RUFLO_FLYWHEEL_ANCHOR_HASH,
+ manifestPath: opts.anchorManifestPath ?? process.env.RUFLO_FLYWHEEL_ANCHOR_MANIFEST,
+ });
const deps: GenerationDeps = {
getPatterns: () => neural.getStorePatterns(),
search: async (query, cfg: RetrievalConfig) => {
const r = await tool.handler({ action: 'search', query, mode: 'hybrid', limit: 5, rerank: false, ...cfg }) as { results?: Array<{ id?: string; name?: string }> };
return (r.results || []).slice(0, 5).map((m) => ({ id: m?.id ?? '', name: m?.name ?? '' }));
},
- anchorTasks: frozen.tasks,
- humanEvalHash: frozen.corpusHash,
+ anchorTasks: anchor.tasks.map((task) => ({
+ id: task.id,
+ q: task.input.q,
+ labels: task.expected,
+ })),
+ humanEvalHash: anchor.anchorRef,
sample: opts.sample ?? 120,
now: opts.now ?? Date.now(),
};
diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel.ts b/v3/@claude-flow/cli/src/services/harness-flywheel.ts
index 0ffb76d84e..06adb29bb7 100644
--- a/v3/@claude-flow/cli/src/services/harness-flywheel.ts
+++ b/v3/@claude-flow/cli/src/services/harness-flywheel.ts
@@ -57,6 +57,8 @@ export interface FlywheelDeps {
lineageId?: string;
evaluationRunId?: string;
safetyEnvelopeRef?: string;
+ /** Hash of the project-specific human-labelled objective. */
+ anchorRef?: string;
requestedProposer?: 'auto' | 'local' | 'darwin';
effectiveProposer?: 'local' | 'darwin';
proposerSubstitution?: string;
@@ -266,6 +268,7 @@ export async function evaluateFlywheelCandidate(projectRoot: string, deps: Flywh
expectedLedgerHead: txState.ledgerHead,
candidatePolicy: candidate as unknown as Record<string, unknown>,
safetyEnvelopeRef,
+ anchorRef: deps.anchorRef,
requestedProposer: deps.requestedProposer ?? 'local',
effectiveProposer: deps.effectiveProposer ?? 'local',
proposerSubstitution: deps.proposerSubstitution,
diff --git a/v3/@claude-flow/cli/src/services/harness-project-anchor.ts b/v3/@claude-flow/cli/src/services/harness-project-anchor.ts
new file mode 100644
index 0000000000..c21229c373
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/harness-project-anchor.ts
@@ -0,0 +1,188 @@
+/**
+ * Project-local, hash-pinned flywheel anchors (#2840).
+ *
+ * Downstream repositories must be evaluated against their own labelled
+ * retrieval tasks. Silently using Ruflo's development-history benchmark makes
+ * the objective flat and indistinguishable from "already optimal", so foreign
+ * projects fail closed unless they supply a pinned anchor manifest.
+ */
+import {
+ existsSync,
+ readFileSync,
+ realpathSync,
+} from 'node:fs';
+import {
+ dirname,
+ isAbsolute,
+ join,
+ relative,
+ resolve,
+ sep,
+} from 'node:path';
+import {
+ FROZEN_HUMAN_EVAL_HASH,
+ loadFrozenHumanEval,
+ humanEvalHash,
+ type HumanEvalTask,
+} from './harness-frozen-eval.js';
+import type { AnchorTask } from './harness-flywheel.js';
+
+export const PROJECT_ANCHOR_SCHEMA = 'ruflo.flywheel-anchor/v1';
+export const PROJECT_ANCHOR_MANIFEST_SCHEMA = 'ruflo.flywheel-anchor-manifest/v1';
+export const DEFAULT_PROJECT_ANCHOR_MANIFEST = join('.claude', 'eval', 'flywheel-anchor.manifest.json');
+
+export interface ProjectAnchorManifest {
+ schemaVersion: typeof PROJECT_ANCHOR_MANIFEST_SCHEMA;
+ path: string;
+ sha256: string;
+}
+
+export interface FlywheelAnchorSelection {
+ version: string;
+ anchorRef: string;
+ tasks: AnchorTask[];
+ source: 'project' | 'ruflo-built-in';
+ path?: string;
+}
+
+export interface LoadFlywheelAnchorOptions {
+ anchorPath?: string;
+ anchorHash?: string;
+ manifestPath?: string;
+}
+
+function normalizeHash(value: string): string {
+ const trimmed = value.trim().toLowerCase();
+ return trimmed.startsWith('sha256:') ? trimmed : `sha256:${trimmed}`;
+}
+
+function containedPath(projectRoot: string, requested: string): string {
+ const root = realpathSync(resolve(projectRoot));
+ const absolute = isAbsolute(requested) ? resolve(requested) : resolve(root, requested);
+ const lexical = relative(root, absolute);
+ if (lexical === '..' || lexical.startsWith(`..${sep}`) || isAbsolute(lexical)) {
+ throw new Error('flywheel anchor path must stay inside project root');
+ }
+ const actual = realpathSync(absolute);
+ const physical = relative(root, actual);
+ if (physical === '..' || physical.startsWith(`..${sep}`) || isAbsolute(physical)) {
+ throw new Error('flywheel anchor symlink escapes project root');
+ }
+ return actual;
+}
+
+function parseTasks(path: string): { version: string; tasks: HumanEvalTask[] } {
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as {
+ schemaVersion?: string;
+ version?: string;
+ tasks?: HumanEvalTask[];
+ };
+ if (parsed.schemaVersion && parsed.schemaVersion !== PROJECT_ANCHOR_SCHEMA) {
+ throw new Error(`unsupported flywheel anchor schema: ${parsed.schemaVersion}`);
+ }
+ if (!Array.isArray(parsed.tasks) || parsed.tasks.length < 4) {
+ throw new Error('project flywheel anchor requires at least 4 labelled tasks');
+ }
+ const ids = new Set<string>();
+ for (const [index, task] of parsed.tasks.entries()) {
+ if (!task || typeof task.id !== 'string' || !/^[A-Za-z0-9._-]{1,128}$/.test(task.id)) {
+ throw new Error(`invalid anchor task id at index ${index}`);
+ }
+ if (ids.has(task.id)) throw new Error(`duplicate anchor task id: ${task.id}`);
+ ids.add(task.id);
+ if (typeof task.q !== 'string' || task.q.trim().length === 0) {
+ throw new Error(`anchor task ${task.id} has no query`);
+ }
+ if (!Array.isArray(task.labels) || task.labels.length === 0 || task.labels.some((label) => typeof label !== 'string' || !label.trim())) {
+ throw new Error(`anchor task ${task.id} requires non-empty string labels`);
+ }
+ }
+ return { version: parsed.version ?? 'project-anchor-v1', tasks: parsed.tasks };
+}
+
+function toSelection(
+ path: string,
+ expectedHash: string,
+): FlywheelAnchorSelection {
+ const parsed = parseTasks(path);
+ const actualHash = humanEvalHash(parsed.tasks);
+ if (actualHash !== normalizeHash(expectedHash)) {
+ throw new Error(`project flywheel anchor hash mismatch (got ${actualHash}, pinned ${normalizeHash(expectedHash)})`);
+ }
+ return {
+ version: parsed.version,
+ anchorRef: actualHash,
+ source: 'project',
+ path,
+ tasks: parsed.tasks.map((task) => ({
+ id: task.id,
+ input: { id: task.id, q: task.q },
+ expected: task.labels,
+ })),
+ };
+}
+
+function isRufloRepository(projectRoot: string): boolean {
+ try {
+ const pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8')) as {
+ name?: string;
+ repository?: string | { url?: string };
+ };
+ const repository = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url;
+ return ['claude-flow', 'ruflo', '@claude-flow/cli'].includes(pkg.name ?? '')
+ && /github\.com[/:]ruvnet\/(?:ruflo|claude-flow)(?:\.git)?$/i.test(repository ?? '');
+ } catch {
+ return false;
+ }
+}
+
+export function loadEffectiveFlywheelAnchor(
+ projectRoot: string,
+ options: LoadFlywheelAnchorOptions = {},
+): FlywheelAnchorSelection {
+ const root = resolve(projectRoot);
+ if (!!options.anchorPath !== !!options.anchorHash) {
+ throw new Error('anchorPath and anchorHash must be supplied together');
+ }
+ if (options.anchorPath && options.anchorHash) {
+ return toSelection(containedPath(root, options.anchorPath), options.anchorHash);
+ }
+
+ const manifestCandidate = options.manifestPath ?? DEFAULT_PROJECT_ANCHOR_MANIFEST;
+ const manifestPath = isAbsolute(manifestCandidate)
+ ? manifestCandidate
+ : resolve(root, manifestCandidate);
+ if (existsSync(manifestPath)) {
+ const containedManifest = containedPath(root, manifestPath);
+ const manifest = JSON.parse(readFileSync(containedManifest, 'utf8')) as ProjectAnchorManifest;
+ if (manifest.schemaVersion !== PROJECT_ANCHOR_MANIFEST_SCHEMA) {
+ throw new Error(`unsupported flywheel anchor manifest schema: ${manifest.schemaVersion}`);
+ }
+ if (typeof manifest.path !== 'string' || typeof manifest.sha256 !== 'string') {
+ throw new Error('flywheel anchor manifest requires path and sha256');
+ }
+ // Manifest-relative paths are easier to relocate while remaining
+ // repository-contained; project-relative paths remain supported.
+ const manifestRelative = resolve(dirname(containedManifest), manifest.path);
+ const requested = existsSync(manifestRelative) ? manifestRelative : resolve(root, manifest.path);
+ return toSelection(containedPath(root, requested), manifest.sha256);
+ }
+
+ if (isRufloRepository(root) || process.env.RUFLO_FLYWHEEL_ALLOW_BUILTIN_ANCHOR === '1') {
+ const frozen = loadFrozenHumanEval();
+ return {
+ version: frozen.version,
+ anchorRef: FROZEN_HUMAN_EVAL_HASH,
+ source: 'ruflo-built-in',
+ tasks: frozen.tasks.map((task) => ({
+ id: task.id,
+ input: { id: task.id, q: task.q },
+ expected: task.labels,
+ })),
+ };
+ }
+
+ throw new Error(
+ `project-local flywheel anchor required; create ${DEFAULT_PROJECT_ANCHOR_MANIFEST} or pass anchorPath + anchorHash`,
+ );
+}
diff --git a/v3/@claude-flow/cli/src/services/learned-routing.ts b/v3/@claude-flow/cli/src/services/learned-routing.ts
new file mode 100644
index 0000000000..8eec0ef2c7
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/learned-routing.ts
@@ -0,0 +1,123 @@
+/**
+ * Discriminative routing-pattern learner (#2839).
+ *
+ * Outcomes are labelled by the agent that actually completed the task. The
+ * previous implementation collapsed every successful task for an agent into
+ * one insertion-ordered Set and kept the first 50 words forever. This module
+ * ranks terms by within-agent support, cross-agent rarity, outcome quality,
+ * and discriminative share. Generic terms therefore lose to stable,
+ * agent-specific evidence, and later outcomes can replace earlier noise.
+ */
+
+export interface LearnedRoutingOutcome {
+ task: string;
+ agent: string;
+ success: boolean;
+ quality: number;
+ keywords: string[];
+ timestamp: string;
+}
+
+export interface LearnedRoutingPattern {
+ keywords: string[];
+ agents: string[];
+ source: 'learned';
+ support: number;
+ reliability: number;
+}
+
+export interface LearnedRoutingOptions {
+ maxKeywords?: number;
+ minAgentOutcomes?: number;
+ minKeywordSupport?: number;
+ minOutcomeQuality?: number;
+ minDiscriminativeShare?: number;
+}
+
+interface KeywordEvidence {
+ support: number;
+ qualityTotal: number;
+}
+
+const finiteUnit = (value: number): number =>
+ Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
+
+export function buildLearnedRoutingPatterns(
+ outcomes: LearnedRoutingOutcome[],
+ options: LearnedRoutingOptions = {},
+): Record<string, LearnedRoutingPattern> {
+ const maxKeywords = Math.max(1, Math.min(options.maxKeywords ?? 50, 100));
+ const minAgentOutcomes = Math.max(1, options.minAgentOutcomes ?? 2);
+ const minKeywordSupport = Math.max(1, options.minKeywordSupport ?? 2);
+ const minOutcomeQuality = finiteUnit(options.minOutcomeQuality ?? 0.65);
+ const minDiscriminativeShare = finiteUnit(options.minDiscriminativeShare ?? 0.6);
+
+ const accepted = outcomes.filter((outcome) =>
+ outcome.success
+ && typeof outcome.agent === 'string'
+ && outcome.agent.length > 0
+ && finiteUnit(outcome.quality) >= minOutcomeQuality
+ && Array.isArray(outcome.keywords)
+ && outcome.keywords.length > 0
+ );
+ const agents = [...new Set(accepted.map((outcome) => outcome.agent))].sort();
+ if (agents.length === 0) return {};
+
+ const agentOutcomes = new Map<string, LearnedRoutingOutcome[]>();
+ const evidence = new Map<string, Map<string, KeywordEvidence>>();
+ const globalSupport = new Map<string, number>();
+ const agentDocumentFrequency = new Map<string, number>();
+
+ for (const agent of agents) {
+ const rows = accepted.filter((outcome) => outcome.agent === agent);
+ agentOutcomes.set(agent, rows);
+ const perKeyword = new Map<string, KeywordEvidence>();
+ for (const row of rows) {
+ const unique = new Set(row.keywords.map((keyword) => keyword.trim().toLowerCase()).filter(Boolean));
+ for (const keyword of unique) {
+ const current = perKeyword.get(keyword) ?? { support: 0, qualityTotal: 0 };
+ current.support++;
+ current.qualityTotal += finiteUnit(row.quality);
+ perKeyword.set(keyword, current);
+ globalSupport.set(keyword, (globalSupport.get(keyword) ?? 0) + 1);
+ }
+ }
+ evidence.set(agent, perKeyword);
+ for (const keyword of perKeyword.keys()) {
+ agentDocumentFrequency.set(keyword, (agentDocumentFrequency.get(keyword) ?? 0) + 1);
+ }
+ }
+
+ const patterns: Record<string, LearnedRoutingPattern> = {};
+ for (const agent of agents) {
+ const rows = agentOutcomes.get(agent) ?? [];
+ if (rows.length < minAgentOutcomes) continue;
+ const ranked = [...(evidence.get(agent) ?? new Map()).entries()]
+ .filter(([, item]) => item.support >= minKeywordSupport)
+ .map(([keyword, item]) => {
+ const totalSupport = globalSupport.get(keyword) ?? item.support;
+ const discriminativeShare = item.support / Math.max(1, totalSupport);
+ const documentFrequency = agentDocumentFrequency.get(keyword) ?? 1;
+ const idf = Math.log(1 + agents.length / documentFrequency);
+ const withinAgentSupport = item.support / rows.length;
+ const meanQuality = item.qualityTotal / item.support;
+ return {
+ keyword,
+ discriminativeShare,
+ score: withinAgentSupport * meanQuality * idf * discriminativeShare,
+ };
+ })
+ .filter((item) => item.discriminativeShare >= minDiscriminativeShare)
+ .sort((a, b) => b.score - a.score || a.keyword.localeCompare(b.keyword))
+ .slice(0, maxKeywords);
+ if (ranked.length === 0) continue;
+ patterns[`learned-${agent}`] = {
+ keywords: ranked.map((item) => item.keyword),
+ agents: [agent],
+ source: 'learned',
+ support: rows.length,
+ reliability: rows.reduce((sum, row) => sum + finiteUnit(row.quality), 0) / rows.length,
+ };
+ }
+ return patterns;
+}
diff --git a/v3/@claude-flow/cli/src/services/pheromone-adaptive.ts b/v3/@claude-flow/cli/src/services/pheromone-adaptive.ts
new file mode 100644
index 0000000000..7806d44c7b
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/pheromone-adaptive.ts
@@ -0,0 +1,293 @@
+/**
+ * ADR-330 — Adaptive Pheromone Swarm Consensus.
+ *
+ * This is a scheduling eligibility layer, not an agent terminator. It learns a
+ * bounded EMA signal per agent, compares agents against role-local baselines,
+ * and may suspend them from future dispatch. Coordinators and other protected
+ * roles remain eligible, quorum is never crossed, pruning per round is capped,
+ * and exploration periodically reactivates a suspended agent.
+ */
+
+export const APSC_SCHEMA = 'ruflo.apsc-state/v1';
+
+export interface ApscConfig {
+ alpha: number;
+ beta: number;
+ gamma: number;
+ emaDecay: number;
+ pruningFactor: number;
+ reactivationThreshold: number;
+ minActiveAgents: number;
+ minSamples: number;
+ maxSuspendFraction: number;
+ explorationRate: number;
+ dryRun: boolean;
+ protectedRoles: string[];
+}
+
+export interface ApscAgentState {
+ agentId: string;
+ role: string;
+ status: 'active' | 'suspended';
+ samples: number;
+ rawScore: number;
+ normalizedScore: number;
+ emaScore: number;
+ lastUpdatedAt: string;
+ lastDecision?: 'keep' | 'would-suspend' | 'suspend' | 'reactivate' | 'explore';
+}
+
+export interface ApscState {
+ schemaVersion: typeof APSC_SCHEMA;
+ config: ApscConfig;
+ round: number;
+ threshold: number;
+ roleBaselines: Record<string, number>;
+ agents: Record<string, ApscAgentState>;
+}
+
+export interface ApscSignal {
+ agentId: string;
+ role: string;
+ taskSuccess: number;
+ normalizedLatency: number;
+ consensusAlignment: number;
+}
+
+export interface ApscDecision {
+ agentId: string;
+ score: number;
+ normalizedScore: number;
+ emaScore: number;
+ threshold: number;
+ action: 'keep' | 'would-suspend' | 'suspend' | 'reactivate' | 'explore';
+ applied: boolean;
+ reason: string;
+ activeAgents: number;
+ suspendedAgents: number;
+}
+
+export const DEFAULT_APSC_CONFIG: ApscConfig = {
+ alpha: 0.5,
+ beta: 0.2,
+ gamma: 0.3,
+ emaDecay: 0.85,
+ pruningFactor: 0.6,
+ reactivationThreshold: 0.75,
+ minActiveAgents: 3,
+ minSamples: 3,
+ maxSuspendFraction: 0.25,
+ explorationRate: 0.1,
+ dryRun: true,
+ protectedRoles: ['coordinator', 'queen', 'security-architect', 'security-auditor'],
+};
+
+const unit = (value: number, field: string): number => {
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
+ throw new Error(`${field} must be a finite number in [0,1]`);
+ }
+ return value;
+};
+
+export function normalizeApscConfig(input: Partial<ApscConfig> = {}): ApscConfig {
+ const alpha = unit(input.alpha ?? DEFAULT_APSC_CONFIG.alpha, 'alpha');
+ const beta = unit(input.beta ?? DEFAULT_APSC_CONFIG.beta, 'beta');
+ const gamma = unit(input.gamma ?? DEFAULT_APSC_CONFIG.gamma, 'gamma');
+ const weight = alpha + beta + gamma;
+ if (weight <= 0) throw new Error('at least one APSC score weight must be positive');
+ const minActiveAgents = input.minActiveAgents ?? DEFAULT_APSC_CONFIG.minActiveAgents;
+ const minSamples = input.minSamples ?? DEFAULT_APSC_CONFIG.minSamples;
+ if (!Number.isInteger(minActiveAgents) || minActiveAgents < 1 || minActiveAgents > 50) {
+ throw new Error('minActiveAgents must be an integer in [1,50]');
+ }
+ if (!Number.isInteger(minSamples) || minSamples < 1 || minSamples > 1000) {
+ throw new Error('minSamples must be an integer in [1,1000]');
+ }
+ const protectedRoles = [...new Set(
+ (input.protectedRoles ?? DEFAULT_APSC_CONFIG.protectedRoles)
+ .map((role) => role.trim().toLowerCase())
+ .filter(Boolean),
+ )].sort();
+ return {
+ alpha: alpha / weight,
+ beta: beta / weight,
+ gamma: gamma / weight,
+ emaDecay: unit(input.emaDecay ?? DEFAULT_APSC_CONFIG.emaDecay, 'emaDecay'),
+ pruningFactor: unit(input.pruningFactor ?? DEFAULT_APSC_CONFIG.pruningFactor, 'pruningFactor'),
+ reactivationThreshold: unit(
+ input.reactivationThreshold ?? DEFAULT_APSC_CONFIG.reactivationThreshold,
+ 'reactivationThreshold',
+ ),
+ minActiveAgents,
+ minSamples,
+ maxSuspendFraction: unit(
+ input.maxSuspendFraction ?? DEFAULT_APSC_CONFIG.maxSuspendFraction,
+ 'maxSuspendFraction',
+ ),
+ explorationRate: unit(input.explorationRate ?? DEFAULT_APSC_CONFIG.explorationRate, 'explorationRate'),
+ dryRun: input.dryRun ?? DEFAULT_APSC_CONFIG.dryRun,
+ protectedRoles,
+ };
+}
+
+export function createApscState(config: Partial<ApscConfig> = {}): ApscState {
+ return {
+ schemaVersion: APSC_SCHEMA,
+ config: normalizeApscConfig(config),
+ round: 0,
+ threshold: 0.5,
+ roleBaselines: {},
+ agents: {},
+ };
+}
+
+function counts(state: ApscState): { activeAgents: number; suspendedAgents: number } {
+ const values = Object.values(state.agents);
+ return {
+ activeAgents: values.filter((agent) => agent.status === 'active').length,
+ suspendedAgents: values.filter((agent) => agent.status === 'suspended').length,
+ };
+}
+
+function protectedRole(state: ApscState, role: string): boolean {
+ return state.config.protectedRoles.includes(role.toLowerCase());
+}
+
+export function recordApscSignal(
+ current: ApscState,
+ signal: ApscSignal,
+ now = Date.now(),
+): { state: ApscState; decision: ApscDecision } {
+ if (!/^[A-Za-z0-9._:-]{1,160}$/.test(signal.agentId)) throw new Error('invalid APSC agentId');
+ if (!/^[A-Za-z0-9._:-]{1,100}$/.test(signal.role)) throw new Error('invalid APSC role');
+ const config = normalizeApscConfig(current.config);
+ const state: ApscState = {
+ ...current,
+ config,
+ round: current.round + 1,
+ roleBaselines: { ...current.roleBaselines },
+ agents: Object.fromEntries(Object.entries(current.agents).map(([id, agent]) => [id, { ...agent }])),
+ };
+ const success = unit(signal.taskSuccess, 'taskSuccess');
+ const latency = unit(signal.normalizedLatency, 'normalizedLatency');
+ const alignment = unit(signal.consensusAlignment, 'consensusAlignment');
+ const rawScore = config.alpha * success + config.beta * (1 - latency) + config.gamma * alignment;
+
+ const role = signal.role.toLowerCase();
+ // Compare against peers in the same role, excluding the current agent.
+ // Letting an agent update its own baseline before normalization caused a
+ // persistently weak agent to redefine "normal" downward and reactivate
+ // without any recovery.
+ const rolePeers = Object.values(state.agents)
+ .filter((item) => item.agentId !== signal.agentId && item.role === role && item.samples > 0);
+ const peerMean = rolePeers.length
+ ? rolePeers.reduce((sum, item) => sum + item.rawScore, 0) / rolePeers.length
+ : undefined;
+ const priorRoleBaseline = peerMean ?? state.roleBaselines[role] ?? rawScore;
+ // A common absolute scale unfairly prunes coordinators/specialists whose
+ // observable task signal differs by role. Center each score on its role EMA.
+ const normalizedScore = Math.max(0, Math.min(1, 0.5 + rawScore - priorRoleBaseline));
+
+ const previous = state.agents[signal.agentId];
+ const agent: ApscAgentState = {
+ agentId: signal.agentId,
+ role,
+ status: previous?.status ?? 'active',
+ samples: (previous?.samples ?? 0) + 1,
+ rawScore,
+ normalizedScore,
+ emaScore: previous
+ ? config.emaDecay * previous.emaScore + (1 - config.emaDecay) * normalizedScore
+ : normalizedScore,
+ lastUpdatedAt: new Date(now).toISOString(),
+ lastDecision: 'keep',
+ };
+ state.agents[signal.agentId] = agent;
+ const allRoleAgents = Object.values(state.agents).filter((item) => item.role === role);
+ const observedRoleMean = allRoleAgents.reduce((sum, item) => sum + item.rawScore, 0) / allRoleAgents.length;
+ state.roleBaselines[role] = config.emaDecay * priorRoleBaseline + (1 - config.emaDecay) * observedRoleMean;
+
+ const mature = Object.values(state.agents).filter((item) => item.samples >= config.minSamples);
+ const observedMean = mature.length
+ ? mature.reduce((sum, item) => sum + item.emaScore, 0) / mature.length
+ : state.threshold;
+ state.threshold = config.emaDecay * state.threshold + (1 - config.emaDecay) * observedMean;
+
+ let action: ApscDecision['action'] = 'keep';
+ let applied = false;
+ let reason = agent.samples < config.minSamples
+ ? `warm-up ${agent.samples}/${config.minSamples}`
+ : 'within adaptive envelope';
+
+ if (agent.status === 'suspended' && agent.emaScore >= state.threshold * config.reactivationThreshold) {
+ action = 'reactivate';
+ reason = 'score recovered above reactivation threshold';
+ if (!config.dryRun) {
+ agent.status = 'active';
+ applied = true;
+ }
+ } else if (
+ agent.status === 'active'
+ && agent.samples >= config.minSamples
+ && !protectedRole(state, agent.role)
+ && agent.emaScore < state.threshold * config.pruningFactor
+ ) {
+ const before = counts(state);
+ const maxThisRound = Math.floor(before.activeAgents * config.maxSuspendFraction);
+ const quorumCapacity = Math.max(0, before.activeAgents - config.minActiveAgents);
+ if (maxThisRound < 1 || quorumCapacity < 1) {
+ reason = 'safety floor prevents suspension';
+ } else {
+ action = config.dryRun ? 'would-suspend' : 'suspend';
+ reason = 'score below adaptive pruning threshold';
+ if (!config.dryRun) {
+ agent.status = 'suspended';
+ applied = true;
+ }
+ }
+ } else if (protectedRole(state, agent.role)) {
+ reason = 'protected role remains eligible';
+ }
+
+ // Deterministic exploration: at a bounded cadence, reactivate the stalest
+ // suspended agent so a transient failure cannot permanently exclude it.
+ if (!config.dryRun && config.explorationRate > 0) {
+ const cadence = Math.max(1, Math.round(1 / config.explorationRate));
+ if (state.round % cadence === 0) {
+ const explorer = Object.values(state.agents)
+ .filter((item) => item.status === 'suspended')
+ .sort((a, b) => a.lastUpdatedAt.localeCompare(b.lastUpdatedAt) || a.agentId.localeCompare(b.agentId))[0];
+ if (explorer) {
+ explorer.status = 'active';
+ explorer.lastDecision = 'explore';
+ if (explorer.agentId === agent.agentId) {
+ action = 'explore';
+ applied = true;
+ reason = 'bounded exploration reactivation';
+ }
+ }
+ }
+ }
+
+ agent.lastDecision = action;
+ const after = counts(state);
+ return {
+ state,
+ decision: {
+ agentId: agent.agentId,
+ score: rawScore,
+ normalizedScore,
+ emaScore: agent.emaScore,
+ threshold: state.threshold,
+ action,
+ applied,
+ reason,
+ ...after,
+ },
+ };
+}
+
+export function isApscAgentEligible(state: ApscState | undefined, agentId: string): boolean {
+ if (!state || state.config.dryRun) return true;
+ return state.agents[agentId]?.status !== 'suspended';
+}
diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.ts
index 8cf5725e74..8e257f6281 100644
--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts
+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts
@@ -183,7 +183,10 @@ const NO_DISTILL_ENV = 'RUFLO_DAEMON_NO_DISTILL';
// half a day; set RUFLO_DAEMON_TTL_SECS=0 (or `--ttl 0`) to opt out. Idle
// shutdown is opt-in (0 = disabled) since a legitimately quiet daemon is not a leak.
const DEFAULT_DAEMON_TTL_MS = 12 * 60 * 60 * 1000;
-const DEFAULT_DAEMON_IDLE_SHUTDOWN_MS = 0;
+// #2834 — an auto-started daemon must not remain alive for the full 12h TTL
+// after its workspace goes idle. Explicit 0 via config/env still disables the
+// idle cap for operators who intentionally want a resident daemon.
+const DEFAULT_DAEMON_IDLE_SHUTDOWN_MS = 30 * 60 * 1000;
/**
* Read a non-negative seconds value from an env var and return it as ms.
diff --git a/v3/@claude-flow/shared/src/core/config/loader.ts b/v3/@claude-flow/shared/src/core/config/loader.ts
index 3d6427db0a..6619c3bec9 100644
--- a/v3/@claude-flow/shared/src/core/config/loader.ts
+++ b/v3/@claude-flow/shared/src/core/config/loader.ts
@@ -127,7 +127,7 @@ function loadEnvConfig(): Partial<SystemConfig> {
const defaultSwarm = defaultSystemConfig.swarm ?? { topology: 'hierarchical-mesh' as const, maxAgents: 20 };
if (process.env.CLAUDE_FLOW_SWARM_TOPOLOGY) {
const topology = process.env.CLAUDE_FLOW_SWARM_TOPOLOGY as NonNullable<SystemConfig['swarm']>['topology'];
- if (['hierarchical', 'mesh', 'ring', 'star', 'adaptive', 'hierarchical-mesh'].includes(topology)) {
+ if (['hierarchical', 'mesh', 'ring', 'star', 'adaptive', 'pheromone-adaptive', 'hierarchical-mesh'].includes(topology)) {
config.swarm = {
...defaultSwarm,
topology,
diff --git a/v3/@claude-flow/shared/src/core/config/schema.ts b/v3/@claude-flow/shared/src/core/config/schema.ts
index 6257eb40f2..1c281f945d 100644
--- a/v3/@claude-flow/shared/src/core/config/schema.ts
+++ b/v3/@claude-flow/shared/src/core/config/schema.ts
@@ -53,7 +53,7 @@ export const TaskConfigSchema = z.object({
* Swarm configuration schema
*/
export const SwarmConfigSchema = z.object({
- topology: z.enum(['hierarchical', 'mesh', 'ring', 'star', 'adaptive', 'hierarchical-mesh']),
+ topology: z.enum(['hierarchical', 'mesh', 'ring', 'star', 'adaptive', 'pheromone-adaptive', 'hierarchical-mesh']),
maxAgents: z.number().int().positive().default(20),
autoScale: z.object({
enabled: z.boolean().default(false),
diff --git a/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts b/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts
index 16a6cf0852..dafc01968c 100644
--- a/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts
+++ b/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts
@@ -16,6 +16,7 @@ export type SwarmTopology =
| 'ring'
| 'star'
| 'adaptive'
+ | 'pheromone-adaptive'
| 'hierarchical-mesh';
/**
diff --git a/v3/@claude-flow/shared/src/types/swarm.types.ts b/v3/@claude-flow/shared/src/types/swarm.types.ts
index 40c4502f13..8832b17017 100644
--- a/v3/@claude-flow/shared/src/types/swarm.types.ts
+++ b/v3/@claude-flow/shared/src/types/swarm.types.ts
@@ -244,6 +244,24 @@ export const TopologyPresets: Record<SwarmTopology, Partial<ISwarmConfig>> = {
retryPolicy: { maxRetries: 5, backoffMs: 500 }
}
},
+ 'pheromone-adaptive': {
+ topology: 'pheromone-adaptive',
+ autoScale: {
+ enabled: true,
+ minAgents: 3,
+ maxAgents: 20,
+ scaleUpThreshold: 0.8,
+ scaleDownThreshold: 0.3
+ },
+ coordination: {
+ consensusRequired: true,
+ timeoutMs: 10000,
+ retryPolicy: { maxRetries: 5, backoffMs: 500 }
+ },
+ metadata: {
+ apsc: { dryRun: true, minActiveAgents: 3, minSamples: 3 }
+ }
+ },
'hierarchical-mesh': {
topology: 'hierarchical-mesh',
coordination: {
diff --git a/v3/docs/adr/ADR-330-adaptive-pheromone-swarm-consensus.md b/v3/docs/adr/ADR-330-adaptive-pheromone-swarm-consensus.md
new file mode 100644
index 0000000000..c3e26a91c5
--- /dev/null
+++ b/v3/docs/adr/ADR-330-adaptive-pheromone-swarm-consensus.md
@@ -0,0 +1,165 @@
+# ADR-330: Adaptive Pheromone Swarm Consensus
+
+**Status:** Accepted and implemented
+**Date:** 2026-07-29
+**Issue:** #2832
+**Supersedes:** the research-only contract in draft PR #2833
+**Related:** ADR-320, ADR-322, ADR-324, ADR-329
+
+## Decision
+
+Ruflo adds the opt-in `pheromone-adaptive` swarm topology. It learns a bounded
+fitness signal after task outcomes and controls whether an agent is eligible
+for future Ruflo-managed dispatch. It does not terminate agents or expand any
+agent capability.
+
+The public initialization contract is:
+
+```bash
+ruflo swarm init \
+ --topology pheromone-adaptive \
+ --max-agents 8
+```
+
+The topology starts in dry-run calibration mode. Applying suspensions requires
+the explicit `--apsc-live` flag:
+
+```bash
+ruflo swarm init \
+ --topology pheromone-adaptive \
+ --max-agents 8 \
+ --apsc-live
+```
+
+This corrects the draft proposal's `--maxAgents` example. Kebab-case is the
+public CLI contract; camelCase remains the internal parsed/MCP representation.
+
+## Signal
+
+Each observation is normalized before it reaches the coordinator:
+
+```text
+raw = α × taskSuccess
+ + β × (1 - normalizedLatency)
+ + γ × consensusAlignment
+```
+
+Defaults are `α=0.5`, `β=0.2`, and `γ=0.3`. Inputs and weights are finite and
+bounded to `[0,1]`; weights are normalized to sum to one.
+
+The raw terms are observations, not interchangeable physical measurements.
+Ruflo therefore does not compare raw scores directly across roles. It centers
+each observation on the role's EMA baseline:
+
+```text
+roleNormalized = clamp(0.5 + raw - roleBaseline, 0, 1)
+agentEMA = decay × priorEMA + (1-decay) × roleNormalized
+```
+
+This prevents a coordinator or specialist with fewer discrete completions from
+being compared as though it were a task-producing coder.
+
+## Safety invariants
+
+The optimizer cannot trade away these invariants:
+
+1. `coordinator`, `queen`, `security-architect`, and `security-auditor` are
+ protected by default.
+2. An agent receives at least `minSamples=3` observations before pruning.
+3. At least `minActiveAgents=3` remain eligible.
+4. At most `maxSuspendFraction=0.25` of active agents may be suspended in one
+ observation round.
+5. Suspension affects Ruflo scheduling eligibility only. It does not kill the
+ process, discard context, revoke memory, or mutate permissions.
+6. Dry-run is the default. Live mode is an explicit operator decision.
+7. A suspended agent is reactivated after recovery or by deterministic bounded
+ exploration.
+8. Invalid or missing state fails open for dispatch: existing topologies and
+ previous installations continue to execute.
+9. Cross-process outcome updates use a workspace-scoped lock and atomic state
+ replacement; concurrent hooks cannot silently overwrite one another.
+
+## Runtime integration
+
+The implementation lives on the actual Ruflo paths:
+
+- `cli/src/services/pheromone-adaptive.ts`: pure scoring and safety state
+- `cli/src/mcp-tools/swarm-tools.ts`: persistence and MCP operations
+- `cli/src/mcp-tools/hooks-tools.ts`: automatic post-task signal
+- `cli/src/mcp-tools/agent-tools.ts`: scheduling eligibility gate
+- `cli/src/commands/swarm.ts`: topology and inspection CLI
+- `shared/src/core/interfaces/coordinator.interface.ts`: topology contract
+
+The earlier draft named paths that do not exist in the repository. The
+implemented surface attaches to the persistent swarm store used by `swarm_init`
+and the tracked-agent execution path used by `agent_execute`.
+
+MCP operations:
+
+- `swarm_pheromone_update`
+- `swarm_pheromone_status`
+
+Human inspection:
+
+```bash
+ruflo swarm pheromone
+ruflo agent metrics --format json
+```
+
+Manual observation:
+
+```bash
+ruflo swarm pheromone \
+ --agent-id coder-1 \
+ --role coder \
+ --task-success 1 \
+ --normalized-latency 0.2 \
+ --consensus-alignment 0.9
+```
+
+`hooks_post-task` emits the same observation automatically when a
+`pheromone-adaptive` swarm is active.
+
+## Evaluation and claims
+
+The Dream-cycle report cited a 50% agent reduction and 11.6% fitness increase
+from a different workload. Those numbers are upstream hypotheses, not Ruflo
+results.
+
+Ruflo's benchmark reports:
+
+- update latency distribution;
+- active-agent reduction on a declared synthetic workload;
+- quorum preservation;
+- protected-role preservation;
+- mean admitted-agent score before and after;
+- exact configuration and seed.
+
+Release text may claim only measured Ruflo results produced by that benchmark.
+
+## Backward compatibility
+
+- All existing topology strings retain their behavior.
+- Default topology remains `hierarchical`.
+- `adaptive` is unchanged.
+- Old swarm-state documents without `apscState` remain readable.
+- Non-APSC `agent_execute` calls have no additional denial path.
+- Dry-run APSC never denies dispatch.
+
+## Acceptance tests
+
+1. The new topology initializes and persists through the existing swarm store.
+2. APSC dry-run records decisions without changing eligibility.
+3. Live APSC never crosses its active-agent floor.
+4. Protected roles are never suspended.
+5. A recovered agent can be reactivated.
+6. Invalid score/config values are rejected.
+7. `hooks_post-task` feeds active APSC state.
+8. `agent_execute` refuses an agent only when live APSC marks that exact ID
+ suspended.
+9. Existing topology schemas and presets still parse.
+10. Benchmark output distinguishes measured results from upstream claims.
+11. Twenty concurrent outcome writers produce twenty persisted rounds and no
+ residual lock file.
+12. `agent metrics` exposes the per-agent EMA pheromone score, role, sample
+ count, and current scheduling eligibility.
diff --git a/v3/docs/adr/ADR-331-project-local-flywheel-anchors.md b/v3/docs/adr/ADR-331-project-local-flywheel-anchors.md
new file mode 100644
index 0000000000..79354b4e8e
--- /dev/null
+++ b/v3/docs/adr/ADR-331-project-local-flywheel-anchors.md
@@ -0,0 +1,59 @@
+# ADR-331: Project-Local Flywheel Evaluation Anchors
+
+**Status:** Accepted and implemented
+**Date:** 2026-07-29
+**Issue:** #2840
+**Related:** ADR-081, ADR-176, ADR-322
+
+## Decision
+
+A downstream flywheel must use a human-labelled benchmark for the project it is
+optimizing. The benchmark is canonicalized, hash-pinned, and identified in
+every new evaluation receipt as `anchorRef`.
+
+Ruflo's built-in development-history benchmark is selected automatically only
+when the target repository identifies itself as Ruflo/Claude Flow. A foreign
+repository without a project anchor fails closed with a clear reason. Operators
+may explicitly retain the historical behavior with
+`RUFLO_FLYWHEEL_ALLOW_BUILTIN_ANCHOR=1`, but it is never silently selected.
+
+## Manifest
+
+Create `.claude/eval/flywheel-anchor.manifest.json`:
+
+```json
+{
+ "schemaVersion": "ruflo.flywheel-anchor-manifest/v1",
+ "path": "my-project-anchor.json",
+ "sha256": "sha256:<canonical-task-hash>"
+}
+```
+
+The anchor file contains at least four tasks:
+
+```json
+{
+ "schemaVersion": "ruflo.flywheel-anchor/v1",
+ "version": "my-project-v1",
+ "tasks": [
+ {
+ "id": "auth-01",
+ "q": "where is request authentication enforced",
+ "labels": ["authentication middleware", "request guard"]
+ }
+ ]
+}
+```
+
+Both files and resolved symlinks must remain inside the project root. Changing
+the tasks without updating the pinned hash is rejected.
+
+The CLI and MCP surfaces also accept an explicit `anchorPath` plus
+`anchorHash`; neither may be supplied alone.
+
+## Receipt compatibility
+
+`anchorRef` is optional when decoding historical `ruflo.flywheel-receipt/v1`
+receipts, preserving verification of already-issued signatures. New
+evaluations include it, so receipts from different project benchmarks cannot
+be treated as one comparable lineage without an explicit migration.
diff --git a/v3/docs/adr/README.md b/v3/docs/adr/README.md
index 31ecfd1ec5..3043b8d8b5 100644
--- a/v3/docs/adr/README.md
+++ b/v3/docs/adr/README.md
@@ -47,6 +47,8 @@ All ADRs are located in [`/v3/implementation/adrs/`](../../implementation/adrs/)
| [ADR-327](ADR-327-federated-concurrent-development-harness.md) | Federated Concurrent Development Harness | Proposed |
| [ADR-328](ADR-328-cognitum-assisted-agent-learning.md) | Cognitum-Assisted Agent Learning Capability Plane | Proposed |
| [ADR-329](ADR-329-ruflo-capability-brain-mcp-guidance.md) | Ruflo Capability Brain for MCP Guidance | Accepted |
+| [ADR-330](ADR-330-adaptive-pheromone-swarm-consensus.md) | Adaptive Pheromone Swarm Consensus | Accepted |
+| [ADR-331](ADR-331-project-local-flywheel-anchors.md) | Project-Local Flywheel Evaluation Anchors | Accepted |
## Summary Documents