diff --git a/src/core/hooks/HookDiscoveryCache.ts b/src/core/hooks/HookDiscoveryCache.ts index fe6fe043..be3169c9 100644 --- a/src/core/hooks/HookDiscoveryCache.ts +++ b/src/core/hooks/HookDiscoveryCache.ts @@ -1,3 +1,4 @@ +import { telemetryService } from "../../services/telemetry" import { getAllHooksDirs } from "../storage/disk" import { HookFactory, Hooks } from "./hook-factory" @@ -56,8 +57,8 @@ export class HookDiscoveryCache { // Directories we've tried to watch (even if watcher creation failed) private watchedDirs = new Set() - // Currently scanning (to prevent concurrent scans) - private scanning = new Set() + // Currently scanning promises (to prevent concurrent scans) + private scanningPromises = new Map>() // For disposal private context: ExtensionContext | null = null @@ -105,60 +106,95 @@ export class HookDiscoveryCache { this.log(`Getting hooks for ${hookName}`) const cached = this.cache.get(hookName) - if (cached) { + const cacheHit = cached !== undefined + + let scripts: string[] + let initiatedScan = false // Track if this caller initiated the scan + + if (cacheHit) { this.log(`Cache hit for ${hookName}: ${cached.scriptPaths.length} scripts`) - return cached.scriptPaths + scripts = cached.scriptPaths + } else { + this.log(`Cache miss for ${hookName}, scanning...`) + + // Check if scan is already in progress + const existingPromise = this.scanningPromises.get(hookName) + if (existingPromise) { + // Another caller is already scanning, reuse their promise + this.log(`Reusing existing scan for ${hookName}`) + scripts = await existingPromise + } else { + // This caller initiates the scan + initiatedScan = true + scripts = await this.scan(hookName) + } } - this.log(`Cache miss for ${hookName}, scanning...`) - return this.scan(hookName) + // Only report telemetry if: + // 1. It was a cache hit, OR + // 2. This caller initiated the scan (not reusing another caller's promise) + if (cacheHit || initiatedScan) { + telemetryService.safeCapture( + () => telemetryService.captureHookCacheAccess(hookName, cacheHit), + "HookDiscoveryCache.get", + ) + } + + return scripts } /** * Scan for hook scripts and cache the result */ private async scan(hookName: HookName): Promise { - // Prevent concurrent scans of the same hook - if (this.scanning.has(hookName)) { - this.log(`Already scanning ${hookName}, waiting...`) - await new Promise((resolve) => setTimeout(resolve, 50)) - return this.get(hookName) + // Check if a scan is already in progress for this hook + const existingPromise = this.scanningPromises.get(hookName) + if (existingPromise) { + this.log(`Already scanning ${hookName}, waiting for existing scan...`) + return existingPromise } - this.scanning.add(hookName) + // Create a new scan promise + const scanPromise = (async () => { + try { + // Get all current hooks directories + const hooksDirs = await getAllHooksDirs() + this.log(`Scanning ${hooksDirs.length} directories for ${hookName}`) - try { - // Get all current hooks directories - const hooksDirs = await getAllHooksDirs() - this.log(`Scanning ${hooksDirs.length} directories for ${hookName}`) + // Ensure watchers are set up for each directory (lazy initialization) + for (const dir of hooksDirs) { + this.ensureWatcher(dir) + } - // Ensure watchers are set up for each directory (lazy initialization) - for (const dir of hooksDirs) { - this.ensureWatcher(dir) + // Scan each directory for this hook + const scriptPromises = hooksDirs.map((dir) => HookFactory.findHookInHooksDir(hookName, dir)) + + const results = await Promise.all(scriptPromises) + const scripts = results.filter((path): path is string => path !== undefined) + + this.log(`Found ${scripts.length} scripts for ${hookName}`) + + // Cache the result + this.cache.set(hookName, { + scriptPaths: scripts, + timestamp: Date.now(), + }) + + return scripts + } catch (error) { + console.error(`Error scanning for ${hookName} hooks:`, error) + // Return empty array on error - don't break the whole system + return [] + } finally { + // Remove from scanning promises map + this.scanningPromises.delete(hookName) } + })() - // Scan each directory for this hook - const scriptPromises = hooksDirs.map((dir) => HookFactory.findHookInHooksDir(hookName, dir)) + // Store the promise so concurrent calls can await it + this.scanningPromises.set(hookName, scanPromise) - const results = await Promise.all(scriptPromises) - const scripts = results.filter((path): path is string => path !== undefined) - - this.log(`Found ${scripts.length} scripts for ${hookName}`) - - // Cache the result - this.cache.set(hookName, { - scriptPaths: scripts, - timestamp: Date.now(), - }) - - return scripts - } catch (error) { - console.error(`Error scanning for ${hookName} hooks:`, error) - // Return empty array on error - don't break the whole system - return [] - } finally { - this.scanning.delete(hookName) - } + return scanPromise } /** diff --git a/src/core/hooks/hook-executor.ts b/src/core/hooks/hook-executor.ts index 24aef94b..2e074348 100644 --- a/src/core/hooks/hook-executor.ts +++ b/src/core/hooks/hook-executor.ts @@ -105,6 +105,8 @@ export async function executeHook(options: HookExecuti hookName, streamCallback, isCancellable ? abortController.signal : undefined, + taskId, + options.toolName, ) const result = await hook.run({ diff --git a/src/core/hooks/hook-factory.ts b/src/core/hooks/hook-factory.ts index c9c16ac9..3dabf98e 100644 --- a/src/core/hooks/hook-factory.ts +++ b/src/core/hooks/hook-factory.ts @@ -2,6 +2,7 @@ import fs from "fs/promises" import path from "path" import { version as clineVersion } from "../../../package.json" import { getDistinctId } from "../../services/logging/distinctId" +import { telemetryService } from "../../services/telemetry" import { HookInput, HookOutput, @@ -25,6 +26,9 @@ const HOOK_EXECUTION_TIMEOUT_MS = 30000 // Maximum size for context modification (to prevent prompt overflow) const MAX_CONTEXT_MODIFICATION_SIZE = 50000 // ~50KB +// Exit code indicating cancellation/interruption (Unix SIGINT convention: 128 + signal 2) +const EXIT_CODE_SIGINT = 130 + /** * Validates hook output JSON structure. * Ensures required fields are present and have correct types. @@ -233,6 +237,7 @@ export type HookStreamCallback = (line: string, stream: "stdout" | "stderr") => * - Parses JSON output from stdout, attempting to extract it even if mixed with debug output * - Truncates context modifications that exceed 50KB to prevent prompt overflow * - Handles both successful and failed executions gracefully + * - Emits per-hook telemetry with source attribution (global or workspace) * * Error handling: * - Treats hooks as "fail-open": only shouldContinue:false blocks tool execution @@ -245,13 +250,31 @@ class StdioHookRunner extends HookRunner { constructor( hookName: Name, public readonly scriptPath: string, + private readonly source: "global" | "workspace", private readonly streamCallback?: HookStreamCallback, private readonly abortSignal?: AbortSignal, + private readonly taskId?: string, + private readonly toolName?: string, ) { super(hookName) } override async [exec](input: HookInput): Promise { + const startTime = performance.now() + const taskId = this.taskId // Local const for type narrowing in closures + + // Capture telemetry at the start of individual hook execution + if (taskId) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "started", { + source: this.source, + toolName: this.toolName, + }), + "HookFactory.exec.started", + ) + } + // Check if already aborted before starting if (this.abortSignal?.aborted) { throw HookExecutionError.cancellation(this.scriptPath) @@ -398,6 +421,8 @@ class StdioHookRunner extends HookRunner { // If we have valid JSON, honor it regardless of exit code if (parsedOutput) { + const durationMs = performance.now() - startTime + // Log warning if non-zero exit but valid JSON (for developers) if (exitCode !== 0) { console.warn(`[Hook ${this.hookName}] Exited with code ${exitCode} but provided valid JSON response`) @@ -406,6 +431,39 @@ class StdioHookRunner extends HookRunner { } } + // Capture success/cancellation telemetry + if (taskId) { + if (parsedOutput.cancel) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "completed", { + source: this.source, + toolName: this.toolName, + durationMs, + exitCode: exitCode ?? EXIT_CODE_SIGINT, + cancelRequested: true, + contextModified: !!parsedOutput.contextModification, + contextSize: parsedOutput.contextModification?.length, + }), + "HookFactory.exec.completed.cancel", + ) + } else { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "completed", { + source: this.source, + toolName: this.toolName, + durationMs, + exitCode: exitCode ?? 0, + cancelRequested: false, + contextModified: !!parsedOutput.contextModification, + contextSize: parsedOutput.contextModification?.length, + }), + "HookFactory.exec.completed.success", + ) + } + } + return parsedOutput } @@ -413,6 +471,24 @@ class StdioHookRunner extends HookRunner { if (exitCode === 0) { // Hook succeeded but didn't provide JSON - allow execution (no cancellation) console.warn(`[Hook ${this.hookName}] Completed successfully but no JSON response found`) + const durationMs = performance.now() - startTime + + // Capture success telemetry even without JSON + if (taskId) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "completed", { + source: this.source, + toolName: this.toolName, + durationMs, + exitCode: 0, + cancelRequested: false, + contextModified: false, + }), + "HookFactory.exec.completed.noJson", + ) + } + return HookOutput.create({ cancel: false, }) @@ -421,8 +497,48 @@ class StdioHookRunner extends HookRunner { throw HookExecutionError.execution(this.scriptPath, exitCode ?? 1, stderr, this.hookName) } } catch (error) { + const durationMs = performance.now() - startTime + // If it's already a HookExecutionError, re-throw it if (HookExecutionError.isHookError(error)) { + // Capture failure telemetry based on error type + if (taskId) { + if (error.errorInfo.type === "cancellation") { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "cancelled", { + source: this.source, + toolName: this.toolName, + }), + "HookFactory.exec.error.cancellation", + ) + } else if (error.errorInfo.type === "timeout") { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "failed", { + source: this.source, + toolName: this.toolName, + durationMs, + errorType: "timeout", + errorMessage: error.message, + }), + "HookFactory.exec.error.timeout", + ) + } else { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "failed", { + source: this.source, + toolName: this.toolName, + durationMs, + exitCode: error.errorInfo.exitCode ?? 1, + errorType: error.errorInfo.type as "execution" | "timeout" | "validation", + errorMessage: error.message, + }), + "HookFactory.exec.error.failed", + ) + } + } throw error } @@ -432,15 +548,52 @@ class StdioHookRunner extends HookRunner { // Check for timeout if (error instanceof Error && error.message.includes("timed out")) { + if (taskId) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "failed", { + source: this.source, + toolName: this.toolName, + durationMs, + errorType: "timeout", + errorMessage: error.message, + }), + "HookFactory.exec.catch.timeout", + ) + } throw HookExecutionError.timeout(this.scriptPath, HOOK_EXECUTION_TIMEOUT_MS, stderr, this.hookName) } // Check for cancellation if (error instanceof Error && error.message.includes("cancelled")) { + if (taskId) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "cancelled", { + source: this.source, + toolName: this.toolName, + }), + "HookFactory.exec.catch.cancelled", + ) + } throw HookExecutionError.cancellation(this.scriptPath, this.hookName) } // Generic execution error - include hook name + if (taskId) { + telemetryService.safeCapture( + () => + telemetryService.captureHookExecution(taskId, this.hookName, "failed", { + source: this.source, + toolName: this.toolName, + durationMs, + exitCode: exitCode ?? 1, + errorType: "execution", + errorMessage: error instanceof Error ? error.message : String(error), + }), + "HookFactory.exec.catch.execution", + ) + } throw HookExecutionError.execution(this.scriptPath, exitCode ?? 1, stderr, this.hookName) } } @@ -546,8 +699,8 @@ export class HookFactory { /** * Create a hook runner without streaming support (backwards compatible) */ - async create(hookName: Name): Promise> { - return this.createWithStreaming(hookName) + async create(hookName: Name, taskId?: string, toolName?: string): Promise> { + return this.createWithStreaming(hookName, undefined, undefined, taskId, toolName) } /** @@ -566,24 +719,94 @@ export class HookFactory { * @param hookName The type of hook to create (e.g., "PreToolUse", "PostToolUse") * @param streamCallback Optional callback for real-time output streaming * @param abortSignal Optional signal to cancel hook execution + * @param taskId Optional task ID for telemetry context + * @param toolName Optional tool name for telemetry context * @returns A HookRunner that executes the hook(s), or NoOpRunner if none found */ async createWithStreaming( hookName: Name, streamCallback?: HookStreamCallback, abortSignal?: AbortSignal, + taskId?: string, + toolName?: string, ): Promise> { // Use cache for hook discovery instead of direct file system scan const { HookDiscoveryCache } = await import("./HookDiscoveryCache") const scripts = await HookDiscoveryCache.getInstance().get(hookName) - const runners = scripts.map((script) => new StdioHookRunner(hookName, script, streamCallback, abortSignal)) + // Fetch hooks dirs once for source determination and telemetry + const hooksDirs = await getAllHooksDirs() + + // Capture hook discovery telemetry + // Categorize scripts by location (global vs workspace) + const { globalCount, workspaceCount } = this.categorizeHookScripts(scripts, hooksDirs) + if (scripts.length > 0) { + telemetryService.safeCapture( + () => telemetryService.captureHookDiscovery(hookName, globalCount, workspaceCount), + "HookFactory.createWithStreaming.discovery", + ) + } + + // Create runners with source determination for each script + const runners = scripts.map((script) => { + const source = this.determineScriptSource(script, hooksDirs) + return new StdioHookRunner(hookName, script, source, streamCallback, abortSignal, taskId, toolName) + }) + if (runners.length === 0) { return new NoOpRunner(hookName) } return runners.length === 1 ? runners[0] : new CombinedHookRunner(hookName, runners) } + /** + * Checks if a hooks directory is a global hooks directory. + * Global hooks are located in paths containing "Cline/Hooks" or "cline/hooks". + */ + private static isGlobalHooksDir(dir: string): boolean { + return /[/\\][Cc]line[/\\][Hh]ooks/i.test(dir) + } + + /** + * Determines if a single script is from global or workspace location + */ + private determineScriptSource(scriptPath: string, hooksDirs: string[]): "global" | "workspace" { + const containingDir = hooksDirs.find((dir) => scriptPath.startsWith(dir)) + if (containingDir && HookFactory.isGlobalHooksDir(containingDir)) { + return "global" + } + return "workspace" // Default to workspace if uncertain + } + + /** + * Categorizes hook scripts by their location (global vs workspace). + * Global hooks are located in ~/Documents/Cline/Hooks/ + * Workspace hooks are located in workspace .clinerules/hooks/ directories + * + * @param scripts Array of hook script paths + * @param hooksDirs Array of hooks directories (passed to avoid redundant fetches) + * @returns Object with globalCount and workspaceCount + */ + private categorizeHookScripts(scripts: string[], hooksDirs: string[]): { globalCount: number; workspaceCount: number } { + if (scripts.length === 0) { + return { globalCount: 0, workspaceCount: 0 } + } + + let globalCount = 0 + let workspaceCount = 0 + + for (const script of scripts) { + const containingDir = hooksDirs.find((dir) => script.startsWith(dir)) + if (containingDir && HookFactory.isGlobalHooksDir(containingDir)) { + globalCount++ + } else { + workspaceCount++ + } + } + + return { globalCount, workspaceCount } + } + /** * @returns A list of paths to scripts for the given hook name. * Includes both global hooks (from ~/Documents/Cline/Hooks/) and workspace hooks diff --git a/src/services/telemetry/TelemetryService.ts b/src/services/telemetry/TelemetryService.ts index 15c97e80..eb3a0238 100644 --- a/src/services/telemetry/TelemetryService.ts +++ b/src/services/telemetry/TelemetryService.ts @@ -16,7 +16,7 @@ import { TelemetryProviderFactory } from "./TelemetryProviderFactory" * When adding a new category, add it both here and to the initial values in telemetryCategoryEnabled * Ensure `if (!this.isCategoryEnabled('')` is added to the capture method */ -type TelemetryCategory = "checkpoints" | "browser" | "focus_chain" | "dictation" | "subagents" +type TelemetryCategory = "checkpoints" | "browser" | "focus_chain" | "dictation" | "subagents" | "hooks" /** * Enum for terminal output failure reasons @@ -89,6 +89,7 @@ export class TelemetryService { ["dictation", true], // Dictation telemetry enabled ["focus_chain", true], // Focus Chain telemetry enabled ["subagents", true], // CLI Subagents telemetry enabled + ["hooks", true], // Hooks telemetry enabled ]) private userId?: string @@ -126,6 +127,14 @@ export class TelemetryService { DURATION_SECONDS: "cline.api.duration.seconds", THROUGHPUT_TOKENS_PER_SECOND: "cline.api.throughput.tokens_per_second", }, + HOOKS: { + EXECUTIONS_TOTAL: "cline.hooks.executions.total", + DURATION_SECONDS: "cline.hooks.duration.seconds", + FAILURES_TOTAL: "cline.hooks.failures.total", + CANCELLATIONS_TOTAL: "cline.hooks.cancellations.total", + CONTEXT_MODIFICATIONS_TOTAL: "cline.hooks.context_modifications.total", + CACHE_ACCESSES_TOTAL: "cline.hooks.cache.accesses.total", + }, } // Event constants for tracking user interactions and system events private static readonly EVENTS = { @@ -267,6 +276,19 @@ export class TelemetryService { // Tracks when the rules menu button is clicked RULES_MENU_OPENED: "ui.rules_menu_opened", }, + // Hooks-related events for tracking hook execution + HOOKS: { + // Tracks when hooks feature is enabled + ENABLED: "hooks.enabled", + // Tracks when hooks feature is disabled + DISABLED: "hooks.disabled", + // Tracks when a hook requests task cancellation + CANCEL_REQUESTED: "hooks.cancel_requested", + // Tracks when a hook modifies context + CONTEXT_MODIFIED: "hooks.context_modified", + // Tracks when hook discovery completes + DISCOVERY_COMPLETED: "hooks.discovery_completed", + }, } public static async create(): Promise { @@ -1926,6 +1948,171 @@ export class TelemetryService { }) } + // Hooks telemetry methods + + /** + * Records hook discovery cache access (hit or miss) + * @param hookName The type of hook being accessed + * @param cacheHit Whether the cache had the result (true) or miss (false) + */ + public captureHookCacheAccess(hookName: string, cacheHit: boolean) { + if (!this.isCategoryEnabled("hooks")) { + return + } + + // Record cache access counter with hit/miss attribute + // This allows deriving hit rate: hits / (hits + misses) + this.recordCounter(TelemetryService.METRICS.HOOKS.CACHE_ACCESSES_TOTAL, 1, { + hookName, + cacheHit: cacheHit.toString(), + }) + } + + // Simplified Hook Telemetry API (following MCP pattern) + + /** + * Records hook execution events with a unified status-based approach. + * This is the simplified API that consolidates multiple hook execution methods. + * + * @param ulid Task identifier + * @param hookName Type of hook (PreToolUse, PostToolUse, etc.) + * @param status Current execution status + * @param metadata Optional execution metadata + */ + public captureHookExecution( + ulid: string, + hookName: string, + status: "started" | "completed" | "failed" | "cancelled", + metadata?: { + source?: "global" | "workspace" + toolName?: string + durationMs?: number + exitCode?: number + errorType?: "timeout" | "execution" | "validation" + errorMessage?: string + cancelRequested?: boolean + contextModified?: boolean + contextSize?: number + }, + ) { + if (!this.isCategoryEnabled("hooks")) { + return + } + + const properties: TelemetryProperties = { + ulid, + hookName, + status, + timestamp: new Date().toISOString(), + ...(metadata?.source && { source: metadata.source }), + ...(metadata?.toolName && { toolName: metadata.toolName }), + ...(metadata?.durationMs !== undefined && { durationMs: metadata.durationMs }), + ...(metadata?.exitCode !== undefined && { exitCode: metadata.exitCode }), + ...(metadata?.errorType && { errorType: metadata.errorType }), + ...(metadata?.errorMessage && { + errorMessage: metadata.errorMessage.substring(0, MAX_ERROR_MESSAGE_LENGTH), + }), + ...(metadata?.cancelRequested !== undefined && { cancelRequested: metadata.cancelRequested }), + ...(metadata?.contextModified !== undefined && { contextModified: metadata.contextModified }), + ...(metadata?.contextSize !== undefined && { contextSize: metadata.contextSize }), + } + + // Single event for all statuses + this.capture({ + event: "hooks.execution", + properties, + }) + + // Record metrics based on status + const hookAttributes = { + ulid, + hookName, + status, + ...(metadata?.source && { source: metadata.source }), + ...(metadata?.toolName && { toolName: metadata.toolName }), + } + + if (status === "started") { + this.recordCounter(TelemetryService.METRICS.HOOKS.EXECUTIONS_TOTAL, 1, hookAttributes) + } else if (status === "completed") { + if (metadata?.durationMs !== undefined) { + this.recordHistogram(TelemetryService.METRICS.HOOKS.DURATION_SECONDS, metadata.durationMs / 1000, hookAttributes) + } + if (metadata?.cancelRequested) { + this.recordCounter(TelemetryService.METRICS.HOOKS.CANCELLATIONS_TOTAL, 1, hookAttributes) + } + if (metadata?.contextModified) { + this.recordCounter(TelemetryService.METRICS.HOOKS.CONTEXT_MODIFICATIONS_TOTAL, 1, hookAttributes) + } + } else if (status === "failed") { + this.recordCounter(TelemetryService.METRICS.HOOKS.FAILURES_TOTAL, 1, { + ...hookAttributes, + errorType: metadata?.errorType || "unknown", + }) + } else if (status === "cancelled") { + this.recordCounter(TelemetryService.METRICS.HOOKS.CANCELLATIONS_TOTAL, 1, hookAttributes) + } + } + + /** + * Records hook discovery results (simplified version). + * + * @param hookName The type of hook being discovered + * @param globalCount Number of global hooks found + * @param workspaceCount Number of workspace-specific hooks found + */ + public captureHookDiscovery(hookName: string, globalCount: number, workspaceCount: number) { + if (!this.isCategoryEnabled("hooks")) { + return + } + + this.capture({ + event: TelemetryService.EVENTS.HOOKS.DISCOVERY_COMPLETED, + properties: { + hookName, + globalCount, + workspaceCount, + totalCount: globalCount + workspaceCount, + timestamp: new Date().toISOString(), + }, + }) + } + + /** + * Safely executes a telemetry call with error protection. + * + * Use for critical execution paths where telemetry errors could break functionality: + * - Hook execution (during tool execution) + * - Browser automation (during active sessions) + * - Auth flows, task initialization + * - MCP server operations + * + * Not needed for non-critical, fire-and-forget events: + * - UI events (clicks, navigation) + * - Post-completion events + * - Background operations + * + * This wrapper protects against both pre-provider errors (parameter construction, + * property access, calculations) and provider-level errors (network, API failures). + * + * @param telemetryFn The telemetry function to execute + * @param context Optional context string for debugging (e.g., "HookFactory.exec") + * + * @example + * telemetryService.safeCapture( + * () => telemetryService.captureHookExecution(taskId, hookName, "started", {...}), + * 'HookFactory.exec.started' + * ) + */ + public safeCapture(telemetryFn: () => void, context?: string): void { + try { + telemetryFn() + } catch (error) { + const contextStr = context ? ` [Context: ${context}]` : "" + console.error(`[Telemetry] Failed to capture telemetry${contextStr}:`, error) + } + } + /** * Clean up resources when the service is disposed */