Automation Hooks

Preserve context across compaction events with PreCompact and SessionStart hooks. Your LLM remembers what it learned, even after context window resets.

All Plans

Automation hooks are available on all plans, including Free.

What Are Automation Hooks?

When your LLM's context window fills up, it performs a "compaction" - summarizing the conversation to free up space. Without hooks, you lose important context like what files were accessed, what decisions were made, and what the current task is.

Automation hooks let you save and restore context automatically:

┌─────────────────────────────────────────────────────────────┐
│  CONTEXT PRESERVATION FLOW                                  │
│                                                             │
│  1. User works with Claude Code / Cursor                    │
│  2. Context window fills up → PreCompact hook triggers      │
│  3. Hook saves context to local file (.session-context)     │
│  4. Optionally syncs to Snipara cloud                       │
│  5. LLM compacts context                                    │
│  6. SessionStart hook restores saved context                │
│  7. User continues seamlessly                               │
└─────────────────────────────────────────────────────────────┘

Supported Hooks

PreCompact

Triggered before context compaction. Receives session summary via stdin. Use this to save important context that should survive the compaction.

context-checkpoint.sh

SessionStart

Triggered when starting a session after compaction or resume. Output is injected as additional context for the LLM.

session-restore.sh

PostToolUse

Triggered after a tool completes. Use with Bash matcher to save context on git commits.

commit-memory.sh
Agents Starter+

Supported AI Clients

ClientConfig FilePreCompactSessionStartNotes
Claude Code.claude/settings.jsonFullFullBest support
Cursor.cursor/mcp.jsonFullFullv1.7+ required
Continue.continue/config.jsonVia MCPVia MCPUse rlm_inject
Windsurf.windsurf/mcp.json--No hook support
Gemini.gemini/settings.jsonVia MCPVia MCPUse rlm_inject
VS Code Copilot.vscode/mcp.json--No hook support yet

Quick Setup (Claude Code)

Required Dependencies:
  • bash (v4+) - Pre-installed on macOS/Linux
  • jq - JSON processor: brew install jq (macOS) or apt install jq (Linux)

Step 1: Generate Configuration

Go to your project's Automation page in the Snipara dashboard and enable the desired options:

  • Preserve on Compaction: Save context when Claude compacts
  • Restore on Session Start: Restore context after compaction
  • Auto-Inject Context: Sync context to Snipara cloud

Download or copy the generated configuration files.

Step 2: Add Files to Your Project

Copy the generated files to your project root:

mkdir -p .claude/hooks
chmod +x .claude/hooks/*.sh

Step 3: Configuration Structure

Your .claude/settings.json should look like this:

{
  "mcpServers": {
    "your-project": {
      "transport": "http",
      "url": "https://api.snipara.com/mcp/your-project",
      "headers": { "X-API-Key": "rlm_..." }
    }
  },
  "hooks": {
    "PreCompact": [{
      "matcher": "auto",
      "hooks": [{ "type": "command", "command": ".claude/hooks/context-checkpoint.sh" }]
    }],
    "SessionStart": [{
      "matcher": "compact",
      "hooks": [{ "type": "command", "command": ".claude/hooks/session-restore.sh" }]
    }]
  }
}

Hook Scripts

PreCompact Hook (context-checkpoint.sh)

This script runs before compaction and saves the session context:

#!/bin/bash
# Pre-Compaction Hook for Context Preservation
set -e
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CHECKPOINT_FILE="$PROJECT_DIR/.claude/.session-context"
# Read context from stdin (Claude passes session summary)
CONTEXT=$(cat)
if [ -n "$CONTEXT" ]; then
  mkdir -p "$(dirname "$CHECKPOINT_FILE")"
  echo "$CONTEXT" > "$CHECKPOINT_FILE"
  echo "PreCompact: Checkpoint saved"
fi

SessionStart Hook (session-restore.sh)

This script runs after compaction and restores the saved context:

#!/bin/bash
# Session Restore Hook for Context Restoration
set -e
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CHECKPOINT_FILE="$PROJECT_DIR/.claude/.session-context"
if [ -f "$CHECKPOINT_FILE" ]; then
  CONTEXT=$(cat "$CHECKPOINT_FILE")
  if [ -n "$CONTEXT" ]; then
    # Output JSON for Claude to inject as context
    jq -n --arg content "$CONTEXT" '{
      hookSpecificOutput: {
        hookEventName: "SessionStart",
        additionalContext: $content
      }
    }'
  fi
fi

Memory Injection

Agents Starter+ Required: Memory Injection requires the Agents Starter+ subscription ($15/month).

Memory Injection enhances hooks with semantic memory persistence. Instead of just saving raw context, your LLM can remember decisions, learnings, and preferences across sessions.

┌─────────────────────────────────────────────────────────────┐
│  MEMORY INJECTION FLOW                                      │
│                                                             │
│  SessionStart:                                              │
│  1. Hook fetches memory settings from API                   │
│  2. Calls rlm_recall with configured filters                │
│  3. Retrieves relevant memories from previous sessions      │
│  4. Injects memories into Claude's context                  │
│                                                             │
│  During Session:                                            │
│  5. Claude uses rlm_remember to persist learnings           │
│                                                             │
│  PreCompact:                                                │
│  6. Hook stores session context as a memory (7-day TTL)     │
└─────────────────────────────────────────────────────────────┘

Memory Types

TypeUse Case
FACTProject-specific knowledge
DECISIONArchitectural or implementation choices
LEARNINGDiscovered patterns or behaviors
PREFERENCEUser preferences
TODOTask items and reminders
CONTEXTSession context (auto-saved by hooks)

Auto-Save on Commit

CLI Only: PostToolUse hooks currently work in the Claude Code CLI, not the VSCode extension. Use the CLI (claude command) to enable this feature.

Automatically save session context when a git commit is made. This ensures work is captured even if you close your session before context compaction occurs.

┌─────────────────────────────────────────────────────────────┐
│  AUTO-SAVE ON COMMIT FLOW                                   │
│                                                             │
│  1. User runs: git commit -m "feat: add auth"               │
│  2. Claude Code executes the Bash tool                      │
│  3. PostToolUse hook triggers for Bash tool                 │
│  4. Hook checks if command contains "git commit"            │
│  5. If yes: calls rlm_remember via MCP                      │
│  6. Memory stored with type=CONTEXT, TTL=7 days             │
│  7. Next session: recalled via SessionStart hook            │
└─────────────────────────────────────────────────────────────┘

Hook Configuration:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": ".claude/hooks/commit-memory.sh",
        "timeout": 15
      }]
    }]
  }
}

Enable in your dashboard: Project → Automation → Memory Injection → Save Memory on Commit

Cloud Sync (Optional)

When Auto-Inject Context is enabled, the PreCompact hook syncs context to Snipara cloud, enabling cross-session persistence:

POST /api/projects/{project}/automation/inject
Content-Type: application/json
X-API-Key: rlm_...

{
  "context": "Session context to store",
  "sessionId": "default",
  "append": false,
  "source": "hook"
}

The context can be retrieved later:

GET /api/projects/{project}/automation/inject?sessionId=default
X-API-Key: rlm_...

Response:
{
  "success": true,
  "data": {
    "id": "ctx_123",
    "sessionId": "default",
    "context": "Stored context...",
    "updatedAt": "2025-01-20T..."
  }
}

Testing Your Setup

Test Local Checkpoint

echo '{"test": "context data"}' | bash .claude/hooks/context-checkpoint.sh
PreCompact: Context checkpoint saved (25 bytes)

Test Local Restore

bash .claude/hooks/session-restore.sh
{
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "additionalContext": "{\"test\": \"context data\"}"
  }
}

Test Cloud API

curl -s -X POST "https://www.snipara.com/api/projects/your-project/automation/inject" \
  -H "X-API-Key: rlm_your_key" \
  -H "Content-Type: application/json" \
  -d '{"context": "Test context", "source": "manual"}'

Troubleshooting

IssueCauseSolution
"Invalid API key"API key not foundRegenerate key from dashboard
"API key does not match project"Key belongs to different projectUse correct key for project
"Project not found"Invalid slug/ID in URLVerify project slug in dashboard
Hook not triggeringScripts not executablechmod +x .claude/hooks/*.sh
Empty context restoredCheckpoint file missingCheck .claude/.session-context exists
jq not foundjq not installedInstall jq: brew install jq

Failure Modes & Recovery

Hooks are designed to fail gracefully. Here's what happens in common failure scenarios:

ScenarioBehaviorRecovery
jq not installedSessionStart outputs raw text instead of JSONInstall jq or use rlm_inject fallback
Cloud sync failsLocal checkpoint still savedContext persists locally; cloud sync retries next compaction
Hook script errorsLLM continues without restored contextRun scripts manually to debug: bash .claude/hooks/session-restore.sh
Permission deniedHook fails silentlyRun chmod +x .claude/hooks/*.sh

Manual Injection Fallback

If hooks aren't working, you can inject context manually via MCP tools:

rlm_inject({ context: "Working on auth refactor. Key files: auth.ts, middleware.ts" })

MCP Alternative

For clients without hook support, you can use MCP tools to manage context manually:

rlm_inject

Inject context into the current session. Use this before compaction to save important context.

rlm_inject("Working on auth refactor")

rlm_context

View current session context. Check what context is currently stored.

rlm_context()

Next Steps