Skip to content

fjibj/claude-code-smart-fork

Repository files navigation

Claude Code Smart Fork

🔀 Smart session forking for Claude Code - Find and resume relevant historical sessions across all your projects using AI-powered semantic search.

中文 | English

npm version License: MIT Node.js CI

🌟 Features

  • 🔍 Semantic Search - Find relevant sessions based on meaning, not just keywords
  • 🌐 Cross-Project - Search across all your projects, not just the current one
  • 🤖 AI-Powered - Uses embeddings to understand context and intent
  • Fast - Local vector storage for instant results
  • 🔒 Private - All data stays on your machine by default
  • 🎯 Easy Integration - Works seamlessly with Claude Code as slash commands

✨ Key Advantages

1. Complete Session History Preservation

Traditional Smart Fork
❌ Only records user input Records both input AND output
❌ Assistant responses lost ✅ Saves complete conversation turns
❌ Context is lost ✅ Preserves all tool calls and metadata
  • Full conversation history saved (user messages + assistant responses)
  • Stored locally in ~/.smart-fork/sessions/<session-id>.json
  • Includes all tool calls, metadata, and timestamps
  • Zero token cost for retrieval (local vector search)

2. 🔐 Privacy First - Fully Local Storage

Data Flow Comparison:

Cloud-based RAG:
  User → Local → Cloud API → Cloud Storage → Results
          ⚠️ Data leaves your machine

Smart Fork:
  User → Local → Local Vector DB → Results
          ✅ Data stays local

Storage Location:

~/.smart-fork/
├── config.json      # Config (local)
├── index.json       # Index + Embeddings (local)
└── sessions/        # Full session data (local)

Benefits:

  • ✅ No data uploaded to cloud (when using local embedding)
  • ✅ No data breach concerns
  • ✅ Enterprise-grade data security
  • ✅ Works offline

3. 💰 Zero Token Cost - Free Retrieval

Operation Traditional RAG Smart Fork
Index session API call required (paid) Local compute (free)
Search sessions API call required (paid) Local compute (free)
Storage Cloud DB (ongoing cost) Local JSON (free)

4. 🤖 Human-in-the-Loop Design

Smart Fork follows Human-in-the-Loop design philosophy:

┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  User Decision│ ──> │ Tool Execution│ ──> │  Confirmation │
│ (Select session)│   │ (Switch session)│  │ (Continue chat)│
└──────────────┘     └──────────────┘     └──────────────┘
       ↑                                                      │
       └──────────────────────────────────────────────────────┘
                        Human Control Loop

How it works:

  1. Search phase - System recommends sessions, user selects
  2. Switch phase - User confirms before switching
  3. Continue phase - User decides whether to continue from history

5. 📦 Complete Context at Session Level

The problem with current tools:

Current CLI tools:
- Only record current session input
- Don't save assistant output (tool results, thinking, etc.)
- All context lost when switching sessions

Smart Fork solution:

{
  "conversationHistory": [
    {
      "userMessage": { "content": "npm install error 403" },
      "assistantMessage": {
        "content": "Let me help you...",
        "toolCalls": [{"type": "Bash", "command": "npm install"}]
      }
    }
  ]
}

Benefits:

  • ✅ Complete conversation turns saved
  • ✅ Tool calls and results included
  • ✅ Can restore to exact previous state
  • ✅ Knowledge retention and team sharing

6. 🚀 Cross-Project Semantic Search

Traditional grep search:
  Search "npm error" → Only matches files with those characters
  ❌ Won't find "npm install failed" or "403 forbidden"

Smart Fork semantic search:
  Search "npm error" → Finds relevant sessions
  ✅ Understands "npm install failed" and "403 forbidden" are related

Technical implementation:

  • Vector embeddings (384 dimensions)
  • Cosine similarity calculation
  • Chinese and English support
  • Local keyword embedder (no external API needed)

7. 🛠️ Seamless Claude Code Integration

Slash commands:

/fork-detect     # Search sessions
/fork-to <id>    # Switch to session
/fork-back       # Return to previous
/index-session   # Index current
/list-sessions   # List all
/fork-status     # Show status

8. 📊 Performance Comparison

Feature Traditional Smart Fork
Index speed ~500ms (API call) <10ms (local)
Search speed ~500ms (API call) <50ms (in-memory)
Storage cost Cloud (ongoing) Local JSON (free)
Privacy ⚠️ Data to cloud ✅ Fully local
Offline mode ❌ Needs internet ✅ Fully offline

📦 Installation

# Install globally
npm install -g claude-code-smart-fork

# Or use npx (no installation needed)
npx claude-code-smart-fork

🚀 Quick Start

1. Index Your Current Session

smart-fork index --summary "Implementing user authentication"

2. Later, Find Relevant Sessions

smart-fork detect

3. Switch to a Session

smart-fork fork-to <session-id>

🛠️ Usage

CLI Commands

Command Description
smart-fork index Index current session for future searching
smart-fork detect Find relevant historical sessions
smart-fork detect --all Search across all projects
smart-fork list List all indexed sessions
smart-fork status Show current status and suggestions
smart-fork export <id> Export a session to JSON

Claude Code Integration

After installation, these slash commands are available in Claude Code:

/index-session    - Index current session
/fork-detect      - Find relevant sessions
/fork-to <id>     - Switch to a session
/list-sessions    - List all sessions
/fork-status      - Show status and suggestions

⚙️ Configuration

Create ~/.smart-fork/config.json:

{
  "embedding": {
    "provider": "local",
    "model": "all-MiniLM-L6-v2",
    "dimension": 384
  },
  "vectorStore": {
    "provider": "local",
    "collectionName": "smart-fork-sessions"
  },
  "storage": {
    "sessionsDir": "~/.smart-fork/sessions",
    "indexPath": "~/.smart-fork/index.json"
  }
}

Embedding Providers

Local (Default) - No API key needed

{
  "embedding": {
    "provider": "local",
    "model": "all-MiniLM-L6-v2"
  }
}

OpenAI

{
  "embedding": {
    "provider": "openai",
    "model": "text-embedding-3-small"
  }
}

Requires OPENAI_API_KEY environment variable.

Ollama

{
  "embedding": {
    "provider": "ollama",
    "model": "nomic-embed-text"
  }
}

Requires a running Ollama server.

💡 Usage Examples

Example 1: Index a Session with Conversation History

# Create a conversation history file
cat > conversation.json << 'EOF'
[
  {
    "id": "turn-1",
    "timestamp": 1709400000000,
    "userMessage": {
      "content": "How do I implement user authentication?",
      "metadata": { "files": ["auth.js"] }
    },
    "assistantMessage": {
      "content": "I recommend using JWT + OAuth2. JWT is great for stateless auth, OAuth2 for third-party login.",
      "toolCalls": [{"id": "1", "type": "search", "parameters": {"query": "JWT best practices"}}]
    }
  },
  {
    "id": "turn-2",
    "timestamp": 1709400100000,
    "userMessage": {
      "content": "Show me code examples"
    },
    "assistantMessage": {
      "content": "Here's a Node.js example using jsonwebtoken...",
      "toolCalls": [
        {"id": "2", "type": "read_file", "parameters": {"path": "examples/auth.js"}},
        {"id": "3", "type": "edit_file", "parameters": {"path": "src/auth.js"}}
      ]
    }
  }
]
EOF

# Index the session
smart-fork index --conversation conversation.json --summary "User authentication with JWT" --tags "auth,jwt,nodejs"

# Output:
# ✓ Session indexed successfully!
# Session ID: 096549e9-13bd-45bd-9f6c-659d55c78b35
# Conversation turns: 2
# Total messages: 4

Example 2: Find and Resume a Session

# Search for relevant sessions
smart-fork detect --query "authentication JWT code examples"

# Output:
# ✓ Found 1 relevant session(s):
#
# 1. my-first-app
#    Path: D:\\claudecode\\MyAICodes\\my-first-app
#    Relevance: 85%
#    Summary: User authentication with JWT
#    Last updated: 2026/3/2

# Fork to the session
smart-fork fork-to 096549e9-13bd-45bd-9f6c-659d55c78b35

# Output:
# 💬 Conversation History:
# ────────────────────────────────────────────────────────────
# [1] 👤 User:
# How do I implement user authentication?
#     🤖 Assistant:
# I recommend using JWT + OAuth2...
#     🔧 Tool calls: search
# ────────────────────────────────────────────────────────────
# [2] 👤 User:
# Show me code examples
#     🤖 Assistant:
# Here's a Node.js example...
#     🔧 Tool calls: read_file, edit_file
# ────────────────────────────────────────────────────────────
# ✨ Total turns: 2
# 💡 You can continue the conversation from here.

Example 3: Cross-Project Search

# Index sessions in multiple projects
# Project A: API Gateway
cd ~/projects/api-gateway
smart-fork index --summary "Implementing rate limiting middleware"

# Project B: Frontend
cd ~/projects/frontend
smart-fork index --summary "Setting up React authentication context"

# Search across all projects
cd ~/projects/api-gateway
smart-fork detect --all --query "authentication middleware"

# Results will show relevant sessions from both projects!

Example 4: Using with Claude Code Slash Commands

# In Claude Code, use slash commands:

# Index current session
/index-session Implementing user authentication --tags auth,jwt

# Later, find relevant sessions
/fork-detect

# Fork to a specific session
/fork-to 096549e9-13bd-45bd-9f6c-659d55c78b35

# List all sessions
/list-sessions

📁 Data Storage

All data is stored locally in ~/.smart-fork/:

~/.smart-fork/
├── sessions/          # Full session data (JSON)
├── index.json         # Session index with embeddings
└── config.json        # User configuration

🔧 Development

# Clone the repository
git clone https://github.com/fjibj/claude-code-smart-fork.git
cd claude-code-smart-fork

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Watch mode for development
npm run dev

📚 API Usage

import { ForkDetector, SessionManager } from 'claude-code-smart-fork';

const detector = new ForkDetector();
await detector.initialize();

// Find relevant sessions
const results = await detector.findRelevantSessions({
  text: "How to implement authentication?",
  limit: 5
});

// Switch to a session
const sessionManager = new SessionManager();
await sessionManager.forkToSession(results[0].session.id);

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

📄 License

MIT License - see LICENSE file for details.

🙏 Acknowledgments

  • Inspired by the need for better session management in Claude Code
  • Thanks to the open-source community for the amazing tools

📮 Support

About

Smart session forking for Claude Code - find and resume relevant historical sessions across projects

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors