Hooks

Automated reactions to events -- validation gates and workflow triggers

Concept

What is a Hook?

A shell script that runs automatically when something happens during an AI session.

Event-Driven Automation

Hooks are like git hooks but for AI sessions. They fire on lifecycle events:

  • SessionStart — when the AI session begins
  • PreToolUse — before the AI calls a tool (can block it)
  • PostToolUse — after the AI finishes calling a tool
  • SessionEnd — when the AI session ends
  • PreModelSwitch / PostModelSwitch — around a model change (Claude Code v2.1.251+; the pre hook can allow, deny, or ask)
Examples

Real Examples from KAI

Hooks that run in production every day.

SessionStart: Environment Validation

Validates .ai/config.yaml exists and Node version matches .nvmrc. Fails fast if the environment is misconfigured.

PreToolUse: Branch Guard

Blocks git commit on protected branches (main, master, development, develop). Prevents accidental commits to the wrong branch.

PostToolUse: Figma Screenshot

Automatically saves screenshots from the Figma MCP to disk. Avoids repeated MCP calls for the same design during a session.

PostToolUse: Subagent Log

Logs a timestamp every time a subagent completes. Useful for debugging long-running autonomous pipelines.

Format

Hook File Format

A single hooks.json file defines all hooks for the project.

hooks.json (simplified)
{
"hooks": {
  "SessionStart": [{
    "matcher": "",
    "hooks": [{
      "type": "command",
      "command": "bash session-start.sh"
    }]
  }],
  "PreToolUse": [{
    "matcher": "Bash",
    "hooks": [{
      "type": "command",
      "if": "Bash(git commit*)",
      "command": "bash branch-guard.sh"
    }]
  }]
}
}

No top-level version key in a plugin hooks.json

Do not add a version field to a plugin’s hooks/hooks.json. Claude Code’s hook schema has no such key and logs hooks.json: unknown key “version” ignored at every session start. One copy still serves both platforms without it — Copilot CLI reads that same plugin file.



The exception is the Copilot-only repo-hooks file /dx-init generates at .github/hooks/hooks.json, which keeps “version”: 1 — a different consumer with a different schema. Do not strip the key there.

Repo hooks in .github/hooks must be self-contained

Copilot sets CLAUDE_PROJECT_DIR for repo hooks but not PLUGIN_ROOT, COPILOT_PLUGIN_ROOT or CLAUDE_PLUGIN_ROOT (checked on Copilot CLI v1.0.109). A repo hook that runs bash ”${PLUGIN_ROOT}/hooks/scripts/x.sh” becomes bash /hooks/scripts/x.sh and exits 127. Copilot CLI already runs the plugin’s own hooks/hooks.json — from every source, with no dedup — so the repo file exists for the Copilot cloud coding agent, which ignores plugins. /dx-init therefore installs only two entries there: the inline branch guard (exit 2) and the Stop guard via ${CLAUDE_PROJECT_DIR:-$PWD}.



Installs from before November 2026 also carried SessionStart and PostToolUse entries that need a plugin root, and some a Bash(git commit*) matcher or exit 1. /dx-doctor reports them; /dx-upgrade repairs dx’s own entries and leaves every other hook in the file alone.

v1.0.11

Hook Merging (Copilot CLI v1.0.11+)

Multiple plugins can contribute hooks without overwriting each other.

Multi-Plugin Hooks

Before v1.0.11, if both dx-core and dx-aem defined hooks, one would overwrite the other. Now hooks from multiple extensions merge — each plugin contributes its own hooks and they all fire correctly.

SessionStart Context Injection

SessionStart hook additionalContext is now injected into the conversation. Our session-start.sh and next-step.sh hooks now surface active specs and pending steps in Copilot CLI sessions — previously this context was lost.

What This Means for KAI

dx-core owns the plugin hooks: branch guard, subagent log, Figma screenshots, and the Playwright screenshot log (it moved from dx-aem with the playwright MCP server, so dx-core-only projects get it too). A SessionEnd hook (run-result-close.sh) closes dx runs the session left open: a skill’s running marker still in .ai/run-results/ whose run_id is the session’s DX_RUN_ID, or — for a skill run by hand — starts with the ending session’s id (<session id>.<n>), is written as failed / interrupted so the tool learns the outcome. Other sessions’ markers are left alone. Hooks from every installed plugin fire in the same session without conflict.

v2.1.251

Model-Switch Hooks (Claude Code)

PreModelSwitch and PostModelSwitch fire around /model, the /config Model row, the model picker, fast mode when it changes the model, and an SDK / IDE / Remote Control set_model. Editing settings.json is not a trigger.

PreModelSwitch

Runs before a switch someone asked for: source is command, picker or sdk. Output permissionDecision is allow, deny or ask (no defer). A session that cannot ask (claude -p, a pipeline) treats ask as a block. It does not fire on an automatic fallback or a resume, so it cannot keep a pipeline on Opus, and the payload carries model IDs only, not effort. Use it to guard interactive and SDK switches.

PostModelSwitch

Runs after any switch, including source: auto (fallback) and resume. It cannot undo the switch, but hookSpecificOutput.additionalContext reaches the new model, so a pipeline can log the model it actually landed on and tell the new model about it. Same release: SessionStart on resume also receives how stale the session is and an estimated re-cache cost.

Input payload (both events): from_model, to_model, requested_model, source, context_tokens, prompt_cache_warm, cache_ttl, estimated_cache_write_usd, pricing (read from the v2.1.301 hook schema).

Not shipped as a dx-core hook (yet)

KAI documents these events but does not install a model-switch guard: a guard in dx-core/hooks/hooks.json would fire for every consumer. If one is added it belongs behind DX_HOOK_PROFILE=strict. Copilot CLI has no equivalent event.

When to Use

When to Use Hooks vs Skills

Different tools for different jobs.

Hooks

  • Automatic — fire without user input
  • Deterministic — shell scripts, no AI reasoning
  • Fast — milliseconds, no token cost
  • Best for: validation gates, caching, logging

Skills

  • Interactive — user invokes with /command
  • AI-driven — reasoning and judgment
  • Flexible — adapts to context
  • Best for: complex tasks, code generation, analysis
Copilot CLI

Hook Limits on Copilot CLI

Verified on Copilot CLI v1.0.108, except the VS Code note.

Guards are best-effort, not a security boundary

  • A fourth hook source. Copilot CLI (v1.0.83+) also runs personal hooks from ~/.copilot/hooks/, alongside plugin, .github/hooks and agent hooks, with no dedup. dx ships nothing there.
  • Hook fields. Copilot ignores if (the hook runs on every matcher hit) and async (the hook runs synchronously, and hooks for one event run one after another, so slow hooks add up). timeout is honoured. onFailure has no effect: a preToolUse hook that errors always denies. Verified on v1.0.109.
  • Status text. Copilot has no statusMessage; a hook shows status by printing a {"type":"progress","message":"…"} line, and the line stays in the transcript. dx hooks print a past-tense line when they finish (“Workflow state checked”, “Completion checks passed”), only on Copilot. SessionStart hooks run with the first prompt, not at launch.
  • Timeouts fail open. A hook that exceeds its timeoutSec is killed and the tool call is allowed. Keep guards fast and offline (no network calls).
  • Stop hooks are capped. An agentStop hook that blocks is overridden after 8 consecutive blocks; persistence can get past a Stop hook. The dx stop-guard.sh is not affected: Copilot sends stop_hook_active: true on the call after a block, as Claude Code does, and the guard then lets the agent stop (verified on v1.0.109, interactive). As a backup it never blocks the same findings twice in a row.
  • Tool name arrives on stdin. Copilot (and Claude Code) do not set CLAUDE_TOOL_NAME; plugin PostToolUse input provides tool_name. In v1.0.108, file creation and editing both arrived as Edit.
  • VS Code Chat (Local agent) ignores matcher. The agent-scoped branch guard therefore filters on the tool input itself rather than relying on the matcher (from upstream research; not re-run in VS Code).
Docs

Official Documentation

KAI by Dragan Filipovic