# Full Lifecycle of the 12 agentmemory Hooks: I² Instrumentation & Integration Guide

> Explore the full lifecycle of the 12 agentmemory hooks, from session-start to post-tool-failure. Understand Node.js instrumentation and integration for Claude Code observability.

- Repository: [Rohit Ghumare/agentmemory](https://github.com/rohitg00/agentmemory)
- Tags: deep-dive
- Published: 2026-05-10

---

**The agentmemory hooks lifecycle comprises 12 distinct Node.js instrumentation points—session-start, pre-tool-use, post-tool-use, stop, task-completed, subagent-start, subagent-stop, sdk-guard, notification, prompt-submit, pre-compact, and post-tool-failure—that capture, enrich, and summarize Claude Code sessions through a closed-loop observability system.**

The `rohitg00/agentmemory` repository implements an **I² (Instrumentation & Integration)** architecture that intercepts Claude Code interactions through client-side hooks written in TypeScript. These hooks form the **agentmemory hooks lifecycle**, creating a complete audit trail from session initialization through tool execution to final summarization. Understanding this lifecycle is essential for developers integrating observability into AI-assisted coding workflows.

## Session Initialization Hooks

The lifecycle begins with hooks that establish the session context and prepare the environment for observation.

### Session Start ([`src/hooks/session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/session-start.ts))

The **[`session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/session-start.ts)** hook runs during the first turn of a Claude Code session or when a new project opens. It generates a unique `sessionId` and sends a `POST /agentmemory/session/start` request containing the session identifier and project working directory.

When `AGENTMEMORY_INJECT_CONTEXT=true` is set in the environment, this hook writes server-returned context directly to **stdout**, prepending it to the first LLM prompt. This allows the agentmemory backend to inject relevant memories or instructions before the conversation begins.

### Sub-Agent Start ([`src/hooks/subagent-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/subagent-start.ts))

For background jobs or spawned processes, **[`subagent-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/subagent-start.ts)** registers child sessions using a distinct `entrypoint` value of `"sdk-ts"`. This differentiation prevents double-counting observations while maintaining traceability between parent and child sessions.

## Tool Execution Hooks

These hooks wrap file-touching tool calls (`Edit`, `Write`, `Read`, `Glob`, `Grep`), capturing both inputs and outputs to build a complete execution history.

### Pre-Tool Use ([`src/hooks/pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/pre-tool-use.ts))

The **[`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts)** hook executes immediately before Claude Code invokes any file-touching tool. Active only when `AGENTMEMORY_INJECT_CONTEXT=true`, it parses the incoming JSON to extract file paths and search terms, then calls `POST /agentmemory/enrich` with the payload `{sessionId, files, terms, toolName}`.

Any context returned by the enrichment endpoint is written to **stdout** and prepended to the next LLM turn, allowing the model to receive relevant background information before modifying files.

### Post-Tool Use ([`src/hooks/post-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/post-tool-use.ts))

After a tool completes, **[`post-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-use.ts)** captures the execution result. This hook checks for the `AGENTMEMORY_SDK_CHILD=1` flag to skip execution when running inside an agentmemory SDK child process, preventing recursive observation.

It extracts Base-64 image data from `tool_output` if present, then sends a `POST /agentmemory/observe` request containing:
- `hookType: "post_tool_use"`
- `sessionId`, project cwd, and timestamp
- Sanitized `tool_output` truncated to 8 KB

### Post-Tool Failure ([`src/hooks/post-tool-failure.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/post-tool-failure.ts))

When tool execution throws an error, **[`post-tool-failure.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-failure.ts)** fires immediately. It sends an observation with `hookType: "post_tool_failure"` to the server, capturing failure metadata and exception details for debugging and audit purposes.

## Session Termination Hooks

These hooks handle graceful shutdown and resource cleanup when Claude Code sessions end.

### Stop ([`src/hooks/stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/stop.ts))

The **[`stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/stop.ts)** hook triggers when the user explicitly terminates the session (e.g., closing the window or issuing a stop command). It sends a `POST /agentmemory/summarize` request that initiates server-side summarization of the session's complete observation history.

This call operates fire-and-forget style with no stdout output, allowing the server to asynchronously process the session summary.

### Task Completed ([`src/hooks/task-completed.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/task-completed.ts))

Following the stop hook, **[`task-completed.ts`](https://github.com/rohitg00/agentmemory/blob/main/task-completed.ts)** runs as a thin wrapper that forwards the JSON payload to `POST /agentmemory/task/completed`. This endpoint marks the session as fully closed in the UI and frees temporary server-side resources.

### Sub-Agent Stop ([`src/hooks/subagent-stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/subagent-stop.ts))

Corresponding to the sub-agent start hook, **[`subagent-stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/subagent-stop.ts)** finalizes child sessions using the same `entrypoint: "sdk-ts"` identifier. It ensures background jobs properly close their observation streams without affecting the parent session's lifecycle.

## Infrastructure and Utility Hooks

These hooks provide cross-cutting concerns like recursion protection, notifications, and extension points for future functionality.

### SDK Guard ([`src/hooks/sdk-guard.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/sdk-guard.ts))

The **[`sdk-guard.ts`](https://github.com/rohitg00/agentmemory/blob/main/sdk-guard.ts)** module implements a critical safety mechanism embedded in every hook. It checks the `AGENTMEMORY_SDK_CHILD` environment flag and the payload's `entrypoint` field, returning early if the call originates from the SDK itself. This prevents infinite recursion when a hook-triggered action invokes another SDK method.

### Notification ([`src/hooks/notification.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/notification.ts))

**[`notification.ts`](https://github.com/rohitg00/agentmemory/blob/main/notification.ts)** establishes a long-polling connection to the server for asynchronous message delivery. When the server pushes notifications (e.g., "summary ready" alerts), this hook forwards the JSON to **stdout** for display in the Claude Code interface.

### Prompt Submit ([`src/hooks/prompt-submit.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/prompt-submit.ts))

Currently a placeholder for future extensions, **[`prompt-submit.ts`](https://github.com/rohitg00/agentmemory/blob/main/prompt-submit.ts)** runs immediately before Claude Code sends a prompt to the LLM. It accepts the full prompt payload but performs no operations in the current implementation.

### Pre-Compact ([`src/hooks/pre-compact.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/pre-compact.ts))

Similarly, **[`pre-compact.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-compact.ts)** serves as a reserved extension point that runs before Claude Code performs token reduction (compaction). It currently executes as a no-op but remains available for future pre-compaction enrichment logic.

## How the agentmemory Hook Lifecycle Works

The 12 hooks cooperate in a specific temporal sequence to create a complete session narrative:

1. **Initialization**: [`session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/session-start.ts) registers the session and optionally injects initial context.
2. **Pre-execution**: For each file-touching tool, [`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts) enriches the request with relevant memories.
3. **Execution**: Claude Code executes the tool (Edit, Write, Read, etc.).
4. **Post-execution**: [`post-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-use.ts) captures the output (or [`post-tool-failure.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-failure.ts) captures errors).
5. **Repetition**: Steps 2-4 repeat for every tool invocation during the session.
6. **Termination**: [`stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/stop.ts) triggers summarization, followed by [`task-completed.ts`](https://github.com/rohitg00/agentmemory/blob/main/task-completed.ts) marking the session closed.

Throughout this flow, [`sdk-guard.ts`](https://github.com/rohitg00/agentmemory/blob/main/sdk-guard.ts) ensures that any SDK calls made by the hooks themselves do not trigger additional hook executions, maintaining a strict single-layer instrumentation boundary.

## Configuration and Usage Examples

### Enabling Context Injection

Configure your environment to activate the enrichment lifecycle:

```bash

# ~/.agentmemory/.env

export AGENTMEMORY_INJECT_CONTEXT=true
export AGENTMEMORY_URL=http://localhost:3111
export AGENTMEMORY_SECRET=your-secret-token

```

With these variables set, [`session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/session-start.ts) will automatically prepend server-generated context to your first Claude Code turn, and [`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts) will enrich subsequent tool calls.

### Debugging Individual Hooks

Test the post-tool-use observation capture manually:

```bash
cat <<EOF | node src/hooks/post-tool-use.ts
{
  "session_id": "ses_demo",
  "cwd": "/home/me/project",
  "tool_name": "Write",
  "tool_input": {"file_path": "README.md", "content": "Hello"},
  "tool_output": "File written successfully"
}
EOF

```

You should observe a `POST /agentmemory/observe` request in your server logs containing the sanitized tool output.

### Managing Sub-Agent Sessions

For background processing workflows, manually trigger the sub-agent lifecycle:

```bash

# Start sub-agent

node src/hooks/subagent-start.ts <<EOF
{
  "session_id": "ses_parent",
  "cwd": "/home/me/project",
  "entrypoint": "sdk-ts"
}
EOF

# ... background work executes ...

# Stop sub-agent

node src/hooks/subagent-stop.ts <<EOF
{
  "session_id": "ses_parent",
  "cwd": "/home/me/project",
  "entrypoint": "sdk-ts"
}
EOF

```

The server treats this as a distinct logical session linked to the parent, preventing observation duplication while maintaining execution context.

## Summary

- The **agentmemory hooks lifecycle** consists of 12 TypeScript files in `src/hooks/` that instrument Claude Code sessions.
- **Session hooks** ([`session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/session-start.ts), [`subagent-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/subagent-start.ts)) initialize observation streams with unique identifiers.
- **Execution hooks** ([`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts), [`post-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-use.ts), [`post-tool-failure.ts`](https://github.com/rohitg00/agentmemory/blob/main/post-tool-failure.ts)) wrap tool calls with context enrichment and output capture.
- **Termination hooks** ([`stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/stop.ts), [`task-completed.ts`](https://github.com/rohitg00/agentmemory/blob/main/task-completed.ts), [`subagent-stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/subagent-stop.ts)) trigger summarization and resource cleanup.
- **Infrastructure hooks** ([`sdk-guard.ts`](https://github.com/rohitg00/agentmemory/blob/main/sdk-guard.ts), [`notification.ts`](https://github.com/rohitg00/agentmemory/blob/main/notification.ts), [`prompt-submit.ts`](https://github.com/rohitg00/agentmemory/blob/main/prompt-submit.ts), [`pre-compact.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-compact.ts)) provide recursion protection, async messaging, and extension points.
- The lifecycle operates as a closed loop, ensuring every LLM interaction is observed, enriched, and persisted without infinite recursion.

## Frequently Asked Questions

### What triggers the pre-tool-use hook in agentmemory?

The [`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts) hook triggers immediately before Claude Code invokes any file-touching tool such as `Edit`, `Write`, `Read`, `Glob`, or `Grep`. According to the source in `rohitg00/agentmemory`, this hook only activates when `AGENTMEMORY_INJECT_CONTEXT=true` is set, at which point it calls `POST /agentmemory/enrich` to fetch relevant context for the upcoming tool execution.

### How does agentmemory prevent infinite loops when hooks trigger SDK calls?

The [`sdk-guard.ts`](https://github.com/rohitg00/agentmemory/blob/main/sdk-guard.ts) hook implements a recursion guard that checks the `AGENTMEMORY_SDK_CHILD` environment flag and the `entrypoint` field in the payload. If either indicates the call originates from the agentmemory SDK itself, the hook returns early without executing, preventing a cascade where hook-triggered SDK calls generate new hook events.

### What is the difference between the stop and task-completed hooks?

The [`stop.ts`](https://github.com/rohitg00/agentmemory/blob/main/stop.ts) hook fires when the user explicitly terminates the Claude Code session and sends a `POST /agentmemory/summarize` request to generate a session summary. The [`task-completed.ts`](https://github.com/rohitg00/agentmemory/blob/main/task-completed.ts) hook runs afterward and sends a `POST /agentmemory/task/completed` request that marks the session as fully closed and frees temporary server resources, effectively serving as the final lifecycle checkpoint.

### How does context injection work in the agentmemory lifecycle?

Context injection operates through two specific hooks: [`session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/session-start.ts) writes initial context to stdout during session registration, and [`pre-tool-use.ts`](https://github.com/rohitg00/agentmemory/blob/main/pre-tool-use.ts) writes enriched context before each tool execution. Both hooks require `AGENTMEMORY_INJECT_CONTEXT=true` and communicate with their respective endpoints (`/agentmemory/session/start` and `/agentmemory/enrich`), writing any returned context directly to stdout where Claude Code prepends it to the next LLM prompt.