🌊 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:
rUv791b9457461e
diff --git a/.claude/helpers/checkpoint-manager.sh b/.claude/helpers/checkpoint-manager.shindex aa6b748fd5..159832d665 100755--- a/.claude/helpers/checkpoint-manager.sh+++ b/.claude/helpers/checkpoint-manager.sh@@ -7,6 +7,8 @@ set -eCHECKPOINT_DIR=".claude-flow/checkpoints"METRICS_DIR=".claude-flow/metrics"AUTO_COMMIT_ENABLED=true+AUTO_PUSH_ENABLED=true+PUSH_BATCH_SIZE=5 # Push after this many commitsMIN_CHANGES_THRESHOLD=1# Color codesdiff --git a/v3/@claude-flow/billing/README.md b/v3/@claude-flow/billing/README.mddeleted file mode 100644index 679f84c6bc..0000000000--- a/v3/@claude-flow/billing/README.md+++ /dev/null@@ -1,71 +0,0 @@-# @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/package.json b/v3/@claude-flow/billing/package.jsondeleted file mode 100644index 86a55cbdc3..0000000000--- a/v3/@claude-flow/billing/package.json+++ /dev/null@@ -1,48 +0,0 @@-{- "name": "@claude-flow/billing",- "version": "3.0.0-alpha.1",- "description": "V3 Billing/Metering - Subscription management, usage tracking, quota enforcement",- "type": "module",- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js"- }- },- "files": [- "dist",- "src"- ],- "scripts": {- "build": "tsc",- "test": "vitest run",- "test:watch": "vitest",- "lint": "eslint src --ext .ts",- "clean": "rm -rf dist"- },- "keywords": [- "billing",- "metering",- "subscription",- "quota",- "usage",- "payments",- "claude-flow",- "v3"- ],- "author": "Claude Flow Team",- "license": "MIT",- "devDependencies": {- "typescript": "^5.3.0",- "vitest": "^1.0.0",- "@types/node": "^20.10.0"- },- "peerDependencies": {- "@claude-flow/shared": "^3.0.0-alpha.1"- },- "engines": {- "node": ">=20.0.0"- }-}diff --git a/v3/@claude-flow/billing/src/__tests__/metering-engine.test.ts b/v3/@claude-flow/billing/src/__tests__/metering-engine.test.tsdeleted file mode 100644index e814081d70..0000000000--- a/v3/@claude-flow/billing/src/__tests__/metering-engine.test.ts+++ /dev/null@@ -1,127 +0,0 @@-/**- * 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(() => {- storage = new InMemoryBillingStorage();- engine = new MeteringEngine(storage, {});- });-- describe('Initialization', () => {- it('should initialize successfully', () => {- const newStorage = new InMemoryBillingStorage();- const newEngine = new MeteringEngine(newStorage);- expect(newEngine).toBeDefined();- });-- it('should create engine with factory function', () => {- const factoryEngine = createMeteringEngine({});- 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',- amount: 1000,- timestamp: Date.now(),- billingPeriod: '2026-01',- };-- await storage.saveUsageRecord(record as any);- const records = await storage.getUsageRecords('sub-1', '2026-01');-- expect(records).toHaveLength(1);- expect(records[0].amount).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/index.ts b/v3/@claude-flow/billing/src/index.tsdeleted file mode 100644index 8d44ecca24..0000000000--- a/v3/@claude-flow/billing/src/index.ts+++ /dev/null@@ -1,49 +0,0 @@-/**- * V3 Billing/Metering Module- *- * Usage tracking and billing aligned with agentic-flow@alpha:- * - Subscription management- * - Usage metering- * - Quota tracking- * - Payment processing- *- * @module @claude-flow/billing- */--export * from './types.js';-export * from './metering-engine.js';--// Re-export commonly used items at top level-export {- MeteringEngine,- InMemoryBillingStorage,- createMeteringEngine,- createMeteringEngineWithStorage,-} from './metering-engine.js';--export {- SubscriptionTier,- BillingCycle,- SubscriptionStatus,- UsageMetric,- PaymentProvider,- PaymentStatus,- CouponType,- BillingEventType,-} from './types.js';--export type {- Subscription,- ResourceLimits,- UsageRecord,- UsageSummary,- QuotaCheckResult,- Payment,- Coupon,- AppliedCoupon,- BillingEvent,- BillingEventListener,- MeteringConfig,- IMeteringEngine,- IBillingStorage,-} from './types.js';diff --git a/v3/@claude-flow/billing/src/metering-engine.ts b/v3/@claude-flow/billing/src/metering-engine.tsdeleted file mode 100644index efa88bb3a8..0000000000--- a/v3/@claude-flow/billing/src/metering-engine.ts+++ /dev/null@@ -1,423 +0,0 @@-/**- * V3 Metering Engine Implementation- *- * Usage tracking and metering aligned with agentic-flow@alpha:- * - Real-time usage tracking- * - Buffered writes for performance- * - Quota checking and enforcement- * - Usage aggregation- *- * Performance Targets:- * - Record usage: <5ms- * - Check quota: <10ms- * - Aggregate stats: <50ms- */--import { EventEmitter } from 'events';-import {- UsageMetric,- BillingEventType,-} from './types.js';-import type {- MeteringConfig,- IMeteringEngine,- IBillingStorage,- UsageRecord,- ResourceLimits,- QuotaCheckResult,- UsageSummary,- BillingEvent,- BillingEventListener,-} from './types.js';--// ============================================================================-// In-Memory Storage (for development/testing)-// ============================================================================--export class InMemoryBillingStorage implements IBillingStorage {- private subscriptions = new Map<string, any>();- private usageRecords = new Map<string, UsageRecord[]>();- private payments = new Map<string, any[]>();- private coupons = new Map<string, any>();-- async saveSubscription(subscription: any): Promise<void> {- this.subscriptions.set(subscription.id, subscription);- }-- async getSubscription(subscriptionId: string): Promise<any> {- return this.subscriptions.get(subscriptionId) || null;- }-- async getSubscriptionByUser(userId: string): Promise<any> {- for (const sub of this.subscriptions.values()) {- if (sub.userId === userId) {- return sub;- }- }- return null;- }-- async saveUsageRecord(record: UsageRecord): Promise<void> {- const key = `${record.subscriptionId}:${record.billingPeriod}`;- const records = this.usageRecords.get(key) || [];- records.push(record);- this.usageRecords.set(key, records);- }-- async getUsageRecords(subscriptionId: string, period: string): Promise<UsageRecord[]> {- const key = `${subscriptionId}:${period}`;- return this.usageRecords.get(key) || [];- }-- async savePayment(payment: any): Promise<void> {- const payments = this.payments.get(payment.subscriptionId) || [];- payments.push(payment);- this.payments.set(payment.subscriptionId, payments);- }-- async getPayments(subscriptionId: string): Promise<any[]> {- return this.payments.get(subscriptionId) || [];- }-- async saveCoupon(coupon: any): Promise<void> {- this.coupons.set(coupon.code, coupon);- }-- async getCoupon(code: string): Promise<any> {- return this.coupons.get(code) || null;- }-- async incrementCouponUsage(code: string): Promise<void> {- const coupon = this.coupons.get(code);- if (coupon) {- coupon.currentUses++;- }- }-}--// ============================================================================-// Metering Engine Implementation-// ============================================================================--export class MeteringEngine extends EventEmitter implements IMeteringEngine {- private readonly config: Required<MeteringConfig>;- private readonly storage: IBillingStorage;- private buffer: UsageRecord[] = [];- private flushTimer?: NodeJS.Timeout;- private usageCache: Map<string, Map<UsageMetric, number>> = new Map();- private billingListeners: Set<BillingEventListener> = new Set();-- constructor(storage: IBillingStorage, config?: Partial<MeteringConfig>) {- super();- this.storage = storage;- this.config = {- enabled: config?.enabled ?? true,- bufferSize: config?.bufferSize ?? 100,- flushInterval: config?.flushInterval ?? 5000,- softLimitPercent: config?.softLimitPercent ?? 80,- hardLimitPercent: config?.hardLimitPercent ?? 100,- };-- if (this.config.enabled) {- this.startFlushTimer();- }- }-- async recordUsage(- record: Omit<UsageRecord, 'id' | 'timestamp' | 'billingPeriod'>- ): Promise<void> {- if (!this.config.enabled) return;-- const fullRecord: UsageRecord = {- ...record,- id: this.generateId(),- timestamp: new Date(),- billingPeriod: this.getCurrentBillingPeriod(),- };-- // Update cache- const userMetrics = this.usageCache.get(record.subscriptionId) || new Map();- const current = userMetrics.get(record.metric) || 0;- userMetrics.set(record.metric, current + record.amount);- this.usageCache.set(record.subscriptionId, userMetrics);-- // Buffer the record- this.buffer.push(fullRecord);-- // Emit event- this.emitEvent({- type: BillingEventType.UsageRecorded,- timestamp: new Date(),- subscriptionId: record.subscriptionId,- data: { metric: record.metric, amount: record.amount },- });-- // Flush if buffer is full- if (this.buffer.length >= this.config.bufferSize) {- await this.flush();- }- }-- async checkQuota(- subscriptionId: string,- metric: UsageMetric,- limits: ResourceLimits- ): Promise<QuotaCheckResult> {- const current = await this.getCurrentUsage(subscriptionId, metric);- const limit = this.getLimitForMetric(metric, limits);-- // Unlimited- if (limit === -1) {- return {- allowed: true,- metric,- current,- limit,- percentUsed: 0,- remaining: Infinity,- overage: 0,- };- }-- const percentUsed = (current / limit) * 100;- const remaining = Math.max(0, limit - current);- const overage = Math.max(0, current - limit);-- // Check soft limit (warning)- if (percentUsed >= this.config.softLimitPercent && percentUsed < this.config.hardLimitPercent) {- this.emitEvent({- type: BillingEventType.QuotaWarning,- timestamp: new Date(),- subscriptionId,- data: { metric, percentUsed, current, limit },- });- }-- // Check hard limit (block)- if (percentUsed >= this.config.hardLimitPercent) {- this.emitEvent({- type: BillingEventType.QuotaExceeded,- timestamp: new Date(),- subscriptionId,- data: { metric, current, limit, overage },- });-- return {- allowed: false,- metric,- current,- limit,- percentUsed,- remaining,- overage,- warning: `Quota exceeded for ${metric}. Current: ${current}, Limit: ${limit}`,- };- }-- return {- allowed: true,- metric,- current,- limit,- percentUsed,- remaining,- overage,- };- }-- async getUsageSummary(subscriptionId: string, limits: ResourceLimits): Promise<UsageSummary> {- const period = this.getCurrentBillingPeriod();- const metrics = new Map<UsageMetric, number>();- const percentUsed = new Map<UsageMetric, number>();- const overages = new Map<UsageMetric, number>();-- // Get all metrics- const allMetrics = Object.values(UsageMetric);-- for (const metric of allMetrics) {- const current = await this.getCurrentUsage(subscriptionId, metric);- const limit = this.getLimitForMetric(metric, limits);-- metrics.set(metric, current);-- if (limit !== -1) {- const percent = (current / limit) * 100;- percentUsed.set(metric, percent);-- if (current > limit) {- overages.set(metric, current - limit);- }- }- }-- const estimatedCost = this.calculateOverageCost(overages);-- return {- subscriptionId,- userId: '',- period,- metrics,- limits,- percentUsed,- overages,- estimatedCost,- };- }-- async getCurrentUsage(subscriptionId: string, metric: UsageMetric): Promise<number> {- // Check cache first- const cached = this.usageCache.get(subscriptionId)?.get(metric);- if (cached !== undefined) {- return cached;- }-- // Query storage- const period = this.getCurrentBillingPeriod();- const records = await this.storage.getUsageRecords(subscriptionId, period);- const total = records- .filter(r => r.metric === metric)- .reduce((sum, r) => sum + r.amount, 0);-- // Update cache- const userMetrics = this.usageCache.get(subscriptionId) || new Map();- userMetrics.set(metric, total);- this.usageCache.set(subscriptionId, userMetrics);-- return total;- }-- async flush(): Promise<void> {- if (this.buffer.length === 0) return;-- const records = [...this.buffer];- this.buffer = [];-- try {- await Promise.all(records.map(r => this.storage.saveUsageRecord(r)));- } catch (error) {- console.error('Failed to flush usage records:', error);- // Re-add to buffer on error- this.buffer.unshift(...records);- }- }-- async stop(): Promise<void> {- this.stopFlushTimer();- await this.flush();- this.billingListeners.clear();- }-- clearCache(subscriptionId?: string): void {- if (subscriptionId) {- this.usageCache.delete(subscriptionId);- } else {- this.usageCache.clear();- }- }-- addEventListener(listener: BillingEventListener): void {- this.billingListeners.add(listener);- }-- removeEventListener(listener: BillingEventListener): void {- this.billingListeners.delete(listener);- }-- // ============================================================================- // Private Methods- // ============================================================================-- private startFlushTimer(): void {- this.flushTimer = setInterval(() => {- this.flush();- }, this.config.flushInterval);- }-- private stopFlushTimer(): void {- if (this.flushTimer) {- clearInterval(this.flushTimer);- this.flushTimer = undefined;- }- }-- private getLimitForMetric(metric: UsageMetric, limits: ResourceLimits): number {- const metricToLimitMap: Record<UsageMetric, keyof ResourceLimits> = {- [UsageMetric.AgentHours]: 'maxAgentHours',- [UsageMetric.Deployments]: 'maxDeployments',- [UsageMetric.APIRequests]: 'maxAPIRequests',- [UsageMetric.StorageGB]: 'maxStorageGB',- [UsageMetric.SwarmSize]: 'maxSwarmSize',- [UsageMetric.GPUHours]: 'maxGPUHours',- [UsageMetric.BandwidthGB]: 'maxBandwidthGB',- [UsageMetric.ConcurrentJobs]: 'maxConcurrentJobs',- [UsageMetric.TeamMembers]: 'maxTeamMembers',- [UsageMetric.CustomDomains]: 'maxCustomDomains',- };-- return limits[metricToLimitMap[metric]] as number;- }-- private calculateOverageCost(overages: Map<UsageMetric, number>): number {- // Overage rates per unit- const rates: Record<UsageMetric, number> = {- [UsageMetric.AgentHours]: 0.50,- [UsageMetric.Deployments]: 5.00,- [UsageMetric.APIRequests]: 0.0001,- [UsageMetric.StorageGB]: 0.10,- [UsageMetric.SwarmSize]: 10.00,- [UsageMetric.GPUHours]: 2.00,- [UsageMetric.BandwidthGB]: 0.05,- [UsageMetric.ConcurrentJobs]: 5.00,- [UsageMetric.TeamMembers]: 15.00,- [UsageMetric.CustomDomains]: 10.00,- };-- let total = 0;- overages.forEach((amount, metric) => {- total += amount * (rates[metric] || 0);- });-- return total;- }-- private getCurrentBillingPeriod(): string {- const now = new Date();- return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;- }-- private generateId(): string {- return `usage_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;- }-- private emitEvent(event: BillingEvent): void {- for (const listener of this.billingListeners) {- try {- listener(event);- } catch (error) {- console.error('Error in billing event listener:', error);- }- }- this.emit(event.type, event);- }-}--// ============================================================================-// Factory Functions-// ============================================================================--/**- * Create metering engine with in-memory storage- */-export function createMeteringEngine(config?: Partial<MeteringConfig>): MeteringEngine {- return new MeteringEngine(new InMemoryBillingStorage(), config);-}--/**- * Create metering engine with custom storage- */-export function createMeteringEngineWithStorage(- storage: IBillingStorage,- config?: Partial<MeteringConfig>-): MeteringEngine {- return new MeteringEngine(storage, config);-}diff --git a/v3/@claude-flow/billing/src/types.ts b/v3/@claude-flow/billing/src/types.tsdeleted file mode 100644index bccc436d33..0000000000--- a/v3/@claude-flow/billing/src/types.ts+++ /dev/null@@ -1,500 +0,0 @@-/**- * V3 Billing/Metering Types- *- * Usage tracking and billing types aligned with agentic-flow@alpha:- * - Subscription management- * - Usage metering- * - Quota tracking- * - Payment processing- *- * Performance Targets:- * - Record usage: <5ms- * - Check quota: <10ms- * - Aggregate stats: <50ms- */--// ============================================================================-// Subscription Types-// ============================================================================--/**- * Subscription tiers- */-export enum SubscriptionTier {- Free = 'free',- Starter = 'starter',- Pro = 'pro',- Enterprise = 'enterprise',- Custom = 'custom',-}--/**- * Billing cycles- */-export enum BillingCycle {- Monthly = 'monthly',- Quarterly = 'quarterly',- Yearly = 'yearly',-}--/**- * Subscription status- */-export enum SubscriptionStatus {- Active = 'active',- Trialing = 'trialing',- PastDue = 'past_due',- Canceled = 'canceled',- Suspended = 'suspended',-}--/**- * Subscription information- */-export interface Subscription {- /** Subscription ID */- id: string;-- /** User/org ID */- userId: string;-- /** Current tier */- tier: SubscriptionTier;-- /** Billing cycle */- cycle: BillingCycle;-- /** Current status */- status: SubscriptionStatus;-- /** Subscription start date */- startDate: Date;-- /** Current period end */- currentPeriodEnd: Date;-- /** Trial end date (if applicable) */- trialEnd?: Date;-- /** Cancellation date (if applicable) */- canceledAt?: Date;-- /** Resource limits */- limits: ResourceLimits;-- /** Applied coupons */- coupons?: AppliedCoupon[];-- /** Payment method ID */- paymentMethodId?: string;-- /** Metadata */- metadata?: Record<string, unknown>;-}--/**- * Resource limits for a tier- */-export interface ResourceLimits {- /** Maximum agent hours per month */- maxAgentHours: number;-- /** Maximum deployments */- maxDeployments: number;-- /** Maximum API requests per month */- maxAPIRequests: number;-- /** Maximum storage in GB */- maxStorageGB: number;-- /** Maximum swarm size */- maxSwarmSize: number;-- /** Maximum GPU hours */- maxGPUHours: number;-- /** Maximum bandwidth in GB */- maxBandwidthGB: number;-- /** Maximum concurrent jobs */- maxConcurrentJobs: number;-- /** Maximum team members */- maxTeamMembers: number;-- /** Maximum custom domains */- maxCustomDomains: number;-}--// ============================================================================-// Usage Metrics-// ============================================================================--/**- * Usage metric types- */-export enum UsageMetric {- AgentHours = 'agent_hours',- Deployments = 'deployments',- APIRequests = 'api_requests',- StorageGB = 'storage_gb',- SwarmSize = 'swarm_size',- GPUHours = 'gpu_hours',- BandwidthGB = 'bandwidth_gb',- ConcurrentJobs = 'concurrent_jobs',- TeamMembers = 'team_members',- CustomDomains = 'custom_domains',-}--/**- * Usage record- */-export interface UsageRecord {- /** Record ID */- id: string;-- /** Subscription ID */- subscriptionId: string;-- /** Metric type */- metric: UsageMetric;-- /** Usage amount */- amount: number;-- /** Timestamp */- timestamp: Date;-- /** Billing period */- billingPeriod: string;-- /** Source/origin of usage */- source?: string;-- /** Metadata */- metadata?: Record<string, unknown>;-}--/**- * Usage summary- */-export interface UsageSummary {- /** Subscription ID */- subscriptionId: string;-- /** User ID */- userId: string;-- /** Billing period */- period: string;-- /** Usage by metric */- metrics: Map<UsageMetric, number>;-- /** Limits by metric */- limits: ResourceLimits;-- /** Percentage used by metric */- percentUsed: Map<UsageMetric, number>;-- /** Overages by metric */- overages: Map<UsageMetric, number>;-- /** Estimated overage cost */- estimatedCost: number;-}--/**- * Quota check result- */-export interface QuotaCheckResult {- /** Whether the action is allowed */- allowed: boolean;-- /** Metric checked */- metric: UsageMetric;-- /** Current usage */- current: number;-- /** Limit */- limit: number;-- /** Percentage used */- percentUsed: number;-- /** Remaining */- remaining: number;-- /** Overage amount */- overage: number;-- /** Warning message (if near limit) */- warning?: string;-}--// ============================================================================-// Payment Types-// ============================================================================--/**- * Payment providers- */-export enum PaymentProvider {- Stripe = 'stripe',- PayPal = 'paypal',- Crypto = 'crypto',-}--/**- * Payment status- */-export enum PaymentStatus {- Pending = 'pending',- Succeeded = 'succeeded',- Failed = 'failed',- Refunded = 'refunded',- Canceled = 'canceled',-}--/**- * Payment record- */-export interface Payment {- /** Payment ID */- id: string;-- /** Subscription ID */- subscriptionId: string;-- /** Amount in cents */- amount: number;-- /** Currency code */- currency: string;-- /** Payment status */- status: PaymentStatus;-- /** Payment provider */- provider: PaymentProvider;-- /** Provider payment ID */- providerPaymentId?: string;-- /** Invoice ID */- invoiceId?: string;-- /** Created at */- createdAt: Date;-- /** Completed at */- completedAt?: Date;-- /** Failure reason */- failureReason?: string;-- /** Metadata */- metadata?: Record<string, unknown>;-}--// ============================================================================-// Coupon Types-// ============================================================================--/**- * Coupon types- */-export enum CouponType {- Percentage = 'percentage',- Fixed = 'fixed',- Credit = 'credit',-}--/**- * Coupon definition- */-export interface Coupon {- /** Coupon code */- code: string;-- /** Coupon type */- type: CouponType;-- /** Discount value (percentage or fixed amount) */- value: number;-- /** Applicable tiers */- applicableTiers?: SubscriptionTier[];-- /** Maximum uses */- maxUses?: number;-- /** Current uses */- currentUses: number;-- /** Expiration date */- expiresAt?: Date;-- /** Created at */- createdAt: Date;-- /** Active status */- active: boolean;-}--/**- * Applied coupon- */-export interface AppliedCoupon {- /** Coupon code */- code: string;-- /** Discount amount applied */- discountAmount: number;-- /** Applied at */- appliedAt: Date;-- /** Valid until */- validUntil?: Date;-}--// ============================================================================-// Event Types-// ============================================================================--/**- * Billing event types- */-export enum BillingEventType {- SubscriptionCreated = 'subscription.created',- SubscriptionUpdated = 'subscription.updated',- SubscriptionCanceled = 'subscription.canceled',- SubscriptionRenewed = 'subscription.renewed',- UsageRecorded = 'usage.recorded',- QuotaExceeded = 'quota.exceeded',- QuotaWarning = 'quota.warning',- PaymentSucceeded = 'payment.succeeded',- PaymentFailed = 'payment.failed',- InvoiceCreated = 'invoice.created',- CouponApplied = 'coupon.applied',-}--/**- * Billing event- */-export interface BillingEvent {- /** Event type */- type: BillingEventType;-- /** Timestamp */- timestamp: Date;-- /** Subscription ID */- subscriptionId: string;-- /** Event data */- data: Record<string, unknown>;-}--/**- * Event listener type- */-export type BillingEventListener = (event: BillingEvent) => void | Promise<void>;--// ============================================================================-// Metering Engine Interface-// ============================================================================--/**- * Metering engine configuration- */-export interface MeteringConfig {- /** Enable metering */- enabled: boolean;-- /** Buffer size before flush */- bufferSize: number;-- /** Flush interval in ms */- flushInterval: number;-- /** Soft limit percentage (warning threshold) */- softLimitPercent: number;-- /** Hard limit percentage (block threshold) */- hardLimitPercent: number;-}--/**- * Metering engine interface- */-export interface IMeteringEngine {- /** Record usage */- recordUsage(record: Omit<UsageRecord, 'id' | 'timestamp' | 'billingPeriod'>): Promise<void>;-- /** Check quota */- checkQuota(subscriptionId: string, metric: UsageMetric, limits: ResourceLimits): Promise<QuotaCheckResult>;-- /** Get usage summary */- getUsageSummary(subscriptionId: string, limits: ResourceLimits): Promise<UsageSummary>;-- /** Get current usage for a metric */- getCurrentUsage(subscriptionId: string, metric: UsageMetric): Promise<number>;-- /** Flush buffered records */- flush(): Promise<void>;-- /** Stop the engine */- stop(): Promise<void>;-- /** Clear cache for subscription */- clearCache(subscriptionId?: string): void;-- /** Add event listener */- addEventListener(listener: BillingEventListener): void;-- /** Remove event listener */- removeEventListener(listener: BillingEventListener): void;-}--// ============================================================================-// Storage Interface-// ============================================================================--/**- * Billing storage interface- */-export interface IBillingStorage {- /** Save subscription */- saveSubscription(subscription: Subscription): Promise<void>;-- /** Get subscription */- getSubscription(subscriptionId: string): Promise<Subscription | null>;-- /** Get subscription by user */- getSubscriptionByUser(userId: string): Promise<Subscription | null>;-- /** Save usage record */- saveUsageRecord(record: UsageRecord): Promise<void>;-- /** Get usage records */- getUsageRecords(subscriptionId: string, period: string): Promise<UsageRecord[]>;-- /** Save payment */- savePayment(payment: Payment): Promise<void>;-- /** Get payments */- getPayments(subscriptionId: string): Promise<Payment[]>;-- /** Save coupon */- saveCoupon(coupon: Coupon): Promise<void>;-- /** Get coupon */- getCoupon(code: string): Promise<Coupon | null>;-- /** Increment coupon usage */- incrementCouponUsage(code: string): Promise<void>;-}diff --git a/v3/@claude-flow/billing/tsconfig.json b/v3/@claude-flow/billing/tsconfig.jsondeleted file mode 100644index b813d42868..0000000000--- a/v3/@claude-flow/billing/tsconfig.json+++ /dev/null@@ -1,9 +0,0 @@-{- "extends": "../../tsconfig.base.json",- "compilerOptions": {- "outDir": "./dist",- "rootDir": "./src"- },- "include": ["src/**/*"],- "exclude": ["node_modules", "dist"]-}diff --git a/v3/@claude-flow/federation/README.md b/v3/@claude-flow/federation/README.mddeleted file mode 100644index 92e7f2b5a6..0000000000--- a/v3/@claude-flow/federation/README.md+++ /dev/null@@ -1,91 +0,0 @@-# @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/package.json b/v3/@claude-flow/federation/package.jsondeleted file mode 100644index cece24267b..0000000000--- a/v3/@claude-flow/federation/package.json+++ /dev/null@@ -1,51 +0,0 @@-{- "name": "@claude-flow/federation",- "version": "3.0.0-alpha.1",- "description": "V3 Federation - Multi-cluster coordination, vector clock sync, ephemeral agents",- "type": "module",- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js"- }- },- "files": [- "dist",- "src"- ],- "scripts": {- "build": "tsc",- "test": "vitest run",- "test:watch": "vitest",- "lint": "eslint src --ext .ts",- "clean": "rm -rf dist"- },- "keywords": [- "federation",- "multi-cluster",- "vector-clock",- "sync",- "distributed",- "multi-tenant",- "claude-flow",- "v3"- ],- "author": "Claude Flow Team",- "license": "MIT",- "dependencies": {- "@claude-flow/transport": "^3.0.0-alpha.1"- },- "devDependencies": {- "typescript": "^5.3.0",- "vitest": "^1.0.0",- "@types/node": "^20.10.0"- },- "peerDependencies": {- "@claude-flow/shared": "^3.0.0-alpha.1"- },- "engines": {- "node": ">=20.0.0"- }-}diff --git a/v3/@claude-flow/federation/src/__tests__/federation-hub.test.ts b/v3/@claude-flow/federation/src/__tests__/federation-hub.test.tsdeleted file mode 100644index 9b0522af87..0000000000--- a/v3/@claude-flow/federation/src/__tests__/federation-hub.test.ts+++ /dev/null@@ -1,157 +0,0 @@-/**- * 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({- endpoint: 'quic://localhost:4433',- agentId: 'test-agent',- tenantId: 'test-tenant',- token: 'test-token',- });-- expect(hub).toBeInstanceOf(FederationHub);- });-- it('should accept optional config options', () => {- const hub = createFederationHub({- endpoint: 'quic://localhost:4433',- agentId: 'test-agent',- tenantId: 'test-tenant',- token: 'test-token',- syncInterval: 5000,- conflictResolution: 'last-write-wins',- });-- expect(hub).toBeDefined();- });- });-- describe('Event Emission', () => {- it('should be an EventEmitter', () => {- const hub = createFederationHub({- endpoint: 'quic://localhost:4433',- agentId: 'test-agent',- tenantId: 'test-tenant',- token: 'test-token',- });-- 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.tsdeleted file mode 100644index 1ab4ea0020..0000000000--- a/v3/@claude-flow/federation/src/federation-hub.ts+++ /dev/null@@ -1,542 +0,0 @@-/**- * V3 Federation Hub Implementation- *- * Multi-cluster coordination aligned with agentic-flow@alpha:- * - QUIC-based synchronization (<50ms latency)- * - Vector clock conflict resolution- * - mTLS transport security- * - Hub-and-spoke topology- */--import { EventEmitter } from 'events';-import type {- FederationHubConfig,- VectorClock,- ClockComparison,- SyncMessage,- SyncUpdate,- SyncResult,- ConflictInfo,- IFederationHub,- SyncStats,- FederationEvent,- FederationEventListener,-} from './types.js';--// ============================================================================-// Logger Interface-// ============================================================================--interface ILogger {- debug(message: string, meta?: Record<string, unknown>): void;- info(message: string, meta?: Record<string, unknown>): void;- warn(message: string, meta?: Record<string, unknown>): void;- error(message: string, meta?: Record<string, unknown>): void;-}--const defaultLogger: ILogger = {- debug: (msg, meta) => console.debug(`[Federation] ${msg}`, meta || ''),- info: (msg, meta) => console.info(`[Federation] ${msg}`, meta || ''),- warn: (msg, meta) => console.warn(`[Federation] ${msg}`, meta || ''),- error: (msg, meta) => console.error(`[Federation] ${msg}`, meta || ''),-};--// ============================================================================-// Vector Clock Utilities-// ============================================================================--/**- * Compare two vector clocks- */-export function compareVectorClocks(a: VectorClock, b: VectorClock): ClockComparison {- let aHasNewer = false;- let bHasNewer = false;-- // Get all agent IDs from both clocks- const allAgents = new Set([...Object.keys(a), ...Object.keys(b)]);-- for (const agentId of allAgents) {- const aTime = a[agentId] || 0;- const bTime = b[agentId] || 0;-- if (aTime > bTime) {- aHasNewer = true;- } else if (bTime > aTime) {- bHasNewer = true;- }- }-- if (aHasNewer && bHasNewer) {- return 'concurrent';- } else if (aHasNewer) {- return 'after';- } else if (bHasNewer) {- return 'before';- } else {- return 'equal';- }-}--/**- * Merge two vector clocks (take max of each component)- */-export function mergeVectorClocks(a: VectorClock, b: VectorClock): VectorClock {- const result: VectorClock = { ...a };-- for (const [agentId, timestamp] of Object.entries(b)) {- result[agentId] = Math.max(result[agentId] || 0, timestamp);- }-- return result;-}--/**- * Increment vector clock for an agent- */-export function incrementVectorClock(clock: VectorClock, agentId: string): VectorClock {- return {- ...clock,- [agentId]: (clock[agentId] || 0) + 1,- };-}--// ============================================================================-// Federation Hub Implementation-// ============================================================================--export class FederationHub extends EventEmitter implements IFederationHub {- private readonly config: Required<FederationHubConfig>;- private readonly logger: ILogger;- private connected = false;- private vectorClock: VectorClock = {};- private lastSyncTime = 0;- private changeLog: SyncUpdate[] = [];-- // Statistics- private stats: SyncStats = {- lastSyncTime: 0,- totalSyncs: 0,- totalPulled: 0,- totalPushed: 0,- totalConflicts: 0,- totalResolved: 0,- avgSyncDurationMs: 0,- };-- private syncDurations: number[] = [];- private eventListeners: Set<FederationEventListener> = new Set();-- constructor(config: FederationHubConfig, logger?: ILogger) {- super();- this.logger = logger || defaultLogger;- this.config = {- endpoint: config.endpoint,- agentId: config.agentId,- tenantId: config.tenantId,- token: config.token,- enableMTLS: config.enableMTLS ?? true,- certPath: config.certPath || '',- keyPath: config.keyPath || '',- caPath: config.caPath || '',- syncInterval: config.syncInterval ?? 30000,- conflictResolution: config.conflictResolution ?? 'last-write-wins',- };-- // Initialize vector clock for this agent- this.vectorClock[config.agentId] = 0;- }-- async connect(): Promise<void> {- if (this.connected) {- this.logger.warn('Already connected to federation hub');- return;- }-- this.logger.info('Connecting to federation hub', {- endpoint: this.config.endpoint,- agentId: this.config.agentId,- mTLS: this.config.enableMTLS,- });-- try {- // In production, this would establish QUIC connection- // For now, simulate connection- this.connected = true;- this.lastSyncTime = Date.now();-- this.emitEvent({- type: 'connected',- agentId: this.config.agentId,- endpoint: this.config.endpoint,- });-- this.logger.info('Connected to federation hub', {- agentId: this.config.agentId,- });- } catch (error) {- this.logger.error('Failed to connect to federation hub', {- endpoint: this.config.endpoint,- error: error instanceof Error ? error.message : String(error),- });- throw error;- }- }-- async disconnect(): Promise<void> {- if (!this.connected) {- return;- }-- this.logger.info('Disconnecting from federation hub', {- agentId: this.config.agentId,- });-- this.connected = false;-- this.emitEvent({- type: 'disconnected',- agentId: this.config.agentId,- });-- this.logger.info('Disconnected from federation hub');- }-- async sync(db: unknown): Promise<SyncResult> {- if (!this.connected) {- throw new Error('Not connected to federation hub');- }-- const startTime = Date.now();- this.emitEvent({ type: 'sync_started', agentId: this.config.agentId });-- try {- // Increment vector clock for this sync- this.vectorClock = incrementVectorClock(this.vectorClock, this.config.agentId);-- // PULL: Get updates from hub- const pullMessage: SyncMessage = {- type: 'pull',- agentId: this.config.agentId,- tenantId: this.config.tenantId,- vectorClock: { ...this.vectorClock },- timestamp: Date.now(),- };-- const remoteUpdates = await this.sendSyncMessage(pullMessage);- const conflicts: ConflictInfo[] = [];-- // Merge remote updates- if (remoteUpdates.length > 0) {- for (const update of remoteUpdates) {- const conflict = await this.processRemoteUpdate(db, update);- if (conflict) {- conflicts.push(conflict);- }- }-- this.logger.info('Pulled remote updates', {- agentId: this.config.agentId,- count: remoteUpdates.length,- conflicts: conflicts.length,- });- }-- // PUSH: Send local changes- const localChanges = this.getLocalChanges();- if (localChanges.length > 0) {- const pushMessage: SyncMessage = {- type: 'push',- agentId: this.config.agentId,- tenantId: this.config.tenantId,- vectorClock: { ...this.vectorClock },- timestamp: Date.now(),- data: localChanges,- };-- await this.sendSyncMessage(pushMessage);- this.clearLocalChanges();-- this.logger.info('Pushed local changes', {- agentId: this.config.agentId,- count: localChanges.length,- });- }-- const durationMs = Date.now() - startTime;- this.lastSyncTime = Date.now();-- // Update statistics- this.stats.totalSyncs++;- this.stats.totalPulled += remoteUpdates.length;- this.stats.totalPushed += localChanges.length;- this.stats.totalConflicts += conflicts.length;- this.stats.totalResolved += conflicts.filter(c => c.resolution !== 'skip').length;- this.stats.lastSyncTime = this.lastSyncTime;- this.updateAvgDuration(durationMs);-- const result: SyncResult = {- success: true,- pullCount: remoteUpdates.length,- pushCount: localChanges.length,- conflictCount: conflicts.length,- resolvedConflicts: conflicts,- durationMs,- vectorClock: { ...this.vectorClock },- };-- this.emitEvent({- type: 'sync_completed',- agentId: this.config.agentId,- result,- });-- this.logger.info('Sync completed', {- agentId: this.config.agentId,- durationMs,- pulled: remoteUpdates.length,- pushed: localChanges.length,- });-- return result;- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- this.emitEvent({- type: 'sync_failed',- agentId: this.config.agentId,- error: message,- });- this.logger.error('Sync failed', { agentId: this.config.agentId, error: message });- throw error;- }- }-- isConnected(): boolean {- return this.connected;- }-- getSyncStats(): SyncStats {- return { ...this.stats };- }-- getVectorClock(): VectorClock {- return { ...this.vectorClock };- }-- async forcePush(updates: SyncUpdate[]): Promise<void> {- if (!this.connected) {- throw new Error('Not connected to federation hub');- }-- const pushMessage: SyncMessage = {- type: 'push',- agentId: this.config.agentId,- tenantId: this.config.tenantId,- vectorClock: { ...this.vectorClock },- timestamp: Date.now(),- data: updates,- };-- await this.sendSyncMessage(pushMessage);- this.stats.totalPushed += updates.length;-- this.logger.info('Force pushed updates', {- agentId: this.config.agentId,- count: updates.length,- });- }-- async forcePull(): Promise<SyncUpdate[]> {- if (!this.connected) {- throw new Error('Not connected to federation hub');- }-- const pullMessage: SyncMessage = {- type: 'pull',- agentId: this.config.agentId,- tenantId: this.config.tenantId,- vectorClock: { ...this.vectorClock },- timestamp: Date.now(),- };-- const updates = await this.sendSyncMessage(pullMessage);- this.stats.totalPulled += updates.length;-- this.logger.info('Force pulled updates', {- agentId: this.config.agentId,- count: updates.length,- });-- return updates;- }-- /**- * Record a local change for sync- */- recordChange(update: SyncUpdate): void {- update.vectorClock = { ...this.vectorClock };- update.timestamp = Date.now();- this.changeLog.push(update);- this.vectorClock = incrementVectorClock(this.vectorClock, this.config.agentId);- }-- // Event handling- addEventListener(listener: FederationEventListener): void {- this.eventListeners.add(listener);- }-- removeEventListener(listener: FederationEventListener): void {- this.eventListeners.delete(listener);- }-- // ============================================================================- // Private Methods- // ============================================================================-- private async sendSyncMessage(message: SyncMessage): Promise<SyncUpdate[]> {- // In production, this would send via QUIC transport- // For now, simulate with empty response- this.logger.debug('Sending sync message', {- type: message.type,- agentId: message.agentId,- });-- // Simulate network delay- await new Promise(resolve => setTimeout(resolve, 10));-- return [];- }-- private async processRemoteUpdate(- db: unknown,- update: SyncUpdate- ): Promise<ConflictInfo | null> {- const comparison = compareVectorClocks(this.vectorClock, update.vectorClock);-- if (comparison === 'concurrent') {- // Conflict detected- this.emitEvent({- type: 'conflict_detected',- recordId: update.id,- local: this.vectorClock,- remote: update.vectorClock,- });-- const resolution = this.resolveConflict(update);-- this.emitEvent({- type: 'conflict_resolved',- recordId: update.id,- resolution: resolution.resolution,- });-- return resolution;- }-- // No conflict, apply update- await this.applyUpdate(db, update);- this.vectorClock = mergeVectorClocks(this.vectorClock, update.vectorClock);-- return null;- }-- private resolveConflict(remoteUpdate: SyncUpdate): ConflictInfo {- // Find local version of the record- const localVersion = this.changeLog.find(u => u.id === remoteUpdate.id);-- const conflictInfo: ConflictInfo = {- recordId: remoteUpdate.id,- localVersion: localVersion || {- id: remoteUpdate.id,- operation: 'update',- vectorClock: this.vectorClock,- timestamp: Date.now(),- },- remoteVersion: remoteUpdate,- resolution: 'skip',- reason: '',- };-- switch (this.config.conflictResolution) {- case 'last-write-wins':- if (remoteUpdate.timestamp > (localVersion?.timestamp || 0)) {- conflictInfo.resolution = 'remote';- conflictInfo.reason = 'Remote has newer timestamp';- } else {- conflictInfo.resolution = 'local';- conflictInfo.reason = 'Local has newer timestamp';- }- break;-- case 'first-write-wins':- if (remoteUpdate.timestamp < (localVersion?.timestamp || Infinity)) {- conflictInfo.resolution = 'remote';- conflictInfo.reason = 'Remote has older timestamp';- } else {- conflictInfo.resolution = 'local';- conflictInfo.reason = 'Local has older timestamp';- }- break;-- case 'merge':- conflictInfo.resolution = 'merge';- conflictInfo.reason = 'Merged local and remote data';- break;-- default:- conflictInfo.resolution = 'skip';- conflictInfo.reason = 'No resolution strategy';- }-- return conflictInfo;- }-- private async applyUpdate(db: unknown, update: SyncUpdate): Promise<void> {- // In production, this would apply the update to the database- this.logger.debug('Applying update', {- id: update.id,- operation: update.operation,- });- }-- private getLocalChanges(): SyncUpdate[] {- return [...this.changeLog];- }-- private clearLocalChanges(): void {- this.changeLog = [];- }-- private updateAvgDuration(durationMs: number): void {- this.syncDurations.push(durationMs);- if (this.syncDurations.length > 100) {- this.syncDurations.shift();- }- this.stats.avgSyncDurationMs =- this.syncDurations.reduce((a, b) => a + b, 0) / this.syncDurations.length;- }-- private emitEvent(event: FederationEvent): void {- for (const listener of this.eventListeners) {- try {- listener(event);- } catch (error) {- this.logger.error('Error in federation event listener', { error });- }- }- this.emit(event.type, event);- }-}--// ============================================================================-// Factory Functions-// ============================================================================--/**- * Create federation hub- */-export function createFederationHub(- config: FederationHubConfig,- logger?: ILogger-): FederationHub {- return new FederationHub(config, logger);-}diff --git a/v3/@claude-flow/federation/src/index.ts b/v3/@claude-flow/federation/src/index.tsdeleted file mode 100644index ca9a0ee6c0..0000000000--- a/v3/@claude-flow/federation/src/index.ts+++ /dev/null@@ -1,42 +0,0 @@-/**- * V3 Federation Module- *- * Multi-cluster coordination and synchronization aligned with agentic-flow@alpha:- * - Federation hub for cross-cluster sync- * - Vector clock conflict resolution- * - Ephemeral agent management- * - Multi-tenant support- *- * @module @claude-flow/federation- */--export * from './types.js';-export * from './federation-hub.js';--// Re-export commonly used items at top level-export {- FederationHub,- createFederationHub,- compareVectorClocks,- mergeVectorClocks,- incrementVectorClock,-} from './federation-hub.js';--export type {- FederationHubConfig,- VectorClock,- ClockComparison,- SyncMessage,- SyncUpdate,- SyncResult,- ConflictInfo,- IFederationHub,- SyncStats,- FederationEvent,- FederationEventListener,- EphemeralAgentConfig,- EphemeralAgentState,- EphemeralAgentInfo,- TenantInfo,- TenantConfig,-} from './types.js';diff --git a/v3/@claude-flow/federation/src/types.ts b/v3/@claude-flow/federation/src/types.tsdeleted file mode 100644index eb3d8fedf1..0000000000--- a/v3/@claude-flow/federation/src/types.ts+++ /dev/null@@ -1,392 +0,0 @@-/**- * V3 Federation Types- *- * Multi-cluster coordination and synchronization types aligned with agentic-flow@alpha:- * - Federation hub for cross-cluster sync- * - Vector clock conflict resolution- * - Ephemeral agent management- * - Multi-tenant support- *- * Performance Targets:- * - Sync latency: <50ms- * - Conflict detection: <5ms- * - Vector clock update: <1ms- */--// ============================================================================-// Federation Hub Types-// ============================================================================--/**- * Federation hub configuration- */-export interface FederationHubConfig {- /** Hub endpoint (quic://host:port) */- endpoint: string;-- /** Agent identifier */- agentId: string;-- /** Tenant identifier */- tenantId: string;-- /** JWT authentication token */- token: string;-- /** Enable mTLS */- enableMTLS?: boolean;-- /** Certificate path */- certPath?: string;-- /** Key path */- keyPath?: string;-- /** CA path */- caPath?: string;-- /** Sync interval in ms */- syncInterval?: number;-- /** Conflict resolution strategy */- conflictResolution?: ConflictResolutionStrategy;-}--/**- * Conflict resolution strategies- */-export type ConflictResolutionStrategy =- | 'last-write-wins'- | 'first-write-wins'- | 'custom'- | 'merge';--// ============================================================================-// Vector Clock Types-// ============================================================================--/**- * Vector clock for conflict detection- */-export interface VectorClock {- /** Map of agent ID to timestamp */- [agentId: string]: number;-}--/**- * Clock comparison result- */-export type ClockComparison = 'before' | 'after' | 'concurrent' | 'equal';--// ============================================================================-// Sync Types-// ============================================================================--/**- * Sync message types- */-export type SyncMessageType = 'pull' | 'push' | 'ack' | 'nack';--/**- * Sync message- */-export interface SyncMessage {- /** Message type */- type: SyncMessageType;-- /** Source agent ID */- agentId: string;-- /** Tenant ID */- tenantId: string;-- /** Vector clock */- vectorClock: VectorClock;-- /** Message timestamp */- timestamp: number;-- /** Data payload (for push) */- data?: SyncUpdate[];-- /** Request ID */- requestId?: string;-}--/**- * Sync update operation- */-export type SyncOperation = 'insert' | 'update' | 'delete';--/**- * Sync update record- */-export interface SyncUpdate {- /** Record ID */- id: string;-- /** Operation type */- operation: SyncOperation;-- /** Record data */- data?: Record<string, unknown>;-- /** Vector clock at time of update */- vectorClock: VectorClock;-- /** Timestamp */- timestamp: number;-}--/**- * Sync result- */-export interface SyncResult {- /** Whether sync was successful */- success: boolean;-- /** Number of records pulled */- pullCount: number;-- /** Number of records pushed */- pushCount: number;-- /** Number of conflicts detected */- conflictCount: number;-- /** Conflicts that were resolved */- resolvedConflicts: ConflictInfo[];-- /** Sync duration in ms */- durationMs: number;-- /** New vector clock after sync */- vectorClock: VectorClock;-}--/**- * Conflict information- */-export interface ConflictInfo {- /** Record ID */- recordId: string;-- /** Local version */- localVersion: SyncUpdate;-- /** Remote version */- remoteVersion: SyncUpdate;-- /** Resolution applied */- resolution: 'local' | 'remote' | 'merge' | 'skip';-- /** Resolution reason */- reason: string;-}--// ============================================================================-// Ephemeral Agent Types-// ============================================================================--/**- * Ephemeral agent configuration- */-export interface EphemeralAgentConfig {- /** Agent ID */- agentId: string;-- /** Agent type */- agentType: string;-- /** Tenant ID */- tenantId: string;-- /** Time-to-live in seconds */- ttlSeconds: number;-- /** Federation hub endpoint */- hubEndpoint: string;-- /** Authentication token */- token: string;-- /** Capabilities */- capabilities?: string[];-- /** Metadata */- metadata?: Record<string, unknown>;-}--/**- * Ephemeral agent state- */-export type EphemeralAgentState =- | 'initializing'- | 'active'- | 'syncing'- | 'idle'- | 'terminating'- | 'terminated';--/**- * Ephemeral agent info- */-export interface EphemeralAgentInfo {- /** Agent ID */- agentId: string;-- /** Agent type */- agentType: string;-- /** Current state */- state: EphemeralAgentState;-- /** Creation time */- createdAt: Date;-- /** Last activity time */- lastActivity: Date;-- /** Remaining TTL in seconds */- remainingTtl: number;-- /** Current vector clock */- vectorClock: VectorClock;-- /** Connected to hub */- connected: boolean;-- /** Last sync time */- lastSync?: Date;-}--// ============================================================================-// Federation Hub Interface-// ============================================================================--/**- * Federation hub interface- */-export interface IFederationHub {- /** Connect to the hub */- connect(): Promise<void>;-- /** Disconnect from the hub */- disconnect(): Promise<void>;-- /** Synchronize with the hub */- sync(db: unknown): Promise<SyncResult>;-- /** Check if connected */- isConnected(): boolean;-- /** Get sync statistics */- getSyncStats(): SyncStats;-- /** Get current vector clock */- getVectorClock(): VectorClock;-- /** Force push local changes */- forcePush(updates: SyncUpdate[]): Promise<void>;-- /** Force pull remote changes */- forcePull(): Promise<SyncUpdate[]>;-}--/**- * Sync statistics- */-export interface SyncStats {- /** Last sync time */- lastSyncTime: number;-- /** Total syncs performed */- totalSyncs: number;-- /** Total records pulled */- totalPulled: number;-- /** Total records pushed */- totalPushed: number;-- /** Total conflicts detected */- totalConflicts: number;-- /** Total conflicts resolved */- totalResolved: number;-- /** Average sync duration in ms */- avgSyncDurationMs: number;-}--// ============================================================================-// Event Types-// ============================================================================--/**- * Federation events- */-export type FederationEvent =- | { type: 'connected'; agentId: string; endpoint: string }- | { type: 'disconnected'; agentId: string; reason?: string }- | { type: 'sync_started'; agentId: string }- | { type: 'sync_completed'; agentId: string; result: SyncResult }- | { type: 'sync_failed'; agentId: string; error: string }- | { type: 'conflict_detected'; recordId: string; local: VectorClock; remote: VectorClock }- | { type: 'conflict_resolved'; recordId: string; resolution: string }- | { type: 'agent_joined'; agentId: string; agentType: string }- | { type: 'agent_left'; agentId: string; reason: string };--/**- * Event listener type- */-export type FederationEventListener = (event: FederationEvent) => void | Promise<void>;--// ============================================================================-// Multi-Tenant Types-// ============================================================================--/**- * Tenant information- */-export interface TenantInfo {- /** Tenant ID */- tenantId: string;-- /** Tenant name */- name: string;-- /** Active agents */- activeAgents: string[];-- /** Data isolation level */- isolation: 'strict' | 'shared' | 'hierarchical';-- /** Quota limits */- quotas?: {- maxAgents: number;- maxSyncSize: number;- maxStorageBytes: number;- };-}--/**- * Tenant configuration- */-export interface TenantConfig {- /** Tenant ID */- tenantId: string;-- /** Encryption key for tenant data */- encryptionKey?: string;-- /** Allowed federation endpoints */- allowedEndpoints?: string[];-- /** Sync policies */- syncPolicies?: {- syncInterval: number;- maxRetries: number;- backoffMs: number;- };-}diff --git a/v3/@claude-flow/federation/tsconfig.json b/v3/@claude-flow/federation/tsconfig.jsondeleted file mode 100644index b813d42868..0000000000--- a/v3/@claude-flow/federation/tsconfig.json+++ /dev/null@@ -1,9 +0,0 @@-{- "extends": "../../tsconfig.base.json",- "compilerOptions": {- "outDir": "./dist",- "rootDir": "./src"- },- "include": ["src/**/*"],- "exclude": ["node_modules", "dist"]-}diff --git a/v3/@claude-flow/hooks/src/swarm/index.ts b/v3/@claude-flow/hooks/src/swarm/index.tsindex a7b835e51c..e73959d760 100644--- a/v3/@claude-flow/hooks/src/swarm/index.ts+++ b/v3/@claude-flow/hooks/src/swarm/index.ts@@ -260,8 +260,9 @@ export class SwarmCommunication extends EventEmitter {if (options.type) {messages = messages.filter(m => m.type === options.type);}- if (options.since) {- messages = messages.filter(m => m.timestamp > options.since);+ if (options.since !== undefined) {+ const sinceTime = options.since;+ messages = messages.filter(m => m.timestamp > sinceTime);}messages.sort((a, b) => {@@ -374,14 +375,16 @@ export class SwarmCommunication extends EventEmitter {} = {}): PatternBroadcast[] {let broadcasts = Array.from(this.broadcasts.values());- if (options.since) {- broadcasts = broadcasts.filter(b => b.broadcastTime > options.since);+ if (options.since !== undefined) {+ const sinceTime = options.since;+ broadcasts = broadcasts.filter(b => b.broadcastTime > sinceTime);}if (options.domain) {broadcasts = broadcasts.filter(b => b.pattern.domain === options.domain);}- if (options.minQuality) {- broadcasts = broadcasts.filter(b => b.pattern.quality >= options.minQuality);+ if (options.minQuality !== undefined) {+ const minQ = options.minQuality;+ broadcasts = broadcasts.filter(b => b.pattern.quality >= minQ);}return broadcasts.sort((a, b) => b.broadcastTime - a.broadcastTime);@@ -797,7 +800,15 @@ export class SwarmCommunication extends EventEmitter {getStats(): {agentId: string;agentCount: number;- metrics: typeof this.metrics;+ metrics: {+ messagesSent: number;+ messagesReceived: number;+ patternsBroadcast: number;+ consensusInitiated: number;+ consensusResolved: number;+ handoffsInitiated: number;+ handoffsCompleted: number;+ };pendingMessages: number;pendingHandoffs: number;pendingConsensus: number;diff --git a/v3/@claude-flow/transport/README.md b/v3/@claude-flow/transport/README.mddeleted file mode 100644index e77315ad15..0000000000--- a/v3/@claude-flow/transport/README.md+++ /dev/null@@ -1,107 +0,0 @@-# @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/package.json b/v3/@claude-flow/transport/package.jsondeleted file mode 100644index 816f3a9d50..0000000000--- a/v3/@claude-flow/transport/package.json+++ /dev/null@@ -1,48 +0,0 @@-{- "name": "@claude-flow/transport",- "version": "3.0.0-alpha.1",- "description": "V3 QUIC Transport Layer - Connection pooling, stream multiplexing, mTLS",- "type": "module",- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js"- }- },- "files": [- "dist",- "src"- ],- "scripts": {- "build": "tsc",- "test": "vitest run",- "test:watch": "vitest",- "lint": "eslint src --ext .ts",- "clean": "rm -rf dist"- },- "keywords": [- "quic",- "transport",- "http3",- "connection-pool",- "multiplexing",- "mtls",- "claude-flow",- "v3"- ],- "author": "Claude Flow Team",- "license": "MIT",- "devDependencies": {- "typescript": "^5.3.0",- "vitest": "^1.0.0",- "@types/node": "^20.10.0"- },- "peerDependencies": {- "@claude-flow/shared": "^3.0.0-alpha.1"- },- "engines": {- "node": ">=20.0.0"- }-}diff --git a/v3/@claude-flow/transport/src/__tests__/quic-transport.test.ts b/v3/@claude-flow/transport/src/__tests__/quic-transport.test.tsdeleted file mode 100644index e9f61670b1..0000000000--- a/v3/@claude-flow/transport/src/__tests__/quic-transport.test.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * 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,- certPath: './cert.pem',- keyPath: './key.pem',- alpnProtocols: ['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,- certPath: './cert.pem',- keyPath: './key.pem',- });-- expect(server).toBeInstanceOf(QUICServer);- });- });-- describe('Event Emission', () => {- it('should be an EventEmitter', () => {- const server = createQUICServer({- host: '0.0.0.0',- port: 4433,- certPath: './cert.pem',- keyPath: './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 client = createQUICClient({- host: 'localhost',- port: 4433,- });- const pool = createConnectionPool(client, {- maxSize: 10,- minSize: 2,- idleTimeout: 30000,- });-- expect(pool).toBeInstanceOf(QUICConnectionPool);- });-- it('should use default values', () => {- const client = createQUICClient({- host: 'localhost',- port: 4433,- });- const pool = createConnectionPool(client, { maxSize: 5 });- 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);- });-});diff --git a/v3/@claude-flow/transport/src/index.ts b/v3/@claude-flow/transport/src/index.tsdeleted file mode 100644index d6cdd5ae41..0000000000--- a/v3/@claude-flow/transport/src/index.ts+++ /dev/null@@ -1,44 +0,0 @@-/**- * V3 Transport Layer Module- *- * QUIC transport and connection pooling aligned with agentic-flow@alpha:- * - QUIC client/server- * - Connection pooling- * - Stream multiplexing- * - mTLS support- *- * @module @claude-flow/transport- */--export * from './types.js';-export * from './quic-transport.js';--// Re-export commonly used items at top level-export {- QUICClient,- QUICServer,- QUICConnectionPool,- createQUICClient,- createQUICServer,- createConnectionPool,-} from './quic-transport.js';--export type {- QUICClientConfig,- QUICServerConfig,- ConnectionInfo,- ConnectionState,- StreamInfo,- StreamState,- IStream,- IQUICClient,- IQUICServer,- HTTP3Request,- HTTP3Response,- TransportStats,- ConnectionPoolConfig,- IConnectionPool,- PoolStats,- TransportEvent,- TransportEventListener,-} from './types.js';diff --git a/v3/@claude-flow/transport/src/quic-transport.ts b/v3/@claude-flow/transport/src/quic-transport.tsdeleted file mode 100644index 6a557b6f32..0000000000--- a/v3/@claude-flow/transport/src/quic-transport.ts+++ /dev/null@@ -1,682 +0,0 @@-/**- * V3 QUIC Transport Implementation- *- * QUIC-based transport layer aligned with agentic-flow@alpha:- * - Low-latency connections (<50ms)- * - Stream multiplexing- * - Connection pooling- * - mTLS support- * - HTTP/3 compatible- *- * Note: This is a WebSocket fallback implementation.- * Full QUIC requires native bindings (quiche, ngtcp2).- */--import { EventEmitter } from 'events';-import type {- QUICClientConfig,- QUICServerConfig,- ConnectionInfo,- ConnectionState,- StreamInfo,- StreamState,- IStream,- IQUICClient,- IQUICServer,- HTTP3Request,- HTTP3Response,- TransportStats,- ConnectionHandler,- RequestHandler,- TransportEvent,- TransportEventListener,-} from './types.js';--// ============================================================================-// Logger Interface-// ============================================================================--interface ILogger {- debug(message: string, meta?: Record<string, unknown>): void;- info(message: string, meta?: Record<string, unknown>): void;- warn(message: string, meta?: Record<string, unknown>): void;- error(message: string, meta?: Record<string, unknown>): void;-}--// Simple console logger-const defaultLogger: ILogger = {- debug: (msg, meta) => console.debug(`[QUIC] ${msg}`, meta || ''),- info: (msg, meta) => console.info(`[QUIC] ${msg}`, meta || ''),- warn: (msg, meta) => console.warn(`[QUIC] ${msg}`, meta || ''),- error: (msg, meta) => console.error(`[QUIC] ${msg}`, meta || ''),-};--// ============================================================================-// Stream Implementation-// ============================================================================--class QUICStream implements IStream {- public state: StreamState = 'open';- private sendBuffer: Uint8Array[] = [];- private receiveBuffer: Uint8Array[] = [];- private readonly createdAt = new Date();-- constructor(- public readonly id: number,- public readonly connectionId: string,- private readonly onSend: (data: Uint8Array) => Promise<void>,- private readonly onClose: () => void- ) {}-- async send(data: Uint8Array): Promise<void> {- if (this.state === 'closed') {- throw new Error('Stream is closed');- }- this.sendBuffer.push(data);- await this.onSend(data);- }-- async receive(): Promise<Uint8Array> {- if (this.state === 'closed') {- throw new Error('Stream is closed');- }- // In real implementation, this would wait for data- return this.receiveBuffer.shift() || new Uint8Array();- }-- async close(): Promise<void> {- this.state = 'closed';- this.onClose();- }-- getInfo(): StreamInfo {- return {- id: this.id,- connectionId: this.connectionId,- state: this.state,- bidirectional: true,- createdAt: this.createdAt,- };- }-- // Internal method to push received data- pushData(data: Uint8Array): void {- this.receiveBuffer.push(data);- }-}--// ============================================================================-// QUIC Client Implementation-// ============================================================================--export class QUICClient extends EventEmitter implements IQUICClient {- private readonly config: Required<QUICClientConfig>;- private readonly logger: ILogger;- private connections: Map<string, ConnectionInfo> = new Map();- private streams: Map<string, Map<number, QUICStream>> = new Map();- private initialized = false;- private streamCounter = 0;-- // Statistics- private stats: TransportStats = {- totalConnections: 0,- activeConnections: 0,- totalStreams: 0,- activeStreams: 0,- bytesReceived: 0,- bytesSent: 0,- packetsLost: 0,- avgRttMs: 0,- connectionErrors: 0,- streamErrors: 0,- };-- private transportListeners: Set<TransportEventListener> = new Set();-- constructor(config: QUICClientConfig, logger?: ILogger) {- super();- this.logger = logger || defaultLogger;- this.config = {- host: config.host,- port: config.port,- certPath: config.certPath || '',- keyPath: config.keyPath || '',- caPath: config.caPath || '',- verifyPeer: config.verifyPeer ?? true,- maxConnections: config.maxConnections ?? 100,- connectionTimeout: config.connectionTimeout ?? 30000,- idleTimeout: config.idleTimeout ?? 60000,- maxConcurrentStreams: config.maxConcurrentStreams ?? 100,- streamTimeout: config.streamTimeout ?? 30000,- initialCongestionWindow: config.initialCongestionWindow ?? 10,- maxDatagramSize: config.maxDatagramSize ?? 1200,- enableEarlyData: config.enableEarlyData ?? true,- alpnProtocols: config.alpnProtocols || ['h3'],- };- }-- async initialize(): Promise<void> {- if (this.initialized) {- this.logger.warn('QUIC client already initialized');- return;- }-- this.logger.info('Initializing QUIC client', {- host: this.config.host,- port: this.config.port,- verifyPeer: this.config.verifyPeer,- });-- // In production, this would load WASM/native QUIC module- // For now, we simulate initialization- this.initialized = true;- this.logger.info('QUIC client initialized (WebSocket fallback mode)');- }-- async connect(host?: string, port?: number): Promise<ConnectionInfo> {- if (!this.initialized) {- throw new Error('QUIC client not initialized');- }-- const targetHost = host || this.config.host;- const targetPort = port || this.config.port;- const connectionId = `${targetHost}:${targetPort}-${Date.now()}`;-- // Check connection limit- if (this.connections.size >= this.config.maxConnections) {- throw new Error(`Maximum connections (${this.config.maxConnections}) reached`);- }-- this.logger.info('Establishing QUIC connection', { host: targetHost, port: targetPort });-- const connection: ConnectionInfo = {- id: connectionId,- remoteAddr: `${targetHost}:${targetPort}`,- state: 'connected',- streamCount: 0,- createdAt: new Date(),- lastActivity: new Date(),- rttMs: 0,- bytesSent: 0,- bytesReceived: 0,- };-- this.connections.set(connectionId, connection);- this.streams.set(connectionId, new Map());-- this.stats.totalConnections++;- this.stats.activeConnections++;-- this.emitEvent({- type: 'connection_established',- connectionId,- remoteAddr: connection.remoteAddr,- });-- this.logger.info('QUIC connection established', { connectionId });- return connection;- }-- async createStream(connectionId: string): Promise<IStream> {- const connection = this.connections.get(connectionId);- if (!connection) {- throw new Error(`Connection ${connectionId} not found`);- }-- if (connection.streamCount >= this.config.maxConcurrentStreams) {- throw new Error(`Maximum concurrent streams (${this.config.maxConcurrentStreams}) reached`);- }-- const streamId = this.streamCounter++;- const streamMap = this.streams.get(connectionId)!;-- const stream = new QUICStream(- streamId,- connectionId,- async (data) => {- this.stats.bytesSent += data.length;- connection.bytesSent = (connection.bytesSent || 0) + data.length;- connection.lastActivity = new Date();- this.emitEvent({ type: 'data_sent', connectionId, bytes: data.length });- },- () => {- streamMap.delete(streamId);- connection.streamCount--;- this.stats.activeStreams--;- this.emitEvent({ type: 'stream_closed', connectionId, streamId });- }- );-- streamMap.set(streamId, stream);- connection.streamCount++;-- this.stats.totalStreams++;- this.stats.activeStreams++;-- this.emitEvent({ type: 'stream_opened', connectionId, streamId });- this.logger.debug('Stream created', { connectionId, streamId });-- return stream;- }-- async sendRequest(- connectionId: string,- method: string,- path: string,- headers: Record<string, string>,- body?: Uint8Array- ): Promise<HTTP3Response> {- const stream = await this.createStream(connectionId);-- try {- // Encode HTTP/3 request- const request = this.encodeHTTP3Request(method, path, headers, body);- await stream.send(request);-- // Receive response (simulated)- this.logger.debug('HTTP/3 request sent', { method, path });-- return {- status: 200,- headers: {},- body: new Uint8Array(),- };- } finally {- await stream.close();- }- }-- async closeConnection(connectionId: string): Promise<void> {- const connection = this.connections.get(connectionId);- if (!connection) {- this.logger.warn('Connection not found', { connectionId });- return;- }-- // Close all streams- const streamMap = this.streams.get(connectionId);- if (streamMap) {- for (const stream of streamMap.values()) {- await stream.close();- }- this.streams.delete(connectionId);- }-- this.connections.delete(connectionId);- this.stats.activeConnections--;-- this.emitEvent({ type: 'connection_closed', connectionId });- this.logger.info('Connection closed', { connectionId });- }-- async shutdown(): Promise<void> {- this.logger.info('Shutting down QUIC client', {- activeConnections: this.connections.size,- });-- for (const connectionId of this.connections.keys()) {- await this.closeConnection(connectionId);- }-- this.initialized = false;- this.logger.info('QUIC client shut down');- }-- getStats(): TransportStats {- return { ...this.stats };- }-- isInitialized(): boolean {- return this.initialized;- }-- addEventListener(listener: TransportEventListener): void {- this.transportListeners.add(listener);- }-- removeEventListener(listener: TransportEventListener): void {- this.transportListeners.delete(listener);- }-- private emitEvent(event: TransportEvent): void {- for (const listener of this.transportListeners) {- try {- listener(event);- } catch (error) {- this.logger.error('Error in transport event listener', { error });- }- }- this.emit(event.type, event);- }-- private encodeHTTP3Request(- method: string,- path: string,- headers: Record<string, string>,- body?: Uint8Array- ): Uint8Array {- // Simplified encoding - in production would use QPACK- const request = JSON.stringify({ method, path, headers, body: body ? Array.from(body) : undefined });- return new TextEncoder().encode(request);- }-}--// ============================================================================-// QUIC Server Implementation-// ============================================================================--export class QUICServer extends EventEmitter implements IQUICServer {- private readonly config: Required<QUICServerConfig>;- private readonly logger: ILogger;- private connections: Map<string, ConnectionInfo> = new Map();- private initialized = false;- private listening = false;- private connectionHandler?: ConnectionHandler;- private requestHandler?: RequestHandler;-- private stats: TransportStats = {- totalConnections: 0,- activeConnections: 0,- totalStreams: 0,- activeStreams: 0,- bytesReceived: 0,- bytesSent: 0,- packetsLost: 0,- avgRttMs: 0,- connectionErrors: 0,- streamErrors: 0,- };-- private transportListeners: Set<TransportEventListener> = new Set();-- constructor(config: QUICServerConfig, logger?: ILogger) {- super();- this.logger = logger || defaultLogger;- this.config = {- host: config.host,- port: config.port,- certPath: config.certPath || '',- keyPath: config.keyPath || '',- caPath: config.caPath || '',- verifyPeer: config.verifyPeer ?? false,- maxConnections: config.maxConnections ?? 1000,- connectionTimeout: config.connectionTimeout ?? 30000,- idleTimeout: config.idleTimeout ?? 120000,- maxConcurrentStreams: config.maxConcurrentStreams ?? 100,- streamTimeout: config.streamTimeout ?? 30000,- initialCongestionWindow: config.initialCongestionWindow ?? 10,- maxDatagramSize: config.maxDatagramSize ?? 1200,- enableEarlyData: config.enableEarlyData ?? false,- alpnProtocols: config.alpnProtocols || ['h3'],- bindAddress: config.bindAddress || '0.0.0.0',- requireClientCert: config.requireClientCert ?? false,- maxPendingConnections: config.maxPendingConnections ?? 100,- };- }-- async initialize(): Promise<void> {- if (this.initialized) {- this.logger.warn('QUIC server already initialized');- return;- }-- this.logger.info('Initializing QUIC server', {- host: this.config.host,- port: this.config.port,- });-- this.initialized = true;- this.logger.info('QUIC server initialized (WebSocket fallback mode)');- }-- async listen(): Promise<void> {- if (!this.initialized) {- throw new Error('QUIC server not initialized');- }-- if (this.listening) {- this.logger.warn('QUIC server already listening');- return;- }-- this.logger.info('Starting QUIC server', {- host: this.config.host,- port: this.config.port,- });-- this.listening = true;- this.logger.info(`QUIC server listening on ${this.config.host}:${this.config.port}`);- }-- async stop(): Promise<void> {- if (!this.listening) {- this.logger.warn('QUIC server not listening');- return;- }-- this.logger.info('Stopping QUIC server', {- activeConnections: this.connections.size,- });-- for (const connectionId of this.connections.keys()) {- await this.closeConnection(connectionId);- }-- this.listening = false;- this.logger.info('QUIC server stopped');- }-- async closeConnection(connectionId: string): Promise<void> {- const connection = this.connections.get(connectionId);- if (!connection) {- this.logger.warn('Connection not found', { connectionId });- return;- }-- this.connections.delete(connectionId);- this.stats.activeConnections--;- this.logger.info('Connection closed', { connectionId });- }-- getStats(): TransportStats {- return { ...this.stats };- }-- isListening(): boolean {- return this.listening;- }-- onConnection(handler: ConnectionHandler): void {- this.connectionHandler = handler;- }-- onRequest(handler: RequestHandler): void {- this.requestHandler = handler;- }-- addEventListener(listener: TransportEventListener): void {- this.transportListeners.add(listener);- }-- removeEventListener(listener: TransportEventListener): void {- this.transportListeners.delete(listener);- }-}--// ============================================================================-// Connection Pool Implementation-// ============================================================================--import type { ConnectionPoolConfig, IConnectionPool, PoolStats } from './types.js';--export class QUICConnectionPool implements IConnectionPool {- private readonly client: QUICClient;- private readonly config: Required<ConnectionPoolConfig>;- private readonly logger: ILogger;- private available: Map<string, ConnectionInfo[]> = new Map();- private inUse: Map<string, ConnectionInfo> = new Map();-- private stats: PoolStats = {- totalConnections: 0,- availableConnections: 0,- inUseConnections: 0,- connectionsCreated: 0,- connectionsDestroyed: 0,- avgWaitTimeMs: 0,- };-- constructor(client: QUICClient, config: ConnectionPoolConfig, logger?: ILogger) {- this.client = client;- this.logger = logger || defaultLogger;- this.config = {- maxSize: config.maxSize,- minSize: config.minSize ?? 0,- idleTimeout: config.idleTimeout ?? 60000,- acquireTimeout: config.acquireTimeout ?? 30000,- enableHealthCheck: config.enableHealthCheck ?? true,- healthCheckInterval: config.healthCheckInterval ?? 30000,- };- }-- async acquire(host: string, port: number): Promise<ConnectionInfo> {- const key = `${host}:${port}`;- const startTime = performance.now();-- // Check for available connection- const available = this.available.get(key);- if (available && available.length > 0) {- const connection = available.pop()!;- this.inUse.set(connection.id, connection);-- this.stats.availableConnections--;- this.stats.inUseConnections++;- this.updateWaitTime(performance.now() - startTime);-- this.logger.debug('Acquired pooled connection', { connectionId: connection.id });- return connection;- }-- // Check pool limit- if (this.stats.totalConnections >= this.config.maxSize) {- throw new Error('Connection pool exhausted');- }-- // Create new connection- const connection = await this.client.connect(host, port);- this.inUse.set(connection.id, connection);-- this.stats.totalConnections++;- this.stats.inUseConnections++;- this.stats.connectionsCreated++;- this.updateWaitTime(performance.now() - startTime);-- this.logger.debug('Created new pooled connection', { connectionId: connection.id });- return connection;- }-- release(connectionId: string): void {- const connection = this.inUse.get(connectionId);- if (!connection) {- this.logger.warn('Connection not found in pool', { connectionId });- return;- }-- this.inUse.delete(connectionId);- this.stats.inUseConnections--;-- // Add back to available pool- const key = connection.remoteAddr;- if (!this.available.has(key)) {- this.available.set(key, []);- }- this.available.get(key)!.push(connection);- this.stats.availableConnections++;-- this.logger.debug('Released connection to pool', { connectionId });- }-- async remove(connectionId: string): Promise<void> {- const inUse = this.inUse.get(connectionId);- if (inUse) {- this.inUse.delete(connectionId);- this.stats.inUseConnections--;- }-- for (const [key, connections] of this.available.entries()) {- const index = connections.findIndex(c => c.id === connectionId);- if (index >= 0) {- connections.splice(index, 1);- this.stats.availableConnections--;- break;- }- }-- await this.client.closeConnection(connectionId);- this.stats.totalConnections--;- this.stats.connectionsDestroyed++;-- this.logger.debug('Removed connection from pool', { connectionId });- }-- async clear(): Promise<void> {- for (const connectionId of this.inUse.keys()) {- await this.remove(connectionId);- }-- for (const connections of this.available.values()) {- for (const connection of connections) {- await this.client.closeConnection(connection.id);- this.stats.connectionsDestroyed++;- }- }-- this.available.clear();- this.stats.totalConnections = 0;- this.stats.availableConnections = 0;-- this.logger.info('Connection pool cleared');- }-- getStats(): PoolStats {- return { ...this.stats };- }-- private updateWaitTime(waitMs: number): void {- const total = this.stats.connectionsCreated + this.stats.inUseConnections;- if (total === 0) {- this.stats.avgWaitTimeMs = waitMs;- } else {- this.stats.avgWaitTimeMs =- (this.stats.avgWaitTimeMs * (total - 1) + waitMs) / total;- }- }-}--// ============================================================================-// Factory Functions-// ============================================================================--/**- * Create QUIC client- */-export function createQUICClient(config: QUICClientConfig, logger?: ILogger): QUICClient {- return new QUICClient(config, logger);-}--/**- * Create QUIC server- */-export function createQUICServer(config: QUICServerConfig, logger?: ILogger): QUICServer {- return new QUICServer(config, logger);-}--/**- * Create QUIC connection pool- */-export function createConnectionPool(- client: QUICClient,- config: ConnectionPoolConfig,- logger?: ILogger-): QUICConnectionPool {- return new QUICConnectionPool(client, config, logger);-}diff --git a/v3/@claude-flow/transport/src/types.ts b/v3/@claude-flow/transport/src/types.tsdeleted file mode 100644index 88854eca03..0000000000--- a/v3/@claude-flow/transport/src/types.ts+++ /dev/null@@ -1,433 +0,0 @@-/**- * V3 Transport Layer Types- *- * QUIC transport and connection pooling types aligned with agentic-flow@alpha:- * - QUIC client/server- * - Connection pooling- * - Stream multiplexing- * - mTLS support- *- * Performance Targets:- * - Connection latency: <50ms- * - Stream creation: <5ms- * - Message latency: <10ms- */--// ============================================================================-// Transport Types-// ============================================================================--/**- * Supported transport protocols- */-export type TransportProtocol = 'quic' | 'http2' | 'websocket' | 'tcp';--/**- * Connection state- */-export type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'failed';--/**- * Stream state- */-export type StreamState = 'open' | 'half-closed' | 'closed';--// ============================================================================-// QUIC Configuration-// ============================================================================--/**- * QUIC client configuration- */-export interface QUICClientConfig {- /** Server host */- host: string;-- /** Server port */- port: number;-- /** Certificate path for mTLS */- certPath?: string;-- /** Key path for mTLS */- keyPath?: string;-- /** CA certificate path */- caPath?: string;-- /** Verify server certificate */- verifyPeer?: boolean;-- /** Maximum concurrent connections */- maxConnections?: number;-- /** Connection timeout in ms */- connectionTimeout?: number;-- /** Idle timeout in ms */- idleTimeout?: number;-- /** Maximum concurrent streams per connection */- maxConcurrentStreams?: number;-- /** Stream timeout in ms */- streamTimeout?: number;-- /** Initial congestion window */- initialCongestionWindow?: number;-- /** Maximum datagram size */- maxDatagramSize?: number;-- /** Enable 0-RTT early data */- enableEarlyData?: boolean;-- /** ALPN protocols */- alpnProtocols?: string[];-}--/**- * QUIC server configuration- */-export interface QUICServerConfig extends QUICClientConfig {- /** Bind address */- bindAddress?: string;-- /** Client certificate requirement */- requireClientCert?: boolean;-- /** Maximum pending connections */- maxPendingConnections?: number;-}--// ============================================================================-// Connection Types-// ============================================================================--/**- * Connection information- */-export interface ConnectionInfo {- /** Unique connection ID */- id: string;-- /** Remote address */- remoteAddr: string;-- /** Local address */- localAddr?: string;-- /** Connection state */- state: ConnectionState;-- /** Current stream count */- streamCount: number;-- /** Connection creation time */- createdAt: Date;-- /** Last activity time */- lastActivity: Date;-- /** Round-trip time in ms */- rttMs?: number;-- /** Bytes sent */- bytesSent?: number;-- /** Bytes received */- bytesReceived?: number;-}--/**- * Stream information- */-export interface StreamInfo {- /** Stream ID */- id: number;-- /** Parent connection ID */- connectionId: string;-- /** Stream state */- state: StreamState;-- /** Bidirectional or unidirectional */- bidirectional: boolean;-- /** Creation time */- createdAt: Date;-}--// ============================================================================-// Stream Interface-// ============================================================================--/**- * QUIC stream interface- */-export interface IStream {- /** Stream ID */- readonly id: number;-- /** Connection ID */- readonly connectionId: string;-- /** Stream state */- readonly state: StreamState;-- /** Send data on the stream */- send(data: Uint8Array): Promise<void>;-- /** Receive data from the stream */- receive(): Promise<Uint8Array>;-- /** Close the stream */- close(): Promise<void>;-- /** Get stream info */- getInfo(): StreamInfo;-}--// ============================================================================-// Client/Server Interfaces-// ============================================================================--/**- * QUIC client interface- */-export interface IQUICClient {- /** Initialize the client */- initialize(): Promise<void>;-- /** Connect to server */- connect(host?: string, port?: number): Promise<ConnectionInfo>;-- /** Create a stream on a connection */- createStream(connectionId: string): Promise<IStream>;-- /** Send HTTP/3 request */- sendRequest(- connectionId: string,- method: string,- path: string,- headers: Record<string, string>,- body?: Uint8Array- ): Promise<HTTP3Response>;-- /** Close a connection */- closeConnection(connectionId: string): Promise<void>;-- /** Shutdown the client */- shutdown(): Promise<void>;-- /** Get client statistics */- getStats(): TransportStats;-- /** Check if initialized */- isInitialized(): boolean;-}--/**- * QUIC server interface- */-export interface IQUICServer {- /** Initialize the server */- initialize(): Promise<void>;-- /** Start listening for connections */- listen(): Promise<void>;-- /** Stop the server */- stop(): Promise<void>;-- /** Close a specific connection */- closeConnection(connectionId: string): Promise<void>;-- /** Get server statistics */- getStats(): TransportStats;-- /** Check if listening */- isListening(): boolean;-- /** Set connection handler */- onConnection(handler: ConnectionHandler): void;-- /** Set request handler */- onRequest(handler: RequestHandler): void;-}--// ============================================================================-// Handler Types-// ============================================================================--/**- * Connection handler- */-export type ConnectionHandler = (connection: ConnectionInfo) => void | Promise<void>;--/**- * Request handler- */-export type RequestHandler = (- request: HTTP3Request,- connectionId: string-) => Promise<HTTP3Response>;--/**- * Stream handler- */-export type StreamHandler = (stream: IStream) => void | Promise<void>;--// ============================================================================-// HTTP/3 Types-// ============================================================================--/**- * HTTP/3 request- */-export interface HTTP3Request {- method: string;- path: string;- headers: Record<string, string>;- body?: Uint8Array;-}--/**- * HTTP/3 response- */-export interface HTTP3Response {- status: number;- headers: Record<string, string>;- body?: Uint8Array;-}--// ============================================================================-// Statistics-// ============================================================================--/**- * Transport statistics- */-export interface TransportStats {- /** Total connections established */- totalConnections: number;-- /** Currently active connections */- activeConnections: number;-- /** Total streams created */- totalStreams: number;-- /** Currently active streams */- activeStreams: number;-- /** Bytes received */- bytesReceived: number;-- /** Bytes sent */- bytesSent: number;-- /** Packets lost */- packetsLost: number;-- /** Average RTT in ms */- avgRttMs: number;-- /** Connection errors */- connectionErrors: number;-- /** Stream errors */- streamErrors: number;-}--// ============================================================================-// Connection Pool Types-// ============================================================================--/**- * Connection pool configuration- */-export interface ConnectionPoolConfig {- /** Maximum pool size */- maxSize: number;-- /** Minimum pool size */- minSize?: number;-- /** Idle timeout before eviction */- idleTimeout?: number;-- /** Connection acquisition timeout */- acquireTimeout?: number;-- /** Enable health checks */- enableHealthCheck?: boolean;-- /** Health check interval */- healthCheckInterval?: number;-}--/**- * Connection pool interface- */-export interface IConnectionPool {- /** Acquire a connection */- acquire(host: string, port: number): Promise<ConnectionInfo>;-- /** Release a connection back to pool */- release(connectionId: string): void;-- /** Remove a connection from pool */- remove(connectionId: string): Promise<void>;-- /** Clear all connections */- clear(): Promise<void>;-- /** Get pool statistics */- getStats(): PoolStats;-}--/**- * Pool statistics- */-export interface PoolStats {- /** Total connections in pool */- totalConnections: number;-- /** Available connections */- availableConnections: number;-- /** Connections in use */- inUseConnections: number;-- /** Connections created */- connectionsCreated: number;-- /** Connections destroyed */- connectionsDestroyed: number;-- /** Wait time in ms */- avgWaitTimeMs: number;-}--// ============================================================================-// Event Types-// ============================================================================--/**- * Transport events- */-export type TransportEvent =- | { type: 'connection_established'; connectionId: string; remoteAddr: string }- | { type: 'connection_closed'; connectionId: string; reason?: string }- | { type: 'connection_error'; connectionId: string; error: string }- | { type: 'stream_opened'; connectionId: string; streamId: number }- | { type: 'stream_closed'; connectionId: string; streamId: number }- | { type: 'data_received'; connectionId: string; bytes: number }- | { type: 'data_sent'; connectionId: string; bytes: number };--/**- * Event listener type- */-export type TransportEventListener = (event: TransportEvent) => void | Promise<void>;diff --git a/v3/@claude-flow/transport/tsconfig.json b/v3/@claude-flow/transport/tsconfig.jsondeleted file mode 100644index b813d42868..0000000000--- a/v3/@claude-flow/transport/tsconfig.json+++ /dev/null@@ -1,9 +0,0 @@-{- "extends": "../../tsconfig.base.json",- "compilerOptions": {- "outDir": "./dist",- "rootDir": "./src"- },- "include": ["src/**/*"],- "exclude": ["node_modules", "dist"]-}diff --git a/v3/implementation/hooks/guidance-system.ts b/v3/implementation/hooks/guidance-system.tsindex 38417dd447..82ce8e1a13 100644--- a/v3/implementation/hooks/guidance-system.ts+++ b/v3/implementation/hooks/guidance-system.ts@@ -14,7 +14,7 @@import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'fs';import { join, basename, extname } from 'path';-import { execSync } from 'child_process';+import { execFileSync } from 'child_process';// =============================================================================// Types@@ -171,24 +171,26 @@ export function generateSessionContext(): string {'- Typed interfaces for all public APIs',];- // Add git status+ // Add git status (using execFileSync to avoid shell injection)try {- const uncommitted = execSync('git status --porcelain 2>/dev/null | wc -l', {+ const gitOutput = execFileSync('git', ['status', '--porcelain'], {encoding: 'utf-8',- }).trim();+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ const uncommitted = gitOutput.split('\n').filter(line => line.trim()).length;lines.push('', `**Git Status**: ${uncommitted} uncommitted files`);} catch {// Ignore git errors}- // Add patterns count+ // Add patterns count (using execFileSync to avoid shell injection)const patternsPath = join(CONFIG.projectRoot, CONFIG.patternsDb);if (existsSync(patternsPath)) {try {- const count = execSync(- `sqlite3 "${patternsPath}" "SELECT COUNT(*) FROM short_term_patterns" 2>/dev/null`,- { encoding: 'utf-8' }- ).trim();+ const count = execFileSync('sqlite3', [patternsPath, 'SELECT COUNT(*) FROM short_term_patterns'], {+ encoding: 'utf-8',+ stdio: ['pipe', 'pipe', 'pipe'],+ }).trim();lines.push(`**Learned Patterns**: ${count} available`);} catch {// Ignore db errors