Hook-System: Der reale Validierungsprozess

Die vollständige Architektur des Claude Code Hook-Systems als TypeScript-Definition. Jedes Event, jedes Modul, jeder Datenfluss - dokumentiert und verifizierbar.

TypeScript Interface Definition

Das Hook-System besteht aus Events, Modulen und einem Bootstrap-Prozess. Die folgende TypeScript-Definition bildet die reale Implementierung aus hooks-config.json und bootstrap.py ab.

claude-hook-system.types.ts

/**
 * Claude Code Hook System - Type Definitions
 *
 * Bildet die reale Implementierung aus:
 * - /var/www/tools/ki-protokoll/claude-hook/hooks-config.json
 * - /var/www/tools/ki-protokoll/claude-hook/bootstrap.py
 *
 * Stand: = date('Y-m-d') ?
 */

// ============================================================================
// CORE TYPES
// ============================================================================

type HookEvent =
  | 'SessionStart'      // Session beginnt
  | 'UserPromptSubmit'  // User sendet Prompt
  | 'PreToolUse'        // VOR Tool-Ausführung (kann blockieren)
  | 'PostToolUse'       // NACH Tool-Ausführung
  | 'Stop'              // Claude stoppt
  | 'SubagentStop'      // Subagent stoppt
  | 'SessionEnd'        // Session endet
  | 'Notification'      // System-Benachrichtigung
  | 'PermissionRequest' // Permission angefragt
  | 'PreCompact';       // Vor Context-Komprimierung

type ToolName = 'Read' | 'Edit' | 'Write' | 'Bash' | 'Glob' | 'Grep' | 'Task';

type Severity = 'critical' | 'major' | 'minor' | 'info';

type RuleType = 'forbidden' | 'required' | 'warning';

type HookResult = {
  status: 'continue' | 'block';
  message?: string;
  violations?: Violation[];
};

interface Violation {
  rule_id: string;
  contract_key: string;
  severity: Severity;
  line?: number;
  message: string;
  fix_suggestion?: string;
}

// ============================================================================
// MODULE CONFIGURATION
// ============================================================================

interface HookModule {
  name: string;
  enabled: boolean;
  matcher?: RegExp;  // z.B. /^(Edit|Write)$/ für Tool-Filter
}

interface HooksConfig {
  version: string;
  modules: Record<HookEvent, HookModule[]>;
  module_paths: Record<string, string>;
}

// ============================================================================
// REALE KONFIGURATION (aus hooks-config.json)
// ============================================================================

const HOOK_SYSTEM: HooksConfig = {
  version: "1.0",

  modules: {
    // ========================================================================
    // STUFE 0: SESSION INITIALISIERUNG
    // ========================================================================
    SessionStart: [
      { name: "log_to_db", enabled: true },
      { name: "contract_loader", enabled: true },      // Lädt Contracts
      { name: "db_manager_info", enabled: true },      // DB-Tool Hinweise
      { name: "qdrant_manager_info", enabled: true },  // Qdrant-Tool Hinweise
      { name: "http_tools_info", enabled: true },      // HTTP-Tool Hinweise
      { name: "gate_status", enabled: true },          // Gate-Status
    ],

    // ========================================================================
    // STUFE 1a: PROAKTIVE GUIDANCE (Prompt-Analyse)
    // ========================================================================
    UserPromptSubmit: [
      { name: "log_to_db", enabled: true },
      { name: "text_contract_pre", enabled: true },    // Text-Validierung
      { name: "contract_guidance", enabled: true },    // Keyword → Contract
      { name: "cq_guidance", enabled: true },          // Code-Quality Hints
    ],

    // ========================================================================
    // STUFE 1b + 2: PRE-VALIDATION (vor Tool-Ausführung)
    // ========================================================================
    PreToolUse: [
      { name: "log_to_db", enabled: true },

      // STUFE 1b: Read-Guidance (Analytics-basiert)
      { name: "contract_read_guidance", enabled: true,
        matcher: /^Read$/ },

      // STUFE 2: Edit/Write Validation (kann BLOCKIEREN)
      { name: "docs_guardrail", enabled: true,         // Blockiert /docs/*.md
        matcher: /^(Edit|Write)$/ },
      { name: "state_write_guard", enabled: true,      // State-Protection
        matcher: /^(Edit|Write)$/ },
      { name: "doku_awareness", enabled: true,         // Zeigt Projekt-Doku
        matcher: /^(Edit|Write)$/ },
      { name: "contract_validator", enabled: true,     // CONTRACT VALIDATION
        matcher: /^(Edit|Write)$/ },
      { name: "quality_gate", enabled: true,           // Quality-Gate
        matcher: /^(Edit|Write)$/ },
      { name: "sql_injection_blocker", enabled: true,  // SQL-Injection Check
        matcher: /^(Edit|Write)$/ },
      { name: "js_eval_blocker", enabled: true,        // JS eval() Check
        matcher: /^(Edit|Write)$/ },
      { name: "file_backup", enabled: true,            // Backup vor Änderung
        matcher: /^(Edit|Write)$/ },

      // STUFE 2: Bash Validation (CLI-Enforcement)
      { name: "block_direct_db", enabled: true,        // Blockiert mysql CLI
        matcher: /^Bash$/ },
      { name: "block_direct_qdrant", enabled: true,    // Blockiert curl :6333
        matcher: /^Bash$/ },
      { name: "block_direct_http", enabled: true,      // Blockiert curl/wget
        matcher: /^Bash$/ },
      { name: "block_file_editing", enabled: true,     // Blockiert sed/awk
        matcher: /^Bash$/ },
      { name: "cli_help_enforcer", enabled: true,      // Erzwingt --help
        matcher: /^Bash$/ },
      { name: "bash_php_validator", enabled: true,     // PHP-Syntax Check
        matcher: /^Bash$/ },
    ],

    // ========================================================================
    // STUFE 3: POST-PROCESSING (nach Tool-Ausführung)
    // ========================================================================
    PostToolUse: [
      { name: "log_to_db", enabled: true },

      // Edit/Write Post-Processing
      { name: "cq_validator", enabled: true,           // CQ-Nachvalidierung
        matcher: /^(Edit|Write)$/ },
      { name: "quality_validator", enabled: true,      // Quality-Check
        matcher: /^(Edit|Write)$/ },
      { name: "text_contract_post", enabled: true,     // Text-Validierung
        matcher: /^(Edit|Write)$/ },
      { name: "fix_permissions", enabled: true,        // www-data:www-data
        matcher: /^(Edit|Write)$/ },
      { name: "doku_reminder", enabled: true,          // Doku-Update Reminder
        matcher: /^(Edit|Write)$/ },
      { name: "code_analyzer", enabled: true,          // Code-Entity Extract
        matcher: /^(Edit|Write)$/ },
      { name: "complexity_warning", enabled: true,     // Komplexitäts-Warnung
        matcher: /^(Edit|Write)$/ },
      { name: "todo_counter", enabled: true,           // TODO-Zähler
        matcher: /^(Edit|Write)$/ },
      { name: "python_ast_validator", enabled: true,   // Python AST Check
        matcher: /^(Edit|Write)$/ },

      // Bash Post-Processing
      { name: "gate_status", enabled: true,
        matcher: /^Bash$/ },
      { name: "permission_guard", enabled: true,
        matcher: /^Bash$/ },
    ],

    // ========================================================================
    // LIFECYCLE EVENTS
    // ========================================================================
    Stop: [
      { name: "log_to_db", enabled: true },
      { name: "task_reminder", enabled: true },        // Offene Tasks
    ],

    SubagentStop: [
      { name: "log_to_db", enabled: true },
    ],

    SessionEnd: [
      { name: "log_to_db", enabled: true },
    ],

    Notification: [
      { name: "log_to_db", enabled: true },
    ],

    PermissionRequest: [
      { name: "log_to_db", enabled: true },
    ],

    PreCompact: [
      { name: "log_to_db", enabled: true },
    ],
  },

  module_paths: {
    // Alle Module in /var/www/tools/ki-protokoll/claude-hook/modules/
    log_to_db: "modules/log_to_db.py",
    contract_loader: "modules/contract_loader.py",
    contract_validator: "modules/contract_validator.py",
    contract_guidance: "modules/contract_guidance.py",
    contract_read_guidance: "modules/contract_read_guidance.py",
    // ... 30+ weitere Module
  }
};

// ============================================================================
// BOOTSTRAP PROCESS (aus bootstrap.py)
// ============================================================================

async function handleHookEvent(
  event: HookEvent,
  toolName?: ToolName,
  payload?: unknown
): Promise<HookResult> {

  const modules = HOOK_SYSTEM.modules[event];
  const results: HookResult[] = [];

  for (const module of modules) {
    // Skip disabled modules
    if (!module.enabled) continue;

    // Check matcher (Tool-Filter)
    if (module.matcher && toolName && !module.matcher.test(toolName)) {
      continue;
    }

    // Execute module (subprocess mit 30s timeout)
    const result = await executeModule(module.name, event, payload);
    results.push(result);

    // BLOCK stops processing immediately
    if (result.status === 'block') {
      return {
        status: 'block',
        message: result.message,
        violations: result.violations
      };
    }
  }

  return { status: 'continue' };
}

// ============================================================================
// CONTRACT VALIDATION FLOW
// ============================================================================

interface ContractRule {
  id: number;
  contract_id: number;
  rule_id: string;
  rule_type: RuleType;
  pattern: string;
  pattern_type: 'regex' | 'contains' | 'not_contains' | 'exact';
  severity: Severity;
  message: string;
  fix_suggestion?: string;
  applies_to_extensions: string[];  // ["php", "js", "py"]
  is_active: boolean;
}

function validateCode(
  code: string,
  filePath: string,
  rules: ContractRule[]
): Violation[] {

  const violations: Violation[] = [];
  const extension = filePath.split('.').pop() || '';

  for (const rule of rules) {
    // Skip inactive rules
    if (!rule.is_active) continue;

    // Check file extension match
    if (!rule.applies_to_extensions.includes(extension)) continue;

    const matches = checkPattern(code, rule);

    if (rule.rule_type === 'forbidden' && matches) {
      violations.push({
        rule_id: rule.rule_id,
        contract_key: `contract-${rule.contract_id}`,
        severity: rule.severity,
        message: rule.message,
        fix_suggestion: rule.fix_suggestion
      });
    }

    if (rule.rule_type === 'required' && !matches) {
      violations.push({
        rule_id: rule.rule_id,
        contract_key: `contract-${rule.contract_id}`,
        severity: rule.severity,
        message: `Required pattern missing: ${rule.message}`,
        fix_suggestion: rule.fix_suggestion
      });
    }
  }

  return violations;
}

// ============================================================================
// SEVERITY → ACTION MAPPING
// ============================================================================

function determineAction(violations: Violation[]): HookResult {
  const hasCritical = violations.some(v => v.severity === 'critical');

  if (hasCritical) {
    return {
      status: 'block',  // Code wird NICHT geschrieben
      message: formatViolations(violations),
      violations
    };
  }

  // major/minor/info: Warnung, aber kein Block
  return {
    status: 'continue',
    message: formatViolations(violations),
    violations
  };
}

// ============================================================================
// STATISTIK (aus DB)
// ============================================================================

const CURRENT_STATS = {
  contracts: 22,
  rules: 319,
  critical_rules: 93,
  modules: 36,
  events: 10
};

export {
  HOOK_SYSTEM,
  handleHookEvent,
  validateCode,
  determineAction,
  CURRENT_STATS
};

Prozess-Ablauf als ASCII-Diagramm

Der vollständige Datenfluss durch alle Hook-Events:

hook-flow --complete

╔═══════════════════════════════════════════════════════════════════════════════╗
║                    CLAUDE CODE HOOK SYSTEM - VOLLSTÄNDIGER PROZESS              ║
║                         36 Module • 10 Events • 319 Rules                       ║
╚═══════════════════════════════════════════════════════════════════════════════╝

                              ┌─────────────────┐
                              │  SessionStart   │
                              └────────┬────────┘
                                       │
            ┌──────────────────────────┼──────────────────────────┐
            ▼                          ▼                          ▼
   contract_loader            db_manager_info           gate_status
   qdrant_manager_info        http_tools_info
                                       │
                                       ▼
                            ┌─────────────────────┐
                            │  UserPromptSubmit   │
                            │  "Erstelle SQL..."  │
                            └──────────┬──────────┘
                                       │
            ┌──────────────────────────┼──────────────────────────┐
            ▼                          ▼                          ▼
   text_contract_pre        contract_guidance          cq_guidance
   Text-Validierung         Keyword → Contract         CQ-Hinweise
                                       │
                                       ▼
                              Claude verarbeitet...
                                       │
                     ┌─────────────────┴─────────────────┐
                     ▼                                   ▼
           ┌─────────────────┐               ┌─────────────────┐
           │  PreToolUse     │               │  PreToolUse     │
           │  Read           │               │  Edit/Write     │
           └────────┬────────┘               └────────┬────────┘
                    │                                   │
                    ▼                    ┌──────────────┴──────────────┐
        contract_read_guidance        │                             │
        Analytics: Top-Violations     ▼                             ▼
                    │         ┌───────────────────┐   ┌───────────────────┐
                    │         │ Security Guards   │   │ Contract Validator│
                    │         │ docs_guardrail    │   │ 319 Rules         │
                    │         │ state_write_guard │   │ 22 Contracts      │
                    │         │ sql_injection_*   │   │                   │
                    │         │ js_eval_blocker   │   │ CRITICAL → BLOCK  │
                    │         └───────────────────┘   │ MAJOR → WARN      │
                    │                    │              │ MINOR → INFO      │
                    │                    │              └─────────┬─────────┘
                    │                    │                        │
                    │                    └────────────┬───────────┘
                    │                                 │
                    │                    ┌────────────┴────────────┐
                    │                    │                         │
                    │                    ▼                         ▼
                    │              ╔═══════════╗           ╔═══════════╗
                    │              ║   BLOCK   ║           ║   PASS    ║
                    │              ║ Code NOT  ║           ║ Code wird ║
                    │              ║ written   ║           ║ written   ║
                    │              ╚═════╤═════╝           ╚═════╤═════╝
                    │                    │                         │
                    │                    │                         ▼
                    │                    │               ┌─────────────────┐
                    │                    │               │  PostToolUse    │
                    │                    │               │  Edit/Write     │
                    │                    │               └────────┬────────┘
                    │                    │                         │
                    │                    │     ┌───────────────────┼───────────────────┐
                    │                    │     ▼                   ▼                   ▼
                    │                    │ fix_permissions    code_analyzer     doku_reminder
                    │                    │ quality_validator  complexity_warn   todo_counter
                    │                    │ cq_validator       python_ast_*      text_contract_post
                    │                    │                         │
                    │                    └─────────────────────────┤
                    │                                              │
                    └──────────────────────────────────────────────┤
                                                                   │
                                                                   ▼
                                                    ┌─────────────────────┐
                                                    │    Feedback          │
                                                    │ an Claude Code      │
                                                    └─────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                          BASH-SPEZIFISCHE VALIDIERUNG                           │
├─────────────────────────────────────────────────────────────────────────────────┤
│                                                                                 │
│  PreToolUse (Bash)                      PostToolUse (Bash)                    │
│  ├─ block_direct_db      BLOCK          ├─ gate_status                         │
│  ├─ block_direct_qdrant  BLOCK          └─ permission_guard                    │
│  ├─ block_direct_http    BLOCK                                                  │
│  ├─ block_file_editing   BLOCK          Erzwingt CLI-Tools statt:             │
│  ├─ cli_help_enforcer    WARN           • mysql/mariadb → db_sql               │
│  └─ bash_php_validator   WARN           • curl/wget → http/download            │
│                                         • sed/awk/cat → Edit/Read              │
│                                                                                 │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                           LIFECYCLE EVENTS                                      │
├─────────────────────────────────────────────────────────────────────────────────┤
│  Stop            → task_reminder (zeigt offene Tasks)                          │
│  SubagentStop    → log_to_db                                                   │
│  SessionEnd      → log_to_db                                                   │
│  PreCompact      → log_to_db (vor Context-Komprimierung)                       │
└─────────────────────────────────────────────────────────────────────────────────┘

Modul-Übersicht

Alle 36 aktiven Module gruppiert nach Funktion:

hook-modules --list-all

LOGGING (1)
  log_to_db              Alle Events → ki_protokoll.hook_communications

CONTRACT SYSTEM (5)
  contract_loader        SessionStart: Lädt Contracts in Session-Context
  contract_guidance      UserPromptSubmit: Keyword → Contract-Regeln
  contract_read_guidance PreToolUse/Read: Analytics-basierte Guidance
  contract_validator     PreToolUse/Edit: HAUPT-VALIDATOR (kann BLOCKIEREN)
  text_contract_pre/post Text-Content Validierung

SECURITY GUARDS (8)
  sql_injection_blocker  PreToolUse/Edit: SQL-Injection Detection
  js_eval_blocker        PreToolUse/Edit: JS eval()/Function() Detection
  block_direct_db        PreToolUse/Bash: Blockiert mysql/mariadb CLI
  block_direct_qdrant    PreToolUse/Bash: Blockiert curl zu :6333
  block_direct_http      PreToolUse/Bash: Blockiert curl/wget
  block_file_editing     PreToolUse/Bash: Blockiert sed/awk/cat
  docs_guardrail         PreToolUse/Edit: Blockiert /docs/*.md
  state_write_guard      PreToolUse/Edit: State-File Protection

QUALITY ASSURANCE (7)
  quality_gate           PreToolUse/Edit: Pre-Write Quality Check
  quality_validator      PostToolUse/Edit: Post-Write Quality Check
  cq_guidance            UserPromptSubmit: Code-Quality Hints
  cq_validator           PostToolUse/Edit: CQ-Nachvalidierung
  complexity_warning     PostToolUse/Edit: Cyclomatic Complexity
  python_ast_validator   PostToolUse/Edit: Python AST-Analyse
  bash_php_validator     PreToolUse/Bash: PHP-Syntax in Shell

DOCUMENTATION (3)
  doku_awareness         PreToolUse/Edit: Zeigt relevante Projekt-Doku
  doku_reminder          PostToolUse/Edit: Erinnert an Doku-Updates
  cli_help_enforcer      PreToolUse/Bash: Erzwingt --help vor CLI-Nutzung

CODE ANALYSIS (2)
  code_analyzer          PostToolUse/Edit: Extrahiert Code-Entities
  todo_counter           PostToolUse/Edit: Zählt TODO/FIXME

FILE OPERATIONS (2)
  file_backup            PreToolUse/Edit: Backup vor Änderung
  fix_permissions        PostToolUse/Edit: chown www-data:www-data

SYSTEM INFO (4)
  db_manager_info        SessionStart: db_sql Tool-Hinweise
  qdrant_manager_info    SessionStart: db_qdrant Tool-Hinweise
  http_tools_info        SessionStart: http/download Tool-Hinweise
  gate_status            SessionStart + PostToolUse/Bash: Gate-Anzeige

LIFECYCLE (3)
  task_loader            SessionStart: Lädt aktive Tasks (disabled)
  task_reminder          Stop: Zeigt offene Tasks
  permission_guard       PostToolUse/Bash: Permission-Überwachung