add-a-claude-code-hook

Maintainer instructions for adding a Claude Code lifecycle hook. A hook is a script that runs automatically when an event such as session start or a tool call occurs.

In plain words
What is it for?
Use it to add, configure, and test hooks that process prompts, tool calls, or session events.
Why use it?
It explains how to automate repeated actions and avoid relying on an agent to remember them manually.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/arkaaiadmin/agentic-memory/add-a-claude-code-hook
Any agent
npx skills add ArkaAiAdmin/Agentic-Memory --skill add-a-claude-code-hook
Clone the repo
git clone --depth 1 https://github.com/ArkaAiAdmin/Agentic-Memory

Made for: Claude Code, Codex.

Per session 71 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,471 The whole file, excluding the scripts and references it only reads on demand.
Security scan B 2 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00071 $0.02471
Opus 5 $0.00036 $0.01236
Sonnet 5 $0.00014 $0.00494
Haiku 4.5 $0.00007 $0.00247

Measured yesterday against content hash 8a36bba73471, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade B, and why

add-a-claude-code-hook scanned grade B with 2 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Reads agent configuration directoriesmediumAgent snooping

.claude/, .codex/, .gemini/ hold keys, settings and other credentials a mod has no legitimate need for.

2. Wire it into the user's Claude Code config (typically `~/.claude/settings.json` or opencode config).

Runs shell commandslowCapability

Expected in a hook, worth knowing in a rule or an instructions file.

result = subprocess.run(
skills/add-a-claude-code-hook/SKILL.md · 268 lines

How it starts

The opening of the file, as written. The whole thing — 268 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Add a Claude Code Hook

How to add a new lifecycle hook to the agentic-memory system. There are 4 lifecycle hooks today (PreToolUse, SessionStart, Stop/PostToolUse, plus a 5th log redirect helper); this is how to add a 6th.

The 60-second version

  1. Create hooks/memory_your_event.py at the repo root.
  2. Wire it into the user's Claude Code config (typically ~/.claude/settings.json or opencode config).
  3. The hook receives JSON on stdin, prints to stdout (NOT stderr — that was a 2-day bug).
  4. Test with a manual JSON invocation: echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | python hooks/memory_your_event.py

Total: ~30 minutes for a read-only hook, ~2 hours for one that mutates state.

Lifecycle event types

Event When it fires What you get What you can do
SessionStart New session begins session_id, cwd, hook_event_name Inject context, load memory
UserPromptSubmit User types a message prompt, session_id, cwd Pre-process prompt, inject context
PreToolUse Before any tool call tool_name, tool_input, session_id Modify tool_input, inject context, deny
PostToolUse After any tool call tool_name, tool_input, tool_output, session_id React to result, save, validate
Stop Agent stops responding session_id, last_user_message, last_assistant_message Save snapshot, ping user
SessionEnd Session deleted session_id, reason, duration_seconds Final save, cleanup

The current lifecycle hooks: memory-proactive-context.py (PreToolUse), memory-session-start.py (SessionStart), memory-session-end.py (Stop/PostToolUse, enforces Rule #7), and the log redirect _log_error.py. The auto-save flow runs on PostToolUse via auto_save.py.

Step 1: write the hook

#!/usr/bin/env python3
"""Hook: <event> — what this does in one line.

Triggered by: <where in claude config>
Input: JSON on stdin with <list of fields>
Output: <what to print, where>
"""
import sys
import json
import os

# Use the user's Python (M8 fix)
sys.path.insert(0, os.path.expanduser("~/.config/agentic-memory"))

def main():
    try:
        # Read input
        raw = sys.stdin.read()
        data = json.loads(raw) if raw else {}
    except Exception as e:
        # NEVER crash a hook silently. Print to stderr, return.
        print(f"hook: failed to parse stdin: {e}", file=sys.stderr)
        return

    # Extract what you need
    event = data.get("hook_event_name", "unknown")
    session_id = data.get("session_id", "unknown")
    tool_name = data.get("tool_name", "")
    tool_input = data.get("tool_input", {})

    # Do your work
    result = your_logic(event, session_id, tool_name, tool_input)

    # Print to STDOUT — this is what Claude Code injects
    print(result)

if __name__ == "__main__":
    main()

Read the full file on GitHub · 268 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 268 lines · 71 tokens per session scan B 8a36bba73471

Subscribe to this mod's changes

add-a-claude-code-hook is a skill published in the GitHub repository ArkaAiAdmin/Agentic-Memory (0 stars, last pushed 2d ago), licensed Apache-2.0. It adds 71 tokens to every session and 2,471 once invoked, about $0.0004 per session on Opus 5. A static security scan graded it B with 2 findings (reads agent configuration directories, runs shell commands). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes.

obra/superpowers · 21 tokens

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.

obra/superpowers · 37 tokens

auto-perf-optimize

Run agent-driven VS Code performance or memory investigations. Use when asked to launch Code OSS, automate a VS Code scenario, run the Chat memory smoke runner, capture renderer heap snapshots, take workflow screenshots, compare run summaries, or drive a repeatable scenario before heap-snapshot analysis.

microsoft/vscode · 62 tokens

chat-perf

Run chat perf benchmarks and memory leak checks against the local dev build or any published VS Code version. Use when investigating chat rendering regressions, validating perf-sensitive changes to chat UI, or checking for memory leaks in the chat response pipeline.

microsoft/vscode · 51 tokens

chat-pet-sprite-creation

Use when creating or changing VS Code chat pet sprite art, sprite sheets, state animations, eye treatments, Stable/Insiders variants, or pet transitions under src/vs/workbench/contrib/chat/browser/widget/media/chatPet.

microsoft/vscode · 53 tokens

cpu-profile-analysis

Analyze V8/Chrome CPU profiles (.cpuprofile) and DevTools trace files (Trace-.json). Use when: profiling performance, investigating slow functions, comparing code paths, finding bottlenecks, analyzing timeToRequest, understanding call trees from sampling profiler data, analyzing layout/paint/rendering, investigating…

microsoft/vscode · 71 tokens