Skip to Content
Hooks

Hooks

Hooks are automated quality checks that run as you code — no manual invocation needed. AI Kit generates hooks in .claude/settings.local.json based on your detected tools and chosen profile.

How They Work

Hooks fire on specific events during your Claude Code session:

EventWhen It FiresExample
SessionStartWhen a new Claude Code session beginsEcho tech stack and project context
PreToolUseBefore a tool runsWarning before git push
PostToolUseAfter a file is edited or writtenAuto-format, type-check
PostCompactAfter context compactionRe-echo tech stack context
StopAfter each AI response completesAudit modified files for console.log

Hooks are configured in .claude/settings.local.json, which is gitignored by default — your hook preferences are local and won’t affect teammates.


Hook Profiles

During ai-kit init, you choose a hook profile that controls what automated checks run:

Minimal

Best for: fast iteration, prototyping, or when you want minimal friction.

HookEventWhat It Does
Session contextSessionStartEchoes tech stack, scripts, and last scan date
Auto-formatPostToolUseFormats edited files with Prettier or Biome
Git push safetyPreToolUseReminder to review changes before pushing

Standard (default)

Best for: everyday development with a safety net.

HookEventWhat It Does
Session contextSessionStartEchoes tech stack, scripts, and last scan date
Auto-formatPostToolUseFormats edited files with Prettier or Biome
TypeScript checkPostToolUseRuns tsc --noEmit on .ts/.tsx files after edits
Console.log warningPostToolUseFlags console.log statements in edited files
Mistakes auto-capturePostToolUseLogs build/lint failures to docs/mistakes-log.md
Bundle impact warningPostToolUseWarns when new dependencies are added to package.json
Pre-edit reminderPreToolUseWarns before editing files over 150 lines to encourage reading first
Context recoveryPostCompactRe-echoes tech stack summary after context compaction
Git push safetyPreToolUseReminder to review changes before pushing

Strict

Best for: production code, pre-merge reviews, or teams with high quality bars.

HookEventWhat It Does
Session contextSessionStartEchoes tech stack, scripts, and last scan date
Auto-formatPostToolUseFormats edited files with Prettier or Biome
TypeScript checkPostToolUseRuns tsc --noEmit on .ts/.tsx files after edits
ESLint checkPostToolUseRuns ESLint with zero warnings on edited files
Console.log warningPostToolUseFlags console.log statements in edited files
Mistakes auto-capturePostToolUseLogs build/lint failures to docs/mistakes-log.md
Bundle impact warningPostToolUseWarns when new dependencies are added to package.json
Pre-edit reminderPreToolUseWarns before editing files over 150 lines to encourage reading first
Config weakening guardPostToolUseFlags eslint-disable, @ts-ignore, and strict: false additions
Credential scanPostToolUseDetects hardcoded API keys and secrets in edited files
Context recoveryPostCompactRe-echoes tech stack summary after context compaction
Console.log auditStopScans all modified files for console.log at end of response
Pre-commit AI reviewPreToolUseChecks staged files for any types, console.log, TODOs without tickets
Git push safetyPreToolUseReminder to review changes before pushing

Session Context (SessionStart)

The SessionStart hook fires once when you open Claude Code in your project. It echoes your project context so the AI has full awareness from the first prompt:

📋 ai-kit v1.11.0 | Stack: Next.js 16.2 (app router) + sitecore-xmc-v2 + tailwind PM: pnpm | Scripts: dev, build, test, lint, typecheck Last scan: 2026-04-08

What it includes

InfoSource
AI Kit versionBaked into the hook at generation time
Tech stackFramework, router type, CMS, styling — from project scan
Package managernpm, pnpm, yarn, or bun
Available scriptsFirst 8 scripts from package.json
Monorepo toolShown if monorepo detected (Turborepo, Nx, etc.)
Last scan dateRead from ai-kit.config.json at runtime

Why it matters

Without the session init hook, the AI has to discover your stack by reading files — wasting the first few turns of every session. With it, Claude knows “this is a Next.js 16 App Router + Sitecore project” instantly and follows the right patterns from the start.

This hook runs on all profiles (minimal, standard, strict).


Formatter Auto-Detection

AI Kit detects your project’s formatter and generates the right hook:

FormatterDetectionHook Command
Biome@biomejs/biome in dependenciesnpx @biomejs/biome check --write --unsafe
Prettierprettier in dependenciesnpx prettier --write

If both are detected, Biome takes priority. If neither is found, the auto-format hook is skipped.


Changing Your Profile

Option 1: Re-run init

npx @mikulgohil/ai-kit init

Select a different hook profile during the prompts.

Option 2: Edit directly

Edit .claude/settings.local.json to add, remove, or modify hooks manually. The file follows this structure:

{ "hooks": { "PreToolUse": [ { "matcher": "Bash(git push*)", "hooks": [ { "type": "command", "command": "echo '⚠️ Review your changes before pushing.'" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true" } ] } ] } }

Disabling a Hook

Remove or comment out the hook entry in .claude/settings.local.json. Since the file is gitignored, your changes are local only.


Hook Behavior Details

Auto-Format

Runs immediately after every Edit or Write tool call. Uses $CLAUDE_FILE_PATH to format only the changed file. Errors are silenced (2>/dev/null || true) so a format failure never blocks your work.

TypeScript Check

Runs tsc --noEmit after .ts or .tsx files are edited. Output is truncated to the first 20 lines to avoid flooding the context. Only available in standard and strict profiles.

Console.log Warning

Uses grep -n to find console.log statements in the edited file and prints a warning. This is a soft check — it doesn’t block anything, just makes you aware.

ESLint Check

Runs ESLint with --max-warnings 0 on the edited file. Only available in strict profile. Output is truncated to 15 lines.

Mistakes Auto-Capture

Fires after every Bash tool call. When the command exits with a non-zero exit code, the hook checks if the output matches common build/lint error patterns:

PatternCatches
error TS, tscTypeScript compilation errors
ESLint, eslint, Lint errorLinting failures
Build error, build failed, ELIFECYCLEBuild failures
Module not found, Cannot find moduleMissing dependency errors
SyntaxError, TypeErrorRuntime-detectable code errors

When a match is found, the hook auto-appends a timestamped entry to docs/mistakes-log.md:

### 2026-03-25 14:30 — Build/lint failure (auto-captured) - **What happened**: Command exited with code 2 - **Error preview**: \`\`\` src/components/Hero.tsx(12,5): error TS2322: Type 'string' is not assignable... \`\`\` - **Root cause**: <!-- TODO: Fill in after investigating --> - **Fix**: <!-- TODO: How was it resolved? --> - **Lesson**: <!-- TODO: What to do differently -->

The error preview shows the first 3 lines containing “error” from the output. The TODO fields are left for you to fill in — this is where the real learning happens. Over time, your mistakes log builds organically without any manual effort.

Available in standard and strict profiles. Requires docs/mistakes-log.md to exist (scaffolded by ai-kit init).

Bundle Impact Warning

Fires after any edit to package.json. Uses git diff to detect newly added dependency lines and prints a warning listing the package names.

⚠ New dependencies detected in package.json: + lodash + date-fns Check bundle impact before committing — run /bundle-check to analyze.

This is a soft check — it does not block any action, just surfaces new additions at the moment they’re added so you can evaluate bundle impact early. Available in standard and strict profiles.

Pre-Commit AI Review

Fires before any git commit command. Scans all staged .ts, .tsx, .js, and .jsx files for common quality issues:

CheckWhat It Finds
any typesTypeScript any annotations that weaken type safety
console.logDebug logging left in staged code
TODOs without tickets// TODO comments that have no issue/ticket reference

Output is file-by-file:

⚠ Pre-commit review found issues in staged files: src/components/CheckoutForm.tsx line 14: any type — consider a specific type line 42: console.log — remove before committing src/lib/api.ts line 8: TODO without ticket — add a ticket reference or resolve Review and fix before committing, or run with --no-verify to skip.

The hook does not block the commit — it prints the findings and lets you decide. Available in strict profile only.

Git Push Safety

Fires before any git push command, printing a reminder to run tests and type-check first. Available in all profiles.


PostCompact Context Recovery

When conversations get long, Claude Code automatically compacts older context to free up the context window. The PostCompact hook fires after this happens, re-echoing critical project context:

  • Confirms CLAUDE.md is still loaded
  • Prints your tech stack summary from ai-kit.config.json (framework, CMS, styling)
  • Reminds about the /effort command for adjusting reasoning depth

This ensures your project conventions survive context compaction without manual re-prompting. Available in standard and strict profiles.

{ "PostCompact": [ { "matcher": "", "hooks": [ { "type": "command", "command": "echo '🔄 Context was compacted. Key reminders:' ..." } ] } ] }

Pre-Edit Investigation Reminder

Fires before every Edit or Write tool call. When the target file is over 150 lines, it prints a reminder to read the file before editing:

📖 Large file (312 lines): src/components/ProductCard.tsx Ensure you have read the full file before editing to avoid missing imports or breaking invariants.

This addresses a common failure mode in AI-assisted coding: making targeted edits to large files without reading the full context first, which leads to missed type dependencies, broken exports, or conflicting logic.

Available in standard and strict profiles.


Config Weakening Guard

Fires after every Edit or Write on TypeScript and JavaScript files. Detects additions that weaken code quality enforcement:

PatternWhat It Catches
eslint-disableDirectives that silence ESLint rules in-file
@ts-ignoreTypeScript errors silenced on the next line
@ts-nocheckTypeScript checking disabled for the entire file
"strict": falseTypeScript strict mode disabled in tsconfig.json
"noImplicitAny": falseImplicit any allowed in tsconfig.json

Output when triggered:

🛡️ Config guard triggered in src/lib/api.ts: ⚠️ eslint-disable: 2 directive(s) found — weakens linting ⚠️ TypeScript suppression: 1 @ts-ignore found Confirm these are intentional before committing.

The hook does not block the edit — it surfaces the issue for review. Available in strict profile only.


Credential Scan

Fires after every Edit or Write on .ts, .tsx, .js, .jsx, .json, .yaml, and .yml files. Scans for patterns that indicate hardcoded credentials:

  • apikey, api_key, secret_key, access_token, private_key, password, auth_token
  • Combined with an assignment (= or :) and a value longer than 8 characters
  • Excludes process.env references (these are the correct pattern)

Output when triggered:

🔐 Credential scan — potential secret detected in src/lib/client.ts: line 14: apiKey = "sk-live-a8f3k2m..." Move real secrets to .env and reference via process.env — never commit credentials.

Available in strict profile only.


Context Window Optimization

AI Kit injects CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=65 into .claude/settings.local.json for all profiles. This tells Claude Code to trigger automatic context compaction when the context window reaches 65% capacity, rather than the default (which lets it fill further before compacting).

{ "env": { "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "65" }, "hooks": { ... } }

Why 65%? On large Sitecore or Next.js projects with many file reads and long CLAUDE.md files, waiting until 80–90% capacity before compacting often results in losing critical context mid-task. Compacting at 65% keeps the context window healthier throughout long sessions.

You can override this by editing the value directly in .claude/settings.local.json.


Security Note

.claude/settings.local.json is automatically added to .gitignore by AI Kit. This prevents local hook configurations (which may contain machine-specific paths) from being committed. If you want to share hooks across your team, move them to .claude/settings.json instead.

Last updated on