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

checkpoint: File edit:

rUv453c5c3774c0
diff --git a/v3/@claude-flow/shared/package.json b/v3/@claude-flow/shared/package.json
index 5fef203091..0f67ba37b8 100644
--- a/v3/@claude-flow/shared/package.json
+++ b/v3/@claude-flow/shared/package.json
@@ -9,7 +9,8 @@
".": "./src/index.ts",
"./types": "./src/types/index.ts",
"./core": "./src/core/index.ts",
- "./events": "./src/events/index.ts"
+ "./events": "./src/events/index.ts",
+ "./hooks": "./src/hooks/index.ts"
},
"scripts": {
"test": "vitest run",
diff --git a/v3/@claude-flow/shared/src/hooks/INTEGRATION.md b/v3/@claude-flow/shared/src/hooks/INTEGRATION.md
new file mode 100644
index 0000000000..ceb06988c2
--- /dev/null
+++ b/v3/@claude-flow/shared/src/hooks/INTEGRATION.md
@@ -0,0 +1,658 @@
+# V3 Hooks System - Integration Guide
+
+This guide shows how to integrate the hooks system with V3's event bus, event store, and other core components.
+
+## Architecture Overview
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Application Layer β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ β”‚
+β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ Tool Manager │───▢│ Hook Executor│───▢│ Event Bus β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β”‚ β”‚ β”‚ β”‚
+β”‚ β”‚ β”‚ β–Ό β”‚
+β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ β”‚ β”‚ β”‚ Event Store β”‚ β”‚
+β”‚ β”‚ β”‚ β”‚ (ADR-007) β”‚ β”‚
+β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β”‚ β”‚ β”‚
+β”‚ β”‚ β–Ό β”‚
+β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
+β”‚ └───────────▢│Hook Registry β”‚ β”‚
+β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
+β”‚ β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## Integration with Event Bus
+
+### Step 1: Initialize Core Components
+
+```typescript
+import { createEventBus } from '@claude-flow/shared/core';
+import { createHookRegistry, createHookExecutor } from '@claude-flow/shared/hooks';
+import { EventStore } from '@claude-flow/shared/events';
+
+// Create core components
+const eventBus = createEventBus();
+const hookRegistry = createHookRegistry();
+const hookExecutor = createHookExecutor(hookRegistry, eventBus);
+
+// Optional: Event store for audit trail (ADR-007)
+const eventStore = new EventStore({
+ databasePath: './data/events.db',
+ verbose: true,
+});
+
+await eventStore.initialize();
+```
+
+### Step 2: Subscribe to Hook Coordination Events
+
+```typescript
+// Listen for hook execution start
+eventBus.on('hooks:pre-execute', async (event) => {
+ console.log(`🎯 Executing ${event.payload.hookCount} hooks for ${event.payload.event}`);
+
+ // Store event in event store (ADR-007)
+ await eventStore.append({
+ id: `evt-${Date.now()}`,
+ type: 'hooks:pre-execute',
+ aggregateId: 'hook-system',
+ aggregateType: 'system',
+ version: 1,
+ timestamp: Date.now(),
+ source: 'hook-executor',
+ payload: event.payload,
+ });
+});
+
+// Listen for hook execution completion
+eventBus.on('hooks:post-execute', async (event) => {
+ const { success, totalExecutionTime, hooksExecuted, hooksFailed } = event.payload;
+
+ console.log(`βœ… Hooks completed: ${hooksExecuted} executed, ${hooksFailed} failed (${totalExecutionTime}ms)`);
+
+ // Store completion event
+ await eventStore.append({
+ id: `evt-${Date.now()}`,
+ type: 'hooks:post-execute',
+ aggregateId: 'hook-system',
+ aggregateType: 'system',
+ version: 1,
+ timestamp: Date.now(),
+ source: 'hook-executor',
+ payload: event.payload,
+ });
+});
+
+// Listen for hook errors
+eventBus.on('hooks:error', async (event) => {
+ console.error(`❌ Hook error:`, event.payload.error);
+
+ // Store error event
+ await eventStore.append({
+ id: `evt-${Date.now()}`,
+ type: 'hooks:error',
+ aggregateId: 'hook-system',
+ aggregateType: 'system',
+ version: 1,
+ timestamp: Date.now(),
+ source: 'hook-executor',
+ payload: {
+ hookId: event.payload.hookId,
+ error: event.payload.error.message,
+ stack: event.payload.error.stack,
+ },
+ });
+});
+```
+
+## Integration with Tool Execution
+
+### Example: File Read with Hooks
+
+```typescript
+import { HookEvent, HookContext } from '@claude-flow/shared/hooks';
+import { readFile } from 'fs/promises';
+
+async function readFileWithHooks(filePath: string): Promise<string> {
+ // Create pre-read context
+ const preContext: HookContext = {
+ event: HookEvent.PreRead,
+ timestamp: new Date(),
+ file: {
+ path: filePath,
+ operation: 'read',
+ },
+ };
+
+ // Execute pre-read hooks
+ const preResult = await hookExecutor.execute(HookEvent.PreRead, preContext);
+
+ if (preResult.aborted) {
+ throw new Error('File read aborted by hooks');
+ }
+
+ // Perform actual read
+ const startTime = Date.now();
+ let content: string;
+ let success = true;
+ let error: Error | undefined;
+
+ try {
+ content = await readFile(filePath, 'utf-8');
+ } catch (err) {
+ success = false;
+ error = err instanceof Error ? err : new Error(String(err));
+ throw error;
+ } finally {
+ // Execute post-read hooks
+ const postContext: HookContext = {
+ event: HookEvent.PostRead,
+ timestamp: new Date(),
+ file: {
+ path: filePath,
+ operation: 'read',
+ size: content?.length || 0,
+ },
+ metadata: {
+ ...preResult.finalContext?.metadata,
+ success,
+ executionTime: Date.now() - startTime,
+ },
+ error: error ? {
+ error,
+ context: 'file-read',
+ severity: 'error',
+ recoverable: false,
+ } : undefined,
+ };
+
+ await hookExecutor.execute(HookEvent.PostRead, postContext);
+ }
+
+ return content;
+}
+```
+
+### Example: Command Execution with Hooks
+
+```typescript
+import { exec } from 'child_process';
+import { promisify } from 'util';
+import { HookEvent, HookContext } from '@claude-flow/shared/hooks';
+
+const execAsync = promisify(exec);
+
+async function executeCommandWithHooks(
+ command: string,
+ options: { cwd?: string; timeout?: number } = {}
+): Promise<{ stdout: string; stderr: string }> {
+ // Pre-command hooks
+ const preContext: HookContext = {
+ event: HookEvent.PreCommand,
+ timestamp: new Date(),
+ command: {
+ command,
+ cwd: options.cwd,
+ timeout: options.timeout,
+ isDestructive: /rm|del|format|dd/.test(command),
+ },
+ };
+
+ const preResult = await hookExecutor.execute(HookEvent.PreCommand, preContext);
+
+ if (preResult.aborted) {
+ throw new Error(`Command execution blocked by security hooks: ${command}`);
+ }
+
+ // Execute command
+ const startTime = Date.now();
+ let result: { stdout: string; stderr: string };
+ let success = true;
+ let error: Error | undefined;
+
+ try {
+ result = await execAsync(command, options);
+ } catch (err) {
+ success = false;
+ error = err instanceof Error ? err : new Error(String(err));
+ throw error;
+ } finally {
+ // Post-command hooks
+ const postContext: HookContext = {
+ event: HookEvent.PostCommand,
+ timestamp: new Date(),
+ command: {
+ command,
+ cwd: options.cwd,
+ timeout: options.timeout,
+ },
+ metadata: {
+ ...preResult.finalContext?.metadata,
+ success,
+ executionTime: Date.now() - startTime,
+ },
+ error: error ? {
+ error,
+ context: 'command-execution',
+ severity: 'error',
+ recoverable: false,
+ } : undefined,
+ };
+
+ await hookExecutor.execute(HookEvent.PostCommand, postContext);
+ }
+
+ return result;
+}
+```
+
+## Integration with Agent Lifecycle
+
+```typescript
+import { HookEvent, HookContext } from '@claude-flow/shared/hooks';
+
+class AgentManager {
+ async spawnAgent(type: string, config: Record<string, unknown>) {
+ const agentId = `agent-${Date.now()}`;
+
+ // Pre-spawn hooks
+ const preContext: HookContext = {
+ event: HookEvent.PreAgentSpawn,
+ timestamp: new Date(),
+ agent: {
+ id: agentId,
+ type,
+ config,
+ },
+ };
+
+ const preResult = await hookExecutor.execute(HookEvent.PreAgentSpawn, preContext);
+
+ if (preResult.aborted) {
+ throw new Error(`Agent spawn aborted: ${type}`);
+ }
+
+ // Spawn agent
+ const agent = await this.createAgent(agentId, type, config);
+
+ // Post-spawn hooks
+ const postContext: HookContext = {
+ event: HookEvent.PostAgentSpawn,
+ timestamp: new Date(),
+ agent: {
+ id: agentId,
+ type,
+ config,
+ },
+ metadata: {
+ ...preResult.finalContext?.metadata,
+ success: true,
+ },
+ };
+
+ await hookExecutor.execute(HookEvent.PostAgentSpawn, postContext);
+
+ return agent;
+ }
+
+ async terminateAgent(agentId: string) {
+ // Pre-terminate hooks
+ const preContext: HookContext = {
+ event: HookEvent.PreAgentTerminate,
+ timestamp: new Date(),
+ agent: { id: agentId, type: 'unknown' },
+ };
+
+ await hookExecutor.execute(HookEvent.PreAgentTerminate, preContext);
+
+ // Terminate agent
+ await this.destroyAgent(agentId);
+
+ // Post-terminate hooks
+ const postContext: HookContext = {
+ event: HookEvent.PostAgentTerminate,
+ timestamp: new Date(),
+ agent: { id: agentId, type: 'unknown' },
+ metadata: { success: true },
+ };
+
+ await hookExecutor.execute(HookEvent.PostAgentTerminate, postContext);
+ }
+
+ private async createAgent(id: string, type: string, config: Record<string, unknown>) {
+ // Implementation
+ return { id, type, config };
+ }
+
+ private async destroyAgent(id: string) {
+ // Implementation
+ }
+}
+```
+
+## Integration with Session Management
+
+```typescript
+import { HookEvent, HookContext } from '@claude-flow/shared/hooks';
+
+class SessionManager {
+ async startSession(userId?: string) {
+ const sessionId = `session-${Date.now()}`;
+
+ const context: HookContext = {
+ event: HookEvent.SessionStart,
+ timestamp: new Date(),
+ session: {
+ id: sessionId,
+ startTime: new Date(),
+ userId,
+ },
+ };
+
+ const result = await hookExecutor.execute(HookEvent.SessionStart, context);
+
+ // Emit system event
+ eventBus.emit('session:created', {
+ sessionId,
+ userId,
+ timestamp: Date.now(),
+ });
+
+ return { sessionId, context: result.finalContext };
+ }
+
+ async endSession(sessionId: string) {
+ const context: HookContext = {
+ event: HookEvent.SessionEnd,
+ timestamp: new Date(),
+ session: {
+ id: sessionId,
+ startTime: new Date(), // Would be loaded from state
+ endTime: new Date(),
+ },
+ };
+
+ await hookExecutor.execute(HookEvent.SessionEnd, context);
+
+ // Emit system event
+ eventBus.emit('session:terminated', {
+ sessionId,
+ timestamp: Date.now(),
+ });
+ }
+}
+```
+
+## Plugin System Integration
+
+Hooks can be registered via plugins (ADR-004):
+
+```typescript
+// v3/plugins/security-hooks/index.ts
+import { Plugin } from '@claude-flow/shared';
+import { HookEvent, HookPriority } from '@claude-flow/shared/hooks';
+
+export default {
+ name: 'security-hooks',
+ version: '1.0.0',
+
+ async initialize({ hookRegistry }) {
+ // Register security hooks
+ hookRegistry.register(
+ HookEvent.PreCommand,
+ async (context) => {
+ // Security validation
+ return { success: true };
+ },
+ HookPriority.Critical,
+ { name: 'Security: Command Validation' }
+ );
+
+ hookRegistry.register(
+ HookEvent.PreWrite,
+ async (context) => {
+ // File write validation
+ return { success: true };
+ },
+ HookPriority.Critical,
+ { name: 'Security: File Write Validation' }
+ );
+ },
+
+ async shutdown({ hookRegistry }) {
+ // Cleanup hooks
+ hookRegistry.unregisterAll();
+ },
+} as Plugin;
+```
+
+## MCP Integration
+
+Expose hooks via MCP tools:
+
+```typescript
+// v3/@claude-flow/shared/src/mcp/tools/hooks.ts
+import { Tool } from '@modelcontextprotocol/sdk/types.js';
+
+export const registerHookTool: Tool = {
+ name: 'hooks_register',
+ description: 'Register a new hook for event interception',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ event: {
+ type: 'string',
+ enum: Object.values(HookEvent),
+ description: 'Hook event type',
+ },
+ priority: {
+ type: 'string',
+ enum: ['critical', 'high', 'normal', 'low', 'lowest'],
+ description: 'Hook priority',
+ },
+ name: {
+ type: 'string',
+ description: 'Hook name',
+ },
+ },
+ required: ['event'],
+ },
+};
+
+export const listHooksTool: Tool = {
+ name: 'hooks_list',
+ description: 'List all registered hooks',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ event: {
+ type: 'string',
+ enum: Object.values(HookEvent),
+ description: 'Filter by event type (optional)',
+ },
+ },
+ },
+};
+
+export const getHookStatsTool: Tool = {
+ name: 'hooks_stats',
+ description: 'Get hook execution statistics',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+};
+```
+
+## Event Sourcing Integration (ADR-007)
+
+Store all hook executions for audit trail:
+
+```typescript
+import { EventStore } from '@claude-flow/shared/events';
+
+// Create event store
+const eventStore = new EventStore({
+ databasePath: './data/hook-events.db',
+});
+
+await eventStore.initialize();
+
+// Subscribe to all hook events
+eventBus.on('hooks:pre-execute', async (event) => {
+ await eventStore.append({
+ id: `evt-${Date.now()}`,
+ type: 'hooks:pre-execute',
+ aggregateId: 'hook-system',
+ aggregateType: 'system',
+ version: 1,
+ timestamp: Date.now(),
+ source: 'hook-executor',
+ payload: event.payload,
+ });
+});
+
+// Query hook history
+const hookEvents = await eventStore.getEventsByType('hooks:pre-execute');
+console.log(`Total hook executions: ${hookEvents.length}`);
+
+// Replay hook events
+for await (const event of eventStore.replay()) {
+ if (event.type.startsWith('hooks:')) {
+ console.log(`Replaying hook event: ${event.type} at ${event.timestamp}`);
+ }
+}
+```
+
+## Complete Example: Tool Manager with Hooks
+
+```typescript
+import {
+ createEventBus,
+ createHookRegistry,
+ createHookExecutor,
+ HookEvent,
+ HookPriority,
+ HookContext,
+} from '@claude-flow/shared';
+
+class V3ToolManager {
+ private eventBus = createEventBus();
+ private hookRegistry = createHookRegistry();
+ private hookExecutor = createHookExecutor(this.hookRegistry, this.eventBus);
+
+ constructor() {
+ this.setupHooks();
+ }
+
+ private setupHooks() {
+ // Security hooks
+ this.hookRegistry.register(
+ HookEvent.PreToolUse,
+ async (context) => {
+ console.log(`Security check: ${context.tool?.name}`);
+ return { success: true };
+ },
+ HookPriority.Critical
+ );
+
+ // Performance tracking
+ this.hookRegistry.register(
+ HookEvent.PreToolUse,
+ async (context) => {
+ return {
+ success: true,
+ data: {
+ metadata: {
+ ...context.metadata,
+ startTime: Date.now(),
+ },
+ },
+ };
+ },
+ HookPriority.High
+ );
+
+ this.hookRegistry.register(
+ HookEvent.PostToolUse,
+ async (context) => {
+ const startTime = context.metadata?.startTime as number;
+ if (startTime) {
+ const duration = Date.now() - startTime;
+ console.log(`Tool ${context.tool?.name} took ${duration}ms`);
+ }
+ return { success: true };
+ },
+ HookPriority.Normal
+ );
+ }
+
+ async executeTool(name: string, parameters: Record<string, unknown>) {
+ const context: HookContext = {
+ event: HookEvent.PreToolUse,
+ timestamp: new Date(),
+ tool: { name, parameters },
+ };
+
+ // Execute pre-hooks
+ const preResult = await this.hookExecutor.execute(HookEvent.PreToolUse, context);
+
+ if (preResult.aborted) {
+ throw new Error(`Tool execution blocked: ${name}`);
+ }
+
+ // Execute tool (simulated)
+ const toolResult = await this.performToolExecution(name, parameters);
+
+ // Execute post-hooks
+ await this.hookExecutor.execute(HookEvent.PostToolUse, {
+ ...context,
+ event: HookEvent.PostToolUse,
+ metadata: {
+ ...preResult.finalContext?.metadata,
+ success: true,
+ },
+ });
+
+ return toolResult;
+ }
+
+ private async performToolExecution(name: string, parameters: Record<string, unknown>) {
+ // Tool execution implementation
+ return { result: 'success' };
+ }
+
+ getStats() {
+ return this.hookRegistry.getStats();
+ }
+}
+
+// Usage
+const toolManager = new V3ToolManager();
+await toolManager.executeTool('Read', { path: 'file.ts' });
+const stats = toolManager.getStats();
+console.log('Hook statistics:', stats);
+```
+
+## Best Practices
+
+1. **Always use event bus**: Connect hookExecutor to eventBus for coordination
+2. **Store critical events**: Use EventStore for audit trail (ADR-007)
+3. **Handle errors gracefully**: Set `continueOnError` based on severity
+4. **Use appropriate priorities**: Security hooks = Critical, monitoring = Low
+5. **Clean up resources**: Unregister hooks in plugin shutdown
+6. **Monitor performance**: Use hook statistics to identify bottlenecks
+7. **Test hooks thoroughly**: Use the provided test suite as a template
+
+## Next Steps
+
+- See `hooks.test.ts` for comprehensive examples
+- See `example-usage.ts` for practical use cases
+- See `README.md` for API documentation
+- Implement hooks in your domain modules (security, memory, swarm)
diff --git a/v3/implementation/swarm-plans/hooks/STATUSLINE-DAEMON.md b/v3/implementation/swarm-plans/hooks/STATUSLINE-DAEMON.md
new file mode 100644
index 0000000000..87643a6613
--- /dev/null
+++ b/v3/implementation/swarm-plans/hooks/STATUSLINE-DAEMON.md
@@ -0,0 +1,271 @@
+# Claude Flow V3 Statusline Daemon System
+
+## Overview
+
+Real-time statusline updates powered by SQLite-backed daemon processes that monitor V3 implementation progress, swarm activity, and security status.
+
+## Architecture
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Claude Code Session β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ SessionStart Hook β”‚
+β”‚ └─> daemon-manager.sh start β”‚
+β”‚ β”œβ”€> swarm-monitor.sh (process detection, 3s) β”‚
+β”‚ └─> metrics-db.mjs daemon (SQLite sync, 30s) β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ statusline.sh (on-demand) β”‚
+β”‚ └─> Reads from: β”‚
+β”‚ β”œβ”€ .claude-flow/metrics.db (primary, SQLite) β”‚
+β”‚ └─ .claude-flow/metrics/*.json (exported, compat) β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ SessionEnd Hook β”‚
+β”‚ └─> daemon-manager.sh stop β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## Components
+
+### 1. Daemon Manager (`daemon-manager.sh`)
+
+Central control for all background processes.
+
+```bash
+# Start all daemons
+.claude/helpers/daemon-manager.sh start [swarm_interval] [metrics_interval]
+
+# Stop all daemons
+.claude/helpers/daemon-manager.sh stop
+
+# Restart daemons
+.claude/helpers/daemon-manager.sh restart
+
+# Check status
+.claude/helpers/daemon-manager.sh status
+```
+
+### 2. Metrics Database (`metrics-db.mjs`)
+
+SQLite-based metrics storage using sql.js (WASM, cross-platform).
+
+**Database Schema:**
+```sql
+-- V3 Implementation Progress
+CREATE TABLE v3_progress (
+ id INTEGER PRIMARY KEY,
+ domains_completed INTEGER, -- 0-5 bounded contexts
+ ddd_progress INTEGER, -- 0-100%
+ total_modules INTEGER, -- @claude-flow modules
+ total_files INTEGER, -- TypeScript files
+ total_lines INTEGER, -- Lines of code
+ last_updated TEXT
+);
+
+-- Security Audit Status
+CREATE TABLE security_audit (
+ id INTEGER PRIMARY KEY,
+ status TEXT, -- PENDING|IN_PROGRESS|CLEAN
+ cves_fixed INTEGER, -- 0-3
+ total_cves INTEGER, -- 3 critical CVEs
+ last_audit TEXT
+);
+
+-- Real-time Swarm Activity
+CREATE TABLE swarm_activity (
+ id INTEGER PRIMARY KEY,
+ agentic_flow_processes INTEGER,
+ mcp_server_processes INTEGER,
+ estimated_agents INTEGER,
+ swarm_active INTEGER,
+ coordination_active INTEGER,
+ last_updated TEXT
+);
+
+-- Per-Module Status
+CREATE TABLE module_status (
+ name TEXT PRIMARY KEY,
+ files INTEGER,
+ lines INTEGER,
+ progress INTEGER,
+ has_src INTEGER,
+ has_tests INTEGER,
+ last_updated TEXT
+);
+
+-- CVE Remediation Status
+CREATE TABLE cve_status (
+ id TEXT PRIMARY KEY,
+ description TEXT,
+ severity TEXT,
+ status TEXT, -- pending|fixed
+ fixed_by TEXT, -- Implementing file
+ last_updated TEXT
+);
+```
+
+**Commands:**
+```bash
+# Sync metrics from V3 implementation
+node .claude/helpers/metrics-db.mjs sync
+
+# Export to JSON (backward compatibility)
+node .claude/helpers/metrics-db.mjs export
+
+# Get current status
+node .claude/helpers/metrics-db.mjs status
+
+# Run as daemon
+node .claude/helpers/metrics-db.mjs daemon [interval_seconds]
+```
+
+### 3. Swarm Monitor (`swarm-monitor.sh`)
+
+Real-time process detection for active agents.
+
+```bash
+# Single check
+.claude/helpers/swarm-monitor.sh check
+
+# Continuous monitoring
+.claude/helpers/swarm-monitor.sh monitor [interval]
+
+# Show status
+.claude/helpers/swarm-monitor.sh status
+```
+
+### 4. Statusline (`statusline.sh`)
+
+On-demand status display for Claude Code.
+
+**Output Format:**
+```
+β–Š Claude Flow V3 ● agentic-flow@alpha β”‚ βŽ‡ v3
+─────────────────────────────────────────────────────
+πŸ—οΈ DDD Domains [●●●●●] 5/5 ⚑ 1.0x β†’ 2.49x-7.47x
+πŸ€– Swarm Agents β—‰ [ 2/15] 🟒 CVE 3/3 πŸ’Ύ 0%
+πŸ”§ Architecture DDD ●93% β”‚ Security ●CLEAN β”‚ Memory ●AgentDB
+─────────────────────────────────────────────────────
+```
+
+## Performance
+
+### Benchmark Results
+
+| Method | Avg Time | Relative |
+|--------|----------|----------|
+| SQLite (sql.js) | 138ms | 1.0x (baseline) |
+| Bash/JSON | 1455ms | 10.5x slower |
+
+SQLite provides **10.5x faster** metrics synchronization.
+
+### Optimization Details
+
+1. **sql.js WASM** - Pure JavaScript, no native compilation
+2. **Single .db file** - Atomic updates, no file fragmentation
+3. **Prepared statements** - Reduced SQL parsing overhead
+4. **Periodic sync** - 30s default, configurable
+5. **JSON export** - Backward compatibility with statusline.sh
+
+## Hook Configuration
+
+In `.claude/settings.json`:
+
+```json
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "timeout": 3000,
+ "command": ".claude/helpers/daemon-manager.sh start 3 30"
+ }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "timeout": 2000,
+ "command": ".claude/helpers/daemon-manager.sh stop"
+ }
+ ]
+ }
+ ]
+ },
+ "statusLine": {
+ "type": "command",
+ "command": "/workspaces/claude-flow/.claude/statusline.sh"
+ }
+}
+```
+
+## Files
+
+| File | Purpose |
+|------|---------|
+| `.claude/helpers/daemon-manager.sh` | Daemon lifecycle management |
+| `.claude/helpers/metrics-db.mjs` | SQLite metrics engine |
+| `.claude/helpers/swarm-monitor.sh` | Process detection |
+| `.claude/helpers/sync-v3-metrics.sh` | Legacy bash sync (deprecated) |
+| `.claude/statusline.sh` | Status display |
+| `.claude-flow/metrics.db` | SQLite database |
+| `.claude-flow/metrics/*.json` | Exported JSON (compatibility) |
+| `.claude-flow/pids/*.pid` | Daemon PID files |
+| `.claude-flow/logs/*.log` | Daemon logs |
+
+## Metrics Tracked
+
+### V3 Progress
+- Domains completed (0-5 bounded contexts)
+- DDD architecture progress (0-100%)
+- Module count (10 @claude-flow modules)
+- Files and lines of code
+
+### Security
+- CVE remediation status (0-3 fixed)
+- Overall security status (PENDING/IN_PROGRESS/CLEAN)
+- Per-CVE tracking
+
+### Swarm Activity
+- agentic-flow processes
+- MCP server status
+- Estimated active agents
+- Coordination status
+
+### Performance
+- Flash Attention speedup target
+- Memory reduction target
+- Search improvement metrics
+
+## Troubleshooting
+
+### Daemons not starting
+```bash
+# Check logs
+cat .claude-flow/logs/daemon.log
+cat .claude-flow/logs/metrics-daemon.log
+
+# Manual start
+.claude/helpers/daemon-manager.sh start
+```
+
+### Stale metrics
+```bash
+# Force sync
+node .claude/helpers/metrics-db.mjs sync
+
+# Restart daemons
+.claude/helpers/daemon-manager.sh restart
+```
+
+### Database corruption
+```bash
+# Remove and recreate
+rm .claude-flow/metrics.db
+node .claude/helpers/metrics-db.mjs sync
+```