Files
claude-mem/docs/architecture/hooks.mdx
T
Alex Newman 12459eab3b docs: comprehensive v5.1.2 documentation update
This commit brings all documentation up to date with the current v5.1.2
codebase, addressing 12+ critical discrepancies and adding 2 major new
documentation files.

## Files Modified (18 documentation files):

### Root Documentation:
- README.md: Updated version badge (4.3.1 → 5.1.2), tool count (7 → 9),
  added viewer UI and theme toggle features, updated "What's New" section
- CHANGELOG.md: Added 8 missing releases (v4.3.2 through v5.1.2) with
  comprehensive release notes
- CLAUDE.md: Removed hardcoded personal paths, documented all 14 worker
  endpoints (was 8), added Chroma integration overview, updated v5.x releases

### Mintlify Documentation (docs/):
- introduction.mdx: Updated search tool count to 9, added viewer UI and
  theme toggle to features
- configuration.mdx: Added smart-install.js documentation, clarified data
  directory locations, added CLAUDE_CODE_PATH env var, explained observations
  vs sessions, updated hook configuration examples
- development.mdx: Added comprehensive viewer UI development section (103 lines),
  updated build output filenames (search-server.mjs)
- usage/search-tools.mdx: Added get_context_timeline and get_timeline_by_query
  documentation with examples, updated tool count to 9
- architecture/overview.mdx: Updated to 7 hook files, 9 search tools, added
  Chroma to tech stack, enhanced component details with viewer UI
- architecture/hooks.mdx: Added smart-install.js and user-message-hook.js
  documentation, updated hook count to 7
- architecture/worker-service.mdx: Documented all 14 endpoints organized by
  category (Viewer & Health, Data Retrieval, Settings, Session Management)
- architecture/mcp-search.mdx: Added timeline tools documentation, updated
  tool count to 9, fixed filename references (search-server.mjs)
- architecture-evolution.mdx: Added complete v5.x release history (v5.0.0
  through v5.1.2), updated title to "v3 to v5"
- hooks-architecture.mdx: Updated to "Seven Hook Scripts", added smart-install
  and user-message-hook documentation
- troubleshooting.mdx: Added v5.x specific issues section (viewer, theme toggle,
  SSE, Chroma, PM2 Windows fix)

### New Documentation Files:
- docs/VIEWER.md: Complete 400+ line guide to web viewer UI including architecture,
  features, usage, development, API integration, performance considerations
- docs/CHROMA.md: Complete 450+ line guide to vector database integration including
  hybrid search architecture, semantic search explanation, performance benchmarks,
  installation, configuration, troubleshooting

## Key Corrections Made:

1.  Updated version badges and references: 4.3.1 → 5.1.2
2.  Corrected search tool count: 7 → 9 (added get_context_timeline, get_timeline_by_query)
3.  Fixed MCP server filename: search-server.js → search-server.mjs
4.  Updated hook count: 5 → 7 (added smart-install.js, user-message-hook.js)
5.  Documented all 14 worker endpoints (was 8, incorrectly claimed 6 were missing)
6.  Removed hardcoded personal file paths
7.  Added Chroma vector database documentation
8.  Added viewer UI comprehensive documentation
9.  Updated CHANGELOG with all missing v4.3.2-v5.1.2 releases
10.  Clarified data directory locations (production vs development)
11.  Added smart-install.js caching system documentation
12.  Updated SessionStart hook configuration examples

## Documentation Statistics:

- Total files modified: 18
- New files created: 2
- Lines added: ~2,000+
- Version mismatches fixed: 2 critical
- Missing features documented: 5+ major
- Missing tools documented: 2 MCP tools
- Missing endpoints documented: 6 API endpoints

## Impact:

Documentation now accurately reflects the current v5.1.2 codebase with:
- Complete viewer UI documentation (v5.1.0)
- Theme toggle feature (v5.1.2)
- Hybrid search architecture with Chroma (v5.0.0)
- Smart install caching (v5.0.3)
- All 7 hook scripts documented
- All 9 MCP search tools documented
- All 14 worker service endpoints documented
- Comprehensive troubleshooting for v5.x issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-06 13:59:10 -05:00

270 lines
7.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Plugin Hooks"
description: "7 hook scripts that power Claude-Mem"
---
# Plugin Hooks
Claude-Mem integrates with Claude Code through 7 hook scripts across 5 lifecycle events that capture events and inject context.
## Hook Overview
| Hook Name | Purpose | Timeout | Script |
|---------------------|--------------------------------------|---------|-------------------------|
| SessionStart | Smart dependency installation | 300s | smart-install.js |
| SessionStart | Inject context from previous sessions| 300s | context-hook.js |
| SessionStart | Display first-time setup message | 10s | user-message-hook.js |
| UserPromptSubmit | Create/track new sessions | 120s | new-hook.js |
| PostToolUse | Capture tool execution observations | 120s | save-hook.js |
| Stop | Generate session summaries | 120s | summary-hook.js |
| SessionEnd | Mark sessions complete | 120s | cleanup-hook.js |
## Hook Configuration
Hooks are configured in `plugin/hooks/hooks.json`:
```json
{
"description": "Claude-mem memory system hooks",
"hooks": {
"SessionStart": [{
"matcher": "startup|clear|compact",
"hooks": [{
"type": "command",
"command": "node \"${CLAUDE_PLUGIN_ROOT}/../scripts/smart-install.js\" && node ${CLAUDE_PLUGIN_ROOT}/scripts/context-hook.js",
"timeout": 300
}, {
"type": "command",
"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/user-message-hook.js",
"timeout": 10
}]
}],
"UserPromptSubmit": [{
"hooks": [{
"type": "command",
"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/new-hook.js",
"timeout": 120
}]
}],
"PostToolUse": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/save-hook.js",
"timeout": 120
}]
}],
"Stop": [{
"hooks": [{
"type": "command",
"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/summary-hook.js",
"timeout": 120
}]
}],
"SessionEnd": [{
"hooks": [{
"type": "command",
"command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/cleanup-hook.js",
"timeout": 120
}]
}]
}
}
```
## 1. SessionStart Hook - Smart Install (`smart-install.js`)
**Purpose**: Intelligently manage dependencies and ensure worker service is running.
**Behavior**:
- Checks if dependencies need installation using version marker (`.install-version`)
- Only runs npm install when:
- First-time installation (no node_modules)
- Version changed in package.json
- Critical dependency missing (e.g., better-sqlite3)
- Provides Windows-specific error messages for build tool issues
- Auto-starts PM2 worker service after installation
- Fast when already installed (~10ms vs 2-5 seconds)
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"source": "startup"
}
```
**Implementation**: `scripts/smart-install.js`
**Key Features**:
- Version caching prevents redundant installs
- Cross-platform compatible (Windows, macOS, Linux)
- Helpful error messages with troubleshooting steps
- Non-blocking worker startup
**v5.0.3 Enhancement**: Smart caching eliminates 2-5 second npm install on every SessionStart, reducing to ~10ms for already-installed dependencies.
## 2. SessionStart Hook - Context Injection (`context-hook.js`)
**Purpose**: Inject context from previous sessions into Claude's initial context.
**Behavior**:
- Retrieves last 10 session summaries with three-tier verbosity (v4.2.0)
- Retrieves last 50 observations (configurable via `CLAUDE_MEM_CONTEXT_OBSERVATIONS`)
- Returns context via `hookSpecificOutput` in JSON format (fixed in v4.1.0)
- Formats results as progressive disclosure index
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"source": "startup"
}
```
**Output** (via stdout):
```json
{
"hookSpecificOutput": "# Recent Sessions\n\n## Session 1...\n"
}
```
**Implementation**: `src/hooks/context-hook.ts`
## 3. SessionStart Hook - User Message (`user-message-hook.js`)
**Purpose**: Display helpful user messages during first-time setup or when viewing context.
**Behavior**:
- Shows first-time setup message when node_modules is missing
- Displays formatted context information with colors
- Provides tips for using claude-mem effectively
- Shows link to web viewer UI (http://localhost:37777)
- Exits with code 3 (informational, not error)
**Output Example**:
```
📝 Claude-Mem Context Loaded
️ Note: This appears as stderr but is informational only
[Context details...]
📺 Watch live in browser http://localhost:37777/ (New! v5.1)
```
**Implementation**: `plugin/scripts/user-message-hook.js` (minified)
**Key Features**:
- User-friendly first-time setup experience
- Visual context display with colors
- Links to new features (viewer UI)
- Non-intrusive messaging
## 4. UserPromptSubmit Hook (`new-hook.js`)
**Purpose**: Create new session records and initialize session tracking.
**Behavior**:
- Creates new session in database
- Initializes session tracking
- Saves raw user prompts for full-text search (as of v4.2.0)
- Sends init signal to worker service
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"prompt": "User's actual prompt text"
}
```
**Implementation**: `src/hooks/new-hook.ts`
## 5. PostToolUse Hook (`save-hook.js`)
**Purpose**: Capture tool execution observations.
**Behavior**:
- Fires after EVERY tool execution (Read, Write, Edit, Bash, etc.)
- Sends observations to worker service for processing
- Includes correlation IDs for tracing
- Filters low-value observations
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"tool_name": "Read",
"tool_input": {...},
"tool_result": "...",
"correlation_id": "abc-123"
}
```
**Implementation**: `src/hooks/save-hook.ts`
## 6. Stop Hook (`summary-hook.js`)
**Purpose**: Generate session summaries when Claude stops.
**Behavior**:
- Triggers final summary generation
- Sends summarize request to worker service
- Summary includes: request, completed, learned, next_steps
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"source": "user_stop"
}
```
**Implementation**: `src/hooks/summary-hook.ts`
## 7. SessionEnd Hook (`cleanup-hook.js`)
**Purpose**: Mark sessions as completed (graceful cleanup as of v4.1.0).
**Behavior**:
- Marks sessions as completed
- Skips cleanup on `/clear` commands to preserve ongoing sessions
- Allows workers to finish pending operations naturally
- Previously sent DELETE requests; now uses graceful completion
**Input** (via stdin):
```json
{
"session_id": "claude-session-123",
"cwd": "/path/to/project",
"source": "normal"
}
```
**Implementation**: `src/hooks/cleanup-hook.ts`
## Hook Development
### Adding a New Hook
1. Create hook implementation in `src/hooks/your-hook.ts`
2. Add to `plugin/hooks/hooks.json`
3. Rebuild with `npm run build`
### Hook Best Practices
- **Fast execution**: Hooks should complete quickly (< 1s ideal)
- **Graceful degradation**: Don't block Claude if worker is down
- **Structured logging**: Use logger for debugging
- **Error handling**: Catch and log errors, don't crash
- **JSON output**: Use `hookSpecificOutput` for context injection
## Troubleshooting
See [Troubleshooting - Hook Issues](../troubleshooting.md#hook-issues) for common problems and solutions.