Integrate Long-Term Memory with Claude Code via Hooks
Overview
Claude Code Hooks is a session lifecycle hook mechanism provided by Claude Code. When you perform specific actions in Claude Code (such as starting a session, context compaction, exiting a session, or calling tools), Claude Code automatically executes your pre-registered scripts, inserting custom logic at critical session checkpoints.
Each Hook receives JSON input from Claude Code via stdin (containing session ID, working directory, tool name, etc.) and returns JSON output via stdout to influence Claude Code's behavior (such as injecting context or blocking dangerous operations).
AnalyticDB for PostgreSQLLong-Term Memory service can build an automated memory management solution based on this mechanism — completing memory loading, saving, and guarding at Claude Code lifecycle trigger points, requiring no manual operation from either the user or Claude.
How It Works
AnalyticDB for PostgreSQLLong-Term Memory Hooks directly calls the adbpgmem REST API via httpx (Python async HTTP client library), without depending on MCP Server. The workflow is as follows:
-
Install Hook scripts: Install the Python package via
pip installto register 4 Hook CLI entry points. -
Register with Claude Code: Use the
adbpgmem-install-hookscommand to write Hook scripts intosettings.json. -
Automatic triggering: Claude Code automatically executes the corresponding Hook scripts at events such as session start, context compaction, and session end.
-
API calls: Hook scripts call the adbpgmem REST API via httpx to perform memory search and save operations.
All operations run silently in the background without affecting normal Claude Code usage.
Four Hooks
|
Hook |
Event |
Function |
Description |
|
|
SessionStart |
Dual-query search for historical memories, injected via additionalContext |
Automatically loads relevant knowledge at session start |
|
|
PreCompact |
Saves session summary as-is (infer=false) |
Saves session snapshot before context compaction |
|
|
Stop |
Extracts session summary and saves to memory store |
Automatically saves new knowledge at session end |
|
|
PreToolUse |
Blocks writing to local memory files such as MEMORY.md |
Guards local files, redirects to Long-Term Memory service |
All Hooks allow Claude Code to work normally when theAnalyticDB for PostgreSQL Long-Term Memory service is unreachable. Sessions are never interrupted due to Hook failures.
Use Cases
Scenarios suitable for Hooks integration:
-
Seamless memory management: You want memory to be automatically loaded and saved in the background without manual operations.
-
Automatic loading at session start: Historical architectural decisions and coding preferences are automatically injected when starting a new session.
-
Automatic saving at session end: Valuable knowledge from the current session is automatically extracted and saved when exiting.
-
Prevent local file scattering: Block Claude from writing memories to local files such as MEMORY.md, centralizing management in the Long-Term Memory service.
Install Hooks
Prerequisites
-
Claude Code CLI is installed and functional.
-
Python >= 3.10.
-
Obtained the AnalyticDB for PostgreSQL Long-Term Memory service API URL and token. For details, see Context service.
-
Obtained the adbpgmem_mcp_selfhosted project source code adbpgmem-mcp-server-0.2.0.tar.gz.
Extract the archive to a directory named
adbpgmem_mcp_selfhosted. All paths in the following steps refer to this extracted directory.
Installation
Install the Python package via pip install to register Hook CLI entry points in the current Python environment:
pip install -e /path/to/adbpgmem_mcp_selfhosted
-e (editable) mode links the source code to the current environment, allowing changes to take effect without reinstallation. Suitable for development and debugging. For production deployment, remove the -e flag for standard installation.
After installation, the following CLI commands will be available:
|
Command |
Description |
|
|
SessionStart Hook entry point |
|
|
PreCompact Hook entry point |
|
|
Stop Hook entry point |
|
|
PreToolUse Hook entry point |
|
|
Hook registration tool |
|
|
Hook uninstallation tool |
Verify installation:
which adbpgmem-claude-context
# Should output the installation path, e.g., /usr/local/bin/adbpgmem-claude-context
Configure Hooks
Hooks support configuring the Long-Term Memory service via environment variables or configuration files. Priority from highest to lowest:
|
Priority |
Source |
Description |
|
1 |
environment variable |
Set via |
|
2 |
|
Environment variable pointing to the configuration file directory |
|
3 |
|
Project-level configuration file |
|
4 |
|
Global configuration file |
Parameters
|
Parameter |
Type |
Required |
Description |
|
|
String |
Yes |
API URL of the adbpgmem Long-Term Memory service |
|
|
String |
Yes |
Service authentication token |
|
|
String |
No |
User identifier. Defaults to the system username |
Method 1: Environment Variables
Export environment variables before starting Claude Code. Hooks inherit environment variables from the parent process:
export ADBPGMEM_API_URL="https://api-longmemory-cn-chengdu.opentrust.net"
export ADBPGMEM_API_TOKEN="sk-your-token-here"
export ADBPGMEM_USER_ID="your.username"
claude
Environment variables need to be re-set each time a new terminal is opened. We recommend adding them to ~/.zshrc or ~/.bashrc for persistence.
Method 2: Configuration File (Recommended)
Once written, no further action is needed.
Global configuration (recommended, applies to all projects):
mkdir -p ~/.claude
cat > ~/.claude/adbpgmem.conf << 'EOF'
ADBPGMEM_API_URL="https://api-longmemory-cn-chengdu.opentrust.net"
ADBPGMEM_API_TOKEN="sk-your-token-here"
ADBPGMEM_USER_ID="your.username"
EOF
Project-level configuration (applies to the current project only):
mkdir -p .claude
cat > .claude/adbpgmem.conf << 'EOF'
ADBPGMEM_API_URL="https://api-longmemory-cn-chengdu.opentrust.net"
ADBPGMEM_API_TOKEN="sk-your-token-here"
ADBPGMEM_USER_ID="your.username"
EOF
adbpgmem.conf contains the API token. Do not commit it to Git. We recommend adding. Hooks silently skip execution when the configuration is missing, without affecting normal Claude Code operation..claude/adbpgmem.conf to .gitignore
Register Hooks
After installation and configuration, run the following command to register 4 Hook scripts to Claude Code lifecycle events.
Global Registration (Recommended)
Writes to ~/.claude/settings.json, applying to all projects:
# (Optional)Back up existing configuration
cp ~/.claude/settings.json ~/.claude/settings.json.bak 2>/dev/null
# Global registration (auto-detect platform)
adbpgmem-install-hooks --global
# Or manually specify Claude Code platform
adbpgmem-install-hooks --platform claude --global
Project-Level Registration
Writes to <project>/.claude/settings.json, applying only to the current project:
# (Optional)Back up existing configuration
cp .claude/settings.json .claude/settings.json.bak 2>/dev/null
# Project-level registration
adbpgmem-install-hooks
# Or manually specify
adbpgmem-install-hooks --platform claude
Selective Registration by Type
The installer supports selective registration by Hook responsibility group:
# Install only write-type Hooks (stop + precompact + pretooluse)
adbpgmem-install-hooks --global --type write
# Install only read-type Hooks (context)
adbpgmem-install-hooks --global --type read
# Install all (default)
adbpgmem-install-hooks --global --type all
Each installation first removes all adbpgmem Hooks under the Claude Code platform, then writes the specified group. Switching types does not leave behind old configurations.
Configuration example after registration:
{
"hooks": {
"SessionStart": [
{
"matcher": "",
"hooks": [
{"type": "command", "command": "adbpgmem-claude-context", "timeout": 15}
]
}
],
"PreCompact": [
{
"matcher": "",
"hooks": [
{"type": "command", "command": "adbpgmem-claude-precompact", "timeout": 10}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{"type": "command", "command": "adbpgmem-claude-stop", "timeout": 30}
]
}
],
"PreToolUse": [
{
"matcher": "Write|Edit|SearchReplace",
"hooks": [
{"type": "command", "command": "adbpgmem-claude-pretooluse", "timeout": 2}
]
}
]
}
}
Repeatedly running adbpgmem-install-hooks does not produce duplicate entries. It first removes all existing adbpgmem Hooks before re-writing.
Uninstall Hooks
# Auto-detect platform (recommended)
adbpgmem-uninstall-hooks --global # Global uninstall
adbpgmem-uninstall-hooks # Project-level uninstall
# Manually specify platform
adbpgmem-uninstall-hooks --platform claude --global
The uninstall command removes all adbpgmem-*-prefixed hook entries from the configuration file and cleans up empty event arrays. Claude Code loads Hook configuration at session start; changes take effect in a new session.
How to Use Hooks
Verify Registration
Check if Hooks are registered successfully:
cat ~/.claude/settings.json
# Should contain entries like adbpgmem-claude-context
Functional test: Restart Claude Code and check whether memory context is automatically loaded at session start.
Invocation
Hooks run fully automatically without any manual operation. Claude Code automatically triggers at the following events:
|
Trigger |
Hook Executed |
User Experience |
|
Start a new session |
|
Claude responses already include historical preferences and architectural decisions |
|
Context is about to be compacted |
|
Seamless, saves session snapshot in the background |
|
Exit session |
|
Seamless, extracts and saves session summary in the background |
|
When Claude writes to a file |
|
Blocks writing to local memory files such as MEMORY.md |
Detailed Hook Behavior
adbpgmem-claude-context (SessionStart: Session Start Injection)
Trigger: Every time a Claude Code session starts.
Workflow:
-
Reads JSON input from Claude Code (containing cwd, etc.).
-
Loads adbpgmem configuration.
-
Executes a dual-query search strategy: Query 1 retrieves project-related architectural decisions; Query 2 retrieves recent development context.
-
Deduplicates the two result sets by memory_id, filtering out low-score results (score < 0.5).
-
Formats results as a numbered list, injecting them via the
additionalContextfield into Claude's session context.
Output Example:
# adbpgmem cross-session memory
1. Project uses Go 1.22 + Gin framework, ORM uses GORM v2
2. Database: PostgreSQL 15, connection pool: PgBouncer, max connections: 50
3. APIs uniformly use RESTful style, error codes follow RFC 7807
adbpgmem-claude-precompact (PreCompact: Pre-Compaction Saving)
Trigger: When Claude Code detects the context window is nearly full, it triggers the PreCompact event for context compaction.
Workflow:
-
Reads JSON input from Claude Code (containing
session_id,cwd, etc.). -
Constructs the session summary.
-
Saves as-is to adbpgmem with
infer=false(no atomic fact extraction, preserving original content). -
Appends metadata:
type=compact_summary,session_id,project.
Design Purpose: Context compaction can cause some historical information to be lost. This Hook saves a snapshot before compaction, ensuring critical information is not permanently lost due to compaction.
adbpgmem-claude-stop (Stop: Session End Saving)
Trigger: When the user exits a Claude Code session.
Workflow:
-
Reads JSON input from Claude Code (containing
session_id,cwd,transcript_path, etc.). -
Reads the session transcript file (complete conversation record in JSONL format).
-
Intelligent summary extraction: Collects all user/assistant messages, filters transitional messages (< 100 characters), selects top 5 by length, with a total budget of 6000 characters.
-
Short session filtering: Skips saving when the summary length is < 50 characters.
-
Saves as-is to adbpgmem with
infer=false, with metadata:type=session_summary.
Design Purpose: Automatically saves valuable content from each session without manual user intervention. The content can be retrieved via the SessionStart Hook in the next session.
adbpgmem-claude-pretooluse (PreToolUse: Local Memory File Guard)
Trigger: When Claude calls file writing tools such as Write/Edit/SearchReplace.
Workflow:
-
Reads JSON input from Claude Code (containing tool_name, tool_input, etc.).
-
Determines whether it is a file writing tool (Write/Edit/SearchReplace).
-
Checks whether the target file path matches the guard pattern (
MEMORY.md,memory.md,.claude/memory/). -
If matched, returns both
decision: "block"andhookSpecificOutput.permissionDecision: "deny"to block the write. -
If not matched, allows the write to proceed normally.
Design Purpose: Prevents Claude from scattering memories into local files, ensuring all memories are centrally stored in the Long-Term Memory service for cross-session retrieval and management.
Typical Usage Scenarios
Scenario 1: Automatically Inherit Historical Decisions in New Sessions
You have determined the tech stack for a project and want Claude to automatically know it when starting a new session.
Session 1 (memory saved via MCP tools or other methods):
You: Remember: the project uses Python 3.11 + FastAPI, database PostgreSQL 15, cache Redis 7
Session 2 (new session started days later):
Start Claude Code
← adbpgmem-claude-context triggered automatically
← Dual-query searches historical memories
← Injects matched memories into additionalContext
You: Help me add a new API endpoint
Claude: Based on the project's FastAPI + PostgreSQL 15 tech stack, I'll create the new endpoint...
[Automatically uses the correct framework and database version]
Users don't need to manually inform Claude about the tech stack. Historical memories are automatically injected.
Scenario 2: No Information Loss During Long Conversation Context Compaction
You are performing a complex system refactoring. The conversation has become very long, and Claude Code needs to perform context compaction.
Process:
[Extended refactoring conversation involving multiple architectural decisions and code changes]
Claude Code detects context window is nearly full
← adbpgmem-claude-precompact triggered automatically
← Saves session summary to Long-Term Memory service (infer=false, saves as-is)
Conversation continues after context compaction...
You: What was the caching strategy we decided on?
Claude: Based on the previously saved information, our caching strategy was...
Critical architectural decisions are not permanently lost due to context compaction.
Scenario 3: Automatically Save Development Experience at Session End
You solved a tricky concurrency issue in a session.
Process:
You: How do I troubleshoot this goroutine deadlock?
Claude: [Analyzes code, identifies the issue, provides a solution]
The root cause is inconsistent channel read/write order causing a deadlock.
Solution: Use select + context timeout mechanism...
[Session ends, exit Claude Code]
← adbpgmem-claude-stop triggered automatically
← Reads session transcript file
← Intelligently extracts key information from the conversation (filters noise, retains substantive content)
← Saves session summary to adbpgmem (metadata: type=session_summary)
The next time you encounter a similar concurrency issue, the SessionStart Hook will automatically load this experience.