Skip to content

cognizonline/claude-memory-hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cogniz Claude Code Integration

Connect Claude Code to your persistent memory layer with automatic context management.

License: MIT Python 3.8+ Claude Code

Automatically connect your Claude Code workflow to Cogniz Memory Platform, enabling persistent memory across coding sessions.

Research Preview: These hooks are currently in research preview and actively being upgraded. A free tier is available on Cogniz Memory Platform.

Features

  • Auto-Save: Important code changes saved automatically to your memory platform
  • Context Loading: Claude remembers your previous work when you start new sessions
  • Smart Search: Find relevant memories when asking questions
  • Project Organization: Memories automatically organized by your code projects
  • Auto-Documentation: Your work history automatically recorded and searchable

Quick Start

Prerequisites

Installation

Step 1: Clone into your project

cd your-project-directory
git clone https://github.com/cognizonline/cogniz-claude-code.git .claude

Step 2: Get your Cogniz API key

Visit https://cogniz.online/dashboard → API Keys → Create New Key

Step 3: Configure your API key

Edit .claude/project-config.json:

{
  "cogniz": {
    "api_key": "YOUR_API_KEY_HERE",
    "api_url": "https://cogniz.online/wp-json/memory/v1",
    "default_project": "my-project"
  }
}

Or use environment variables:

echo "COGNIZ_API_KEY=your_key_here" > .claude/.env

Step 4: Make hooks executable (Mac/Linux only)

chmod +x .claude/hooks/*.sh

Step 5: Test the integration

curl -X GET "https://cogniz.online/wp-json/memory/v1/user-stats" \
  -H "Authorization: Bearer YOUR_API_KEY"

Expected response: {"success": true, ...}

Step 6: Start coding

Open Claude Code in your project. The integration will automatically:

  • Load recent memories from your previous sessions
  • Detect which project you're working on
  • Save important code changes as you work

How It Works

Automatic Project Detection

Your code repositories are automatically mapped to Cogniz projects based on directory structure:

your-workspace/
├── my-app/              → Cogniz Project: "my-app"
├── backend-api/         → Cogniz Project: "backend-api"
└── frontend/            → Cogniz Project: "frontend"

Three Smart Hooks

The integration uses three Claude Code hooks to manage memory:

1. SessionStart Hook

  • Runs when you start a new Claude Code session
  • Loads recent memories from the current project
  • Provides context about your previous work

2. PostToolUse Hook

  • Runs after Edit or Write operations
  • Automatically saves significant code changes
  • Filters by file type and content size

3. UserPromptSubmit Hook

  • Runs before processing your messages
  • Searches memories when you ask questions
  • Injects relevant context from your history

Configuration

Basic Configuration

{
  "cogniz": {
    "api_key": "YOUR_API_KEY",
    "api_url": "https://cogniz.online/wp-json/memory/v1",
    "default_project": "my-project"
  },
  "projects": {
    "auto-detect": true,
    "mappings": [
      {
        "directory_pattern": "**/my-app/**",
        "cogniz_project_id": "my-app",
        "cogniz_project_name": "My Application",
        "save_files": ["*.js", "*.ts", "*.py", "*.md"]
      }
    ]
  },
  "hooks": {
    "session_start": {
      "enabled": true,
      "load_recent_memories": true,
      "memory_limit": 5
    },
    "auto_save": {
      "enabled": true,
      "file_types": ["*.py", "*.js", "*.ts", "*.md"],
      "exclude_patterns": ["**/node_modules/**", "**/.git/**"]
    },
    "search_memories": {
      "enabled": true,
      "trigger_keywords": ["remember", "previous", "earlier"]
    }
  }
}

See docs/CONFIGURATION.md for complete configuration reference.

See examples/ for configuration templates for Python, web development, and data science projects.

Usage Examples

Starting a New Session

When you open Claude Code in a project where you've worked before:

Claude Code (SessionStart):
Cogniz Memory Loaded

Project: Backend API
Recent work:
• Added JWT token generation in auth.py
• Fixed password hashing bug
• Updated /api/auth/login endpoint

[Session continues with full context]

Auto-Save Code Changes

When you make code changes:

You: "Add input validation to login"

Claude: [Makes changes to auth.py]

PostToolUse:
Saved to Cogniz (Backend API)

Next session: Claude remembers this change

Search Your Memories

When you ask about previous work:

You: "How did we handle password reset before?"

UserPromptSubmit searches your memory...

Claude:
From Your Cogniz Memory:
Password reset: email with token → verify → new password → hash

Hook Implementation Details

SessionStart Hook

File: hooks/session-start.py or hooks/session-start.sh

Trigger: At the beginning of each Claude Code session

Process:

  1. Detects current project from directory path
  2. Fetches recent memories from Cogniz API
  3. Formats and loads context into conversation
  4. Displays project name and memory count

Configuration:

  • enabled: Enable/disable the hook
  • load_recent_memories: Whether to load memories
  • memory_limit: Number of memories to load (1-10)
  • context_length: Max characters per memory

PostToolUse Hook

File: hooks/auto-save.py or hooks/auto-save.sh

Trigger: After Edit or Write tool usage in Claude Code

Process:

  1. Captures the code change content
  2. Checks file type against configured patterns
  3. Validates content length (min/max thresholds)
  4. Excludes files matching exclude patterns
  5. Saves to Cogniz with project association

Configuration:

  • enabled: Enable/disable auto-save
  • file_types: Array of file patterns to save (e.g., ["*.py", "*.js"])
  • min_content_length: Skip small changes (default: 50)
  • max_content_length: Truncate large changes (default: 2000)
  • exclude_patterns: Patterns to never save (e.g., ["**/node_modules/**"])

UserPromptSubmit Hook

File: hooks/search-memories.py or hooks/search-memories.sh

Trigger: Before each user message is processed

Process:

  1. Scans user message for trigger keywords
  2. If keywords found, searches Cogniz for relevant memories
  3. Injects search results into context
  4. Claude receives both your message and relevant memories

Configuration:

  • enabled: Enable/disable memory search
  • trigger_keywords: Words that trigger search (e.g., ["remember", "previous"])
  • search_limit: Max search results (1-5)
  • context_length: Max characters per result

Security

Best Practices

1. Never commit API keys

Add to your project's .gitignore:

.claude/.env
.claude/project-config.json

2. Use environment variables

export COGNIZ_API_KEY="your_key"

3. Exclude sensitive files from auto-save

{
  "hooks": {
    "auto_save": {
      "exclude_patterns": [
        "**/.env",
        "**/secrets.json",
        "**/credentials.json",
        "**/private/**"
      ]
    }
  }
}

4. Rotate API keys regularly

Generate new API keys every 90 days from your Cogniz dashboard.

Troubleshooting

Hooks Not Running

Check hook file permissions:

ls -la .claude/hooks/
# Should show: -rwxr-xr-x (executable)

# Fix permissions:
chmod +x .claude/hooks/*.sh

API Key Errors

Test your API key:

curl -H "Authorization: Bearer YOUR_KEY" \
  https://cogniz.online/wp-json/memory/v1/user-stats

Expected response includes "success": true

No Memories Loading

  1. Verify you have memories in your Cogniz dashboard
  2. Check load_recent_memories: true in config
  3. Verify project mapping matches your current directory
  4. Check hook execution in Claude Code logs

Wrong Project Detected

Update project mappings in project-config.json with more specific patterns:

{
  "directory_pattern": "**/exact-path/my-app/**"
}

Repository Structure

cogniz-claude-code/
├── README.md                 # This file
├── LICENSE                   # MIT License
├── CONTRIBUTING.md           # Contribution guidelines
├── CHANGELOG.md              # Version history
├── hooks.json                # Hook configuration for Claude Code
├── project-config.json       # Template configuration file
├── .env.example              # Environment variable template
├── .gitignore                # Excludes sensitive files
├── hooks/
│   ├── session-start.py      # Python: Load context on session start
│   ├── session-start.sh      # Shell: Load context on session start
│   ├── auto-save.py          # Python: Auto-save code changes
│   ├── auto-save.sh          # Shell: Auto-save code changes
│   ├── search-memories.py    # Python: Search memories on questions
│   └── search-memories.sh    # Shell: Search memories on questions
├── examples/
│   ├── python-project.json   # Configuration for Python projects
│   ├── web-project.json      # Configuration for web development
│   └── data-science.json     # Configuration for data science
└── docs/
    ├── INSTALLATION.md       # Detailed installation guide
    └── CONFIGURATION.md      # Complete configuration reference

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

See CONTRIBUTING.md for detailed guidelines.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Documentation

Community

Changelog

v1.0.0 (2025-01-25)

  • Initial public release
  • SessionStart, PostToolUse, UserPromptSubmit hooks
  • Project-based organization with auto-detection
  • Python and Shell script implementations
  • Comprehensive documentation and examples

Built by Cogniz Memory Platform

About

Claude Code integration for Cogniz Memory Platform - Auto-save code, load context, and search memories

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors