Files
ruflo/v3/@claude-flow/shared
rUv 07ff7f5641 fix: prevent MCP server self-kill on startup (#1381)
* fix: intelligence layer loads flat array from auto-memory store

The auto-memory-hook.mjs writes a flat JSON array to auto-memory-store.json,
but intelligence.cjs loadEntries() only checked for store.entries (object
wrapper format). This caused the vector store to load only 1 fallback
pattern from MEMORY.md instead of the full 1,300+ entries.

Now supports both formats: flat array and { entries: [...] } wrapper.
Also fixes deprecated Dirent.path usage (use parentPath first).

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: apply same loadEntries fix to helpers-generator.ts

The published CLI package generates intelligence.cjs during `init` via
helpers-generator.ts — it had the same flat-array bug. Users running
`npx claude-flow init` would get the broken version.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: statusline uses real data instead of hardcoded/estimated values

- Hooks: count actual hook entries instead of hardcoding total=17
- Vectors: count real entries from auto-memory-store.json, not file-size/2
- Tests: scan v3/ directory (depth 6), was missing ~2000 test files
- Swarm: only show active if state updated within 5 min (stale check)
- Security: flag as STALE if audit older than 7 days
- ADRs: count actual files (76), don't use stale compliance JSON (7)
- Intelligence: scale to 2000 entries = 100% instead of 100 entries

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: apply statusline accuracy fixes to generator (end-user path)

The statusline-generator.ts always overwrites the bundled statusline.cjs
during init, so all 6 accuracy fixes must be in both files:

- Hooks: count actual entries, not hardcode 17
- Vectors: read real entry count from store JSON
- Tests: scan depth 6, include v3/ directory
- Swarm: 5-min staleness check on metrics
- Security: PENDING when no audit run, STALE after 7 days
- ADRs: count files directly, skip stale compliance JSON

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: prevent MCP server self-kill on startup (#1380)

Three compounding bugs caused `mcp start` to crash with "Killed":

1. Self-kill: getStatus() reported current process as "running" for stdio
   transport, then start command sent SIGKILL to its own PID
2. Config crash: Zod schema rejected partial configs with non-object values
3. Hook exit: process.exitCode=0 was overridden by async errors

Fixes:
- Add isSelfDetected guard to skip kill when PID matches process.pid
- Add .passthrough() to SystemConfigSchema, merge partial configs with defaults
- Use process.exit(0) in .finally() for reliable hook exits
- Remove invalid hook events (TeammateIdle, TaskCompleted, PostCompact)
- Wrap hook commands in sh -c for cross-platform CLAUDE_PROJECT_DIR expansion

Published as v3.5.39. Tested in Docker — clean startup, no warnings.

Closes #1380

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-03-19 11:08:37 -04:00
..
2026-01-04 20:24:17 +00:00
2026-01-05 21:17:24 +00:00
2026-01-04 17:48:23 +00:00

@claude-flow/shared

npm version npm downloads License: MIT TypeScript Core

Shared utilities, types, and core infrastructure for Claude Flow V3 - the foundation module used by all other @claude-flow packages.

Features

  • Core Types - Agent, Task, Memory, MCP, and Swarm type definitions
  • Core Interfaces - Agent, Task, Memory, Event, and Coordinator interfaces
  • Configuration - Schema validation, loading, and default values
  • Event System - Event bus, coordinator, and handler utilities
  • Hooks System - Pre/post execution hooks for extensibility
  • MCP Infrastructure - Server, transport, connection pool, and tool registry
  • Health Monitoring - Health checks and monitoring utilities

Installation

npm install @claude-flow/shared

Quick Start

import {
  AgentState,
  TaskDefinition,
  MemoryEntry,
  EventBus,
  ConfigLoader
} from '@claude-flow/shared';

// Use shared types
const agent: AgentState = {
  id: { id: 'agent-1', swarmId: 'swarm-1', type: 'coder' },
  name: 'Code Agent',
  type: 'coder',
  status: 'idle'
};

// Use configuration
const config = await ConfigLoader.load('./config.json');

// Use event system
const eventBus = new EventBus();
eventBus.on('task.completed', (event) => {
  console.log(`Task ${event.taskId} completed`);
});

Package Exports

// Main entry (recommended - includes all modules)
import { ... } from '@claude-flow/shared';

// Submodule exports (for tree-shaking or specific imports)
import { ... } from '@claude-flow/shared/types';      // Type definitions
import { ... } from '@claude-flow/shared/core';       // Config, interfaces, orchestrator
import { ... } from '@claude-flow/shared/events';     // Event sourcing (ADR-007)
import { ... } from '@claude-flow/shared/hooks';      // Hooks system
import { ... } from '@claude-flow/shared/mcp';        // MCP server infrastructure
import { ... } from '@claude-flow/shared/security';   // Security utilities
import { ... } from '@claude-flow/shared/resilience'; // Retry, circuit breaker, rate limiter

API Reference

Types

import type {
  // Agent types
  AgentId,
  AgentState,
  AgentType,
  AgentStatus,
  AgentCapabilities,
  AgentMetrics,

  // Task types
  TaskId,
  TaskDefinition,
  TaskType,
  TaskStatus,
  TaskPriority,

  // Memory types
  MemoryEntry,
  MemoryType,
  SearchResult,

  // Swarm types
  SwarmId,
  SwarmStatus,
  SwarmEvent,
  CoordinatorConfig,

  // MCP types
  MCPTool,
  MCPRequest,
  MCPResponse
} from '@claude-flow/shared/types';

Core Interfaces

import type {
  IAgent,
  ITask,
  IMemory,
  ICoordinator,
  IEventHandler
} from '@claude-flow/shared/core';

// Agent interface
interface IAgent {
  getId(): AgentId;
  getState(): AgentState;
  execute(task: TaskDefinition): Promise<TaskResult>;
  handleMessage(message: Message): Promise<void>;
}

// Memory interface
interface IMemory {
  store(entry: MemoryEntry): Promise<string>;
  retrieve(id: string): Promise<MemoryEntry | null>;
  search(query: SearchQuery): Promise<SearchResult[]>;
  delete(id: string): Promise<boolean>;
}

// Coordinator interface
interface ICoordinator {
  initialize(): Promise<void>;
  shutdown(): Promise<void>;
  registerAgent(agent: IAgent): Promise<string>;
  submitTask(task: TaskDefinition): Promise<string>;
}

Configuration

import {
  ConfigLoader,
  ConfigValidator,
  defaultConfig,
  ConfigSchema
} from '@claude-flow/shared/core';

// Load configuration
const config = await ConfigLoader.load('./config.json');
const config2 = await ConfigLoader.loadFromEnv();

// Validate configuration
const errors = ConfigValidator.validate(config);
if (errors.length > 0) {
  console.error('Invalid config:', errors);
}

// Default configuration
const defaults = defaultConfig();

Event System

import { EventBus, EventCoordinator } from '@claude-flow/shared/events';

const eventBus = new EventBus();

// Subscribe to events
eventBus.on('agent.joined', (event) => {
  console.log(`Agent ${event.agentId} joined`);
});

eventBus.on('task.*', (event) => {
  console.log(`Task event: ${event.type}`);
});

// Emit events
eventBus.emit({
  type: 'task.completed',
  taskId: 'task-1',
  result: { success: true }
});

// Event coordinator for complex workflows
const coordinator = new EventCoordinator();
coordinator.orchestrate([
  { event: 'step1.done', handler: () => startStep2() },
  { event: 'step2.done', handler: () => startStep3() }
]);

Hooks System

import { HooksManager, Hook } from '@claude-flow/shared/hooks';

const hooks = new HooksManager();

// Register pre-execution hook
hooks.register('pre:task', async (context) => {
  console.log(`Starting task: ${context.taskId}`);
  return { ...context, startTime: Date.now() };
});

// Register post-execution hook
hooks.register('post:task', async (context, result) => {
  const duration = Date.now() - context.startTime;
  console.log(`Task completed in ${duration}ms`);
});

// Execute with hooks
const result = await hooks.execute('task', context, async (ctx) => {
  return await runTask(ctx);
});

MCP Infrastructure

import {
  createMCPServer,
  createToolRegistry,
  createConnectionPool,
  createSessionManager,
  defineTool,
  quickStart,
} from '@claude-flow/shared/mcp';

// Quick start - simplest way to create an MCP server
const server = await quickStart({
  transport: 'stdio',
  name: 'My MCP Server',
});

// Tool registry
const registry = createToolRegistry();
registry.register(defineTool({
  name: 'swarm_init',
  description: 'Initialize a swarm',
  inputSchema: { type: 'object', properties: { topology: { type: 'string' } } },
  handler: async (params) => ({ result: 'initialized' }),
}));

// Connection pool
const pool = createConnectionPool({
  maxConnections: 10,
  acquireTimeoutMs: 30000,
});

// Session manager
const sessions = createSessionManager({ timeoutMs: 3600000 });
const session = await sessions.create({ clientInfo: { name: 'client' } });

Health Monitor

import { HealthMonitor, HealthCheck } from '@claude-flow/shared/core';

const monitor = new HealthMonitor();

// Register health checks
monitor.register('database', async () => {
  const connected = await db.ping();
  return { healthy: connected, latency: pingTime };
});

monitor.register('memory', async () => {
  const usage = process.memoryUsage();
  return { healthy: usage.heapUsed < MAX_HEAP, usage };
});

// Run health checks
const report = await monitor.check();
// { overall: 'healthy', checks: { database: {...}, memory: {...} } }

TypeScript Types

All types are fully exported and documented:

// Re-export all types
export * from './types/agent.types';
export * from './types/task.types';
export * from './types/memory.types';
export * from './types/swarm.types';
export * from './types/mcp.types';

Dependencies

  • sql.js - SQLite WASM for cross-platform persistence

Used By

This package is a dependency of all other @claude-flow modules:

License

MIT