agentleFS
MaGe1993MaGe1993/Claude-Code-Base-Harness/.claude/skills/hooks/SKILL.md

hooks

Skill1 starsChanged 5 months agoMITView on GitHub

Create or update Claude Code hook configurations — settings.json entries and companion scripts for lifecycle event automation, policy enforcement, logging, and validation.

22 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use yt-titles, outlines and 1 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • Samin12Skill

    yt-titles

    Generate high-performing YouTube title ideas based on the user's video content description, cross-referenced with your recent top-performing videos. Use this skill whenever the user wants YouTube title suggestions, asks "what should I title this video", "give me title ideas", "title options for my video about...", "help me name this video", brainstorming video titles, or any request involving YouTube title generation or optimization. Also trigger when the user mentions titling, naming, or headlining a YouTube video even casually.

    Also in 3 projects that use this

  • Clay-HHKSkill

    outlines

    Guarantee valid JSON/XML/code structure during generation, use Pydantic models for type-safe outputs, support local models (Transformers, vLLM), and maximize inference speed with Outlines - dottxt.ai's structured generation library

    Also in 3 projects that use this

  • BlockSkill

    frontend-design

    Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

11 rules. 0 are common, 2 are distinctive, and 9 are very specific to this project.

  • 0

    Common

    Most of the 21 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never put hook logic in CLAUDE.md or rules — hooks belong in settings.json.

    line 24
  2. Very specific:

    Always produce a complete hook entry in settings.json, never a partial snippet.

    line 25
  3. Very specific:

    Write complex logic to a companion script — do not inline multi-line shell logic in the command field.

    line 26
  4. Distinctive:

    Read stdin exactly once per script.

    line 29
  5. Very specific:

    Never use suppressOutput: true on security-relevant hook output.

    line 34
  6. Very specific:

    Always reference companion scripts via ${CLAUDE_PROJECT_DIR}/.claude/hooks/<name>.sh.

    line 35
  7. Distinctive:

    Always-relevant project context → always-loaded context (CLAUDE.md), not a hook.

    line 40
  8. Very specific:

    Default to command. Use http for external service integrations.

    line 97
  9. Very specific:

    Stop additional context: {"hookSpecificOutput":{"hookEventName":"Stop","additionalContext":"..."}}

    line 136
  10. Very specific:

    Write the complete settings.json hook entry.

    line 158
  11. Very specific:

    Write the companion script: read stdin once, process, output JSON if needed, exit with the correct code.

    line 159

“Common” is measured: kept by at least 6 in 10 of the 21 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Hook Create

1§ Purpose

Produce settings.json hook entries and companion scripts for Claude Code lifecycle automation. Use for deterministic actions tied to lifecycle events: blocking tool calls, validating output, logging activity, or running setup on session start.

2§ Use when

  • User wants to block, validate, or log a specific tool call.
  • User wants to run a check after file edits (lint, format, test).
  • User wants setup or teardown logic on session start or stop.
  • User wants to enforce policies beyond what permission rules allow.
  • User wants to audit or verify an existing hook against these conventions (companion script exists, exit-code semantics documented, correct event and matcher).
  • User says "hook", "intercept", "pre-tool", "post-tool", "block", "enforce", or "run a script when Claude...".

3§ Hard constraints

  • Never put hook logic in CLAUDE.md or rules — hooks belong in settings.json.
  • Always produce a complete hook entry in settings.json, never a partial snippet.
  • Write complex logic to a companion script — do not inline multi-line shell logic in the command field.
  • Exit 2 to block an action; exit 1 shows a warning but does not block.
  • Read stdin exactly once per script.
  • Include a bash shebang (#!/usr/bin/env bash) and set -euo pipefail in all bash companion scripts. Exception: hooks that must never block (cleanup, logging) may omit strict mode when every failure path is explicitly tolerated — document the omission in the script header.
  • Never use suppressOutput: true on security-relevant hook output.
  • Always reference companion scripts via ${CLAUDE_PROJECT_DIR}/.claude/hooks/<name>.sh.

4§ Decision gate

  • Behavioral guidance ("Claude should prefer...") → a rule, not a hook.
  • Permission allow/deny rules (not lifecycle hooks) → a settings.json permission entry, not a hook.
  • Always-relevant project context → always-loaded context (CLAUDE.md), not a hook.
  • Hook vs. rule unclear: hooks execute code deterministically on an event; rules are advisory. If the intended action is a shell command or HTTP call, it is a hook.

5§ Lifecycle events

Key events for most hook use cases:

EventFires whenCan block
PreToolUseBefore any tool executesYes
PostToolUseAfter a tool succeedsNo
PostToolUseFailureAfter a tool failsNo
PermissionRequestPermission dialog fires; before auto-mode approvalYes
PermissionDeniedTool call denied by auto modeNo
UserPromptSubmitBefore Claude processes the user promptYes — erases prompt; 30 s timeout
StopClaude finishes a turnYes — prevents stop; conversation continues
SessionStartSession begins, resumes, or follows /clear or compactionNo
SessionEndSession terminatesNo
SetupOne-time initialization via !claude --initNo
PreCompactBefore context compactionYes
PostCompactAfter context compaction completesNo
SubagentStartSubagent spawnedNo
SubagentStopSubagent finishesYes

Matchers for tool events (PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionDenied): exact tool name (Bash, Edit), pipe-separated list (Bash|Edit), JavaScript regex, or * for all. MCP tools use mcp__<server>__<tool> pattern. Matchers for SessionStart: startup, resume, clear, compact. Matchers for SessionEnd: clear, resume, logout, prompt_input_exit, other. Matchers for PreCompact and PostCompact: manual (user-triggered /compact), auto (context-threshold compaction). Matchers for Setup: init, maintenance. Matchers for SubagentStart and SubagentStop: agent type name (general-purpose, Explore, Plan, or any custom agent name). Events with no matcher support: Stop, UserPromptSubmit, PostToolBatch.

Claude Code documents further usable events beyond the table above — fetch the official hooks reference for their matchers and payloads before targeting one: Notification, MessageDisplay, UserPromptExpansion, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, ConfigChange, CwdChanged, FileChanged, WorktreeCreate, WorktreeRemove, Elicitation, ElicitationResult.

Optional if field on any handler for finer filtering using permission-rule syntax: Bash(rm *), Edit(*.ts) — one rule per handler, no compound operators.

6§ Handler types

TypeUse forStability
commandShell script (bash / PowerShell)Stable
httpPOST to a webhook URLStable
mcp_toolCall a connected MCP server toolStable
promptYes/no question answered by ClaudeExperimental
agentSpawn a subagent for evaluationExperimental

Default to command. Use http for external service integrations. Avoid prompt and agent in production hooks — semantics are not yet finalized.

7§ Configuration

Three-level structure: event → matcher group → handler array.

"hooks": {
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/pre-bash.sh",
          "timeout": 30
        }
      ]
    }
  ]
}

Exit code semantics for command handlers:

Exit codeEffect
0Success; stdout JSON parsed for decision fields. For SessionStart, UserPromptSubmit, and UserPromptExpansion, plain stdout is added to Claude's context
2Blocking; stderr (not stdout) is fed back to Claude, action stopped
any otherNon-blocking; stderr shown as warning, action continues; stdout ignored

JSON output (stdout, exit 0) — key fields:

  • PreToolUse deny: {"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"...","updatedInput":{...}}}
  • General block: {"decision":"block","reason":"..."}
  • Stop session: {"continue":false,"stopReason":"..."}
  • Hide hook output: {"suppressOutput":true}
  • SessionStart context injection: {"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"...","sessionTitle":"...","watchPaths":[...],"reloadSkills":true}}
  • Stop additional context: {"hookSpecificOutput":{"hookEventName":"Stop","additionalContext":"..."}}

Each JSON schema above is event-specific — select by the event the handler is registered on; fields from another event's schema are ignored. For SessionStart context injection, plain stdout on exit 0 and the additionalContext JSON field are equivalent; use JSON only when sessionTitle, watchPaths, or reloadSkills are also needed.

Input to every hook (stdin JSON) includes tool_name, tool_input, cwd, session_id, and hook_event_name. Parse with jq in bash scripts.

Note: SessionStart only supports command and mcp_tool handler types — http, prompt, and agent types are ignored on this event.

8§ Workflow

  1. Apply decision gate — confirm a hook is the right artifact.
  2. Identify the trigger: what event and which tool or context should fire the hook.
  3. Select lifecycle event (§5) and handler type (§6).
  4. Determine scope: .claude/settings.json (team-shared) or ~/.claude/settings.json (personal). Label [assumed] when defaulting.
  5. Determine the response: exit 2 to block, exit 0 + JSON for structured decisions, exit 0 alone for logging or side effects.
  6. Write the complete settings.json hook entry.
  7. Write the companion script: read stdin once, process, output JSON if needed, exit with the correct code. Bash on Unix/Mac; PowerShell on Windows ($input = [Console]::In.ReadToEnd() | ConvertFrom-Json).
  8. Confirm: state both file paths and a one-line summary of what fires and when.

9§ Output contract

Must include:

  • Complete settings.json hook entry — not a snippet
  • Companion script with shebang, set -euo pipefail, single stdin read, explicit exit code
  • Both file paths
  • One-line summary of hook purpose and trigger event

Must not include:

  • Multi-line logic inlined in command — use a companion script
  • Exit code 1 where exit 2 is intended for blocking
  • suppressOutput: true on security-relevant output
  • Partial JSON requiring manual merging
  • Behavioral guidance — that belongs in rules

10§ Associated documents

  • [assets/hook.example.sh] — companion script template with stdin/stdout/exit code pattern.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.