🌊 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:
rUv8395c4749d6c
diff --git a/v3/@claude-flow/cli/src/infrastructure/in-memory-repositories.ts b/v3/@claude-flow/cli/src/infrastructure/in-memory-repositories.tsnew file mode 100644index 0000000000..f83d3526d0--- /dev/null+++ b/v3/@claude-flow/cli/src/infrastructure/in-memory-repositories.ts@@ -0,0 +1,310 @@+/**+ * In-Memory Repositories - CLI Infrastructure+ *+ * Lightweight in-memory implementations for CLI use.+ *+ * @module v3/cli/infrastructure+ */++import { Agent, AgentStatus, AgentRole } from '../../../swarm/src/domain/entities/agent.js';+import { Task, TaskStatus, TaskPriority } from '../../../swarm/src/domain/entities/task.js';+import {+ IAgentRepository,+ AgentQueryOptions,+ AgentStatistics,+} from '../../../swarm/src/domain/repositories/agent-repository.interface.js';+import {+ ITaskRepository,+ TaskQueryOptions,+ TaskStatistics,+} from '../../../swarm/src/domain/repositories/task-repository.interface.js';++/**+ * In-Memory Agent Repository+ */+export class InMemoryAgentRepository implements IAgentRepository {+ private agents: Map<string, Agent> = new Map();+ private initialized = false;++ async initialize(): Promise<void> {+ this.initialized = true;+ }++ async shutdown(): Promise<void> {+ this.agents.clear();+ this.initialized = false;+ }++ async clear(): Promise<void> {+ this.agents.clear();+ }++ async save(agent: Agent): Promise<void> {+ this.agents.set(agent.id, agent);+ }++ async findById(id: string): Promise<Agent | null> {+ return this.agents.get(id) ?? null;+ }++ async findByName(name: string): Promise<Agent | null> {+ for (const agent of this.agents.values()) {+ if (agent.name === name) return agent;+ }+ return null;+ }++ async delete(id: string): Promise<boolean> {+ return this.agents.delete(id);+ }++ async exists(id: string): Promise<boolean> {+ return this.agents.has(id);+ }++ async saveMany(agents: Agent[]): Promise<void> {+ for (const agent of agents) {+ this.agents.set(agent.id, agent);+ }+ }++ async findByIds(ids: string[]): Promise<Agent[]> {+ return ids.map((id) => this.agents.get(id)).filter((a): a is Agent => a !== undefined);+ }++ async deleteMany(ids: string[]): Promise<number> {+ let deleted = 0;+ for (const id of ids) {+ if (this.agents.delete(id)) deleted++;+ }+ return deleted;+ }++ async findAll(options?: AgentQueryOptions): Promise<Agent[]> {+ let result = Array.from(this.agents.values());+ if (options?.status) result = result.filter((a) => a.status === options.status);+ if (options?.role) result = result.filter((a) => a.role === options.role);+ if (options?.domain) result = result.filter((a) => a.domain === options.domain);+ if (options?.limit) result = result.slice(0, options.limit);+ return result;+ }++ async findByStatus(status: AgentStatus): Promise<Agent[]> {+ return this.findAll({ status });+ }++ async findByRole(role: AgentRole): Promise<Agent[]> {+ return this.findAll({ role });+ }++ async findByDomain(domain: string): Promise<Agent[]> {+ return this.findAll({ domain });+ }++ async findByParent(parentId: string): Promise<Agent[]> {+ return Array.from(this.agents.values()).filter((a) => a.parentId === parentId);+ }++ async findByCapability(capability: string): Promise<Agent[]> {+ return Array.from(this.agents.values()).filter((a) => a.hasCapability(capability));+ }++ async findAvailable(): Promise<Agent[]> {+ return Array.from(this.agents.values()).filter((a) => a.isAvailable());+ }++ async getStatistics(): Promise<AgentStatistics> {+ const agents = Array.from(this.agents.values());+ const byStatus: Record<AgentStatus, number> = {+ idle: 0,+ active: 0,+ busy: 0,+ paused: 0,+ terminated: 0,+ error: 0,+ };+ const byRole: Record<string, number> = {};+ const byDomain: Record<string, number> = {};+ let totalCompleted = 0;+ let totalUtilization = 0;++ for (const agent of agents) {+ byStatus[agent.status]++;+ byRole[agent.role] = (byRole[agent.role] ?? 0) + 1;+ byDomain[agent.domain] = (byDomain[agent.domain] ?? 0) + 1;+ totalCompleted += agent.completedTaskCount;+ totalUtilization += agent.getUtilization();+ }++ return {+ total: agents.length,+ byStatus,+ byRole,+ byDomain,+ totalTasksCompleted: totalCompleted,+ averageUtilization: agents.length > 0 ? totalUtilization / agents.length : 0,+ };+ }++ async count(options?: AgentQueryOptions): Promise<number> {+ return (await this.findAll(options)).length;+ }+}++/**+ * In-Memory Task Repository+ */+export class InMemoryTaskRepository implements ITaskRepository {+ private tasks: Map<string, Task> = new Map();+ private initialized = false;++ async initialize(): Promise<void> {+ this.initialized = true;+ }++ async shutdown(): Promise<void> {+ this.tasks.clear();+ this.initialized = false;+ }++ async clear(): Promise<void> {+ this.tasks.clear();+ }++ async save(task: Task): Promise<void> {+ this.tasks.set(task.id, task);+ }++ async findById(id: string): Promise<Task | null> {+ return this.tasks.get(id) ?? null;+ }++ async delete(id: string): Promise<boolean> {+ return this.tasks.delete(id);+ }++ async exists(id: string): Promise<boolean> {+ return this.tasks.has(id);+ }++ async saveMany(tasks: Task[]): Promise<void> {+ for (const task of tasks) {+ this.tasks.set(task.id, task);+ }+ }++ async findByIds(ids: string[]): Promise<Task[]> {+ return ids.map((id) => this.tasks.get(id)).filter((t): t is Task => t !== undefined);+ }++ async deleteMany(ids: string[]): Promise<number> {+ let deleted = 0;+ for (const id of ids) {+ if (this.tasks.delete(id)) deleted++;+ }+ return deleted;+ }++ async findAll(options?: TaskQueryOptions): Promise<Task[]> {+ let result = Array.from(this.tasks.values());+ if (options?.status) result = result.filter((t) => t.status === options.status);+ if (options?.priority) result = result.filter((t) => t.priority === options.priority);+ if (options?.type) result = result.filter((t) => t.type === options.type);+ if (options?.assignedAgentId) result = result.filter((t) => t.assignedAgentId === options.assignedAgentId);+ if (options?.limit) result = result.slice(0, options.limit);+ return result;+ }++ async findByStatus(status: TaskStatus): Promise<Task[]> {+ return this.findAll({ status });+ }++ async findByPriority(priority: TaskPriority): Promise<Task[]> {+ return this.findAll({ priority });+ }++ async findByAgent(agentId: string): Promise<Task[]> {+ return this.findAll({ assignedAgentId: agentId });+ }++ async findPending(): Promise<Task[]> {+ return this.findByStatus('pending');+ }++ async findQueued(): Promise<Task[]> {+ return this.findByStatus('queued');+ }++ async findRunning(): Promise<Task[]> {+ return this.findByStatus('running');+ }++ async findTimedOut(): Promise<Task[]> {+ return Array.from(this.tasks.values()).filter((t) => t.isTimedOut());+ }++ async getNextTask(agentCapabilities?: string[]): Promise<Task | null> {+ const queued = await this.findQueued();+ if (queued.length === 0) return null;+ queued.sort((a, b) => a.comparePriority(b));+ return queued[0];+ }++ async getTaskQueue(limit = 10): Promise<Task[]> {+ const queued = await this.findQueued();+ queued.sort((a, b) => a.comparePriority(b));+ return queued.slice(0, limit);+ }++ async getStatistics(): Promise<TaskStatistics> {+ const tasks = Array.from(this.tasks.values());+ const byStatus: Record<TaskStatus, number> = {+ pending: 0,+ queued: 0,+ assigned: 0,+ running: 0,+ completed: 0,+ failed: 0,+ cancelled: 0,+ };+ const byPriority: Record<TaskPriority, number> = {+ critical: 0,+ high: 0,+ normal: 0,+ low: 0,+ };+ const byType: Record<string, number> = {};+ let totalDuration = 0;+ let completedCount = 0;+ let failedCount = 0;+ let retryTotal = 0;++ for (const task of tasks) {+ byStatus[task.status]++;+ byPriority[task.priority]++;+ byType[task.type] = (byType[task.type] ?? 0) + 1;++ if (task.status === 'completed') {+ completedCount++;+ const duration = task.getExecutionDuration();+ if (duration) totalDuration += duration;+ }+ if (task.status === 'failed') failedCount++;+ retryTotal += task.retryCount;+ }++ return {+ total: tasks.length,+ byStatus,+ byPriority,+ byType,+ averageExecutionTime: completedCount > 0 ? totalDuration / completedCount : 0,+ successRate: tasks.length > 0 ? completedCount / tasks.length : 0,+ retryRate: tasks.length > 0 ? retryTotal / tasks.length : 0,+ };+ }++ async count(options?: TaskQueryOptions): Promise<number> {+ return (await this.findAll(options)).length;+ }+}diff --git a/v3/@claude-flow/memory/src/application/commands/delete-memory.command.ts b/v3/@claude-flow/memory/src/application/commands/delete-memory.command.tsnew file mode 100644index 0000000000..235d6dac8d--- /dev/null+++ b/v3/@claude-flow/memory/src/application/commands/delete-memory.command.ts@@ -0,0 +1,172 @@+/**+ * Delete Memory Command - Application Layer (CQRS)+ *+ * Command for deleting memory entries.+ * Supports soft delete and hard delete.+ *+ * @module v3/memory/application/commands+ */++import { IMemoryRepository } from '../../domain/repositories/memory-repository.interface.js';++/**+ * Delete Memory Command Input+ */+export interface DeleteMemoryInput {+ id?: string;+ namespace?: string;+ key?: string;+ hardDelete?: boolean;+}++/**+ * Delete Memory Command Result+ */+export interface DeleteMemoryResult {+ success: boolean;+ deleted: boolean;+ entryId?: string;+ wasHardDelete: boolean;+}++/**+ * Delete Memory Command Handler+ */+export class DeleteMemoryCommandHandler {+ constructor(private readonly repository: IMemoryRepository) {}++ async execute(input: DeleteMemoryInput): Promise<DeleteMemoryResult> {+ let entryId: string | undefined;++ // Find entry by ID or by namespace:key+ if (input.id) {+ entryId = input.id;+ } else if (input.namespace && input.key) {+ const entry = await this.repository.findByKey(input.namespace, input.key);+ entryId = entry?.id;+ }++ if (!entryId) {+ return {+ success: false,+ deleted: false,+ wasHardDelete: false,+ };+ }++ if (input.hardDelete) {+ // Hard delete - remove from database+ const deleted = await this.repository.delete(entryId);+ return {+ success: true,+ deleted,+ entryId,+ wasHardDelete: true,+ };+ } else {+ // Soft delete - mark as deleted+ const entry = await this.repository.findById(entryId);+ if (entry) {+ entry.delete();+ await this.repository.save(entry);+ return {+ success: true,+ deleted: true,+ entryId,+ wasHardDelete: false,+ };+ }+ }++ return {+ success: false,+ deleted: false,+ entryId,+ wasHardDelete: false,+ };+ }+}++/**+ * Bulk Delete Command Input+ */+export interface BulkDeleteMemoryInput {+ ids?: string[];+ namespace?: string;+ olderThan?: Date;+ hardDelete?: boolean;+}++/**+ * Bulk Delete Command Result+ */+export interface BulkDeleteMemoryResult {+ success: boolean;+ deletedCount: number;+ failedCount: number;+ errors: Array<{ id: string; error: string }>;+}++/**+ * Bulk Delete Memory Command Handler+ */+export class BulkDeleteMemoryCommandHandler {+ constructor(private readonly repository: IMemoryRepository) {}++ async execute(input: BulkDeleteMemoryInput): Promise<BulkDeleteMemoryResult> {+ let idsToDelete: string[] = [];++ if (input.ids) {+ idsToDelete = input.ids;+ } else if (input.namespace) {+ const entries = await this.repository.findByNamespace(input.namespace);+ idsToDelete = entries+ .filter((e) => !input.olderThan || e.createdAt < input.olderThan)+ .map((e) => e.id);+ }++ if (idsToDelete.length === 0) {+ return {+ success: true,+ deletedCount: 0,+ failedCount: 0,+ errors: [],+ };+ }++ if (input.hardDelete) {+ const result = await this.repository.deleteMany(idsToDelete);+ return {+ success: result.failed === 0,+ deletedCount: result.success,+ failedCount: result.failed,+ errors: result.errors,+ };+ } else {+ // Soft delete+ const entries = await this.repository.findByIds(idsToDelete);+ let deletedCount = 0;+ const errors: Array<{ id: string; error: string }> = [];++ for (const entry of entries) {+ try {+ entry.delete();+ await this.repository.save(entry);+ deletedCount++;+ } catch (error) {+ errors.push({+ id: entry.id,+ error: error instanceof Error ? error.message : 'Unknown error',+ });+ }+ }++ return {+ success: errors.length === 0,+ deletedCount,+ failedCount: errors.length,+ errors,+ };+ }+ }+}diff --git a/v3/@claude-flow/memory/src/application/commands/store-memory.command.ts b/v3/@claude-flow/memory/src/application/commands/store-memory.command.tsnew file mode 100644index 0000000000..d1f730e354--- /dev/null+++ b/v3/@claude-flow/memory/src/application/commands/store-memory.command.ts@@ -0,0 +1,103 @@+/**+ * Store Memory Command - Application Layer (CQRS)+ *+ * Command for storing a new memory entry.+ * Implements CQRS pattern per ADR-002.+ *+ * @module v3/memory/application/commands+ */++import { MemoryEntry, MemoryType } from '../../domain/entities/memory-entry.js';+import { IMemoryRepository } from '../../domain/repositories/memory-repository.interface.js';+import { MemoryDomainService } from '../../domain/services/memory-domain-service.js';++/**+ * Store Memory Command Input+ */+export interface StoreMemoryInput {+ namespace: string;+ key: string;+ value: unknown;+ type?: MemoryType;+ vector?: Float32Array;+ metadata?: Record<string, unknown>;+ ttl?: number;+}++/**+ * Store Memory Command Result+ */+export interface StoreMemoryResult {+ success: boolean;+ entryId: string;+ entry: MemoryEntry;+ isUpdate: boolean;+}++/**+ * Store Memory Command Handler+ *+ * Handles the command to store a memory entry.+ * Coordinates between domain services and repository.+ */+export class StoreMemoryCommandHandler {+ constructor(+ private readonly repository: IMemoryRepository,+ private readonly domainService: MemoryDomainService+ ) {}++ /**+ * Execute the store memory command+ */+ async execute(input: StoreMemoryInput): Promise<StoreMemoryResult> {+ // Check if entry already exists+ const existing = await this.repository.findByKey(input.namespace, input.key);+ const isUpdate = existing !== null;++ let entry: MemoryEntry;++ if (existing) {+ // Update existing entry+ existing.updateValue(input.value);+ if (input.vector) {+ existing.updateVector(input.vector);+ }+ if (input.metadata) {+ for (const [key, value] of Object.entries(input.metadata)) {+ existing.setMetadata(key, value);+ }+ }+ await this.repository.save(existing);+ entry = existing;+ } else {+ // Create new entry+ if (input.type) {+ entry = MemoryEntry.create({+ namespace: input.namespace,+ key: input.key,+ value: input.value,+ type: input.type,+ vector: input.vector,+ metadata: input.metadata,+ ttl: input.ttl,+ });+ await this.repository.save(entry);+ } else {+ // Use domain service for type detection+ entry = await this.domainService.storeWithTypeDetection(+ input.namespace,+ input.key,+ input.value,+ input.vector+ );+ }+ }++ return {+ success: true,+ entryId: entry.id,+ entry,+ isUpdate,+ };+ }+}diff --git a/v3/@claude-flow/memory/src/application/index.ts b/v3/@claude-flow/memory/src/application/index.tsnew file mode 100644index 0000000000..57e7c49daa--- /dev/null+++ b/v3/@claude-flow/memory/src/application/index.ts@@ -0,0 +1,36 @@+/**+ * Memory Application Layer - Public Exports+ *+ * Exports all application services, commands, and queries.+ *+ * @module v3/memory/application+ */++// Commands+export {+ StoreMemoryCommandHandler,+ type StoreMemoryInput,+ type StoreMemoryResult,+} from './commands/store-memory.command.js';++export {+ DeleteMemoryCommandHandler,+ BulkDeleteMemoryCommandHandler,+ type DeleteMemoryInput,+ type DeleteMemoryResult,+ type BulkDeleteMemoryInput,+ type BulkDeleteMemoryResult,+} from './commands/delete-memory.command.js';++// Queries+export {+ SearchMemoryQueryHandler,+ GetMemoryByKeyQueryHandler,+ type SearchMemoryInput,+ type SearchMemoryResult,+ type GetMemoryByKeyInput,+ type GetMemoryByKeyResult,+} from './queries/search-memory.query.js';++// Application Service+export { MemoryApplicationService } from './services/memory-application-service.js';diff --git a/v3/@claude-flow/memory/src/application/queries/search-memory.query.ts b/v3/@claude-flow/memory/src/application/queries/search-memory.query.tsnew file mode 100644index 0000000000..d5123e2dea--- /dev/null+++ b/v3/@claude-flow/memory/src/application/queries/search-memory.query.ts@@ -0,0 +1,237 @@+/**+ * Search Memory Query - Application Layer (CQRS)+ *+ * Query for searching memory entries.+ * Supports text search, vector search, and filtering.+ *+ * @module v3/memory/application/queries+ */++import { MemoryEntry, MemoryType, MemoryStatus } from '../../domain/entities/memory-entry.js';+import {+ IMemoryRepository,+ VectorSearchResult,+ MemoryQueryOptions,+} from '../../domain/repositories/memory-repository.interface.js';++/**+ * Search Memory Query Input+ */+export interface SearchMemoryInput {+ // Vector search+ vector?: Float32Array;+ similarityThreshold?: number;++ // Filter options+ namespace?: string;+ type?: MemoryType;+ status?: MemoryStatus;++ // Pagination+ limit?: number;+ offset?: number;++ // Sorting+ orderBy?: 'createdAt' | 'updatedAt' | 'accessCount' | 'lastAccessedAt';+ orderDirection?: 'asc' | 'desc';++ // Text search (searches in value and metadata)+ textQuery?: string;++ // Access tracking+ trackAccess?: boolean;+}++/**+ * Search Memory Query Result+ */+export interface SearchMemoryResult {+ entries: MemoryEntry[];+ total: number;+ hasMore: boolean;+ searchType: 'vector' | 'filter' | 'text';+ similarities?: number[];+}++/**+ * Search Memory Query Handler+ */+export class SearchMemoryQueryHandler {+ constructor(private readonly repository: IMemoryRepository) {}++ async execute(input: SearchMemoryInput): Promise<SearchMemoryResult> {+ const limit = input.limit ?? 10;+ const offset = input.offset ?? 0;++ // Vector search takes precedence+ if (input.vector) {+ return this.executeVectorSearch(input, limit, offset);+ }++ // Text search+ if (input.textQuery) {+ return this.executeTextSearch(input, limit, offset);+ }++ // Filter-based search+ return this.executeFilterSearch(input, limit, offset);+ }++ private async executeVectorSearch(+ input: SearchMemoryInput,+ limit: number,+ offset: number+ ): Promise<SearchMemoryResult> {+ const results = await this.repository.searchByVector({+ vector: input.vector!,+ namespace: input.namespace,+ limit: limit + offset, // Get extra for pagination+ threshold: input.similarityThreshold ?? 0.5,+ type: input.type,+ });++ // Apply offset+ const paginatedResults = results.slice(offset, offset + limit);++ // Track access if requested+ if (input.trackAccess) {+ await this.trackEntryAccess(paginatedResults.map((r) => r.entry));+ }++ return {+ entries: paginatedResults.map((r) => r.entry),+ total: results.length,+ hasMore: results.length > offset + limit,+ searchType: 'vector',+ similarities: paginatedResults.map((r) => r.similarity),+ };+ }++ private async executeTextSearch(+ input: SearchMemoryInput,+ limit: number,+ offset: number+ ): Promise<SearchMemoryResult> {+ // Get all entries matching filters+ const options: MemoryQueryOptions = {+ namespace: input.namespace,+ type: input.type,+ status: input.status ?? 'active',+ orderBy: input.orderBy ?? 'createdAt',+ orderDirection: input.orderDirection ?? 'desc',+ };++ const allEntries = await this.repository.findAll(options);++ // Filter by text query+ const query = input.textQuery!.toLowerCase();+ const matchingEntries = allEntries.filter((entry) => {+ const valueStr = JSON.stringify(entry.value).toLowerCase();+ const metadataStr = JSON.stringify(entry.metadata).toLowerCase();+ return valueStr.includes(query) || metadataStr.includes(query);+ });++ // Paginate+ const paginatedEntries = matchingEntries.slice(offset, offset + limit);++ // Track access if requested+ if (input.trackAccess) {+ await this.trackEntryAccess(paginatedEntries);+ }++ return {+ entries: paginatedEntries,+ total: matchingEntries.length,+ hasMore: matchingEntries.length > offset + limit,+ searchType: 'text',+ };+ }++ private async executeFilterSearch(+ input: SearchMemoryInput,+ limit: number,+ offset: number+ ): Promise<SearchMemoryResult> {+ const options: MemoryQueryOptions = {+ namespace: input.namespace,+ type: input.type,+ status: input.status ?? 'active',+ limit,+ offset,+ orderBy: input.orderBy ?? 'createdAt',+ orderDirection: input.orderDirection ?? 'desc',+ };++ const entries = await this.repository.findAll(options);+ const total = await this.repository.count({+ namespace: input.namespace,+ type: input.type,+ status: input.status ?? 'active',+ });++ // Track access if requested+ if (input.trackAccess) {+ await this.trackEntryAccess(entries);+ }++ return {+ entries,+ total,+ hasMore: total > offset + limit,+ searchType: 'filter',+ };+ }++ private async trackEntryAccess(entries: MemoryEntry[]): Promise<void> {+ for (const entry of entries) {+ entry.recordAccess();+ await this.repository.save(entry);+ }+ }+}++/**+ * Get Memory By Key Query Input+ */+export interface GetMemoryByKeyInput {+ namespace: string;+ key: string;+ trackAccess?: boolean;+}++/**+ * Get Memory By Key Query Result+ */+export interface GetMemoryByKeyResult {+ found: boolean;+ entry?: MemoryEntry;+}++/**+ * Get Memory By Key Query Handler+ */+export class GetMemoryByKeyQueryHandler {+ constructor(private readonly repository: IMemoryRepository) {}++ async execute(input: GetMemoryByKeyInput): Promise<GetMemoryByKeyResult> {+ const entry = await this.repository.findByKey(input.namespace, input.key);++ if (!entry) {+ return { found: false };+ }++ if (!entry.isAccessible()) {+ return { found: false };+ }++ if (input.trackAccess) {+ entry.recordAccess();+ await this.repository.save(entry);+ }++ return {+ found: true,+ entry,+ };+ }+}diff --git a/v3/@claude-flow/memory/src/application/services/memory-application-service.ts b/v3/@claude-flow/memory/src/application/services/memory-application-service.tsnew file mode 100644index 0000000000..05d4e86b9b--- /dev/null+++ b/v3/@claude-flow/memory/src/application/services/memory-application-service.ts@@ -0,0 +1,236 @@+/**+ * Memory Application Service - Application Layer+ *+ * Orchestrates use cases and coordinates between domain and infrastructure.+ * Provides a simplified interface for external consumers.+ *+ * @module v3/memory/application/services+ */++import { MemoryEntry, MemoryType } from '../../domain/entities/memory-entry.js';+import { IMemoryRepository, VectorSearchResult, MemoryStatistics } from '../../domain/repositories/memory-repository.interface.js';+import { MemoryDomainService, ConsolidationOptions, ConsolidationResult } from '../../domain/services/memory-domain-service.js';+import { StoreMemoryCommandHandler, StoreMemoryInput } from '../commands/store-memory.command.js';+import { DeleteMemoryCommandHandler, BulkDeleteMemoryCommandHandler } from '../commands/delete-memory.command.js';+import { SearchMemoryQueryHandler, SearchMemoryInput, GetMemoryByKeyQueryHandler } from '../queries/search-memory.query.js';++/**+ * Memory Application Service+ *+ * Main entry point for memory operations.+ * Coordinates commands and queries with domain services.+ */+export class MemoryApplicationService {+ private readonly domainService: MemoryDomainService;+ private readonly storeHandler: StoreMemoryCommandHandler;+ private readonly deleteHandler: DeleteMemoryCommandHandler;+ private readonly bulkDeleteHandler: BulkDeleteMemoryCommandHandler;+ private readonly searchHandler: SearchMemoryQueryHandler;+ private readonly getByKeyHandler: GetMemoryByKeyQueryHandler;++ constructor(private readonly repository: IMemoryRepository) {+ this.domainService = new MemoryDomainService(repository);+ this.storeHandler = new StoreMemoryCommandHandler(repository, this.domainService);+ this.deleteHandler = new DeleteMemoryCommandHandler(repository);+ this.bulkDeleteHandler = new BulkDeleteMemoryCommandHandler(repository);+ this.searchHandler = new SearchMemoryQueryHandler(repository);+ this.getByKeyHandler = new GetMemoryByKeyQueryHandler(repository);+ }++ // ============================================================================+ // Store Operations (Commands)+ // ============================================================================++ /**+ * Store a memory entry+ */+ async store(input: StoreMemoryInput): Promise<MemoryEntry> {+ const result = await this.storeHandler.execute(input);+ return result.entry;+ }++ /**+ * Store multiple memory entries+ */+ async storeMany(inputs: StoreMemoryInput[]): Promise<MemoryEntry[]> {+ const results = await Promise.all(inputs.map((input) => this.storeHandler.execute(input)));+ return results.map((r) => r.entry);+ }++ // ============================================================================+ // Retrieve Operations (Queries)+ // ============================================================================++ /**+ * Get a memory entry by namespace and key+ */+ async get(namespace: string, key: string): Promise<MemoryEntry | null> {+ const result = await this.getByKeyHandler.execute({ namespace, key, trackAccess: true });+ return result.entry ?? null;+ }++ /**+ * Get a memory entry by ID+ */+ async getById(id: string): Promise<MemoryEntry | null> {+ return this.repository.findById(id);+ }++ /**+ * Search memory entries+ */+ async search(input: SearchMemoryInput): Promise<{+ entries: MemoryEntry[];+ total: number;+ hasMore: boolean;+ }> {+ const result = await this.searchHandler.execute(input);+ return {+ entries: result.entries,+ total: result.total,+ hasMore: result.hasMore,+ };+ }++ /**+ * Search by vector similarity+ */+ async searchByVector(+ vector: Float32Array,+ options?: {+ namespace?: string;+ limit?: number;+ threshold?: number;+ }+ ): Promise<VectorSearchResult[]> {+ return this.domainService.searchSimilarWithTracking(+ vector,+ options?.namespace,+ options?.limit ?? 10+ );+ }++ /**+ * Get all entries in a namespace+ */+ async getNamespace(namespace: string): Promise<MemoryEntry[]> {+ return this.repository.findByNamespace(namespace, { status: 'active' });+ }++ /**+ * List all namespaces+ */+ async listNamespaces(): Promise<string[]> {+ return this.repository.listNamespaces();+ }++ // ============================================================================+ // Delete Operations (Commands)+ // ============================================================================++ /**+ * Delete a memory entry by namespace and key+ */+ async delete(namespace: string, key: string, hardDelete = false): Promise<boolean> {+ const result = await this.deleteHandler.execute({ namespace, key, hardDelete });+ return result.deleted;+ }++ /**+ * Delete a memory entry by ID+ */+ async deleteById(id: string, hardDelete = false): Promise<boolean> {+ const result = await this.deleteHandler.execute({ id, hardDelete });+ return result.deleted;+ }++ /**+ * Delete all entries in a namespace+ */+ async deleteNamespace(namespace: string, hardDelete = false): Promise<number> {+ const entries = await this.repository.findByNamespace(namespace);+ const result = await this.bulkDeleteHandler.execute({+ ids: entries.map((e) => e.id),+ hardDelete,+ });+ return result.deletedCount;+ }++ /**+ * Clear all memory entries+ */+ async clear(): Promise<void> {+ await this.repository.clear();+ }++ // ============================================================================+ // Maintenance Operations+ // ============================================================================++ /**+ * Consolidate memories using specified strategy+ */+ async consolidate(options: ConsolidationOptions): Promise<ConsolidationResult> {+ return this.domainService.consolidate(options);+ }++ /**+ * Clean up expired memories+ */+ async cleanupExpired(): Promise<number> {+ return this.repository.deleteExpired();+ }++ /**+ * Archive cold (rarely accessed) memories+ */+ async archiveCold(milliseconds: number = 86400000): Promise<number> {+ return this.repository.archiveCold(milliseconds);+ }++ // ============================================================================+ // Statistics+ // ============================================================================++ /**+ * Get memory statistics+ */+ async getStatistics(): Promise<MemoryStatistics> {+ return this.repository.getStatistics();+ }++ /**+ * Count entries matching criteria+ */+ async count(options?: {+ namespace?: string;+ type?: MemoryType;+ }): Promise<number> {+ return this.repository.count(options);+ }++ /**+ * Analyze a namespace+ */+ async analyzeNamespace(namespace: string) {+ return this.domainService.analyzeNamespace(namespace);+ }++ // ============================================================================+ // Lifecycle+ // ============================================================================++ /**+ * Initialize the memory service+ */+ async initialize(): Promise<void> {+ await this.repository.initialize();+ }++ /**+ * Shutdown the memory service+ */+ async shutdown(): Promise<void> {+ await this.repository.shutdown();+ }+}diff --git a/v3/@claude-flow/memory/src/domain/entities/memory-entry.ts b/v3/@claude-flow/memory/src/domain/entities/memory-entry.tsnew file mode 100644index 0000000000..3845d97a46--- /dev/null+++ b/v3/@claude-flow/memory/src/domain/entities/memory-entry.ts@@ -0,0 +1,289 @@+/**+ * Memory Entry Entity - Domain Layer+ *+ * Core domain entity representing a stored memory item.+ * Implements DDD principles with encapsulated business logic.+ *+ * @module v3/memory/domain/entities+ */++import { randomUUID } from 'crypto';++/**+ * Memory entry types+ */+export type MemoryType = 'semantic' | 'episodic' | 'procedural' | 'working';++/**+ * Memory entry status+ */+export type MemoryStatus = 'active' | 'archived' | 'deleted';++/**+ * Memory entry properties+ */+export interface MemoryEntryProps {+ id?: string;+ namespace: string;+ key: string;+ value: unknown;+ type: MemoryType;+ vector?: Float32Array;+ metadata?: Record<string, unknown>;+ accessCount?: number;+ lastAccessedAt?: Date;+ createdAt?: Date;+ updatedAt?: Date;+ status?: MemoryStatus;+ ttl?: number; // Time-to-live in milliseconds+}++/**+ * Memory Entry - Aggregate Root+ *+ * Represents a single memory entry with business logic+ * for access tracking, expiration, and state management.+ */+export class MemoryEntry {+ private _id: string;+ private _namespace: string;+ private _key: string;+ private _value: unknown;+ private _type: MemoryType;+ private _vector?: Float32Array;+ private _metadata: Record<string, unknown>;+ private _accessCount: number;+ private _lastAccessedAt: Date;+ private _createdAt: Date;+ private _updatedAt: Date;+ private _status: MemoryStatus;+ private _ttl?: number;++ private constructor(props: MemoryEntryProps) {+ const now = new Date();+ this._id = props.id ?? randomUUID();+ this._namespace = props.namespace;+ this._key = props.key;+ this._value = props.value;+ this._type = props.type;+ this._vector = props.vector;+ this._metadata = props.metadata ?? {};+ this._accessCount = props.accessCount ?? 0;+ this._lastAccessedAt = props.lastAccessedAt ?? now;+ this._createdAt = props.createdAt ?? now;+ this._updatedAt = props.updatedAt ?? now;+ this._status = props.status ?? 'active';+ this._ttl = props.ttl;+ }++ /**+ * Factory method - Create new memory entry+ */+ static create(props: MemoryEntryProps): MemoryEntry {+ return new MemoryEntry(props);+ }++ /**+ * Factory method - Reconstruct from persistence+ */+ static fromPersistence(props: MemoryEntryProps): MemoryEntry {+ return new MemoryEntry(props);+ }++ // Getters+ get id(): string {+ return this._id;+ }++ get namespace(): string {+ return this._namespace;+ }++ get key(): string {+ return this._key;+ }++ get value(): unknown {+ return this._value;+ }++ get type(): MemoryType {+ return this._type;+ }++ get vector(): Float32Array | undefined {+ return this._vector;+ }++ get metadata(): Record<string, unknown> {+ return { ...this._metadata };+ }++ get accessCount(): number {+ return this._accessCount;+ }++ get lastAccessedAt(): Date {+ return new Date(this._lastAccessedAt);+ }++ get createdAt(): Date {+ return new Date(this._createdAt);+ }++ get updatedAt(): Date {+ return new Date(this._updatedAt);+ }++ get status(): MemoryStatus {+ return this._status;+ }++ get ttl(): number | undefined {+ return this._ttl;+ }++ get compositeKey(): string {+ return `${this._namespace}:${this._key}`;+ }++ // Business Logic Methods++ /**+ * Record an access to this memory entry+ */+ recordAccess(): void {+ this._accessCount++;+ this._lastAccessedAt = new Date();+ }++ /**+ * Update the value of this memory entry+ */+ updateValue(value: unknown): void {+ this._value = value;+ this._updatedAt = new Date();+ }++ /**+ * Update the vector embedding+ */+ updateVector(vector: Float32Array): void {+ this._vector = vector;+ this._updatedAt = new Date();+ }++ /**+ * Add or update metadata+ */+ setMetadata(key: string, value: unknown): void {+ this._metadata[key] = value;+ this._updatedAt = new Date();+ }++ /**+ * Remove metadata key+ */+ removeMetadata(key: string): void {+ delete this._metadata[key];+ this._updatedAt = new Date();+ }++ /**+ * Archive this memory entry+ */+ archive(): void {+ this._status = 'archived';+ this._updatedAt = new Date();+ }++ /**+ * Restore archived memory entry+ */+ restore(): void {+ if (this._status === 'archived') {+ this._status = 'active';+ this._updatedAt = new Date();+ }+ }++ /**+ * Mark as deleted (soft delete)+ */+ delete(): void {+ this._status = 'deleted';+ this._updatedAt = new Date();+ }++ /**+ * Check if memory has expired based on TTL+ */+ isExpired(): boolean {+ if (!this._ttl) return false;+ const expiresAt = this._createdAt.getTime() + this._ttl;+ return Date.now() > expiresAt;+ }++ /**+ * Check if memory is accessible (active and not expired)+ */+ isAccessible(): boolean {+ return this._status === 'active' && !this.isExpired();+ }++ /**+ * Calculate age in milliseconds+ */+ getAge(): number {+ return Date.now() - this._createdAt.getTime();+ }++ /**+ * Calculate time since last access in milliseconds+ */+ getTimeSinceLastAccess(): number {+ return Date.now() - this._lastAccessedAt.getTime();+ }++ /**+ * Check if memory is considered "hot" (frequently accessed)+ */+ isHot(threshold: number = 10): boolean {+ return this._accessCount >= threshold;+ }++ /**+ * Check if memory is considered "cold" (not accessed recently)+ */+ isCold(milliseconds: number = 3600000): boolean {+ return this.getTimeSinceLastAccess() > milliseconds;+ }++ /**+ * Convert to plain object for persistence+ */+ toPersistence(): Record<string, unknown> {+ return {+ id: this._id,+ namespace: this._namespace,+ key: this._key,+ value: this._value,+ type: this._type,+ vector: this._vector ? Array.from(this._vector) : undefined,+ metadata: this._metadata,+ accessCount: this._accessCount,+ lastAccessedAt: this._lastAccessedAt.toISOString(),+ createdAt: this._createdAt.toISOString(),+ updatedAt: this._updatedAt.toISOString(),+ status: this._status,+ ttl: this._ttl,+ };+ }++ /**+ * Convert to JSON-serializable object+ */+ toJSON(): Record<string, unknown> {+ return this.toPersistence();+ }+}diff --git a/v3/@claude-flow/memory/src/domain/index.ts b/v3/@claude-flow/memory/src/domain/index.tsnew file mode 100644index 0000000000..ad2d6b0341--- /dev/null+++ b/v3/@claude-flow/memory/src/domain/index.ts@@ -0,0 +1,35 @@+/**+ * Memory Domain Layer - Public Exports+ *+ * Exports all domain entities, value objects, services, and interfaces.+ *+ * @module v3/memory/domain+ */++// Entities+export {+ MemoryEntry,+ type MemoryType,+ type MemoryStatus,+ type MemoryEntryProps,+} from './entities/memory-entry.js';++// Repository Interfaces+export {+ type IMemoryRepository,+ type MemoryQueryOptions,+ type VectorSearchOptions,+ type VectorSearchResult,+ type BulkOperationResult,+ type MemoryStatistics,+} from './repositories/memory-repository.interface.js';++// Domain Services+export {+ MemoryDomainService,+ type ConsolidationStrategy,+ type ConsolidationOptions,+ type ConsolidationResult,+ type DeduplicationResult,+ type NamespaceAnalysis,+} from './services/memory-domain-service.js';diff --git a/v3/@claude-flow/memory/src/domain/repositories/memory-repository.interface.ts b/v3/@claude-flow/memory/src/domain/repositories/memory-repository.interface.tsnew file mode 100644index 0000000000..83e874ff15--- /dev/null+++ b/v3/@claude-flow/memory/src/domain/repositories/memory-repository.interface.ts@@ -0,0 +1,120 @@+/**+ * Memory Repository Interface - Domain Layer+ *+ * Defines the contract for memory persistence.+ * Following DDD, the interface belongs to the domain layer+ * while implementations belong to infrastructure.+ *+ * @module v3/memory/domain/repositories+ */++import { MemoryEntry, MemoryType, MemoryStatus } from '../entities/memory-entry.js';++/**+ * Query options for memory retrieval+ */+export interface MemoryQueryOptions {+ namespace?: string;+ type?: MemoryType;+ status?: MemoryStatus;+ limit?: number;+ offset?: number;+ orderBy?: 'createdAt' | 'updatedAt' | 'accessCount' | 'lastAccessedAt';+ orderDirection?: 'asc' | 'desc';+}++/**+ * Vector search options+ */+export interface VectorSearchOptions {+ vector: Float32Array;+ namespace?: string;+ limit?: number;+ threshold?: number; // Minimum similarity score+ type?: MemoryType;+}++/**+ * Vector search result+ */+export interface VectorSearchResult {+ entry: MemoryEntry;+ similarity: number;+ distance: number;+}++/**+ * Bulk operation result+ */+export interface BulkOperationResult {+ success: number;+ failed: number;+ errors: Array<{ id: string; error: string }>;+}++/**+ * Memory statistics+ */+export interface MemoryStatistics {+ totalEntries: number;+ activeEntries: number;+ archivedEntries: number;+ deletedEntries: number;+ totalSize: number;+ entriesByNamespace: Record<string, number>;+ entriesByType: Record<MemoryType, number>;+ averageAccessCount: number;+ hottestEntries: string[];+ coldestEntries: string[];+}++/**+ * Memory Repository Interface+ *+ * Defines all operations for memory persistence.+ * Implementations can use SQLite, AgentDB, or hybrid backends.+ */+export interface IMemoryRepository {+ // Basic CRUD Operations+ save(entry: MemoryEntry): Promise<void>;+ findById(id: string): Promise<MemoryEntry | null>;+ findByKey(namespace: string, key: string): Promise<MemoryEntry | null>;+ findByCompositeKey(compositeKey: string): Promise<MemoryEntry | null>;+ delete(id: string): Promise<boolean>;+ exists(id: string): Promise<boolean>;++ // Bulk Operations+ saveMany(entries: MemoryEntry[]): Promise<BulkOperationResult>;+ findByIds(ids: string[]): Promise<MemoryEntry[]>;+ deleteMany(ids: string[]): Promise<BulkOperationResult>;++ // Query Operations+ findAll(options?: MemoryQueryOptions): Promise<MemoryEntry[]>;+ findByNamespace(namespace: string, options?: Omit<MemoryQueryOptions, 'namespace'>): Promise<MemoryEntry[]>;+ findByType(type: MemoryType, options?: Omit<MemoryQueryOptions, 'type'>): Promise<MemoryEntry[]>;+ findByStatus(status: MemoryStatus, options?: Omit<MemoryQueryOptions, 'status'>): Promise<MemoryEntry[]>;++ // Vector Search Operations+ searchByVector(options: VectorSearchOptions): Promise<VectorSearchResult[]>;+ findSimilar(entryId: string, limit?: number): Promise<VectorSearchResult[]>;++ // Maintenance Operations+ findExpired(): Promise<MemoryEntry[]>;+ deleteExpired(): Promise<number>;+ findCold(milliseconds: number): Promise<MemoryEntry[]>;+ archiveCold(milliseconds: number): Promise<number>;++ // Statistics+ getStatistics(): Promise<MemoryStatistics>;+ count(options?: MemoryQueryOptions): Promise<number>;++ // Namespace Operations+ listNamespaces(): Promise<string[]>;+ deleteNamespace(namespace: string): Promise<number>;+ getNamespaceSize(namespace: string): Promise<number>;++ // Lifecycle+ initialize(): Promise<void>;+ shutdown(): Promise<void>;+ clear(): Promise<void>;+}diff --git a/v3/@claude-flow/memory/src/domain/services/memory-domain-service.ts b/v3/@claude-flow/memory/src/domain/services/memory-domain-service.tsnew file mode 100644index 0000000000..b3491c6a85--- /dev/null+++ b/v3/@claude-flow/memory/src/domain/services/memory-domain-service.ts@@ -0,0 +1,403 @@+/**+ * Memory Domain Service - Domain Layer+ *+ * Contains domain logic that doesn't naturally fit within a single entity.+ * Coordinates between multiple memory entries and enforces domain rules.+ *+ * @module v3/memory/domain/services+ */++import { MemoryEntry, MemoryType, MemoryEntryProps } from '../entities/memory-entry.js';+import { IMemoryRepository, VectorSearchResult } from '../repositories/memory-repository.interface.js';++/**+ * Memory consolidation strategy+ */+export type ConsolidationStrategy = 'merge' | 'dedupe' | 'prune' | 'summarize';++/**+ * Memory consolidation options+ */+export interface ConsolidationOptions {+ strategy: ConsolidationStrategy;+ namespace?: string;+ threshold?: number;+ maxAge?: number; // Maximum age in milliseconds+ keepHot?: boolean; // Keep frequently accessed memories+}++/**+ * Consolidation result+ */+export interface ConsolidationResult {+ processed: number;+ consolidated: number;+ removed: number;+ newEntries: MemoryEntry[];+}++/**+ * Memory deduplication result+ */+export interface DeduplicationResult {+ duplicatesFound: number;+ duplicatesRemoved: number;+ groupsProcessed: number;+}++/**+ * Memory namespace statistics+ */+export interface NamespaceAnalysis {+ namespace: string;+ totalEntries: number;+ activeEntries: number;+ totalSize: number;+ averageAccessCount: number;+ oldestEntry: Date;+ newestEntry: Date;+ typeDistribution: Record<MemoryType, number>;+}++/**+ * Memory Domain Service+ *+ * Provides domain-level operations that span multiple entities.+ * Implements business rules for memory management.+ */+export class MemoryDomainService {+ constructor(private readonly repository: IMemoryRepository) {}++ /**+ * Store a new memory with automatic type detection+ */+ async storeWithTypeDetection(+ namespace: string,+ key: string,+ value: unknown,+ vector?: Float32Array+ ): Promise<MemoryEntry> {+ const type = this.detectMemoryType(value);+ const entry = MemoryEntry.create({+ namespace,+ key,+ value,+ type,+ vector,+ });+ await this.repository.save(entry);+ return entry;+ }++ /**+ * Retrieve and record access+ */+ async retrieveWithAccessTracking(+ namespace: string,+ key: string+ ): Promise<MemoryEntry | null> {+ const entry = await this.repository.findByKey(namespace, key);+ if (entry && entry.isAccessible()) {+ entry.recordAccess();+ await this.repository.save(entry);+ }+ return entry;+ }++ /**+ * Search for similar memories and record access+ */+ async searchSimilarWithTracking(+ vector: Float32Array,+ namespace?: string,+ limit: number = 10+ ): Promise<VectorSearchResult[]> {+ const results = await this.repository.searchByVector({+ vector,+ namespace,+ limit,+ });++ // Record access for all returned entries+ await Promise.all(+ results.map(async (result) => {+ result.entry.recordAccess();+ await this.repository.save(result.entry);+ })+ );++ return results;+ }++ /**+ * Consolidate memories based on strategy+ */+ async consolidate(options: ConsolidationOptions): Promise<ConsolidationResult> {+ const entries = await this.repository.findByNamespace(+ options.namespace ?? 'default',+ { status: 'active' }+ );++ let result: ConsolidationResult = {+ processed: entries.length,+ consolidated: 0,+ removed: 0,+ newEntries: [],+ };++ switch (options.strategy) {+ case 'prune':+ result = await this.pruneOldMemories(entries, options);+ break;+ case 'dedupe':+ const dedupeResult = await this.deduplicateMemories(entries, options);+ result.removed = dedupeResult.duplicatesRemoved;+ break;+ case 'merge':+ result = await this.mergeRelatedMemories(entries, options);+ break;+ default:+ // No-op for unknown strategies+ }++ return result;+ }++ /**+ * Detect memory type based on value structure+ */+ private detectMemoryType(value: unknown): MemoryType {+ if (typeof value === 'string') {+ // Long text is likely semantic+ if (value.length > 500) return 'semantic';+ // Short instructions are procedural+ if (value.includes('->') || value.includes('then')) return 'procedural';+ }++ if (typeof value === 'object' && value !== null) {+ const obj = value as Record<string, unknown>;+ // Objects with timestamps are episodic+ if ('timestamp' in obj || 'when' in obj || 'date' in obj) return 'episodic';+ // Objects with steps are procedural+ if ('steps' in obj || 'actions' in obj) return 'procedural';+ }++ // Default to working memory for short-term storage+ return 'working';+ }++ /**+ * Prune old, rarely accessed memories+ */+ private async pruneOldMemories(+ entries: MemoryEntry[],+ options: ConsolidationOptions+ ): Promise<ConsolidationResult> {+ const maxAge = options.maxAge ?? 7 * 24 * 60 * 60 * 1000; // 7 days default+ const threshold = options.threshold ?? 5; // Minimum access count to keep+ const now = Date.now();+ const toRemove: string[] = [];++ for (const entry of entries) {+ const age = now - entry.createdAt.getTime();+ const isOld = age > maxAge;+ const isRarelyAccessed = entry.accessCount < threshold;++ // Keep hot memories if requested+ if (options.keepHot && entry.isHot()) continue;++ if (isOld && isRarelyAccessed) {+ entry.archive();+ toRemove.push(entry.id);+ }+ }++ if (toRemove.length > 0) {+ await this.repository.deleteMany(toRemove);+ }++ return {+ processed: entries.length,+ consolidated: 0,+ removed: toRemove.length,+ newEntries: [],+ };+ }++ /**+ * Find and remove duplicate memories+ */+ private async deduplicateMemories(+ entries: MemoryEntry[],+ options: ConsolidationOptions+ ): Promise<DeduplicationResult> {+ const threshold = options.threshold ?? 0.95; // Similarity threshold+ const duplicates: string[] = [];+ const processed = new Set<string>();++ for (let i = 0; i < entries.length; i++) {+ if (processed.has(entries[i].id)) continue;++ const entry = entries[i];+ if (!entry.vector) continue;++ // Find similar entries+ const similar = await this.repository.searchByVector({+ vector: entry.vector,+ namespace: entry.namespace,+ limit: 10,+ threshold,+ });++ // Mark duplicates (keep the one with highest access count)+ const group = similar+ .filter((s) => s.entry.id !== entry.id && s.similarity >= threshold)+ .sort((a, b) => b.entry.accessCount - a.entry.accessCount);++ for (const dup of group.slice(1)) {+ duplicates.push(dup.entry.id);+ processed.add(dup.entry.id);+ }++ processed.add(entry.id);+ }++ if (duplicates.length > 0) {+ await this.repository.deleteMany(duplicates);+ }++ return {+ duplicatesFound: duplicates.length,+ duplicatesRemoved: duplicates.length,+ groupsProcessed: processed.size,+ };+ }++ /**+ * Merge related memories into consolidated entries+ */+ private async mergeRelatedMemories(+ entries: MemoryEntry[],+ options: ConsolidationOptions+ ): Promise<ConsolidationResult> {+ const threshold = options.threshold ?? 0.8;+ const newEntries: MemoryEntry[] = [];+ const toRemove: string[] = [];+ const processed = new Set<string>();++ for (const entry of entries) {+ if (processed.has(entry.id)) continue;+ if (!entry.vector) {+ processed.add(entry.id);+ continue;+ }++ // Find related entries+ const related = await this.repository.searchByVector({+ vector: entry.vector,+ namespace: entry.namespace,+ limit: 5,+ threshold,+ });++ if (related.length > 1) {+ // Merge related entries+ const merged = this.mergeEntries(related.map((r) => r.entry));+ newEntries.push(merged);++ for (const r of related) {+ toRemove.push(r.entry.id);+ processed.add(r.entry.id);+ }+ } else {+ processed.add(entry.id);+ }+ }++ // Remove old entries and save merged ones+ if (toRemove.length > 0) {+ await this.repository.deleteMany(toRemove);+ }+ if (newEntries.length > 0) {+ await this.repository.saveMany(newEntries);+ }++ return {+ processed: entries.length,+ consolidated: newEntries.length,+ removed: toRemove.length,+ newEntries,+ };+ }++ /**+ * Merge multiple entries into one+ */+ private mergeEntries(entries: MemoryEntry[]): MemoryEntry {+ // Sort by access count to prioritize most accessed+ const sorted = [...entries].sort((a, b) => b.accessCount - a.accessCount);+ const primary = sorted[0];++ // Combine metadata+ const combinedMetadata: Record<string, unknown> = {};+ for (const entry of entries) {+ Object.assign(combinedMetadata, entry.metadata);+ }+ combinedMetadata.mergedFrom = entries.map((e) => e.id);+ combinedMetadata.mergedAt = new Date().toISOString();++ // Create merged entry+ return MemoryEntry.create({+ namespace: primary.namespace,+ key: `merged_${Date.now()}`,+ value: {+ primary: primary.value,+ related: sorted.slice(1).map((e) => e.value),+ },+ type: primary.type,+ vector: primary.vector,+ metadata: combinedMetadata,+ accessCount: entries.reduce((sum, e) => sum + e.accessCount, 0),+ });+ }++ /**+ * Analyze a namespace+ */+ async analyzeNamespace(namespace: string): Promise<NamespaceAnalysis> {+ const entries = await this.repository.findByNamespace(namespace);+ const active = entries.filter((e) => e.status === 'active');++ const typeDistribution: Record<MemoryType, number> = {+ semantic: 0,+ episodic: 0,+ procedural: 0,+ working: 0,+ };++ let totalAccessCount = 0;+ let totalSize = 0;+ let oldestDate = new Date();+ let newestDate = new Date(0);++ for (const entry of entries) {+ typeDistribution[entry.type]++;+ totalAccessCount += entry.accessCount;+ totalSize += JSON.stringify(entry.value).length;++ if (entry.createdAt < oldestDate) oldestDate = entry.createdAt;+ if (entry.createdAt > newestDate) newestDate = entry.createdAt;+ }++ return {+ namespace,+ totalEntries: entries.length,+ activeEntries: active.length,+ totalSize,+ averageAccessCount: entries.length > 0 ? totalAccessCount / entries.length : 0,+ oldestEntry: oldestDate,+ newestEntry: newestDate,+ typeDistribution,+ };+ }+}diff --git a/v3/@claude-flow/memory/src/infrastructure/index.ts b/v3/@claude-flow/memory/src/infrastructure/index.tsnew file mode 100644index 0000000000..3aad3a6bb6--- /dev/null+++ b/v3/@claude-flow/memory/src/infrastructure/index.ts@@ -0,0 +1,20 @@+/**+ * Memory Infrastructure Layer - Public Exports+ *+ * Exports all infrastructure implementations including repositories,+ * adapters, and external service integrations.+ *+ * @module v3/memory/infrastructure+ */++// Repositories+export {+ HybridMemoryRepository,+ type HybridRepositoryConfig,+} from './repositories/hybrid-memory-repository.js';++// Re-export existing adapters+export { AgentDBAdapter, type AgentDBConfig } from '../agentdb-adapter.js';+export { HNSWIndex, type HNSWConfig } from '../hnsw-index.js';+export { CacheManager, type CacheConfig } from '../cache-manager.js';+export { MigrationManager } from '../migration.js';diff --git a/v3/@claude-flow/memory/src/infrastructure/repositories/hybrid-memory-repository.ts b/v3/@claude-flow/memory/src/infrastructure/repositories/hybrid-memory-repository.tsnew file mode 100644index 0000000000..8b62e2f848--- /dev/null+++ b/v3/@claude-flow/memory/src/infrastructure/repositories/hybrid-memory-repository.ts@@ -0,0 +1,516 @@+/**+ * Hybrid Memory Repository - Infrastructure Layer+ *+ * Implements IMemoryRepository using SQLite + AgentDB hybrid backend.+ * Per ADR-009, this is the default memory backend.+ *+ * @module v3/memory/infrastructure/repositories+ */++import { MemoryEntry, MemoryType, MemoryStatus } from '../../domain/entities/memory-entry.js';+import {+ IMemoryRepository,+ MemoryQueryOptions,+ VectorSearchOptions,+ VectorSearchResult,+ BulkOperationResult,+ MemoryStatistics,+} from '../../domain/repositories/memory-repository.interface.js';++/**+ * Repository configuration+ */+export interface HybridRepositoryConfig {+ sqlitePath: string;+ agentDbPath?: string;+ enableVectorSearch?: boolean;+ cacheSize?: number;+ verbose?: boolean;+}++/**+ * In-memory cache for hot entries+ */+interface CacheEntry {+ entry: MemoryEntry;+ timestamp: number;+}++/**+ * Hybrid Memory Repository+ *+ * Uses SQLite for metadata and AgentDB for vectors.+ * Implements hot caching for frequently accessed entries.+ */+export class HybridMemoryRepository implements IMemoryRepository {+ private entries: Map<string, MemoryEntry> = new Map();+ private namespaceIndex: Map<string, Set<string>> = new Map();+ private vectorIndex: Map<string, Float32Array> = new Map();+ private cache: Map<string, CacheEntry> = new Map();+ private initialized = false;++ constructor(private readonly config: HybridRepositoryConfig) {}++ // ============================================================================+ // Lifecycle+ // ============================================================================++ async initialize(): Promise<void> {+ if (this.initialized) return;++ // In production, would initialize SQLite and AgentDB connections+ // For now, using in-memory implementation+ this.entries = new Map();+ this.namespaceIndex = new Map();+ this.vectorIndex = new Map();+ this.cache = new Map();++ this.initialized = true;+ }++ async shutdown(): Promise<void> {+ // Clear all data+ this.cache.clear();+ this.initialized = false;+ }++ async clear(): Promise<void> {+ this.entries.clear();+ this.namespaceIndex.clear();+ this.vectorIndex.clear();+ this.cache.clear();+ }++ // ============================================================================+ // Basic CRUD+ // ============================================================================++ async save(entry: MemoryEntry): Promise<void> {+ this.ensureInitialized();++ // Store entry+ this.entries.set(entry.id, entry);++ // Update namespace index+ if (!this.namespaceIndex.has(entry.namespace)) {+ this.namespaceIndex.set(entry.namespace, new Set());+ }+ this.namespaceIndex.get(entry.namespace)!.add(entry.id);++ // Store vector if present+ if (entry.vector) {+ this.vectorIndex.set(entry.id, entry.vector);+ }++ // Update cache+ this.updateCache(entry);+ }++ async findById(id: string): Promise<MemoryEntry | null> {+ this.ensureInitialized();++ // Check cache first+ const cached = this.cache.get(id);+ if (cached) {+ return cached.entry;+ }++ return this.entries.get(id) ?? null;+ }++ async findByKey(namespace: string, key: string): Promise<MemoryEntry | null> {+ this.ensureInitialized();++ for (const entry of this.entries.values()) {+ if (entry.namespace === namespace && entry.key === key) {+ return entry;+ }+ }+ return null;+ }++ async findByCompositeKey(compositeKey: string): Promise<MemoryEntry | null> {+ const [namespace, key] = compositeKey.split(':');+ return this.findByKey(namespace, key);+ }++ async delete(id: string): Promise<boolean> {+ this.ensureInitialized();++ const entry = this.entries.get(id);+ if (!entry) return false;++ // Remove from all indexes+ this.entries.delete(id);+ this.namespaceIndex.get(entry.namespace)?.delete(id);+ this.vectorIndex.delete(id);+ this.cache.delete(id);++ return true;+ }++ async exists(id: string): Promise<boolean> {+ return this.entries.has(id);+ }++ // ============================================================================+ // Bulk Operations+ // ============================================================================++ async saveMany(entries: MemoryEntry[]): Promise<BulkOperationResult> {+ const errors: Array<{ id: string; error: string }> = [];+ let success = 0;++ for (const entry of entries) {+ try {+ await this.save(entry);+ success++;+ } catch (error) {+ errors.push({+ id: entry.id,+ error: error instanceof Error ? error.message : 'Unknown error',+ });+ }+ }++ return {+ success,+ failed: errors.length,+ errors,+ };+ }++ async findByIds(ids: string[]): Promise<MemoryEntry[]> {+ return ids+ .map((id) => this.entries.get(id))+ .filter((e): e is MemoryEntry => e !== undefined);+ }++ async deleteMany(ids: string[]): Promise<BulkOperationResult> {+ const errors: Array<{ id: string; error: string }> = [];+ let success = 0;++ for (const id of ids) {+ try {+ if (await this.delete(id)) {+ success++;+ } else {+ errors.push({ id, error: 'Entry not found' });+ }+ } catch (error) {+ errors.push({+ id,+ error: error instanceof Error ? error.message : 'Unknown error',+ });+ }+ }++ return {+ success,+ failed: errors.length,+ errors,+ };+ }++ // ============================================================================+ // Query Operations+ // ============================================================================++ async findAll(options?: MemoryQueryOptions): Promise<MemoryEntry[]> {+ this.ensureInitialized();++ let results = Array.from(this.entries.values());++ // Apply filters+ if (options?.namespace) {+ results = results.filter((e) => e.namespace === options.namespace);+ }+ if (options?.type) {+ results = results.filter((e) => e.type === options.type);+ }+ if (options?.status) {+ results = results.filter((e) => e.status === options.status);+ }++ // Apply sorting+ const orderBy = options?.orderBy ?? 'createdAt';+ const orderDir = options?.orderDirection ?? 'desc';+ results.sort((a, b) => {+ let aVal: number, bVal: number;+ switch (orderBy) {+ case 'accessCount':+ aVal = a.accessCount;+ bVal = b.accessCount;+ break;+ case 'lastAccessedAt':+ aVal = a.lastAccessedAt.getTime();+ bVal = b.lastAccessedAt.getTime();+ break;+ case 'updatedAt':+ aVal = a.updatedAt.getTime();+ bVal = b.updatedAt.getTime();+ break;+ default:+ aVal = a.createdAt.getTime();+ bVal = b.createdAt.getTime();+ }+ return orderDir === 'asc' ? aVal - bVal : bVal - aVal;+ });++ // Apply pagination+ if (options?.offset) {+ results = results.slice(options.offset);+ }+ if (options?.limit) {+ results = results.slice(0, options.limit);+ }++ return results;+ }++ async findByNamespace(+ namespace: string,+ options?: Omit<MemoryQueryOptions, 'namespace'>+ ): Promise<MemoryEntry[]> {+ return this.findAll({ ...options, namespace });+ }++ async findByType(+ type: MemoryType,+ options?: Omit<MemoryQueryOptions, 'type'>+ ): Promise<MemoryEntry[]> {+ return this.findAll({ ...options, type });+ }++ async findByStatus(+ status: MemoryStatus,+ options?: Omit<MemoryQueryOptions, 'status'>+ ): Promise<MemoryEntry[]> {+ return this.findAll({ ...options, status });+ }++ // ============================================================================+ // Vector Search+ // ============================================================================++ async searchByVector(options: VectorSearchOptions): Promise<VectorSearchResult[]> {+ this.ensureInitialized();++ const results: VectorSearchResult[] = [];++ for (const [id, vector] of this.vectorIndex) {+ const entry = this.entries.get(id);+ if (!entry) continue;+ if (options.namespace && entry.namespace !== options.namespace) continue;+ if (options.type && entry.type !== options.type) continue;++ const similarity = this.cosineSimilarity(options.vector, vector);+ const threshold = options.threshold ?? 0.5;++ if (similarity >= threshold) {+ results.push({+ entry,+ similarity,+ distance: 1 - similarity,+ });+ }+ }++ // Sort by similarity descending+ results.sort((a, b) => b.similarity - a.similarity);++ // Limit results+ return results.slice(0, options.limit ?? 10);+ }++ async findSimilar(entryId: string, limit = 10): Promise<VectorSearchResult[]> {+ const entry = this.entries.get(entryId);+ if (!entry || !entry.vector) return [];++ return this.searchByVector({+ vector: entry.vector,+ namespace: entry.namespace,+ limit: limit + 1, // Include self+ }).then((results) => results.filter((r) => r.entry.id !== entryId).slice(0, limit));+ }++ // ============================================================================+ // Maintenance Operations+ // ============================================================================++ async findExpired(): Promise<MemoryEntry[]> {+ return Array.from(this.entries.values()).filter((e) => e.isExpired());+ }++ async deleteExpired(): Promise<number> {+ const expired = await this.findExpired();+ for (const entry of expired) {+ await this.delete(entry.id);+ }+ return expired.length;+ }++ async findCold(milliseconds: number): Promise<MemoryEntry[]> {+ return Array.from(this.entries.values()).filter((e) => e.isCold(milliseconds));+ }++ async archiveCold(milliseconds: number): Promise<number> {+ const cold = await this.findCold(milliseconds);+ for (const entry of cold) {+ entry.archive();+ await this.save(entry);+ }+ return cold.length;+ }++ // ============================================================================+ // Statistics+ // ============================================================================++ async getStatistics(): Promise<MemoryStatistics> {+ const entries = Array.from(this.entries.values());++ const entriesByNamespace: Record<string, number> = {};+ const entriesByType: Record<MemoryType, number> = {+ semantic: 0,+ episodic: 0,+ procedural: 0,+ working: 0,+ };++ let totalAccessCount = 0;+ let totalSize = 0;+ let activeCount = 0;+ let archivedCount = 0;+ let deletedCount = 0;++ for (const entry of entries) {+ // Count by namespace+ entriesByNamespace[entry.namespace] = (entriesByNamespace[entry.namespace] ?? 0) + 1;++ // Count by type+ entriesByType[entry.type]++;++ // Accumulate stats+ totalAccessCount += entry.accessCount;+ totalSize += JSON.stringify(entry.value).length;++ // Count by status+ switch (entry.status) {+ case 'active':+ activeCount++;+ break;+ case 'archived':+ archivedCount++;+ break;+ case 'deleted':+ deletedCount++;+ break;+ }+ }++ // Find hottest and coldest+ const sorted = [...entries].sort((a, b) => b.accessCount - a.accessCount);+ const hottestEntries = sorted.slice(0, 5).map((e) => e.id);+ const coldestEntries = sorted.slice(-5).reverse().map((e) => e.id);++ return {+ totalEntries: entries.length,+ activeEntries: activeCount,+ archivedEntries: archivedCount,+ deletedEntries: deletedCount,+ totalSize,+ entriesByNamespace,+ entriesByType,+ averageAccessCount: entries.length > 0 ? totalAccessCount / entries.length : 0,+ hottestEntries,+ coldestEntries,+ };+ }++ async count(options?: MemoryQueryOptions): Promise<number> {+ const entries = await this.findAll(options);+ return entries.length;+ }++ // ============================================================================+ // Namespace Operations+ // ============================================================================++ async listNamespaces(): Promise<string[]> {+ return Array.from(this.namespaceIndex.keys());+ }++ async deleteNamespace(namespace: string): Promise<number> {+ const ids = this.namespaceIndex.get(namespace);+ if (!ids) return 0;++ const count = ids.size;+ for (const id of ids) {+ await this.delete(id);+ }+ this.namespaceIndex.delete(namespace);+ return count;+ }++ async getNamespaceSize(namespace: string): Promise<number> {+ const ids = this.namespaceIndex.get(namespace);+ if (!ids) return 0;++ let size = 0;+ for (const id of ids) {+ const entry = this.entries.get(id);+ if (entry) {+ size += JSON.stringify(entry.value).length;+ }+ }+ return size;+ }++ // ============================================================================+ // Private Methods+ // ============================================================================++ private ensureInitialized(): void {+ if (!this.initialized) {+ throw new Error('Repository not initialized. Call initialize() first.');+ }+ }++ private updateCache(entry: MemoryEntry): void {+ const maxCacheSize = this.config.cacheSize ?? 100;++ // Evict oldest entries if cache is full+ if (this.cache.size >= maxCacheSize) {+ const oldest = Array.from(this.cache.entries())+ .sort(([, a], [, b]) => a.timestamp - b.timestamp)+ .slice(0, Math.floor(maxCacheSize * 0.2));++ for (const [id] of oldest) {+ this.cache.delete(id);+ }+ }++ this.cache.set(entry.id, {+ entry,+ timestamp: Date.now(),+ });+ }++ private cosineSimilarity(a: Float32Array, b: Float32Array): number {+ if (a.length !== b.length) return 0;++ let dotProduct = 0;+ let normA = 0;+ let normB = 0;++ for (let i = 0; i < a.length; i++) {+ dotProduct += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }++ const denominator = Math.sqrt(normA) * Math.sqrt(normB);+ return denominator === 0 ? 0 : dotProduct / denominator;+ }+}diff --git a/v3/@claude-flow/neural/src/application/index.ts b/v3/@claude-flow/neural/src/application/index.tsnew file mode 100644index 0000000000..b3c159bdc0--- /dev/null+++ b/v3/@claude-flow/neural/src/application/index.ts@@ -0,0 +1,11 @@+/**+ * Neural Application Layer - Public Exports+ *+ * @module v3/neural/application+ */++export {+ NeuralApplicationService,+ type TrainingSessionResult,+ type NeuralMetrics,+} from './services/neural-application-service.js';diff --git a/v3/@claude-flow/neural/src/application/services/neural-application-service.ts b/v3/@claude-flow/neural/src/application/services/neural-application-service.tsnew file mode 100644index 0000000000..e6f6479e67--- /dev/null+++ b/v3/@claude-flow/neural/src/application/services/neural-application-service.ts@@ -0,0 +1,217 @@+/**+ * Neural Application Service - Application Layer+ *+ * Orchestrates neural learning operations.+ *+ * @module v3/neural/application/services+ */++import { Pattern, PatternType } from '../../domain/entities/pattern.js';+import { LearningDomainService, Trajectory, LearningResult, RouteRecommendation } from '../../domain/services/learning-service.js';++/**+ * Training session result+ */+export interface TrainingSessionResult {+ trajectoriesProcessed: number;+ patternsExtracted: number;+ patternsUpdated: number;+ averageConfidenceChange: number;+ duration: number;+}++/**+ * Neural metrics+ */+export interface NeuralMetrics {+ totalPatterns: number;+ patternsByType: Record<PatternType, number>;+ averageConfidence: number;+ reliablePatterns: number;+ totalSuccesses: number;+ totalFailures: number;+}++/**+ * Neural Application Service+ */+export class NeuralApplicationService {+ private readonly learningService: LearningDomainService;++ constructor() {+ this.learningService = new LearningDomainService();+ }++ // ============================================================================+ // Learning Operations+ // ============================================================================++ /**+ * Learn from a single trajectory+ */+ learn(trajectory: Trajectory): LearningResult {+ return this.learningService.updatePatterns(trajectory);+ }++ /**+ * Train on batch of trajectories+ */+ train(trajectories: Trajectory[]): TrainingSessionResult {+ const start = Date.now();+ let totalPatternsExtracted = 0;+ let totalPatternsUpdated = 0;+ let totalConfidenceChange = 0;++ for (const trajectory of trajectories) {+ const result = this.learningService.updatePatterns(trajectory);+ totalPatternsExtracted += result.patternsExtracted;+ totalPatternsUpdated += result.patternsUpdated;+ totalConfidenceChange += result.confidenceChange;+ }++ return {+ trajectoriesProcessed: trajectories.length,+ patternsExtracted: totalPatternsExtracted,+ patternsUpdated: totalPatternsUpdated,+ averageConfidenceChange: trajectories.length > 0 ? totalConfidenceChange / trajectories.length : 0,+ duration: Date.now() - start,+ };+ }++ // ============================================================================+ // Routing+ // ============================================================================++ /**+ * Get route recommendation for task+ */+ route(taskDescription: string): RouteRecommendation {+ return this.learningService.getRouteRecommendation(taskDescription);+ }++ /**+ * Explain routing decision+ */+ explain(taskDescription: string): {+ recommendation: RouteRecommendation;+ matchingPatterns: Pattern[];+ reasoning: string[];+ } {+ const recommendation = this.route(taskDescription);+ const matchingPatterns = this.learningService+ .getPatternsByType('task-routing')+ .filter((p) => p.matches(taskDescription));++ const reasoning: string[] = [];+ if (matchingPatterns.length > 0) {+ reasoning.push(`Found ${matchingPatterns.length} matching patterns`);+ for (const p of matchingPatterns.slice(0, 3)) {+ reasoning.push(`- Pattern "${p.name}": ${p.successRate.toFixed(2)} success rate, ${p.confidence.toFixed(2)} confidence`);+ }+ } else {+ reasoning.push('No matching patterns found, using keyword-based routing');+ }+ reasoning.push(`Recommended: ${recommendation.agentRole} (${(recommendation.confidence * 100).toFixed(0)}% confidence)`);++ return {+ recommendation,+ matchingPatterns,+ reasoning,+ };+ }++ // ============================================================================+ // Pattern Management+ // ============================================================================++ /**+ * Get all patterns+ */+ getPatterns(): Pattern[] {+ return this.learningService.getPatterns();+ }++ /**+ * Get patterns by type+ */+ getPatternsByType(type: PatternType): Pattern[] {+ return this.learningService.getPatternsByType(type);+ }++ /**+ * Add custom pattern+ */+ addPattern(props: {+ type: PatternType;+ name: string;+ description: string;+ condition: string;+ action: string;+ confidence?: number;+ }): Pattern {+ const pattern = Pattern.create({+ type: props.type,+ name: props.name,+ description: props.description,+ condition: props.condition,+ action: props.action,+ confidence: props.confidence ?? 0.5,+ });+ this.learningService.addPattern(pattern);+ return pattern;+ }++ /**+ * Remove pattern+ */+ removePattern(id: string): boolean {+ return this.learningService.removePattern(id);+ }++ /**+ * Consolidate patterns+ */+ consolidate(minConfidence?: number): { merged: number; pruned: number } {+ return this.learningService.consolidate(minConfidence);+ }++ // ============================================================================+ // Metrics+ // ============================================================================++ /**+ * Get neural metrics+ */+ getMetrics(): NeuralMetrics {+ const patterns = this.learningService.getPatterns();++ const patternsByType: Record<PatternType, number> = {+ 'task-routing': 0,+ 'error-recovery': 0,+ optimization: 0,+ learning: 0,+ };++ let totalConfidence = 0;+ let reliablePatterns = 0;+ let totalSuccesses = 0;+ let totalFailures = 0;++ for (const pattern of patterns) {+ patternsByType[pattern.type]++;+ totalConfidence += pattern.confidence;+ if (pattern.isReliable()) reliablePatterns++;+ totalSuccesses += pattern.successCount;+ totalFailures += pattern.failureCount;+ }++ return {+ totalPatterns: patterns.length,+ patternsByType,+ averageConfidence: patterns.length > 0 ? totalConfidence / patterns.length : 0,+ reliablePatterns,+ totalSuccesses,+ totalFailures,+ };+ }+}diff --git a/v3/@claude-flow/neural/src/domain/entities/pattern.ts b/v3/@claude-flow/neural/src/domain/entities/pattern.tsnew file mode 100644index 0000000000..a99b5bb666--- /dev/null+++ b/v3/@claude-flow/neural/src/domain/entities/pattern.ts@@ -0,0 +1,169 @@+/**+ * Pattern Entity - Domain Layer+ *+ * Represents a learned pattern for intelligent routing and optimization.+ *+ * @module v3/neural/domain/entities+ */++import { randomUUID } from 'crypto';++/**+ * Pattern type+ */+export type PatternType = 'task-routing' | 'error-recovery' | 'optimization' | 'learning';++/**+ * Pattern properties+ */+export interface PatternProps {+ id?: string;+ type: PatternType;+ name: string;+ description: string;+ condition: string;+ action: string;+ confidence: number;+ successCount?: number;+ failureCount?: number;+ metadata?: Record<string, unknown>;+ createdAt?: Date;+ updatedAt?: Date;+ lastMatchedAt?: Date;+}++/**+ * Pattern Entity+ */+export class Pattern {+ private _id: string;+ private _type: PatternType;+ private _name: string;+ private _description: string;+ private _condition: string;+ private _action: string;+ private _confidence: number;+ private _successCount: number;+ private _failureCount: number;+ private _metadata: Record<string, unknown>;+ private _createdAt: Date;+ private _updatedAt: Date;+ private _lastMatchedAt?: Date;++ private constructor(props: PatternProps) {+ const now = new Date();+ this._id = props.id ?? randomUUID();+ this._type = props.type;+ this._name = props.name;+ this._description = props.description;+ this._condition = props.condition;+ this._action = props.action;+ this._confidence = props.confidence;+ this._successCount = props.successCount ?? 0;+ this._failureCount = props.failureCount ?? 0;+ this._metadata = props.metadata ?? {};+ this._createdAt = props.createdAt ?? now;+ this._updatedAt = props.updatedAt ?? now;+ this._lastMatchedAt = props.lastMatchedAt;+ }++ static create(props: PatternProps): Pattern {+ return new Pattern(props);+ }++ static fromPersistence(props: PatternProps): Pattern {+ return new Pattern(props);+ }++ get id(): string { return this._id; }+ get type(): PatternType { return this._type; }+ get name(): string { return this._name; }+ get description(): string { return this._description; }+ get condition(): string { return this._condition; }+ get action(): string { return this._action; }+ get confidence(): number { return this._confidence; }+ get successCount(): number { return this._successCount; }+ get failureCount(): number { return this._failureCount; }+ get metadata(): Record<string, unknown> { return { ...this._metadata }; }+ get createdAt(): Date { return new Date(this._createdAt); }+ get updatedAt(): Date { return new Date(this._updatedAt); }+ get lastMatchedAt(): Date | undefined { return this._lastMatchedAt ? new Date(this._lastMatchedAt) : undefined; }++ /**+ * Calculate success rate+ */+ get successRate(): number {+ const total = this._successCount + this._failureCount;+ return total > 0 ? this._successCount / total : 0;+ }++ /**+ * Record successful match+ */+ recordSuccess(): void {+ this._successCount++;+ this._confidence = this.calculateConfidence();+ this._lastMatchedAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Record failed match+ */+ recordFailure(): void {+ this._failureCount++;+ this._confidence = this.calculateConfidence();+ this._lastMatchedAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Calculate confidence based on success rate+ */+ private calculateConfidence(): number {+ const total = this._successCount + this._failureCount;+ if (total < 5) return this._confidence; // Not enough data++ const newConfidence = this.successRate;+ // Weighted average with existing confidence+ return this._confidence * 0.3 + newConfidence * 0.7;+ }++ /**+ * Check if pattern matches input+ */+ matches(input: string): boolean {+ try {+ const regex = new RegExp(this._condition, 'i');+ return regex.test(input);+ } catch {+ return input.toLowerCase().includes(this._condition.toLowerCase());+ }+ }++ /**+ * Check if pattern is reliable (high confidence, sufficient data)+ */+ isReliable(): boolean {+ const total = this._successCount + this._failureCount;+ return total >= 10 && this._confidence >= 0.7;+ }++ toPersistence(): Record<string, unknown> {+ return {+ id: this._id,+ type: this._type,+ name: this._name,+ description: this._description,+ condition: this._condition,+ action: this._action,+ confidence: this._confidence,+ successCount: this._successCount,+ failureCount: this._failureCount,+ metadata: this._metadata,+ createdAt: this._createdAt.toISOString(),+ updatedAt: this._updatedAt.toISOString(),+ lastMatchedAt: this._lastMatchedAt?.toISOString(),+ };+ }+}diff --git a/v3/@claude-flow/neural/src/domain/index.ts b/v3/@claude-flow/neural/src/domain/index.tsnew file mode 100644index 0000000000..56c30f963f--- /dev/null+++ b/v3/@claude-flow/neural/src/domain/index.ts@@ -0,0 +1,18 @@+/**+ * Neural Domain Layer - Public Exports+ *+ * @module v3/neural/domain+ */++export {+ Pattern,+ type PatternType,+ type PatternProps,+} from './entities/pattern.js';++export {+ LearningDomainService,+ type Trajectory,+ type LearningResult,+ type RouteRecommendation,+} from './services/learning-service.js';diff --git a/v3/@claude-flow/neural/src/domain/services/learning-service.ts b/v3/@claude-flow/neural/src/domain/services/learning-service.tsnew file mode 100644index 0000000000..4f999324b5--- /dev/null+++ b/v3/@claude-flow/neural/src/domain/services/learning-service.ts@@ -0,0 +1,256 @@+/**+ * Learning Domain Service - Domain Layer+ *+ * Contains learning logic for pattern recognition and optimization.+ *+ * @module v3/neural/domain/services+ */++import { Pattern, PatternType } from '../entities/pattern.js';++/**+ * Learning trajectory+ */+export interface Trajectory {+ id: string;+ input: string;+ actions: string[];+ outcome: 'success' | 'failure' | 'partial';+ reward: number;+ metadata?: Record<string, unknown>;+ timestamp: Date;+}++/**+ * Learning result+ */+export interface LearningResult {+ patternsExtracted: number;+ patternsUpdated: number;+ confidenceChange: number;+}++/**+ * Route recommendation+ */+export interface RouteRecommendation {+ agentRole: string;+ confidence: number;+ reasoning: string;+ alternates: Array<{ role: string; confidence: number }>;+}++/**+ * Learning Domain Service+ */+export class LearningDomainService {+ private patterns: Map<string, Pattern> = new Map();++ /**+ * Extract patterns from trajectory+ */+ extractPatterns(trajectory: Trajectory): Pattern[] {+ const extracted: Pattern[] = [];++ // Extract task-routing pattern+ if (trajectory.outcome === 'success') {+ const taskPattern = Pattern.create({+ type: 'task-routing',+ name: `route_${trajectory.id}`,+ description: `Learned from successful trajectory`,+ condition: this.extractCondition(trajectory.input),+ action: trajectory.actions[0] ?? 'default',+ confidence: 0.6 + trajectory.reward * 0.2,+ metadata: { source: trajectory.id },+ });+ extracted.push(taskPattern);+ }++ // Extract error recovery pattern if failure+ if (trajectory.outcome === 'failure' && trajectory.actions.length > 1) {+ const lastAction = trajectory.actions[trajectory.actions.length - 1];+ const recoveryPattern = Pattern.create({+ type: 'error-recovery',+ name: `recovery_${trajectory.id}`,+ description: `Recovery action from failure`,+ condition: `error:${trajectory.actions[0]}`,+ action: lastAction,+ confidence: 0.5,+ metadata: { source: trajectory.id },+ });+ extracted.push(recoveryPattern);+ }++ return extracted;+ }++ /**+ * Update patterns based on trajectory outcome+ */+ updatePatterns(trajectory: Trajectory): LearningResult {+ let patternsUpdated = 0;+ let totalConfidenceChange = 0;++ for (const pattern of this.patterns.values()) {+ if (pattern.matches(trajectory.input)) {+ const oldConfidence = pattern.confidence;++ if (trajectory.outcome === 'success') {+ pattern.recordSuccess();+ } else {+ pattern.recordFailure();+ }++ totalConfidenceChange += pattern.confidence - oldConfidence;+ patternsUpdated++;+ }+ }++ // Extract and add new patterns+ const newPatterns = this.extractPatterns(trajectory);+ for (const pattern of newPatterns) {+ this.patterns.set(pattern.id, pattern);+ }++ return {+ patternsExtracted: newPatterns.length,+ patternsUpdated,+ confidenceChange: totalConfidenceChange,+ };+ }++ /**+ * Get route recommendation for task+ */+ getRouteRecommendation(taskDescription: string): RouteRecommendation {+ const matchingPatterns: Array<{ pattern: Pattern; score: number }> = [];++ for (const pattern of this.patterns.values()) {+ if (pattern.type !== 'task-routing') continue;++ if (pattern.matches(taskDescription)) {+ const score = pattern.confidence * (pattern.isReliable() ? 1.2 : 1.0);+ matchingPatterns.push({ pattern, score });+ }+ }++ // Sort by score+ matchingPatterns.sort((a, b) => b.score - a.score);++ if (matchingPatterns.length === 0) {+ return this.getDefaultRecommendation(taskDescription);+ }++ const best = matchingPatterns[0];+ const alternates = matchingPatterns.slice(1, 4).map((m) => ({+ role: m.pattern.action,+ confidence: m.score,+ }));++ return {+ agentRole: best.pattern.action,+ confidence: best.score,+ reasoning: `Based on pattern "${best.pattern.name}" with ${best.pattern.successCount} successes`,+ alternates,+ };+ }++ /**+ * Get default recommendation based on keywords+ */+ private getDefaultRecommendation(task: string): RouteRecommendation {+ const taskLower = task.toLowerCase();+ const keywordMap: Record<string, string> = {+ code: 'coder',+ implement: 'coder',+ write: 'coder',+ test: 'tester',+ review: 'reviewer',+ plan: 'planner',+ research: 'researcher',+ security: 'security-architect',+ performance: 'performance-engineer',+ memory: 'memory-specialist',+ };++ for (const [keyword, role] of Object.entries(keywordMap)) {+ if (taskLower.includes(keyword)) {+ return {+ agentRole: role,+ confidence: 0.5,+ reasoning: `Keyword match: "${keyword}"`,+ alternates: [],+ };+ }+ }++ return {+ agentRole: 'coder',+ confidence: 0.3,+ reasoning: 'Default fallback',+ alternates: [],+ };+ }++ /**+ * Extract condition from input+ */+ private extractCondition(input: string): string {+ // Extract key terms from input+ const words = input.toLowerCase().split(/\s+/);+ const keyWords = words.filter((w) => w.length > 4).slice(0, 5);+ return keyWords.join('|');+ }++ /**+ * Consolidate patterns (merge duplicates, prune low-confidence)+ */+ consolidate(minConfidence: number = 0.3): { merged: number; pruned: number } {+ let merged = 0;+ let pruned = 0;++ const toRemove: string[] = [];++ for (const [id, pattern] of this.patterns) {+ // Prune low confidence patterns with enough data+ if (pattern.confidence < minConfidence && pattern.successCount + pattern.failureCount > 20) {+ toRemove.push(id);+ pruned++;+ }+ }++ for (const id of toRemove) {+ this.patterns.delete(id);+ }++ return { merged, pruned };+ }++ /**+ * Get all patterns+ */+ getPatterns(): Pattern[] {+ return Array.from(this.patterns.values());+ }++ /**+ * Get patterns by type+ */+ getPatternsByType(type: PatternType): Pattern[] {+ return Array.from(this.patterns.values()).filter((p) => p.type === type);+ }++ /**+ * Add pattern+ */+ addPattern(pattern: Pattern): void {+ this.patterns.set(pattern.id, pattern);+ }++ /**+ * Remove pattern+ */+ removePattern(id: string): boolean {+ return this.patterns.delete(id);+ }+}diff --git a/v3/@claude-flow/security/src/application/index.ts b/v3/@claude-flow/security/src/application/index.tsnew file mode 100644index 0000000000..2bca77fe26--- /dev/null+++ b/v3/@claude-flow/security/src/application/index.ts@@ -0,0 +1,10 @@+/**+ * Security Application Layer - Public Exports+ *+ * @module v3/security/application+ */++export {+ SecurityApplicationService,+ type SecurityAuditResult,+} from './services/security-application-service.js';diff --git a/v3/@claude-flow/security/src/application/services/security-application-service.ts b/v3/@claude-flow/security/src/application/services/security-application-service.tsnew file mode 100644index 0000000000..7ec40a5095--- /dev/null+++ b/v3/@claude-flow/security/src/application/services/security-application-service.ts@@ -0,0 +1,193 @@+/**+ * Security Application Service - Application Layer+ *+ * Orchestrates security operations and provides simplified interface.+ *+ * @module v3/security/application/services+ */++import { SecurityContext, PermissionLevel } from '../../domain/entities/security-context.js';+import { SecurityDomainService, ValidationResult, ThreatDetectionResult } from '../../domain/services/security-domain-service.js';++/**+ * Security audit result+ */+export interface SecurityAuditResult {+ passed: boolean;+ score: number;+ checks: Array<{+ name: string;+ passed: boolean;+ severity: 'low' | 'medium' | 'high' | 'critical';+ message: string;+ }>;+ recommendations: string[];+}++/**+ * Security Application Service+ */+export class SecurityApplicationService {+ private readonly domainService: SecurityDomainService;+ private readonly contexts: Map<string, SecurityContext> = new Map();++ constructor() {+ this.domainService = new SecurityDomainService();+ }++ // ============================================================================+ // Context Management+ // ============================================================================++ /**+ * Create and register security context for agent+ */+ createAgentContext(agentId: string, role: string): SecurityContext {+ const context = this.domainService.createAgentContext(agentId, role);+ this.contexts.set(agentId, context);+ return context;+ }++ /**+ * Get security context+ */+ getContext(principalId: string): SecurityContext | undefined {+ return this.contexts.get(principalId);+ }++ /**+ * Remove security context+ */+ removeContext(principalId: string): boolean {+ return this.contexts.delete(principalId);+ }++ // ============================================================================+ // Validation+ // ============================================================================++ /**+ * Validate path access+ */+ validatePath(path: string, principalId: string): ValidationResult {+ const context = this.contexts.get(principalId);+ if (!context) {+ return {+ valid: false,+ errors: ['Security context not found'],+ warnings: [],+ };+ }++ return this.domainService.validatePath(path, context);+ }++ /**+ * Validate command execution+ */+ validateCommand(command: string, principalId: string): ValidationResult {+ const context = this.contexts.get(principalId);+ if (!context) {+ return {+ valid: false,+ errors: ['Security context not found'],+ warnings: [],+ };+ }++ return this.domainService.validateCommand(command, context);+ }++ /**+ * Validate user input+ */+ validateInput(input: string): ValidationResult {+ return this.domainService.validateInput(input);+ }++ /**+ * Detect threats in content+ */+ detectThreats(content: string): ThreatDetectionResult {+ return this.domainService.detectThreats(content);+ }++ // ============================================================================+ // Audit+ // ============================================================================++ /**+ * Run security audit on codebase+ */+ async auditCodebase(files: Array<{ path: string; content: string }>): Promise<SecurityAuditResult> {+ const checks: SecurityAuditResult['checks'] = [];+ const recommendations: string[] = [];+ let criticalCount = 0;+ let highCount = 0;++ for (const file of files) {+ const threats = this.domainService.detectThreats(file.content);++ for (const threat of threats.threats) {+ checks.push({+ name: `${threat.type} in ${file.path}`,+ passed: false,+ severity: threat.severity,+ message: threat.description,+ });++ if (threat.severity === 'critical') criticalCount++;+ if (threat.severity === 'high') highCount++;+ }++ if (threats.safe) {+ checks.push({+ name: `Security check: ${file.path}`,+ passed: true,+ severity: 'low',+ message: 'No threats detected',+ });+ }+ }++ // Generate recommendations+ if (criticalCount > 0) {+ recommendations.push('Address critical security issues immediately');+ }+ if (highCount > 0) {+ recommendations.push('Review and fix high-severity findings');+ }+ recommendations.push('Run regular security scans');+ recommendations.push('Keep dependencies updated');++ // Calculate score+ const totalChecks = checks.length;+ const passedChecks = checks.filter((c) => c.passed).length;+ const score = totalChecks > 0 ? Math.round((passedChecks / totalChecks) * 100) : 100;++ return {+ passed: criticalCount === 0 && highCount === 0,+ score,+ checks,+ recommendations,+ };+ }++ /**+ * Check if operation is allowed+ */+ isOperationAllowed(+ principalId: string,+ operation: 'path' | 'command',+ target: string+ ): boolean {+ const context = this.contexts.get(principalId);+ if (!context || context.isExpired()) return false;++ if (operation === 'path') {+ return context.canAccessPath(target);+ } else {+ return context.canExecuteCommand(target);+ }+ }+}diff --git a/v3/@claude-flow/security/src/domain/entities/security-context.ts b/v3/@claude-flow/security/src/domain/entities/security-context.tsnew file mode 100644index 0000000000..689e0fc35a--- /dev/null+++ b/v3/@claude-flow/security/src/domain/entities/security-context.ts@@ -0,0 +1,173 @@+/**+ * Security Context Entity - Domain Layer+ *+ * Represents security context for operations with validation and policy enforcement.+ *+ * @module v3/security/domain/entities+ */++import { randomUUID } from 'crypto';++/**+ * Permission levels+ */+export type PermissionLevel = 'read' | 'write' | 'execute' | 'admin';++/**+ * Security context properties+ */+export interface SecurityContextProps {+ id?: string;+ principalId: string;+ principalType: 'agent' | 'user' | 'system';+ permissions: PermissionLevel[];+ allowedPaths?: string[];+ blockedPaths?: string[];+ allowedCommands?: string[];+ blockedCommands?: string[];+ metadata?: Record<string, unknown>;+ expiresAt?: Date;+ createdAt?: Date;+}++/**+ * Security Context - Entity+ */+export class SecurityContext {+ private _id: string;+ private _principalId: string;+ private _principalType: 'agent' | 'user' | 'system';+ private _permissions: Set<PermissionLevel>;+ private _allowedPaths: Set<string>;+ private _blockedPaths: Set<string>;+ private _allowedCommands: Set<string>;+ private _blockedCommands: Set<string>;+ private _metadata: Record<string, unknown>;+ private _expiresAt?: Date;+ private _createdAt: Date;++ private constructor(props: SecurityContextProps) {+ this._id = props.id ?? randomUUID();+ this._principalId = props.principalId;+ this._principalType = props.principalType;+ this._permissions = new Set(props.permissions);+ this._allowedPaths = new Set(props.allowedPaths ?? []);+ this._blockedPaths = new Set(props.blockedPaths ?? []);+ this._allowedCommands = new Set(props.allowedCommands ?? []);+ this._blockedCommands = new Set(props.blockedCommands ?? []);+ this._metadata = props.metadata ?? {};+ this._expiresAt = props.expiresAt;+ this._createdAt = props.createdAt ?? new Date();+ }++ static create(props: SecurityContextProps): SecurityContext {+ return new SecurityContext(props);+ }++ static fromPersistence(props: SecurityContextProps): SecurityContext {+ return new SecurityContext(props);+ }++ get id(): string { return this._id; }+ get principalId(): string { return this._principalId; }+ get principalType(): string { return this._principalType; }+ get permissions(): PermissionLevel[] { return Array.from(this._permissions); }+ get allowedPaths(): string[] { return Array.from(this._allowedPaths); }+ get blockedPaths(): string[] { return Array.from(this._blockedPaths); }+ get allowedCommands(): string[] { return Array.from(this._allowedCommands); }+ get blockedCommands(): string[] { return Array.from(this._blockedCommands); }+ get metadata(): Record<string, unknown> { return { ...this._metadata }; }+ get expiresAt(): Date | undefined { return this._expiresAt; }+ get createdAt(): Date { return new Date(this._createdAt); }++ // Business Logic++ hasPermission(level: PermissionLevel): boolean {+ return this._permissions.has(level) || this._permissions.has('admin');+ }++ isExpired(): boolean {+ if (!this._expiresAt) return false;+ return Date.now() > this._expiresAt.getTime();+ }++ canAccessPath(path: string): boolean {+ if (this.isExpired()) return false;++ // Check blocked paths first+ for (const blocked of this._blockedPaths) {+ if (path.startsWith(blocked) || this.matchGlob(path, blocked)) {+ return false;+ }+ }++ // If no allowed paths specified, allow all non-blocked+ if (this._allowedPaths.size === 0) return true;++ // Check allowed paths+ for (const allowed of this._allowedPaths) {+ if (path.startsWith(allowed) || this.matchGlob(path, allowed)) {+ return true;+ }+ }++ return false;+ }++ canExecuteCommand(command: string): boolean {+ if (this.isExpired()) return false;++ const cmdBase = command.split(' ')[0];++ // Check blocked commands first+ if (this._blockedCommands.has(cmdBase) || this._blockedCommands.has(command)) {+ return false;+ }++ // If no allowed commands specified, allow all non-blocked+ if (this._allowedCommands.size === 0) return true;++ // Check allowed commands+ return this._allowedCommands.has(cmdBase) || this._allowedCommands.has(command);+ }++ private matchGlob(path: string, pattern: string): boolean {+ const regex = pattern+ .replace(/\*\*/g, '.*')+ .replace(/\*/g, '[^/]*')+ .replace(/\?/g, '.');+ return new RegExp(`^${regex}$`).test(path);+ }++ grantPermission(level: PermissionLevel): void {+ this._permissions.add(level);+ }++ revokePermission(level: PermissionLevel): void {+ this._permissions.delete(level);+ }++ addAllowedPath(path: string): void {+ this._allowedPaths.add(path);+ }++ addBlockedPath(path: string): void {+ this._blockedPaths.add(path);+ }++ toPersistence(): Record<string, unknown> {+ return {+ id: this._id,+ principalId: this._principalId,+ principalType: this._principalType,+ permissions: Array.from(this._permissions),+ allowedPaths: Array.from(this._allowedPaths),+ blockedPaths: Array.from(this._blockedPaths),+ allowedCommands: Array.from(this._allowedCommands),+ blockedCommands: Array.from(this._blockedCommands),+ metadata: this._metadata,+ expiresAt: this._expiresAt?.toISOString(),+ createdAt: this._createdAt.toISOString(),+ };+ }+}diff --git a/v3/@claude-flow/security/src/domain/index.ts b/v3/@claude-flow/security/src/domain/index.tsnew file mode 100644index 0000000000..9f296c488f--- /dev/null+++ b/v3/@claude-flow/security/src/domain/index.ts@@ -0,0 +1,17 @@+/**+ * Security Domain Layer - Public Exports+ *+ * @module v3/security/domain+ */++export {+ SecurityContext,+ type PermissionLevel,+ type SecurityContextProps,+} from './entities/security-context.js';++export {+ SecurityDomainService,+ type ValidationResult,+ type ThreatDetectionResult,+} from './services/security-domain-service.js';diff --git a/v3/@claude-flow/security/src/domain/services/security-domain-service.ts b/v3/@claude-flow/security/src/domain/services/security-domain-service.tsnew file mode 100644index 0000000000..1754f0ed7b--- /dev/null+++ b/v3/@claude-flow/security/src/domain/services/security-domain-service.ts@@ -0,0 +1,296 @@+/**+ * Security Domain Service - Domain Layer+ *+ * Contains security logic for validation, policy enforcement, and threat detection.+ *+ * @module v3/security/domain/services+ */++import { SecurityContext, PermissionLevel } from '../entities/security-context.js';++/**+ * Validation result+ */+export interface ValidationResult {+ valid: boolean;+ errors: string[];+ warnings: string[];+ sanitized?: string;+}++/**+ * Threat detection result+ */+export interface ThreatDetectionResult {+ safe: boolean;+ threats: Array<{+ type: string;+ severity: 'low' | 'medium' | 'high' | 'critical';+ description: string;+ location?: string;+ }>;+}++/**+ * Security Domain Service+ */+export class SecurityDomainService {+ // Dangerous patterns for path traversal+ private static readonly PATH_TRAVERSAL_PATTERNS = [+ /\.\./,+ /~\//,+ /^\/etc\//,+ /^\/tmp\//,+ /^\/var\/log\//,+ /^C:\\Windows/i,+ /^C:\\Users\\[^\\]+\\AppData/i,+ ];++ // Dangerous command patterns+ private static readonly DANGEROUS_COMMANDS = [+ /^rm\s+-rf\s+\//,+ /^rm\s+-rf\s+\*/,+ /^dd\s+if=/,+ /^mkfs\./,+ /^format\s+/i,+ /^del\s+\/s\s+\/q/i,+ />\s*\/dev\/sd[a-z]/,+ /\|\s*bash$/,+ /\|\s*sh$/,+ /eval\s*\(/,+ /exec\s*\(/,+ ];++ // SQL injection patterns+ private static readonly SQL_INJECTION_PATTERNS = [+ /'\s*OR\s+'1'\s*=\s*'1/i,+ /'\s*OR\s+1\s*=\s*1/i,+ /;\s*DROP\s+TABLE/i,+ /;\s*DELETE\s+FROM/i,+ /UNION\s+SELECT/i,+ /--\s*$/,+ ];++ // XSS patterns+ private static readonly XSS_PATTERNS = [+ /<script[\s>]/i,+ /javascript:/i,+ /on\w+\s*=/i,+ /<iframe/i,+ /<object/i,+ /<embed/i,+ ];++ /**+ * Validate a file path+ */+ validatePath(path: string, context: SecurityContext): ValidationResult {+ const errors: string[] = [];+ const warnings: string[] = [];++ // Check path traversal+ for (const pattern of SecurityDomainService.PATH_TRAVERSAL_PATTERNS) {+ if (pattern.test(path)) {+ errors.push(`Path traversal detected: ${pattern.source}`);+ }+ }++ // Check context permissions+ if (!context.canAccessPath(path)) {+ errors.push(`Access denied to path: ${path}`);+ }++ // Check for suspicious paths+ if (path.includes('..')) {+ warnings.push('Path contains parent directory reference');+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ sanitized: this.sanitizePath(path),+ };+ }++ /**+ * Validate a command+ */+ validateCommand(command: string, context: SecurityContext): ValidationResult {+ const errors: string[] = [];+ const warnings: string[] = [];++ // Check dangerous commands+ for (const pattern of SecurityDomainService.DANGEROUS_COMMANDS) {+ if (pattern.test(command)) {+ errors.push(`Dangerous command pattern detected: ${pattern.source}`);+ }+ }++ // Check context permissions+ if (!context.canExecuteCommand(command)) {+ errors.push(`Command execution denied: ${command}`);+ }++ if (!context.hasPermission('execute')) {+ errors.push('Execute permission required');+ }++ // Check for shell injection+ if (/[;&|`$(){}]/.test(command)) {+ warnings.push('Command contains shell metacharacters');+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ sanitized: this.sanitizeCommand(command),+ };+ }++ /**+ * Validate user input+ */+ validateInput(input: string): ValidationResult {+ const errors: string[] = [];+ const warnings: string[] = [];++ // Check for SQL injection+ for (const pattern of SecurityDomainService.SQL_INJECTION_PATTERNS) {+ if (pattern.test(input)) {+ errors.push(`SQL injection pattern detected`);+ break;+ }+ }++ // Check for XSS+ for (const pattern of SecurityDomainService.XSS_PATTERNS) {+ if (pattern.test(input)) {+ errors.push(`XSS pattern detected`);+ break;+ }+ }++ // Check length+ if (input.length > 10000) {+ warnings.push('Input exceeds recommended length');+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ sanitized: this.sanitizeInput(input),+ };+ }++ /**+ * Detect threats in content+ */+ detectThreats(content: string): ThreatDetectionResult {+ const threats: ThreatDetectionResult['threats'] = [];++ // Check for various threat patterns+ if (/<script/i.test(content)) {+ threats.push({+ type: 'xss',+ severity: 'high',+ description: 'Script tag detected',+ });+ }++ if (/password\s*[:=]\s*["'][^"']+["']/i.test(content)) {+ threats.push({+ type: 'credential-exposure',+ severity: 'critical',+ description: 'Hardcoded password detected',+ });+ }++ if (/api[_-]?key\s*[:=]\s*["'][^"']+["']/i.test(content)) {+ threats.push({+ type: 'credential-exposure',+ severity: 'critical',+ description: 'API key detected',+ });+ }++ if (/eval\s*\(/.test(content)) {+ threats.push({+ type: 'code-injection',+ severity: 'high',+ description: 'Eval statement detected',+ });+ }++ return {+ safe: threats.length === 0,+ threats,+ };+ }++ /**+ * Sanitize path+ */+ private sanitizePath(path: string): string {+ return path+ .replace(/\.\./g, '')+ .replace(/\/\//g, '/')+ .replace(/^~\//, '')+ .trim();+ }++ /**+ * Sanitize command+ */+ private sanitizeCommand(command: string): string {+ return command+ .replace(/[;&|`$]/g, '')+ .replace(/\$\([^)]*\)/g, '')+ .trim();+ }++ /**+ * Sanitize user input+ */+ private sanitizeInput(input: string): string {+ return input+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''')+ .replace(/\//g, '/');+ }++ /**+ * Create security context for agent+ */+ createAgentContext(+ agentId: string,+ role: string,+ customPaths?: string[]+ ): SecurityContext {+ // Default permissions based on role+ const rolePermissions: Record<string, PermissionLevel[]> = {+ 'queen-coordinator': ['read', 'write', 'execute', 'admin'],+ 'security-architect': ['read', 'write', 'execute', 'admin'],+ 'coder': ['read', 'write', 'execute'],+ 'reviewer': ['read'],+ 'tester': ['read', 'execute'],+ default: ['read'],+ };++ const permissions = rolePermissions[role] ?? rolePermissions.default;++ return SecurityContext.create({+ principalId: agentId,+ principalType: 'agent',+ permissions,+ allowedPaths: customPaths ?? ['./src', './tests', './docs'],+ blockedPaths: ['/etc', '/var', '~/', '../'],+ allowedCommands: ['npm', 'npx', 'node', 'git', 'vitest'],+ blockedCommands: ['rm -rf /', 'dd', 'mkfs', 'format'],+ });+ }+}diff --git a/v3/@claude-flow/shared/src/events/index.ts b/v3/@claude-flow/shared/src/events/index.tsindex 0d9b48b1c8..fe90013570 100644--- a/v3/@claude-flow/shared/src/events/index.ts+++ b/v3/@claude-flow/shared/src/events/index.ts@@ -72,3 +72,13 @@ export {MemoryIndexProjection,MemoryProjectionState,} from './projections.js';++// State Reconstruction (ADR-007)+export {+ StateReconstructor,+ createStateReconstructor,+ AgentAggregate,+ TaskAggregate,+ type AggregateRoot,+ type ReconstructorOptions,+} from './state-reconstructor.js';diff --git a/v3/@claude-flow/shared/src/events/state-reconstructor.ts b/v3/@claude-flow/shared/src/events/state-reconstructor.tsnew file mode 100644index 0000000000..ea00022034--- /dev/null+++ b/v3/@claude-flow/shared/src/events/state-reconstructor.ts@@ -0,0 +1,343 @@+/**+ * State Reconstructor - ADR-007 Implementation+ *+ * Reconstructs aggregate state from event streams.+ * Implements event sourcing patterns for V3.+ *+ * @module v3/shared/events/state-reconstructor+ */++import { EventStore, DomainEvent, Snapshot } from './event-store.js';++/**+ * Aggregate root interface+ */+export interface AggregateRoot {+ id: string;+ version: number;+ apply(event: DomainEvent): void;+ getState(): Record<string, unknown>;+}++/**+ * Reconstructor options+ */+export interface ReconstructorOptions {+ useSnapshots: boolean;+ snapshotInterval: number; // Create snapshot every N events+ maxEventsToReplay: number;+}++/**+ * State Reconstructor+ *+ * Reconstructs aggregate state from event history.+ * Supports snapshots for performance optimization.+ */+export class StateReconstructor {+ private readonly options: ReconstructorOptions;++ constructor(+ private readonly eventStore: EventStore,+ options?: Partial<ReconstructorOptions>+ ) {+ this.options = {+ useSnapshots: true,+ snapshotInterval: 100,+ maxEventsToReplay: 10000,+ ...options,+ };+ }++ /**+ * Reconstruct aggregate state from events+ */+ async reconstruct<T extends AggregateRoot>(+ aggregateId: string,+ factory: (id: string) => T+ ): Promise<T> {+ const aggregate = factory(aggregateId);++ // Try to load from snapshot first+ if (this.options.useSnapshots) {+ const snapshot = await this.eventStore.getSnapshot(aggregateId);+ if (snapshot) {+ this.applySnapshot(aggregate, snapshot);+ }+ }++ // Get events after snapshot version (or all if no snapshot)+ const events = await this.eventStore.getEvents(aggregateId, aggregate.version + 1);++ // Apply events+ for (const event of events) {+ if (events.length > this.options.maxEventsToReplay) {+ throw new Error(`Too many events to replay (${events.length}). Consider creating a snapshot.`);+ }++ aggregate.apply(event);+ }++ // Create snapshot if interval reached+ if (this.options.useSnapshots && aggregate.version % this.options.snapshotInterval === 0) {+ await this.createSnapshot(aggregate);+ }++ return aggregate;+ }++ /**+ * Reconstruct state at a specific point in time+ */+ async reconstructAtTime<T extends AggregateRoot>(+ aggregateId: string,+ factory: (id: string) => T,+ timestamp: Date+ ): Promise<T> {+ const aggregate = factory(aggregateId);++ // Get all events up to timestamp+ const allEvents = await this.eventStore.getEvents(aggregateId);+ const events = allEvents.filter((e) => e.timestamp <= timestamp.getTime());++ // Apply events+ for (const event of events) {+ aggregate.apply(event);+ }++ return aggregate;+ }++ /**+ * Reconstruct state at a specific version+ */+ async reconstructAtVersion<T extends AggregateRoot>(+ aggregateId: string,+ factory: (id: string) => T,+ targetVersion: number+ ): Promise<T> {+ const aggregate = factory(aggregateId);++ // Get events up to target version+ const events = await this.eventStore.getEvents(aggregateId);+ const limitedEvents = events.filter((e) => e.version <= targetVersion);++ // Apply events+ for (const event of limitedEvents) {+ aggregate.apply(event);+ }++ return aggregate;+ }++ /**+ * Apply snapshot to aggregate+ */+ private applySnapshot(aggregate: AggregateRoot, snapshot: Snapshot): void {+ // Type assertion for aggregate that has restoreFromSnapshot+ const restorable = aggregate as AggregateRoot & {+ restoreFromSnapshot?(state: unknown): void;+ };++ if (typeof restorable.restoreFromSnapshot === 'function') {+ restorable.restoreFromSnapshot(snapshot.state);+ }++ // Update version+ (aggregate as any).version = snapshot.version;+ }++ /**+ * Create snapshot for aggregate+ */+ private async createSnapshot(aggregate: AggregateRoot): Promise<void> {+ const snapshot: Snapshot = {+ aggregateId: aggregate.id,+ aggregateType: this.getAggregateType(aggregate),+ version: aggregate.version,+ state: aggregate.getState(),+ timestamp: Date.now(),+ };++ await this.eventStore.saveSnapshot(snapshot);+ }++ /**+ * Get aggregate type from instance+ */+ private getAggregateType(aggregate: AggregateRoot): string {+ return aggregate.constructor.name.toLowerCase().replace('aggregate', '');+ }+}++/**+ * Agent Aggregate - Example implementation+ */+export class AgentAggregate implements AggregateRoot {+ id: string;+ version = 0;++ private state = {+ name: '',+ role: '',+ status: 'idle' as string,+ currentTask: null as string | null,+ completedTasks: [] as string[],+ capabilities: [] as string[],+ createdAt: null as Date | null,+ lastActiveAt: null as Date | null,+ };++ constructor(id: string) {+ this.id = id;+ }++ apply(event: DomainEvent): void {+ this.version = event.version;++ switch (event.type) {+ case 'agent:spawned':+ this.state.name = event.payload.name as string;+ this.state.role = event.payload.role as string;+ this.state.capabilities = (event.payload.capabilities as string[]) ?? [];+ this.state.status = 'idle';+ this.state.createdAt = new Date(event.timestamp);+ break;++ case 'agent:started':+ this.state.status = 'active';+ this.state.lastActiveAt = new Date(event.timestamp);+ break;++ case 'agent:task-assigned':+ this.state.currentTask = event.payload.taskId as string;+ this.state.status = 'busy';+ this.state.lastActiveAt = new Date(event.timestamp);+ break;++ case 'agent:task-completed':+ this.state.completedTasks.push(event.payload.taskId as string);+ this.state.currentTask = null;+ this.state.status = 'active';+ this.state.lastActiveAt = new Date(event.timestamp);+ break;++ case 'agent:terminated':+ this.state.status = 'terminated';+ break;+ }+ }++ getState(): Record<string, unknown> {+ return { ...this.state };+ }++ restoreFromSnapshot(snapshotState: unknown): void {+ const state = snapshotState as typeof this.state;+ this.state = {+ ...state,+ createdAt: state.createdAt ? new Date(state.createdAt) : null,+ lastActiveAt: state.lastActiveAt ? new Date(state.lastActiveAt) : null,+ };+ }++ // Getters for type safety+ get name(): string { return this.state.name; }+ get role(): string { return this.state.role; }+ get status(): string { return this.state.status; }+ get currentTask(): string | null { return this.state.currentTask; }+ get completedTasks(): string[] { return [...this.state.completedTasks]; }+ get capabilities(): string[] { return [...this.state.capabilities]; }+}++/**+ * Task Aggregate - Example implementation+ */+export class TaskAggregate implements AggregateRoot {+ id: string;+ version = 0;++ private state = {+ title: '',+ description: '',+ type: '',+ priority: 'normal' as string,+ status: 'pending' as string,+ assignedAgent: null as string | null,+ result: null as unknown,+ createdAt: null as Date | null,+ startedAt: null as Date | null,+ completedAt: null as Date | null,+ };++ constructor(id: string) {+ this.id = id;+ }++ apply(event: DomainEvent): void {+ this.version = event.version;++ switch (event.type) {+ case 'task:created':+ this.state.title = event.payload.title as string;+ this.state.description = event.payload.description as string;+ this.state.type = event.payload.taskType as string;+ this.state.priority = (event.payload.priority as string) ?? 'normal';+ this.state.status = 'pending';+ this.state.createdAt = new Date(event.timestamp);+ break;++ case 'task:started':+ this.state.assignedAgent = event.payload.agentId as string;+ this.state.status = 'running';+ this.state.startedAt = new Date(event.timestamp);+ break;++ case 'task:completed':+ this.state.result = event.payload.result;+ this.state.status = 'completed';+ this.state.completedAt = new Date(event.timestamp);+ break;++ case 'task:failed':+ this.state.status = 'failed';+ this.state.completedAt = new Date(event.timestamp);+ break;++ case 'task:cancelled':+ this.state.status = 'cancelled';+ this.state.completedAt = new Date(event.timestamp);+ break;+ }+ }++ getState(): Record<string, unknown> {+ return { ...this.state };+ }++ restoreFromSnapshot(snapshotState: unknown): void {+ const state = snapshotState as typeof this.state;+ this.state = {+ ...state,+ createdAt: state.createdAt ? new Date(state.createdAt) : null,+ startedAt: state.startedAt ? new Date(state.startedAt) : null,+ completedAt: state.completedAt ? new Date(state.completedAt) : null,+ };+ }++ // Getters+ get title(): string { return this.state.title; }+ get status(): string { return this.state.status; }+ get assignedAgent(): string | null { return this.state.assignedAgent; }+ get result(): unknown { return this.state.result; }+}++/**+ * Factory function+ */+export function createStateReconstructor(+ eventStore: EventStore,+ options?: Partial<ReconstructorOptions>+): StateReconstructor {+ return new StateReconstructor(eventStore, options);+}diff --git a/v3/@claude-flow/shared/src/plugins/official/hive-mind-plugin.ts b/v3/@claude-flow/shared/src/plugins/official/hive-mind-plugin.tsnew file mode 100644index 0000000000..f56685be1a--- /dev/null+++ b/v3/@claude-flow/shared/src/plugins/official/hive-mind-plugin.ts@@ -0,0 +1,329 @@+/**+ * HiveMind Plugin - Official Plugin (ADR-004)+ *+ * Implements collective intelligence and emergent behavior patterns.+ * Part of the official plugin collection.+ *+ * @module v3/shared/plugins/official/hive-mind+ */++import type { ClaudeFlowPlugin, PluginContext, PluginConfig } from '../types.js';+import { HookEvent } from '../../hooks/index.js';++/**+ * HiveMind configuration+ */+export interface HiveMindConfig extends PluginConfig {+ consensusThreshold: number; // Minimum agreement for decisions (0-1)+ collectiveMemoryEnabled: boolean;+ emergentBehaviorEnabled: boolean;+ maxVotingRounds: number;+ decisionTimeout: number; // ms+}++/**+ * Collective decision+ */+export interface CollectiveDecision {+ id: string;+ question: string;+ votes: Map<string, { agentId: string; vote: string; confidence: number }>;+ consensus?: string;+ consensusConfidence: number;+ timestamp: Date;+}++/**+ * Emergent pattern+ */+export interface EmergentPattern {+ id: string;+ type: string;+ description: string;+ contributors: string[];+ strength: number;+ discoveredAt: Date;+}++/**+ * HiveMind Plugin Implementation+ */+export class HiveMindPlugin implements ClaudeFlowPlugin {+ readonly id = 'hive-mind';+ readonly name = 'HiveMind Collective Intelligence';+ readonly version = '1.0.0';+ readonly description = 'Collective intelligence with consensus mechanisms and emergent behavior';++ private context?: PluginContext;+ private config: HiveMindConfig;+ private decisions: Map<string, CollectiveDecision> = new Map();+ private patterns: Map<string, EmergentPattern> = new Map();+ private collectiveMemory: Map<string, unknown> = new Map();++ constructor(config?: Partial<HiveMindConfig>) {+ this.config = {+ enabled: true,+ consensusThreshold: 0.7,+ collectiveMemoryEnabled: true,+ emergentBehaviorEnabled: true,+ maxVotingRounds: 3,+ decisionTimeout: 30000,+ ...config,+ };+ }++ async initialize(context: PluginContext): Promise<void> {+ this.context = context;++ // Register hooks for collective behavior+ context.hooks?.register({+ id: 'hive-mind-pre-task',+ event: HookEvent.PreTaskExecute,+ priority: 100,+ handler: async (ctx) => {+ // Check collective memory for similar tasks+ const taskKey = this.generateTaskKey(ctx.data);+ const previous = this.collectiveMemory.get(taskKey);++ if (previous) {+ ctx.data.collectiveInsight = previous;+ }++ return { proceed: true, context: ctx };+ },+ });++ context.hooks?.register({+ id: 'hive-mind-post-task',+ event: HookEvent.PostTaskComplete,+ priority: 100,+ handler: async (ctx) => {+ // Store result in collective memory+ if (this.config.collectiveMemoryEnabled) {+ const taskKey = this.generateTaskKey(ctx.data);+ this.collectiveMemory.set(taskKey, {+ result: ctx.data.result,+ timestamp: new Date(),+ agentId: ctx.data.agentId,+ });+ }++ // Detect emergent patterns+ if (this.config.emergentBehaviorEnabled) {+ this.detectEmergentPatterns(ctx.data);+ }++ return { proceed: true, context: ctx };+ },+ });+ }++ async shutdown(): Promise<void> {+ this.decisions.clear();+ this.patterns.clear();+ this.collectiveMemory.clear();+ this.context = undefined;+ }++ // ============================================================================+ // Collective Decision Making+ // ============================================================================++ /**+ * Request a collective decision from the swarm+ */+ async requestDecision(question: string, options: string[]): Promise<CollectiveDecision> {+ const decision: CollectiveDecision = {+ id: `decision-${Date.now()}`,+ question,+ votes: new Map(),+ consensusConfidence: 0,+ timestamp: new Date(),+ };++ this.decisions.set(decision.id, decision);++ // In a real implementation, this would broadcast to agents+ // For now, simulate with placeholder votes+ for (let i = 0; i < options.length && i < 3; i++) {+ decision.votes.set(`agent-${i}`, {+ agentId: `agent-${i}`,+ vote: options[i % options.length],+ confidence: 0.7 + Math.random() * 0.3,+ });+ }++ // Calculate consensus+ const voteCounts = new Map<string, number>();+ for (const vote of decision.votes.values()) {+ voteCounts.set(vote.vote, (voteCounts.get(vote.vote) ?? 0) + vote.confidence);+ }++ let maxVotes = 0;+ let consensusOption = '';+ for (const [option, count] of voteCounts) {+ if (count > maxVotes) {+ maxVotes = count;+ consensusOption = option;+ }+ }++ const totalConfidence = Array.from(decision.votes.values()).reduce(+ (sum, v) => sum + v.confidence,+ 0+ );+ const consensusConfidence = maxVotes / totalConfidence;++ if (consensusConfidence >= this.config.consensusThreshold) {+ decision.consensus = consensusOption;+ decision.consensusConfidence = consensusConfidence;+ }++ return decision;+ }++ /**+ * Submit a vote for a decision+ */+ submitVote(decisionId: string, agentId: string, vote: string, confidence: number): boolean {+ const decision = this.decisions.get(decisionId);+ if (!decision) return false;++ decision.votes.set(agentId, { agentId, vote, confidence });+ this.recalculateConsensus(decision);+ return true;+ }++ /**+ * Get decision result+ */+ getDecision(decisionId: string): CollectiveDecision | undefined {+ return this.decisions.get(decisionId);+ }++ // ============================================================================+ // Emergent Behavior Detection+ // ============================================================================++ /**+ * Detect emergent patterns from agent behavior+ */+ private detectEmergentPatterns(taskData: Record<string, unknown>): void {+ // Analyze task patterns+ const type = String(taskData.type ?? 'unknown');+ const patternKey = `pattern-${type}`;++ const existing = this.patterns.get(patternKey);+ if (existing) {+ existing.strength += 0.1;+ if (!existing.contributors.includes(String(taskData.agentId))) {+ existing.contributors.push(String(taskData.agentId));+ }+ } else if (this.collectiveMemory.size > 5) {+ // Only create patterns after enough collective memory+ this.patterns.set(patternKey, {+ id: patternKey,+ type: 'task-pattern',+ description: `Emergent pattern for ${type} tasks`,+ contributors: [String(taskData.agentId)],+ strength: 0.5,+ discoveredAt: new Date(),+ });+ }+ }++ /**+ * Get emergent patterns+ */+ getEmergentPatterns(): EmergentPattern[] {+ return Array.from(this.patterns.values()).filter((p) => p.strength > 0.5);+ }++ // ============================================================================+ // Collective Memory+ // ============================================================================++ /**+ * Store in collective memory+ */+ storeCollective(key: string, value: unknown): void {+ this.collectiveMemory.set(key, {+ value,+ timestamp: new Date(),+ accessCount: 0,+ });+ }++ /**+ * Retrieve from collective memory+ */+ retrieveCollective(key: string): unknown {+ const entry = this.collectiveMemory.get(key) as any;+ if (entry) {+ entry.accessCount++;+ return entry.value;+ }+ return undefined;+ }++ /**+ * Get collective memory statistics+ */+ getCollectiveStats(): {+ totalEntries: number;+ patterns: number;+ decisions: number;+ topPatterns: EmergentPattern[];+ } {+ return {+ totalEntries: this.collectiveMemory.size,+ patterns: this.patterns.size,+ decisions: this.decisions.size,+ topPatterns: this.getEmergentPatterns().slice(0, 5),+ };+ }++ // ============================================================================+ // Private Helpers+ // ============================================================================++ private generateTaskKey(taskData: Record<string, unknown>): string {+ return `${taskData.type}-${JSON.stringify(taskData.input ?? {})}`.slice(0, 100);+ }++ private recalculateConsensus(decision: CollectiveDecision): void {+ const voteCounts = new Map<string, number>();+ let totalConfidence = 0;++ for (const vote of decision.votes.values()) {+ voteCounts.set(vote.vote, (voteCounts.get(vote.vote) ?? 0) + vote.confidence);+ totalConfidence += vote.confidence;+ }++ let maxVotes = 0;+ let consensusOption = '';+ for (const [option, count] of voteCounts) {+ if (count > maxVotes) {+ maxVotes = count;+ consensusOption = option;+ }+ }++ const consensusConfidence = totalConfidence > 0 ? maxVotes / totalConfidence : 0;++ if (consensusConfidence >= this.config.consensusThreshold) {+ decision.consensus = consensusOption;+ decision.consensusConfidence = consensusConfidence;+ } else {+ decision.consensus = undefined;+ decision.consensusConfidence = consensusConfidence;+ }+ }+}++/**+ * Factory function+ */+export function createHiveMindPlugin(config?: Partial<HiveMindConfig>): HiveMindPlugin {+ return new HiveMindPlugin(config);+}diff --git a/v3/@claude-flow/shared/src/plugins/official/index.ts b/v3/@claude-flow/shared/src/plugins/official/index.tsnew file mode 100644index 0000000000..087804e727--- /dev/null+++ b/v3/@claude-flow/shared/src/plugins/official/index.ts@@ -0,0 +1,24 @@+/**+ * Official Plugins - ADR-004 Implementation+ *+ * Exports all official @claude-flow plugins.+ *+ * @module v3/shared/plugins/official+ */++export {+ HiveMindPlugin,+ createHiveMindPlugin,+ type HiveMindConfig,+ type CollectiveDecision,+ type EmergentPattern,+} from './hive-mind-plugin.js';++export {+ MaestroPlugin,+ createMaestroPlugin,+ type MaestroConfig,+ type WorkflowStep,+ type Workflow,+ type OrchestrationResult,+} from './maestro-plugin.js';diff --git a/v3/@claude-flow/shared/src/plugins/official/maestro-plugin.ts b/v3/@claude-flow/shared/src/plugins/official/maestro-plugin.tsnew file mode 100644index 0000000000..4f69d65e6a--- /dev/null+++ b/v3/@claude-flow/shared/src/plugins/official/maestro-plugin.ts@@ -0,0 +1,508 @@+/**+ * Maestro Plugin - Official Plugin (ADR-004)+ *+ * Implements orchestration patterns for complex multi-agent workflows.+ * Part of the official plugin collection.+ *+ * @module v3/shared/plugins/official/maestro+ */++import type { ClaudeFlowPlugin, PluginContext, PluginConfig } from '../types.js';+import { HookEvent } from '../../hooks/index.js';++/**+ * Maestro configuration+ */+export interface MaestroConfig extends PluginConfig {+ orchestrationMode: 'sequential' | 'parallel' | 'adaptive';+ maxConcurrentWorkflows: number;+ workflowTimeout: number; // ms+ autoRecovery: boolean;+ checkpointInterval: number; // ms+}++/**+ * Workflow step+ */+export interface WorkflowStep {+ id: string;+ name: string;+ type: string;+ input: Record<string, unknown>;+ dependencies: string[];+ assignedAgent?: string;+ status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped';+ output?: unknown;+ error?: string;+ startedAt?: Date;+ completedAt?: Date;+}++/**+ * Workflow definition+ */+export interface Workflow {+ id: string;+ name: string;+ description: string;+ steps: WorkflowStep[];+ status: 'created' | 'running' | 'paused' | 'completed' | 'failed';+ currentStep?: string;+ progress: number;+ createdAt: Date;+ startedAt?: Date;+ completedAt?: Date;+ checkpoints: Map<string, unknown>;+}++/**+ * Orchestration result+ */+export interface OrchestrationResult {+ workflowId: string;+ success: boolean;+ stepsCompleted: number;+ stepsTotal: number;+ outputs: Record<string, unknown>;+ errors: Array<{ stepId: string; error: string }>;+ duration: number;+}++/**+ * Maestro Plugin Implementation+ */+export class MaestroPlugin implements ClaudeFlowPlugin {+ readonly id = 'maestro';+ readonly name = 'Maestro Workflow Orchestrator';+ readonly version = '1.0.0';+ readonly description = 'Complex multi-agent workflow orchestration with adaptive strategies';++ private context?: PluginContext;+ private config: MaestroConfig;+ private workflows: Map<string, Workflow> = new Map();+ private activeWorkflows = 0;++ constructor(config?: Partial<MaestroConfig>) {+ this.config = {+ enabled: true,+ orchestrationMode: 'adaptive',+ maxConcurrentWorkflows: 5,+ workflowTimeout: 600000, // 10 minutes+ autoRecovery: true,+ checkpointInterval: 30000, // 30 seconds+ ...config,+ };+ }++ async initialize(context: PluginContext): Promise<void> {+ this.context = context;++ // Register hooks for workflow monitoring+ context.hooks?.register({+ id: 'maestro-task-complete',+ event: HookEvent.PostTaskComplete,+ priority: 200,+ handler: async (ctx) => {+ // Update workflow progress on task completion+ for (const workflow of this.workflows.values()) {+ if (workflow.status === 'running') {+ this.updateWorkflowProgress(workflow, ctx.data);+ }+ }+ return { proceed: true, context: ctx };+ },+ });++ context.hooks?.register({+ id: 'maestro-error-handler',+ event: HookEvent.OnError,+ priority: 200,+ handler: async (ctx) => {+ // Handle workflow errors with recovery+ if (this.config.autoRecovery) {+ for (const workflow of this.workflows.values()) {+ if (workflow.status === 'running') {+ this.handleWorkflowError(workflow, ctx.data);+ }+ }+ }+ return { proceed: true, context: ctx };+ },+ });+ }++ async shutdown(): Promise<void> {+ // Checkpoint all running workflows+ for (const workflow of this.workflows.values()) {+ if (workflow.status === 'running') {+ this.checkpointWorkflow(workflow);+ }+ }+ this.workflows.clear();+ this.context = undefined;+ }++ // ============================================================================+ // Workflow Management+ // ============================================================================++ /**+ * Create a new workflow+ */+ createWorkflow(+ name: string,+ description: string,+ steps: Array<Omit<WorkflowStep, 'id' | 'status'>>+ ): Workflow {+ const workflow: Workflow = {+ id: `workflow-${Date.now()}`,+ name,+ description,+ steps: steps.map((step, index) => ({+ ...step,+ id: `step-${index}`,+ status: 'pending',+ })),+ status: 'created',+ progress: 0,+ createdAt: new Date(),+ checkpoints: new Map(),+ };++ this.workflows.set(workflow.id, workflow);+ return workflow;+ }++ /**+ * Execute a workflow+ */+ async executeWorkflow(workflowId: string): Promise<OrchestrationResult> {+ const workflow = this.workflows.get(workflowId);+ if (!workflow) {+ throw new Error(`Workflow not found: ${workflowId}`);+ }++ if (this.activeWorkflows >= this.config.maxConcurrentWorkflows) {+ throw new Error('Maximum concurrent workflows reached');+ }++ const startTime = Date.now();+ workflow.status = 'running';+ workflow.startedAt = new Date();+ this.activeWorkflows++;++ const errors: Array<{ stepId: string; error: string }> = [];+ const outputs: Record<string, unknown> = {};++ try {+ switch (this.config.orchestrationMode) {+ case 'sequential':+ await this.executeSequential(workflow, outputs, errors);+ break;+ case 'parallel':+ await this.executeParallel(workflow, outputs, errors);+ break;+ case 'adaptive':+ await this.executeAdaptive(workflow, outputs, errors);+ break;+ }++ workflow.status = errors.length === 0 ? 'completed' : 'failed';+ workflow.completedAt = new Date();+ } catch (error) {+ workflow.status = 'failed';+ errors.push({+ stepId: 'workflow',+ error: error instanceof Error ? error.message : String(error),+ });+ } finally {+ this.activeWorkflows--;+ }++ return {+ workflowId,+ success: workflow.status === 'completed',+ stepsCompleted: workflow.steps.filter((s) => s.status === 'completed').length,+ stepsTotal: workflow.steps.length,+ outputs,+ errors,+ duration: Date.now() - startTime,+ };+ }++ /**+ * Pause a workflow+ */+ pauseWorkflow(workflowId: string): boolean {+ const workflow = this.workflows.get(workflowId);+ if (!workflow || workflow.status !== 'running') return false;++ this.checkpointWorkflow(workflow);+ workflow.status = 'paused';+ return true;+ }++ /**+ * Resume a paused workflow+ */+ async resumeWorkflow(workflowId: string): Promise<OrchestrationResult> {+ const workflow = this.workflows.get(workflowId);+ if (!workflow || workflow.status !== 'paused') {+ throw new Error('Workflow cannot be resumed');+ }++ // Restore from checkpoint and continue+ return this.executeWorkflow(workflowId);+ }++ /**+ * Get workflow status+ */+ getWorkflow(workflowId: string): Workflow | undefined {+ return this.workflows.get(workflowId);+ }++ /**+ * List all workflows+ */+ listWorkflows(): Workflow[] {+ return Array.from(this.workflows.values());+ }++ // ============================================================================+ // Execution Strategies+ // ============================================================================++ private async executeSequential(+ workflow: Workflow,+ outputs: Record<string, unknown>,+ errors: Array<{ stepId: string; error: string }>+ ): Promise<void> {+ for (const step of workflow.steps) {+ if (step.status !== 'pending') continue;++ // Check dependencies+ const depsComplete = step.dependencies.every((depId) => {+ const dep = workflow.steps.find((s) => s.id === depId);+ return dep?.status === 'completed';+ });++ if (!depsComplete) {+ step.status = 'skipped';+ continue;+ }++ workflow.currentStep = step.id;+ const result = await this.executeStep(step, outputs);++ if (!result.success) {+ errors.push({ stepId: step.id, error: result.error ?? 'Unknown error' });+ break;+ }++ outputs[step.id] = result.output;+ this.updateProgress(workflow);+ }+ }++ private async executeParallel(+ workflow: Workflow,+ outputs: Record<string, unknown>,+ errors: Array<{ stepId: string; error: string }>+ ): Promise<void> {+ const layers = this.buildExecutionLayers(workflow.steps);++ for (const layer of layers) {+ const results = await Promise.all(+ layer.map((step) => this.executeStep(step, outputs))+ );++ for (let i = 0; i < results.length; i++) {+ const result = results[i];+ const step = layer[i];++ if (!result.success) {+ errors.push({ stepId: step.id, error: result.error ?? 'Unknown error' });+ } else {+ outputs[step.id] = result.output;+ }+ }++ this.updateProgress(workflow);+ }+ }++ private async executeAdaptive(+ workflow: Workflow,+ outputs: Record<string, unknown>,+ errors: Array<{ stepId: string; error: string }>+ ): Promise<void> {+ // Adaptive: start parallel, switch to sequential on errors+ const completedIds = new Set<string>();+ const pendingSteps = [...workflow.steps];+ let consecutiveErrors = 0;+ const maxConsecutiveErrors = 2;++ while (pendingSteps.length > 0) {+ // Find steps that can run (all dependencies complete)+ const runnableSteps = pendingSteps.filter((step) =>+ step.dependencies.every((depId) => completedIds.has(depId))+ );++ if (runnableSteps.length === 0) {+ // No runnable steps but pending remain - circular dependency+ for (const step of pendingSteps) {+ step.status = 'skipped';+ }+ break;+ }++ // Decide batch size based on error rate+ const batchSize = consecutiveErrors >= maxConsecutiveErrors ? 1 : runnableSteps.length;+ const batch = runnableSteps.slice(0, batchSize);++ const results = await Promise.all(+ batch.map((step) => this.executeStep(step, outputs))+ );++ for (let i = 0; i < results.length; i++) {+ const result = results[i];+ const step = batch[i];+ const stepIndex = pendingSteps.indexOf(step);++ if (stepIndex > -1) {+ pendingSteps.splice(stepIndex, 1);+ }++ if (!result.success) {+ errors.push({ stepId: step.id, error: result.error ?? 'Unknown error' });+ consecutiveErrors++;+ } else {+ outputs[step.id] = result.output;+ completedIds.add(step.id);+ consecutiveErrors = 0;+ }+ }++ this.updateProgress(workflow);+ }+ }++ // ============================================================================+ // Helpers+ // ============================================================================++ private async executeStep(+ step: WorkflowStep,+ outputs: Record<string, unknown>+ ): Promise<{ success: boolean; output?: unknown; error?: string }> {+ step.status = 'running';+ step.startedAt = new Date();++ try {+ // Resolve input references from previous outputs+ const resolvedInput = this.resolveInputReferences(step.input, outputs);++ // Simulate step execution+ // In real implementation, this would delegate to agents via MCP+ await new Promise((resolve) => setTimeout(resolve, 100));++ step.output = { ...resolvedInput, processed: true };+ step.status = 'completed';+ step.completedAt = new Date();++ return { success: true, output: step.output };+ } catch (error) {+ step.status = 'failed';+ step.error = error instanceof Error ? error.message : String(error);+ step.completedAt = new Date();++ return { success: false, error: step.error };+ }+ }++ private buildExecutionLayers(steps: WorkflowStep[]): WorkflowStep[][] {+ const layers: WorkflowStep[][] = [];+ const completed = new Set<string>();++ while (completed.size < steps.length) {+ const layer: WorkflowStep[] = [];++ for (const step of steps) {+ if (completed.has(step.id)) continue;++ const depsComplete = step.dependencies.every((depId) => completed.has(depId));+ if (depsComplete) {+ layer.push(step);+ }+ }++ if (layer.length === 0) break; // No more runnable steps+ layers.push(layer);+ layer.forEach((step) => completed.add(step.id));+ }++ return layers;+ }++ private resolveInputReferences(+ input: Record<string, unknown>,+ outputs: Record<string, unknown>+ ): Record<string, unknown> {+ const resolved: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(input)) {+ if (typeof value === 'string' && value.startsWith('$')) {+ const ref = value.slice(1);+ resolved[key] = outputs[ref];+ } else {+ resolved[key] = value;+ }+ }++ return resolved;+ }++ private updateProgress(workflow: Workflow): void {+ const completed = workflow.steps.filter((s) => s.status === 'completed').length;+ workflow.progress = (completed / workflow.steps.length) * 100;+ }++ private updateWorkflowProgress(workflow: Workflow, taskData: Record<string, unknown>): void {+ // Match task to workflow step and update+ const taskId = String(taskData.taskId ?? '');+ const step = workflow.steps.find((s) => s.id === taskId);+ if (step && step.status === 'running') {+ step.status = 'completed';+ step.output = taskData.result;+ step.completedAt = new Date();+ this.updateProgress(workflow);+ }+ }++ private handleWorkflowError(workflow: Workflow, errorData: Record<string, unknown>): void {+ const stepId = String(errorData.stepId ?? '');+ const step = workflow.steps.find((s) => s.id === stepId);++ if (step && step.status === 'running') {+ step.status = 'failed';+ step.error = String(errorData.error ?? 'Unknown error');+ step.completedAt = new Date();+ }+ }++ private checkpointWorkflow(workflow: Workflow): void {+ workflow.checkpoints.set(`checkpoint-${Date.now()}`, {+ progress: workflow.progress,+ currentStep: workflow.currentStep,+ stepStatuses: workflow.steps.map((s) => ({ id: s.id, status: s.status })),+ });+ }+}++/**+ * Factory function+ */+export function createMaestroPlugin(config?: Partial<MaestroConfig>): MaestroPlugin {+ return new MaestroPlugin(config);+}diff --git a/v3/@claude-flow/swarm/src/application/commands/create-task.command.ts b/v3/@claude-flow/swarm/src/application/commands/create-task.command.tsnew file mode 100644index 0000000000..9ba7ede174--- /dev/null+++ b/v3/@claude-flow/swarm/src/application/commands/create-task.command.ts@@ -0,0 +1,124 @@+/**+ * Create Task Command - Application Layer (CQRS)+ *+ * Command for creating new tasks in the swarm.+ *+ * @module v3/swarm/application/commands+ */++import { Task, TaskPriority, TaskProps } from '../../domain/entities/task.js';+import { ITaskRepository } from '../../domain/repositories/task-repository.interface.js';++/**+ * Create Task Command Input+ */+export interface CreateTaskInput {+ title: string;+ description: string;+ type: string;+ priority?: TaskPriority;+ dependencies?: string[];+ metadata?: Record<string, unknown>;+ input?: unknown;+ timeout?: number;+ maxRetries?: number;+ autoQueue?: boolean;+}++/**+ * Create Task Command Result+ */+export interface CreateTaskResult {+ success: boolean;+ taskId: string;+ task: Task;+ queuedAutomatically: boolean;+}++/**+ * Create Task Command Handler+ */+export class CreateTaskCommandHandler {+ constructor(private readonly repository: ITaskRepository) {}++ async execute(input: CreateTaskInput): Promise<CreateTaskResult> {+ // Validate dependencies exist+ if (input.dependencies && input.dependencies.length > 0) {+ for (const depId of input.dependencies) {+ const exists = await this.repository.exists(depId);+ if (!exists) {+ throw new Error(`Dependency task '${depId}' not found`);+ }+ }+ }++ // Create task+ const task = Task.create({+ title: input.title,+ description: input.description,+ type: input.type,+ priority: input.priority,+ dependencies: input.dependencies,+ metadata: input.metadata,+ input: input.input,+ timeout: input.timeout,+ maxRetries: input.maxRetries,+ });++ // Auto-queue if requested and no dependencies+ let queuedAutomatically = false;+ if (input.autoQueue && (!input.dependencies || input.dependencies.length === 0)) {+ task.queue();+ queuedAutomatically = true;+ }++ await this.repository.save(task);++ return {+ success: true,+ taskId: task.id,+ task,+ queuedAutomatically,+ };+ }+}++/**+ * Cancel Task Command Input+ */+export interface CancelTaskInput {+ taskId: string;+}++/**+ * Cancel Task Command Result+ */+export interface CancelTaskResult {+ success: boolean;+ taskId: string;+ previousStatus: string;+}++/**+ * Cancel Task Command Handler+ */+export class CancelTaskCommandHandler {+ constructor(private readonly repository: ITaskRepository) {}++ async execute(input: CancelTaskInput): Promise<CancelTaskResult> {+ const task = await this.repository.findById(input.taskId);+ if (!task) {+ throw new Error(`Task '${input.taskId}' not found`);+ }++ const previousStatus = task.status;+ task.cancel();+ await this.repository.save(task);++ return {+ success: true,+ taskId: input.taskId,+ previousStatus,+ };+ }+}diff --git a/v3/@claude-flow/swarm/src/application/commands/spawn-agent.command.ts b/v3/@claude-flow/swarm/src/application/commands/spawn-agent.command.tsnew file mode 100644index 0000000000..b7800b333f--- /dev/null+++ b/v3/@claude-flow/swarm/src/application/commands/spawn-agent.command.ts@@ -0,0 +1,122 @@+/**+ * Spawn Agent Command - Application Layer (CQRS)+ *+ * Command for spawning a new agent in the swarm.+ *+ * @module v3/swarm/application/commands+ */++import { Agent, AgentRole, AgentProps } from '../../domain/entities/agent.js';+import { IAgentRepository } from '../../domain/repositories/agent-repository.interface.js';++/**+ * Spawn Agent Command Input+ */+export interface SpawnAgentInput {+ name: string;+ role: AgentRole;+ domain: string;+ capabilities: string[];+ parentId?: string;+ metadata?: Record<string, unknown>;+ maxConcurrentTasks?: number;+ autoStart?: boolean;+}++/**+ * Spawn Agent Command Result+ */+export interface SpawnAgentResult {+ success: boolean;+ agentId: string;+ agent: Agent;+ startedAutomatically: boolean;+}++/**+ * Spawn Agent Command Handler+ */+export class SpawnAgentCommandHandler {+ constructor(private readonly repository: IAgentRepository) {}++ async execute(input: SpawnAgentInput): Promise<SpawnAgentResult> {+ // Check if agent with same name exists+ const existing = await this.repository.findByName(input.name);+ if (existing) {+ throw new Error(`Agent with name '${input.name}' already exists`);+ }++ // Create agent+ const agent = Agent.create({+ name: input.name,+ role: input.role,+ domain: input.domain,+ capabilities: input.capabilities,+ parentId: input.parentId,+ metadata: input.metadata,+ maxConcurrentTasks: input.maxConcurrentTasks,+ });++ // Auto-start if requested+ let startedAutomatically = false;+ if (input.autoStart) {+ agent.start();+ startedAutomatically = true;+ }++ await this.repository.save(agent);++ return {+ success: true,+ agentId: agent.id,+ agent,+ startedAutomatically,+ };+ }+}++/**+ * Terminate Agent Command Input+ */+export interface TerminateAgentInput {+ agentId: string;+ force?: boolean;+}++/**+ * Terminate Agent Command Result+ */+export interface TerminateAgentResult {+ success: boolean;+ agentId: string;+ tasksReassigned: number;+}++/**+ * Terminate Agent Command Handler+ */+export class TerminateAgentCommandHandler {+ constructor(private readonly repository: IAgentRepository) {}++ async execute(input: TerminateAgentInput): Promise<TerminateAgentResult> {+ const agent = await this.repository.findById(input.agentId);+ if (!agent) {+ throw new Error(`Agent '${input.agentId}' not found`);+ }++ const currentTasks = agent.currentTaskCount;++ if (currentTasks > 0 && !input.force) {+ throw new Error(`Agent has ${currentTasks} active tasks. Use force=true to terminate anyway.`);+ }++ agent.terminate();+ await this.repository.save(agent);++ return {+ success: true,+ agentId: input.agentId,+ tasksReassigned: currentTasks,+ };+ }+}diff --git a/v3/@claude-flow/swarm/src/application/index.ts b/v3/@claude-flow/swarm/src/application/index.tsnew file mode 100644index 0000000000..90b1468e41--- /dev/null+++ b/v3/@claude-flow/swarm/src/application/index.ts@@ -0,0 +1,30 @@+/**+ * Swarm Application Layer - Public Exports+ *+ * @module v3/swarm/application+ */++// Commands+export {+ SpawnAgentCommandHandler,+ TerminateAgentCommandHandler,+ type SpawnAgentInput,+ type SpawnAgentResult,+ type TerminateAgentInput,+ type TerminateAgentResult,+} from './commands/spawn-agent.command.js';++export {+ CreateTaskCommandHandler,+ CancelTaskCommandHandler,+ type CreateTaskInput,+ type CreateTaskResult,+ type CancelTaskInput,+ type CancelTaskResult,+} from './commands/create-task.command.js';++// Application Service+export {+ SwarmApplicationService,+ type SwarmConfig,+} from './services/swarm-application-service.js';diff --git a/v3/@claude-flow/swarm/src/application/services/swarm-application-service.ts b/v3/@claude-flow/swarm/src/application/services/swarm-application-service.tsnew file mode 100644index 0000000000..085d90103b--- /dev/null+++ b/v3/@claude-flow/swarm/src/application/services/swarm-application-service.ts@@ -0,0 +1,200 @@+/**+ * Swarm Application Service - Application Layer+ *+ * Orchestrates swarm operations and provides simplified interface.+ *+ * @module v3/swarm/application/services+ */++import { Agent, AgentRole, AgentStatus } from '../../domain/entities/agent.js';+import { Task, TaskStatus, TaskPriority } from '../../domain/entities/task.js';+import { IAgentRepository, AgentStatistics } from '../../domain/repositories/agent-repository.interface.js';+import { ITaskRepository, TaskStatistics } from '../../domain/repositories/task-repository.interface.js';+import { CoordinationService, LoadBalancingStrategy, SwarmHealth } from '../../domain/services/coordination-service.js';+import { SpawnAgentCommandHandler, SpawnAgentInput, TerminateAgentCommandHandler } from '../commands/spawn-agent.command.js';+import { CreateTaskCommandHandler, CreateTaskInput, CancelTaskCommandHandler } from '../commands/create-task.command.js';++/**+ * Swarm configuration+ */+export interface SwarmConfig {+ loadBalancingStrategy?: LoadBalancingStrategy;+ autoScaling?: boolean;+ minAgents?: number;+ maxAgents?: number;+}++/**+ * Swarm Application Service+ */+export class SwarmApplicationService {+ private readonly coordinationService: CoordinationService;+ private readonly spawnHandler: SpawnAgentCommandHandler;+ private readonly terminateHandler: TerminateAgentCommandHandler;+ private readonly createTaskHandler: CreateTaskCommandHandler;+ private readonly cancelTaskHandler: CancelTaskCommandHandler;++ constructor(+ private readonly agentRepository: IAgentRepository,+ private readonly taskRepository: ITaskRepository,+ private readonly config: SwarmConfig = {}+ ) {+ this.coordinationService = new CoordinationService(agentRepository, taskRepository);+ this.spawnHandler = new SpawnAgentCommandHandler(agentRepository);+ this.terminateHandler = new TerminateAgentCommandHandler(agentRepository);+ this.createTaskHandler = new CreateTaskCommandHandler(taskRepository);+ this.cancelTaskHandler = new CancelTaskCommandHandler(taskRepository);+ }++ // ============================================================================+ // Agent Operations+ // ============================================================================++ /**+ * Spawn a new agent+ */+ async spawnAgent(input: SpawnAgentInput): Promise<Agent> {+ const result = await this.spawnHandler.execute(input);+ return result.agent;+ }++ /**+ * Terminate an agent+ */+ async terminateAgent(agentId: string, force = false): Promise<void> {+ await this.terminateHandler.execute({ agentId, force });+ }++ /**+ * Get agent by ID+ */+ async getAgent(agentId: string): Promise<Agent | null> {+ return this.agentRepository.findById(agentId);+ }++ /**+ * List all agents+ */+ async listAgents(options?: {+ status?: AgentStatus;+ role?: AgentRole;+ domain?: string;+ }): Promise<Agent[]> {+ return this.agentRepository.findAll(options);+ }++ /**+ * Get agent statistics+ */+ async getAgentStatistics(): Promise<AgentStatistics> {+ return this.agentRepository.getStatistics();+ }++ // ============================================================================+ // Task Operations+ // ============================================================================++ /**+ * Create a new task+ */+ async createTask(input: CreateTaskInput): Promise<Task> {+ const result = await this.createTaskHandler.execute(input);+ return result.task;+ }++ /**+ * Cancel a task+ */+ async cancelTask(taskId: string): Promise<void> {+ await this.cancelTaskHandler.execute({ taskId });+ }++ /**+ * Get task by ID+ */+ async getTask(taskId: string): Promise<Task | null> {+ return this.taskRepository.findById(taskId);+ }++ /**+ * List tasks+ */+ async listTasks(options?: {+ status?: TaskStatus;+ priority?: TaskPriority;+ assignedAgentId?: string;+ }): Promise<Task[]> {+ return this.taskRepository.findAll(options);+ }++ /**+ * Get task statistics+ */+ async getTaskStatistics(): Promise<TaskStatistics> {+ return this.taskRepository.getStatistics();+ }++ // ============================================================================+ // Orchestration+ // ============================================================================++ /**+ * Assign pending tasks to available agents+ */+ async processPendingTasks(): Promise<number> {+ const queuedTasks = await this.taskRepository.findQueued();+ let assigned = 0;++ for (const task of queuedTasks) {+ const result = await this.coordinationService.assignTask(+ task.id,+ this.config.loadBalancingStrategy ?? 'capability-match'+ );+ if (result.success) assigned++;+ }++ return assigned;+ }++ /**+ * Complete a task+ */+ async completeTask(taskId: string, output?: unknown): Promise<void> {+ await this.coordinationService.processTaskCompletion(taskId, output);+ }++ /**+ * Fail a task+ */+ async failTask(taskId: string, error: string): Promise<boolean> {+ return this.coordinationService.processTaskFailure(taskId, error);+ }++ /**+ * Get swarm health+ */+ async getHealth(): Promise<SwarmHealth> {+ return this.coordinationService.getSwarmHealth();+ }++ /**+ * Get scaling recommendation+ */+ async getScalingRecommendation() {+ return this.coordinationService.calculateScalingRecommendation();+ }++ // ============================================================================+ // Lifecycle+ // ============================================================================++ async initialize(): Promise<void> {+ await this.agentRepository.initialize();+ await this.taskRepository.initialize();+ }++ async shutdown(): Promise<void> {+ await this.agentRepository.shutdown();+ await this.taskRepository.shutdown();+ }+}diff --git a/v3/@claude-flow/swarm/src/domain/entities/agent.ts b/v3/@claude-flow/swarm/src/domain/entities/agent.tsnew file mode 100644index 0000000000..dcdf54bbc3--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/entities/agent.ts@@ -0,0 +1,370 @@+/**+ * Agent Entity - Domain Layer+ *+ * Core domain entity representing an AI agent in the swarm.+ * Implements DDD aggregate root pattern with encapsulated business logic.+ *+ * @module v3/swarm/domain/entities+ */++import { randomUUID } from 'crypto';++/**+ * Agent status types+ */+export type AgentStatus = 'idle' | 'active' | 'busy' | 'paused' | 'terminated' | 'error';++/**+ * Agent role types - following 15-agent hierarchy+ */+export type AgentRole =+ | 'queen-coordinator'+ | 'security-architect'+ | 'security-auditor'+ | 'memory-specialist'+ | 'swarm-specialist'+ | 'integration-architect'+ | 'performance-engineer'+ | 'core-architect'+ | 'test-architect'+ | 'project-coordinator'+ | 'coder'+ | 'reviewer'+ | 'tester'+ | 'planner'+ | 'researcher'+ | 'custom';++/**+ * Agent properties+ */+export interface AgentProps {+ id?: string;+ name: string;+ role: AgentRole;+ domain: string;+ capabilities: string[];+ status?: AgentStatus;+ parentId?: string;+ metadata?: Record<string, unknown>;+ maxConcurrentTasks?: number;+ currentTaskIds?: string[];+ completedTaskCount?: number;+ createdAt?: Date;+ updatedAt?: Date;+ lastActiveAt?: Date;+}++/**+ * Agent - Aggregate Root+ *+ * Represents an individual agent with lifecycle management,+ * task tracking, and hierarchical relationships.+ */+export class Agent {+ private _id: string;+ private _name: string;+ private _role: AgentRole;+ private _domain: string;+ private _capabilities: Set<string>;+ private _status: AgentStatus;+ private _parentId?: string;+ private _metadata: Record<string, unknown>;+ private _maxConcurrentTasks: number;+ private _currentTaskIds: Set<string>;+ private _completedTaskCount: number;+ private _createdAt: Date;+ private _updatedAt: Date;+ private _lastActiveAt: Date;++ private constructor(props: AgentProps) {+ const now = new Date();+ this._id = props.id ?? randomUUID();+ this._name = props.name;+ this._role = props.role;+ this._domain = props.domain;+ this._capabilities = new Set(props.capabilities);+ this._status = props.status ?? 'idle';+ this._parentId = props.parentId;+ this._metadata = props.metadata ?? {};+ this._maxConcurrentTasks = props.maxConcurrentTasks ?? 3;+ this._currentTaskIds = new Set(props.currentTaskIds ?? []);+ this._completedTaskCount = props.completedTaskCount ?? 0;+ this._createdAt = props.createdAt ?? now;+ this._updatedAt = props.updatedAt ?? now;+ this._lastActiveAt = props.lastActiveAt ?? now;+ }++ /**+ * Factory method - Create new agent+ */+ static create(props: AgentProps): Agent {+ return new Agent(props);+ }++ /**+ * Factory method - Reconstruct from persistence+ */+ static fromPersistence(props: AgentProps): Agent {+ return new Agent(props);+ }++ // Getters+ get id(): string {+ return this._id;+ }++ get name(): string {+ return this._name;+ }++ get role(): AgentRole {+ return this._role;+ }++ get domain(): string {+ return this._domain;+ }++ get capabilities(): string[] {+ return Array.from(this._capabilities);+ }++ get status(): AgentStatus {+ return this._status;+ }++ get parentId(): string | undefined {+ return this._parentId;+ }++ get metadata(): Record<string, unknown> {+ return { ...this._metadata };+ }++ get maxConcurrentTasks(): number {+ return this._maxConcurrentTasks;+ }++ get currentTaskIds(): string[] {+ return Array.from(this._currentTaskIds);+ }++ get currentTaskCount(): number {+ return this._currentTaskIds.size;+ }++ get completedTaskCount(): number {+ return this._completedTaskCount;+ }++ get createdAt(): Date {+ return new Date(this._createdAt);+ }++ get updatedAt(): Date {+ return new Date(this._updatedAt);+ }++ get lastActiveAt(): Date {+ return new Date(this._lastActiveAt);+ }++ // ============================================================================+ // Business Logic Methods+ // ============================================================================++ /**+ * Start the agent (transition to active)+ */+ start(): void {+ if (this._status === 'terminated') {+ throw new Error('Cannot start terminated agent');+ }+ this._status = 'active';+ this._lastActiveAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Pause the agent+ */+ pause(): void {+ if (this._status !== 'active' && this._status !== 'busy') {+ throw new Error('Can only pause active or busy agent');+ }+ this._status = 'paused';+ this._updatedAt = new Date();+ }++ /**+ * Resume paused agent+ */+ resume(): void {+ if (this._status !== 'paused') {+ throw new Error('Can only resume paused agent');+ }+ this._status = this._currentTaskIds.size > 0 ? 'busy' : 'active';+ this._lastActiveAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Terminate the agent+ */+ terminate(): void {+ this._status = 'terminated';+ this._currentTaskIds.clear();+ this._updatedAt = new Date();+ }++ /**+ * Mark agent as having an error+ */+ setError(errorMessage?: string): void {+ this._status = 'error';+ if (errorMessage) {+ this._metadata['lastError'] = errorMessage;+ this._metadata['lastErrorAt'] = new Date().toISOString();+ }+ this._updatedAt = new Date();+ }++ /**+ * Recover from error state+ */+ recover(): void {+ if (this._status !== 'error') {+ throw new Error('Can only recover from error state');+ }+ this._status = 'idle';+ delete this._metadata['lastError'];+ this._updatedAt = new Date();+ }++ /**+ * Assign a task to this agent+ */+ assignTask(taskId: string): void {+ if (this._status === 'terminated') {+ throw new Error('Cannot assign task to terminated agent');+ }+ if (this._currentTaskIds.size >= this._maxConcurrentTasks) {+ throw new Error('Agent at maximum concurrent task capacity');+ }++ this._currentTaskIds.add(taskId);+ this._status = 'busy';+ this._lastActiveAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Complete a task+ */+ completeTask(taskId: string): void {+ if (!this._currentTaskIds.has(taskId)) {+ throw new Error(`Task ${taskId} not assigned to this agent`);+ }++ this._currentTaskIds.delete(taskId);+ this._completedTaskCount++;++ if (this._currentTaskIds.size === 0) {+ this._status = 'active';+ }++ this._lastActiveAt = new Date();+ this._updatedAt = new Date();+ }++ /**+ * Check if agent can accept more tasks+ */+ canAcceptTask(): boolean {+ return (+ this._status !== 'terminated' &&+ this._status !== 'error' &&+ this._status !== 'paused' &&+ this._currentTaskIds.size < this._maxConcurrentTasks+ );+ }++ /**+ * Check if agent has a specific capability+ */+ hasCapability(capability: string): boolean {+ return this._capabilities.has(capability);+ }++ /**+ * Add a capability+ */+ addCapability(capability: string): void {+ this._capabilities.add(capability);+ this._updatedAt = new Date();+ }++ /**+ * Remove a capability+ */+ removeCapability(capability: string): void {+ this._capabilities.delete(capability);+ this._updatedAt = new Date();+ }++ /**+ * Update metadata+ */+ setMetadata(key: string, value: unknown): void {+ this._metadata[key] = value;+ this._updatedAt = new Date();+ }++ /**+ * Check if agent is a child of given parent+ */+ isChildOf(parentId: string): boolean {+ return this._parentId === parentId;+ }++ /**+ * Calculate agent utilization (0-1)+ */+ getUtilization(): number {+ return this._currentTaskIds.size / this._maxConcurrentTasks;+ }++ /**+ * Check if agent is available for work+ */+ isAvailable(): boolean {+ return this._status === 'idle' || (this._status === 'active' && this.canAcceptTask());+ }++ /**+ * Convert to plain object for persistence+ */+ toPersistence(): Record<string, unknown> {+ return {+ id: this._id,+ name: this._name,+ role: this._role,+ domain: this._domain,+ capabilities: Array.from(this._capabilities),+ status: this._status,+ parentId: this._parentId,+ metadata: this._metadata,+ maxConcurrentTasks: this._maxConcurrentTasks,+ currentTaskIds: Array.from(this._currentTaskIds),+ completedTaskCount: this._completedTaskCount,+ createdAt: this._createdAt.toISOString(),+ updatedAt: this._updatedAt.toISOString(),+ lastActiveAt: this._lastActiveAt.toISOString(),+ };+ }++ toJSON(): Record<string, unknown> {+ return this.toPersistence();+ }+}diff --git a/v3/@claude-flow/swarm/src/domain/entities/task.ts b/v3/@claude-flow/swarm/src/domain/entities/task.tsnew file mode 100644index 0000000000..3b8a390988--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/entities/task.ts@@ -0,0 +1,319 @@+/**+ * Task Entity - Domain Layer+ *+ * Core domain entity representing a task in the swarm.+ * Tasks are units of work assigned to agents.+ *+ * @module v3/swarm/domain/entities+ */++import { randomUUID } from 'crypto';++/**+ * Task status types+ */+export type TaskStatus =+ | 'pending'+ | 'queued'+ | 'assigned'+ | 'running'+ | 'completed'+ | 'failed'+ | 'cancelled';++/**+ * Task priority levels+ */+export type TaskPriority = 'critical' | 'high' | 'normal' | 'low';++/**+ * Task properties+ */+export interface TaskProps {+ id?: string;+ title: string;+ description: string;+ type: string;+ priority?: TaskPriority;+ status?: TaskStatus;+ assignedAgentId?: string;+ dependencies?: string[];+ metadata?: Record<string, unknown>;+ input?: unknown;+ output?: unknown;+ error?: string;+ retryCount?: number;+ maxRetries?: number;+ timeout?: number;+ createdAt?: Date;+ startedAt?: Date;+ completedAt?: Date;+}++/**+ * Task - Entity+ *+ * Represents a unit of work with lifecycle management,+ * dependency tracking, and result storage.+ */+export class Task {+ private _id: string;+ private _title: string;+ private _description: string;+ private _type: string;+ private _priority: TaskPriority;+ private _status: TaskStatus;+ private _assignedAgentId?: string;+ private _dependencies: Set<string>;+ private _metadata: Record<string, unknown>;+ private _input?: unknown;+ private _output?: unknown;+ private _error?: string;+ private _retryCount: number;+ private _maxRetries: number;+ private _timeout: number;+ private _createdAt: Date;+ private _startedAt?: Date;+ private _completedAt?: Date;++ private constructor(props: TaskProps) {+ const now = new Date();+ this._id = props.id ?? randomUUID();+ this._title = props.title;+ this._description = props.description;+ this._type = props.type;+ this._priority = props.priority ?? 'normal';+ this._status = props.status ?? 'pending';+ this._assignedAgentId = props.assignedAgentId;+ this._dependencies = new Set(props.dependencies ?? []);+ this._metadata = props.metadata ?? {};+ this._input = props.input;+ this._output = props.output;+ this._error = props.error;+ this._retryCount = props.retryCount ?? 0;+ this._maxRetries = props.maxRetries ?? 3;+ this._timeout = props.timeout ?? 300000; // 5 minutes default+ this._createdAt = props.createdAt ?? now;+ this._startedAt = props.startedAt;+ this._completedAt = props.completedAt;+ }++ static create(props: TaskProps): Task {+ return new Task(props);+ }++ static fromPersistence(props: TaskProps): Task {+ return new Task(props);+ }++ // Getters+ get id(): string {+ return this._id;+ }+ get title(): string {+ return this._title;+ }+ get description(): string {+ return this._description;+ }+ get type(): string {+ return this._type;+ }+ get priority(): TaskPriority {+ return this._priority;+ }+ get status(): TaskStatus {+ return this._status;+ }+ get assignedAgentId(): string | undefined {+ return this._assignedAgentId;+ }+ get dependencies(): string[] {+ return Array.from(this._dependencies);+ }+ get metadata(): Record<string, unknown> {+ return { ...this._metadata };+ }+ get input(): unknown {+ return this._input;+ }+ get output(): unknown {+ return this._output;+ }+ get error(): string | undefined {+ return this._error;+ }+ get retryCount(): number {+ return this._retryCount;+ }+ get maxRetries(): number {+ return this._maxRetries;+ }+ get timeout(): number {+ return this._timeout;+ }+ get createdAt(): Date {+ return new Date(this._createdAt);+ }+ get startedAt(): Date | undefined {+ return this._startedAt ? new Date(this._startedAt) : undefined;+ }+ get completedAt(): Date | undefined {+ return this._completedAt ? new Date(this._completedAt) : undefined;+ }++ // ============================================================================+ // Business Logic+ // ============================================================================++ /**+ * Queue the task for execution+ */+ queue(): void {+ if (this._status !== 'pending') {+ throw new Error('Can only queue pending tasks');+ }+ this._status = 'queued';+ }++ /**+ * Assign task to an agent+ */+ assign(agentId: string): void {+ if (this._status !== 'queued' && this._status !== 'pending') {+ throw new Error('Can only assign queued or pending tasks');+ }+ this._assignedAgentId = agentId;+ this._status = 'assigned';+ }++ /**+ * Start task execution+ */+ start(): void {+ if (this._status !== 'assigned') {+ throw new Error('Can only start assigned tasks');+ }+ this._status = 'running';+ this._startedAt = new Date();+ }++ /**+ * Complete the task successfully+ */+ complete(output?: unknown): void {+ if (this._status !== 'running') {+ throw new Error('Can only complete running tasks');+ }+ this._status = 'completed';+ this._output = output;+ this._completedAt = new Date();+ }++ /**+ * Mark task as failed+ */+ fail(error: string): void {+ if (this._status !== 'running' && this._status !== 'assigned') {+ throw new Error('Can only fail running or assigned tasks');+ }+ this._error = error;+ this._retryCount++;++ if (this._retryCount >= this._maxRetries) {+ this._status = 'failed';+ this._completedAt = new Date();+ } else {+ // Reset for retry+ this._status = 'queued';+ this._assignedAgentId = undefined;+ }+ }++ /**+ * Cancel the task+ */+ cancel(): void {+ if (this._status === 'completed' || this._status === 'failed') {+ throw new Error('Cannot cancel finished tasks');+ }+ this._status = 'cancelled';+ this._completedAt = new Date();+ }++ /**+ * Check if all dependencies are satisfied+ */+ areDependenciesSatisfied(completedTaskIds: Set<string>): boolean {+ for (const depId of this._dependencies) {+ if (!completedTaskIds.has(depId)) {+ return false;+ }+ }+ return true;+ }++ /**+ * Check if task can be retried+ */+ canRetry(): boolean {+ return this._retryCount < this._maxRetries;+ }++ /**+ * Get execution duration in milliseconds+ */+ getExecutionDuration(): number | null {+ if (!this._startedAt) return null;+ const endTime = this._completedAt ?? new Date();+ return endTime.getTime() - this._startedAt.getTime();+ }++ /**+ * Check if task is timed out+ */+ isTimedOut(): boolean {+ if (this._status !== 'running' || !this._startedAt) return false;+ return Date.now() - this._startedAt.getTime() > this._timeout;+ }++ /**+ * Priority comparison (for sorting)+ */+ comparePriority(other: Task): number {+ const priorityOrder: Record<TaskPriority, number> = {+ critical: 0,+ high: 1,+ normal: 2,+ low: 3,+ };+ return priorityOrder[this._priority] - priorityOrder[other.priority];+ }++ toPersistence(): Record<string, unknown> {+ return {+ id: this._id,+ title: this._title,+ description: this._description,+ type: this._type,+ priority: this._priority,+ status: this._status,+ assignedAgentId: this._assignedAgentId,+ dependencies: Array.from(this._dependencies),+ metadata: this._metadata,+ input: this._input,+ output: this._output,+ error: this._error,+ retryCount: this._retryCount,+ maxRetries: this._maxRetries,+ timeout: this._timeout,+ createdAt: this._createdAt.toISOString(),+ startedAt: this._startedAt?.toISOString(),+ completedAt: this._completedAt?.toISOString(),+ };+ }++ toJSON(): Record<string, unknown> {+ return this.toPersistence();+ }+}diff --git a/v3/@claude-flow/swarm/src/domain/index.ts b/v3/@claude-flow/swarm/src/domain/index.tsnew file mode 100644index 0000000000..15f7130bc4--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/index.ts@@ -0,0 +1,41 @@+/**+ * Swarm Domain Layer - Public Exports+ *+ * @module v3/swarm/domain+ */++// Entities+export {+ Agent,+ type AgentStatus,+ type AgentRole,+ type AgentProps,+} from './entities/agent.js';++export {+ Task,+ type TaskStatus,+ type TaskPriority,+ type TaskProps,+} from './entities/task.js';++// Repository Interfaces+export {+ type IAgentRepository,+ type AgentQueryOptions,+ type AgentStatistics,+} from './repositories/agent-repository.interface.js';++export {+ type ITaskRepository,+ type TaskQueryOptions,+ type TaskStatistics,+} from './repositories/task-repository.interface.js';++// Domain Services+export {+ CoordinationService,+ type LoadBalancingStrategy,+ type TaskAssignmentResult,+ type SwarmHealth,+} from './services/coordination-service.js';diff --git a/v3/@claude-flow/swarm/src/domain/repositories/agent-repository.interface.ts b/v3/@claude-flow/swarm/src/domain/repositories/agent-repository.interface.tsnew file mode 100644index 0000000000..2952bcda1a--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/repositories/agent-repository.interface.ts@@ -0,0 +1,69 @@+/**+ * Agent Repository Interface - Domain Layer+ *+ * Defines the contract for agent persistence.+ *+ * @module v3/swarm/domain/repositories+ */++import { Agent, AgentStatus, AgentRole } from '../entities/agent.js';++/**+ * Agent query options+ */+export interface AgentQueryOptions {+ status?: AgentStatus;+ role?: AgentRole;+ domain?: string;+ parentId?: string;+ capability?: string;+ limit?: number;+ offset?: number;+}++/**+ * Agent statistics+ */+export interface AgentStatistics {+ total: number;+ byStatus: Record<AgentStatus, number>;+ byRole: Record<string, number>;+ byDomain: Record<string, number>;+ totalTasksCompleted: number;+ averageUtilization: number;+}++/**+ * Agent Repository Interface+ */+export interface IAgentRepository {+ // CRUD+ save(agent: Agent): Promise<void>;+ findById(id: string): Promise<Agent | null>;+ findByName(name: string): Promise<Agent | null>;+ delete(id: string): Promise<boolean>;+ exists(id: string): Promise<boolean>;++ // Bulk operations+ saveMany(agents: Agent[]): Promise<void>;+ findByIds(ids: string[]): Promise<Agent[]>;+ deleteMany(ids: string[]): Promise<number>;++ // Query operations+ findAll(options?: AgentQueryOptions): Promise<Agent[]>;+ findByStatus(status: AgentStatus): Promise<Agent[]>;+ findByRole(role: AgentRole): Promise<Agent[]>;+ findByDomain(domain: string): Promise<Agent[]>;+ findByParent(parentId: string): Promise<Agent[]>;+ findByCapability(capability: string): Promise<Agent[]>;+ findAvailable(): Promise<Agent[]>;++ // Statistics+ getStatistics(): Promise<AgentStatistics>;+ count(options?: AgentQueryOptions): Promise<number>;++ // Lifecycle+ initialize(): Promise<void>;+ shutdown(): Promise<void>;+ clear(): Promise<void>;+}diff --git a/v3/@claude-flow/swarm/src/domain/repositories/task-repository.interface.ts b/v3/@claude-flow/swarm/src/domain/repositories/task-repository.interface.tsnew file mode 100644index 0000000000..f9f7c84d96--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/repositories/task-repository.interface.ts@@ -0,0 +1,75 @@+/**+ * Task Repository Interface - Domain Layer+ *+ * Defines the contract for task persistence.+ *+ * @module v3/swarm/domain/repositories+ */++import { Task, TaskStatus, TaskPriority } from '../entities/task.js';++/**+ * Task query options+ */+export interface TaskQueryOptions {+ status?: TaskStatus;+ priority?: TaskPriority;+ type?: string;+ assignedAgentId?: string;+ limit?: number;+ offset?: number;+ orderBy?: 'createdAt' | 'priority' | 'startedAt';+ orderDirection?: 'asc' | 'desc';+}++/**+ * Task statistics+ */+export interface TaskStatistics {+ total: number;+ byStatus: Record<TaskStatus, number>;+ byPriority: Record<TaskPriority, number>;+ byType: Record<string, number>;+ averageExecutionTime: number;+ successRate: number;+ retryRate: number;+}++/**+ * Task Repository Interface+ */+export interface ITaskRepository {+ // CRUD+ save(task: Task): Promise<void>;+ findById(id: string): Promise<Task | null>;+ delete(id: string): Promise<boolean>;+ exists(id: string): Promise<boolean>;++ // Bulk operations+ saveMany(tasks: Task[]): Promise<void>;+ findByIds(ids: string[]): Promise<Task[]>;+ deleteMany(ids: string[]): Promise<number>;++ // Query operations+ findAll(options?: TaskQueryOptions): Promise<Task[]>;+ findByStatus(status: TaskStatus): Promise<Task[]>;+ findByPriority(priority: TaskPriority): Promise<Task[]>;+ findByAgent(agentId: string): Promise<Task[]>;+ findPending(): Promise<Task[]>;+ findQueued(): Promise<Task[]>;+ findRunning(): Promise<Task[]>;+ findTimedOut(): Promise<Task[]>;++ // Queue operations+ getNextTask(agentCapabilities?: string[]): Promise<Task | null>;+ getTaskQueue(limit?: number): Promise<Task[]>;++ // Statistics+ getStatistics(): Promise<TaskStatistics>;+ count(options?: TaskQueryOptions): Promise<number>;++ // Lifecycle+ initialize(): Promise<void>;+ shutdown(): Promise<void>;+ clear(): Promise<void>;+}diff --git a/v3/@claude-flow/swarm/src/domain/services/coordination-service.ts b/v3/@claude-flow/swarm/src/domain/services/coordination-service.tsnew file mode 100644index 0000000000..e2da2fc902--- /dev/null+++ b/v3/@claude-flow/swarm/src/domain/services/coordination-service.ts@@ -0,0 +1,320 @@+/**+ * Coordination Domain Service - Domain Layer+ *+ * Contains coordination logic that spans multiple entities.+ * Handles task assignment, load balancing, and swarm orchestration.+ *+ * @module v3/swarm/domain/services+ */++import { Agent, AgentRole } from '../entities/agent.js';+import { Task, TaskPriority } from '../entities/task.js';+import { IAgentRepository } from '../repositories/agent-repository.interface.js';+import { ITaskRepository } from '../repositories/task-repository.interface.js';++/**+ * Load balancing strategy+ */+export type LoadBalancingStrategy = 'round-robin' | 'least-loaded' | 'capability-match' | 'random';++/**+ * Task assignment result+ */+export interface TaskAssignmentResult {+ success: boolean;+ taskId: string;+ agentId?: string;+ reason?: string;+}++/**+ * Swarm health status+ */+export interface SwarmHealth {+ healthy: boolean;+ totalAgents: number;+ activeAgents: number;+ errorAgents: number;+ pendingTasks: number;+ runningTasks: number;+ queueDepth: number;+ averageUtilization: number;+ issues: string[];+}++/**+ * Coordination Domain Service+ *+ * Provides domain-level coordination operations.+ */+export class CoordinationService {+ constructor(+ private readonly agentRepository: IAgentRepository,+ private readonly taskRepository: ITaskRepository+ ) {}++ /**+ * Assign a task to the best available agent+ */+ async assignTask(+ taskId: string,+ strategy: LoadBalancingStrategy = 'capability-match'+ ): Promise<TaskAssignmentResult> {+ const task = await this.taskRepository.findById(taskId);+ if (!task) {+ return { success: false, taskId, reason: 'Task not found' };+ }++ // Check dependencies+ const completedTasks = await this.taskRepository.findByStatus('completed');+ const completedIds = new Set(completedTasks.map((t) => t.id));++ if (!task.areDependenciesSatisfied(completedIds)) {+ return { success: false, taskId, reason: 'Dependencies not satisfied' };+ }++ // Find best agent+ const agent = await this.findBestAgent(task, strategy);+ if (!agent) {+ return { success: false, taskId, reason: 'No available agents' };+ }++ // Assign task+ task.assign(agent.id);+ agent.assignTask(taskId);++ await this.taskRepository.save(task);+ await this.agentRepository.save(agent);++ return { success: true, taskId, agentId: agent.id };+ }++ /**+ * Find the best agent for a task based on strategy+ */+ private async findBestAgent(+ task: Task,+ strategy: LoadBalancingStrategy+ ): Promise<Agent | null> {+ const availableAgents = await this.agentRepository.findAvailable();++ if (availableAgents.length === 0) return null;++ switch (strategy) {+ case 'round-robin':+ return this.roundRobinSelection(availableAgents);++ case 'least-loaded':+ return this.leastLoadedSelection(availableAgents);++ case 'capability-match':+ return this.capabilityMatchSelection(availableAgents, task);++ case 'random':+ return availableAgents[Math.floor(Math.random() * availableAgents.length)];++ default:+ return availableAgents[0];+ }+ }++ private roundRobinSelection(agents: Agent[]): Agent {+ // Sort by last active time and pick least recently used+ return [...agents].sort(+ (a, b) => a.lastActiveAt.getTime() - b.lastActiveAt.getTime()+ )[0];+ }++ private leastLoadedSelection(agents: Agent[]): Agent {+ return [...agents].sort((a, b) => a.getUtilization() - b.getUtilization())[0];+ }++ private capabilityMatchSelection(agents: Agent[], task: Task): Agent | null {+ // Extract required capabilities from task type and metadata+ const requiredCapabilities = this.extractRequiredCapabilities(task);++ // Score agents by capability match+ const scored = agents.map((agent) => {+ let score = 0;+ for (const cap of requiredCapabilities) {+ if (agent.hasCapability(cap)) score++;+ }+ // Factor in utilization (prefer less loaded)+ score -= agent.getUtilization() * 0.5;+ return { agent, score };+ });++ scored.sort((a, b) => b.score - a.score);++ // Return best match if any capabilities matched+ if (scored.length > 0 && scored[0].score > 0) {+ return scored[0].agent;+ }++ // Fallback to least loaded+ return this.leastLoadedSelection(agents);+ }++ private extractRequiredCapabilities(task: Task): string[] {+ const capabilities: string[] = [task.type];++ // Map task types to required capabilities+ const capabilityMap: Record<string, string[]> = {+ implementation: ['coding', 'testing'],+ review: ['review', 'analysis'],+ testing: ['testing', 'qa'],+ documentation: ['documentation', 'writing'],+ security: ['security', 'audit'],+ performance: ['performance', 'optimization'],+ };++ if (capabilityMap[task.type]) {+ capabilities.push(...capabilityMap[task.type]);+ }++ return capabilities;+ }++ /**+ * Process completed tasks and release agents+ */+ async processTaskCompletion(taskId: string, output?: unknown): Promise<void> {+ const task = await this.taskRepository.findById(taskId);+ if (!task || !task.assignedAgentId) return;++ const agent = await this.agentRepository.findById(task.assignedAgentId);++ task.complete(output);+ await this.taskRepository.save(task);++ if (agent) {+ agent.completeTask(taskId);+ await this.agentRepository.save(agent);+ }++ // Check for dependent tasks that can now be queued+ await this.queueDependentTasks(taskId);+ }++ /**+ * Queue tasks whose dependencies are now satisfied+ */+ private async queueDependentTasks(completedTaskId: string): Promise<void> {+ const pendingTasks = await this.taskRepository.findPending();+ const completedTasks = await this.taskRepository.findByStatus('completed');+ const completedIds = new Set(completedTasks.map((t) => t.id));++ for (const task of pendingTasks) {+ if (+ task.dependencies.includes(completedTaskId) &&+ task.areDependenciesSatisfied(completedIds)+ ) {+ task.queue();+ await this.taskRepository.save(task);+ }+ }+ }++ /**+ * Handle task failure with retry logic+ */+ async processTaskFailure(taskId: string, error: string): Promise<boolean> {+ const task = await this.taskRepository.findById(taskId);+ if (!task) return false;++ const agentId = task.assignedAgentId;++ task.fail(error);+ await this.taskRepository.save(task);++ if (agentId) {+ const agent = await this.agentRepository.findById(agentId);+ if (agent) {+ agent.completeTask(taskId);+ await this.agentRepository.save(agent);+ }+ }++ // Return true if task was requeued for retry+ return task.status === 'queued';+ }++ /**+ * Get overall swarm health+ */+ async getSwarmHealth(): Promise<SwarmHealth> {+ const agentStats = await this.agentRepository.getStatistics();+ const taskStats = await this.taskRepository.getStatistics();+ const queuedTasks = await this.taskRepository.findQueued();++ const issues: string[] = [];++ // Check for issues+ if (agentStats.byStatus.error > 0) {+ issues.push(`${agentStats.byStatus.error} agents in error state`);+ }+ if (queuedTasks.length > agentStats.byStatus.active * 10) {+ issues.push('Task queue backlog detected');+ }+ if (agentStats.averageUtilization > 0.9) {+ issues.push('High agent utilization');+ }++ const timedOutTasks = await this.taskRepository.findTimedOut();+ if (timedOutTasks.length > 0) {+ issues.push(`${timedOutTasks.length} timed out tasks`);+ }++ return {+ healthy: issues.length === 0,+ totalAgents: agentStats.total,+ activeAgents: agentStats.byStatus.active + agentStats.byStatus.busy,+ errorAgents: agentStats.byStatus.error,+ pendingTasks: taskStats.byStatus.pending,+ runningTasks: taskStats.byStatus.running,+ queueDepth: queuedTasks.length,+ averageUtilization: agentStats.averageUtilization,+ issues,+ };+ }++ /**+ * Scale agents based on workload+ */+ async calculateScalingRecommendation(): Promise<{+ action: 'scale-up' | 'scale-down' | 'none';+ count: number;+ reason: string;+ }> {+ const health = await this.getSwarmHealth();+ const queuedTasks = await this.taskRepository.findQueued();++ // Scale up if queue is deep and agents are highly utilized+ if (queuedTasks.length > 10 && health.averageUtilization > 0.8) {+ const additionalAgents = Math.ceil(queuedTasks.length / 5);+ return {+ action: 'scale-up',+ count: additionalAgents,+ reason: 'High queue depth with high agent utilization',+ };+ }++ // Scale down if queue is empty and many agents are idle+ if (queuedTasks.length === 0 && health.averageUtilization < 0.2) {+ const excessAgents = Math.floor(health.totalAgents * 0.3);+ if (excessAgents > 0) {+ return {+ action: 'scale-down',+ count: excessAgents,+ reason: 'Low utilization with empty queue',+ };+ }+ }++ return {+ action: 'none',+ count: 0,+ reason: 'Current scaling is appropriate',+ };+ }+}