src — hooks

Module: src-hooks Cohesion: 0.80 Members: 0

src — hooks

The src/hooks module is a central component for extending, automating, and managing various aspects of the Code Buddy application. It provides multiple, distinct hook systems and related utilities, allowing developers to inject custom logic at different points in the application's lifecycle, integrate with external services, manage session state, log actions, and enhance user interface interactions.

This module can be broadly categorized into:

  1. Core Event & Lifecycle Hook Systems: For executing commands or custom logic in response to application events.
  2. Advanced, LLM-Integrated Hook Systems: More sophisticated, Enterprise-grade hooks that can interact with LLMs or external HTTP services.
  3. Specialized Hook-Related Utilities: Components that support or enhance the hook systems, such as asynchronous execution, environment persistence, or a global event bus.
  4. Moltbot-Inspired Hooks: A suite of managers for handling session introductions, persistence, and command logging.
  5. UI-Related React Hooks: For managing user input, history, and suggestions within the chat interface.

I. Core Event & Lifecycle Hook Systems

This section covers the foundational hook systems that primarily execute shell commands or custom handlers in response to various application events.

A. HookSystem (src/hooks/hook-system.ts)

The HookSystem provides a basic, file-based mechanism for executing shell commands at predefined lifecycle events. It's designed for straightforward automation tasks.

    import { getHookSystem, HookType } from './hooks/hook-system.js';

    const hookSystem = getHookSystem();
    if (hookSystem.hasHooks('pre-commit')) {
      const results = await hookSystem.executeHooks('pre-commit', { files: ['src/index.ts'] });
      class="hl-cmt">// Process results
    }

B. HookManager (src/hooks/hook-manager.ts)

The HookManager is another command-execution hook system, offering slightly different event types and a more structured approach to configuration loading (global then project-level). It also introduces the concept of hooks blocking operations or modifying arguments via JSON output.

    import { getHookManager, HookEvent } from './hooks/hook-manager.js';

    const hookManager = getHookManager();
    const result = await hookManager.executeHooks(HookEvent.PreToolUse, {
      toolName: 'bash',
      toolArgs: { command: 'ls -la' },
    });
    if (result.blocked) {
      console.log('Operation blocked:', result.error);
    }

C. HooksManager (Comprehensive Lifecycle Hooks - src/hooks/lifecycle-hooks.ts)

This HooksManager provides a more comprehensive and extensible lifecycle hook system, supporting not just shell commands but also script files and direct JavaScript handler functions. It comes with a set of BUILTIN_HOOKS and a rich set of event types.

    import { getHooksManager, HookType } from './hooks/lifecycle-hooks.js';

    const hooksManager = getHooksManager();
    hooksManager.registerHook({
      name: 'custom-pre-edit',
      type: 'pre-edit',
      handler: async (context) => {
        console.log(`Pre-edit hook for ${context.file}`);
        return { success: true, duration: 10 };
      },
      enabled: true,
      timeout: 5000,
      failOnError: false,
    });

    const results = await hooksManager.executeHooks(HookType['pre-edit'], { file: 'test.txt' });

II. Advanced, LLM-Integrated Hook Systems (Enterprise-grade)

These systems offer more sophisticated hook capabilities, including interaction with LLMs and HTTP services, often inspired by the extensibility model of tools natively.

A. HookRunner (Extended Hooks with Multiple Handlers - src/hooks/hook-runner.ts & src/hooks/hook-types.ts)

The HookRunner implements an advanced, Enterprise-grade hook system with support for various handler types beyond just shell commands. It uses hook-types.ts to define its rich type system.

    import { getHookRunner, ExtendedHookEvent } from './hooks/hook-runner.js';

    const runner = getHookRunner();
    const result = await runner.run(ExtendedHookEvent.PreToolUse, {
      toolName: 'git',
      toolArgs: { command: 'commit' },
    });
    if (result.blocked) {
      console.log('Git commit blocked by hook:', result.error);
    }

B. AdvancedHookRunner & HookRegistry (src/hooks/advanced-hooks.ts)

This module presents another Native Engine-like hook system, focusing on command, prompt, and agent hooks with a dedicated registry for managing them.

    import { getHookRegistry, getAdvancedHookRunner, HookEvent } from './hooks/advanced-hooks.js';

    const registry = getHookRegistry();
    registry.addHook({
      name: 'security-check',
      event: HookEvent.PreToolUse,
      type: 'command',
      command: 'security-script.sh',
      matcher: /^(npm|yarn)$/,
    });

    const runner = getAdvancedHookRunner();
    const decision = await runner.runHook(registry.getHook('security-check')!, {
      event: HookEvent.PreToolUse,
      toolName: 'npm',
      input: { args: ['install'] },
    });
    console.log('Hook decision:', decision.action);

These modules provide supporting functionality that can be used independently or in conjunction with the various hook systems.

A. AsyncHookManager (src/hooks/async-hooks.ts)

Manages the asynchronous execution of hooks, providing concurrency control, job tracking, and result collection.

    import { AsyncHookManager } from './hooks/async-hooks.js';
    import { SmartHookConfig } from './hooks/smart-hooks.js'; class="hl-cmt">// Assuming SmartHookConfig is compatible

    const asyncManager = new AsyncHookManager(5); class="hl-cmt">// Max 5 concurrent hooks
    const hookConfig: SmartHookConfig = {
      name: 'long-running-check',
      event: 'PostToolUse',
      type: 'command',
      command: 'sleep 10 && echo "Done"',
    };
    const jobId = asyncManager.submit(hookConfig, { toolName: 'test' });
    class="hl-cmt">// ... later ...
    const completedJobs = asyncManager.getCompletedJobs();
    const systemMessages = asyncManager.getSystemMessages();

B. HookEventEmitter (src/hooks/hook-events.ts)

A global EventEmitter instance for specific, high-level application events, particularly those requiring synchronous responses like permission requests.

    import { HookEventEmitter, NotificationType } from './hooks/hook-events.js';

    const eventEmitter = HookEventEmitter.getInstance();
    eventEmitter.onNotification((payload) => {
      console.log(`Notification: ${payload.type} - ${payload.message}`);
    });
    eventEmitter.emitNotification({ type: 'auth_success', message: 'User logged in' });

    const response = eventEmitter.emitPermissionRequest({ tool: 'rm', input: 'file.txt' });
    console.log('Permission decision:', response.action);

C. EnvPersistence (src/hooks/env-persistence.ts)

Manages environment variables for a session, persisting them to a temporary .env file and allowing them to be applied to process.env.

    import { EnvPersistence } from './hooks/env-persistence.js';

    const envManager = new EnvPersistence('my-session-id');
    envManager.setVar('MY_API_KEY', 'some-secret-value');
    envManager.applyToProcess();
    console.log(process.env.MY_API_KEY);

    const before = { ...process.env };
    process.env.NEW_VAR = 'new-value';
    envManager.captureEnvChanges(before, process.env as Record<string, string>);

IV. Moltbot-Inspired Hooks (src/hooks/moltbot/)

This sub-module provides a suite of managers inspired by Moltbot's approach to session management, introductory messages, and command logging. It's designed to enhance the AI's context and provide auditing capabilities.

A. Overview

The Moltbot hooks system is composed of three core managers: IntroHookManager, SessionPersistenceManager, and CommandLogger, all orchestrated by the MoltbotHooksManager. It aims to provide a robust framework for:

B. IntroHookManager (src/hooks/moltbot/intro-hook-manager.ts)

Manages the loading and combination of introductory content for new sessions.

    import { IntroHookManager } from &#39;./hooks/moltbot/intro-hook-manager.js&#39;;

    const introManager = new IntroHookManager(process.cwd());
    const introResult = await introManager.loadIntro();
    console.log(&#39;Intro content:&#39;, introResult.content);

C. SessionPersistenceManager (src/hooks/moltbot/session-persistence-manager.ts)

Handles the saving and loading of conversation sessions, including messages and tool calls.

    import { SessionPersistenceManager } from &#39;./hooks/moltbot/session-persistence-manager.js&#39;;

    const sessionManager = new SessionPersistenceManager(process.cwd());
    const session = await sessionManager.startSession();
    sessionManager.addMessage({ role: &#39;user&#39;, content: &#39;Hello&#39; });
    await sessionManager.saveSession();

D. CommandLogger (src/hooks/moltbot/command-logger.ts)

Logs all AI actions, including tool calls, bash commands, and file edits, with support for redaction and log rotation.

    import { CommandLogger } from &#39;./hooks/moltbot/command-logger.js&#39;;

    const commandLogger = new CommandLogger();
    commandLogger.setSessionId(&#39;my-session-id&#39;);
    commandLogger.logBashCommand(&#39;ls -la&#39;, { success: true, output: &#39;file.txt&#39; });

E. MoltbotHooksManager (Orchestrator - src/hooks/moltbot/moltbot-hooks-manager.ts)

The central manager that orchestrates the IntroHookManager, SessionPersistenceManager, and CommandLogger.

    import { getMoltbotHooksManager } from &#39;./hooks/moltbot/moltbot-hooks-manager.js&#39;;

    const moltbotManager = getMoltbotHooksManager(process.cwd());
    const { intro, session } = await moltbotManager.initializeSession();
    console.log(`Session ${session.id} started with intro content.`);
    moltbotManager.getCommandLogger().log({ type: &#39;system&#39;, action: &#39;session_init&#39; });
    await moltbotManager.endSession();

F. Setup Utilities (src/hooks/moltbot/setup-utilities.ts)

Convenience functions for checking, setting up, enabling, and disabling Moltbot hooks configuration files.

These hooks are specifically designed for use within React components to manage user input, history, and provide interactive suggestions in the chat interface.

A. useEnhancedInput (src/hooks/use-enhanced-input.ts)

A React hook that provides enhanced input field capabilities, including history navigation and command/file suggestions.

    import { useEnhancedInput } from &#39;./hooks/use-enhanced-input.js&#39;;

    function MyInputComponent() {
      const { inputValue, setInputValue, handleKeyDown, suggestions } = useEnhancedInput();
      class="hl-cmt">// ... render input and suggestions ...
    }

B. useInputHandler (src/hooks/use-input-handler.ts)

A React hook that centralizes keyboard event handling for the chat input, parsing commands, and dispatching actions.

    import { useInputHandler } from &#39;./hooks/use-input-handler.js&#39;;

    function ChatInput() {
      const { handleInputChange, handleKeyDown, handleInputSubmit } = useInputHandler();
      class="hl-cmt">// ... render input with these handlers ...
    }

C. useInputHistory (src/hooks/use-input-history.ts)

A React hook for managing the history of user inputs.

    import { useInputHistory } from &#39;./hooks/use-input-history.js&#39;;

    function HistoryNavigator() {
      const { historyUp, historyDown, currentInput } = useInputHistory();
      class="hl-cmt">// ... use currentInput and navigation functions ...
    }

VI. Architectural Overview

The src/hooks module is a collection of distinct, yet sometimes overlapping, systems. The following diagram illustrates the high-level categories of hook systems and their primary interactions.

graph TD
    subgraph Hook System Categories
        A[Basic Command Hooks]
        B[Lifecycle Hooks]
        C[Advanced LLM/HTTP Hooks]
        D[Moltbot Session/Logging Hooks]
        E[UI Input Hooks]
    end

    A -->|Config: .codebuddy/hooks.json| F[File System]
    B -->|Config: .codebuddy/hooks.json| F
    C -->|Config: .codebuddy/hooks.json (extendedHooks)| F
    D -->|Config: .codebuddy/moltbot-hooks.json| F
    C -->|Integrates with| G[LLM / HTTP Services]
    D -->|Integrates with| H[Session Storage / Command Logs]
    E -->|Manages| I[User Input & History]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#ffc,stroke:#333,stroke-width:2px
    style D fill:#cfc,stroke:#333,stroke-width:2px
    style E fill:#ccf,stroke:#333,stroke-width:2px

VII. Integration Points

The various hook systems in src/hooks integrate with the rest of the codebase at different levels:

The src/hooks/index.ts file serves as the public API for many of these components, re-exporting key classes, functions, and types for easier consumption throughout the application.