UNPKG

claude-git-hooks

Version:

Git hooks with Claude CLI for code analysis and automatic commit messages

937 lines (723 loc) β€’ 64.6 kB
# Changelog Todos los cambios notables en este proyecto se documentarΓ‘n en este archivo. El formato estΓ‘ basado en [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), y este proyecto adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [2.9.1] - 2025-12-30 ### πŸ› Fixed - **Template path mismatch after v2.8.0 migration** - Fixed critical bug where templates were not found after config migration (#51) - **What was broken**: After v2.8.0 moved templates from `.claude/` to `.claude/prompts/`, the code still looked in the old location - **Root cause**: `prompt-builder.js` and `resolution-prompt.js` had hardcoded `.claude/` paths instead of `.claude/prompts/` - **Symptom**: `ENOENT: no such file or directory` errors for `CLAUDE_ANALYSIS_PROMPT.md` and `CLAUDE_RESOLUTION_PROMPT.md` - **Fix**: Updated default paths in template loading functions to `.claude/prompts/` - **Files changed**: - `lib/utils/prompt-builder.js:45,133,223,234-235,244` - Updated `loadTemplate`, `loadPrompt`, `buildAnalysisPrompt` defaults - `lib/utils/resolution-prompt.js:183` - Updated `generateResolutionPrompt` template path - **Impact**: Pre-commit analysis and resolution prompt generation now work correctly after v2.8.0+ installation ### 🎯 User Experience - **Before**: Users upgrading from v2.6.x to v2.8.0+ experienced "Template not found" errors even after successful installation - **After**: Templates are found in correct `.claude/prompts/` directory as intended by v2.8.0 changes ## [2.9.0] - 2025-12-26 ### ✨ Added - **Local telemetry system with per-retry tracking** - Enabled by default for debugging JSON parsing failures (#50) - **What it does**: Tracks JSON parsing failures and successes with full context, recording EVERY retry attempt individually - **Key features**: - **Granular tracking**: Records each retry attempt separately (not just final result) - **Unique IDs**: Each event has unique ID (timestamp-counter-random) for deduplication - **Success flag**: Boolean indicating whether attempt succeeded (true) or failed (false) - **Retry metadata**: `retryAttempt` (0-3) and `totalRetries` (max configured) - **Error types**: Tracks EXECUTION_ERROR, JSON_PARSE_ERROR, etc. - **Hook coverage**: pre-commit, prepare-commit-msg, analyze-diff, create-pr - **Privacy-first**: Local-only (`.claude/telemetry/`), no data leaves user's machine, no external transmission - **Storage**: JSON lines format with automatic rotation (keeps last 30 days) - **CLI commands**: - `claude-hooks telemetry show` - Display statistics (failure rate, failures by batch size/model/hook, retry patterns) - `claude-hooks telemetry clear` - Reset telemetry data - **Enabled by default**: To disable, add `"system": { "telemetry": false }` to `.claude/config.json` - **Files added**: - `lib/utils/telemetry.js` - Telemetry collection with ID generation, retry tracking, and statistics - **Files changed**: - `lib/utils/claude-client.js:678-780,788-798` - Modified withRetry() to record telemetry on each attempt - `lib/utils/claude-client.js:609-618,845-856` - Removed duplicate telemetry recordings - `lib/hooks/pre-commit.js` - Pass telemetry context for analysis - `lib/hooks/prepare-commit-msg.js` - Pass telemetry context for commit messages - `lib/config.js` - Add telemetry config option (default: true) - `bin/claude-hooks:1076-1091,1354-1366` - Add telemetry context to analyze-diff and create-pr - `bin/claude-hooks` - Add telemetry CLI commands - **Impact**: Enables diagnosis of retry patterns, identifies which retry attempts succeed, tracks transient vs persistent errors, helps optimize batch sizes and models ## [2.8.0] - 2025-12-24 ### 🎨 Changed - **Simplified configuration format** - New v2.8.0 config structure reduces redundancy and improves maintainability - **What changed**: Config now uses `version` field and `overrides` structure, 21 parameters moved to hardcoded defaults - **New format**: `{ "version": "2.8.0", "preset": "backend", "overrides": {...} }` - **Old format**: `{ "preset": "backend", "analysis": {...}, "subagents": {...}, ... }` (20+ top-level keys) - **User-configurable** (5 params): `preset`, `github.pr.*`, `subagents.batchSize` - **Hardcoded** (21 params): `analysis.*` (maxFileSize, maxFiles, timeout), `commitMessage.*`, `templates.*`, etc. - **Advanced** (3 params): `analysis.ignoreExtensions`, `commitMessage.taskIdPattern`, `subagents.model` - **Files changed**: - `lib/config.js:1-280` - Split into HARDCODED and defaults, added legacy format detection - `templates/config.example.json` - New simplified format with examples - `templates/config.advanced.example.json` - Advanced parameters with documentation - `bin/claude-hooks:483-570` - Auto-migration during install - **Impact**: Cleaner config files, sensible defaults work for 99% of users - **Automatic config migration** - Legacy configs auto-migrate during installation with backup - **What changed**: `claude-hooks install` detects legacy format and migrates automatically - **Migration process**: Backup to `.claude/config_old/`, extract allowed params, create v2.8.0 config - **Preserved settings**: `github.pr.*`, `subagents.batchSize`, and advanced params (with warnings) - **Files changed**: - `bin/claude-hooks:510-530,1942-2115` - Auto-migration in install, new `migrate-config` command - **Impact**: Seamless upgrade path, settings preserved, zero manual work - **Organized prompt templates** - All .md files moved to `.claude/prompts/` subdirectory - **What changed**: Installation creates `.claude/prompts/` and places markdown templates there - **Old location**: `.claude/CLAUDE_ANALYSIS_PROMPT.md`, `.claude/CLAUDE_PRE_COMMIT.md`, etc. - **New location**: `.claude/prompts/CLAUDE_ANALYSIS_PROMPT.md`, `.claude/prompts/CLAUDE_PRE_COMMIT.md`, etc. - **Auto-cleanup**: Old .md files in `.claude/` root are automatically removed during installation - **Files changed**: - `bin/claude-hooks:401-457` - Creates prompts directory, moves .md files, cleans up old files - `lib/config.js:57` - Updated `templates.baseDir` to `.claude/prompts` - **Impact**: Cleaner `.claude/` directory structure, prompts separated from config files - **Parallel analysis enabled by default** - Subagents now hardcoded to enabled (was opt-in) - **What changed**: `subagents.enabled` moved from user config to hardcoded `true` - **Why**: Faster analysis is universally beneficial, no reason to disable - **Files changed**: `lib/config.js:52-54` - Hardcoded `enabled: true`, `model: 'haiku'`, `batchSize: 3` - **Impact**: All users get faster analysis out-of-box (4x speedup on 3+ files) ### ✨ Added - **Config example files** - Split documentation into simple and advanced examples - `templates/config.example.json` - Minimal config (99% of users) with inline examples - `templates/config.advanced.example.json` - Advanced parameters with full documentation - Installation copies both to `.claude/config_example/` for reference - **Impact**: Clear guidance for common use cases, power users can tinker safely - **Manual config migration command** - New `claude-hooks migrate-config` for manual upgrades - Checks config version, creates backup in `.claude/config_old/` - Extracts allowed parameters, warns about advanced params - Shows diff preview before writing - **Impact**: Users can migrate at their pace, review changes before applying ### πŸ”§ Fixed - **Preset name now correctly displayed in hooks** - Fixed config loader not including preset name in final config - **What was broken**: Hooks always showed "Default (General-purpose)" preset regardless of actual preset configured - **Root cause**: Config loader extracted `presetName` but never added it to the final merged config object - **Fix**: Add `preset` field to final config object after merge operations - **Files changed**: `lib/config.js:181-184` - **Impact**: Hooks now correctly display configured preset (e.g., "AI", "Backend", "Frontend") - **Example configs no longer clutter .claude/** - Example files only exist in `.claude/config_example/` - **What was broken**: Installation copied `*example.json` to both `.claude/` and `.claude/config_example/` - **Fix**: Filter `*example.json` during template copy, only place in `config_example/` - **Files changed**: `bin/claude-hooks:410-415,498-507` - **Impact**: Cleaner `.claude/` directory without redundant example files ### ⚠️ Breaking Changes - **Config format change** - Legacy config format (pre-v2.8.0) requires migration - **Migration**: Automatic during `install`, or manual via `claude-hooks migrate-config` - **Compatibility**: Legacy format still works with deprecation warning until v3.0.0 - **Action required**: None (auto-migrates), but consider running `migrate-config` to see diff - **Template location change** - .md files moved from `.claude/` to `.claude/prompts/` - **Migration**: Automatic during `install --force` - **Custom templates**: If you customized templates, move them to `.claude/prompts/` manually - **Impact**: Low - most users don't customize, system checks both locations - **Hardcoded parameters** - 21 parameters no longer user-configurable in .claude/config.json - **Removed from user config**: `analysis.*` (except ignoreExtensions), `commitMessage.*` (except taskIdPattern), `templates.*`, `output.*`, `system.*`, `git.*`, `subagents.enabled`, `subagents.model` (except in advanced config) - **Rationale**: Sensible defaults work for everyone, reduces configuration complexity - **Override**: Advanced params available in `config.advanced.example.json` (use with caution) ## [2.7.2] - 2025-12-23 ### ✨ Added - **Retry logic for PR commands** - Added automatic retry for `create-pr` and `analyze-diff` commands (#49) - **What changed**: Both commands now use `executeClaudeWithRetry()` with exponential backoff (2s, 4s, 8s delays) - **Impact**: PR creation and diff analysis now automatically recover from transient Claude API errors - **Files changed**: - `lib/utils/claude-client.js:676-745,846` - Created reusable `withRetry()` wrapper and `executeClaudeWithRetry()` export - `bin/claude-hooks:11,972,1234` - Updated create-pr and analyze-diff to use retry logic ### πŸ› Fixed - **Windows WSL timeout** - Increased WSL availability check from 3s to 15s to handle system load (#49) - `lib/config.js:78` - Made configurable via `config.system.wslCheckTimeout` - `lib/utils/claude-client.js:107` - Uses config value for WSL check - **Duplicate task ID logging** - Removed redundant log in prepare-commit-msg (#49) - `lib/hooks/prepare-commit-msg.js:191-193` - Removed duplicate logger.info call ### 🎯 Improved - **Error diagnostics** - Added timing information to all error contexts (#49) - `lib/utils/claude-client.js:248-340` - Added `elapsedTime`, `timeoutValue`, `retryAttempt` to errors - `lib/utils/claude-diagnostics.js:118-143,187-344` - Created `formatTimingInfo()` helper, updated all error formatters ## [2.7.1] - 2025-12-22 ### πŸ› Fixed - **Improved reliability with automatic retry logic** - Fixed intermittent "Execution error" failures from Claude API - **What was broken**: Claude CLI occasionally returned "Execution error" (15 chars) with exit code 0, causing commits to fail ~50% of the time - **Root cause**: Claude API rate limiting or temporary backend issues returned error text instead of valid JSON, but was treated as success due to exit code 0 - **Fix**: Added detection for "Execution error" responses and automatic retry logic with 2-second delay - **Files changed**: - `lib/utils/claude-diagnostics.js:22-29,47-57,122-170,307-310` - Added EXECUTION_ERROR type detection and formatting - `lib/utils/claude-client.js:24,246-270,620-679` - Check for error even with exit code 0, added retry logic - **Impact**: Significantly improved reliability - transient API errors now automatically retry once, reducing failure rate - **User experience**: Clear error messages explain the issue, automatic retry happens transparently with "⏳ Retrying..." message ### 🎯 User Experience - **Before**: Commits failed ~50% of the time with cryptic "No valid JSON found" error, requiring manual retries - **After**: System automatically detects and retries recoverable errors, with helpful messages explaining what's happening - **Error messages**: Now include specific guidance for "Execution error" (likely rate limiting, try haiku model, commit fewer files) ## [2.7.0] - 2025-12-19 ### 🎨 Changed - **Simplified code analysis output format** - Replaced fake SonarQube metrics with issue count summary (#47) - **What changed**: Removed BLOCKER/CRITICAL/MAJOR/MINOR severity labels and A-E reliability/security/maintainability ratings - **Why**: Metrics were Claude's opinion presented as facts, causing confusion and false sense of precision - **New format**: Simple summary "X issue(s) found across Y file(s)" or "βœ… No issues found!" - **Files changed**: - `lib/hooks/pre-commit.js:67-100` - Replaced metrics display with issue count summary - `templates/CLAUDE_PRE_COMMIT_SONAR.md` β†’ `templates/CLAUDE_PRE_COMMIT.md` (renamed) - `templates/CLAUDE_ANALYSIS_PROMPT_SONAR.md` β†’ `templates/CLAUDE_ANALYSIS_PROMPT.md` (renamed) - `lib/config.js:58-59` - Updated template paths to remove SONAR suffix - `bin/claude-hooks:387-407` - Installer now removes old SONAR template files - **Impact**: Cleaner output focused on actual issues, not fake quality scores - **Added false-positive prevention guidance** - Pre-commit hook now avoids reporting improvements as issues (#47) - **What was broken**: Hook reported routine improvements (better formatting, added docs) as CODE_SMELL issues - **Root cause**: Prompts lacked explicit guidance to distinguish problems from improvements - **Fix**: Added clear instructions to only report actual bugs, security issues, or quality degradations - **New guidance in templates**: - "Only report actual problems, bugs, security issues, or code quality concerns" - "Do NOT report improvements, positive changes, or routine maintenance as issues" - "It is perfectly acceptable to find ZERO issues - this is a positive outcome" - "When in doubt, err on the side of NOT reporting it" - **Files changed**: - `templates/CLAUDE_PRE_COMMIT.md` - Added false-positive prevention section at top - `templates/CLAUDE_ANALYSIS_PROMPT.md` - Updated instructions before JSON schema - **Compatibility**: Existing configurations continue to work, but users get fewer false positives ### πŸ”§ Fixed - **Pre-commit hook no longer reports improvements as issues** - Documentation additions and formatting improvements now correctly pass analysis (#47) ### ⚠️ Breaking Changes (Minor) - **Template file renames**: `CLAUDE_PRE_COMMIT_SONAR.md` β†’ `CLAUDE_PRE_COMMIT.md`, `CLAUDE_ANALYSIS_PROMPT_SONAR.md` β†’ `CLAUDE_ANALYSIS_PROMPT.md` - **Migration**: Installer automatically removes old files and installs new ones on `claude-hooks install --force` - **Impact**: Low - most users don't customize these files. Custom templates need manual rename. ## [2.6.3] ### πŸ› Fixed - **WSL timeout error misreporting** - Fixed misleading error message when WSL times out under system load (#49) - **What was broken**: ETIMEDOUT errors during WSL Claude verification were misreported as "Claude CLI not found in WSL" - **Root cause**: Catch block in WSL verification treated all errors identically, including transient ETIMEDOUT timeouts from system load - **Fix**: Added error type differentiation to distinguish between ETIMEDOUT (transient timeout), ENOENT (missing CLI), and generic WSL errors - **Files changed**: - `lib/utils/claude-client.js:109-146` - Enhanced error detection with three distinct error paths - **Impact**: - ETIMEDOUT: Clear message "Timeout connecting to WSL - system under heavy load" with suggestion to retry or skip - ENOENT: Preserved original "Claude CLI not found in WSL" with installation instructions - Generic: New fallback "Failed to verify Claude CLI in WSL" with WSL diagnostic suggestions - **Compatibility**: No breaking changes, improves error accuracy for Windows WSL users ### 🎯 User Experience - **Before**: Users experiencing system load timeouts saw misleading "Claude CLI not found" error and tried reinstalling unnecessarily - **After**: Clear distinction between transient timeouts (retry/skip) and missing CLI (install) with actionable suggestions for each - **Debug**: All error cases now include context with platform, wslPath, error type, and specific remediation steps ## [2.6.2] - 2025-12-12 ### πŸ› Fixed - **Parallel analysis stdin error handling** - Added graceful error handling for EOF errors during parallel execution (#43) - **What was broken**: Unhandled 'error' events on stdin stream when Claude CLI process terminates unexpectedly during parallel analysis - **Root cause**: `stdin.write()` failures emit asynchronous 'error' events that weren't being caught, causing uncaught exceptions with large prompts (18+ files) in parallel mode - **Fix**: Added explicit error handler on `stdin` stream before writing prompt - **Files changed**: - `lib/utils/claude-client.js:287-308` - Added stdin error handler with detailed diagnostics - **Impact**: - Provides clear error message: "Failed to write to Claude stdin - process terminated unexpectedly" - Logs diagnostic info: prompt length, error code, duration - Suggests actionable fix: "Try reducing batch size or number of files per commit" - **Compatibility**: No breaking changes, improves error reporting for all platforms ### 🎯 User Experience - **Before**: Cryptic unhandled 'write EOF' exceptions crashed commit process with no actionable information - **After**: Clear error message with diagnostic context and suggested remediation - **Debug**: Added structured logging with prompt length and timing when EOF errors occur ## [2.6.1] - 2025-12-04 ### πŸ› Fixed - **Windows spawn ENOENT errors** - Fixed critical issue where Claude CLI failed to execute on Windows with npm-installed tools - **What was broken**: `spawn()` cannot execute `.cmd`/`.bat` files directly on Windows, causing `ENOENT` errors - **Root cause**: npm on Windows creates both `claude` (non-executable) and `claude.cmd` (executable), and system was selecting the wrong one - **Fix 1**: `which-command.js` now prefers `.cmd`/`.bat` extensions over extensionless entries when multiple matches found - **Fix 2**: `claude-client.js` wraps `.cmd`/`.bat` commands with `cmd.exe /c` before spawning - **Files changed**: - `lib/utils/which-command.js:135-163` - Prefer `.cmd`/`.bat` in Windows path resolution - `lib/utils/claude-client.js:165-179` - Wrap batch files with cmd.exe - **Impact**: Fixes `analyze-diff` and commit hooks for Windows users with npm-installed Claude CLI - **Compatibility**: No impact on Linux/macOS or Windows WSL setups, only affects Windows native npm installations ### 🎯 User Experience - **Before**: Windows users with npm-installed Claude CLI got `ENOENT` errors on every command - **After**: Commands work seamlessly, same as other platforms - **Debug**: Added detailed logging for Windows .cmd file detection and wrapping ## [2.6.0] - 2025-12-02 ### ✨ Added - Node.js 24 Compatibility - **Full Node.js 24 Support** - claude-hooks now compatible with Node.js 24 without deprecation warnings - **What changed**: Removed `shell: true` from `spawn()` calls to avoid DEP0190 deprecation - **Why**: Node.js 24 deprecates passing args array to `spawn()` with `shell: true` due to security risks (shell injection) - **Solution**: New `which-command.js` utility resolves executable paths without shell - **Impact**: No DEP0190 warnings, more secure execution, works on Node 16-24+ - **New Utility Module**: `lib/utils/which-command.js` - **Purpose**: Cross-platform executable path resolution (like Unix `which`, Windows `where`) - **Key Features**: - Finds executables in PATH without `shell: true` - Handles Windows `.exe/.cmd/.bat` extensions automatically - Platform-agnostic API (`which()`, `whichOrThrow()`, `hasCommand()`) - Fast: tries platform command first, fallback to manual PATH search - Secure: no shell invocation needed - **Exports**: `which()`, `whichOrThrow()`, `hasCommand()` - **Tests**: 11 tests covering Unix/Windows scenarios ### πŸ”„ Changed - **`claude-client.js` - Updated Command Resolution** - **Line 25**: Added `import { which } from './which-command.js'` - **Lines 77-143**: Refactored `getClaudeCommand()` to use `which()` for absolute paths - Windows: resolves `claude.exe` or `wsl.exe` absolute path - Unix: resolves `claude` absolute path - Fallback: returns 'claude' if which() fails (will error later if not in PATH) - **Lines 181-183**: **Removed `shell: true`** from `spawn()` call - **Before**: `spawn(command, args, { shell: true })` - **After**: `spawn(command, args, { stdio: [...] })` - **Why**: Avoids DEP0190, improves security, works on Node 24 - **Impact**: Claude CLI execution now uses absolute paths, no shell overhead - **`package.json` - Platform Documentation** - **Lines 36-41**: Added `engineStrict: false` and `os` array - **Why**: Documents supported platforms (darwin, linux, win32) - **No breaking change**: Still supports Node >= 16.9.0 ### πŸ§ͺ Testing - **New Test Suite**: `test/unit/claude-client-node24.test.js` - 8 tests covering Node 24 compatibility - Verifies `getClaudeCommand()` returns absolute paths - Checks DEP0190 is not triggered - Platform detection tests (Windows/WSL/Unix) - **New Test Suite**: `test/unit/which-command.test.js` - 11 tests for executable resolution - Verifies no DEP0190 warnings - Tests `which()`, `whichOrThrow()`, `hasCommand()` - Cross-platform compatibility checks - **All Tests Pass**: 51 passed (Node 24 migration), 7 failed (pre-existing task-id issues) ### πŸ“š Documentation - **New Migration Guide**: `MIGRATION_NODE24.md` - Comprehensive 400+ line document - Explains DEP0190 deprecation in detail - Step-by-step migration plan - Testing strategy across Node 16/18/20/24 - Platform test matrix (Windows/WSL/Linux/macOS) - Rollback plan if issues arise - References to Node.js GitHub issues and PRs ### πŸ”§ Technical Details **DEP0190 Explanation**: - **What**: Node.js 24 deprecates `spawn(cmd, args, { shell: true })` - **Why**: Args are not escaped, just concatenated β†’ shell injection risk - **Fix**: Use absolute executable paths, remove `shell: true` **Files Changed**: - `lib/utils/claude-client.js` - Command resolution and spawn call - `lib/utils/which-command.js` - NEW utility for path resolution - `package.json` - Platform documentation - `test/unit/claude-client-node24.test.js` - NEW tests - `test/unit/which-command.test.js` - NEW tests - `MIGRATION_NODE24.md` - NEW migration guide **Backward Compatibility**: - βœ… Works on Node 16.9.0+ (unchanged) - βœ… Works on Node 18 (unchanged) - βœ… Works on Node 20 (unchanged) - βœ… Works on Node 24 (NEW - no warnings) - βœ… No API changes - βœ… No behavioral changes ### 🎯 User Experience - **No Action Required**: Upgrade works transparently - **No Warnings**: Clean execution on Node 24 - **Better Security**: No shell injection risk - **Faster**: No shell overhead (small performance gain) - **Same API**: All commands work identically ### πŸ“‹ Migration Checklist For users on Node 24: - [x] Update to claude-git-hooks 2.6.0 - [x] Verify no DEP0190 warnings: `claude-hooks install` - [x] Test pre-commit hook: `git commit` - [x] Test GitHub setup: `claude-hooks setup-github` ### πŸ”— References - [Node.js DEP0190 Documentation](https://nodejs.org/api/deprecations.html#dep0190-passing-args-to-spawn-with-shell-true) - [GitHub Issue #58763 - DEP0190 not fixable with stdio](https://github.com/nodejs/node/issues/58763) - [PR #57199 - Disallow args with shell: true](https://github.com/nodejs/node/pull/57199) --- ## [2.5.0] - 2025-11-26 ### ✨ Added - **GitHub Integration - One-Command PR Creation** - Create pull requests with auto-generated metadata - **What's new**: `claude-hooks create-pr [base]` command that creates PRs on GitHub via Octokit (deterministic) - **Architecture**: Claude analyzes diff and generates metadata (brain) β†’ Octokit creates PR (deterministic actions) - **Key features**: - **Task-ID Extraction**: Automatically extracts task identifiers from branch names (Jira: IX-123, GitHub: #456, Linear: LIN-123) - **Smart PR Generation**: Claude analyzes git diff and generates PR title, description, reviewers, and labels - **Deterministic Creation**: Octokit directly creates PR via GitHub REST API (no MCP dependencies) - **Token Management**: 4-level priority (GITHUB_TOKEN env β†’ GITHUB_PERSONAL_ACCESS_TOKEN env β†’ .claude/settings.local.json β†’ Claude Desktop config) - **Auto-Reviewer Detection**: Detects reviewers from CODEOWNERS file, config patterns, or preset-based rules - **Preset-Based Labels**: Automatically adds labels based on tech stack (backend β†’ java/spring-boot, frontend β†’ react/typescript) - **Interactive Preview**: Shows formatted PR preview with confirmation before creating - **Configurable Defaults**: Set default base branch, reviewers, labels, and rules in `.claude/config.json` - **Error Recovery**: Saves PR metadata to .claude/out/pr-metadata.json on failure for manual retry - **Task-ID in Commits**: Auto-detect task-id from branch when using `git commit -m "auto"` with configurable regex pattern - **Task-ID Pattern (Configurable)**: - **Default**: 1-3 uppercase letters + separator + 3-5 digits (e.g., ABC-12345, IX-123, DE 4567) - **Config**: Set custom regex in `.claude/config.json` β†’ `commitMessage.taskIdPattern` - **Avoids false positives**: Won't match hashes (471459f), invalid formats (ABCD-123, IX-12) - **Examples**: `([A-Z]{1,3}[-\\s]\\d{3,5})` (default), `([A-Z]{2,10}-\\d+)` (Jira-style) - **New modules**: - `lib/utils/task-id.js` - Reusable task-id extraction and formatting (29 tests) - `lib/utils/github-api.js` - Direct Octokit integration (token resolution, PR creation, validation) - `lib/utils/github-client.js` - GitHub MCP wrapper (deprecated, kept for compatibility) - `lib/utils/interactive-ui.js` - Terminal UI helpers (preview, prompts, menus, spinners) - **Configuration**: New `github.pr` section in config with reviewers, labels, and pattern rules - **Files created**: - `lib/utils/task-id.js` - Task ID extraction/formatting - `lib/utils/github-api.js` - Octokit integration with token resolution - `lib/utils/github-client.js` - GitHub MCP client wrapper (deprecated) - `lib/utils/interactive-ui.js` - Interactive CLI components - `templates/config.github.example.json` - Example GitHub configuration - `templates/settings.local.example.json` - Local token storage template - **Files updated**: - `bin/claude-hooks:1044-1377` - Rewritten createPr() function with 13-step Octokit workflow - `bin/claude-hooks:1299-1344` - New setupGitHub() function - `bin/claude-hooks:1772-1774` - Added setup-github case statement - `bin/claude-hooks:1515,1537-1548` - Updated help with token configuration - `bin/claude-hooks:488-490` - Added GitHub PR creation to post-install message - `lib/config.js:37-46` - Added commitMessage.taskIdPattern configuration - `lib/config.js:81-102` - Simplified GitHub config, enabled by default - `lib/utils/github-client.js:792-794` - Deprecation notice for MCP-based createPullRequest - `lib/utils/task-id.js:21-55,71-98,107-144` - Made pattern configurable, reads from config - `lib/hooks/prepare-commit-msg.js:27,182-193,280-290` - Added task-id detection with config support - `package.json` - Added @octokit/rest ^21.0.0 dependency - **Requirements**: - GitHub token with repo and read:org scopes - Repository must have GitHub remote origin - **Token configuration**: `claude-hooks setup-github` guides through token setup - **Comprehensive logging**: Debug logs throughout github-api.js and createPr() for troubleshooting - **Dynamic user agent**: Version read from package.json to prevent staleness - **Task-ID Detection**: Auto-extract or prompt for task-id in commit messages (Jira, GitHub, Linear) - **Impact**: Developers can create well-formatted PRs with proper metadata in one command, reducing PR creation friction ### 🎯 User Experience - **One-Command Workflow**: `claude-hooks create-pr develop` replaces manual PR creation steps - **Deterministic & Reliable**: Octokit provides consistent PR creation (no MCP reliability issues) - **Flexible Token Configuration**: Four methods to provide token - choose what works best for your setup - **Clear Error Messages**: HTTP status codes (401, 403, 404, 422) with actionable suggestions - **Setup Wizard**: `claude-hooks setup-github` validates token and guides configuration - **Consistency**: All PRs follow same format with task-ids, descriptions, and appropriate reviewers - **Interactive**: Preview and edit PR before creation, choose between Create/Edit/Cancel - **Recovery Support**: Failed PRs save metadata to .claude/out/pr-metadata.json for manual retry ### πŸ“š Documentation - **Help Text**: Added create-pr and setup-github commands to `claude-hooks help` - **Token Configuration**: Clear explanation of 4-level token resolution priority - **Use Cases**: Documented create-pr workflow with example output - **Configuration Example**: Added `templates/config.github.example.json` with reviewer and label rules - **Architecture Note**: Claude only for metadata generation (brain), Octokit for PR creation (deterministic actions) - **Post-Install Message**: Added GitHub PR creation section with setup-github and create-pr examples - **README Updates**: - Quick Setup section for GitHub PR creation - File structure updated with new GitHub modules - Utility modules table includes github-api.js, task-id.js, interactive-ui.js - Task-ID detection in commit messages documented ## [2.4.2] - 2025-11-24 ### πŸ—‘οΈ Removed - **SKIP_ANALYSIS Feature** - Removed broken/experimental code exclusion feature - **What was removed**: `// SKIP_ANALYSIS_LINE` and `// SKIP_ANALYSIS_BLOCK` comment markers - **Why**: Feature never worked reliably - hooks analyze git diff instead of full files, so markers in previous commits weren't detected - **Impact**: No user action needed - feature was marked EXPERIMENTAL/BROKEN and wasn't functional - **Cleanup**: Removed all code, documentation, and references from README.md, CHANGELOG.md ## [2.4.1] - 2025-11-19 ### πŸ› Fixed - **Git Bash Windows Support** - Claude hooks now works correctly on Git Bash in Windows - **What changed**: - `--skip-auth` now skips both Claude CLI verification AND authentication (previously only auth) - Windows detection now tries native Claude first, WSL as fallback - `spawn()` now uses `shell: true` to resolve `.cmd`/`.bat` executables - **Why**: - Installation with `--skip-auth` was failing before copying `.md` files and presets - Code assumed Claude must always run via WSL on Windows, ignoring native installations - Git Bash runs Node.js natively on Windows, not in WSL - `spawn()` without shell couldn't find Windows batch files - **Files updated**: - `bin/claude-hooks:512-518` - Skip auth now skips Claude CLI check - `bin/claude-hooks:532-544` - Native Windows Claude detection - `lib/utils/claude-client.js:75-115` - Smart platform detection with fallback - `lib/utils/claude-client.js:145-148` - Added `shell: true` for Windows compatibility - **Impact**: Git Bash users on Windows can now use native Claude (via npm/NVM) instead of requiring WSL ### 🎯 User Experience - **Installation**: `claude-hooks install --skip-auth` now completes successfully, installing all templates and presets - **NVM Compatibility**: Works with Claude CLI installed via npm in current Node version (NVM managed) - **Flexible Setup**: Automatically detects and uses best available Claude CLI method (native Windows or WSL) ## [2.4.0] - 2025-11-17 ### ⚠️ BREAKING CHANGES - **Debug Mode** - Environment variable `DEBUG` no longer supported - **What changed**: Removed `DEBUG` environment variable support from `lib/utils/logger.js` - **Why**: Aligns with project philosophy "no environment variables" and provides better user experience - **Migration**: Use `claude-hooks --debug true` instead of `DEBUG=1 git commit` - **Alternative**: Set `"system": { "debug": true }` in `.claude/config.json` ### πŸ”„ Changed - **File Size Limit Increased** - Default `maxFileSize` increased from 100KB to 1MB - **What changed**: `analysis.maxFileSize` now defaults to 1000000 (1MB) instead of 100000 (100KB) - **Why**: Previous 100KB limit was too restrictive, rejected many legitimate source files - **Files updated**: - `lib/config.js:29` - Default configuration - All preset configs in `templates/presets/*/config.json` - `templates/config.example.json` - **Impact**: More files will be analyzed without manual config adjustment - **User action**: If you want stricter limits, set `"maxFileSize": 100000` in `.claude/config.json` ### ✨ Added - **Debug CLI Command** - New `--debug` flag for managing debug mode - **Usage**: `claude-hooks --debug <true|false|status>` - **Purpose**: Enables detailed logging for troubleshooting - **Implementation**: Generic `updateConfig()` function in `bin/claude-hooks:1262` - **Benefits**: Consistent with `--set-preset` pattern, no need to remember env var syntax - **Generic Config Updater** - Reusable `updateConfig()` function - **Purpose**: Centralized config update logic for all CLI commands - **Location**: `bin/claude-hooks:1262` - **Features**: Dot notation path support, custom validators, custom success messages - **Extensibility**: Easy to add new config commands (`--set-max-files`, `--set-timeout`, etc.) ### πŸ”„ Changed - **setPreset() Refactored** - Now uses generic `updateConfig()` function - **Effect**: Less code duplication, consistent error handling - **Location**: `bin/claude-hooks:1349` - **Debug Mode Activation** - Hooks now enable debug from config - **Files**: `lib/hooks/pre-commit.js:185`, `lib/hooks/prepare-commit-msg.js:124` - **Effect**: Debug logs appear when `config.system.debug` is true ### πŸ“š Documentation - **Help Text Updated** - Added `--debug` command documentation - **Location**: `bin/claude-hooks:1170` - **Includes**: Command description, examples, debug mode section - **README.md Updated** - Debug command documented in multiple sections - **Cheatsheet**: Added debug commands to "Comandos Frecuentes" (line 52-56) - **Tips**: Updated tip #4 with CLI command (line 269) - **Features**: Updated debug mode description (line 492) ## [2.3.1] - 2025-11-13 ### πŸ”„ Changed - **Configuration Priority** - Updated merge order: `defaults < user config < preset config` - **Rationale**: User sets general preferences in `.claude/config.json`, preset provides tech-stack-specific overrides (highest priority) - **Effect**: Presets now correctly override user settings (e.g., preset's `model: sonnet` wins over user's `model: haiku`) - **Files updated**: `lib/config.js:116` (merge logic), README.md:222 (documentation) ### ✨ Added - **Installation Diagnostics Utility** - New `lib/utils/installation-diagnostics.js` - **Purpose**: Reusable error diagnostics with actionable remediation steps - **Exports**: `formatError()`, `getInstallationDiagnostics()`, `isInstallationHealthy()` - **Use case**: Detects installation in wrong directory (common cause of "presets not found" errors) - **Extensible**: Documented future enhancements (file permissions, Claude CLI check, etc.) - **Enhanced Error Messages** - Better guidance when installation fails - **Presets not found** (`lib/utils/preset-loader.js:194`): Shows current vs repo root directory - **Hook scripts missing** (`templates/pre-commit:76`, `templates/prepare-commit-msg:76`): Early `.claude/` check with remediation steps - **npm package issues**: Suggests verifying `npm list -g claude-git-hooks` - **Bash Wrapper Early Validation** - Hooks now check `.claude/` exists before attempting execution - **Why**: Fails fast with helpful message if installation incomplete or performed from wrong directory - **Effect**: Users immediately know to `cd` to repo root and reinstall - **Claude Error Diagnostics** - New `lib/utils/claude-diagnostics.js` - **Purpose**: Detects and formats Claude CLI errors with actionable solutions - **Error types**: Rate limit, authentication, network, invalid response, generic - **Exports**: `detectClaudeError()`, `formatClaudeError()`, `ClaudeErrorType`, `isRecoverableError()` - **Integration**: `lib/utils/claude-client.js:147` automatically detects and formats errors - **Effect**: Users see clear guidance (e.g., "Rate limit resets in 2 hours, switch to haiku model") ### πŸ“š Documentation - **CUSTOMIZATION_GUIDE.md** - Comprehensive preset creation guide in `/templates` - Visual flowchart showing prompt assembly (8-step diagram) - Step-by-step preset creation tutorial - Placeholder system reference with examples - Preset kickstart prompt for Claude-assisted generation - **Burst limit warning**: Explains why git hooks hit rate limits when manual CLI doesn't - Referenced in README.md:333 for discoverability - **Utility Modules Reference** - New section in README.md:596 - Table of all `lib/utils/` modules with purpose and key exports - Usage examples for other Claude instances - Promotes code reuse across projects - **README-NPM.md** - Complete rewrite for npm package page - **Length**: 266 lines (up from 145 lines, but more focused) - **Updated**: v2.3.0 presets, v2.2.0 config centralization, v2.0.0 cross-platform - **Added**: Configuration priority explanation, troubleshooting, "What's New" section - **Removed**: Outdated v1.x references, environment variable examples ### 🎯 User Experience - **Clearer error context**: Errors now show current directory vs repository root - **Actionable solutions**: Every error includes specific commands to fix the issue - **Installation verification**: Early checks prevent confusing downstream errors - **Better documentation**: Users can find utility functions and customization guides easily - **Claude error clarity**: Rate limits, auth failures, and network errors now show specific remediation steps ## [2.3.0] - 2025-11-11 ### ✨ Added - **Preset System (Phase 3)** - 🎯 6 built-in presets: `backend`, `frontend`, `fullstack`, `database`, `ai`, `default` - πŸ“¦ Self-contained preset packages with custom prompts and configurations - πŸ” Smart file filtering per preset (`.java` for backend, `.tsx` for frontend, etc.) - 🎨 Rich metadata: tech stack, focus areas, file extensions, display names - πŸ”Œ Template inheritance with placeholder replacement ({{TECH_STACK}}, {{FOCUS_AREAS}}) - πŸ› οΈ Manual preset selection via CLI: `claude-hooks --set-preset <name>` - πŸ“‹ Preset management commands: `presets`, `preset current`, `--set-preset` - πŸ“– See `next-steps/V2.3.0_PHASE3_PRESETS_FINAL.md` for full specification - **CLI Enhancements** - 🏷️ Added `--version`, `-v`, and `version` commands to display current version - πŸ“Š Version check on install with interactive update prompt (skippable with `--skip-auth` or `--force`) ### πŸ› Fixed - **Critical Bug**: `prepare-commit-msg` now properly loads merged config (preset + user overrides) - Was using sync default import instead of async `getConfig()` - Preset settings were being ignored in commit message generation - **Template Name Mismatch**: Fixed config.js template paths - `COMMIT_MESSAGE.md` (was `CLAUDE_COMMIT_MESSAGE.md`) - `ANALYZE_DIFF.md` (was `CLAUDE_ANALYZE_DIFF.md`) - **Missing Auto-Update**: `checkVersionAndPromptUpdate()` now called during install ### πŸ—‘οΈ Removed - ❌ Deleted `readPassword()` function (24 lines) - unused since v2.0.0 sudo removal - ❌ Deleted `setMode()` function (5 lines) - empty implementation, never used - ❌ Deleted `readMultipleFiles()` function (62 lines) - exported but never imported - ❌ Removed `"main": "lib/index.js"` from package.json - CLI-only package - ❌ Deleted obsolete root template `CLAUDE_PRE_COMMIT_SONAR.md` ### πŸ”„ Changed - **Commit Message Timeout**: Increased from 120s to 180s for complex analysis - **Config Loading**: All hooks now use async `getConfig()` for proper preset merging ### πŸ“š Documentation - πŸ“– Updated CHANGELOG with v2.3.0 release notes - πŸ“ Marked Phase 3 preset system as IMPLEMENTED in spec ### 🎯 Preset Examples ```bash # List available presets claude-hooks presets # Set backend preset (filters to .java, .xml, .yml files) claude-hooks --set-preset backend # Check active preset claude-hooks preset current # All presets installed during: claude-hooks install ``` ### πŸ“¦ Available Presets 1. **backend** - Spring Boot + SQL Server (Java, XML, YAML) 2. **frontend** - React + Material-UI (JS, JSX, TS, TSX, CSS) 3. **fullstack** - Backend + Frontend + DB with consistency checks 4. **database** - SQL Server migrations and procedures 5. **ai** - Node.js + Claude CLI integration 6. **default** - General-purpose scripting ### πŸ“‹ Migration from v2.2.0 No breaking changes. Presets are opt-in: ```bash # Continue using defaults (no preset) git commit -m "message" # Or activate a preset claude-hooks --set-preset backend git commit -m "message" # Now filters to .java, .xml, .yml only ``` ## [2.2.0] - 2025-11-04 ### ✨ Added - **Configuration Centralization (Phase 1)** - πŸ“ Created `lib/config.js` - single source of truth for all configurable values - πŸ”§ User override support via `.claude/config.json` with deep merge - πŸ“Š Structured config: analysis, commitMessage, subagents, templates, output, system, git - 🚫 Eliminated environment variables (except OS for platform detection) - πŸ“– See `next-steps/V2.2.0_CONFIG_CENTRALIZATION.md` for details - **Prompt Externalization (Phase 2)** - πŸ“ Extracted ALL embedded prompts to external .md template files - πŸ”Œ Created `loadPrompt()` utility - combines load + variable replacement - πŸ“„ New templates: `COMMIT_MESSAGE.md`, `ANALYZE_DIFF.md` - 🎯 JavaScript is now completely "prompt-agnostic" - πŸ“– See `next-steps/V2.2.0_PHASE2_PROMPTS.md` for details - **Parallel Analysis** - πŸš€ True OS-level parallel execution using multiple Claude CLI processes simultaneously - ⚑ `analyzeCodeParallel()` function runs batches via Node.js `Promise.all()` - πŸ“Š Configurable `batchSize` for optimal speed/cost balance (default: 2) - πŸ”€ Automatic result consolidation with worst-case quality gate logic - πŸ“ˆ Real-time console output showing parallel batch launches and completion - 🎯 Enabled by default for commits with 3+ files - ⏱️ Speed improvement: up to 4x faster with `batchSize: 1` ### πŸ”„ Changed - **Configuration Migration** - ♻️ Migrated `lib/hooks/pre-commit.js` to use centralized config - ♻️ Migrated `lib/hooks/prepare-commit-msg.js` to use centralized config - ♻️ Migrated `lib/utils/claude-client.js` to use centralized config - πŸ”§ `process.env.DEBUG` β†’ `config.system.debug` - πŸ”§ All hardcoded timeouts now configurable - **Prompt Migration** - ♻️ `prepare-commit-msg.js`: 40 lines β†’ 15 lines (62% reduction) - ♻️ `bin/claude-hooks`: 30 lines β†’ 10 lines (67% reduction) - 🎨 Prompts now editable without touching JavaScript code - **Template Loading** - πŸ“‚ Enhanced `loadTemplate()` with fallback: `.claude/` β†’ `templates/` - πŸ”€ Enables per-project customization of prompts ### πŸ—‘οΈ Removed - ❌ Deleted `buildCommitMessagePrompt()` - unused legacy code - ❌ Removed all `process.env` references except OS check ### πŸ“š Documentation - πŸ“– Added `next-steps/V2.2.0_CONFIG_CENTRALIZATION.md` - πŸ“– Added `next-steps/V2.2.0_PHASE2_PROMPTS.md` - πŸ“ Updated configuration examples and customization guides ### 🎯 Benefits - **Maintainability:** Prompts editable by non-developers - **Flexibility:** Easy A/B testing of prompt styles - **Customization:** Per-project overrides via `.claude/config.json` - **Simplicity:** Clear separation of concerns (JS = logic, .md = content) ### πŸ“‹ Migration Guide No breaking changes. All defaults match previous behavior. **Optional: Customize configuration** ```bash # Create project config mkdir -p .claude cat > .claude/config.json << 'EOF' { "analysis": { "maxFileSize": 200000, "maxFiles": 15 }, "subagents": { "enabled": true, "model": "sonnet" }, "system": { "debug": true } } EOF ``` **Optional: Customize prompts** ```bash # Override commit message prompt cp templates/COMMIT_MESSAGE.md .claude/ # Edit .claude/COMMIT_MESSAGE.md as needed ``` ## [2.1.0] - 2025-11-04 ### Changed - πŸ”„ Renombrado marcador de exclusiΓ³n de lΓ­nea ΓΊnica: `// SKIP-ANALYSIS` β†’ `// SKIP_ANALYSIS_LINE` para consistencia de nomenclatura - πŸ› Corregido bug crΓ­tico en orden de detecciΓ³n de patrones que impedΓ­a funcionamiento de `SKIP_ANALYSIS_BLOCK` ### Known Issues - ⚠️ **SKIP_ANALYSIS marcado como EXPERIMENTAL/BROKEN**: Los marcadores de exclusiΓ³n no funcionan correctamente porque el anΓ‘lisis se realiza sobre git diff en lugar del archivo completo. Marcadores agregados en commits anteriores no son detectados en cambios subsecuentes. ### Migration Guide Si utilizabas `// SKIP-ANALYSIS` en tu cΓ³digo, reemplΓ‘zalo por `// SKIP_ANALYSIS_LINE`: ```java // Antes (deprecated): // SKIP-ANALYSIS private String legacyCode; // Ahora: // SKIP_ANALYSIS_LINE private String legacyCode; ``` El marcador de bloque `// SKIP_ANALYSIS_BLOCK` permanece sin cambios. ## [2.0.1] - 2025-11-04 ### Fixed - πŸ”§ Compatibilidad completa en Windows: corregidos line endings CRLF, validaciΓ³n WSL, y comparaciΓ³n de versiones sin dependencia bash - πŸ”§ Operaciones de rutas utilizan mΓ³dulo `path` nativo para mejor portabilidad multiplataforma ## [2.0.0] - 2025-10-30 ### πŸš€ BREAKING CHANGE: Migration from Bash to Node.js Hooks **Why this change?** The bash-based hooks created fundamental incompatibilities with Windows Git and IDE workflows (VSCode, IntelliJ), causing: - Git worktree path conflicts (Windows paths incompatible with WSL) - IDE commit failures when using Windows Git - Developers forced to use WSL terminal exclusively, abandoning IDE Git features ### βœ… Advantages **Cross-Platform Native Support** - βœ… Works with Windows Git, WSL, and Bash - βœ… No more worktree path issues - βœ… Single codebase for all platforms **Dramatically Improved Maintainability** - βœ… JavaScript/Node.js: ~60-70% of developers proficient vs ~1-2% with bash/jq/sed/awk - βœ… Modern tooling: ESLint, Prettier, Jest testing framework - βœ… VS Code debugging support vs echo statements **Professional Development Practices** - βœ… Unit and integration testing with Jest - βœ… Type safety optional (TypeScript) - βœ… Consistent error handling patterns ### ⚠️ Disadvantages - ⚠️ Initial migration effort - ⚠️ Startup performance: +40-90ms overhead (~1% of total execution time) ### πŸ† Industry Success Cases **Node.js Git Hooks - Proven Track Record:** - **Husky**: 43k GitHub stars, 500+ contributors, 7M+ weekly npm downloads - **lint-staged**: 12k stars, 200+ contributors - **Commitizen**: 16k stars, industry standard - **simple-git-hooks**: Fast, minimal, 1M+ weekly downloads ### Changed - πŸ”„ **Migrated from Bash to Node.js with ES6 modules** - Hooks now in `lib/hooks/*.js` with bash wrappers, removing jq/sed/awk dependencies - 🌐 **Cross-platform support enabled** - Works on Windows Git Bash, WSL, Linux, and macOS with automatic Claude detection - πŸ”§ **Platform compatibility** - CRLF-to-LF conversion during install, Windows path support (C:\ to /c/) in bash wrappers ### Migration Guide Existing installations will continue working. To upgrade: 1. Run `claude-hooks update` to get v2.0.0 2. Run `claude-hooks install --force` to reinstall with Node.js hooks 3. No configuration changes needed - works transparently ## [1.5.5] - 2025-10-29 ### Added - πŸš€ **Parallel Analysis with Subagents** - New `CLAUDE_USE_SUBAGENTS` environment variable to enable parallel file analysis - Each file analyzed by dedicated Claude subagent for faster processing - Works across all analysis functions: pre-commit, message generation, and analyze-diff - Significantly faster for commits with 3+ files - βš™οΈ **Subagent Configuration Options** - `CLAUDE_SUBAGENT_MODEL` - Choose model: haiku (fast), sonnet (balanced), opus (thorough) - `CLAUDE_