Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUvfaa45521f83c
diff --git a/v3/@claude-flow/cli/__tests__/cli.test.ts b/v3/@claude-flow/cli/__tests__/cli.test.ts
new file mode 100644
index 0000000000..04f1c66ee5
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/cli.test.ts
@@ -0,0 +1,455 @@
+/**
+ * V3 CLI Main Tests
+ * Comprehensive tests for CLI parsing, help output, version, and error handling
+ */
+
+import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
+import { CLI, VERSION } from '../src/index.js';
+import type { Command } from '../src/types.js';
+
+describe('CLI', () => {
+ let cli: CLI;
+ let consoleOutput: string[];
+ let consoleErrorOutput: string[];
+ let processExitMock: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ // Capture console output
+ consoleOutput = [];
+ consoleErrorOutput = [];
+
+ vi.spyOn(process.stdout, 'write').mockImplementation((str: string | Uint8Array) => {
+ consoleOutput.push(String(str));
+ return true;
+ });
+
+ vi.spyOn(process.stderr, 'write').mockImplementation((str: string | Uint8Array) => {
+ consoleErrorOutput.push(String(str));
+ return true;
+ });
+
+ // Mock process.exit to prevent actual exits
+ processExitMock = vi.spyOn(process, 'exit').mockImplementation((code?: string | number | null | undefined) => {
+ throw new Error(`process.exit: ${code}`);
+ });
+
+ // Create CLI instance (non-interactive for testing)
+ cli = new CLI({ interactive: false });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe('Version Command', () => {
+ it('should show version with --version flag', async () => {
+ await cli.run(['--version']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('claude-flow');
+ expect(output).toContain(VERSION);
+ });
+
+ it('should show version with -V flag', async () => {
+ await cli.run(['-V']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('claude-flow');
+ expect(output).toContain(VERSION);
+ });
+
+ it('should show version with correct format', async () => {
+ await cli.run(['--version']);
+
+ const output = consoleOutput.join('');
+ expect(output).toMatch(/claude-flow v\d+\.\d+\.\d+/);
+ });
+ });
+
+ describe('Help Command', () => {
+ it('should show help when no command provided', async () => {
+ await cli.run([]);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('USAGE:');
+ expect(output).toContain('COMMANDS:');
+ expect(output).toContain('GLOBAL OPTIONS:');
+ });
+
+ it('should show help with --help flag', async () => {
+ await cli.run(['--help']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('USAGE:');
+ expect(output).toContain('COMMANDS:');
+ });
+
+ it('should show help with -h flag', async () => {
+ await cli.run(['-h']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('USAGE:');
+ expect(output).toContain('COMMANDS:');
+ });
+
+ it('should show command-specific help', async () => {
+ await cli.run(['agent', '--help']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('agent');
+ expect(output).toContain('Agent management');
+ });
+
+ it('should list all available commands', async () => {
+ await cli.run(['--help']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('agent');
+ expect(output).toContain('swarm');
+ expect(output).toContain('memory');
+ expect(output).toContain('config');
+ });
+
+ it('should show V3 features in help', async () => {
+ await cli.run(['--help']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('V3 FEATURES:');
+ expect(output).toContain('15-agent');
+ expect(output).toContain('AgentDB');
+ expect(output).toContain('Flash Attention');
+ });
+
+ it('should show examples in help', async () => {
+ await cli.run(['--help']);
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('EXAMPLES:');
+ });
+ });
+
+ describe('Invalid Commands', () => {
+ it('should show error for unknown command', async () => {
+ await expect(cli.run(['invalid-command'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Unknown command: invalid-command');
+ });
+
+ it('should suggest help for unknown command', async () => {
+ await expect(cli.run(['nonexistent'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Run "claude-flow --help" for available commands');
+ });
+
+ it('should handle misspelled commands', async () => {
+ await expect(cli.run(['agnet'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Unknown command: agnet');
+ });
+ });
+
+ describe('Argument Parsing', () => {
+ it('should parse long flags', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.verbose).toBe(true);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--verbose']);
+ });
+
+ it('should parse short flags', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.v).toBe(true);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '-v']);
+ });
+
+ it('should parse flags with values', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.format).toBe('json');
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--format', 'json']);
+ });
+
+ it('should parse flags with equals syntax', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.output).toBe('file.txt');
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--output=file.txt']);
+ });
+
+ it('should parse multiple flags', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.verbose).toBe(true);
+ expect(ctx.flags.format).toBe('json');
+ expect(ctx.flags.quiet).toBe(true);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--verbose', '--format', 'json', '-q']);
+ });
+
+ it('should parse positional arguments', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.args).toEqual(['arg1', 'arg2', 'arg3']);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', 'arg1', 'arg2', 'arg3']);
+ });
+
+ it('should handle boolean flags correctly', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ options: [
+ { name: 'force', type: 'boolean', description: 'Force operation' }
+ ],
+ action: async (ctx) => {
+ expect(ctx.flags.force).toBe(true);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--force']);
+ });
+
+ it('should handle negated boolean flags', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.color).toBe(false);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--no-color']);
+ });
+ });
+
+ describe('Global Flags', () => {
+ it('should handle --quiet flag', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.quiet).toBe(true);
+ expect(ctx.interactive).toBe(false);
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--quiet']);
+ });
+
+ it('should handle --format flag', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.format).toBe('json');
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--format', 'json']);
+ });
+
+ it('should handle --config flag', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async (ctx) => {
+ expect(ctx.flags.config).toBe('./custom-config.json');
+ return { success: true };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await cli.run(['test', '--config', './custom-config.json']);
+ });
+
+ it('should disable color with --no-color', async () => {
+ await cli.run(['--no-color', '--help']);
+ // Color should be disabled - check output formatter state
+ expect(cli['output']['colorEnabled']).toBe(false);
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should handle command execution errors', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async () => {
+ throw new Error('Command failed');
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await expect(cli.run(['test'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Command failed');
+ });
+
+ it('should handle missing required options', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ options: [
+ { name: 'required-opt', type: 'string', required: true, description: 'Required option' }
+ ],
+ action: async () => ({ success: true })
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await expect(cli.run(['test'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Required option missing');
+ });
+
+ it('should show debug info when DEBUG env var is set', async () => {
+ process.env.DEBUG = '1';
+
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async () => {
+ const error = new Error('Test error');
+ error.stack = 'Error: Test error\n at test:1:1';
+ throw error;
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await expect(cli.run(['test'])).rejects.toThrow('process.exit: 1');
+
+ const output = consoleOutput.join('');
+ expect(output).toContain('Test error');
+
+ delete process.env.DEBUG;
+ });
+ });
+
+ describe('Subcommands', () => {
+ it('should execute subcommand', async () => {
+ let subcommandExecuted = false;
+
+ const subcommand: Command = {
+ name: 'sub',
+ description: 'Subcommand',
+ action: async () => {
+ subcommandExecuted = true;
+ return { success: true };
+ }
+ };
+
+ const mainCommand: Command = {
+ name: 'main',
+ description: 'Main command',
+ subcommands: [subcommand]
+ };
+
+ cli['parser'].registerCommand(mainCommand);
+ await cli.run(['main', 'sub']);
+
+ expect(subcommandExecuted).toBe(true);
+ });
+
+ it('should handle subcommand aliases', async () => {
+ let executed = false;
+
+ const subcommand: Command = {
+ name: 'list',
+ aliases: ['ls'],
+ description: 'List items',
+ action: async () => {
+ executed = true;
+ return { success: true };
+ }
+ };
+
+ const mainCommand: Command = {
+ name: 'main',
+ description: 'Main command',
+ subcommands: [subcommand]
+ };
+
+ cli['parser'].registerCommand(mainCommand);
+ await cli.run(['main', 'ls']);
+
+ expect(executed).toBe(true);
+ });
+ });
+
+ describe('Exit Codes', () => {
+ it('should exit with code 0 on success', async () => {
+ await cli.run(['--version']);
+ // No error thrown = exit code 0
+ });
+
+ it('should exit with code 1 on unknown command', async () => {
+ await expect(cli.run(['unknown'])).rejects.toThrow('process.exit: 1');
+ });
+
+ it('should exit with custom code from command result', async () => {
+ const mockCommand: Command = {
+ name: 'test',
+ description: 'Test command',
+ action: async () => {
+ return { success: false, exitCode: 42 };
+ }
+ };
+
+ cli['parser'].registerCommand(mockCommand);
+ await expect(cli.run(['test'])).rejects.toThrow('process.exit: 42');
+ });
+ });
+});
diff --git a/v3/@claude-flow/deployment/src/types.ts b/v3/@claude-flow/deployment/src/types.ts
new file mode 100644
index 0000000000..266bb89967
--- /dev/null
+++ b/v3/@claude-flow/deployment/src/types.ts
@@ -0,0 +1,159 @@
+/**
+ * Type definitions for deployment module
+ */
+
+export type VersionBumpType = 'major' | 'minor' | 'patch' | 'prerelease';
+export type ReleaseChannel = 'alpha' | 'beta' | 'rc' | 'latest';
+
+export interface ReleaseOptions {
+ /** Type of version bump */
+ bumpType?: VersionBumpType;
+ /** Specific version to set (overrides bumpType) */
+ version?: string;
+ /** Release channel/tag */
+ channel?: ReleaseChannel;
+ /** Generate changelog from git commits */
+ generateChangelog?: boolean;
+ /** Create git tag */
+ createTag?: boolean;
+ /** Commit changes */
+ commit?: boolean;
+ /** Dry run mode */
+ dryRun?: boolean;
+ /** Skip validation checks */
+ skipValidation?: boolean;
+ /** Custom git tag prefix */
+ tagPrefix?: string;
+ /** Custom changelog file path */
+ changelogPath?: string;
+}
+
+export interface ReleaseResult {
+ /** Previous version */
+ oldVersion: string;
+ /** New version */
+ newVersion: string;
+ /** Git tag name */
+ tag?: string;
+ /** Changelog content */
+ changelog?: string;
+ /** Commit hash */
+ commitHash?: string;
+ /** Success status */
+ success: boolean;
+ /** Error message if failed */
+ error?: string;
+ /** Validation warnings */
+ warnings?: string[];
+}
+
+export interface PublishOptions {
+ /** npm tag (alpha, beta, latest) */
+ tag?: string;
+ /** Access level (public, restricted) */
+ access?: 'public' | 'restricted';
+ /** Dry run mode */
+ dryRun?: boolean;
+ /** Custom registry URL */
+ registry?: string;
+ /** OTP for 2FA */
+ otp?: string;
+ /** Skip build step */
+ skipBuild?: boolean;
+ /** Custom build command */
+ buildCommand?: string;
+}
+
+export interface PublishResult {
+ /** Package name */
+ packageName: string;
+ /** Published version */
+ version: string;
+ /** npm tag */
+ tag: string;
+ /** Package tarball URL */
+ tarball?: string;
+ /** Success status */
+ success: boolean;
+ /** Error message if failed */
+ error?: string;
+ /** Publish timestamp */
+ publishedAt?: Date;
+}
+
+export interface ValidationOptions {
+ /** Run linter */
+ lint?: boolean;
+ /** Run tests */
+ test?: boolean;
+ /** Run build */
+ build?: boolean;
+ /** Check dependencies */
+ checkDependencies?: boolean;
+ /** Check uncommitted changes */
+ checkGitStatus?: boolean;
+ /** Custom lint command */
+ lintCommand?: string;
+ /** Custom test command */
+ testCommand?: string;
+ /** Custom build command */
+ buildCommand?: string;
+}
+
+export interface ValidationResult {
+ /** Overall validation success */
+ valid: boolean;
+ /** Individual check results */
+ checks: {
+ lint?: { passed: boolean; errors?: string[] };
+ test?: { passed: boolean; errors?: string[] };
+ build?: { passed: boolean; errors?: string[] };
+ dependencies?: { passed: boolean; errors?: string[] };
+ gitStatus?: { passed: boolean; errors?: string[] };
+ packageJson?: { passed: boolean; errors?: string[] };
+ };
+ /** Overall errors */
+ errors: string[];
+ /** Warnings */
+ warnings: string[];
+}
+
+export interface PackageInfo {
+ name: string;
+ version: string;
+ description?: string;
+ private?: boolean;
+ repository?: {
+ type: string;
+ url: string;
+ };
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+ publishConfig?: {
+ access?: string;
+ registry?: string;
+ };
+}
+
+export interface GitCommit {
+ hash: string;
+ message: string;
+ author: string;
+ date: string;
+ type?: string;
+ scope?: string;
+ breaking?: boolean;
+}
+
+export interface ChangelogEntry {
+ version: string;
+ date: string;
+ changes: {
+ breaking?: string[];
+ features?: string[];
+ fixes?: string[];
+ chore?: string[];
+ docs?: string[];
+ other?: string[];
+ };
+}
diff --git a/v3/hooks/composition.ts b/v3/hooks/composition.ts
deleted file mode 100644
index 5d7d4d1a29..0000000000
--- a/v3/hooks/composition.ts
+++ /dev/null
@@ -1,425 +0,0 @@
-/**
- * V3 Hook Composition
- * Utilities for composing and chaining hooks
- */
-
-import type {
- HookHandler,
- HookContext,
- HookPayload,
- HookResult,
- HookChain,
- CompositionResult,
- HookCombinators
-} from './types.js';
-
-/**
- * Hook composition utilities
- */
-export class HookComposer implements HookCombinators {
- /**
- * Pipe hooks in sequence, passing result to next
- * Each hook receives the output of the previous hook
- */
- pipe<T>(...handlers: HookHandler<T>[]): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- let currentData = payload.data;
- let lastResult: HookResult<T> = { continue: true, modified: false };
-
- for (const handler of handlers) {
- const currentPayload: HookPayload<T> = {
- ...payload,
- data: currentData
- };
-
- const result = await handler(currentPayload, context);
- lastResult = result;
-
- if (result.modified && result.data !== undefined) {
- currentData = result.data;
- }
-
- if (!result.continue) {
- break;
- }
- }
-
- return {
- ...lastResult,
- data: currentData,
- modified: currentData !== payload.data
- };
- };
- }
-
- /**
- * Execute hooks in parallel and wait for all to complete
- */
- parallel<T>(...handlers: HookHandler<T>[]): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- const results = await Promise.all(
- handlers.map(handler => handler(payload, context))
- );
-
- // Aggregate results
- const errors = results.filter(r => r.error).map(r => r.error!);
- const allContinue = results.every(r => r.continue);
- const anyModified = results.some(r => r.modified);
-
- // Merge side effects
- const sideEffects = results.flatMap(r => r.sideEffects || []);
-
- return {
- continue: allContinue,
- modified: anyModified,
- data: payload.data, // Parallel doesn't modify data
- sideEffects: sideEffects.length > 0 ? sideEffects : undefined,
- error: errors.length > 0 ? errors[0] : undefined
- };
- };
- }
-
- /**
- * Execute hooks in parallel, return first successful result
- */
- race<T>(...handlers: HookHandler<T>[]): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- return new Promise((resolve) => {
- let resolved = false;
- const errors: Error[] = [];
-
- handlers.forEach(handler => {
- handler(payload, context)
- .then(result => {
- if (resolved) return;
-
- if (!result.error) {
- resolved = true;
- resolve(result);
- } else {
- errors.push(result.error);
-
- // If all failed, resolve with error
- if (errors.length === handlers.length) {
- resolve({
- continue: true,
- modified: false,
- error: errors[0]
- });
- }
- }
- })
- .catch(error => {
- errors.push(error);
- if (errors.length === handlers.length && !resolved) {
- resolve({
- continue: true,
- modified: false,
- error: errors[0]
- });
- }
- });
- });
- });
- };
- }
-
- /**
- * Execute hooks and merge their data results
- */
- merge<T>(...handlers: HookHandler<T>[]): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- const results = await Promise.all(
- handlers.map(handler => handler(payload, context))
- );
-
- // Merge all modified data
- let mergedData = payload.data;
-
- for (const result of results) {
- if (result.modified && result.data !== undefined) {
- if (typeof mergedData === 'object' && typeof result.data === 'object') {
- mergedData = { ...mergedData as object, ...result.data as object } as T;
- } else {
- mergedData = result.data;
- }
- }
- }
-
- // Merge side effects
- const sideEffects = results.flatMap(r => r.sideEffects || []);
-
- return {
- continue: results.every(r => r.continue),
- modified: mergedData !== payload.data,
- data: mergedData,
- sideEffects: sideEffects.length > 0 ? sideEffects : undefined
- };
- };
- }
-
- /**
- * Conditionally execute hook based on predicate
- */
- when<T>(
- condition: (ctx: HookContext) => boolean,
- handler: HookHandler<T>
- ): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- if (condition(context)) {
- return handler(payload, context);
- }
-
- return {
- continue: true,
- modified: false
- };
- };
- }
-
- /**
- * Retry hook on failure with exponential backoff
- */
- retry<T>(
- handler: HookHandler<T>,
- attempts: number,
- delay: number = 1000
- ): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- let lastError: Error | undefined;
-
- for (let i = 0; i < attempts; i++) {
- try {
- const result = await handler(payload, context);
-
- if (!result.error) {
- return result;
- }
-
- lastError = result.error;
- } catch (error) {
- lastError = error as Error;
- }
-
- if (i < attempts - 1) {
- await this.delay(delay * Math.pow(2, i));
- }
- }
-
- return {
- continue: true,
- modified: false,
- error: lastError
- };
- };
- }
-
- /**
- * Add timeout to hook execution
- */
- timeout<T>(handler: HookHandler<T>, ms: number): HookHandler<T> {
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- return Promise.race([
- handler(payload, context),
- new Promise<HookResult<T>>((_, reject) => {
- setTimeout(() => {
- reject(new Error(`Hook timed out after ${ms}ms`));
- }, ms);
- })
- ]).catch(error => ({
- continue: true,
- modified: false,
- error
- }));
- };
- }
-
- /**
- * Cache hook results
- */
- cache<T>(
- handler: HookHandler<T>,
- ttl: number,
- keyFn?: (payload: HookPayload<T>) => string
- ): HookHandler<T> {
- const cache = new Map<string, { result: HookResult<T>; expires: number }>();
-
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- const key = keyFn
- ? keyFn(payload)
- : JSON.stringify(payload.data);
-
- const cached = cache.get(key);
-
- if (cached && cached.expires > Date.now()) {
- return {
- ...cached.result,
- metrics: {
- ...cached.result.metrics,
- duration: 0
- }
- };
- }
-
- const result = await handler(payload, context);
-
- cache.set(key, {
- result,
- expires: Date.now() + ttl
- });
-
- return result;
- };
- }
-
- /**
- * Execute hook only if previous result matches condition
- */
- ifResult<T>(
- condition: (result: HookResult<T>) => boolean,
- handler: HookHandler<T>
- ): HookHandler<T> {
- let lastResult: HookResult<T> | undefined;
-
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- if (lastResult && condition(lastResult)) {
- const result = await handler(payload, context);
- lastResult = result;
- return result;
- }
-
- // Execute and store result for next check
- lastResult = {
- continue: true,
- modified: false,
- data: payload.data
- };
-
- return lastResult;
- };
- }
-
- /**
- * Add logging/tracing to hook
- */
- trace<T>(
- handler: HookHandler<T>,
- name: string,
- logger?: (msg: string, data?: unknown) => void
- ): HookHandler<T> {
- const log = logger || console.log;
-
- return async (payload: HookPayload<T>, context: HookContext): Promise<HookResult<T>> => {
- const start = Date.now();
- log(`[${name}] Starting`, { hookType: context.hookType });
-
- try {
- const result = await handler(payload, context);
- const duration = Date.now() - start;
-
- log(`[${name}] Completed`, {
- hookType: context.hookType,
- duration,
- modified: result.modified,
- continue: result.continue
- });
-
- return result;
- } catch (error) {
- const duration = Date.now() - start;
- log(`[${name}] Error`, {
- hookType: context.hookType,
- duration,
- error: (error as Error).message
- });
-
- throw error;
- }
- };
- }
-
- /**
- * Create a hook chain from configuration
- */
- createChain<T>(config: HookChain): HookHandler<T> {
- const handlers = config.hooks.map(h => h.handler) as HookHandler<T>[];
-
- switch (config.mode) {
- case 'serial':
- return this.pipe(...handlers);
-
- case 'waterfall':
- return this.pipe(...handlers);
-
- case 'parallel':
- return this.parallel(...handlers);
-
- case 'race':
- return this.race(...handlers);
-
- default:
- return this.pipe(...handlers);
- }
- }
-
- /**
- * Execute a hook chain
- */
- async executeChain<T>(
- chain: HookChain,
- payload: T,
- context: HookContext
- ): Promise<CompositionResult<T>> {
- const startTime = Date.now();
- const handler = this.createChain<T>(chain);
-
- const hookPayload: HookPayload<T> = {
- data: payload,
- context,
- modifiable: true
- };
-
- try {
- const result = await handler(hookPayload, context);
-
- return {
- success: !result.error,
- results: [result],
- aggregatedData: result.modified ? result.data : payload,
- errors: result.error ? [result.error] : [],
- duration: Date.now() - startTime,
- hookCount: chain.hooks.length
- };
- } catch (error) {
- return {
- success: false,
- results: [],
- errors: [error as Error],
- duration: Date.now() - startTime,
- hookCount: chain.hooks.length
- };
- }
- }
-
- // ============================================
- // Private Methods
- // ============================================
-
- private delay(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
-
-// Export singleton instance and convenience functions
-export const composer = new HookComposer();
-
-// Re-export convenience functions
-export const pipe = composer.pipe.bind(composer);
-export const parallel = composer.parallel.bind(composer);
-export const race = composer.race.bind(composer);
-export const merge = composer.merge.bind(composer);
-export const when = composer.when.bind(composer);
-export const retry = composer.retry.bind(composer);
-export const timeout = composer.timeout.bind(composer);
-export const cache = composer.cache.bind(composer);
-export const trace = composer.trace.bind(composer);
diff --git a/v3/hooks/hook-executor.ts b/v3/hooks/hook-executor.ts
deleted file mode 100644
index c329600a69..0000000000
--- a/v3/hooks/hook-executor.ts
+++ /dev/null
@@ -1,416 +0,0 @@
-/**
- * V3 Hook Executor
- * Executes hooks with error handling, retries, and timeout support
- */
-
-import type {
- HookType,
- HookRegistration,
- HookContext,
- HookPayload,
- HookResult,
- HookMetrics,
- HookOptions,
- SideEffect,
- HookError,
- HookTimeoutError
-} from './types.js';
-import { HookRegistry, hookRegistry } from './hook-registry.js';
-
-/**
- * Executor options
- */
-export interface ExecutorOptions {
- /** Default timeout for all hooks */
- defaultTimeout?: number;
- /** Default retry count */
- defaultRetries?: number;
- /** Default retry delay */
- defaultRetryDelay?: number;
- /** Whether to collect metrics */
- collectMetrics?: boolean;
- /** Whether to process side effects */
- processSideEffects?: boolean;
- /** Side effect handler */
- sideEffectHandler?: (effect: SideEffect, context: HookContext) => Promise<void>;
-}
-
-/**
- * Execution result with full details
- */
-export interface ExecutionResult<T = unknown> {
- hookId: string;
- hookType: HookType;
- result: HookResult<T>;
- metrics: HookMetrics;
- error?: Error;
- retryCount: number;
-}
-
-/**
- * Hook executor
- */
-export class HookExecutor {
- private registry: HookRegistry;
- private options: ExecutorOptions;
- private activeExecutions: Set<string> = new Set();
-
- constructor(registry: HookRegistry = hookRegistry, options: ExecutorOptions = {}) {
- this.registry = registry;
- this.options = {
- defaultTimeout: 30000,
- defaultRetries: 0,
- defaultRetryDelay: 1000,
- collectMetrics: true,
- processSideEffects: true,
- ...options
- };
- }
-
- /**
- * Execute a single hook
- */
- async executeHook<TPayload, TResult>(
- registration: HookRegistration<TPayload, TResult>,
- payload: HookPayload<TPayload>,
- context: HookContext
- ): Promise<ExecutionResult<TResult>> {
- const executionId = this.generateExecutionId();
- const startTime = Date.now();
- let retryCount = 0;
- let lastError: Error | undefined;
-
- this.activeExecutions.add(executionId);
-
- const hookOptions = registration.options || {};
- const timeout = hookOptions.timeout || this.options.defaultTimeout!;
- const maxRetries = hookOptions.retries || this.options.defaultRetries!;
- const retryDelay = hookOptions.retryDelay || this.options.defaultRetryDelay!;
-
- try {
- while (retryCount <= maxRetries) {
- try {
- // Execute with timeout
- const result = await this.executeWithTimeout<TResult>(
- () => registration.handler(payload, context) as Promise<HookResult<TResult>>,
- timeout,
- registration.id,
- registration.type
- );
-
- // Process side effects
- if (result.sideEffects && this.options.processSideEffects && this.options.sideEffectHandler) {
- await this.processSideEffects(result.sideEffects, context);
- }
-
- // Update statistics
- if (this.options.collectMetrics) {
- const duration = Date.now() - startTime;
- this.registry.updateStatistics(registration.id, {
- totalExecutions: 1,
- successfulExecutions: 1,
- duration
- });
- }
-
- return {
- hookId: registration.id,
- hookType: registration.type,
- result,
- metrics: {
- duration: Date.now() - startTime,
- cached: false
- },
- retryCount
- };
-
- } catch (error) {
- lastError = error as Error;
- retryCount++;
-
- if (retryCount <= maxRetries) {
- // Wait before retry
- await this.delay(retryDelay * Math.pow(2, retryCount - 1)); // Exponential backoff
- }
- }
- }
-
- // All retries exhausted
- if (this.options.collectMetrics) {
- this.registry.updateStatistics(registration.id, {
- totalExecutions: 1,
- failedExecutions: 1,
- duration: Date.now() - startTime
- });
- }
-
- // Try fallback if available
- if (hookOptions.fallback) {
- try {
- const fallbackResult = await hookOptions.fallback(payload, context) as HookResult<TResult>;
- return {
- hookId: registration.id,
- hookType: registration.type,
- result: fallbackResult,
- metrics: {
- duration: Date.now() - startTime,
- cached: false
- },
- retryCount,
- error: lastError
- };
- } catch (fallbackError) {
- lastError = fallbackError as Error;
- }
- }
-
- // Call error handler if available
- if (hookOptions.onError && lastError) {
- hookOptions.onError(lastError, context);
- }
-
- // Return error result
- return {
- hookId: registration.id,
- hookType: registration.type,
- result: {
- continue: true, // Default to continue even on error
- modified: false,
- error: lastError
- },
- metrics: {
- duration: Date.now() - startTime
- },
- error: lastError,
- retryCount
- };
-
- } finally {
- this.activeExecutions.delete(executionId);
- }
- }
-
- /**
- * Execute all hooks for a type
- */
- async executeAll<TPayload, TResult>(
- type: HookType,
- payload: TPayload,
- context: Partial<HookContext> = {}
- ): Promise<ExecutionResult<TResult>[]> {
- const fullContext = this.buildContext(type, context);
- const hooks = this.registry.getByType(type).filter(h => h.enabled);
-
- if (hooks.length === 0) {
- return [];
- }
-
- const results: ExecutionResult<TResult>[] = [];
- let currentPayload = payload;
-
- for (const hook of hooks) {
- const hookPayload: HookPayload<TPayload> = {
- data: currentPayload,
- context: fullContext,
- modifiable: true
- };
-
- const result = await this.executeHook<TPayload, TResult>(
- hook as HookRegistration<TPayload, TResult>,
- hookPayload,
- fullContext
- );
-
- results.push(result);
-
- // Update payload if modified
- if (result.result.modified && result.result.data !== undefined) {
- currentPayload = result.result.data as unknown as TPayload;
- }
-
- // Stop if hook returns continue: false
- if (!result.result.continue) {
- break;
- }
- }
-
- return results;
- }
-
- /**
- * Execute hooks in parallel
- */
- async executeParallel<TPayload, TResult>(
- type: HookType,
- payload: TPayload,
- context: Partial<HookContext> = {}
- ): Promise<ExecutionResult<TResult>[]> {
- const fullContext = this.buildContext(type, context);
- const hooks = this.registry.getByType(type).filter(h => h.enabled);
-
- if (hooks.length === 0) {
- return [];
- }
-
- const hookPayload: HookPayload<TPayload> = {
- data: payload,
- context: fullContext,
- modifiable: false // Parallel execution shouldn't modify shared payload
- };
-
- const promises = hooks.map(hook =>
- this.executeHook<TPayload, TResult>(
- hook as HookRegistration<TPayload, TResult>,
- hookPayload,
- fullContext
- )
- );
-
- return Promise.all(promises);
- }
-
- /**
- * Execute hooks with race semantics (first success wins)
- */
- async executeRace<TPayload, TResult>(
- type: HookType,
- payload: TPayload,
- context: Partial<HookContext> = {}
- ): Promise<ExecutionResult<TResult> | null> {
- const fullContext = this.buildContext(type, context);
- const hooks = this.registry.getByType(type).filter(h => h.enabled);
-
- if (hooks.length === 0) {
- return null;
- }
-
- const hookPayload: HookPayload<TPayload> = {
- data: payload,
- context: fullContext,
- modifiable: false
- };
-
- return new Promise((resolve) => {
- let resolved = false;
- const results: ExecutionResult<TResult>[] = [];
-
- for (const hook of hooks) {
- this.executeHook<TPayload, TResult>(
- hook as HookRegistration<TPayload, TResult>,
- hookPayload,
- fullContext
- ).then(result => {
- if (resolved) return;
-
- if (!result.error && result.result.continue) {
- resolved = true;
- resolve(result);
- } else {
- results.push(result);
-
- // If all failed, return the first result
- if (results.length === hooks.length) {
- resolve(results[0]);
- }
- }
- });
- }
- });
- }
-
- /**
- * Get active execution count
- */
- getActiveCount(): number {
- return this.activeExecutions.size;
- }
-
- /**
- * Cancel all active executions
- */
- cancelAll(): void {
- // In a real implementation, this would abort all running hooks
- // For now, just clear the set
- this.activeExecutions.clear();
- }
-
- // ============================================
- // Private Methods
- // ============================================
-
- /**
- * Execute with timeout
- */
- private async executeWithTimeout<T>(
- fn: () => Promise<HookResult<T>>,
- timeout: number,
- hookId: string,
- hookType: HookType
- ): Promise<HookResult<T>> {
- return Promise.race([
- fn(),
- new Promise<HookResult<T>>((_, reject) => {
- setTimeout(() => {
- reject(this.createTimeoutError(hookId, hookType, timeout));
- }, timeout);
- })
- ]);
- }
-
- /**
- * Process side effects
- */
- private async processSideEffects(effects: SideEffect[], context: HookContext): Promise<void> {
- if (!this.options.sideEffectHandler) return;
-
- for (const effect of effects) {
- try {
- await this.options.sideEffectHandler(effect, context);
- } catch (error) {
- // Log but don't fail on side effect errors
- console.error(`Side effect error (${effect.type}):`, error);
- }
- }
- }
-
- /**
- * Build full context
- */
- private buildContext(type: HookType, partial: Partial<HookContext>): HookContext {
- return {
- executionId: this.generateExecutionId(),
- hookType: type,
- timestamp: Date.now(),
- source: partial.source || 'hook-executor',
- ...partial
- };
- }
-
- /**
- * Generate execution ID
- */
- private generateExecutionId(): string {
- return `exec-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- }
-
- /**
- * Create timeout error
- */
- private createTimeoutError(hookId: string, hookType: HookType, timeout: number): HookTimeoutError {
- const error = new Error(`Hook ${hookId} timed out after ${timeout}ms`) as HookTimeoutError;
- error.name = 'HookTimeoutError';
- error.hookId = hookId;
- error.hookType = hookType;
- return error;
- }
-
- /**
- * Delay helper
- */
- private delay(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
-
-// Export singleton instance
-export const hookExecutor = new HookExecutor();
diff --git a/v3/hooks/hook-manager.ts b/v3/hooks/hook-manager.ts
deleted file mode 100644
index 233229e1a9..0000000000
--- a/v3/hooks/hook-manager.ts
+++ /dev/null
@@ -1,585 +0,0 @@
-/**
- * V3 Hook Manager
- * Central manager for all hook operations
- */
-
-import { EventEmitter } from 'events';
-import type {
- HookType,
- HookRegistration,
- HookContext,
- HookPayload,
- HookResult,
- HookFilter,
- HookStatistics,
- HookPipeline,
- PipelineStage,
- SideEffect,
- IHookManager,
- HookEvent,
- HookEventType
-} from './types.js';
-import { HookRegistry } from './hook-registry.js';
-import { HookExecutor, ExecutionResult } from './hook-executor.js';
-import { HookComposer } from './composition.js';
-
-/**
- * Hook manager configuration
- */
-export interface HookManagerConfig {
- /** Default timeout for hooks */
- defaultTimeout?: number;
- /** Whether to enable metrics collection */
- enableMetrics?: boolean;
- /** Whether to process side effects */
- processSideEffects?: boolean;
- /** Maximum concurrent executions */
- maxConcurrent?: number;
- /** Whether to emit events */
- emitEvents?: boolean;
-}
-
-/**
- * V3 Hook Manager
- * Central manager for hook registration, execution, and lifecycle
- */
-export class HookManager extends EventEmitter implements IHookManager {
- private registry: HookRegistry;
- private executor: HookExecutor;
- private composer: HookComposer;
- private pipelines: Map<string, HookPipeline> = new Map();
- private config: HookManagerConfig;
-
- constructor(config: HookManagerConfig = {}) {
- super();
-
- this.config = {
- defaultTimeout: 30000,
- enableMetrics: true,
- processSideEffects: true,
- maxConcurrent: 100,
- emitEvents: true,
- ...config
- };
-
- this.registry = new HookRegistry();
- this.executor = new HookExecutor(this.registry, {
- defaultTimeout: this.config.defaultTimeout,
- collectMetrics: this.config.enableMetrics,
- processSideEffects: this.config.processSideEffects,
- sideEffectHandler: this.handleSideEffect.bind(this)
- });
- this.composer = new HookComposer();
- }
-
- // ============================================
- // Registration Methods
- // ============================================
-
- /**
- * Register a new hook
- */
- register(registration: HookRegistration): void {
- this.registry.register(registration);
-
- this.emitEvent('hook:registered', {
- hookId: registration.id,
- hookType: registration.type
- });
- }
-
- /**
- * Register multiple hooks at once
- */
- registerAll(registrations: HookRegistration[]): void {
- for (const registration of registrations) {
- this.register(registration);
- }
- }
-
- /**
- * Unregister a hook by ID
- */
- unregister(hookId: string): void {
- const hook = this.registry.getById(hookId);
- const removed = this.registry.unregister(hookId);
-
- if (removed && hook) {
- this.emitEvent('hook:unregistered', {
- hookId,
- hookType: hook.type
- });
- }
- }
-
- // ============================================
- // Execution Methods
- // ============================================
-
- /**
- * Execute hooks for a given type
- */
- async execute<T>(
- type: HookType,
- payload: T,
- context: Partial<HookContext> = {}
- ): Promise<HookResult<T>[]> {
- const fullContext = this.buildContext(type, context);
-
- this.emitEvent('hook:executing', {
- hookType: type,
- executionId: fullContext.executionId
- });
-
- const executionResults = await this.executor.executeAll<T, T>(type, payload, fullContext);
-
- this.emitEvent('hook:executed', {
- hookType: type,
- executionId: fullContext.executionId,
- resultCount: executionResults.length
- });
-
- return executionResults.map(er => er.result);
- }
-
- /**
- * Execute hooks in parallel
- */
- async executeParallel<T>(
- type: HookType,
- payload: T,
- context: Partial<HookContext> = {}
- ): Promise<HookResult<T>[]> {
- const fullContext = this.buildContext(type, context);
- const executionResults = await this.executor.executeParallel<T, T>(type, payload, fullContext);
- return executionResults.map(er => er.result);
- }
-
- /**
- * Execute hooks with race semantics
- */
- async executeRace<T>(
- type: HookType,
- payload: T,
- context: Partial<HookContext> = {}
- ): Promise<HookResult<T> | null> {
- const fullContext = this.buildContext(type, context);
- const result = await this.executor.executeRace<T, T>(type, payload, fullContext);
- return result?.result || null;
- }
-
- /**
- * Trigger a hook event (convenience method)
- */
- async trigger<T>(
- type: HookType,
- data: T,
- source: string = 'manual'
- ): Promise<HookResult<T>[]> {
- return this.execute(type, data, { source });
- }
-
- // ============================================
- // Pipeline Methods
- // ============================================
-
- /**
- * Create a new pipeline
- */
- createPipeline(config: Partial<HookPipeline>): HookPipeline {
- const pipeline: HookPipeline = {
- id: config.id || this.generatePipelineId(),
- name: config.name || 'Unnamed Pipeline',
- description: config.description,
- stages: config.stages || [],
- errorStrategy: config.errorStrategy || 'fail-fast',
- metrics: {
- executions: 0,
- avgDuration: 0,
- errorRate: 0,
- throughput: 0
- }
- };
-
- this.pipelines.set(pipeline.id, pipeline);
-
- return pipeline;
- }
-
- /**
- * Add stage to pipeline
- */
- addStage(pipelineId: string, stage: PipelineStage): void {
- const pipeline = this.pipelines.get(pipelineId);
- if (!pipeline) {
- throw new Error(`Pipeline ${pipelineId} not found`);
- }
-
- pipeline.stages.push(stage);
- }
-
- /**
- * Execute a pipeline
- */
- async executePipeline(
- pipelineId: string,
- payload: unknown,
- context: Partial<HookContext> = {}
- ): Promise<HookResult[]> {
- const pipeline = this.pipelines.get(pipelineId);
- if (!pipeline) {
- throw new Error(`Pipeline ${pipelineId} not found`);
- }
-
- const startTime = Date.now();
- const fullContext = this.buildContext('custom', { ...context, source: `pipeline:${pipelineId}` });
- const results: HookResult[] = [];
- let currentPayload = payload;
-
- this.emitEvent('pipeline:start', { pipelineId, stages: pipeline.stages.length });
-
- try {
- for (const stage of pipeline.stages) {
- // Check stage condition
- if (stage.condition && !stage.condition(fullContext)) {
- continue;
- }
-
- // Execute stage hooks
- const stagePayload: HookPayload = {
- data: currentPayload,
- context: fullContext,
- modifiable: true
- };
-
- let stageResults: HookResult[];
-
- if (stage.parallel) {
- // Execute hooks in parallel
- stageResults = await Promise.all(
- stage.hooks.map(hook =>
- hook.handler(stagePayload, fullContext)
- )
- );
- } else {
- // Execute hooks sequentially
- stageResults = [];
- for (const hook of stage.hooks) {
- const result = await hook.handler(stagePayload, fullContext);
- stageResults.push(result);
-
- if (result.modified && result.data !== undefined) {
- currentPayload = result.data;
- stagePayload.data = currentPayload;
- }
-
- if (!result.continue) {
- break;
- }
- }
- }
-
- // Apply transform if provided
- if (stage.transform) {
- stageResults = stageResults.map(stage.transform);
- }
-
- results.push(...stageResults);
-
- // Check for errors
- const hasError = stageResults.some(r => r.error);
- if (hasError) {
- if (pipeline.errorStrategy === 'fail-fast') {
- throw stageResults.find(r => r.error)!.error;
- } else if (stage.onError === 'abort') {
- break;
- }
- }
- }
-
- // Update pipeline metrics
- this.updatePipelineMetrics(pipeline, Date.now() - startTime, false);
-
- this.emitEvent('pipeline:complete', {
- pipelineId,
- duration: Date.now() - startTime,
- resultCount: results.length
- });
-
- return results;
-
- } catch (error) {
- this.updatePipelineMetrics(pipeline, Date.now() - startTime, true);
-
- this.emitEvent('pipeline:error', {
- pipelineId,
- error: (error as Error).message
- });
-
- if (pipeline.errorStrategy === 'rollback') {
- await this.rollbackPipeline(pipeline, results, fullContext);
- }
-
- throw error;
- }
- }
-
- /**
- * Get pipeline by ID
- */
- getPipeline(pipelineId: string): HookPipeline | undefined {
- return this.pipelines.get(pipelineId);
- }
-
- /**
- * Get all pipelines
- */
- getPipelines(): HookPipeline[] {
- return Array.from(this.pipelines.values());
- }
-
- // ============================================
- // Query Methods
- // ============================================
-
- /**
- * Get hooks by type
- */
- getHooks(type: HookType): HookRegistration[] {
- return this.registry.getByType(type);
- }
-
- /**
- * Get hook by ID
- */
- getHook(hookId: string): HookRegistration | undefined {
- return this.registry.getById(hookId);
- }
-
- /**
- * Get hooks by tag
- */
- getHooksByTag(tag: string): HookRegistration[] {
- return this.registry.getByTag(tag);
- }
-
- /**
- * Get all registered hook types
- */
- getTypes(): HookType[] {
- return this.registry.getTypes();
- }
-
- /**
- * Get total hook count
- */
- getCount(): number {
- return this.registry.getCount();
- }
-
- // ============================================
- // State Management
- // ============================================
-
- /**
- * Enable/disable a hook
- */
- setEnabled(hookId: string, enabled: boolean): void {
- this.registry.setEnabled(hookId, enabled);
- }
-
- /**
- * Get hook statistics
- */
- getStatistics(hookId?: string): HookStatistics | HookStatistics[] {
- const stats = this.registry.getStatistics(hookId);
- return stats || [];
- }
-
- /**
- * Clear all hooks
- */
- clear(): void {
- this.registry.clear();
- this.pipelines.clear();
- }
-
- // ============================================
- // Convenience Methods
- // ============================================
-
- /**
- * Create a simple hook registration
- */
- on<T>(
- type: HookType,
- handler: (data: T, context: HookContext) => Promise<void> | void,
- options: { id?: string; priority?: number; tags?: string[] } = {}
- ): string {
- const id = options.id || `hook-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
-
- this.register({
- id,
- type,
- name: id,
- priority: options.priority || 100,
- enabled: true,
- tags: options.tags,
- handler: async (payload, context) => {
- await handler(payload.data as T, context);
- return { continue: true, modified: false };
- }
- });
-
- return id;
- }
-
- /**
- * Remove a hook by ID (alias for unregister)
- */
- off(hookId: string): void {
- this.unregister(hookId);
- }
-
- /**
- * Register a one-time hook
- */
- once<T>(
- type: HookType,
- handler: (data: T, context: HookContext) => Promise<void> | void
- ): string {
- const id = `once-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
-
- this.register({
- id,
- type,
- name: id,
- priority: 100,
- enabled: true,
- handler: async (payload, context) => {
- await handler(payload.data as T, context);
- // Unregister after execution
- setTimeout(() => this.unregister(id), 0);
- return { continue: true, modified: false };
- }
- });
-
- return id;
- }
-
- // ============================================
- // Private Methods
- // ============================================
-
- /**
- * Build full context
- */
- private buildContext(type: HookType, partial: Partial<HookContext>): HookContext {
- return {
- executionId: this.generateExecutionId(),
- hookType: type,
- timestamp: Date.now(),
- source: partial.source || 'hook-manager',
- ...partial
- };
- }
-
- /**
- * Handle side effects
- */
- private async handleSideEffect(effect: SideEffect, context: HookContext): Promise<void> {
- // Emit side effect for external handling
- this.emit('sideEffect', { effect, context });
-
- // Built-in side effect handling
- switch (effect.type) {
- case 'log':
- console.log(`[${effect.action}]`, effect.data);
- break;
-
- case 'notification':
- this.emit('notification', effect.data);
- break;
-
- case 'metric':
- this.emit('metric', { name: effect.action, ...effect.data });
- break;
-
- case 'event':
- this.emit(effect.action, effect.data);
- break;
-
- default:
- // Other side effects handled externally
- break;
- }
- }
-
- /**
- * Update pipeline metrics
- */
- private updatePipelineMetrics(
- pipeline: HookPipeline,
- duration: number,
- hasError: boolean
- ): void {
- const metrics = pipeline.metrics;
-
- metrics.executions++;
- metrics.avgDuration = ((metrics.avgDuration * (metrics.executions - 1)) + duration) / metrics.executions;
-
- if (hasError) {
- metrics.errorRate = ((metrics.errorRate * (metrics.executions - 1)) + 1) / metrics.executions;
- } else {
- metrics.errorRate = (metrics.errorRate * (metrics.executions - 1)) / metrics.executions;
- }
-
- metrics.lastExecution = Date.now();
- }
-
- /**
- * Rollback pipeline
- */
- private async rollbackPipeline(
- pipeline: HookPipeline,
- results: HookResult[],
- context: HookContext
- ): Promise<void> {
- // Implement rollback logic based on side effects
- // This is a placeholder for actual rollback implementation
- console.warn(`Rolling back pipeline ${pipeline.name}`);
- }
-
- /**
- * Emit hook event
- */
- private emitEvent(type: HookEventType, data?: unknown): void {
- if (!this.config.emitEvents) return;
-
- const event: HookEvent = {
- type,
- timestamp: Date.now(),
- data
- };
-
- this.emit(type, event);
- this.emit('hookEvent', event);
- }
-
- /**
- * Generate execution ID
- */
- private generateExecutionId(): string {
- return `exec-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- }
-
- /**
- * Generate pipeline ID
- */
- private generatePipelineId(): string {
- return `pipe-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- }
-}
-
-// Export singleton instance
-export const hookManager = new HookManager();
diff --git a/v3/hooks/hook-registry.ts b/v3/hooks/hook-registry.ts
deleted file mode 100644
index b98a20a08f..0000000000
--- a/v3/hooks/hook-registry.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-/**
- * V3 Hook Registry
- * Central registry for hook registration and lookup
- */
-
-import type {
- HookType,
- HookRegistration,
- HookFilter,
- HookContext,
- HookStatistics,
- HookValidationError
-} from './types.js';
-
-/**
- * Hook registry for managing hook registrations
- */
-export class HookRegistry {
- /** Hooks organized by type */
- private hooksByType: Map<HookType, HookRegistration[]> = new Map();
-
- /** All hooks by ID for quick lookup */
- private hooksById: Map<string, HookRegistration> = new Map();
-
- /** Hook statistics */
- private statistics: Map<string, HookStatistics> = new Map();
-
- /** Tags index for filtering */
- private hooksByTag: Map<string, Set<string>> = new Map();
-
- /**
- * Register a new hook
- */
- register(registration: HookRegistration): void {
- // Validate registration
- this.validateRegistration(registration);
-
- const { id, type } = registration;
-
- // Check for duplicate ID
- if (this.hooksById.has(id)) {
- throw new Error(`Hook with ID '${id}' is already registered`);
- }
-
- // Initialize type list if needed
- if (!this.hooksByType.has(type)) {
- this.hooksByType.set(type, []);
- }
-
- // Add to type list, maintaining priority order
- const hookList = this.hooksByType.get(type)!;
- const insertIndex = hookList.findIndex(h => h.priority < registration.priority);
-
- if (insertIndex === -1) {
- hookList.push(registration);
- } else {
- hookList.splice(insertIndex, 0, registration);
- }
-
- // Add to ID map
- this.hooksById.set(id, registration);
-
- // Index tags
- if (registration.tags) {
- for (const tag of registration.tags) {
- if (!this.hooksByTag.has(tag)) {
- this.hooksByTag.set(tag, new Set());
- }
- this.hooksByTag.get(tag)!.add(id);
- }
- }
-
- // Initialize statistics
- this.statistics.set(id, {
- hookId: id,
- hookType: type,
- totalExecutions: 0,
- successfulExecutions: 0,
- failedExecutions: 0,
- averageDuration: 0,
- p50Duration: 0,
- p95Duration: 0,
- p99Duration: 0,
- cacheHitRate: 0
- });
- }
-
- /**
- * Unregister a hook by ID
- */
- unregister(hookId: string): boolean {
- const registration = this.hooksById.get(hookId);
-
- if (!registration) {
- return false;
- }
-
- // Remove from type list
- const hookList = this.hooksByType.get(registration.type);
- if (hookList) {
- const index = hookList.findIndex(h => h.id === hookId);
- if (index !== -1) {
- hookList.splice(index, 1);
- }
-
- // Clean up empty type list
- if (hookList.length === 0) {
- this.hooksByType.delete(registration.type);
- }
- }
-
- // Remove from ID map
- this.hooksById.delete(hookId);
-
- // Remove from tag index
- if (registration.tags) {
- for (const tag of registration.tags) {
- const tagSet = this.hooksByTag.get(tag);
- if (tagSet) {
- tagSet.delete(hookId);
- if (tagSet.size === 0) {
- this.hooksByTag.delete(tag);
- }
- }
- }
- }
-
- // Remove statistics
- this.statistics.delete(hookId);
-
- return true;
- }
-
- /**
- * Get all hooks for a specific type
- */
- getByType(type: HookType): HookRegistration[] {
- return [...(this.hooksByType.get(type) || [])];
- }
-
- /**
- * Get hooks matching a filter
- */
- getByFilter(type: HookType, filter: HookFilter, context?: HookContext): HookRegistration[] {
- const hooks = this.getByType(type);
-
- return hooks.filter(hook => {
- // Skip disabled hooks
- if (!hook.enabled) {
- return false;
- }
-
- // No filter on hook = matches all
- if (!hook.filter) {
- return true;
- }
-
- return this.matchesFilter(hook.filter, filter, context);
- });
- }
-
- /**
- * Get hook by ID
- */
- getById(hookId: string): HookRegistration | undefined {
- return this.hooksById.get(hookId);
- }
-
- /**
- * Get hooks by tag
- */
- getByTag(tag: string): HookRegistration[] {
- const hookIds = this.hooksByTag.get(tag);
- if (!hookIds) {
- return [];
- }
-
- return Array.from(hookIds)
- .map(id => this.hooksById.get(id))
- .filter((h): h is HookRegistration => h !== undefined);
- }
-
- /**
- * Check if hook exists
- */
- has(hookId: string): boolean {
- return this.hooksById.has(hookId);
- }
-
- /**
- * Set hook enabled state
- */
- setEnabled(hookId: string, enabled: boolean): boolean {
- const hook = this.hooksById.get(hookId);
- if (!hook) {
- return false;
- }
-
- hook.enabled = enabled;
- return true;
- }
-
- /**
- * Get all registered hook types
- */
- getTypes(): HookType[] {
- return Array.from(this.hooksByType.keys());
- }
-
- /**
- * Get all hooks
- */
- getAll(): HookRegistration[] {
- return Array.from(this.hooksById.values());
- }
-
- /**
- * Get hook count by type
- */
- getCountByType(): Map<HookType, number> {
- const counts = new Map<HookType, number>();
- for (const [type, hooks] of this.hooksByType) {
- counts.set(type, hooks.length);
- }
- return counts;
- }
-
- /**
- * Get total hook count
- */
- getCount(): number {
- return this.hooksById.size;
- }
-
- /**
- * Get hook statistics
- */
- getStatistics(hookId?: string): HookStatistics | HookStatistics[] | undefined {
- if (hookId) {
- return this.statistics.get(hookId);
- }
- return Array.from(this.statistics.values());
- }
-
- /**
- * Update hook statistics
- */
- updateStatistics(
- hookId: string,
- update: Partial<Pick<HookStatistics, 'totalExecutions' | 'successfulExecutions' | 'failedExecutions'>> & {
- duration?: number;
- cacheHit?: boolean;
- }
- ): void {
- const stats = this.statistics.get(hookId);
- if (!stats) return;
-
- if (update.totalExecutions !== undefined) {
- stats.totalExecutions += update.totalExecutions;
- }
-
- if (update.successfulExecutions !== undefined) {
- stats.successfulExecutions += update.successfulExecutions;
- }
-
- if (update.failedExecutions !== undefined) {
- stats.failedExecutions += update.failedExecutions;
- }
-
- if (update.duration !== undefined) {
- // Update average duration (running average)
- const n = stats.totalExecutions;
- stats.averageDuration = ((stats.averageDuration * (n - 1)) + update.duration) / n;
- }
-
- stats.lastExecutedAt = Date.now();
- }
-
- /**
- * Clear all hooks
- */
- clear(): void {
- this.hooksByType.clear();
- this.hooksById.clear();
- this.hooksByTag.clear();
- this.statistics.clear();
- }
-
- /**
- * Export registry state for persistence
- */
- export(): { hooks: HookRegistration[]; statistics: HookStatistics[] } {
- return {
- hooks: this.getAll().map(h => ({
- ...h,
- // Exclude non-serializable handler
- handler: undefined as any
- })),
- statistics: Array.from(this.statistics.values())
- };
- }
-
- // ============================================
- // Private Methods
- // ============================================
-
- /**
- * Validate hook registration
- */
- private validateRegistration(registration: HookRegistration): void {
- if (!registration.id || typeof registration.id !== 'string') {
- throw this.createValidationError('id', 'Hook ID is required and must be a string', registration.id);
- }
-
- if (!registration.type) {
- throw this.createValidationError('type', 'Hook type is required', registration.type);
- }
-
- if (typeof registration.handler !== 'function') {
- throw this.createValidationError('handler', 'Hook handler must be a function', typeof registration.handler);
- }
-
- if (typeof registration.priority !== 'number' || registration.priority < 0) {
- throw this.createValidationError('priority', 'Hook priority must be a non-negative number', registration.priority);
- }
-
- if (registration.options?.timeout !== undefined && registration.options.timeout <= 0) {
- throw this.createValidationError('options.timeout', 'Timeout must be a positive number', registration.options.timeout);
- }
-
- if (registration.options?.retries !== undefined && registration.options.retries < 0) {
- throw this.createValidationError('options.retries', 'Retries must be a non-negative number', registration.options.retries);
- }
- }
-
- /**
- * Check if a hook filter matches the given filter and context
- */
- private matchesFilter(hookFilter: HookFilter, filter: HookFilter, context?: HookContext): boolean {
- // Check agent types
- if (hookFilter.agentTypes && filter.agentTypes) {
- const hasMatch = hookFilter.agentTypes.some(t => filter.agentTypes!.includes(t));
- if (!hasMatch) return false;
- }
-
- // Check task types
- if (hookFilter.taskTypes && filter.taskTypes) {
- const hasMatch = hookFilter.taskTypes.some(t => filter.taskTypes!.includes(t));
- if (!hasMatch) return false;
- }
-
- // Check namespaces
- if (hookFilter.namespaces && filter.namespaces) {
- const hasMatch = hookFilter.namespaces.some(n => filter.namespaces!.includes(n));
- if (!hasMatch) return false;
- }
-
- // Check providers
- if (hookFilter.providers && filter.providers) {
- const hasMatch = hookFilter.providers.some(p => filter.providers!.includes(p));
- if (!hasMatch) return false;
- }
-
- // Check custom filter
- if (hookFilter.custom && context) {
- if (!hookFilter.custom(context)) return false;
- }
-
- return true;
- }
-
- /**
- * Create validation error
- */
- private createValidationError(field: string, message: string, value?: unknown): HookValidationError {
- const error = new Error(message) as HookValidationError;
- error.name = 'HookValidationError';
- error.field = field;
- error.value = value;
- return error;
- }
-}
-
-// Export singleton instance
-export const hookRegistry = new HookRegistry();
diff --git a/v3/hooks/index.ts b/v3/hooks/index.ts
deleted file mode 100644
index d55f613a63..0000000000
--- a/v3/hooks/index.ts
+++ /dev/null
@@ -1,461 +0,0 @@
-/**
- * V3 Hooks System
- * Enhanced hook system with composition, pipelines, and V3-specific hooks
- */
-
-// Export types
-export * from './types.js';
-
-// Export core components
-export { HookRegistry, hookRegistry } from './hook-registry.js';
-export { HookExecutor, hookExecutor, type ExecutorOptions, type ExecutionResult } from './hook-executor.js';
-export { HookManager, hookManager, type HookManagerConfig } from './hook-manager.js';
-export {
- HookComposer,
- composer,
- pipe,
- parallel,
- race,
- merge,
- when,
- retry,
- timeout,
- cache,
- trace
-} from './composition.js';
-
-// Import types for factory functions
-import type {
- HookType,
- HookRegistration,
- HookHandler,
- HookContext,
- HookResult,
- HookOptions,
- HookFilter,
- AgentHookContext,
- TaskHookContext,
- SwarmHookContext,
- MemoryHookContext,
- PerformanceHookContext,
- LearningHookContext
-} from './types.js';
-
-import { hookManager } from './hook-manager.js';
-
-// ============================================
-// Hook Registration Factories
-// ============================================
-
-/**
- * Create an agent lifecycle hook
- */
-export function createAgentHook(
- event: 'spawn:before' | 'spawn:after' | 'stop:before' | 'stop:after' | 'error' | 'message' | 'state-change',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `agent:${event}` as HookType;
-
- return {
- id: options.id || `agent-${event}-${Date.now()}`,
- type,
- name: options.name || `Agent ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['agent'],
- ...options
- };
-}
-
-/**
- * Create a task hook
- */
-export function createTaskHook(
- event: 'create:before' | 'create:after' | 'start:before' | 'start:after' | 'complete' | 'fail' | 'decompose' | 'assign',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `task:${event}` as HookType;
-
- return {
- id: options.id || `task-${event}-${Date.now()}`,
- type,
- name: options.name || `Task ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['task'],
- ...options
- };
-}
-
-/**
- * Create a swarm coordination hook
- */
-export function createSwarmHook(
- event: 'init:before' | 'init:after' | 'coordinate:before' | 'coordinate:after' | 'consensus:start' | 'consensus:complete' | 'scale' | 'topology-change',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `swarm:${event}` as HookType;
-
- return {
- id: options.id || `swarm-${event}-${Date.now()}`,
- type,
- name: options.name || `Swarm ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['swarm'],
- ...options
- };
-}
-
-/**
- * Create a memory hook
- */
-export function createMemoryHook(
- event: 'store:before' | 'store:after' | 'retrieve:before' | 'retrieve:after' | 'search:before' | 'search:after' | 'delete' | 'sync',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `memory:${event}` as HookType;
-
- return {
- id: options.id || `memory-${event}-${Date.now()}`,
- type,
- name: options.name || `Memory ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['memory'],
- ...options
- };
-}
-
-/**
- * Create a performance hook
- */
-export function createPerformanceHook(
- event: 'benchmark:start' | 'benchmark:end' | 'metric' | 'threshold-exceeded' | 'optimize',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `performance:${event}` as HookType;
-
- return {
- id: options.id || `performance-${event}-${Date.now()}`,
- type,
- name: options.name || `Performance ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['performance'],
- ...options
- };
-}
-
-/**
- * Create a learning/SONA hook
- */
-export function createLearningHook(
- event: 'pattern:detected' | 'pattern:stored' | 'adapt' | 'train:start' | 'train:complete' | 'feedback',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `learning:${event}` as HookType;
-
- return {
- id: options.id || `learning-${event}-${Date.now()}`,
- type,
- name: options.name || `Learning ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['learning', 'sona'],
- ...options
- };
-}
-
-/**
- * Create a session hook
- */
-export function createSessionHook(
- event: 'start' | 'end' | 'restore' | 'save',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `session:${event}` as HookType;
-
- return {
- id: options.id || `session-${event}-${Date.now()}`,
- type,
- name: options.name || `Session ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['session'],
- ...options
- };
-}
-
-/**
- * Create an MCP hook
- */
-export function createMCPHook(
- event: 'tool:call:before' | 'tool:call:after' | 'server:start' | 'server:stop',
- handler: HookHandler<unknown, unknown>,
- options: Partial<Omit<HookRegistration, 'type' | 'handler'>> = {}
-): HookRegistration {
- const type: HookType = `mcp:${event}` as HookType;
-
- return {
- id: options.id || `mcp-${event}-${Date.now()}`,
- type,
- name: options.name || `MCP ${event} hook`,
- description: options.description,
- handler,
- priority: options.priority || 100,
- enabled: options.enabled ?? true,
- filter: options.filter,
- options: options.options,
- tags: options.tags || ['mcp'],
- ...options
- };
-}
-
-// ============================================
-// Convenience Registration Functions
-// ============================================
-
-/**
- * Register a hook with the global hook manager
- */
-export function registerHook(registration: HookRegistration): void {
- hookManager.register(registration);
-}
-
-/**
- * Unregister a hook from the global hook manager
- */
-export function unregisterHook(hookId: string): void {
- hookManager.unregister(hookId);
-}
-
-/**
- * Execute hooks for a given type
- */
-export async function executeHooks<T>(
- type: HookType,
- payload: T,
- context?: Partial<HookContext>
-): Promise<HookResult<T>[]> {
- return hookManager.execute(type, payload, context);
-}
-
-/**
- * Trigger a hook event
- */
-export async function triggerHook<T>(
- type: HookType,
- data: T,
- source?: string
-): Promise<HookResult<T>[]> {
- return hookManager.trigger(type, data, source);
-}
-
-// ============================================
-// Pre-built Hook Handlers
-// ============================================
-
-/**
- * Logging hook handler
- */
-export function createLoggingHandler(
- logFn: (message: string, data?: unknown) => void = console.log
-): HookHandler<unknown, unknown> {
- return async (payload, context) => {
- logFn(`[${context.hookType}] ${context.source}`, payload.data);
- return { continue: true, modified: false };
- };
-}
-
-/**
- * Metrics collection hook handler
- */
-export function createMetricsHandler(
- metricsCollector: (metrics: { type: string; duration: number; data: unknown }) => void
-): HookHandler<unknown, unknown> {
- const startTime = Date.now();
-
- return async (payload, context) => {
- metricsCollector({
- type: context.hookType,
- duration: Date.now() - startTime,
- data: payload.data
- });
-
- return { continue: true, modified: false };
- };
-}
-
-/**
- * Validation hook handler factory
- */
-export function createValidationHandler<T>(
- validator: (data: T) => boolean | string
-): HookHandler<T, T> {
- return async (payload, context) => {
- const result = validator(payload.data);
-
- if (result === true) {
- return { continue: true, modified: false };
- }
-
- const errorMessage = typeof result === 'string' ? result : 'Validation failed';
- return {
- continue: false,
- modified: false,
- error: new Error(errorMessage)
- };
- };
-}
-
-/**
- * Transform hook handler factory
- */
-export function createTransformHandler<TIn, TOut>(
- transformer: (data: TIn) => TOut | Promise<TOut>
-): HookHandler<TIn, TOut> {
- return async (payload, context) => {
- const transformed = await transformer(payload.data);
- return {
- continue: true,
- modified: true,
- data: transformed
- };
- };
-}
-
-/**
- * Filter hook handler factory
- */
-export function createFilterHandler<T>(
- predicate: (data: T, context: HookContext) => boolean
-): HookHandler<T, T> {
- return async (payload, context) => {
- const shouldContinue = predicate(payload.data, context);
- return {
- continue: shouldContinue,
- modified: false
- };
- };
-}
-
-// ============================================
-// V3 Specific Hook Presets
-// ============================================
-
-/**
- * V3 Performance monitoring hooks
- */
-export const v3PerformanceHooks = {
- flashAttention: createPerformanceHook('metric', async (payload, context) => {
- // Track Flash Attention performance
- return {
- continue: true,
- modified: false,
- sideEffects: [{
- type: 'metric',
- action: 'flash-attention-speedup',
- data: { target: '2.49x-7.47x' }
- }]
- };
- }, { id: 'v3-flash-attention', tags: ['v3', 'performance', 'flash-attention'] }),
-
- agentDBSearch: createPerformanceHook('metric', async (payload, context) => {
- // Track AgentDB search performance
- return {
- continue: true,
- modified: false,
- sideEffects: [{
- type: 'metric',
- action: 'agentdb-search',
- data: { target: '150x-12500x' }
- }]
- };
- }, { id: 'v3-agentdb-search', tags: ['v3', 'performance', 'agentdb'] }),
-
- memoryOptimization: createPerformanceHook('optimize', async (payload, context) => {
- // Track memory optimization
- return {
- continue: true,
- modified: false,
- sideEffects: [{
- type: 'metric',
- action: 'memory-reduction',
- data: { target: '50-75%' }
- }]
- };
- }, { id: 'v3-memory-optimization', tags: ['v3', 'performance', 'memory'] })
-};
-
-/**
- * V3 Swarm coordination hooks
- */
-export const v3SwarmHooks = {
- hierarchicalMesh: createSwarmHook('init:after', async (payload, context) => {
- // Initialize hierarchical mesh topology
- return {
- continue: true,
- modified: false,
- message: 'Hierarchical mesh topology initialized'
- };
- }, { id: 'v3-hierarchical-mesh', tags: ['v3', 'swarm', 'topology'] }),
-
- fifteenAgentCoordination: createSwarmHook('coordinate:before', async (payload, context) => {
- // Setup 15-agent coordination
- return {
- continue: true,
- modified: false,
- message: '15-agent coordination prepared'
- };
- }, { id: 'v3-15-agent-coordination', tags: ['v3', 'swarm', 'coordination'] })
-};
-
-/**
- * Register all V3 preset hooks
- */
-export function registerV3Hooks(): void {
- // Register performance hooks
- Object.values(v3PerformanceHooks).forEach(hook => hookManager.register(hook));
-
- // Register swarm hooks
- Object.values(v3SwarmHooks).forEach(hook => hookManager.register(hook));
-}
-
-// Default export
-export default hookManager;
diff --git a/v3/hooks/types.ts b/v3/hooks/types.ts
deleted file mode 100644
index 5e0c5d34c3..0000000000
--- a/v3/hooks/types.ts
+++ /dev/null
@@ -1,602 +0,0 @@
-/**
- * V3 Hook System Types
- * Comprehensive type definitions for the enhanced hook system
- */
-
-// ============================================
-// Core Hook Types
-// ============================================
-
-/**
- * All available hook types in V3
- */
-export type HookType =
- // Agent lifecycle hooks
- | 'agent:spawn:before'
- | 'agent:spawn:after'
- | 'agent:stop:before'
- | 'agent:stop:after'
- | 'agent:error'
- | 'agent:message'
- | 'agent:state-change'
-
- // Task hooks
- | 'task:create:before'
- | 'task:create:after'
- | 'task:start:before'
- | 'task:start:after'
- | 'task:complete'
- | 'task:fail'
- | 'task:decompose'
- | 'task:assign'
-
- // Swarm coordination hooks
- | 'swarm:init:before'
- | 'swarm:init:after'
- | 'swarm:coordinate:before'
- | 'swarm:coordinate:after'
- | 'swarm:consensus:start'
- | 'swarm:consensus:complete'
- | 'swarm:scale'
- | 'swarm:topology-change'
-
- // Memory hooks
- | 'memory:store:before'
- | 'memory:store:after'
- | 'memory:retrieve:before'
- | 'memory:retrieve:after'
- | 'memory:search:before'
- | 'memory:search:after'
- | 'memory:delete'
- | 'memory:sync'
-
- // Performance hooks
- | 'performance:benchmark:start'
- | 'performance:benchmark:end'
- | 'performance:metric'
- | 'performance:threshold-exceeded'
- | 'performance:optimize'
-
- // Learning/SONA hooks
- | 'learning:pattern:detected'
- | 'learning:pattern:stored'
- | 'learning:adapt'
- | 'learning:train:start'
- | 'learning:train:complete'
- | 'learning:feedback'
-
- // Session hooks
- | 'session:start'
- | 'session:end'
- | 'session:restore'
- | 'session:save'
-
- // MCP hooks
- | 'mcp:tool:call:before'
- | 'mcp:tool:call:after'
- | 'mcp:server:start'
- | 'mcp:server:stop'
-
- // General hooks
- | 'error'
- | 'warning'
- | 'log'
- | 'custom';
-
-/**
- * Hook priority levels
- */
-export type HookPriority = 'critical' | 'high' | 'normal' | 'low' | 'background';
-
-/**
- * Hook execution mode
- */
-export type HookExecutionMode = 'sync' | 'async' | 'parallel' | 'sequential';
-
-// ============================================
-// Hook Context and Payload
-// ============================================
-
-/**
- * Base context available to all hooks
- */
-export interface HookContext {
- /** Unique execution ID */
- executionId: string;
- /** Hook type being executed */
- hookType: HookType;
- /** Timestamp of hook execution */
- timestamp: number;
- /** Source of the hook trigger */
- source: string;
- /** Current session ID if available */
- sessionId?: string;
- /** Metadata from the trigger */
- metadata?: Record<string, unknown>;
- /** Parent context for nested hooks */
- parent?: HookContext;
-}
-
-/**
- * Agent-specific context
- */
-export interface AgentHookContext extends HookContext {
- agentId: string;
- agentType: string;
- agentName: string;
- provider?: string;
- model?: string;
- capabilities?: string[];
-}
-
-/**
- * Task-specific context
- */
-export interface TaskHookContext extends HookContext {
- taskId: string;
- taskDescription: string;
- taskPriority?: 'high' | 'medium' | 'low';
- assignedAgent?: string;
- dependencies?: string[];
- estimatedDuration?: number;
-}
-
-/**
- * Swarm-specific context
- */
-export interface SwarmHookContext extends HookContext {
- swarmId: string;
- topology: string;
- agentCount: number;
- strategy: string;
- coordinatorId?: string;
-}
-
-/**
- * Memory-specific context
- */
-export interface MemoryHookContext extends HookContext {
- namespace: string;
- key?: string;
- operation: 'store' | 'retrieve' | 'search' | 'delete' | 'sync';
- backend: string;
- isVector?: boolean;
-}
-
-/**
- * Performance-specific context
- */
-export interface PerformanceHookContext extends HookContext {
- operation: string;
- duration?: number;
- metrics?: Record<string, number>;
- threshold?: number;
-}
-
-/**
- * Learning-specific context
- */
-export interface LearningHookContext extends HookContext {
- patternId?: string;
- patternType?: string;
- confidence?: number;
- source?: string;
- rewardSignal?: number;
-}
-
-/**
- * Generic hook payload
- */
-export interface HookPayload<T = unknown> {
- data: T;
- context: HookContext;
- modifiable?: boolean;
-}
-
-// ============================================
-// Hook Handler Types
-// ============================================
-
-/**
- * Result returned by hook handlers
- */
-export interface HookResult<T = unknown> {
- /** Whether to continue execution */
- continue: boolean;
- /** Whether the payload was modified */
- modified: boolean;
- /** Modified payload data */
- data?: T;
- /** Error if any */
- error?: Error;
- /** Side effects to process */
- sideEffects?: SideEffect[];
- /** Metrics from this hook execution */
- metrics?: HookMetrics;
- /** Message for logging */
- message?: string;
-}
-
-/**
- * Hook handler function signature
- */
-export type HookHandler<TPayload = unknown, TResult = unknown> = (
- payload: HookPayload<TPayload>,
- context: HookContext
-) => Promise<HookResult<TResult>> | HookResult<TResult>;
-
-/**
- * Async hook handler
- */
-export type AsyncHookHandler<TPayload = unknown, TResult = unknown> = (
- payload: HookPayload<TPayload>,
- context: HookContext
-) => Promise<HookResult<TResult>>;
-
-/**
- * Sync hook handler
- */
-export type SyncHookHandler<TPayload = unknown, TResult = unknown> = (
- payload: HookPayload<TPayload>,
- context: HookContext
-) => HookResult<TResult>;
-
-// ============================================
-// Hook Registration
-// ============================================
-
-/**
- * Hook registration configuration
- */
-export interface HookRegistration<TPayload = unknown, TResult = unknown> {
- /** Unique hook ID */
- id: string;
- /** Hook type to listen for */
- type: HookType;
- /** Hook name for display */
- name: string;
- /** Hook description */
- description?: string;
- /** Handler function */
- handler: HookHandler<TPayload, TResult>;
- /** Execution priority (higher = earlier) */
- priority: number;
- /** Priority level for readability */
- priorityLevel?: HookPriority;
- /** Whether hook is enabled */
- enabled: boolean;
- /** Execution mode */
- mode?: HookExecutionMode;
- /** Filter conditions */
- filter?: HookFilter;
- /** Hook options */
- options?: HookOptions;
- /** Tags for categorization */
- tags?: string[];
- /** Version requirement */
- version?: string;
-}
-
-/**
- * Hook filter conditions
- */
-export interface HookFilter {
- /** Filter by agent types */
- agentTypes?: string[];
- /** Filter by task types */
- taskTypes?: string[];
- /** Filter by namespaces */
- namespaces?: string[];
- /** Filter by providers */
- providers?: string[];
- /** Filter by patterns */
- patterns?: RegExp[];
- /** Custom filter function */
- custom?: (context: HookContext) => boolean;
-}
-
-/**
- * Hook options
- */
-export interface HookOptions {
- /** Timeout in milliseconds */
- timeout?: number;
- /** Number of retries on failure */
- retries?: number;
- /** Retry delay in milliseconds */
- retryDelay?: number;
- /** Whether to run in isolated context */
- isolated?: boolean;
- /** Cache configuration */
- cache?: {
- enabled: boolean;
- ttl: number;
- key: (payload: HookPayload) => string;
- };
- /** Error handler */
- onError?: (error: Error, context: HookContext) => void;
- /** Fallback handler on failure */
- fallback?: HookHandler;
- /** Dependencies on other hooks */
- dependsOn?: string[];
- /** Abort signal for cancellation */
- signal?: AbortSignal;
-}
-
-// ============================================
-// Side Effects
-// ============================================
-
-/**
- * Side effect types
- */
-export type SideEffectType =
- | 'memory'
- | 'neural'
- | 'metric'
- | 'notification'
- | 'log'
- | 'event'
- | 'spawn-agent'
- | 'create-task'
- | 'update-state'
- | 'external-call';
-
-/**
- * Side effect definition
- */
-export interface SideEffect {
- type: SideEffectType;
- action: string;
- data: Record<string, unknown>;
- priority?: HookPriority;
- async?: boolean;
-}
-
-// ============================================
-// Hook Pipeline
-// ============================================
-
-/**
- * Pipeline stage
- */
-export interface PipelineStage {
- name: string;
- hooks: HookRegistration[];
- parallel?: boolean;
- condition?: (context: HookContext) => boolean;
- transform?: (result: HookResult) => HookResult;
- onError?: 'skip' | 'abort' | 'retry';
-}
-
-/**
- * Hook pipeline configuration
- */
-export interface HookPipeline {
- id: string;
- name: string;
- description?: string;
- stages: PipelineStage[];
- errorStrategy: 'fail-fast' | 'continue' | 'rollback';
- metrics: PipelineMetrics;
-}
-
-/**
- * Pipeline metrics
- */
-export interface PipelineMetrics {
- executions: number;
- avgDuration: number;
- errorRate: number;
- throughput: number;
- lastExecution?: number;
-}
-
-// ============================================
-// Hook Metrics
-// ============================================
-
-/**
- * Metrics from hook execution
- */
-export interface HookMetrics {
- /** Execution duration in ms */
- duration: number;
- /** Whether result was cached */
- cached?: boolean;
- /** Memory used */
- memoryUsed?: number;
- /** Tokens processed */
- tokensProcessed?: number;
- /** Custom metrics */
- custom?: Record<string, number>;
-}
-
-/**
- * Aggregated hook statistics
- */
-export interface HookStatistics {
- hookId: string;
- hookType: HookType;
- totalExecutions: number;
- successfulExecutions: number;
- failedExecutions: number;
- averageDuration: number;
- p50Duration: number;
- p95Duration: number;
- p99Duration: number;
- cacheHitRate: number;
- lastExecutedAt?: number;
- errorTypes?: Record<string, number>;
-}
-
-// ============================================
-// Hook Events
-// ============================================
-
-/**
- * Hook event types
- */
-export type HookEventType =
- | 'hook:registered'
- | 'hook:unregistered'
- | 'hook:executing'
- | 'hook:executed'
- | 'hook:error'
- | 'hook:timeout'
- | 'hook:retry'
- | 'pipeline:start'
- | 'pipeline:complete'
- | 'pipeline:error';
-
-/**
- * Hook event
- */
-export interface HookEvent {
- type: HookEventType;
- hookId?: string;
- hookType?: HookType;
- pipelineId?: string;
- timestamp: number;
- data?: unknown;
- error?: Error;
-}
-
-// ============================================
-// Hook Manager Interface
-// ============================================
-
-/**
- * Hook manager interface
- */
-export interface IHookManager {
- /** Register a hook */
- register(registration: HookRegistration): void;
-
- /** Unregister a hook */
- unregister(hookId: string): void;
-
- /** Execute hooks for a type */
- execute<T>(type: HookType, payload: T, context?: Partial<HookContext>): Promise<HookResult<T>[]>;
-
- /** Get hooks by type */
- getHooks(type: HookType): HookRegistration[];
-
- /** Get hook by ID */
- getHook(hookId: string): HookRegistration | undefined;
-
- /** Enable/disable hook */
- setEnabled(hookId: string, enabled: boolean): void;
-
- /** Get hook statistics */
- getStatistics(hookId?: string): HookStatistics | HookStatistics[];
-
- /** Clear all hooks */
- clear(): void;
-
- /** Create a pipeline */
- createPipeline(config: Partial<HookPipeline>): HookPipeline;
-
- /** Execute a pipeline */
- executePipeline(pipelineId: string, payload: unknown, context?: Partial<HookContext>): Promise<HookResult[]>;
-}
-
-// ============================================
-// Hook Composition Types
-// ============================================
-
-/**
- * Hook chain configuration
- */
-export interface HookChain {
- id: string;
- name: string;
- hooks: HookRegistration[];
- mode: 'serial' | 'waterfall' | 'parallel' | 'race';
- stopOnError?: boolean;
- timeout?: number;
-}
-
-/**
- * Hook composition result
- */
-export interface CompositionResult<T = unknown> {
- success: boolean;
- results: HookResult<T>[];
- aggregatedData?: T;
- errors: Error[];
- duration: number;
- hookCount: number;
-}
-
-/**
- * Hook combinator functions
- */
-export interface HookCombinators {
- /** Run hooks in sequence, passing result to next */
- pipe<T>(...handlers: HookHandler<T>[]): HookHandler<T>;
-
- /** Run hooks in parallel */
- parallel<T>(...handlers: HookHandler<T>[]): HookHandler<T>;
-
- /** Run first successful hook */
- race<T>(...handlers: HookHandler<T>[]): HookHandler<T>;
-
- /** Run hooks and merge results */
- merge<T>(...handlers: HookHandler<T>[]): HookHandler<T>;
-
- /** Apply condition before running hook */
- when<T>(condition: (ctx: HookContext) => boolean, handler: HookHandler<T>): HookHandler<T>;
-
- /** Retry hook on failure */
- retry<T>(handler: HookHandler<T>, attempts: number, delay?: number): HookHandler<T>;
-
- /** Add timeout to hook */
- timeout<T>(handler: HookHandler<T>, ms: number): HookHandler<T>;
-
- /** Cache hook results */
- cache<T>(handler: HookHandler<T>, ttl: number, keyFn?: (payload: HookPayload<T>) => string): HookHandler<T>;
-}
-
-// ============================================
-// Error Types
-// ============================================
-
-/**
- * Hook error
- */
-export class HookError extends Error {
- constructor(
- message: string,
- public hookId: string,
- public hookType: HookType,
- public cause?: Error
- ) {
- super(message);
- this.name = 'HookError';
- }
-}
-
-/**
- * Hook timeout error
- */
-export class HookTimeoutError extends HookError {
- constructor(hookId: string, hookType: HookType, timeout: number) {
- super(`Hook ${hookId} timed out after ${timeout}ms`, hookId, hookType);
- this.name = 'HookTimeoutError';
- }
-}
-
-/**
- * Hook validation error
- */
-export class HookValidationError extends Error {
- constructor(
- message: string,
- public field: string,
- public value?: unknown
- ) {
- super(message);
- this.name = 'HookValidationError';
- }
-}