Hook System
Six lifecycle hooks — SessionStart, PreCompact, PreToolUse, PostToolUse, UserPromptSubmit, and Stop — provide safety guardrails, context persistence, and automatic identity sync across every Claude Code agent session.
Six hooks fire during each Claude Code session, providing safety, context management, and persistence. Hooks are implemented in src/hooks/hook.ts.
Hook Overview
| Hook | When | What it does |
|---|---|---|
| SessionStart | Session begins | Writes CLAUDE.md from DB, loads concurrent session context for leads |
| PreCompact | Before context compaction | Injects a "goal reminder" with current task details so the agent doesn't lose track |
| PreToolUse | Before each tool call | Checks for task cancellation, detects tool loops, blocks excessive polling |
| PostToolUse | After each tool call | Sends heartbeat, syncs identity file edits to DB, auto-indexes memory files |
| UserPromptSubmit | New iteration starts | Checks for task cancellation |
| Stop | Session ends | Cleans up artifact tunnels, saves PM2 state, syncs all identity files, runs session summarization, marks agent offline |
Hook Details
SessionStart
Fires when a new Claude Code session begins. This hook:
- Writes the agent's
CLAUDE.mdfrom the database to the filesystem - For lead agents, loads context about other concurrent sessions
- Sets up the workspace environment
PreCompact
Fires before Claude Code compacts its context window. This is critical for long-running tasks — without this hook, the agent might lose track of what it's working on after compaction.
The hook injects the current task description and any saved progress as a "goal reminder" into the compacted context.
PreToolUse
Fires before every tool call. This hook provides safety guardrails:
- Cancellation check — If the task has been cancelled, the hook blocks the tool call and notifies the agent
- Loop detection — Detects when the same tool is called with identical arguments repeatedly (a sign the agent is stuck), including nested MCP argument payloads; low-cardinality Codex file-change ping-pong patterns use a higher threshold before blocking
- Polling limits — Prevents excessive polling of external services
PostToolUse
Fires after every tool call. This is the most active hook:
- Heartbeat — Sends a heartbeat to the MCP server so the lead knows the worker is alive
- Activity tracking — Updates the agent's
lastActivityAttimestamp (fire-and-forget) for stall detection - Identity sync — If an identity file (SOUL.md, IDENTITY.md, TOOLS.md, CLAUDE.md) was edited, syncs each changed file independently with
changeSource: "self_edit", so one rejected field cannot discard valid edits to the others. The session-start runner records baseline hashes; the Stop/session-end path skips unchanged files so lead-sideupdate-profileedits are not overwritten by stale local copies. Filesystem sync skips SOUL.md and IDENTITY.md shorter than 500 characters, and growth beyond the identity-field budgets is surfaced as a persisted rejection for the next session - Memory indexing — If a file was written to a memory directory, automatically generates an embedding and indexes it
UserPromptSubmit
Fires when a new iteration of the agent loop begins (i.e., the agent receives a new prompt from the runner). This hook:
- Checks for task cancellation
- Can inject additional context if needed
Stop
Fires when the session ends. This hook handles cleanup:
- Artifact cleanup — Stops any active artifact tunnels (PM2 processes prefixed with
artifact-) - PM2 state — Saves the current PM2 process list for auto-restart
- Identity sync — Final independent sync of identity files that changed relative to their session-start hashes. HTTP failures and budget rejections are logged instead of being swallowed, while unchanged files are skipped so DB-side lead edits survive the session
- Session summary + LLM memory rating — Runs a lightweight structured-output call via the shared
internal-aiabstraction (src/utils/internal-ai/) to extract key learnings from the session transcript. The wrapper resolves credentials in priority order —OPENROUTER_API_KEY→ANTHROPIC_API_KEY→OPENAI_API_KEY→ Codex OAuth (~/.codex/auth.json) →CLAUDE_CODE_OAUTH_TOKEN(mirrored toAGENT_SWARM_CLAUDE_OAUTH_TOKENto survive Claude CLI's hook env-stripping) — and dispatches the call to the matching backend (OpenRouter / Anthropic / OpenAI SDK or aclaude -p --json-schemafallback). Default model:google/gemini-3-flash-previewvia OpenRouter; override withMEMORY_RATER_LLM_MODEL. WhenMEMORY_LLM_RATER_ENABLED=true, the same call also produces structureduseful: true | falseratings for the memories that were retrieved into the task's prompt — piggybacking on the summary call so there's no extra LLM round-trip. Self-similar retrievals (e.g. cron clones of the same task) are deduped by memory name before the rater sees them, preventing posterior inflation. Ratings are POSTed to/api/memory/ratewithsource: "llm". No-op when no credential resolves — self-hosters / OSS users without any of the supported credentials skip session summary + LLM ratings entirely. The same wrapper drives session summarization for thepi,opencode, andcodexworker harnesses (src/providers/pi-mono-extension.ts,plugin/opencode-plugins/lib/summarize.ts,src/providers/codex-adapter.ts), so Pro/Max OAuth-only workers and non-Claude harnesses now get summaries that previously silently dropped. - Agent status — Marks the agent as offline in the database
Related
- Memory System — How PostToolUse auto-indexes memory files
- Agent Identity & Configuration — Identity files synced by PostToolUse and Stop hooks
- Task Lifecycle — Task states checked by PreToolUse cancellation detection
Memory System
Persistent AI agent memory — vector embeddings, semantic search, TTL expiry, and reranking with recency and access signals so agents accumulate knowledge across Claude Code sessions instead of starting fresh.
Task Lifecycle
The complete task lifecycle in Agent Swarm — from unassigned through offered, pending, in_progress, paused, and finally completed or failed. Learn heartbeat detection, checkpoint recovery, retry strategies, and how task dependencies orchestrate multi-agent workflows.