Files
claude-mem/cursor-hooks
Alex Newman 2659ec3231 fix: Claude Code 2.1.1 compatibility + log-level audit + path validation fixes (#614)
* Refactor CLAUDE.md and related files for December 2025 updates

- Updated CLAUDE.md in src/services/worker with new entries for December 2025, including changes to Search.ts, GeminiAgent.ts, SDKAgent.ts, and SessionManager.ts.
- Revised CLAUDE.md in src/shared to reflect updates and new entries for December 2025, including paths.ts and worker-utils.ts.
- Modified hook-constants.ts to clarify exit codes and their behaviors.
- Added comprehensive hooks reference documentation for Claude Code, detailing usage, events, and examples.
- Created initial CLAUDE.md files in various directories to track recent activity.

* fix: Merge user-message-hook output into context-hook hookSpecificOutput

- Add footer message to additionalContext in context-hook.ts
- Remove user-message-hook from SessionStart hooks array
- Fixes issue where stderr+exit(1) approach was silently discarded

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update logs and documentation for recent plugin and worker service changes

- Added detailed logs for worker service activities from Dec 10, 2025 to Jan 7, 2026, including initialization patterns, cleanup confirmations, and diagnostic logging.
- Updated plugin documentation with recent activities, including plugin synchronization and configuration changes from Dec 3, 2025 to Jan 7, 2026.
- Enhanced the context hook and worker service logs to reflect improvements and fixes in the plugin architecture.
- Documented the migration and verification processes for the Claude memory system and its integration with the marketplace.

* Refactor hooks architecture and remove deprecated user-message-hook

- Updated hook configurations in CLAUDE.md and hooks.json to reflect changes in session start behavior.
- Removed user-message-hook functionality as it is no longer utilized in Claude Code 2.1.0; context is now injected silently.
- Enhanced context-hook to handle session context injection without user-visible messages.
- Cleaned up documentation across multiple files to align with the new hook structure and removed references to obsolete hooks.
- Adjusted timing and command execution for hooks to improve performance and reliability.

* fix: Address PR #610 review issues

- Replace USER_MESSAGE_ONLY test with BLOCKING_ERROR test in hook-constants.test.ts
- Standardize Claude Code 2.1.0 note wording across all three documentation files
- Exclude deprecated user-message-hook.ts from logger-usage-standards test

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: Remove hardcoded fake token counts from context injection

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Address PR #610 review issues by fixing test files, standardizing documentation notes, and verifying code quality improvements.

* fix: Add path validation to CLAUDE.md distribution to prevent invalid directory creation

- Add isValidPathForClaudeMd() function to reject invalid paths:
  - Tilde paths (~) that Node.js doesn't expand
  - URLs (http://, https://)
  - Paths with spaces (likely command text or PR references)
  - Paths with # (GitHub issue/PR references)
  - Relative paths that escape project boundary

- Integrate validation in updateFolderClaudeMdFiles loop
- Add 6 unit tests for path validation
- Update .gitignore to prevent accidental commit of malformed directories
- Clean up existing invalid directories (~/, PR #610..., git diff..., https:)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: Implement path validation in CLAUDE.md generation to prevent invalid directory creation

- Added `isValidPathForClaudeMd()` function to validate file paths in `src/utils/claude-md-utils.ts`.
- Integrated path validation in `updateFolderClaudeMdFiles` to skip invalid paths.
- Added 6 new unit tests in `tests/utils/claude-md-utils.test.ts` to cover various rejection cases.
- Updated `.gitignore` to prevent tracking of invalid directories.
- Cleaned up existing invalid directories in the repository.

* feat: Promote critical WARN logs to ERROR level across codebase

Comprehensive log-level audit promoting 38+ WARN messages to ERROR for
improved debugging and incident response:

- Parser: observation type errors, data contamination
- SDK/Agents: empty init responses (Gemini, OpenRouter)
- Worker/Queue: session recovery, auto-recovery failures
- Chroma: sync failures, search failures (now treated as critical)
- SQLite: search failures (primary data store)
- Session/Generator: failures, missing context
- Infrastructure: shutdown, process management failures
- File Operations: CLAUDE.md updates, config reads
- Branch Management: recovery checkout failures

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: Address PR #614 review issues

- Remove incorrectly tracked tilde-prefixed files from git
- Fix absolute path validation to check projectRoot boundaries
- Add test coverage for absolute path validation edge cases

Closes review issues:
- Issue 1: ~/ prefixed files removed from tracking
- Issue 3: Absolute paths now validated against projectRoot
- Issue 4: Added 3 new test cases for absolute path scenarios

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* build assets and context

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 23:34:20 -05:00
..

Claude-Mem Cursor Hooks Integration

Persistent AI Memory for Cursor - Free Options Available

Give your Cursor AI persistent memory across sessions. Your agent remembers what it worked on, the decisions it made, and the patterns in your codebase - automatically.

Why Claude-Mem?

  • Remember context across sessions: No more re-explaining your codebase every time
  • Automatic capture: MCP tools, shell commands, and file edits are logged without effort
  • Free tier options: Works with Gemini (1500 free req/day) or OpenRouter (free models available)
  • Works with or without Claude Code: Full functionality either way

Quick Install (5 minutes)

# Clone and build
git clone https://github.com/thedotmack/claude-mem.git
cd claude-mem && bun install && bun run build

# Interactive setup (configures provider + installs hooks)
bun run cursor:setup

Quick Start for Cursor Users

Using Claude Code? Skip to Installation - everything works automatically.

Cursor-only (no Claude Code)? See STANDALONE-SETUP.md for free-tier options using Gemini or OpenRouter.


Overview

The hooks bridge Cursor's hook system to claude-mem's worker API, allowing:

  • Session Management: Initialize sessions and generate summaries
  • Observation Capture: Record MCP tool usage, shell commands, and file edits
  • Worker Readiness: Ensure the worker is running before prompt submission

Context Injection

Context is automatically injected via Cursor's Rules system:

  1. Install: claude-mem cursor install generates initial context
  2. Stop hook: Updates context in .cursor/rules/claude-mem-context.mdc after each session
  3. Cursor: Automatically includes this rule in ALL chat sessions

The context updates after each session ends, so the next session sees fresh context.

Additional Access Methods

  • MCP Tools: Configure claude-mem's MCP server for search, timeline, get_observations tools
  • Web Viewer: Access context at http://localhost:37777
  • Manual Request: Ask the agent to search memory

See CONTEXT-INJECTION.md for details.

Installation

# Install globally for all projects (recommended)
claude-mem cursor install user

# Or install for current project only
claude-mem cursor install

Manual Installation

Click to expand manual installation steps

User-level (recommended - applies to all projects):

# Copy hooks.json to your home directory
cp cursor-hooks/hooks.json ~/.cursor/hooks.json

# Copy hook scripts
mkdir -p ~/.cursor/hooks
cp cursor-hooks/*.sh ~/.cursor/hooks/
chmod +x ~/.cursor/hooks/*.sh

Project-level (for per-project hooks):

# Copy hooks.json to your project
mkdir -p .cursor
cp cursor-hooks/hooks.json .cursor/hooks.json

# Copy hook scripts to your project
mkdir -p .cursor/hooks
cp cursor-hooks/*.sh .cursor/hooks/
chmod +x .cursor/hooks/*.sh

After Installation

  1. Start the worker:

    claude-mem start
    
  2. Restart Cursor to load the hooks

  3. Verify installation:

    claude-mem cursor status
    

Hook Mappings

Cursor Hook Script Purpose
beforeSubmitPrompt session-init.sh Initialize claude-mem session
beforeSubmitPrompt context-inject.sh Ensure worker is running
afterMCPExecution save-observation.sh Capture MCP tool usage
afterShellExecution save-observation.sh Capture shell command execution
afterFileEdit save-file-edit.sh Capture file edits
stop session-summary.sh Generate summary + update context file

How It Works

Session Initialization (session-init.sh)

  • Called before each prompt submission
  • Initializes a new session in claude-mem using conversation_id as the session ID
  • Extracts project name from workspace root
  • Outputs {"continue": true} to allow prompt submission

Context Hook (context-inject.sh)

  • Ensures claude-mem worker is running before session
  • Outputs {"continue": true} to allow prompt submission
  • Note: Context file is updated by session-summary.sh (stop hook), not here

Observation Capture (save-observation.sh)

  • Captures MCP tool executions and shell commands
  • Maps them to claude-mem's observation format
  • Sends to /api/sessions/observations endpoint (fire-and-forget)

File Edit Capture (save-file-edit.sh)

  • Captures file edits made by the agent
  • Treats edits as "write_file" tool usage
  • Includes edit summaries in observations

Session Summary (session-summary.sh)

  • Called when agent loop ends (stop hook)
  • Requests summary generation from claude-mem
  • Updates context file in .cursor/rules/claude-mem-context.mdc for next session

Configuration

The hooks read configuration from ~/.claude-mem/settings.json:

  • CLAUDE_MEM_WORKER_PORT: Worker port (default: 37777)
  • CLAUDE_MEM_WORKER_HOST: Worker host (default: 127.0.0.1)

Dependencies

The hook scripts require:

  • jq - JSON processing
  • curl - HTTP requests
  • bash - Shell interpreter

Install on macOS: brew install jq curl Install on Ubuntu: apt-get install jq curl

Troubleshooting

Hooks not executing

  1. Check hooks are in the correct location:

    ls .cursor/hooks.json  # Project-level
    ls ~/.cursor/hooks.json  # User-level
    
  2. Verify scripts are executable:

    chmod +x ~/.cursor/hooks/*.sh
    
  3. Check Cursor Settings → Hooks tab for configuration status

  4. Check Hooks output channel in Cursor for error messages

Worker not responding

  1. Verify worker is running:

    curl http://127.0.0.1:37777/api/readiness
    
  2. Check worker logs:

    tail -f ~/.claude-mem/logs/worker-$(date +%Y-%m-%d).log
    
  3. Restart worker:

    claude-mem restart
    

Observations not being saved

  1. Monitor worker logs for incoming requests

  2. Verify session was initialized via web viewer at http://localhost:37777

  3. Test observation endpoint directly:

    curl -X POST http://127.0.0.1:37777/api/sessions/observations \
      -H "Content-Type: application/json" \
      -d '{"contentSessionId":"test","tool_name":"test","tool_input":{},"tool_response":{},"cwd":"/tmp"}'
    

Comparison with Claude Code Integration

Feature Claude Code Cursor
Session Initialization SessionStart hook beforeSubmitPrompt hook
Context Injection additionalContext field Auto-updated .cursor/rules/ file
Observation Capture PostToolUse hook afterMCPExecution, afterShellExecution, afterFileEdit
Session Summary Stop hook with transcript ⚠️ stop hook (no transcript)
MCP Search Tools Full support Full support (if MCP configured)

Files

  • hooks.json - Hook configuration
  • common.sh - Shared utility functions
  • session-init.sh - Session initialization
  • context-inject.sh - Context/worker readiness hook
  • save-observation.sh - MCP and shell observation capture
  • save-file-edit.sh - File edit observation capture
  • session-summary.sh - Summary generation
  • cursorrules-template.md - Template for .cursorrules file

See Also