How ai-memory Captures Agent Lifecycle Hooks: Hook Installation, Sanitization, and Storage
ai-memory captures AI agent behavior by installing shell scripts that execute automatically at key lifecycle points—session start, tool usage, and shutdown—then sanitizes and stores these events via an MCP router to SQLite and searchable wiki storage.
The ai-memory system provides complete observability into AI coding agents without requiring explicit logging calls from the agent itself. By intercepting agent lifecycle hooks at the operating system level, the system records bounded, privacy-preserving telemetry that feeds a cross-session knowledge base. This article examines the hook installation process, payload sanitization pipeline, and server-side storage architecture implemented in the akitaonrails/ai-memory repository.
Hook Installation and the MCP Runtime
The Multi-Client Protocol (MCP) runtime sources hook scripts from a dedicated pool directory, enabling automatic execution whenever an agent process starts or interacts with system tools.
Running the Installer Script
Hook registration begins with scripts/install-hooks.sh, which copies shell and PowerShell scripts into hooks/pool/. This installation binds the hooks to the MCP runtime environment, ensuring they are available for every subsequently launched agent process.
# From the repository root
./scripts/install-hooks.sh
Pool Directory Structure
After installation, the hooks/pool/ directory contains platform-specific variants for Unix (.sh) and Windows PowerShell (.ps1). The MCP runtime automatically sources these scripts when spawning agent processes, creating a consistent capture layer across operating systems.
The Four Core Lifecycle Hook Entry Points
The system captures agent lifecycle hooks through four specific entry points that fire at distinct phases of execution.
Session Start Hook
The session-start.{sh,ps1} script fires immediately when an agent session begins. It transmits a bounded JSON payload containing the session-id, agent-kind, and timestamp to the server’s /hook endpoint.
{
"session_id": "7f3c9e4b-a1d2-4f5e-b8c9-d3e4f5a6b7c8",
"agent_kind": "OpenCode",
"timestamp": "2026-09-09T12:34:56Z",
"event": "session_start"
}
Pre-Tool-Use and Post-Tool-Use Hooks
pre-tool-use.{sh,ps1} executes immediately before the agent invokes any external tool (e.g., git, curl, cargo). It records the tool name, arguments, and current session context. Conversely, post-tool-use.{sh,ps1} captures exit status, duration, and stdout/stderr snippets after the tool completes.
#!/usr/bin/env bash
session_id="${AI_MEMORY_SESSION_ID}"
tool="$1"
shift
args="$@"
curl -s -X POST -H "Content-Type: application/json" \
-d "{\"session_id\":\"$session_id\",\"event\":\"pre_tool\",\"tool\":\"$tool\",\"args\":\"$args\"}" \
http://127.0.0.1:49374/hook
Session Stop Hook
The stop.{sh,ps1} script signals session termination when the agent process exits, ensuring the system records the exact end time and final state of the interaction.
Payload Sanitization and Security Boundaries
All hook payloads pass through the ai-memory-hooks crate before reaching permanent storage. Located in crates/ai-memory-hooks/src/lib.rs, this library enforces the only trust boundary for untrusted data entering the system.
The sanitize() function strips user-provided secrets, normalizes timestamps, and produces a Sanitized<NewObservation> struct. This guarantees that sensitive information never reaches the storage layer, even if agents accidentally include credentials in command arguments.
use ai_memory_hooks::{sanitize, NewObservation};
let raw = NewObservation::new(json_payload);
let sanitized = sanitize(raw).expect("sanitisation failed");
store::write_observation(sanitized);
Server-Side Ingestion and Storage
Once sanitized, lifecycle events flow through the MCP router into persistent storage with full-text search capabilities.
MCP Router and Authentication
The MCP router at crates/ai-memory-mcp/src/router.rs receives POST requests at the /hook endpoint. It validates the AuthLevel of the submitting agent before forwarding the sanitized observation to the storage actor. This authentication step ensures that only authorized agents can write to the observation log.
SQLite Storage with FTS5 Indexing
The ai-memory-store actor writes observations into an SQLite database’s observations table. Simultaneously, the system updates an FTS5 full-text-search index, enabling immediate querying of captured tool outputs and session metadata.
Atomic Wiki Updates
Certain hooks—particularly user-prompt-submit—trigger writes to the Wiki layer in crates/ai-memory-wiki/src/wiki.rs. This component performs an atomic tmp + rename + fsync operation, ensuring that captured prompts appear as permanent markdown pages that are instantly searchable without risking data corruption during concurrent writes.
Summary
- Hook installation via
scripts/install-hooks.shregisters shell scripts that the MCP runtime sources automatically for every agent session. - Four core entry points—
session-start,pre-tool-use,post-tool-use, andstop—capture the complete agent lifecycle without explicit logging code. - Sanitization boundary at
crates/ai-memory-hooks/src/lib.rsremoves secrets via thesanitize()function before storage. - Server-side pipeline validates
AuthLevelin the MCP router, then persists to SQLite with FTS5 indexing and atomic wiki updates.
Frequently Asked Questions
What are agent lifecycle hooks in ai-memory?
Agent lifecycle hooks are automated shell scripts that execute at specific points during an AI agent's execution—specifically when sessions start, before and after tool usage, and when processes stop. These hooks capture telemetry without requiring the agent to perform explicit logging calls.
How does ai-memory prevent secrets from leaking through hooks?
The ai-memory-hooks crate in crates/ai-memory-hooks/src/lib.rs implements a mandatory sanitize() function that processes all payloads before storage. This function strips user-provided secrets and normalizes data into a Sanitized<NewObservation> struct, ensuring the capture layer serves as the sole trust boundary for untrusted data.
Which hook runs before a tool is executed?
The pre-tool-use.{sh,ps1} hook executes immediately before the agent invokes any external tool. According to the source in hooks/pool/pre-tool-use.sh, this script captures the tool name, arguments, and session context, then POSTs this data to the local MCP router at http://127.0.0.1:49374/hook.
Where are the captured lifecycle events stored?
Sanitized observations are stored in an SQLite database by the ai-memory-store actor, with concurrent updates to an FTS5 full-text-search index. Additionally, certain events trigger atomic writes to the Wiki layer at crates/ai-memory-wiki/src/wiki.rs, which uses tmp-file creation followed by rename and fsync operations to guarantee durable, searchable markdown records.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →