Skip to content

Lifecycle Hooks

11 MCP lifecycle hooks plus 11 shell hooks that capture context, enforce rules, and preserve memory without any manual effort


Lifecycle Hooks

Massu AI includes 17 MCP lifecycle hooks and 11 shell utility hooks that run automatically during Claude Code sessions. Together they capture observations, inject context, enforce rules, filter output, preserve state, and drive the auto-learning pipeline -- all without any manual effort from the developer.

How Hooks Work

Hooks are compiled TypeScript files that Claude Code executes at specific lifecycle events. Each hook:

  1. Receives JSON on stdin with session context (session ID, transcript path, tool details)
  2. Processes the input (reads databases, analyzes tool calls, generates context)
  3. Outputs result on stdout (plain text for context injection, JSON for structured responses)
  4. Exits within 5 seconds to avoid blocking Claude Code

Hooks are compiled with esbuild into standalone JavaScript files bundled inside the @massu/core npm package (dist/hooks/). They are automatically configured in .claude/settings.local.json when you run npx massu init. They have no runtime dependencies beyond Node.js built-ins and the bundled Massu AI modules.

The 17-Hook Lifecycle

HookEventPurposeTiming
session-startSession beginsInject memory contextStartup, resume, compact
session-endSession endsGenerate summary, archive stateSession stop
pre-tool-use-gateBefore tool executionConsolidated security-gate + pre-delete-check (single-spawn)Before every tool
post-tool-useAfter each tool callCapture observationsAfter every tool
user-promptUser submits promptCapture prompts, link tasksEvery prompt
pre-compactBefore compactionPreserve session stateBefore context window compaction
pre-delete-checkBefore file deletionFeature impact check (back-compat; folded into pre-tool-use-gate)Before rm/delete operations
post-edit-contextAfter file editSurface applicable rulesAfter Edit/Write on src/ files
security-gateBefore tool executionValidate security policies (back-compat; folded into pre-tool-use-gate)Before dangerous operations
cost-trackerAfter each tool callTrack token usage and costsAfter every tool
quality-eventAfter each tool callDetect quality signalsAfter every tool
intent-suggesterUser submits promptSuggest relevant commandsEvery prompt
fix-detectorAfter Edit/Write to sourceDetect bug-fix shape via git diff; arm auto-learning pipelineAfter every code edit
classify-failureAfter Edit/Write to sourceScore detected fix against known failure classes (KNOWN / SIMILAR / NEW)After every code edit
incident-pipelineAfter Write to docs/incidents/*.mdTrigger rule derivation from new incident reportWhen incident written
rule-enforcement-pipelineAfter Write to memory/feedback_*.mdTrigger enforcement placement for new ruleWhen feedback rule written
auto-learning-pipelineSession ends with armed fixForcing function: block session-end until incident → rule → enforcement completeStop hook with pending fix

Session Lifecycle Flow

Session Start
  |
  v
[session-start hook] --> Injects memory context
  |
  v
User writes prompt
  |
  v
[user-prompt hook] --> Captures prompt, links to task
[intent-suggester hook] --> Suggests relevant commands
  |
  v
Claude Code prepares a tool call
  |
  v
[pre-tool-use-gate hook] --> Single-spawn check: security policies +
                             feature-impact protection on deletions
  |
  v
Claude Code processes (reads, edits, runs commands)
  |
  v
[post-tool-use hook] --> Captures observation per tool call
[post-edit-context hook] --> Surfaces rules on file edits
[cost-tracker hook] --> Records token usage
[quality-event hook] --> Detects quality signals
[fix-detector hook] --> Detects fix-shape diffs (arms auto-learning)
[classify-failure hook] --> Scores fix as KNOWN/SIMILAR/NEW
[incident-pipeline hook] --> Triggers when incidents/*.md written
[rule-enforcement-pipeline hook] --> Triggers when feedback_*.md written
  |
  v
(if context window fills up)
[pre-compact hook] --> Snapshots state before compaction
[session-start hook] --> Re-injects context after compact
  |
  v
Session ends
  |
  v
[auto-learning-pipeline hook] --> Forcing function: blocks Stop until
                                  fix-detector arm has produced an
                                  incident report + rule + enforcement
[session-end hook] --> Generates summary, archives CURRENT.md

Zero Effort for Users

You do not need to interact with hooks directly. They run silently in the background:

  • No commands to remember: Hooks trigger automatically at the right lifecycle events
  • No performance impact: Each hook completes in under 500ms
  • No configuration needed: Hooks use your massu.config.yaml automatically
  • Best-effort execution: If a hook fails, it exits silently without blocking Claude Code

Hook Compilation

Hooks are written in TypeScript and compiled with esbuild:

bash
cd packages/core && npm run build:hooks

This produces standalone JavaScript files in packages/core/dist/hooks/ that are referenced by .claude/settings.local.json during installation. Run npx massu install-hooks to update the hooks configuration.

Detailed Hook Documentation

Click any hook below for complete documentation including input/output formats, configuration, and examples:

Shell Hooks (11)

In addition to the 11 MCP lifecycle hooks, Massu AI includes 11 shell utility hooks located in scripts/hooks/. These hooks are invoked at specific points to enforce policies, filter output, and automate routine tasks.

HookTriggerPurpose
output-secret-filter.shAfter every tool outputStrip potential secrets (API keys, tokens, passwords) from Claude Code output before display
memory-integrity-check.shSession startVerify SQLite memory database integrity; alert if corruption detected
loop-circuit-breaker.shDuring /massu-loopDetect infinite loops and halt with a structured error after configurable iteration limit
auto-ingest-incident.shSession endAutomatically ingest any incidents detected during the session into the knowledge system
auto-review-on-stop.shSession stopTrigger an automated code review of uncommitted changes when the session stops
validate-deliverables.shDuring /massu-loopVerify each plan deliverable is actually complete before marking it done
surface-review-findings.shPost-reviewSurface /massu-review findings inline as Claude Code context for the next prompt
pattern-feedback.shAfter tool callsCapture pattern usage signals and feed them back to the knowledge system
mcp-rate-limiter.shBefore each MCP tool callEnforce per-tool rate limits to prevent runaway tool usage in long sessions
mcp-usage-tracker.shAfter each MCP tool callRecord tool invocation counts and latency for the observability dashboard
cost-tracker.shAfter each MCP tool callTrack estimated token costs per tool invocation for the cost intelligence dashboard

Shell Hook Configuration

Shell hooks are configured in .claude/settings.local.json alongside the MCP lifecycle hooks. They are installed by npx massu init and updated by npx massu install-hooks.

json
{
  "hooks": {
    "PostToolUse": [
      { "matcher": "*", "hooks": [{ "type": "command", "command": "node dist/hooks/post-tool-use.js" }] },
      { "matcher": "*", "hooks": [{ "type": "command", "command": "bash dist/hooks/mcp-usage-tracker.sh" }] }
    ]
  }
}

Shell hooks follow the same stdin/stdout contract as MCP hooks: they receive JSON on stdin, write output on stdout, and must exit within 5 seconds.