Skip to content

Latest commit

 

History

History
487 lines (421 loc) · 21.2 KB

File metadata and controls

487 lines (421 loc) · 21.2 KB

ContextStream Claude Code Plugin - Complete Implementation

Version: 1.0.0 Date: January 2026 Architecture: Pure hooks + shell scripts (zero dependencies)


Table of Contents

  1. Overview
  2. Architecture
  3. Hook System
  4. API Scripts
  5. Search System
  6. Snapshot System
  7. Compaction Handling
  8. File Structure
  9. API Endpoints Required
  10. Configuration

Overview

The ContextStream Claude Code Plugin provides intelligent, automatic memory and context management for Claude Code sessions. It uses hooks that run automatically at key moments in the conversation.

Key Principles

  1. Automatic Execution - Hooks run at specific events without manual intervention
  2. Lightweight - Pure bash + curl + jq, no npm/node required
  3. Intelligent Automation - Detects patterns, learns from errors, triggers snapshots
  4. Complete Coverage - Every aspect of the conversation is captured and enhanced

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                     CLAUDE CODE SESSION                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │ SessionStart │───▶│ session-init │───▶│ Full Context │       │
│  └──────────────┘    └──────────────┘    └──────────────┘       │
│                                                                  │
│  ┌──────────────┐    ┌───────────────┐   ┌──────────────┐       │
│  │ User Message │───▶│ smart-context │───▶│ Auto-Search  │       │
│  └──────────────┘    └───────────────┘   │ + Warnings   │       │
│                                           └──────────────┘       │
│                                                                  │
│  ┌──────────────┐    ┌────────────────┐  ┌──────────────┐       │
│  │ Edit/Write   │───▶│ on-file-change │───▶│ Capture +    │       │
│  └──────────────┘    └────────────────┘  │ Index +      │       │
│                                           │ Snapshot     │       │
│                                           └──────────────┘       │
│                                                                  │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │ Bash Command │───▶│   on-bash    │───▶│ Learn Errors │       │
│  └──────────────┘    └──────────────┘    │ + Snapshot   │       │
│                                           └──────────────┘       │
│                                                                  │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │ Pre-Compact  │───▶│ pre-compact  │───▶│ Save All     │       │
│  └──────────────┘    └──────────────┘    └──────────────┘       │
│                                                                  │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │ Post-Compact │───▶│ post-compact │───▶│ Restore All  │       │
│  └──────────────┘    └──────────────┘    └──────────────┘       │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
                 ┌────────────────────────┐
                 │  ContextStream API     │
                 │  api.contextstream.io  │
                 └────────────────────────┘

Hook System

12 Hook Scripts

Script Trigger Purpose Key Features
session-init.sh SessionStart Initialize session Injects decisions, lessons, tasks, plans, user profile, project context
smart-context.sh UserPromptSubmit Per-message context Analyzes message, auto-searches, surfaces warnings/lessons
on-file-change.sh Edit/Write/NotebookEdit File change handler Captures, indexes, updates graph, detects patterns, triggers snapshots
on-bash.sh Bash Command handler Captures commands, learns from errors, detects patterns, triggers snapshots
on-task.sh Task Agent handler Tracks agent work, updates plan progress, triggers snapshots
on-read.sh Read/Glob/Grep File read tracker Tracks exploration patterns
on-web.sh WebFetch/WebSearch Web research handler Captures research, indexes findings
pre-compact.sh PreCompact Pre-compaction Saves full conversation, extracts decisions/lessons, generates continuation
post-compact.sh SessionStart (compact) Post-compaction Restores full context after compaction
on-stop.sh Stop Session end Finalizes session, flushes pending data
snapshot-trigger.sh Internal Snapshot trigger Called by other hooks for strategic snapshots

hooks.json Configuration

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|clear",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/session-init.sh",
            "timeout": 15000
          }
        ]
      },
      {
        "matcher": "compact",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/post-compact.sh",
            "timeout": 10000
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/smart-context.sh",
            "timeout": 5000
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-file-change.sh",
            "timeout": 5000
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-bash.sh",
            "timeout": 5000
          }
        ]
      },
      {
        "matcher": "Task",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-task.sh",
            "timeout": 5000
          }
        ]
      },
      {
        "matcher": "Read|Glob|Grep",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-read.sh",
            "timeout": 3000
          }
        ]
      },
      {
        "matcher": "WebFetch|WebSearch",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-web.sh",
            "timeout": 3000
          }
        ]
      }
    ],
    "PreCompact": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/pre-compact.sh",
            "timeout": 15000
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/on-stop.sh",
            "timeout": 5000
          }
        ]
      }
    ]
  }
}

API Scripts

19 API Scripts

Script Purpose Key Actions
cs-search.sh Comprehensive search 15 search modes (smart, hybrid, semantic, keyword, pattern, memory, code, files, knowledge, github, slack, notion, media, team, all)
cs-recall.sh Natural language recall Ask questions about past work
cs-capture.sh Quick capture Capture decision, lesson, note, insight
cs-decisions.sh Decision management list, capture, trace
cs-lessons.sh Lesson management list, get, capture
cs-todos.sh Todo management list, add, done, delete
cs-plans.sh Plan management list, get, create, update, complete
cs-reminders.sh Reminder management list, create, snooze, complete, dismiss
cs-diagrams.sh Mermaid diagrams list, get, create, update, delete
cs-docs.sh Persistent docs list, get, create, update, delete
cs-graph.sh Code analysis deps, impact, circular, unused, path
cs-project.sh Project management index, status, overview, stats, files
cs-knowledge.sh Knowledge graph list, get, create, update, supersede, delete, relate
cs-media.sh Media indexing index, status, search, get, list, delete
cs-workspace.sh Workspace management list, get, create, associate, bootstrap
cs-ai.sh AI features plan, tasks, embeddings, context, analyze
cs-snapshot.sh Strategic snapshots save, list, get, restore, diff, auto
cs-integrations.sh External integrations github/slack/notion search, status, activity
cs-team.sh Team features decisions, lessons, plans, activity, search

Search System

15 Search Modes

# Smart (auto-detects best mode)
cs-search.sh "authentication"

# Core modes
cs-search.sh hybrid "query"      # Semantic + keyword
cs-search.sh semantic "query"    # Meaning-based
cs-search.sh keyword "query"     # Exact matches
cs-search.sh pattern "regex"     # Code patterns

# Memory search
cs-search.sh memory "query"      # Decisions, lessons, notes
cs-search.sh knowledge "query"   # Knowledge graph nodes

# Code search
cs-search.sh code "handleAuth"   # Functions, classes, symbols
cs-search.sh files "config"      # File names/paths

# Integration search
cs-search.sh github "bug fix"    # GitHub issues, PRs
cs-search.sh slack "deployment"  # Slack messages
cs-search.sh notion "roadmap"    # Notion pages

# Other
cs-search.sh media "meeting"     # Video/audio transcripts
cs-search.sh team "auth"         # Cross-project search
cs-search.sh all "query"         # Everything at once

Auto-Search Detection

The smart-context.sh hook analyzes each user message and auto-triggers relevant searches:

User Message Pattern Detected Intent Auto-Search Type
"where did", "find the", "search for" search_needed hybrid
"why did we", "decision about" decision_search memory (decisions)
"error with", "bug in", "problem" lesson_search memory (lessons)
"function", "class", "handler" code_search code symbols
".ts", ".py", "config" file_search files
"github", "issue", "PR" integration_search integrations

Snapshot System

Automatic Snapshot Triggers

Trigger Hook When
Database changes on-file-change .sql, migration, schema files
Config changes on-file-change .env, config, secrets
Infrastructure on-file-change Dockerfile, docker-compose, yaml
Dependencies on-file-change package.json, Cargo.toml, etc.
Risky operations on-file-change DROP TABLE, rm -rf, force push
Git commits on-bash git commit, merge, rebase
Git push on-bash git push
Deployments on-bash deploy, migrate, rollback
Package publish on-bash npm/cargo/pip publish
Docker builds on-bash docker build, push
Error fixes on-bash Success after previous error
Plan steps on-task Plan agent completes
Important findings on-task Explore agent finds issues
Pre-compaction pre-compact Before context compaction

Manual Snapshot Commands

cs-snapshot.sh save "Before refactor"    # Save with label
cs-snapshot.sh list                       # List all snapshots
cs-snapshot.sh get <id>                   # View snapshot
cs-snapshot.sh restore <id>               # Restore context
cs-snapshot.sh diff <id>                  # See what changed
cs-snapshot.sh auto all true              # Enable all auto-triggers

Compaction Handling

Flow

┌─────────────────────────────────────────────────────────────┐
│                    CONTEXT COMPACTION                        │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  PRE-COMPACT (before compaction)                            │
│  ─────────────────────────────────                          │
│  • Saves full conversation (up to 50KB)                     │
│  • Extracts decisions made in session                       │
│  • Extracts lessons learned                                 │
│  • Captures files modified                                  │
│  • Updates plan progress                                    │
│  • Generates continuation context                           │
│  • Creates session summary                                  │
│                                                              │
│  ────────── COMPACTION HAPPENS ──────────                   │
│                                                              │
│  POST-COMPACT (after compaction)                            │
│  ──────────────────────────────                             │
│  • Injects session summary                                  │
│  • Restores continuation context                            │
│  • Shows active plan with progress                          │
│  • Lists active tasks                                       │
│  • Shows decisions made this session                        │
│  • Lists files modified                                     │
│  • Surfaces relevant lessons                                │
│  • Includes any warnings                                    │
│  • Suggests next steps                                      │
│                                                              │
└─────────────────────────────────────────────────────────────┘

File Structure

claude-code/
├── .claude-plugin/
│   └── plugin.json              # Plugin manifest
├── hooks/
│   └── hooks.json               # Hook configuration
├── scripts/
│   ├── hooks/                   # 11 hook scripts
│   │   ├── session-init.sh      # Comprehensive session setup
│   │   ├── smart-context.sh     # Per-message intelligence + auto-search
│   │   ├── on-file-change.sh    # File change handling + snapshots
│   │   ├── on-bash.sh           # Command handling + error learning
│   │   ├── on-task.sh           # Task agent tracking + plan progress
│   │   ├── on-read.sh           # File exploration tracking
│   │   ├── on-web.sh            # Web research capture
│   │   ├── pre-compact.sh       # Pre-compaction: save everything
│   │   ├── post-compact.sh      # Post-compaction: restore everything
│   │   ├── on-stop.sh           # Session finalization
│   │   └── snapshot-trigger.sh  # Internal: strategic snapshot trigger
│   ├── cs-search.sh             # Comprehensive search (15 modes)
│   ├── cs-recall.sh             # Natural language recall
│   ├── cs-capture.sh            # Quick capture
│   ├── cs-decisions.sh          # Decision management
│   ├── cs-lessons.sh            # Lesson management
│   ├── cs-todos.sh              # Todo management
│   ├── cs-plans.sh              # Plan management
│   ├── cs-reminders.sh          # Reminder management
│   ├── cs-diagrams.sh           # Mermaid diagrams
│   ├── cs-docs.sh               # Persistent docs
│   ├── cs-graph.sh              # Code analysis
│   ├── cs-project.sh            # Project management
│   ├── cs-knowledge.sh          # Knowledge graph
│   ├── cs-media.sh              # Media indexing
│   ├── cs-workspace.sh          # Workspace management
│   ├── cs-ai.sh                 # AI features
│   ├── cs-snapshot.sh           # Strategic snapshots
│   ├── cs-integrations.sh       # External integrations
│   └── cs-team.sh               # Team features
├── README.md                    # User documentation
└── IMPLEMENTATION.md            # This file

API Endpoints Required

The plugin requires these API endpoints on the ContextStream backend:

Plugin-Specific Endpoints

Endpoint Method Purpose
/api/v1/plugin/session-init POST Full session initialization
/api/v1/plugin/smart-context POST Per-message smart context with auto-search
/api/v1/plugin/on-file-change POST File change capture + indexing
/api/v1/plugin/on-bash POST Command capture + error learning
/api/v1/plugin/on-task POST Task agent tracking
/api/v1/plugin/on-read POST File read tracking
/api/v1/plugin/on-web POST Web research capture
/api/v1/plugin/pre-compact POST Pre-compaction save
/api/v1/plugin/post-compact POST Post-compaction restore
/api/v1/plugin/session-end POST Session finalization
/api/v1/plugin/snapshot POST Strategic snapshot management

Existing Endpoints Used

Endpoint Method Purpose
/api/v1/search POST All search types
/api/v1/memory POST Memory operations
/api/v1/session POST Session operations
/api/v1/integration POST Integration operations
/api/v1/workspaces GET/POST Workspace management
/api/v1/projects GET/POST Project management
/api/v1/ai POST AI operations

Configuration

Environment Variables

Variable Required Default Description
CONTEXTSTREAM_API_KEY Yes - API key from console.contextstream.io
CONTEXTSTREAM_API_URL No https://api.contextstream.io API base URL
CLAUDE_PLUGIN_ROOT Auto - Set by Claude Code
CLAUDE_SESSION_ID Auto - Set by Claude Code

Installation

# Install the plugin
/plugin install contextstream/claude-code

# Set API key
export CONTEXTSTREAM_API_KEY="cs_your_key_here"

# Restart Claude Code

Summary

30 Total Scripts:

  • 11 Hook scripts (intelligent automation)
  • 19 API scripts (on-demand functionality)

Key Features:

  1. Automatic Execution - Hooks run at specific events
  2. Intelligent Automation - Detects patterns, learns from errors, triggers snapshots
  3. Complete Compaction Handling - Nothing is lost during context compaction
  4. Comprehensive Search - 15 search modes with auto-detection
  5. Strategic Snapshots - Automatic at key moments
  6. Lightweight - Pure bash + curl + jq