Agent SwarmAgent Swarm
Architecture

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

HookWhenWhat it does
SessionStartSession beginsWrites CLAUDE.md from DB, loads concurrent session context for leads
PreCompactBefore context compactionInjects a "goal reminder" with current task details so the agent doesn't lose track
PreToolUseBefore each tool callChecks for task cancellation, detects tool loops, blocks excessive polling
PostToolUseAfter each tool callSends heartbeat, syncs identity file edits to DB, auto-indexes memory files
UserPromptSubmitNew iteration startsChecks for task cancellation
StopSession endsCleans 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.md from 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)
  • Polling limits — Prevents excessive polling of external services
  • Shared disk write prevention — On Archil-mounted environments, warns agents before they attempt to write to another agent's directory under /workspace/shared/. Each agent can only write to its own subdirectory (/workspace/shared/{category}/{agentId}/)

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 lastActivityAt timestamp (fire-and-forget) for stall detection
  • Identity sync — If an identity file (SOUL.md, IDENTITY.md, TOOLS.md, CLAUDE.md) was edited, syncs the changes to the database with changeSource: "self_edit" tracking to distinguish agent edits from session-end syncs. Files shorter than 100 characters are rejected to prevent accidental profile corruption
  • Memory indexing — If a file was written to a memory directory, automatically generates an embedding and indexes it
  • Shared disk write failure detection — On Archil-mounted environments, detects "Read-only file system" errors from Write, Edit, or Bash tools and warns the agent about the per-agent directory convention

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 sync of all identity files to the database
  • Session summary + LLM memory rating — Runs a lightweight structured-output call via the shared internal-ai abstraction (src/utils/internal-ai/) to extract key learnings from the session transcript. The wrapper resolves credentials in priority order — OPENROUTER_API_KEYANTHROPIC_API_KEYOPENAI_API_KEY → Codex OAuth (~/.codex/auth.json) → CLAUDE_CODE_OAUTH_TOKEN (mirrored to AGENT_SWARM_CLAUDE_OAUTH_TOKEN to survive Claude CLI's hook env-stripping) — and dispatches the call to the matching backend (OpenRouter / Anthropic / OpenAI SDK or a claude -p --json-schema fallback). Default model: google/gemini-3-flash-preview via OpenRouter; override with MEMORY_RATER_LLM_MODEL. When MEMORY_LLM_RATER_ENABLED=true, the same call also produces structured useful: true | false ratings 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/rate with source: "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 the pi, opencode, and codex worker 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

On this page