跳到主要内容
    ↑↓ 选择↵ 打开esc 关闭
    中文English
    Davidcreador

    Branch Memory Manager

    v0.1.9记忆与上下文
    opencode-branch-memory-manager

    Automatically manages branch-specific context for OpenCode with auto-save, auto-load, and git workflow integration

    GitHub 星标

    1

    月装机量

    128

    近 7 天 21

    综合评分SCORE

    23.1

    生态多维模型

    最近提交

    7 个月前

    2026-01-05

    快速安装与配置

    opencode.json

    写入当前项目的 opencode.json,只对这个仓库生效。

    opencode.json

    {
      "$schema": "https://opencode.ai/config.json",
      "plugin": ["opencode-branch-memory-manager@0.1.9"]
    }

    opencode 启动时会通过内嵌运行时自动加载 npm 依赖并缓存至本地目录,无需手动在全局环境执行安装。

    Automatically manages branch-specific context for OpenCode so you never lose your development context when switching branches.

    ✨ Features

    • 🔄 Automatic Context Loading: Loads saved context when switching branches (configurable)
    • 💾 Automatic Saving: Auto-saves context on tool execution, session updates, and branch changes
    • 🎛️ Manual Control: Save/load context with fine-grained filters
    • 💾 Branch-Specific Storage: Context saved per git branch
    • 📊 Status Dashboard: See all your saved contexts at a glance
    • 🛡️ Error Resilient: Automatic backups and recovery from corrupted data
    • 🌐 Cross-Platform: Works seamlessly on macOS, Linux, and Windows
    • 📋 List & Delete: Manage saved contexts easily
    • 🎯 Configurable: Customize auto-save behavior, context loading mode, and storage options

    🚀 Quick Start

    Installation

    The plugin supports three installation methods to fit different workflows:

    Method 1: NPM Package (Recommended for Individual Users)

    Add the plugin to your opencode.json:

    {
      "plugin": ["opencode-branch-memory-manager"]
    }
    

    OpenCode will automatically install and load the package from npm when you run opencode.

    Alternative - Manual installation:

    # Install the package manually
    npm install opencode-branch-memory-manager
    # or
    bun install opencode-branch-memory-manager
    

    Then add it to your opencode.json as shown above.

    Method 2: Direct Git Clone (For Development/Testing)

    Clone the repository directly into your project:

    # Navigate to your project's .opencode directory
    cd .opencode
    
    # Clone the plugin
    git clone https://github.com/Davidcreador/opencode-branch-memory-manager.git
    
    # Install dependencies and build
    cd opencode-branch-memory-manager
    bun install
    bun run build:local
    

    The plugin will be automatically loaded when you run opencode from your project.

    Method 3: Marketplace (For Teams/Organizations)

    For team or organizational distribution, you can set up a marketplace:

    1. Add the marketplace to your .opencode/settings.json:

    {
      "extraKnownMarketplaces": {
        "your-org": {
          "source": {
            "source": "github",
            "repo": "your-org/opencode-plugins"
          }
        }
      }
    }
    

    2. Enable the plugin:

    {
      "enabledPlugins": {
        "branch-memory-manager@your-org": true
      }
    }
    

    The plugin will be installed from your organization's marketplace.

    Getting Started

    opencode
    
    # Check status
    @branch-memory_status
    
    # Save current context with filters
    @branch-memory_save --include-messages --include-todos --include-files "Working on user authentication"
    
    # Load context for a specific branch
    @branch-memory_load --branch feature/payment-api
    
    # List all saved contexts
    @branch-memory_list --verbose
    

    📖 Commands

    @branch-memory_save

    Save current session context for current git branch.

    Arguments:

    • --include-messages: Include conversation messages (default: true)
    • --include-todos: Include todo items (default: true)
    • --include-files: Include modified files (default: true)
    • --description: Description of what you're saving

    Examples:

    # Save everything
    @branch-memory_save "Adding Stripe integration"
    
    # Save only messages and todos
    @branch-memory_save --include-messages --include-todos "Quick checkpoint"
    
    # Save only files
    @branch-memory_save --include-files "API work"
    

    @branch-memory_load

    Load branch-specific context into current session.

    Arguments:

    • --branch: Branch name (default: current branch)

    Examples:

    # Load current branch context
    @branch-memory_load
    
    # Load specific branch context
    @branch-memory_load --branch feature/authentication
    

    @branch-memory_status

    Show branch memory status and available contexts.

    Examples:

    @branch-memory_status
    

    Output:

    📊 Branch Memory Status
    ═════════════════
    
    Current branch: feature/user-auth
    Current context:
      📝 Messages: 23
      ✅ Todos: 7
      📁 Files: 5
      💾 Size: 2.3KB
      ⏰ Saved: 2025-01-01T14:30:00.000Z
      📄 Description: Adding user authentication with OAuth
    
    Available contexts:
      → feature/user-auth (2.3KB, 2025-01-01T14:30:00)
      → feature/payment-api (4.1KB, 2025-01-01T15:45:00)
        main (1.8KB, 2025-01-01T12:00:00.000Z)
    

    @branch-memory_deleteContext

    Delete saved context for a branch.

    Arguments:

    • --branch: Branch name to delete context for

    Example:

    @branch-memory_deleteContext --branch old-feature
    

    @branch-memory_list

    List all branches with saved contexts.

    Arguments:

    • --verbose: Show detailed information including message, todo, and file counts

    Examples:

    @branch-memory_list
    
    # With verbose details
    @branch-memory_list --verbose
    

    Output (verbose):

    📋 Branches with saved contexts
    ═════════════════
    
    feature/user-auth
      💾 Size: 2.3KB
      ⏰ Modified: 2025-01-01T14:30:00
      📝 Messages: 23
      ✅ Todos: 7
      📁 Files: 5
    
    feature/payment-api
      💾 Size: 4.1KB
      ⏰ Modified: 2025-01-01T15:45:00
      📝 Messages: 31
      ✅ Todos: 12
      📁 Files: 8
    
    main
      💾 Size: 1.8KB
      ⏰ Modified: 2025-01-01T12:00:00
      📝 Messages: 15
      ✅ Todos: 3
      📁 Files: 2
    
    ═════════════════
    Total: 3 branch(es)
    

    ⚙️ Configuration

    Configuration is stored in .opencode/config/branch-memory.json

    Default Configuration

    {
      "autoSave": {
        "enabled": true,
        "onMessageChange": true,
        "onBranchChange": true,
        "onToolExecute": true
      },
      "contextLoading": "auto",
      "context": {
        "defaultInclude": ["messages", "todos", "files"],
        "maxMessages": 50,
        "maxTodos": 20,
        "compression": false
      },
      "storage": {
        "maxBackups": 5,
        "retentionDays": 90
      },
      "monitoring": {
        "method": "both",
        "pollingInterval": 1000
      }
    }
    

    Configuration Options

    autoSave

    • enabled: Enable/disable automatic saving (default: true)
    • onMessageChange: Auto-save when messages change (default: true)
    • onBranchChange: Auto-save when switching branches (default: true)
    • onToolExecute: Auto-save before running tools (default: true)

    contextLoading

    • "auto": Automatically load context when switching branches
    • "ask": Prompt user before loading context
    • "manual": Don't auto-load; use @branch-memory_load manually

    context

    • defaultInclude: Array of data types to include by default
    • maxMessages: Maximum number of messages to save (default: 50)
    • maxTodos: Maximum number of todos to save (default: 20)
    • compression: Enable compression (not yet implemented)

    storage

    • maxBackups: Number of backups to keep (default: 5)
    • retentionDays: Days to keep old contexts (default: 90)

    monitoring

    • "watcher": Use file watcher only (fast, uses chokidar)
    • "polling": Use polling only (reliable, slower)
    • "both": Use watcher with polling fallback (default)

    🔧 How It Works

    1. Initialization: Plugin loads configuration from .opencode/config/branch-memory.json
    2. Automatic Features (when plugin is loaded):
      • Auto-loads context when a new session starts (configurable)
      • Auto-saves before tool execution
      • Auto-saves on session updates (throttled)
      • Monitors for git branch changes and auto-loads/saves
    3. Manual Saving: Use @branch-memory_save to save context:
      • Saves conversation messages
      • Saves todo items
      • Saves modified file references
    4. Manual Loading: Use @branch-memory_load to restore context:
      • Loads messages and todos
      • Shows what was saved
    5. Status Checking: Use @branch-memory_status to see:
      • Current branch and context
      • All saved contexts
      • Metadata (size, dates, counts)
    6. Error Recovery: Automatic backups prevent data loss
    7. Management: Use @branch-memory_list and @branch-memory_deleteContext to manage saved contexts

    🐛 Troubleshooting

    Tools not available

    1. Check if tools are in opencode.json:
    {
      "tools": ["@branch-memory_save", "@branch-memory_load", "@branch-memory_status", "@branch-memory_list", "@branch-memory_deleteContext"]
    }
    
    1. Verify dependencies are installed:
    cd .opencode
    bun install
    

    Context not saving

    1. Check if in a git repository:
    git status
    
    1. Check configuration:
    cat .opencode/config/branch-memory.json
    
    1. Check logs for errors:
    # Look for emoji indicators:
    # ✅ = success
    # ⚠️  = warning
    # ❌ = error
    

    Branch changes not detected

    1. Verify git repository:
    git rev-parse --git-dir
    
    1. Check .git/HEAD file exists and is being updated

    2. Try both monitoring modes:

    {
      "monitoring": {
        "method": "watcher"  // or "polling"
      }
    }
    

    Corrupted context files

    The system automatically restores from backups. If issues persist:

    1. Check backup files:
    ls -la .opencode/branch-memory/
    
    1. Manual cleanup:
    @branch-memory_deleteContext --branch broken-branch
    

    Permission errors

    1. Check file permissions:
    ls -la .opencode/branch-memory/
    
    1. Ensure write access:
    chmod -R u+w .opencode/branch-memory/
    

    📁 File Structure

    .opencode/
    ├── plugin/
    │   └── branch-memory-plugin.ts   # Event hooks for auto-save/load
    ├── tool/
    │   └── branch-memory.ts          # User-facing tools
    ├── branch-memory/
    │   ├── index.ts                  # Exports
    │   ├── storage.ts                # Context persistence
    │   ├── git.ts                   # Git operations
    │   ├── monitor.ts                # Branch monitoring
    │   ├── collector.ts             # Context collection
    │   ├── injector.ts              # Context injection
    │   ├── types.ts                 # TypeScript types
    │   └── config.ts                # Configuration
    ├── config/
    │   └── branch-memory.json        # Configuration file
    └── package.json                  # Dependencies
    

    🚀 Advanced Usage

    Custom Configuration

    Edit .opencode/config/branch-memory.json to customize behavior:

    {
      "autoSave": {
        "enabled": true,
        "onMessageChange": true,
        "onBranchChange": true,
        "onToolExecute": true
      },
      "contextLoading": "ask",
      "context": {
        "defaultInclude": ["messages", "todos", "files"],
        "maxMessages": 100,
        "maxTodos": 50
      }
    }
    

    Workflow Example

    1. Start working on a feature:
    git checkout -b feature/user-profile
    opencode
    
    1. Context auto-loads on session start (if contextLoading is "auto"):
    🚀 Session created - checking for saved context...
    📥 Found context for branch 'feature/user-profile'
       Use @branch-memory_load to restore it
    
    1. Work on feature - context auto-saves as you work:
    # Plugin auto-saves before tool execution and periodically
    @branch-memory_save "Adding user profile feature"
    
    1. Switch to main to work on bug fix:
    git checkout main
    # Plugin detects branch change
    🔄 Branch changed: feature/user-profile → main
    💾 Saved context for old branch 'feature/user-profile'
    📥 Found context for branch 'main'
    
    1. Switch back to feature - context auto-loads:
    git checkout feature/user-profile
    # Plugin detects branch change
    🔄 Branch changed: main → feature/user-profile
    📥 Found context for branch 'feature/user-profile'
       Use @branch-memory_load to restore it
    
    1. Or manually load context:
    @branch-memory_load
    
    # Context is restored - messages and todos are back
    

    🛠️ Development

    Type Check

    bun run typecheck
    

    Testing

    bun test
    

    🛠️ Local Development

    For development, testing, and local usage, you can install directly without npm:

    # 1. Install dependencies
    bun install
    
    # 2. Build
    bun run build
    
    # 3. The .opencode/ directory is ready to use
    # The build creates .opencode/dist/ with all plugin files
    

    The .opencode/ directory structure is now ready:

    .opencode/
    ├── dist/
    │   └── branch-memory.js       # Bundled plugin + tools
    ├── config/
    │   └── branch-memory.json      # Configuration
    └── package.json                  # Dependencies
    

    Note: For development, you can work directly in src/ and run npm run build:local to test the .opencode/ version.

    📦 Publishing to npm

    1. Update version in package.json
    2. Build: bun run build
    3. Publish: npm publish --access public

    Make sure you're logged in to npm: npm whoami

    📝 Notes

    • Package name: opencode-branch-memory-manager (unscoped)
    • Scoped packages (@davidcreador/...) may require OTP for publishing
    • If prompted for OTP, provide the one-time password
    • For testing purposes, unscoped name avoids OTP requirement
    • After successful publish with unscoped name, you can switch to scoped name if needed
    • Update README and package.json accordingly
    1. Update version in package.json
    2. Build: bun run build
    3. Publish: npm publish

    Make sure you're logged in to npm: npm whoami

    📝 License

    MIT License - see LICENSE file for details.

    🤝 Contributing

    Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

    🐛 Issues

    Found a bug? Have a feature request? Please open an issue on GitHub.


    Made with ❤️ for the OpenCode community