π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
checkpoint: File edit:
rUv6ee718a6bc69
diff --git a/.claude/statusline.sh b/.claude/statusline.shindex 4f4d6823c3..77b4f83fa8 100755--- a/.claude/statusline.sh+++ b/.claude/statusline.sh@@ -57,6 +57,15 @@ if git rev-parse --is-inside-work-tree >/dev/null 2>&1; thenGIT_BRANCH=$(git branch --show-current 2>/dev/null || echo "")fi+# Get GitHub username (try gh CLI first, fallback to git config)+GH_USER=""+if command -v gh >/dev/null 2>&1; then+ GH_USER=$(gh api user --jq '.login' 2>/dev/null || echo "")+fi+if [ -z "$GH_USER" ]; then+ GH_USER=$(git config user.name 2>/dev/null || echo "user")+fi+# Check V3 domain implementation progressif [ -f "$V3_METRICS" ]; thenDOMAINS_COMPLETED=$(jq -r '.domains.completed // 0' "$V3_METRICS" 2>/dev/null || echo "0")@@ -207,7 +216,7 @@ OUTPUT=""# Header Line: V3 Project + Branch + Integration StatusOUTPUT="${BOLD}${BRIGHT_PURPLE}β Claude Flow V3 ${RESET}"-OUTPUT="${OUTPUT}${INTEGRATION_COLOR}${INTEGRATION_STATUS} ${BRIGHT_CYAN}agentic-flow@alpha${RESET}"+OUTPUT="${OUTPUT}${INTEGRATION_COLOR}${INTEGRATION_STATUS} ${BRIGHT_CYAN}rUv${RESET}"if [ -n "$GIT_BRANCH" ]; thenOUTPUT="${OUTPUT} ${DIM}β${RESET} ${BRIGHT_BLUE}β ${GIT_BRANCH}${RESET}"fidiff --git a/v3/@claude-flow/billing/README.md b/v3/@claude-flow/billing/README.mdnew file mode 100644index 0000000000..679f84c6bc--- /dev/null+++ b/v3/@claude-flow/billing/README.md@@ -0,0 +1,71 @@+# @claude-flow/billing++Billing and metering module for Claude-Flow V3.++## Overview++This module provides billing, metering, and usage tracking capabilities for Claude-Flow agents and swarms.++## Features++- **Usage Metering**: Track API calls, tokens, and compute usage+- **Billing Integration**: Connect to payment providers+- **Cost Estimation**: Estimate costs before execution+- **Usage Reporting**: Generate usage reports and analytics++## Installation++```bash+npm install @claude-flow/billing+```++## Usage++```typescript+import { MeteringEngine } from '@claude-flow/billing';++const metering = new MeteringEngine({+ // configuration+});++// Track usage+await metering.trackUsage({+ agentId: 'agent-1',+ operation: 'task-execution',+ tokens: 1500,+ duration: 5000,+});++// Get usage report+const report = await metering.getUsageReport({+ startDate: new Date('2026-01-01'),+ endDate: new Date(),+});+```++## API Reference++### MeteringEngine++Main class for usage metering and billing.++#### Methods++- `trackUsage(usage: UsageRecord)` - Record usage event+- `getUsageReport(options)` - Generate usage report+- `estimateCost(task: Task)` - Estimate task cost++## Configuration++```typescript+interface BillingConfig {+ enabled: boolean;+ provider?: 'stripe' | 'custom';+ meteringInterval?: number;+ retentionDays?: number;+}+```++## License++MITdiff --git a/v3/@claude-flow/billing/src/__tests__/metering-engine.test.ts b/v3/@claude-flow/billing/src/__tests__/metering-engine.test.tsnew file mode 100644index 0000000000..fa73372ab9--- /dev/null+++ b/v3/@claude-flow/billing/src/__tests__/metering-engine.test.ts@@ -0,0 +1,129 @@+/**+ * Tests for MeteringEngine+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { MeteringEngine, InMemoryBillingStorage, createMeteringEngine } from '../index.js';++describe('MeteringEngine', () => {+ let engine: MeteringEngine;+ let storage: InMemoryBillingStorage;++ beforeEach(async () => {+ storage = new InMemoryBillingStorage();+ engine = new MeteringEngine({}, storage);+ await engine.initialize();+ });++ describe('Initialization', () => {+ it('should initialize successfully', async () => {+ const newEngine = new MeteringEngine({});+ await newEngine.initialize();+ expect(newEngine).toBeDefined();+ });++ it('should create engine with factory function', async () => {+ const factoryEngine = createMeteringEngine({});+ await factoryEngine.initialize();+ expect(factoryEngine).toBeInstanceOf(MeteringEngine);+ });+ });++ describe('Event Emission', () => {+ it('should emit events', () => {+ let eventReceived = false;+ engine.on('usage:recorded', () => {+ eventReceived = true;+ });++ // The engine should be an EventEmitter+ expect(typeof engine.on).toBe('function');+ expect(typeof engine.emit).toBe('function');+ });+ });+});++describe('InMemoryBillingStorage', () => {+ let storage: InMemoryBillingStorage;++ beforeEach(() => {+ storage = new InMemoryBillingStorage();+ });++ describe('Subscription Storage', () => {+ it('should save and retrieve subscription', async () => {+ const sub = { id: 'sub-1', userId: 'user-1', tier: 'pro' };+ await storage.saveSubscription(sub);++ const retrieved = await storage.getSubscription('sub-1');+ expect(retrieved).toEqual(sub);+ });++ it('should return null for non-existent subscription', async () => {+ const result = await storage.getSubscription('non-existent');+ expect(result).toBeNull();+ });++ it('should get subscription by user id', async () => {+ const sub = { id: 'sub-2', userId: 'user-2', tier: 'starter' };+ await storage.saveSubscription(sub);++ const retrieved = await storage.getSubscriptionByUser('user-2');+ expect(retrieved).toEqual(sub);+ });+ });++ describe('Usage Record Storage', () => {+ it('should save and retrieve usage records', async () => {+ const record = {+ id: 'record-1',+ subscriptionId: 'sub-1',+ metric: 'tokens',+ value: 1000,+ timestamp: Date.now(),+ billingPeriod: '2026-01',+ };++ await storage.saveUsageRecord(record);+ const records = await storage.getUsageRecords('sub-1', '2026-01');++ expect(records).toHaveLength(1);+ expect(records[0].value).toBe(1000);+ });++ it('should return empty array for no records', async () => {+ const records = await storage.getUsageRecords('none', 'none');+ expect(records).toEqual([]);+ });+ });++ describe('Payment Storage', () => {+ it('should save and retrieve payments', async () => {+ const payment = { id: 'pay-1', subscriptionId: 'sub-1', amount: 100 };+ await storage.savePayment(payment);++ const payments = await storage.getPayments('sub-1');+ expect(payments).toHaveLength(1);+ expect(payments[0].amount).toBe(100);+ });+ });++ describe('Coupon Storage', () => {+ it('should save and retrieve coupon', async () => {+ const coupon = { code: 'SAVE10', discount: 10, currentUses: 0 };+ await storage.saveCoupon(coupon);++ const retrieved = await storage.getCoupon('SAVE10');+ expect(retrieved.discount).toBe(10);+ });++ it('should increment coupon usage', async () => {+ const coupon = { code: 'USAGE', discount: 5, currentUses: 0 };+ await storage.saveCoupon(coupon);++ await storage.incrementCouponUsage('USAGE');++ const updated = await storage.getCoupon('USAGE');+ expect(updated.currentUses).toBe(1);+ });+ });+});diff --git a/v3/@claude-flow/billing/src/metering-engine.ts b/v3/@claude-flow/billing/src/metering-engine.tsindex 003bb9aed5..0d41752025 100644--- a/v3/@claude-flow/billing/src/metering-engine.ts+++ b/v3/@claude-flow/billing/src/metering-engine.ts@@ -14,17 +14,19 @@*/import { EventEmitter } from 'events';+import {+ UsageMetric,+ BillingEventType,+} from './types.js';import type {MeteringConfig,IMeteringEngine,IBillingStorage,UsageRecord,- UsageMetric,ResourceLimits,QuotaCheckResult,UsageSummary,BillingEvent,- BillingEventType,BillingEventListener,} from './types.js';diff --git a/v3/@claude-flow/deployment/package.json b/v3/@claude-flow/deployment/package.jsonindex f8f4e8edf2..7b517d834f 100644--- a/v3/@claude-flow/deployment/package.json+++ b/v3/@claude-flow/deployment/package.json@@ -10,12 +10,14 @@},"scripts": {"build": "tsc",+ "test": "vitest run","release": "semantic-release"},"dependencies": {"@claude-flow/shared": "workspace:*"},"devDependencies": {- "semantic-release": "^22.0.0"+ "semantic-release": "^22.0.0",+ "vitest": "^1.6.0"}}diff --git a/v3/@claude-flow/deployment/src/__tests__/release-manager.test.ts b/v3/@claude-flow/deployment/src/__tests__/release-manager.test.tsnew file mode 100644index 0000000000..e9e5ea4cc6--- /dev/null+++ b/v3/@claude-flow/deployment/src/__tests__/release-manager.test.ts@@ -0,0 +1,72 @@+/**+ * Tests for Deployment Module+ */+import { describe, it, expect } from 'vitest';+import { ReleaseManager } from '../index.js';++describe('ReleaseManager', () => {+ describe('Constructor', () => {+ it('should create with default cwd', () => {+ const manager = new ReleaseManager();+ expect(manager).toBeDefined();+ });++ it('should create with custom cwd', () => {+ const manager = new ReleaseManager('/custom/path');+ expect(manager).toBeDefined();+ });+ });+});++describe('Version Bump Logic', () => {+ it('should parse version parts', () => {+ const version = '1.2.3';+ const parts = version.split('.').map(Number);++ expect(parts[0]).toBe(1);+ expect(parts[1]).toBe(2);+ expect(parts[2]).toBe(3);+ });++ it('should bump patch version', () => {+ const parts = '1.0.0'.split('.').map(Number);+ const newVersion = [parts[0], parts[1], parts[2] + 1].join('.');+ expect(newVersion).toBe('1.0.1');+ });++ it('should bump minor version', () => {+ const parts = '1.0.0'.split('.').map(Number);+ const newVersion = [parts[0], parts[1] + 1, 0].join('.');+ expect(newVersion).toBe('1.1.0');+ });++ it('should bump major version', () => {+ const parts = '1.0.0'.split('.').map(Number);+ const newVersion = [parts[0] + 1, 0, 0].join('.');+ expect(newVersion).toBe('2.0.0');+ });+});++describe('Changelog Generation', () => {+ it('should format date correctly', () => {+ const date = new Date('2026-01-05');+ const formatted = date.toISOString().split('T')[0];+ expect(formatted).toBe('2026-01-05');+ });++ it('should categorize commits by type', () => {+ const commits = [+ { message: 'feat: add new feature' },+ { message: 'fix: fix bug' },+ { message: 'docs: update docs' },+ ];++ const feat = commits.filter(c => c.message.startsWith('feat:'));+ const fix = commits.filter(c => c.message.startsWith('fix:'));+ const docs = commits.filter(c => c.message.startsWith('docs:'));++ expect(feat).toHaveLength(1);+ expect(fix).toHaveLength(1);+ expect(docs).toHaveLength(1);+ });+});diff --git a/v3/@claude-flow/embeddings/README.md b/v3/@claude-flow/embeddings/README.mdnew file mode 100644index 0000000000..a2114805fe--- /dev/null+++ b/v3/@claude-flow/embeddings/README.md@@ -0,0 +1,81 @@+# @claude-flow/embeddings++Embedding generation and management module for Claude-Flow V3.++## Overview++This module provides embedding generation, caching, and management for semantic search and memory systems.++## Features++- **Multiple Providers**: OpenAI, Anthropic, local models+- **Caching**: LRU cache for frequently used embeddings+- **Batch Processing**: Efficient batch embedding generation+- **Dimensionality**: Support for various embedding dimensions++## Installation++```bash+npm install @claude-flow/embeddings+```++## Usage++```typescript+import { EmbeddingService } from '@claude-flow/embeddings';++const embeddings = new EmbeddingService({+ provider: 'openai',+ model: 'text-embedding-3-small',+ dimensions: 1536,+});++// Generate embedding+const vector = await embeddings.embed('Hello world');++// Batch embed+const vectors = await embeddings.embedBatch([+ 'First text',+ 'Second text',+ 'Third text',+]);++// Calculate similarity+const similarity = embeddings.cosineSimilarity(vector1, vector2);+```++## API Reference++### EmbeddingService++Main class for embedding operations.++#### Methods++- `embed(text: string)` - Generate embedding for text+- `embedBatch(texts: string[])` - Batch embedding generation+- `cosineSimilarity(a, b)` - Calculate similarity score++## Configuration++```typescript+interface EmbeddingConfig {+ provider: 'openai' | 'anthropic' | 'local';+ model?: string;+ dimensions?: number;+ cacheEnabled?: boolean;+ cacheSize?: number;+}+```++## Supported Providers++| Provider | Models | Dimensions |+|----------|--------|------------|+| OpenAI | text-embedding-3-small/large | 1536/3072 |+| Anthropic | claude-embed | 1024 |+| Local | sentence-transformers | 384-768 |++## License++MITdiff --git a/v3/@claude-flow/embeddings/src/__tests__/embedding-service.test.ts b/v3/@claude-flow/embeddings/src/__tests__/embedding-service.test.tsnew file mode 100644index 0000000000..94333163e7--- /dev/null+++ b/v3/@claude-flow/embeddings/src/__tests__/embedding-service.test.ts@@ -0,0 +1,126 @@+/**+ * Tests for EmbeddingService+ */+import { describe, it, expect, beforeEach } from 'vitest';+import {+ createEmbeddingService,+ MockEmbeddingService,+ cosineSimilarity,+ euclideanDistance,+ dotProduct,+ computeSimilarity,+} from '../index.js';++describe('EmbeddingService', () => {+ describe('MockEmbeddingService', () => {+ let service: MockEmbeddingService;++ beforeEach(() => {+ service = new MockEmbeddingService({ dimensions: 128 });+ });++ it('should generate embeddings with correct dimensions', async () => {+ const result = await service.embed('Hello, world!');+ expect(result.embedding).toHaveLength(128);+ });++ it('should generate deterministic embeddings for same text', async () => {+ const result1 = await service.embed('test text');+ const result2 = await service.embed('test text');++ // Mock service should be deterministic+ expect(Array.from(result1.embedding)).toEqual(Array.from(result2.embedding));+ });++ it('should handle batch embeddings', async () => {+ const texts = ['text1', 'text2', 'text3'];+ const results = await service.embedBatch(texts);++ expect(results.embeddings).toHaveLength(3);+ // Each embedding should have correct dimensions+ results.embeddings.forEach((emb) => {+ expect(emb.length).toBe(128);+ });+ });+ });++ describe('createEmbeddingService', () => {+ it('should create mock service', () => {+ const service = createEmbeddingService({+ provider: 'mock',+ dimensions: 64,+ });++ expect(service).toBeInstanceOf(MockEmbeddingService);+ });+ });+});++describe('Similarity Functions', () => {+ const vec1 = new Float32Array([1, 0, 0]);+ const vec2 = new Float32Array([1, 0, 0]);+ const vec3 = new Float32Array([0, 1, 0]);+ const vec4 = new Float32Array([-1, 0, 0]);++ describe('cosineSimilarity', () => {+ it('should return 1 for identical vectors', () => {+ expect(cosineSimilarity(vec1, vec2)).toBeCloseTo(1);+ });++ it('should return 0 for orthogonal vectors', () => {+ expect(cosineSimilarity(vec1, vec3)).toBeCloseTo(0);+ });++ it('should return -1 for opposite vectors', () => {+ expect(cosineSimilarity(vec1, vec4)).toBeCloseTo(-1);+ });+ });++ describe('euclideanDistance', () => {+ it('should return 0 for identical vectors', () => {+ expect(euclideanDistance(vec1, vec2)).toBeCloseTo(0);+ });++ it('should return sqrt(2) for unit orthogonal vectors', () => {+ expect(euclideanDistance(vec1, vec3)).toBeCloseTo(Math.sqrt(2));+ });++ it('should return 2 for opposite unit vectors', () => {+ expect(euclideanDistance(vec1, vec4)).toBeCloseTo(2);+ });+ });++ describe('dotProduct', () => {+ it('should return 1 for identical unit vectors', () => {+ expect(dotProduct(vec1, vec2)).toBeCloseTo(1);+ });++ it('should return 0 for orthogonal vectors', () => {+ expect(dotProduct(vec1, vec3)).toBeCloseTo(0);+ });++ it('should return -1 for opposite unit vectors', () => {+ expect(dotProduct(vec1, vec4)).toBeCloseTo(-1);+ });+ });++ describe('computeSimilarity', () => {+ it('should use cosine metric by default', () => {+ const result = computeSimilarity(vec1, vec2);+ expect(result.metric).toBe('cosine');+ expect(result.score).toBeCloseTo(1);+ });++ it('should support euclidean metric', () => {+ const result = computeSimilarity(vec1, vec3, 'euclidean');+ expect(result.metric).toBe('euclidean');+ expect(result.score).toBeCloseTo(Math.sqrt(2));+ });++ it('should support dot product metric', () => {+ const result = computeSimilarity(vec1, vec4, 'dot');+ expect(result.metric).toBe('dot');+ expect(result.score).toBeCloseTo(-1);+ });+ });+});diff --git a/v3/@claude-flow/federation/README.md b/v3/@claude-flow/federation/README.mdnew file mode 100644index 0000000000..92e7f2b5a6--- /dev/null+++ b/v3/@claude-flow/federation/README.md@@ -0,0 +1,91 @@+# @claude-flow/federation++Federation and cross-swarm coordination module for Claude-Flow V3.++## Overview++This module enables federation between multiple Claude-Flow instances, allowing distributed swarm coordination across different environments.++## Features++- **Cross-Swarm Communication**: Connect swarms across instances+- **Agent Discovery**: Discover and connect to remote agents+- **Task Delegation**: Delegate tasks to federated swarms+- **State Synchronization**: Keep federated state consistent++## Installation++```bash+npm install @claude-flow/federation+```++## Usage++```typescript+import { FederationHub } from '@claude-flow/federation';++const hub = new FederationHub({+ instanceId: 'instance-1',+ discoveryEndpoint: 'https://discovery.example.com',+});++await hub.initialize();++// Register with federation+await hub.register({+ capabilities: ['code-generation', 'testing'],+ maxAgents: 10,+});++// Discover remote swarms+const remoteSwarms = await hub.discoverSwarms({+ capabilities: ['security-analysis'],+});++// Delegate task to remote swarm+const result = await hub.delegateTask(remoteSwarms[0].id, task);+```++## API Reference++### FederationHub++Main class for federation management.++#### Methods++- `initialize()` - Initialize federation hub+- `register(config)` - Register with federation network+- `discoverSwarms(query)` - Discover available swarms+- `delegateTask(swarmId, task)` - Delegate task to remote swarm+- `shutdown()` - Gracefully disconnect from federation++## Configuration++```typescript+interface FederationConfig {+ instanceId: string;+ discoveryEndpoint?: string;+ heartbeatInterval?: number;+ maxConnections?: number;+ tls?: TLSConfig;+}+```++## Architecture++```+βββββββββββββββββββ βββββββββββββββββββ+β Local Swarm ββββββΊβ Federation Hub β+βββββββββββββββββββ ββββββββββ¬βββββββββ+ β+ ββββββββββββββ΄βββββββββββββ+ β β+ βββββββββΌββββββββ βββββββββΌββββββββ+ β Remote Swarm 1β β Remote Swarm 2β+ βββββββββββββββββ βββββββββββββββββ+```++## License++MITdiff --git a/v3/@claude-flow/federation/src/__tests__/federation-hub.test.ts b/v3/@claude-flow/federation/src/__tests__/federation-hub.test.tsnew file mode 100644index 0000000000..f5c96dd7e5--- /dev/null+++ b/v3/@claude-flow/federation/src/__tests__/federation-hub.test.ts@@ -0,0 +1,146 @@+/**+ * Tests for FederationHub+ */+import { describe, it, expect } from 'vitest';+import {+ FederationHub,+ createFederationHub,+ compareVectorClocks,+ mergeVectorClocks,+ incrementVectorClock,+} from '../index.js';+import type { VectorClock } from '../types.js';++describe('Vector Clock Operations', () => {+ describe('compareVectorClocks', () => {+ it('should return equal for identical clocks', () => {+ const clock1: VectorClock = { a: 1, b: 2 };+ const clock2: VectorClock = { a: 1, b: 2 };++ expect(compareVectorClocks(clock1, clock2)).toBe('equal');+ });++ it('should return before when first is older', () => {+ const clock1: VectorClock = { a: 1, b: 1 };+ const clock2: VectorClock = { a: 1, b: 2 };++ expect(compareVectorClocks(clock1, clock2)).toBe('before');+ });++ it('should return after when first is newer', () => {+ const clock1: VectorClock = { a: 2, b: 2 };+ const clock2: VectorClock = { a: 1, b: 2 };++ expect(compareVectorClocks(clock1, clock2)).toBe('after');+ });++ it('should return concurrent for conflicting clocks', () => {+ const clock1: VectorClock = { a: 2, b: 1 };+ const clock2: VectorClock = { a: 1, b: 2 };++ expect(compareVectorClocks(clock1, clock2)).toBe('concurrent');+ });++ it('should handle missing keys', () => {+ const clock1: VectorClock = { a: 1 };+ const clock2: VectorClock = { b: 1 };++ expect(compareVectorClocks(clock1, clock2)).toBe('concurrent');+ });++ it('should handle empty clocks', () => {+ const clock1: VectorClock = {};+ const clock2: VectorClock = {};++ expect(compareVectorClocks(clock1, clock2)).toBe('equal');+ });+ });++ describe('mergeVectorClocks', () => {+ it('should take max of each component', () => {+ const clock1: VectorClock = { a: 2, b: 1 };+ const clock2: VectorClock = { a: 1, b: 3 };++ const merged = mergeVectorClocks(clock1, clock2);++ expect(merged.a).toBe(2);+ expect(merged.b).toBe(3);+ });++ it('should include keys from both clocks', () => {+ const clock1: VectorClock = { a: 1, c: 3 };+ const clock2: VectorClock = { b: 2, d: 4 };++ const merged = mergeVectorClocks(clock1, clock2);++ expect(merged).toEqual({ a: 1, b: 2, c: 3, d: 4 });+ });++ it('should handle empty clocks', () => {+ const clock1: VectorClock = {};+ const clock2: VectorClock = { a: 1 };++ const merged = mergeVectorClocks(clock1, clock2);++ expect(merged).toEqual({ a: 1 });+ });+ });++ describe('incrementVectorClock', () => {+ it('should increment specified node', () => {+ const clock: VectorClock = { a: 1, b: 2 };+ const updated = incrementVectorClock(clock, 'a');++ expect(updated.a).toBe(2);+ expect(updated.b).toBe(2);+ });++ it('should add new node if not present', () => {+ const clock: VectorClock = { a: 1 };+ const updated = incrementVectorClock(clock, 'b');++ expect(updated.a).toBe(1);+ expect(updated.b).toBe(1);+ });++ it('should not mutate original clock', () => {+ const clock: VectorClock = { a: 1 };+ const updated = incrementVectorClock(clock, 'a');++ expect(clock.a).toBe(1);+ expect(updated.a).toBe(2);+ });+ });+});++describe('FederationHub', () => {+ describe('Creation', () => {+ it('should create hub with config', () => {+ const hub = createFederationHub({+ clusterId: 'test-cluster',+ });++ expect(hub).toBeInstanceOf(FederationHub);+ });++ it('should accept optional config options', () => {+ const hub = createFederationHub({+ clusterId: 'test-cluster',+ syncInterval: 5000,+ conflictResolution: 'last-write-wins',+ });++ expect(hub).toBeDefined();+ });+ });++ describe('Event Emission', () => {+ it('should be an EventEmitter', () => {+ const hub = createFederationHub({ clusterId: 'test' });++ expect(typeof hub.on).toBe('function');+ expect(typeof hub.emit).toBe('function');+ expect(typeof hub.off).toBe('function');+ });+ });+});diff --git a/v3/@claude-flow/federation/src/federation-hub.ts b/v3/@claude-flow/federation/src/federation-hub.tsindex f91cd02a49..1ab4ea0020 100644--- a/v3/@claude-flow/federation/src/federation-hub.ts+++ b/v3/@claude-flow/federation/src/federation-hub.ts@@ -124,7 +124,7 @@ export class FederationHub extends EventEmitter implements IFederationHub {};private syncDurations: number[] = [];- private listeners: Set<FederationEventListener> = new Set();+ private eventListeners: Set<FederationEventListener> = new Set();constructor(config: FederationHubConfig, logger?: ILogger) {super();@@ -381,11 +381,11 @@ export class FederationHub extends EventEmitter implements IFederationHub {// Event handlingaddEventListener(listener: FederationEventListener): void {- this.listeners.add(listener);+ this.eventListeners.add(listener);}removeEventListener(listener: FederationEventListener): void {- this.listeners.delete(listener);+ this.eventListeners.delete(listener);}// ============================================================================@@ -516,7 +516,7 @@ export class FederationHub extends EventEmitter implements IFederationHub {}private emitEvent(event: FederationEvent): void {- for (const listener of this.listeners) {+ for (const listener of this.eventListeners) {try {listener(event);} catch (error) {diff --git a/v3/@claude-flow/integration/src/agent-adapter.ts b/v3/@claude-flow/integration/src/agent-adapter.tsindex aa5671e4d5..911480f995 100644--- a/v3/@claude-flow/integration/src/agent-adapter.ts+++ b/v3/@claude-flow/integration/src/agent-adapter.ts@@ -442,9 +442,10 @@ export class AgentAdapter extends EventEmitter {private async connectToAgenticFlow(): Promise<void> {try {// Dynamic import to handle optional dependency- const agenticFlowModule = await import('agentic-flow').catch(() => null);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const agenticFlowModule: any = await import('agentic-flow').catch(() => null);- if (agenticFlowModule && agenticFlowModule.createAgenticFlow) {+ if (agenticFlowModule && typeof agenticFlowModule.createAgenticFlow === 'function') {this.agenticFlowCore = await agenticFlowModule.createAgenticFlow({});this.emit('agentic-flow-connected', {diff --git a/v3/@claude-flow/integration/src/agentic-flow-bridge.ts b/v3/@claude-flow/integration/src/agentic-flow-bridge.tsindex b0825c7841..5f2f1f3894 100644--- a/v3/@claude-flow/integration/src/agentic-flow-bridge.ts+++ b/v3/@claude-flow/integration/src/agentic-flow-bridge.ts@@ -169,7 +169,9 @@ export class AgenticFlowBridge extends EventEmitter {if (this.config.features.enableSONA) {this.sona = new SONAAdapter(this.config.sona);if (this.agenticFlowCore) {- this.sona.setAgenticFlowReference(this.agenticFlowCore.sona);+ // Type cast: agentic-flow runtime API is compatible but typed as `unknown`+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ this.sona.setAgenticFlowReference(this.agenticFlowCore.sona as any);}await this.sona.initialize();this.updateComponentHealth('sona', 'healthy');@@ -180,7 +182,9 @@ export class AgenticFlowBridge extends EventEmitter {if (this.config.features.enableFlashAttention) {this.attention = new AttentionCoordinator(this.config.attention);if (this.agenticFlowCore) {- this.attention.setAgenticFlowReference(this.agenticFlowCore.attention);+ // Type cast: agentic-flow runtime API is compatible but typed as `unknown`+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ this.attention.setAgenticFlowReference(this.agenticFlowCore.attention as any);}await this.attention.initialize();this.updateComponentHealth('attention', 'healthy');@@ -218,10 +222,10 @@ export class AgenticFlowBridge extends EventEmitter {try {// Dynamic import to handle optional dependency// eslint-disable-next-line @typescript-eslint/no-explicit-any- const agenticFlowModule = await import('agentic-flow').catch(() => null);+ const agenticFlowModule: any = await import('agentic-flow').catch(() => null);if (agenticFlowModule && typeof agenticFlowModule.createAgenticFlow === 'function') {- const factory = agenticFlowModule.createAgenticFlow as AgenticFlowFactory;+ const factory: AgenticFlowFactory = agenticFlowModule.createAgenticFlow;this.agenticFlowCore = await factory({sona: this.config.sona,diff --git a/v3/@claude-flow/integration/src/attention-coordinator.ts b/v3/@claude-flow/integration/src/attention-coordinator.tsindex fff009d43c..a62d81dd8b 100644--- a/v3/@claude-flow/integration/src/attention-coordinator.ts+++ b/v3/@claude-flow/integration/src/attention-coordinator.ts@@ -610,7 +610,9 @@ export class AttentionCoordinator extends EventEmitter {if (this.cache.size >= this.maxCacheSize) {// Remove oldest entryconst firstKey = this.cache.keys().next().value;- this.cache.delete(firstKey);+ if (firstKey !== undefined) {+ this.cache.delete(firstKey);+ }}this.cache.set(key, result);}diff --git a/v3/@claude-flow/integration/src/feature-flags.ts b/v3/@claude-flow/integration/src/feature-flags.tsindex 3d47ec87ab..8f297a71af 100644--- a/v3/@claude-flow/integration/src/feature-flags.ts+++ b/v3/@claude-flow/integration/src/feature-flags.ts@@ -400,13 +400,12 @@ export class FeatureFlagManager extends EventEmitter {},};- const base = Object.fromEntries(- Object.entries(FEATURE_FLAG_DEFINITIONS).map(- ([flag, info]) => [flag, info.defaultValue]- )- ) as FeatureFlags;+ const base: Record<string, boolean> = {};+ for (const [flag, info] of Object.entries(FEATURE_FLAG_DEFINITIONS)) {+ base[flag] = info.defaultValue;+ }- return { ...base, ...profiles[profile] };+ return { ...base, ...profiles[profile] } as FeatureFlags;}// ===== Private Methods =====diff --git a/v3/@claude-flow/integration/src/index.ts b/v3/@claude-flow/integration/src/index.tsindex 76d6b0f03d..5b28aad1e5 100644--- a/v3/@claude-flow/integration/src/index.ts+++ b/v3/@claude-flow/integration/src/index.ts@@ -278,7 +278,6 @@ export {export {MultiModelRouter,createMultiModelRouter,- getDefaultMultiModelRouter,} from './multi-model-router.js';export type {@@ -287,12 +286,10 @@ export type {ProviderConfig,RoutingRule,RoutingMode,- CacheConfig,- BudgetConfig,- MultiModelRouterConfig,- RouteRequest,- RouteResult,- RouterStats,+ RouterConfig as MultiModelRouterConfig,+ RoutingRequest as RouteRequest,+ RoutingResult as RouteResult,+ CostTracker as RouterStats,} from './multi-model-router.js';// ===== Quick Start Utilities =====@@ -310,6 +307,8 @@ export async function quickStart(options?: {}> {const { AgenticFlowBridge } = await import('./agentic-flow-bridge.js');const { FeatureFlagManager } = await import('./feature-flags.js');+ type SONAAdapterType = import('./sona-adapter.js').SONAAdapter;+ type AttentionCoordinatorType = import('./attention-coordinator.js').AttentionCoordinator;const mode = options?.mode || 'standard';const flags = FeatureFlagManager.fromProfile(mode);@@ -321,8 +320,8 @@ export async function quickStart(options?: {await bridge.initialize();- let sona = null;- let attention = null;+ let sona: SONAAdapterType | null = null;+ let attention: AttentionCoordinatorType | null = null;if (flags.enableSONA) {sona = await bridge.getSONAAdapter();diff --git a/v3/@claude-flow/integration/src/swarm-adapter.ts b/v3/@claude-flow/integration/src/swarm-adapter.tsindex 4bb7563824..045cd121da 100644--- a/v3/@claude-flow/integration/src/swarm-adapter.ts+++ b/v3/@claude-flow/integration/src/swarm-adapter.ts@@ -847,7 +847,8 @@ export class SwarmAdapter extends EventEmitter {private async connectToAgenticFlow(): Promise<void> {try {- const agenticFlowModule = await import('agentic-flow').catch(() => null);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const agenticFlowModule: any = await import('agentic-flow').catch(() => null);if (agenticFlowModule &&diff --git a/v3/@claude-flow/integration/tsconfig.vitest-temp.json b/v3/@claude-flow/integration/tsconfig.vitest-temp.jsondeleted file mode 100644index c315231e15..0000000000--- a/v3/@claude-flow/integration/tsconfig.vitest-temp.json+++ /dev/null@@ -1,38 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "bundler",- "lib": [- "ES2022"- ],- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "declaration": true,- "declarationMap": true,- "sourceMap": true,- "resolveJsonModule": true,- "isolatedModules": true,- "noUnusedLocals": false,- "noUnusedParameters": false,- "noImplicitReturns": true,- "noFallthroughCasesInSwitch": true,- "noImplicitAny": false,- "composite": true,- "incremental": true,- "outDir": "./dist",- "rootDir": "./src",- "emitDeclarationOnly": false,- "tsBuildInfoFile": "/workspaces/claude-flow/v3/node_modules/.pnpm/[email protected]_@[email protected]/node_modules/vitest/dist/vendor/tsconfig.tmp.tsbuildinfo"- },- "include": [- "src/**/*"- ],- "exclude": [- "node_modules",- "dist",- "./dist"- ]-}\ No newline at end of filediff --git a/v3/@claude-flow/memory/src/agentdb-backend.ts b/v3/@claude-flow/memory/src/agentdb-backend.tsindex e886153a7c..17166ac6a6 100644--- a/v3/@claude-flow/memory/src/agentdb-backend.ts+++ b/v3/@claude-flow/memory/src/agentdb-backend.ts@@ -709,16 +709,26 @@ export class AgentDBBackend extends EventEmitter implements IMemoryBackend {* Convert agentdb data to MemoryEntry*/private dataToEntry(id: string, data: any): MemoryEntry {- return createDefaultEntry({+ const now = Date.now();+ return {id,key: data.key || id,content: data.content || '',embedding: data.embedding,- type: data.type || 'general',+ type: data.type || 'semantic',namespace: data.namespace || this.config.namespace,tags: data.tags || [],metadata: data.metadata || {},- });+ ownerId: data.ownerId,+ accessLevel: data.accessLevel || 'private',+ createdAt: data.createdAt || now,+ updatedAt: data.updatedAt || now,+ expiresAt: data.expiresAt,+ version: data.version || 1,+ references: data.references || [],+ accessCount: data.accessCount || 0,+ lastAccessedAt: data.lastAccessedAt || now,+ };}/**diff --git a/v3/@claude-flow/memory/src/cache-manager.ts b/v3/@claude-flow/memory/src/cache-manager.tsindex 83089cf703..2bb67f2e6b 100644--- a/v3/@claude-flow/memory/src/cache-manager.ts+++ b/v3/@claude-flow/memory/src/cache-manager.ts@@ -436,7 +436,7 @@ export class TieredCacheManager<T = MemoryEntry> extends EventEmitter {if (l2Options) {this.l2Loader = l2Options.loader;- this.l2Writer = l2Options.writer;+ this.l2Writer = l2Options.writer ?? null;}// Forward L1 eventsdiff --git a/v3/@claude-flow/memory/src/hybrid-backend.test.ts b/v3/@claude-flow/memory/src/hybrid-backend.test.tsindex 0561f3e0e3..85d990921c 100644--- a/v3/@claude-flow/memory/src/hybrid-backend.test.ts+++ b/v3/@claude-flow/memory/src/hybrid-backend.test.ts@@ -29,8 +29,7 @@ describe('HybridBackend - ADR-009', () => {verbose: false,},agentdb: {- dimensions: 128,- cacheEnabled: true,+ vectorDimension: 128,},embeddingGenerator: mockEmbedding,dualWrite: true,diff --git a/v3/@claude-flow/memory/src/migration.ts b/v3/@claude-flow/memory/src/migration.tsindex 5e725fe723..1a058311c3 100644--- a/v3/@claude-flow/memory/src/migration.ts+++ b/v3/@claude-flow/memory/src/migration.ts@@ -584,8 +584,8 @@ export class MemoryMigrator extends EventEmitter {// Parse common typesif (value === 'true') value = true;else if (value === 'false') value = false;- else if (/^\d+$/.test(value as string)) value = parseInt(value as string, 10);- else if (value.startsWith('[') && value.endsWith(']')) {+ else if (typeof value === 'string' && /^\d+$/.test(value)) value = parseInt(value, 10);+ else if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) {try {value = JSON.parse(value.replace(/'/g, '"'));} catch {diff --git a/v3/@claude-flow/memory/src/query-builder.ts b/v3/@claude-flow/memory/src/query-builder.tsindex 7e50e67327..0358ea7446 100644--- a/v3/@claude-flow/memory/src/query-builder.ts+++ b/v3/@claude-flow/memory/src/query-builder.ts@@ -527,7 +527,7 @@ export const QueryTemplates = {limit: number = 100): MemoryQuery {const builder = query()- .updatedBefore(Date.now() - staleThresholdMs)+ .updatedBetween(0, Date.now() - staleThresholdMs).sortBy('lastAccessedAt', 'asc').limit(limit);diff --git a/v3/@claude-flow/memory/tsconfig.vitest-temp.json b/v3/@claude-flow/memory/tsconfig.vitest-temp.jsondeleted file mode 100644index c315231e15..0000000000--- a/v3/@claude-flow/memory/tsconfig.vitest-temp.json+++ /dev/null@@ -1,38 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "bundler",- "lib": [- "ES2022"- ],- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "declaration": true,- "declarationMap": true,- "sourceMap": true,- "resolveJsonModule": true,- "isolatedModules": true,- "noUnusedLocals": false,- "noUnusedParameters": false,- "noImplicitReturns": true,- "noFallthroughCasesInSwitch": true,- "noImplicitAny": false,- "composite": true,- "incremental": true,- "outDir": "./dist",- "rootDir": "./src",- "emitDeclarationOnly": false,- "tsBuildInfoFile": "/workspaces/claude-flow/v3/node_modules/.pnpm/[email protected]_@[email protected]/node_modules/vitest/dist/vendor/tsconfig.tmp.tsbuildinfo"- },- "include": [- "src/**/*"- ],- "exclude": [- "node_modules",- "dist",- "./dist"- ]-}\ No newline at end of filediff --git a/v3/@claude-flow/shared/src/core/config/loader.ts b/v3/@claude-flow/shared/src/core/config/loader.tsindex 9a33aab925..a3e6aca31c 100644--- a/v3/@claude-flow/shared/src/core/config/loader.ts+++ b/v3/@claude-flow/shared/src/core/config/loader.ts@@ -87,23 +87,24 @@ function loadEnvConfig(): Partial<SystemConfig> {// Memory typeif (process.env.CLAUDE_FLOW_MEMORY_TYPE) {- const memoryType = process.env.CLAUDE_FLOW_MEMORY_TYPE as SystemConfig['memory']['type'];+ const memoryType = process.env.CLAUDE_FLOW_MEMORY_TYPE as NonNullable<SystemConfig['memory']>['type'];if (['sqlite', 'agentdb', 'hybrid', 'redis', 'memory'].includes(memoryType)) {config.memory = {- ...defaultSystemConfig.memory,+ ...(defaultSystemConfig.memory ?? { type: 'hybrid' }),type: memoryType,};}}// MCP transport+ const defaultMcp = defaultSystemConfig.mcp ?? { name: 'claude-flow', version: '3.0.0', transport: { type: 'stdio' as const } };if (process.env.CLAUDE_FLOW_MCP_TRANSPORT) {const transport = process.env.CLAUDE_FLOW_MCP_TRANSPORT as 'stdio' | 'http' | 'websocket';if (['stdio', 'http', 'websocket'].includes(transport)) {config.mcp = {- ...defaultSystemConfig.mcp,+ ...defaultMcp,transport: {- ...defaultSystemConfig.mcp.transport,+ ...defaultMcp.transport,type: transport,},};@@ -113,21 +114,22 @@ function loadEnvConfig(): Partial<SystemConfig> {if (process.env.CLAUDE_FLOW_MCP_PORT) {config.mcp = {...config.mcp,- ...defaultSystemConfig.mcp,+ ...defaultMcp,transport: {...config.mcp?.transport,- ...defaultSystemConfig.mcp.transport,+ ...defaultMcp.transport,port: parseInt(process.env.CLAUDE_FLOW_MCP_PORT, 10),},};}// Swarm topology+ 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 SystemConfig['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)) {config.swarm = {- ...defaultSystemConfig.swarm,+ ...defaultSwarm,topology,};}diff --git a/v3/@claude-flow/shared/src/core/config/schema.ts b/v3/@claude-flow/shared/src/core/config/schema.tsindex 63ffa7b47b..dabfeaa95f 100644--- a/v3/@claude-flow/shared/src/core/config/schema.ts+++ b/v3/@claude-flow/shared/src/core/config/schema.ts@@ -166,11 +166,23 @@ export const SystemConfigSchema = z.object({/*** Export schema types+ * Using z.output to get post-default types (fields with defaults are required in output)*/-export type AgentConfig = z.infer<typeof AgentConfigSchema>;-export type TaskConfig = z.infer<typeof TaskConfigSchema>;-export type SwarmConfig = z.infer<typeof SwarmConfigSchema>;-export type MemoryConfig = z.infer<typeof MemoryConfigSchema>;-export type MCPServerConfig = z.infer<typeof MCPServerConfigSchema>;-export type OrchestratorConfig = z.infer<typeof OrchestratorConfigSchema>;-export type SystemConfig = z.infer<typeof SystemConfigSchema>;+export type AgentConfig = z.output<typeof AgentConfigSchema>;+export type TaskConfig = z.output<typeof TaskConfigSchema>;+export type SwarmConfig = z.output<typeof SwarmConfigSchema>;+export type MemoryConfig = z.output<typeof MemoryConfigSchema>;+export type MCPServerConfig = z.output<typeof MCPServerConfigSchema>;+export type OrchestratorConfig = z.output<typeof OrchestratorConfigSchema>;+export type SystemConfig = z.output<typeof SystemConfigSchema>;++/**+ * Input types (for validation before defaults are applied)+ */+export type AgentConfigInput = z.input<typeof AgentConfigSchema>;+export type TaskConfigInput = z.input<typeof TaskConfigSchema>;+export type SwarmConfigInput = z.input<typeof SwarmConfigSchema>;+export type MemoryConfigInput = z.input<typeof MemoryConfigSchema>;+export type MCPServerConfigInput = z.input<typeof MCPServerConfigSchema>;+export type OrchestratorConfigInput = z.input<typeof OrchestratorConfigSchema>;+export type SystemConfigInput = z.input<typeof SystemConfigSchema>;diff --git a/v3/@claude-flow/shared/src/core/config/validator.ts b/v3/@claude-flow/shared/src/core/config/validator.tsindex 560f5bc033..134b82f57d 100644--- a/v3/@claude-flow/shared/src/core/config/validator.ts+++ b/v3/@claude-flow/shared/src/core/config/validator.ts@@ -3,7 +3,7 @@* Validation logic using Zod schemas*/-import type { ZodError, ZodSchema } from 'zod';+import { z, type ZodError } from 'zod';import {AgentConfigSchema,TaskConfigSchema,@@ -52,21 +52,27 @@ function zodErrorToValidationErrors(error: ZodError): ValidationError[] {/*** Generic validation function+ * Uses parse + try/catch to get output types with defaults applied*/-function validate<T>(schema: ZodSchema<T>, data: unknown): ValidationResult<T> {- const result = schema.safeParse(data);-- if (result.success) {+function validate<TInput, TOutput>(+ schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,+ data: unknown+): ValidationResult<TOutput> {+ try {+ const parsed = schema.parse(data);return {success: true,- data: result.data,+ data: parsed,};+ } catch (error) {+ if (error instanceof z.ZodError) {+ return {+ success: false,+ errors: zodErrorToValidationErrors(error),+ };+ }+ throw error;}-- return {- success: false,- errors: zodErrorToValidationErrors(result.error),- };}/**@@ -125,7 +131,11 @@ export class ConfigValidator {/*** Validate and throw on error*/- static validateOrThrow<T>(schema: ZodSchema<T>, data: unknown, configName: string): T {+ static validateOrThrow<TInput, TOutput>(+ schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,+ data: unknown,+ configName: string+ ): TOutput {const result = validate(schema, data);if (!result.success) {@@ -190,7 +200,10 @@ export class ConfigValidator {/*** Check if data matches schema*/- static isValid<T>(schema: ZodSchema<T>, data: unknown): boolean {+ static isValid<TInput, TOutput>(+ schema: z.ZodType<TOutput, z.ZodTypeDef, TInput>,+ data: unknown+ ): boolean {return validate(schema, data).success;}}diff --git a/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts b/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.tsindex 6e44e1ecf2..16a6cf0852 100644--- a/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts+++ b/v3/@claude-flow/shared/src/core/interfaces/coordinator.interface.ts@@ -311,3 +311,53 @@ export interface IOrchestratorMetrics {cpuUsage: NodeJS.CpuUsage;timestamp: Date;}++/**+ * Main orchestrator interface - facade for all orchestration capabilities+ */+export interface IOrchestrator {+ /**+ * Initialize the orchestrator+ */+ initialize(): Promise<void>;++ /**+ * Shutdown the orchestrator+ */+ shutdown(): Promise<void>;++ /**+ * Get health status+ */+ getHealthStatus(): Promise<IHealthStatus>;++ /**+ * Get orchestrator metrics+ */+ getMetrics(): Promise<IOrchestratorMetrics>;++ /**+ * Spawn a new agent+ */+ spawnAgent(config: IAgentConfig): Promise<IAgent>;++ /**+ * Terminate an agent+ */+ terminateAgent(agentId: string, reason?: string): Promise<void>;++ /**+ * Submit a task+ */+ submitTask(task: ITask): Promise<ITaskResult>;++ /**+ * Get task by ID+ */+ getTask(taskId: string): Promise<ITask | undefined>;++ /**+ * Cancel a task+ */+ cancelTask(taskId: string): Promise<void>;+}diff --git a/v3/@claude-flow/shared/src/core/orchestrator/index.ts b/v3/@claude-flow/shared/src/core/orchestrator/index.tsindex 5c056d1339..14d33e66f7 100644--- a/v3/@claude-flow/shared/src/core/orchestrator/index.ts+++ b/v3/@claude-flow/shared/src/core/orchestrator/index.ts@@ -23,18 +23,19 @@ export * from './lifecycle-manager.js';export * from './event-coordinator.js';/**- * Orchestrator configuration+ * Orchestrator facade configuration+ * (Note: For schema-validated config, use OrchestratorConfig from config/schema.ts)*/-export interface OrchestratorConfig {+export interface OrchestratorFacadeConfig {session: SessionManagerConfig;health: HealthMonitorConfig;lifecycle: LifecycleManagerConfig;}/**- * Default orchestrator configuration+ * Default orchestrator facade configuration*/-export const defaultOrchestratorConfig: OrchestratorConfig = {+export const defaultOrchestratorFacadeConfig: OrchestratorFacadeConfig = {session: {persistSessions: true,dataDir: './data',@@ -57,11 +58,11 @@ export const defaultOrchestratorConfig: OrchestratorConfig = {/*** Create orchestrator components*/-export function createOrchestrator(config: Partial<OrchestratorConfig> = {}) {- const mergedConfig: OrchestratorConfig = {- session: { ...defaultOrchestratorConfig.session, ...config.session },- health: { ...defaultOrchestratorConfig.health, ...config.health },- lifecycle: { ...defaultOrchestratorConfig.lifecycle, ...config.lifecycle },+export function createOrchestrator(config: Partial<OrchestratorFacadeConfig> = {}) {+ const mergedConfig: OrchestratorFacadeConfig = {+ session: { ...defaultOrchestratorFacadeConfig.session, ...config.session },+ health: { ...defaultOrchestratorFacadeConfig.health, ...config.health },+ lifecycle: { ...defaultOrchestratorFacadeConfig.lifecycle, ...config.lifecycle },};const eventBus = new EventBus();diff --git a/v3/@claude-flow/shared/src/events/index.ts b/v3/@claude-flow/shared/src/events/index.tsindex fe90013570..eae412f364 100644--- a/v3/@claude-flow/shared/src/events/index.ts+++ b/v3/@claude-flow/shared/src/events/index.ts@@ -10,8 +10,8 @@* @module v3/shared/events*/-// Domain Events-export {+// Domain Event Types+export type {DomainEvent,AllDomainEvents,AgentSpawnedEvent,@@ -37,6 +37,10 @@ export {SwarmPhaseChangedEvent,SwarmMilestoneReachedEvent,SwarmErrorEvent,+} from './domain-events.js';++// Domain Event Factory Functions+export {createAgentSpawnedEvent,createAgentStartedEvent,createAgentStoppedEvent,@@ -54,8 +58,8 @@ export {} from './domain-events.js';// Event Store-export {- EventStore,+export { EventStore } from './event-store.js';+export type {EventStoreConfig,EventFilter,EventSnapshot,@@ -66,10 +70,12 @@ export {export {Projection,AgentStateProjection,- AgentProjectionState,TaskHistoryProjection,- TaskProjectionState,MemoryIndexProjection,+} from './projections.js';+export type {+ AgentProjectionState,+ TaskProjectionState,MemoryProjectionState,} from './projections.js';diff --git a/v3/@claude-flow/shared/src/events/state-reconstructor.ts b/v3/@claude-flow/shared/src/events/state-reconstructor.tsindex ea00022034..15ef2d3369 100644--- a/v3/@claude-flow/shared/src/events/state-reconstructor.ts+++ b/v3/@claude-flow/shared/src/events/state-reconstructor.ts@@ -7,7 +7,8 @@* @module v3/shared/events/state-reconstructor*/-import { EventStore, DomainEvent, Snapshot } from './event-store.js';+import { EventStore, type EventSnapshot } from './event-store.js';+import type { DomainEvent } from './domain-events.js';/*** Aggregate root interface@@ -133,7 +134,7 @@ export class StateReconstructor {/*** Apply snapshot to aggregate*/- private applySnapshot(aggregate: AggregateRoot, snapshot: Snapshot): void {+ private applySnapshot(aggregate: AggregateRoot, snapshot: EventSnapshot): void {// Type assertion for aggregate that has restoreFromSnapshotconst restorable = aggregate as AggregateRoot & {restoreFromSnapshot?(state: unknown): void;@@ -151,7 +152,7 @@ export class StateReconstructor {* Create snapshot for aggregate*/private async createSnapshot(aggregate: AggregateRoot): Promise<void> {- const snapshot: Snapshot = {+ const snapshot: EventSnapshot = {aggregateId: aggregate.id,aggregateType: this.getAggregateType(aggregate),version: aggregate.version,diff --git a/v3/@claude-flow/shared/src/index.ts b/v3/@claude-flow/shared/src/index.tsindex 46792786e5..023128a676 100644--- a/v3/@claude-flow/shared/src/index.ts+++ b/v3/@claude-flow/shared/src/index.ts@@ -5,30 +5,186 @@* Based on ADR-002 (DDD) and ADR-006 (Unified Memory Service)*/-// Types - Shared type definitions+// =============================================================================+// Types - Primary type definitions (from ./types.js)+// =============================================================================export * from './types.js';-// Events - Event bus and event sourcing (existing)-export * from './events.js';+// =============================================================================+// Events - Event bus and basic event interfaces (from ./events.js)+// =============================================================================+export { EventBus } from './events.js';+export type { IEventBus, EventFilter } from './events.js';-// Event Sourcing - ADR-007 (Event Sourcing for State Changes)-export * from './events/index.js';+// =============================================================================+// Event Sourcing - ADR-007 Domain events and event store+// (from ./events/index.js - no duplicates with ./events.js)+// =============================================================================+export type {+ DomainEvent,+ AllDomainEvents,+ AgentSpawnedEvent,+ AgentStartedEvent,+ AgentStoppedEvent,+ AgentFailedEvent,+ AgentStatusChangedEvent,+ AgentTaskAssignedEvent,+ AgentTaskCompletedEvent,+ TaskCreatedEvent,+ TaskStartedEvent,+ TaskCompletedEvent,+ TaskFailedEvent,+ TaskBlockedEvent,+ TaskQueuedEvent,+ MemoryStoredEvent,+ MemoryRetrievedEvent,+ MemoryDeletedEvent,+ MemoryExpiredEvent,+ SwarmInitializedEvent,+ SwarmScaledEvent,+ SwarmTerminatedEvent,+ SwarmPhaseChangedEvent,+ SwarmMilestoneReachedEvent,+ SwarmErrorEvent,+ EventStoreConfig,+ EventSnapshot,+ EventStoreStats,+ AgentProjectionState,+ TaskProjectionState,+ MemoryProjectionState,+ AggregateRoot,+ ReconstructorOptions,+} from './events/index.js';-// Plugin System - ADR-004 (Plugin-Based Architecture)-export * from './plugin-interface.js';+export {+ createAgentSpawnedEvent,+ createAgentStartedEvent,+ createAgentStoppedEvent,+ createAgentFailedEvent,+ createTaskCreatedEvent,+ createTaskStartedEvent,+ createTaskCompletedEvent,+ createTaskFailedEvent,+ createMemoryStoredEvent,+ createMemoryRetrievedEvent,+ createMemoryDeletedEvent,+ createSwarmInitializedEvent,+ createSwarmScaledEvent,+ createSwarmTerminatedEvent,+ EventStore,+ Projection,+ AgentStateProjection,+ TaskHistoryProjection,+ MemoryIndexProjection,+ StateReconstructor,+ createStateReconstructor,+ AgentAggregate,+ TaskAggregate,+} from './events/index.js';++// =============================================================================+// Plugin System - ADR-004+// =============================================================================export * from './plugin-loader.js';export * from './plugin-registry.js';-export * from './plugins/index.js';-// Re-export from submodules for convenience-export * from './types/index.js';-export * from './core/index.js';+// =============================================================================+// Core - DDD interfaces, config, orchestrator+// Note: Only export non-overlapping items from core to avoid duplicates with types.js+// =============================================================================+export {+ // Event Bus+ createEventBus,+ // Orchestrator+ createOrchestrator,+ TaskManager,+ SessionManager,+ HealthMonitor,+ LifecycleManager,+ EventCoordinator,+ // Config validation/loading+ ConfigLoader,+ loadConfig,+ ConfigValidator,+ validateAgentConfig,+ validateTaskConfig,+ validateSwarmConfig,+ validateMemoryConfig,+ validateMCPServerConfig,+ validateOrchestratorConfig,+ validateSystemConfig,+ // Defaults+ defaultAgentConfig,+ defaultTaskConfig,+ defaultSwarmConfigCore,+ defaultMemoryConfig,+ defaultMCPServerConfig,+ defaultOrchestratorConfig,+ defaultSystemConfig,+ agentTypePresets,+ mergeWithDefaults,+} from './core/index.js';++export type {+ // Config types+ LoadedConfig,+ ConfigSource,+ ValidationResult,+ ValidationError,+ // Orchestrator types+ OrchestratorFacadeConfig,+ OrchestratorComponents,+ SessionManagerConfig,+ HealthMonitorConfig,+ LifecycleManagerConfig,+ // Schema types (from config - note these extend the basic types from types.js)+ AgentConfig,+ TaskConfig,+ SwarmConfig as SwarmConfigSchema,+ MemoryConfig,+ MCPServerConfig,+ OrchestratorConfig,+ SystemConfig,+ AgentConfigInput,+ TaskConfigInput,+ SwarmConfigInput,+ MemoryConfigInput,+ MCPServerConfigInput,+ OrchestratorConfigInput,+ SystemConfigInput,+ // Interface types+ ITask,+ ITaskCreate,+ ITaskResult,+ IAgent,+ IAgentConfig,+ IEventBus as ICoreEventBus,+ IMemoryBackend as ICoreMemoryBackend,+ ISwarmConfig,+ ISwarmState,+ ICoordinator,+ ICoordinationManager,+ IHealthStatus,+ IComponentHealth,+ IHealthMonitor,+ IMetricsCollector,+ IOrchestratorMetrics,+ IOrchestrator,+ SwarmTopology,+ CoordinationStatus,+} from './core/index.js';-// Hooks System - Extensible hook points for tool execution and lifecycle events+// =============================================================================+// Hooks System+// =============================================================================export * from './hooks/index.js';-// Security Utilities - Secure random generation, input validation+// =============================================================================+// Security Utilities+// =============================================================================export * from './security/index.js';-// Resilience Patterns - Retry, circuit breaker, rate limiting+// =============================================================================+// Resilience Patterns+// =============================================================================export * from './resilience/index.js';diff --git a/v3/@claude-flow/shared/src/plugin-interface.ts b/v3/@claude-flow/shared/src/plugin-interface.tsindex 99b0a3c201..bc8b2058e7 100644--- a/v3/@claude-flow/shared/src/plugin-interface.ts+++ b/v3/@claude-flow/shared/src/plugin-interface.ts@@ -6,9 +6,9 @@* Enables modular extension points for agents, tasks, MCP tools, CLI commands, and memory backends*/-import type { IEventBus } from '../../../core/interfaces/event.interface.js';-import type { IAgentConfig } from '../../../core/interfaces/agent.interface.js';-import type { MCPTool } from '../../../types/mcp.types.js';+import type { IEventBus } from './core/interfaces/event.interface.js';+import type { IAgentConfig } from './core/interfaces/agent.interface.js';+import type { MCPTool } from './types/mcp.types.js';/*** Logger interface for plugin contextdiff --git a/v3/@claude-flow/shared/src/resilience/index.ts b/v3/@claude-flow/shared/src/resilience/index.tsindex b7f0d6aac3..aec3d097a8 100644--- a/v3/@claude-flow/shared/src/resilience/index.ts+++ b/v3/@claude-flow/shared/src/resilience/index.ts@@ -9,30 +9,18 @@* @module v3/shared/resilience*/-export {- retry,- RetryOptions,- RetryError,- type RetryResult,-} from './retry.js';+// Retry+export { retry, RetryError } from './retry.js';+export type { RetryOptions, RetryResult } from './retry.js';-export {- CircuitBreaker,- CircuitBreakerOptions,- CircuitBreakerState,- type CircuitBreakerStats,-} from './circuit-breaker.js';+// Circuit Breaker+export { CircuitBreaker } from './circuit-breaker.js';+export type { CircuitBreakerOptions, CircuitBreakerStats } from './circuit-breaker.js';-export {- RateLimiter,- RateLimiterOptions,- SlidingWindowRateLimiter,- TokenBucketRateLimiter,- type RateLimitResult,-} from './rate-limiter.js';+// Rate Limiter+export { SlidingWindowRateLimiter, TokenBucketRateLimiter } from './rate-limiter.js';+export type { RateLimiter, RateLimiterOptions, RateLimitResult } from './rate-limiter.js';-export {- Bulkhead,- BulkheadOptions,- type BulkheadStats,-} from './bulkhead.js';+// Bulkhead+export { Bulkhead } from './bulkhead.js';+export type { BulkheadOptions, BulkheadStats } from './bulkhead.js';diff --git a/v3/@claude-flow/shared/tsconfig.vitest-temp.json b/v3/@claude-flow/shared/tsconfig.vitest-temp.jsondeleted file mode 100644index c315231e15..0000000000--- a/v3/@claude-flow/shared/tsconfig.vitest-temp.json+++ /dev/null@@ -1,38 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "bundler",- "lib": [- "ES2022"- ],- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "forceConsistentCasingInFileNames": true,- "declaration": true,- "declarationMap": true,- "sourceMap": true,- "resolveJsonModule": true,- "isolatedModules": true,- "noUnusedLocals": false,- "noUnusedParameters": false,- "noImplicitReturns": true,- "noFallthroughCasesInSwitch": true,- "noImplicitAny": false,- "composite": true,- "incremental": true,- "outDir": "./dist",- "rootDir": "./src",- "emitDeclarationOnly": false,- "tsBuildInfoFile": "/workspaces/claude-flow/v3/node_modules/.pnpm/[email protected]_@[email protected]/node_modules/vitest/dist/vendor/tsconfig.tmp.tsbuildinfo"- },- "include": [- "src/**/*"- ],- "exclude": [- "node_modules",- "dist",- "./dist"- ]-}\ No newline at end of filediff --git a/v3/@claude-flow/swarm/src/consensus/index.ts b/v3/@claude-flow/swarm/src/consensus/index.tsindex 879dd61942..ef0f601235 100644--- a/v3/@claude-flow/swarm/src/consensus/index.ts+++ b/v3/@claude-flow/swarm/src/consensus/index.ts@@ -18,7 +18,7 @@ import { ByzantineConsensus, createByzantineConsensus, ByzantineConfig } from '.import { GossipConsensus, createGossipConsensus, GossipConfig } from './gossip.js';export { RaftConsensus, ByzantineConsensus, GossipConsensus };-export { RaftConfig, ByzantineConfig, GossipConfig };+export type { RaftConfig, ByzantineConfig, GossipConfig };type ConsensusImplementation = RaftConsensus | ByzantineConsensus | GossipConsensus;diff --git a/v3/@claude-flow/swarm/src/shared/events.ts b/v3/@claude-flow/swarm/src/shared/events.tsnew file mode 100644index 0000000000..739db2b627--- /dev/null+++ b/v3/@claude-flow/swarm/src/shared/events.ts@@ -0,0 +1,133 @@+/**+ * Re-export shared events from @claude-flow/shared+ * This enables local relative imports from '../shared/events'+ */+export {+ EventBus,+} from '@claude-flow/shared';++export type {+ IEventBus,+ EventFilter,+} from '@claude-flow/shared';++import type { SwarmEvent, EventType } from './types';++// Helper function to generate event IDs+function generateEventId(): string {+ return `evt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;+}++// Helper function to create a base SwarmEvent+function createSwarmEvent<T>(+ type: EventType,+ source: string,+ payload: T+): SwarmEvent<T> {+ return {+ id: generateEventId(),+ type,+ timestamp: new Date(),+ source,+ payload,+ };+}++// Agent events+export function agentSpawnedEvent(agentId: string, state: unknown): SwarmEvent<{ agentId: string; state: unknown }> {+ return createSwarmEvent('agent:spawned', agentId, { agentId, state });+}++export function agentStatusChangedEvent(+ agentId: string,+ previousStatus: string,+ newStatus: string+): SwarmEvent<{ agentId: string; previousStatus: string; newStatus: string }> {+ return createSwarmEvent('agent:status-changed', agentId, { agentId, previousStatus, newStatus });+}++export function agentErrorEvent(+ agentId: string,+ error: Error | string+): SwarmEvent<{ agentId: string; error: string; stack?: string }> {+ return createSwarmEvent('agent:error', agentId, {+ agentId,+ error: error instanceof Error ? error.message : error,+ stack: error instanceof Error ? error.stack : undefined,+ });+}++// Task events+export function taskCreatedEvent(taskId: string, taskData: unknown): SwarmEvent<{ taskId: string; data: unknown }> {+ return createSwarmEvent('task:created', 'swarm', { taskId, data: taskData });+}++export function taskQueuedEvent(taskId: string, queuePosition: number): SwarmEvent<{ taskId: string; queuePosition: number }> {+ return createSwarmEvent('task:queued', 'swarm', { taskId, queuePosition });+}++export function taskStartedEvent(taskId: string, agentId: string): SwarmEvent<{ taskId: string; agentId: string }> {+ return createSwarmEvent('task:started', agentId, { taskId, agentId });+}++export function taskAssignedEvent(taskId: string, agentId: string): SwarmEvent<{ taskId: string; agentId: string }> {+ return createSwarmEvent('task:assigned', 'swarm', { taskId, agentId });+}++export function taskCompletedEvent(taskId: string, result: unknown): SwarmEvent<{ taskId: string; result: unknown }> {+ return createSwarmEvent('task:completed', 'swarm', { taskId, result });+}++export function taskFailedEvent(+ taskId: string,+ error: Error | string+): SwarmEvent<{ taskId: string; error: string; stack?: string }> {+ return createSwarmEvent('task:failed', 'swarm', {+ taskId,+ error: error instanceof Error ? error.message : error,+ stack: error instanceof Error ? error.stack : undefined,+ });+}++export function taskBlockedEvent(+ taskId: string,+ reason: string,+ blockedBy?: string+): SwarmEvent<{ taskId: string; reason: string; blockedBy?: string }> {+ return createSwarmEvent('task:blocked', 'swarm', { taskId, reason, blockedBy });+}++// Swarm lifecycle events+export function swarmInitializedEvent(+ swarmId: string,+ config: unknown+): SwarmEvent<{ swarmId: string; config: unknown }> {+ return createSwarmEvent('swarm:initialized', 'swarm', { swarmId, config });+}++export function swarmPhaseChangedEvent(+ swarmId: string,+ previousPhase: string,+ newPhase: string+): SwarmEvent<{ swarmId: string; previousPhase: string; newPhase: string }> {+ return createSwarmEvent('swarm:phase-changed', 'swarm', { swarmId, previousPhase, newPhase });+}++export function swarmMilestoneReachedEvent(+ swarmId: string,+ milestone: string,+ data: unknown = {}+): SwarmEvent<{ swarmId: string; milestone: string; data: unknown }> {+ return createSwarmEvent('swarm:milestone-reached', 'swarm', { swarmId, milestone, data });+}++export function swarmErrorEvent(+ swarmId: string,+ error: Error | string+): SwarmEvent<{ swarmId: string; error: string; stack?: string }> {+ return createSwarmEvent('swarm:error', 'swarm', {+ swarmId,+ error: error instanceof Error ? error.message : error,+ stack: error instanceof Error ? error.stack : undefined,+ });+}diff --git a/v3/@claude-flow/swarm/src/shared/types.ts b/v3/@claude-flow/swarm/src/shared/types.tsnew file mode 100644index 0000000000..1e0dba0e48--- /dev/null+++ b/v3/@claude-flow/swarm/src/shared/types.ts@@ -0,0 +1,41 @@+/**+ * Re-export shared types from @claude-flow/shared+ * This enables local relative imports from '../shared/types'+ */+export type {+ AgentId,+ AgentRole,+ AgentDomain,+ AgentStatus,+ AgentDefinition,+ AgentState,+ AgentCapability,+ AgentMetrics,+ TaskType,+ TaskId,+ TaskStatus,+ TaskPriority,+ TaskDefinition,+ SwarmEvent,+ EventType,+ EventHandler,+ SwarmConfig,+ TopologyType,+ IAgent,+ ITask,+ // Additional types needed by swarm module+ TaskResult,+ TaskMetadata,+ TaskResultMetrics,+ PhaseId,+ PhaseDefinition,+ MilestoneDefinition,+ SwarmState,+ SwarmMetrics,+ SwarmMessage,+ MessageType,+ MessageHandler,+} from '@claude-flow/shared';++// Value exports (constants)+export { V3_PERFORMANCE_TARGETS } from '@claude-flow/shared';diff --git a/v3/@claude-flow/transport/README.md b/v3/@claude-flow/transport/README.mdnew file mode 100644index 0000000000..e77315ad15--- /dev/null+++ b/v3/@claude-flow/transport/README.md@@ -0,0 +1,107 @@+# @claude-flow/transport++Transport layer module for Claude-Flow V3.++## Overview++This module provides transport layer implementations for agent communication, including QUIC, WebSocket, and HTTP/2 protocols.++## Features++- **QUIC Transport**: High-performance UDP-based communication+- **WebSocket**: Real-time bidirectional communication+- **HTTP/2**: Multiplexed request/response patterns+- **Connection Pooling**: Efficient connection management+- **Load Balancing**: Distribute traffic across endpoints++## Installation++```bash+npm install @claude-flow/transport+```++## Usage++```typescript+import { QUICTransport, WebSocketTransport } from '@claude-flow/transport';++// QUIC Transport (recommended for high-throughput)+const quic = new QUICTransport({+ host: 'localhost',+ port: 4433,+ tls: {+ cert: './cert.pem',+ key: './key.pem',+ },+});++await quic.listen();++// WebSocket Transport+const ws = new WebSocketTransport({+ url: 'ws://localhost:8080',+ reconnect: true,+});++await ws.connect();++// Send message+await ws.send({+ type: 'task',+ payload: { /* ... */ },+});++// Receive messages+ws.on('message', (msg) => {+ console.log('Received:', msg);+});+```++## API Reference++### QUICTransport++High-performance QUIC-based transport.++#### Methods++- `listen()` - Start listening for connections+- `connect(endpoint)` - Connect to remote endpoint+- `send(message)` - Send message+- `close()` - Close transport++### WebSocketTransport++WebSocket-based transport for real-time communication.++#### Methods++- `connect()` - Establish WebSocket connection+- `send(message)` - Send message+- `on(event, handler)` - Register event handler+- `close()` - Close connection++## Configuration++```typescript+interface TransportConfig {+ protocol: 'quic' | 'websocket' | 'http2';+ host?: string;+ port?: number;+ tls?: TLSConfig;+ poolSize?: number;+ timeout?: number;+}+```++## Performance++| Protocol | Latency | Throughput | Use Case |+|----------|---------|------------|----------|+| QUIC | <5ms | High | Inter-agent messaging |+| WebSocket | <10ms | Medium | Real-time updates |+| HTTP/2 | <20ms | Medium | Request/response |++## License++MITdiff --git a/v3/@claude-flow/transport/src/__tests__/quic-transport.test.ts b/v3/@claude-flow/transport/src/__tests__/quic-transport.test.tsnew file mode 100644index 0000000000..7a53fa71b7--- /dev/null+++ b/v3/@claude-flow/transport/src/__tests__/quic-transport.test.ts@@ -0,0 +1,109 @@+/**+ * Tests for QUIC Transport+ */+import { describe, it, expect } from 'vitest';+import {+ QUICClient,+ QUICServer,+ QUICConnectionPool,+ createQUICClient,+ createQUICServer,+ createConnectionPool,+} from '../index.js';++describe('QUICClient', () => {+ describe('Configuration', () => {+ it('should create client with config', () => {+ const client = createQUICClient({+ host: 'localhost',+ port: 4433,+ });++ expect(client).toBeInstanceOf(QUICClient);+ });++ it('should accept TLS options', () => {+ const client = createQUICClient({+ host: 'localhost',+ port: 4433,+ cert: './cert.pem',+ key: './key.pem',+ alpn: ['h3'],+ });++ expect(client).toBeDefined();+ });+ });++ describe('Event Emission', () => {+ it('should be an EventEmitter', () => {+ const client = createQUICClient({+ host: 'localhost',+ port: 4433,+ });++ expect(typeof client.on).toBe('function');+ expect(typeof client.emit).toBe('function');+ });+ });+});++describe('QUICServer', () => {+ describe('Configuration', () => {+ it('should create server with config', () => {+ const server = createQUICServer({+ host: '0.0.0.0',+ port: 4433,+ cert: './cert.pem',+ key: './key.pem',+ });++ expect(server).toBeInstanceOf(QUICServer);+ });+ });++ describe('Event Emission', () => {+ it('should be an EventEmitter', () => {+ const server = createQUICServer({+ host: '0.0.0.0',+ port: 4433,+ cert: './cert.pem',+ key: './key.pem',+ });++ expect(typeof server.on).toBe('function');+ expect(typeof server.emit).toBe('function');+ });+ });+});++describe('QUICConnectionPool', () => {+ describe('Configuration', () => {+ it('should create pool with config', () => {+ const pool = createConnectionPool({+ maxConnections: 10,+ minConnections: 2,+ idleTimeout: 30000,+ });++ expect(pool).toBeInstanceOf(QUICConnectionPool);+ });++ it('should use default values', () => {+ const pool = createConnectionPool();+ expect(pool).toBeDefined();+ });+ });+});++describe('Transport Types', () => {+ it('should define connection states', () => {+ const states = ['connecting', 'connected', 'disconnecting', 'disconnected', 'error'];+ expect(states).toHaveLength(5);+ });++ it('should define stream states', () => {+ const states = ['open', 'half-closed-local', 'half-closed-remote', 'closed'];+ expect(states).toHaveLength(4);+ });+});