claude-git-hooks 2.33.1 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,40 @@ Todos los cambios notables en este proyecto se documentarán en este archivo.
5
5
  El formato está basado en [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  y este proyecto adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.35.0] - 2026-03-27
9
+
10
+ ### ✨ Added
11
+ - Prettier formatting support — auto-formats JS/TS/CSS/HTML/JSON/YAML/MD files before linting (format first, then lint)
12
+ - Remote formatter configuration — preset-to-tools mapping fetched from centralized git-hooks-config repo, allowing team-wide control without releasing new versions
13
+ - New `parsePrettierOutput()` function for parsing Prettier --check output into structured issues
14
+
15
+ ### 🔧 Changed
16
+ - Linting pipeline now runs formatters (Prettier) before linters (ESLint) for consistent code style
17
+ - Updated preset-to-tools mapping: frontend, fullstack, ai, and default presets now include Prettier
18
+ - `getLinterToolsForPreset()` now fetches remote config with local fallback instead of using hardcoded mapping only
19
+ - `runLinters()` and `checkLinterAvailability()` converted to async functions to support remote config fetching
20
+ - Unfixable linting issues are now forwarded to the Claude judge for semantic resolution instead of blocking directly
21
+
22
+
23
+ ## [2.34.0] - 2026-03-27
24
+
25
+ ### ✨ Added
26
+ - Pre-commit linting with ESLint, Spotless, and sqlfluff - runs before Claude analysis with auto-fix and re-stage
27
+ - `lint` command - run linters on staged files, directories, or specific files (`claude-hooks lint [paths...]`)
28
+ - Linter availability check during installation - verifies linter presence per preset and shows install instructions
29
+ - Generic tool executor infrastructure (`tool-runner.js`) for linters and future formatters
30
+ - Linter orchestration system (`linter-runner.js`) with preset-to-linter mapping
31
+ - Maven availability check during installation with install instructions for backend/fullstack presets
32
+
33
+ ### 🔧 Changed
34
+ - Pre-commit flow now runs linting before Claude analysis - fast, deterministic checks first
35
+ - Unfixable lint issues are forwarded to the judge for semantic resolution
36
+ - Updated documentation to reflect new linting workflow and command usage
37
+
38
+ ### 🐛 Fixed
39
+ - WSL Claude CLI detection in non-default distros (#120, #121)
40
+
41
+
8
42
  ## [2.33.1] - 2026-03-26
9
43
 
10
44
  ### 🔧 Changed
package/CLAUDE.md CHANGED
@@ -6,17 +6,19 @@
6
6
 
7
7
  **Main use cases:**
8
8
 
9
- 1. **Pre-commit analysis**: Detects security issues, bugs, and code smells before each commit (blocks on CRITICAL/BLOCKER only)
10
- 2. **Interactive analysis**: `claude-hooks analyze` - review all issues (INFO to BLOCKER) interactively before committing
11
- 3. **Automatic messages**: Write `git commit -m "auto"` and Claude generates the message in Conventional Commits format with task-id extracted from branch
12
- 4. **PR analysis**: `claude-hooks analyze-diff [branch]` generates title, description, and test plan for PRs
13
- 5. **PR review**: `claude-hooks analyze-pr <url>` analyzes a GitHub PR with preset guidelines, Linear ticket enrichment, and posts review comments
14
- 6. **PR creation**: `claude-hooks create-pr [branch]` creates the PR on GitHub with automatic metadata (reviewers from CODEOWNERS, labels by preset, merge strategy auto-detected from branch naming)
15
- 7. **Coupling detection**: `claude-hooks check-coupling` scans open PRs targeting a base branch, computes file overlap, and reports which features are coupled (share modified files) helps TL make informed decisions before cutting a release
16
- 8. **Shadow management**: `claude-hooks shadow <analyze|reset|sync>` manages the shadow branch lifecycle analyze divergence vs main and active RC, reset shadow to a clean copy of main, or sync shadow with a source branch (RC, develop, feature)
17
- 9. **Release creation**: `claude-hooks create-release <major|minor|patch>` creates a release-candidate branch from develop, bumps version files, commits, pushes, and deploys to shadow replaces the 8 manual steps executed every Tuesday by the Tech Lead
18
- 10. **Feature revert**: `claude-hooks revert-feature <task-id>` finds a squash-merged feature commit by task ID in the current release-candidate, checks coupling with other RC features, reverts it, pushes, and optionally re-deploys shadow
19
- 11. **Release closure**: `claude-hooks close-release [description]` finalizes the active release-candidate soft-resets onto main, creates a single clean commit, force-pushes, and creates a PR to main with the merge-commit strategy
9
+ 1. **Pre-commit linting**: Runs formatters and linters (Prettier, ESLint, Spotless, sqlfluff) on staged files before Claude analysis fast, deterministic, auto-fix enabled by default
10
+ 2. **Pre-commit analysis**: Detects security issues, bugs, and code smells before each commit (blocks on CRITICAL/BLOCKER only)
11
+ 3. **Interactive analysis**: `claude-hooks analyze` - review all issues (INFO to BLOCKER) interactively before committing
12
+ 4. **Automatic messages**: Write `git commit -m "auto"` and Claude generates the message in Conventional Commits format with task-id extracted from branch
13
+ 5. **PR analysis**: `claude-hooks analyze-diff [branch]` generates title, description, and test plan for PRs
14
+ 6. **PR review**: `claude-hooks analyze-pr <url>` analyzes a GitHub PR with preset guidelines, Linear ticket enrichment, and posts review comments
15
+ 7. **PR creation**: `claude-hooks create-pr [branch]` creates the PR on GitHub with automatic metadata (reviewers from CODEOWNERS, labels by preset, merge strategy auto-detected from branch naming)
16
+ 8. **Linting**: `claude-hooks lint [paths...]` runs formatters and linters on staged files, directories, or specific files supports Prettier, ESLint, Spotless, sqlfluff per preset (remote config priority with local fallback)
17
+ 9. **Coupling detection**: `claude-hooks check-coupling` scans open PRs targeting a base branch, computes file overlap, and reports which features are coupled (share modified files) helps TL make informed decisions before cutting a release
18
+ 10. **Shadow management**: `claude-hooks shadow <analyze|reset|sync>` manages the shadow branch lifecycle analyze divergence vs main and active RC, reset shadow to a clean copy of main, or sync shadow with a source branch (RC, develop, feature)
19
+ 11. **Release creation**: `claude-hooks create-release <major|minor|patch>` creates a release-candidate branch from develop, bumps version files, commits, pushes, and deploys to shadow replaces the 8 manual steps executed every Tuesday by the Tech Lead
20
+ 12. **Feature revert**: `claude-hooks revert-feature <task-id>` finds a squash-merged feature commit by task ID in the current release-candidate, checks coupling with other RC features, reverts it, pushes, and optionally re-deploys shadow
21
+ 13. **Release closure**: `claude-hooks close-release [description]` finalizes the active release-candidate — soft-resets onto main, creates a single clean commit, force-pushes, and creates a PR to main with the merge-commit strategy
20
22
 
21
23
  ## Architecture
22
24
 
@@ -57,7 +59,7 @@ claude-git-hooks/
57
59
  │ ├── config.js # Config system - load/merge with priority
58
60
  │ ├── commands/ # Command modules - one file per CLI command
59
61
  │ │ ├── helpers.js # Shared CLI utilities - colors, output, platform
60
- │ │ ├── install.js # Install command - dependencies, hooks, templates
62
+ │ │ ├── install.js # Install command - dependencies, hooks, templates, linter check
61
63
  │ │ ├── hooks.js # Hook management - enable, disable, status, uninstall
62
64
  │ │ ├── analyze-diff.js # Diff analysis - generate PR metadata from git diff
63
65
  │ │ ├── analyze-pr.js # PR analysis - analyze GitHub PR with team guidelines
@@ -77,11 +79,14 @@ claude-git-hooks/
77
79
  │ │ ├── bump-version.js # Version management - bump with commit, CHANGELOG and tags
78
80
  │ │ ├── generate-changelog.js # CHANGELOG generation - standalone command
79
81
  │ │ ├── diff-batch-info.js # Batch info - orchestration config + speed telemetry (v2.20.0)
82
+ │ │ ├── lint.js # Lint command - run linters on staged files, dirs, or files
80
83
  │ │ └── help.js # Help, AI help, and report-issue commands
81
84
  │ ├── hooks/ # Git hooks - Node.js implementations
82
85
  │ │ ├── pre-commit.js # Pre-commit analysis - code quality gate
83
86
  │ │ └── prepare-commit-msg.js # Message generation - auto commit messages
84
87
  │ └── utils/ # Reusable modules - shared logic
88
+ │ ├── tool-runner.js # Generic tool executor - resolve, spawn, parse, auto-fix (v2.34.0)
89
+ │ ├── linter-runner.js # Linter orchestration - preset mapping, Prettier/ESLint/Spotless/sqlfluff, remote config (v2.34.0)
85
90
  │ ├── analysis-engine.js # Shared analysis logic - file data, 3-tier routing, results (v2.13.0+)
86
91
  │ ├── diff-analysis-orchestrator.js # Intelligent batch orchestration via Opus (v2.20.0)
87
92
  │ ├── claude-client.js # Claude CLI wrapper - spawn, retry, model override
@@ -178,6 +183,7 @@ preset config (.claude/presets/{name}/config.json) ← HIGHEST PRIORITY
178
183
  **Team-wide remote config** ([`mscope-S-L/git-hooks-config`](https://github.com/mscope-S-L/git-hooks-config)):
179
184
 
180
185
  - `labels.json` — PR label rules (fetched by `remote-config.js`, consumed by `label-resolver.js`)
186
+ - `formatters.json` — preset-to-tools mapping for linting/formatting (fetched by `remote-config.js`, consumed by `linter-runner.js`)
181
187
  - `permissions.json` — role-based authorization (fetched directly by `authorization.js`, fail-closed)
182
188
  - Changes take effect immediately across all governed repos — no tool update needed
183
189
 
@@ -218,6 +224,11 @@ preset config (.claude/presets/{name}/config.json) ← HIGHEST PRIORITY
218
224
  | Judge timeout | 120s | Per-judge call timeout |
219
225
  | PR analysis model | sonnet | Default, configurable via `config.prAnalysis.model` |
220
226
  | PR analysis timeout | 300s | Per-analysis Claude call |
227
+ | Linting enabled | true | Runs linters before Claude analysis |
228
+ | Linting auto-fix | true | Auto-fix and re-stage files |
229
+ | Linting fail on error | true | Block commit on linting errors |
230
+ | Linting fail on warn | false | Do not block on warnings |
231
+ | Linting timeout | 30s | Per-linter timeout |
221
232
 
222
233
  **Judge behavior (v2.20.0):**
223
234
 
@@ -299,6 +310,7 @@ consolidateResults()
299
310
  | `debug.js` | Debug toggle | `runSetDebug()` |
300
311
  | `telemetry-cmd.js` | Telemetry commands | `runShowTelemetry()`, `runClearTelemetry()` |
301
312
  | `diff-batch-info.js` | Batch info display | `runDiffBatchInfo()` |
313
+ | `lint.js` | Lint command | `runLint()`, `resolvePaths()` |
302
314
  | `help.js` | Help, AI help, report-issue | `runShowHelp()`, `showStaticHelp()`, `runShowVersion()` |
303
315
 
304
316
  **Utility Modules (`lib/utils/`):**
@@ -307,6 +319,8 @@ consolidateResults()
307
319
  | ------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
308
320
  | `lib/cli-metadata.js` | Command registry | `commands`, `buildCommandMap()`, `generateCompletionData()`, `PRESET_NAMES`, `HOOK_NAMES`, `BUMP_TYPES` |
309
321
  | `lib/config.js` | Config system | `getConfig()` |
322
+ | `tool-runner.js` | Generic tool executor | `isToolAvailable()`, `filterFilesByTool()`, `runTool()`, `runToolFix()`, `runToolWithAutoFix()`, `displayToolResult()` (v2.34.0) |
323
+ | `linter-runner.js` | Linter orchestration | `runLinters()`, `displayLintResults()`, `checkLinterAvailability()`, `getLinterToolsForPreset()`, `LINTER_TOOLS`, `PRESET_LINTERS`, `parsePrettierOutput()`, `parseEslintOutput()`, `parseSpotlessOutput()`, `parseSqlfluffOutput()`, `filesToSpotlessRegex()` (v2.34.0) |
310
324
  | `analysis-engine.js` | Shared analysis logic | `buildFileData()`, `buildFilesData()`, `runAnalysis()`, `consolidateResults()`, `hasBlockingIssues()`, `hasAnyIssues()`, `displayResults()`, `displayIssueSummary()` (v2.13.0+) |
311
325
  | `diff-analysis-orchestrator.js` | Intelligent batch orchestration | `orchestrateBatches()`, `buildFileOverview()`, `detectDependencies()` (v2.20.0) |
312
326
  | `claude-client.js` | Claude CLI wrapper | `analyzeCode()`, `executeClaudeWithRetry()`, `extractJSON()` — spawn, retry, model override |
@@ -346,16 +360,38 @@ consolidateResults()
346
360
  7. **Adapter Pattern**: `git-operations.js` abstracts git commands into JS functions
347
361
  8. **Singleton Pattern**: `config.js` loads configuration once per execution
348
362
  9. **Guard Pattern**: `authorization.js` — fail-closed gate in `bin/claude-hooks` before command dispatch; static `PROTECTED_COMMANDS` set avoids API calls for unprotected commands; permissions sourced from `mscope-S-L/git-hooks-config/permissions.json`
349
- 10. **Remote Config Pattern**: `remote-config.js` — fetches JSON from `mscope-S-L/git-hooks-config`, caches per-process (including nulls), graceful degradation (warn + return null); `label-resolver.js` — callers receive config via dependency injection and decide fallback
363
+ 10. **Remote Config Pattern**: `remote-config.js` — fetches JSON from `mscope-S-L/git-hooks-config`, caches per-process (including nulls), graceful degradation (warn + return null); `label-resolver.js` and `linter-runner.js` — callers fetch remote config and decide fallback (`labels.json` for PR labels, `formatters.json` for preset-to-tools mapping)
364
+ 11. **Pipeline Pattern**: `tool-runner.js` + `linter-runner.js` — generic tool execution infrastructure; formatters (Prettier) and linters (ESLint, Spotless, sqlfluff) share the same resolve → spawn → parse → fix → re-stage pipeline. Tool definitions are data objects, not classes. Preset-to-tools mapping fetched from `mscope-S-L/git-hooks-config/formatters.json` (remote config priority, local fallback).
350
365
 
351
366
  ### Key Data Flows
352
367
 
368
+ **Flow 0: Pre-commit linting (v2.34.0)**
369
+
370
+ ```
371
+ git commit
372
+ → hook reads staged files
373
+ → filters by preset extensions + size
374
+
375
+ → LINTING STEP (fast, deterministic)
376
+ → getLinterToolsForPreset(presetName):
377
+ 1. fetchRemoteConfig('formatters.json') → remote presetTools mapping
378
+ 2. fallback to local PRESET_LINTERS if remote unavailable
379
+ → for each tool (formatters first, then linters):
380
+ isToolAvailable() → not found? warn + install hint → skip
381
+ filterFilesByTool() → matching files
382
+ runToolWithAutoFix() → check → auto-fix → re-stage → re-check
383
+ → unfixable issues forwarded to judge
384
+
385
+ → continues to Claude analysis
386
+ ```
387
+
353
388
  **Flow 1: Pre-commit with blocking**
354
389
 
355
390
  ```
356
391
  git commit
357
392
  → hook reads staged files
358
393
  → filters by preset extensions
394
+ → [linting step — see Flow 0]
359
395
  → builds prompt with diff
360
396
  → Claude analyzes → detects issues
361
397
  → judge evaluates ALL issues (any severity):
@@ -1107,6 +1143,13 @@ claude-hooks presets # List available presets
1107
1143
  claude-hooks --set-preset backend # Change preset
1108
1144
  claude-hooks preset current # View current preset
1109
1145
 
1146
+ # Linting
1147
+ claude-hooks lint # Lint staged files
1148
+ claude-hooks lint src/ # Lint all files in directory
1149
+ claude-hooks lint src/ lib/utils/ # Multiple directories
1150
+ claude-hooks lint file1.js file2.js # Specific files
1151
+ claude-hooks lint src/ file.js lib/ # Mix of dirs and files
1152
+
1110
1153
  # Analysis and PRs
1111
1154
  claude-hooks analyze-diff [branch] # Analyze diff for PR
1112
1155
  claude-hooks analyze-pr <pr-url> # Analyze GitHub PR with team guidelines
package/README.md CHANGED
@@ -82,6 +82,43 @@ export GITHUB_TOKEN="ghp_..."
82
82
 
83
83
  Create token at https://github.com/settings/tokens with scopes: `repo`, `read:org`
84
84
 
85
+ ### Linting & Formatting
86
+
87
+ Runs formatters and linters on staged files automatically during pre-commit, or on demand:
88
+
89
+ ```bash
90
+ # Lint staged files (default)
91
+ claude-hooks lint
92
+
93
+ # Lint all files in a directory
94
+ claude-hooks lint src/
95
+
96
+ # Lint specific files
97
+ claude-hooks lint file1.js file2.java
98
+
99
+ # Mix of directories and files
100
+ claude-hooks lint src/ lib/utils/ file.js
101
+ ```
102
+
103
+ **Tools per preset** (configured via [remote config](https://github.com/mscope-S-L/git-hooks-config)):
104
+
105
+ | Preset | Tools |
106
+ | ----------- | ----------------------------- |
107
+ | `frontend` | Prettier, ESLint |
108
+ | `backend` | Spotless |
109
+ | `fullstack` | Prettier, ESLint, Spotless |
110
+ | `database` | sqlfluff |
111
+ | `ai` | Prettier, ESLint |
112
+ | `default` | Prettier, ESLint |
113
+
114
+ **Behavior:**
115
+
116
+ - Formatters run first (Prettier), then linters (ESLint) — format before lint
117
+ - Auto-fix enabled by default — fixes and re-stages files automatically
118
+ - Missing tools are skipped with install instructions (never blocks)
119
+ - Unfixable issues are forwarded to the Claude judge for semantic resolution
120
+ - Tool-to-preset mapping is fetched from remote config (team-controlled, no release needed)
121
+
85
122
  ### Analyze Code (Interactive Review)
86
123
 
87
124
  Run interactive code analysis before committing:
package/bin/claude-hooks CHANGED
@@ -187,6 +187,7 @@ async function main() {
187
187
  if (
188
188
  [
189
189
  'install',
190
+ 'lint',
190
191
  'analyze-diff',
191
192
  'analyze-pr',
192
193
  'back-merge',
@@ -97,6 +97,15 @@ export const commands = [
97
97
  description: 'Show hook status',
98
98
  handler: async () => (await import('./commands/hooks.js')).runStatus
99
99
  },
100
+ {
101
+ name: 'lint',
102
+ description: 'Run linters on staged files, directories, or specific files',
103
+ handler: async () => (await import('./commands/lint.js')).runLint,
104
+ args: {
105
+ name: 'paths',
106
+ completion: "find . -maxdepth 3 -type d -not -path '*/\\.*' -not -path '*/node_modules/*'"
107
+ }
108
+ },
100
109
  {
101
110
  name: 'analyze',
102
111
  description: 'Analyze code interactively before committing',
@@ -32,6 +32,7 @@ import {
32
32
  } from './helpers.js';
33
33
  import { runSetupGitHub } from './setup-github.js';
34
34
  import { generateCompletionData } from '../cli-metadata.js';
35
+ import { getConfig } from '../config.js';
35
36
 
36
37
  /**
37
38
  * Function to check version (used by hooks)
@@ -186,6 +187,17 @@ async function checkAndInstallDependencies(skipAuth = false) {
186
187
  error('npm is not installed.');
187
188
  }
188
189
 
190
+ // Check Maven (optional — needed for backend/fullstack presets with Spotless)
191
+ try {
192
+ const mvnVersion = execSync('mvn --version', { encoding: 'utf8', timeout: 5000 })
193
+ .split('\n')[0].trim();
194
+ success(`${mvnVersion}`);
195
+ } catch {
196
+ warning('Maven (mvn) not found — required for Spotless linting in backend/fullstack presets');
197
+ info(' Install: https://maven.apache.org/install.html');
198
+ info(' Or via package manager: brew install maven / choco install maven / apt install maven');
199
+ }
200
+
189
201
  // v2.0.0+: jq and curl are no longer needed (pure Node.js implementation)
190
202
 
191
203
  // Check Git
@@ -655,6 +667,18 @@ export async function runInstall(args) {
655
667
  // Install shell completions
656
668
  installCompletions();
657
669
 
670
+ // Check linter toolchain availability for the selected preset
671
+ try {
672
+ const config = await getConfig();
673
+ const presetName = config.preset || 'default';
674
+ if (config.linting?.enabled !== false) {
675
+ const { checkLinterAvailability } = await import('../utils/linter-runner.js');
676
+ await checkLinterAvailability(presetName);
677
+ }
678
+ } catch {
679
+ // Non-fatal — linter check failure should not block installation
680
+ }
681
+
658
682
  success('Claude Git Hooks installed successfully! 🎉');
659
683
  console.log('\nRun claude-hooks --help to see all available commands.');
660
684
 
@@ -0,0 +1,187 @@
1
+ /**
2
+ * File: lint.js
3
+ * Purpose: CLI command to run linters on files or directories
4
+ *
5
+ * Usage:
6
+ * claude-hooks lint # lint staged files
7
+ * claude-hooks lint src/ # lint all files in src/
8
+ * claude-hooks lint src/ lib/utils/ # multiple directories
9
+ * claude-hooks lint file1.js file2.java # specific files
10
+ * claude-hooks lint src/ file3.js lib/ # mix of dirs and files
11
+ *
12
+ * Path resolution (like git add):
13
+ * - Directories → walk and collect files matching preset extensions
14
+ * - Files → use directly
15
+ * - No args → fall back to staged files
16
+ *
17
+ * Dependencies:
18
+ * - linter-runner: Linter orchestration
19
+ * - git-operations: Staged files, repo root
20
+ * - file-utils: Directory walking
21
+ * - preset-loader: Extension filtering
22
+ * - config: Linting configuration
23
+ * - helpers: checkGitRepo, colors
24
+ */
25
+
26
+ import fs from 'fs';
27
+ import path from 'path';
28
+ import { checkGitRepo, error, info } from './helpers.js';
29
+ import { getConfig } from '../config.js';
30
+ import { loadPreset } from '../utils/preset-loader.js';
31
+ import { getStagedFiles, getRepoRoot } from '../utils/git-operations.js';
32
+ import { runLinters, displayLintResults } from '../utils/linter-runner.js';
33
+ import logger from '../utils/logger.js';
34
+
35
+ /**
36
+ * Resolve user-provided paths into a flat list of files
37
+ * Handles directories (walked recursively), individual files, and mixtures.
38
+ *
39
+ * @param {string[]} paths - User-provided paths (files and/or directories)
40
+ * @param {string[]} extensions - Allowed file extensions from preset
41
+ * @param {string} repoRoot - Repository root for relative path resolution
42
+ * @returns {string[]} Resolved file paths (relative to cwd)
43
+ */
44
+ export function resolvePaths(paths, extensions, _repoRoot) {
45
+ const files = new Set();
46
+ const extSet = new Set(extensions.map((e) => e.toLowerCase()));
47
+
48
+ for (const userPath of paths) {
49
+ const resolved = path.resolve(userPath);
50
+
51
+ if (!fs.existsSync(resolved)) {
52
+ logger.warning(`Path not found: ${userPath}`);
53
+ continue;
54
+ }
55
+
56
+ const stat = fs.statSync(resolved);
57
+
58
+ if (stat.isFile()) {
59
+ // Accept file if it matches preset extensions, or if no extensions filter
60
+ const ext = path.extname(resolved).toLowerCase();
61
+ if (extSet.size === 0 || extSet.has(ext)) {
62
+ files.add(path.relative(process.cwd(), resolved));
63
+ } else {
64
+ logger.debug('lint - resolvePaths', `Skipping ${userPath}: extension ${ext} not in preset`);
65
+ }
66
+ } else if (stat.isDirectory()) {
67
+ // Walk directory and collect matching files
68
+ _walkForFiles(resolved, extSet, files);
69
+ }
70
+ }
71
+
72
+ return Array.from(files);
73
+ }
74
+
75
+ /**
76
+ * Recursively walk a directory collecting files that match extensions
77
+ *
78
+ * @param {string} dir - Directory to walk
79
+ * @param {Set<string>} extSet - Allowed extensions
80
+ * @param {Set<string>} files - Accumulator set of relative file paths
81
+ * @param {number} [depth] - Current depth (max 10)
82
+ */
83
+ function _walkForFiles(dir, extSet, files, depth = 0) {
84
+ if (depth > 10) return;
85
+
86
+ try {
87
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
88
+
89
+ for (const entry of entries) {
90
+ // Skip hidden dirs, node_modules, target, build
91
+ if (
92
+ entry.name.startsWith('.') ||
93
+ entry.name === 'node_modules' ||
94
+ entry.name === 'target' ||
95
+ entry.name === 'build' ||
96
+ entry.name === 'dist'
97
+ ) {
98
+ continue;
99
+ }
100
+
101
+ const fullPath = path.join(dir, entry.name);
102
+
103
+ if (entry.isDirectory()) {
104
+ _walkForFiles(fullPath, extSet, files, depth + 1);
105
+ } else if (entry.isFile()) {
106
+ const ext = path.extname(entry.name).toLowerCase();
107
+ if (extSet.size === 0 || extSet.has(ext)) {
108
+ files.add(path.relative(process.cwd(), fullPath));
109
+ }
110
+ }
111
+ }
112
+ } catch (err) {
113
+ logger.debug('lint - _walkForFiles', `Cannot read directory: ${dir}`, {
114
+ error: err.message
115
+ });
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Main lint command handler
121
+ *
122
+ * @param {string[]} args - CLI arguments (paths and flags)
123
+ */
124
+ export async function runLint(args = []) {
125
+ if (!checkGitRepo()) {
126
+ error('Not a git repository');
127
+ process.exit(1);
128
+ }
129
+
130
+ const config = await getConfig();
131
+
132
+ if (config.system?.debug) {
133
+ logger.setDebugMode(true);
134
+ }
135
+
136
+ if (config.linting?.enabled === false) {
137
+ info('Linting is disabled in configuration');
138
+ return;
139
+ }
140
+
141
+ const repoRoot = getRepoRoot();
142
+ const presetName = config.preset || 'default';
143
+ const { metadata } = await loadPreset(presetName);
144
+
145
+ // Separate flags from paths
146
+ const paths = args.filter((a) => !a.startsWith('--'));
147
+
148
+ let filesToLint;
149
+
150
+ if (paths.length === 0) {
151
+ // No paths → lint staged files
152
+ info('No paths specified — linting staged files');
153
+ const stagedFiles = getStagedFiles({ extensions: metadata.fileExtensions });
154
+
155
+ if (stagedFiles.length === 0) {
156
+ info('No staged files to lint');
157
+ return;
158
+ }
159
+
160
+ filesToLint = stagedFiles;
161
+ } else {
162
+ // Resolve user-provided paths
163
+ filesToLint = resolvePaths(paths, metadata.fileExtensions, repoRoot);
164
+
165
+ if (filesToLint.length === 0) {
166
+ info('No matching files found in specified paths');
167
+ return;
168
+ }
169
+ }
170
+
171
+ info(`🎯 Linting ${filesToLint.length} file(s) with '${metadata.displayName}' preset`);
172
+
173
+ const lintResult = await runLinters(filesToLint, config, presetName);
174
+ displayLintResults(lintResult);
175
+
176
+ // Exit with error code if linting failed
177
+ const failOnError = config.linting?.failOnError !== false;
178
+ const failOnWarning = config.linting?.failOnWarning === true;
179
+
180
+ if (failOnError && lintResult.totalErrors > 0) {
181
+ process.exit(1);
182
+ }
183
+
184
+ if (failOnWarning && lintResult.totalWarnings > 0) {
185
+ process.exit(1);
186
+ }
187
+ }
package/lib/config.js CHANGED
@@ -84,6 +84,13 @@ const HARDCODED = {
84
84
  'documentation',
85
85
  'testing'
86
86
  ]
87
+ },
88
+ linting: {
89
+ enabled: true, // Run linters before Claude analysis
90
+ autoFix: true, // Auto-fix and re-stage
91
+ failOnError: true, // Block commit on linting errors
92
+ failOnWarning: false, // Do not block on warnings
93
+ timeout: 30000 // 30s per linter
87
94
  }
88
95
  };
89
96