---
description: Run linting checks and auto-fix lint errors
argument-hint: '[scope] [--fix] [--diff] [--strict] [--force]'
allowed-tools: Bash, Read, Edit, Write, Task
---

# Lint Execution for: $ARGUMENTS

## Overview

The `/lint` command runs linting checks using the unified `ai-toolkit lint` CLI. This provides consistent linting across all repositories that use ai-toolkit.

**CLI Commands Available:**

```bash
# Run lint on staged files (default)
npx ai-toolkit lint

# Run lint on all files
npx ai-toolkit lint --scope all

# Run lint with auto-fix
npx ai-toolkit lint --fix

# Run lint on changed files (staged + unstaged)
npx ai-toolkit lint --scope changed

# Verbose output
npx ai-toolkit lint --verbose

# Specific files
npx ai-toolkit lint --files "src/foo.ts,src/bar.ts"
```

**Pre-commit hook (unified):**

```bash
# Runs: security → lint → typecheck → test
npx ai-toolkit hook

# Or specific checks only
npx ai-toolkit hook --lint
npx ai-toolkit hook --security --lint
```

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **Scope**: Optional with smart defaults
  - `.` or empty → Staged files (default)
  - `--scope all` → All files in repo
  - `--scope changed` → Git changed files (staged + unstaged)
  - File pattern or directory → Custom scope
- **--fix**: Auto-fix all fixable lint errors
- **--diff**: Only lint git-changed files (alias for `--scope changed`)
- **--strict**: Fail fast on first lint error
- **--force**: Fix ALL issues including warnings (JSDoc, etc.) using parallel subagents

**Argument parsing:**

```bash
SCOPE="staged"
FIX_MODE=false
FORCE_MODE=false
STRICT_MODE=false

# Parse arguments
for arg in $ARGUMENTS; do
  case "$arg" in
    --fix) FIX_MODE=true ;;
    --force) FORCE_MODE=true; FIX_MODE=true ;;
    --diff|--changed) SCOPE="changed" ;;
    --all) SCOPE="all" ;;
    --strict) STRICT_MODE=true ;;
    *) CUSTOM_SCOPE="$arg" ;;
  esac
done
```

## Phase 1: Run Linting

### 1.1 Standard Lint (Default)

Run the unified lint command:

```bash
# Determine scope
if [ -n "$CUSTOM_SCOPE" ]; then
  npx ai-toolkit lint --files "$CUSTOM_SCOPE" ${FIX_MODE:+--fix} ${VERBOSE:+--verbose}
else
  npx ai-toolkit lint --scope "$SCOPE" ${FIX_MODE:+--fix} ${VERBOSE:+--verbose}
fi
```

**Output formats:**

- Human-readable (default): Colored output with file locations
- JSON: `--format json` for programmatic parsing
- Claude: `--format claude` for PostToolUse hooks

### 1.2 Check Results

```bash
LINT_EXIT=$?

if [ $LINT_EXIT -eq 0 ]; then
  echo "✓ All lint checks passed"
  exit 0
fi

# Count errors vs warnings
ERRORS=$(npx ai-toolkit lint --scope "$SCOPE" --format json 2>/dev/null | jq '.summary.totalErrors')
WARNINGS=$(npx ai-toolkit lint --scope "$SCOPE" --format json 2>/dev/null | jq '.summary.totalWarnings')

echo "Lint results:"
echo "  Errors: $ERRORS"
echo "  Warnings: $WARNINGS"
```

## Phase 2: Force Mode (--force)

**Purpose:** Fix ALL lint issues including warnings that `--fix` cannot auto-fix (JSDoc missing docs, complex refactoring, etc.).

**Strategy:** Spawn parallel subagents using worktrees to fix different areas of the codebase concurrently.

### 2.1 Identify Work Areas

Analyze lint output to partition work:

```bash
# Get files with issues grouped by directory
npx ai-toolkit lint --scope "$SCOPE" --format json | \
  jq -r '.results[].issues[] | .file' | \
  sort -u | \
  xargs -I {} dirname {} | \
  sort | uniq -c | sort -rn
```

**Partitioning strategy:**

1. **By domain/module**: `src/cli/`, `src/domains/`, `src/utils/`, etc.
2. **By issue count**: Balance workload across subagents
3. **By file type**: TypeScript, markdown, YAML separately

### 2.2 Create Worktrees for Parallel Work

For each work partition, create a worktree:

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
WORKTREE_BASE=".worktree/lint-fix-$TIMESTAMP"

# Create worktrees for each partition
mkdir -p "$WORKTREE_BASE"

# Example partitions:
# - lint-cli: src/cli/**
# - lint-domains: src/domains/**
# - lint-utils: src/utils/**
# - lint-tasks: src/tasks/**
```

### 2.3 Spawn Subagents

Launch parallel subagents, each working in their own worktree:

**Subagent task template:**

```text
You are a lint-fix subagent working in worktree: {worktree_path}

Your task: Fix ALL lint warnings in these files:
{file_list}

Focus on:
1. JSDoc warnings - Add missing @param, @returns, @param types
2. Import ordering - Fix perfectionist/sort-imports
3. Unused variables - Remove or prefix with underscore
4. Type annotations - Add explicit types where missing

Rules:
- Only modify files in your assigned area
- Do NOT modify files outside your scope
- Run `npx ai-toolkit lint --files "{files}"` to verify fixes
- Report back: files fixed, remaining issues, any blockers

When done, create PROGRESS.md in worktree with:
- Files modified
- Issues fixed (count by type)
- Any remaining issues that couldn't be fixed
```

**Parallel execution:**

```bash
# Launch subagents in parallel (using Task tool with multiple invocations)
# Each subagent gets:
# - Worktree path
# - File list to fix
# - Expected issue types

# Example: 4 parallel subagents
PARTITIONS=("src/cli" "src/domains" "src/utils" "src/tasks")

for partition in "${PARTITIONS[@]}"; do
  # Subagent works in worktree, fixes issues, reports back
  # Main agent monitors progress
done
```

### 2.4 Merge Results

After subagents complete:

1. **Review changes**: Each worktree contains fixes
2. **Verify lint passes**: Run lint on each worktree
3. **Merge into main**: Use `/worktree --merge` pattern
4. **Cleanup**: Remove worktrees after successful merge

```bash
# Merge from each worktree
for worktree in "$WORKTREE_BASE"/*; do
  if [ -d "$worktree" ]; then
    # Copy fixed files back
    rsync -av --include='*.ts' --include='*/' --exclude='*' \
      "$worktree/src/" "src/"
  fi
done

# Verify all fixes
npx ai-toolkit lint --scope "$SCOPE"

# Cleanup worktrees
rm -rf "$WORKTREE_BASE"
```

### 2.5 Force Mode Workflow Summary

```text
/lint --force workflow:

1. Run initial lint → identify all issues
2. Partition files by directory/module
3. Create worktrees for parallel work
4. Spawn subagents (one per partition)
5. Each subagent:
   - Fixes all warnings in their area
   - Runs lint to verify
   - Reports progress
6. Main agent:
   - Monitors subagent progress
   - Merges successful fixes
   - Re-runs full lint
7. Cleanup worktrees
8. Report final results
```

## Phase 3: Manual Fix Guidance

If issues remain after auto-fix (or when `--force` is not used):

### Common JSDoc Warnings

**Missing @returns:**

```typescript
// Before (warning)
/**
 * Get user by ID
 * @param id - User identifier
 */
function getUser(id: string): User { ... }

// After (fixed)
/**
 * Get user by ID
 * @param id - User identifier
 * @returns User object if found
 */
function getUser(id: string): User { ... }
```

**Missing @param type:**

```typescript
// Before (warning)
/**
 * Process data
 * @param data
 */
function process(data: Data): void { ... }

// After (fixed)
/**
 * Process data
 * @param {Data} data - Data to process
 */
function process(data: Data): void { ... }
```

### Import Ordering

ESLint perfectionist/sort-imports expects:

```typescript
// 1. Type imports (with 'type' keyword)
import type { Config } from './types.js';

// 2. External packages
import chalk from 'chalk';
import { Command } from 'commander';

// 3. Internal absolute imports (@src/...)
import { logger } from '@src/utils/logger.js';

// 4. Internal relative imports
import { helper } from './helper.js';
```

### Unused Variables

```typescript
// Option 1: Remove if truly unused
// const unused = 'value'; // DELETE

// Option 2: Prefix with underscore if intentionally unused
const _intentionallyUnused = 'for future use';

// Option 3: Use in catch blocks
try {
  // ...
} catch {
  // Error variable removed (was: catch (error))
}
```

## Phase 4: Generate Report

**Report location:** `${TMPDIR:-/tmp}/lint-report-$(date +%Y%m%d-%H%M%S).md`

```markdown
# Lint Report

**Generated:** [timestamp]
**Scope:** [scope]
**Mode:** [standard | --fix | --force]

## Summary

- **Files Checked:** [count]
- **Errors:** [count]
- **Warnings:** [count]
- **Auto-fixed:** [count]

## Results by Linter

### ESLint (TypeScript)

- Files: [count]
- Errors: [count]
- Warnings: [count]

### Markdown

- Files: [count]
- Issues: [count]

### YAML

- Files: [count]
- Issues: [count]

## Force Mode Results

[If --force was used]

### Subagent Summary

| Partition   | Files Fixed | Issues Resolved | Duration |
| ----------- | ----------- | --------------- | -------- |
| src/cli     | 12          | 45              | 2m 30s   |
| src/domains | 8           | 32              | 1m 45s   |
| ...         | ...         | ...             | ...      |

### Remaining Issues

[Any issues that couldn't be auto-fixed]

## Recommendations

- [Actionable suggestions]
```

## Quick Reference

**Common workflows:**

```bash
# Check staged files (pre-commit style)
/lint

# Fix all auto-fixable issues
/lint --fix

# Fix EVERYTHING including warnings (parallel subagents)
/lint --force

# Check specific directory
/lint src/cli/

# Check changed files only
/lint --diff

# Strict mode (fail on first error)
/lint --strict
```

**CLI equivalents:**

```bash
# Slash command → CLI
/lint           → npx ai-toolkit lint --scope staged
/lint --fix     → npx ai-toolkit lint --scope staged --fix
/lint --diff    → npx ai-toolkit lint --scope changed
/lint --all     → npx ai-toolkit lint --scope all
/lint src/      → npx ai-toolkit lint --files "src/**/*.ts"
```

**What gets auto-fixed (--fix):**

- Import ordering (perfectionist/sort-imports)
- Formatting (prettier)
- Simple ESLint auto-fixable rules
- Trailing whitespace, semicolons

**What requires --force or manual fix:**

- JSDoc missing documentation (@param, @returns, @param types)
- Unused variables (decision required)
- Complex type errors
- Logic/security issues

**Force mode subagent strategy:**

1. Partition codebase by directory
2. Create isolated worktrees
3. Spawn parallel subagents
4. Each fixes their area
5. Merge successful fixes
6. Cleanup worktrees

## Integration

### With Pre-commit Hook

The pre-commit hook uses the unified hook command:

```bash
# .husky/pre-commit
npx ai-toolkit hook
```

This runs security → lint → typecheck → test in sequence.

### With Claude Code PostToolUse

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "npx ai-toolkit lint-hook $CLAUDE_TOOL_OUTPUT_FILE",
            "statusMessage": "Checking modified file..."
          }
        ]
      }
    ]
  }
}
```

The `lint-hook` command runs both linting AND security scanning on modified files.

### With Task Master

After completing lint fixes:

```bash
# Mark task as done
mcp__task_master_ai__set_task_status --id "X.Y" --status "done"

# Add implementation notes
mcp__task_master_ai__update_subtask --id "X.Y" --prompt "Fixed 45 JSDoc warnings using parallel subagents"
```

## Error Handling

- **Lint tools not found**: Suggests `npm install` commands
- **No files to lint**: Reports clean exit
- **Force mode subagent fails**: Main agent continues with other partitions
- **Worktree creation fails**: Falls back to sequential fixing
- **Merge conflicts**: Reports to user for manual resolution

## Related Commands

- [/worktree](./worktree.md) - Manage worktrees for parallel work
- [/commit](./commit.md) - Commit changes after fixing
- [/qa](./qa.md) - Full QA including lint checks
- [/cover](./cover.md) - Check test coverage
