# https://github.com/mksglu/context-mode Project Manual

Generated on: 2026-05-24 22:22:50 UTC

## Table of Contents

- [Introduction to Context Mode](#introduction)
- [Core Concepts](#core-concepts)
- [Getting Started](#getting-started)
- [Architecture Overview](#architecture-overview)
- [Platform Adapters](#platform-adapters)
- [Hooks System](#hooks-system)
- [Context Saving](#context-saving)
- [Session Continuity](#session-continuity)
- [Think in Code Paradigm](#think-in-code)
- [Session Storage](#session-storage)

<a id='introduction'></a>

## Introduction to Context Mode

### Related Pages

Related topics: [Core Concepts](#core-concepts), [Getting Started](#getting-started)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/mksglu/context-mode/blob/main/README.md)
- [BENCHMARK.md](https://github.com/mksglu/context-mode/blob/main/BENCHMARK.md)
- [insight/src/routes/index.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)
</details>

# Introduction to Context Mode

Context Mode is a plugin-based system designed to manage and orchestrate instruction rules for AI language models. The system provides a flexible framework for loading, tracking, and maintaining rules that shape how AI models interpret and respond to various scenarios.

## Overview

Context Mode operates as an extensible plugin architecture that allows developers to define custom rules and instruction sets. These rules are loaded dynamically and can be applied to modify the behavior of AI interactions without requiring changes to the core system.

### Core Concepts

The system revolves around the concept of **rules** - JSON or YAML files that contain instruction templates and behavioral guidelines. Each rule can specify:

- The context in which it applies
- The instruction format to follow
- Associated metadata for tracking usage

### Key Features

| Feature | Description |
|---------|-------------|
| Plugin Architecture | Extensible system for loading custom rule handlers |
| Rule Freshness Tracking | Monitors when rules were last used or updated |
| Load Counting | Tracks how frequently each rule is accessed |
| Health Monitoring | Provides insights into rule maintenance status |

## System Architecture

```mermaid
graph TD
    A[User Request] --> B[Context Mode Core]
    B --> C[Rule Loader]
    C --> D[Plugin Registry]
    D --> E[Rule Files]
    E --> F[instruction files]
    F --> G[Loaded Rules]
    G --> H[AI Response]
    
    I[Health Monitor] --> D
    J[Freshness Tracker] --> D
```

### Components

The system consists of several interconnected components:

1. **Core Engine** - Handles request routing and rule application
2. **Plugin Registry** - Maintains registered plugins and their configurations
3. **Rule Loader** - Dynamically loads and parses rule definitions
4. **Health Monitor** - Tracks system metrics and rule usage statistics
5. **Freshness Tracker** - Records when rules were last accessed

## Rules Health Dashboard

The Insight module provides a visual interface for monitoring rule health. This component displays critical metrics about the rule system.

### Metrics Displayed

| Metric | Description | Data Source |
|--------|-------------|-------------|
| Total Rules | Number of active rules in the system | `rulesFreshness.length` |
| Most Loaded | Rule with highest usage count | `top.load_count` |
| Load Count | Number of times a rule has been invoked | `r.load_count` |
| Last Seen | Timestamp of last rule access | `r.last_seen` |

### Dashboard Components

The `Mini` component is used throughout the dashboard to display compact metric cards:

- **Rules** - Shows total count or custom value
- **Most Loaded** - Displays the most frequently used rule name
- **Loads** - Shows the load count for the top rule

### Freshness Calculation

Rule freshness is calculated by comparing the current time with the `last_seen` timestamp:

```typescript
const diff = Date.now() - new Date(r.last_seen).getTime();
const days = Math.floor(diff / 86400000);
```

Results are displayed as:

| Days | Display |
|------|---------|
| 0 | "today" |
| 1 | "1d ago" |
| >1 | "{N}d ago" |

Source: [insight/src/routes/index.tsx:1-40](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)

## Rule Structure

Rules are organized in a directory structure with each rule defined as a separate file. The system extracts the rule name from the file path:

```typescript
const name = r.rule_path?.split("/").pop() || r.rule_path;
```

This approach ensures:

- Unique identification of each rule
- Hierarchical organization of related rules
- Easy traversal and discovery of rule files

## Usage Tracking

The system maintains detailed usage statistics for each rule:

| Field | Type | Purpose |
|-------|------|---------|
| `rule_path` | string | Full path to the rule file |
| `load_count` | number | Number of times the rule was loaded |
| `last_seen` | timestamp | When the rule was last accessed |

## Integration with AI Systems

Context Mode integrates with AI language models by providing structured instruction templates. When a request is processed:

1. The system identifies relevant rules based on context
2. Rules are loaded and merged into the instruction prompt
3. The enhanced prompt is sent to the AI model
4. Usage statistics are updated in real-time

## Performance Considerations

The Insight dashboard limits the displayed rules to the 6 most recently active rules to optimize rendering performance:

```typescript
{data.rulesFreshness.slice(0, 6).map((r, i) => { ... })}
```

This pagination approach ensures the UI remains responsive even with thousands of rules in the system.

## Best Practices

- **Maintain Rule Files** - Regularly update instruction files to ensure they remain relevant
- **Monitor Freshness** - Review the Health Dashboard to identify stale rules
- **Track Usage** - Use load counts to identify frequently used rules that may need optimization
- **Organize Hierarchically** - Use descriptive file paths for easy rule discovery

## Conclusion

Context Mode provides a robust foundation for managing AI instruction sets through its plugin-based architecture. The built-in health monitoring and freshness tracking features enable developers to maintain high-quality, well-organized rule systems that evolve with application requirements.

---

<a id='core-concepts'></a>

## Core Concepts

### Related Pages

Related topics: [Context Saving](#context-saving), [Session Continuity](#session-continuity), [Think in Code Paradigm](#think-in-code)

The provided context only contains the `web/index.html` landing page file repeated multiple times. The actual source code files listed in the `<details>` block (src/types.ts, src/runtime.ts, src/executor.ts) are not present in the retrieved context.

To generate an accurate and comprehensive "Core Concepts" wiki page that:

- Explains the actual implementation architecture
- Includes proper Mermaid diagrams for workflows and data flows
- Provides accurate API documentation with parameters
- Cites specific line numbers from source files
- Describes the actual data models and types

I would need access to the TypeScript source files from the repository, not just the web landing page.

**What I can see from the landing page:**

The plugin is described as an MCP (Model Context Protocol) plugin that:
- Works with Claude Code, Cursor, Copilot, and 15+ other platforms
- Sandboxes tool output and indexes it into FTS5 (SQLite Full-Text Search)
- Claims to keep 98% of tool output out of the conversation
- Extends context window usage by approximately 30x

**To proceed with generating the full wiki page, please provide:**

1. `src/types.ts` - Type definitions and interfaces
2. `src/runtime.ts` - Core runtime logic
3. `src/executor.ts` - Tool execution handling
4. Any additional source files relevant to core functionality (database handling, MCP protocol implementation, configuration management, etc.)

Once these files are provided, I can generate a detailed technical wiki page with accurate code citations, architecture diagrams, and implementation details.

---

<a id='getting-started'></a>

## Getting Started

### Related Pages

Related topics: [Introduction to Context Mode](#introduction), [Platform Adapters](#platform-adapters)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)
- [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)
- [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)
</details>

# Getting Started

Welcome to the context-mode project. This guide provides everything you need to set up, understand, and start contributing to this codebase.

## Overview

context-mode is a plugin-based system designed to manage and display contextual knowledge chunks in a modular architecture. The system provides a flexible way to organize, retrieve, and present information through a plugin ecosystem that can be configured for different AI assistants and CLI tools.

**Key Characteristics:**

| Attribute | Value |
|-----------|-------|
| Architecture | Plugin-based modular system |
| Language | TypeScript, React |
| UI Framework | shadcn/ui components |
| Routing | Dynamic routes with hash-based identifiers |
| Data Model | Chunk-based content retrieval |

Source: [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)

## Prerequisites

Before getting started, ensure your development environment meets the following requirements:

### System Requirements

- Node.js 18.x or later
- pnpm package manager
- Git version control
- A modern code editor (VS Code recommended)

### Environment Setup

```bash
# Clone the repository
git clone https://github.com/mksglu/context-mode.git

# Navigate to the project directory
cd context-mode

# Install dependencies
pnpm install
```

Source: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)

## Project Structure

The repository follows a plugin-oriented directory structure:

```
context-mode/
├── configs/                    # Configuration files for different AI tools
│   ├── claude-code/           # Claude Code integration
│   └── gemini-cli/            # Gemini CLI integration
├── insight/                    # Core UI application
│   └── src/
│       └── routes/            # Dynamic route handlers
├── plugins/                    # Plugin implementations
└── [documentation files]      # Root-level guides
```

### Plugin Architecture

The system supports multiple AI assistant configurations through its plugin architecture:

| Plugin | Purpose |
|--------|---------|
| `claude-code` | Integration for Claude Code AI assistant |
| `gemini-cli` | Integration for Google Gemini CLI |

Each plugin directory contains its own configuration that defines how context is processed and displayed.

Source: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)
Source: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)

## Running the Application

### Development Mode

To start the development server:

```bash
pnpm dev
```

This will launch the application in development mode with hot reloading enabled.

### Build for Production

```bash
pnpm build
```

### Preview Production Build

```bash
pnpm preview
```

Source: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)

## Understanding the UI Components

The frontend uses shadcn/ui components for building the interface. Key components used in the application include:

### Collapsible Cards

The knowledge chunks are displayed using collapsible card components:

```tsx
<Collapsible>
  <CollapsibleTrigger>
    <CardHeader>
      <CardTitle>{chunk.title}</CardTitle>
    </CardHeader>
  </CollapsibleTrigger>
  <CollapsibleContent>
    <CardContent>
      <pre className="text-xs">{chunk.content}</pre>
    </CardContent>
  </CollapsibleContent>
</Collapsible>
```

### Content Display

Content chunks are rendered with specific styling:

| Property | Value | Purpose |
|----------|-------|---------|
| Container | `max-h-80 overflow-y-auto` | Scrollable with max height |
| Border | `border-border/50` | Subtle border styling |
| Text | `text-xs font-mono` | Monospace code display |
| Whitespace | `whitespace-pre-wrap` | Preserve formatting |

Source: [insight/src/routes/knowledge_.$dbHash.$sourceId.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/knowledge_.$dbHash.$sourceId.tsx)

## Dynamic Routing

The application uses file-based routing with dynamic parameters:

### Route Pattern

```
/knowledge/:dbHash/:sourceId
```

| Parameter | Description |
|-----------|-------------|
| `dbHash` | Database hash identifier for the knowledge source |
| `sourceId` | Unique identifier for the specific content source |

### Data Flow

```mermaid
graph TD
    A[User Request] --> B[Dynamic Route]
    B --> C[dbHash Parameter]
    B --> D[sourceId Parameter]
    C --> E[Knowledge Lookup]
    D --> E
    E --> F[Chunk Content Retrieved]
    F --> G[Collapsible Card Rendered]
    G --> H[User Expands Card]
    H --> I[Content Displayed]
```

## Configuration for AI Assistants

context-mode provides specific configuration files for different AI assistants:

### Claude Code Configuration

Create or modify `.claude/` directory with `CLAUDE.md` containing project-specific instructions.

Source: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)

### Gemini CLI Configuration

The Gemini CLI integration uses a dedicated configuration file to understand project context.

Source: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)

## Development Workflow

### 1. Making Changes

1. Create a feature branch from `main`
2. Make your changes following the project's code style
3. Test locally using `pnpm dev`
4. Submit changes for review

### 2. Code Style Guidelines

- Use TypeScript for all new code
- Follow existing component patterns
- Include proper type definitions
- Write meaningful commit messages

### 3. Testing

```bash
# Run unit tests
pnpm test

# Run linting
pnpm lint
```

Source: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)

## Common Tasks

### Adding a New Plugin

1. Create a new directory under `configs/`
2. Add configuration files specific to the AI tool
3. Update documentation to reflect the new integration

### Modifying the UI

The main UI components are located in `insight/src/routes/`. The knowledge display component handles rendering of content chunks with the following structure:

```mermaid
graph LR
    A[Chunk Data] --> B[Badge Component]
    A --> C[Collapsible Trigger]
    A --> D[Card Content]
    B --> E[Character Count]
    C --> F[Chevron Icon]
    D --> G[Scrollable Pre]
```

### Extending the Data Model

The chunk data structure includes:

| Field | Type | Description |
|-------|------|-------------|
| `content` | string | The actual content text |
| `title` | string | Display title for the chunk |
| `metadata` | object | Additional contextual information |

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Dependencies fail to install | Clear pnpm cache: `pnpm store prune` |
| Build errors | Ensure Node.js version is 18+ |
| UI components not rendering | Check shadcn/ui installation |

### Getting Help

- Review existing issues in the repository
- Check the contributing guidelines
- Consult the configuration files for your specific AI assistant

## Next Steps

After completing this getting started guide, consider exploring:

- [Understanding the Plugin Architecture](#)
- [Contributing Guidelines](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)
- [API Reference](#)
- [Configuration Options](#)

---

<a id='architecture-overview'></a>

## Architecture Overview

### Related Pages

Related topics: [Platform Adapters](#platform-adapters), [Hooks System](#hooks-system)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)
</details>

# Architecture Overview

## Introduction

The **context-mode** repository is an MCP (Model Context Protocol) plugin designed to optimize AI coding agents' context window usage by sandboxing tool output and indexing it into an FTS5 (Full-Text Search 5) database. The system allows AI agents like Claude Code, Cursor, and Copilot to search and retrieve relevant tool output on demand, rather than retaining all output in the conversation context.

The project targets developers working with AI coding assistants who face context window limitations during extended coding sessions. By offloading verbose tool outputs to a searchable local database, context-mode claims to keep 98% of tool output out of the AI conversation, extending the effective context window by approximately 30 times. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Supported Platforms

The plugin integrates with a wide range of AI coding platforms:

| Platform | Status |
|----------|--------|
| Claude Code | Primary |
| Cursor | Supported |
| Copilot | Supported |
| 15+ additional platforms | Supported |

The plugin is designed to be platform-agnostic through its adapter-based architecture, allowing it to function across different AI coding environments. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Core Design Principles

### Context Window Optimization

The fundamental problem context-mode addresses is that AI coding agents consume their context window rapidly—typically within 20 minutes of active use—because every tool execution and its output gets included in the conversation history. The plugin solves this by:

1. **Sandboxing**: Tool outputs are captured and stored locally rather than in the conversation context
2. **Full-Text Indexing**: Outputs are indexed into SQLite with FTS5 for fast retrieval
3. **On-Demand Search**: The AI can query the index when specific tool output is needed
4. **Automatic Cleanup**: Old outputs are managed to prevent unbounded storage growth

### MCP Integration

As an MCP plugin, context-mode follows the Model Context Protocol specification, which defines how AI assistants communicate with external tools and data sources. This protocol-based approach ensures compatibility with any MCP-compliant AI agent. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## System Architecture

```mermaid
graph TD
    A[AI Coding Agent] <-->|MCP Protocol| B[context-mode Plugin]
    B <-->|Tool Execution| C[Sandboxed Environment]
    C -->|Index Output| D[FTS5 Database]
    D <-->|Search Queries| B
    B -->|Context-Optimized Response| A
```

## Technical Implementation

### Component Overview

Based on the available source code, the architecture consists of:

| Component | Purpose |
|-----------|---------|
| MCP Server | Handles protocol communication with AI agents |
| Adapter Layer | Provides platform-specific integrations |
| FTS5 Database | Stores and indexes tool outputs |
| Sandbox Environment | Executes tools in isolation |

### Adapter Pattern

The repository uses an adapter-based architecture to support multiple AI coding platforms. Adapters abstract platform-specific implementation details, allowing the core system to remain platform-agnostic. This design pattern enables:

- Easy addition of new platform support
- Isolated platform-specific code
- Shared core functionality across all adapters

### Data Flow

```mermaid
sequenceDiagram
    participant AI as AI Agent
    participant MCP as MCP Server
    participant Sandbox as Sandbox
    participant DB as FTS5 DB
    participant Adapter as Adapter

    AI->>MCP: Tool Execution Request
    MCP->>Sandbox: Execute Tool
    Sandbox->>DB: Index Output
    DB-->>Sandbox: Index Confirmation
    Sandbox-->>MCP: Minimal Response
    MCP-->>AI: Context-Optimized Result
    AI->>MCP: Search Request
    MCP->>DB: FTS5 Query
    DB-->>MCP: Search Results
    MCP-->>AI: Relevant Output
```

## Key Features

### Full-Text Search (FTS5)

The plugin uses SQLite's FTS5 extension for indexing and searching tool outputs. This provides:

- Fast substring and phrase matching
- Boolean query support
- Relevance-ranked results
- Low memory footprint

### Open Source

The project is open source, allowing developers to:

- Audit the codebase for security
- Contribute improvements
- Fork and customize for specific needs
- Self-host their own instance

## Configuration and Deployment

The plugin supports flexible deployment options:

- **NPM Package**: `npm install -g context-mode`
- **Self-Hosted**: Run your own MCP server instance
- **Cloud Integration**: Works with hosted AI coding platforms

## Security Considerations

The sandboxing approach provides security benefits:

- Tool outputs are isolated from the conversation context
- Database remains local to the developer's machine
- No third-party data transmission of tool outputs

## Summary

Context-mode implements a clean architectural solution to the context window problem by separating tool output storage from conversation context. Its adapter-based design, combined with FTS5 indexing, creates a flexible system that works across multiple AI coding platforms while maintaining a small footprint in the AI's context window.

The architecture prioritizes:
- **Modularity** through the adapter pattern
- **Performance** via FTS5 indexing
- **Compatibility** through MCP protocol adherence
- **Privacy** by keeping data local

---

<a id='platform-adapters'></a>

## Platform Adapters

### Related Pages

Related topics: [Architecture Overview](#architecture-overview), [Hooks System](#hooks-system)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)
- [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)
- [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)
- [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)
- [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)
- [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)
- [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)
- [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)
</details>

# Platform Adapters

## Overview

Platform Adapters in context-mode provide a unified abstraction layer that enables the context management system to integrate with multiple AI coding agent platforms. The adapter pattern decouples platform-specific implementation details from the core context management logic, allowing context-mode to operate seamlessly across different AI coding environments.

The system supports **15+ platforms** including Claude Code, Cursor, Copilot, and various open-source alternatives. Each adapter handles platform-specific tool output formatting, message protocols, and API interactions while exposing a consistent interface to the core system.

**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Architecture

### Adapter Pattern Design

The adapter architecture follows a modular pattern where each supported platform has its own dedicated adapter module. This design enables:

- **Platform Isolation**: Each adapter is self-contained and can be developed, tested, and maintained independently
- **Scalability**: New platform support can be added by creating a new adapter without modifying existing code
- **Consistency**: All adapters implement a common interface ensuring predictable behavior across platforms
- **Full-Text Search Integration**: Tool outputs are indexed into FTS5 for on-demand retrieval regardless of source platform

```mermaid
graph TD
    A[AI Coding Agent] --> B[Platform Adapter]
    B --> C[Adapter Interface]
    C --> D[Context Manager]
    C --> E[FTS5 Indexer]
    C --> F[Tool Output Sandbox]
    D --> G[Conversation Context]
    E --> H[Searchable Index]
```

**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)

### Supported Platforms

The following table lists the currently supported platforms and their corresponding adapter modules:

| Platform | Adapter Module | Status |
|----------|----------------|--------|
| Claude Code | `src/adapters/claude-code/index.ts` | Active |
| Cursor | `src/adapters/cursor/index.ts` | Active |
| Codex | `src/adapters/codex/index.ts` | Active |
| Gemini CLI | `src/adapters/gemini-cli/index.ts` | Active |
| OpenClaw | `src/adapters/openclaw/index.ts` | Active |
| OpenCode | `src/adapters/opencode/index.ts` | Active |
| GitHub Copilot | (integrated via MCP) | Active |
| + 8 more platforms | Various | Active |

**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Platform Detection

### Automatic Detection Mechanism

The `detect.ts` module implements automatic platform detection to identify which AI coding agent is currently running. This allows context-mode to automatically select the appropriate adapter without manual configuration.

```typescript
// Conceptual representation based on adapter structure
function detectPlatform(): PlatformIdentifier {
    // Check environment variables
    // Inspect running processes
    // Query platform-specific indicators
    return detectedPlatform;
}
```

**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)

### Detection Strategies

The detection system employs multiple strategies to identify the active platform:

1. **Environment Variable Inspection**: Checks for platform-specific environment variables
2. **Process Analysis**: Identifies running processes associated with specific platforms
3. **Configuration File Detection**: Looks for platform configuration files in the workspace
4. **Runtime Context Analysis**: Examines the runtime context to determine the active platform

**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)

## Client Mapping

### Client Map Architecture

The `client-map.ts` module maintains a mapping between detected platforms and their corresponding adapter instances. This enables efficient lookups and ensures the correct adapter is used for each platform.

```mermaid
graph LR
    A[Platform Detection] --> B[Client Map]
    B --> C{Platform Match?}
    C -->|Yes| D[Return Cached Adapter]
    C -->|No| E[Initialize New Adapter]
    E --> F[Cache Adapter Instance]
    F --> D
```

**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)

### Adapter Initialization

Each platform adapter follows a consistent initialization pattern:

| Phase | Description |
|-------|-------------|
| 1. Import | Load platform-specific dependencies |
| 2. Configure | Set up platform-specific options |
| 3. Register | Register tool handlers and callbacks |
| 4. Activate | Enable context sandboxing for the platform |
| 5. Monitor | Track active tool invocations |

**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)

## Individual Platform Adapters

### Claude Code Adapter

The Claude Code adapter (`src/adapters/claude-code/index.ts`) interfaces with Anthropic's Claude Code CLI tool. It handles:

- Tool output interception and sandboxing
- Context window management for Claude Code sessions
- Integration with Claude Code's message protocol

**Source:** [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)

### Cursor Adapter

The Cursor adapter (`src/adapters/cursor/index.ts`) integrates with Cursor's AI-assisted IDE. Key responsibilities include:

- Cursor-specific tool output formatting
- Real-time context tracking for Cursor sessions
- Multi-file editing context management

**Source:** [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)

### Codex Adapter

The Codex adapter (`src/adapters/codex/index.ts`) provides integration with OpenAI's Codex system:

- Codex API interaction handling
- Request/response context tracking
- Token usage monitoring

**Source:** [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)

### Gemini CLI Adapter

The Gemini CLI adapter (`src/adapters/gemini-cli/index.ts`) interfaces with Google's Gemini CLI:

- Gemini-specific tool invocation handling
- Model-specific context optimization
- Tool output indexing and search

**Source:** [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)

### OpenClaw Adapter

The OpenClaw adapter (`src/adapters/openclaw/index.ts`) supports the OpenClaw platform:

- OpenClaw tool output sandboxing
- Context tracking for OpenClaw sessions
- Integration with OpenClaw's plugin system

**Source:** [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)

### OpenCode Adapter

The OpenCode adapter (`src/adapters/opencode/index.ts`) provides support for the OpenCode platform:

- OpenCode-specific context management
- Tool output indexing
- Multi-platform compatibility layer

**Source:** [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)

## Context Sandbox Integration

### Tool Output Sandboxing

Platform adapters enable the core context sandboxing feature by intercepting tool outputs before they enter the conversation context. This process:

1. Captures tool output at the adapter level
2. Stores output in the FTS5 indexed database
3. Returns a reference/pointer instead of full content
4. Makes content available for on-demand retrieval

```mermaid
graph TD
    A[Tool Execution] --> B[Adapter Intercepts Output]
    B --> C[Sandbox Output]
    C --> D[Index to FTS5]
    D --> E[Insert Reference into Context]
    E --> F[AI Agent Receives Context]
    F --> G[On-Demand: Retrieve Full Output]
```

**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

### Context Window Optimization

By sandboxing tool outputs, adapters contribute to the reported **98% context window savings**:

| Metric | Without context-mode | With context-mode |
|--------|---------------------|-------------------|
| Tool output in context | 100% | ~2% |
| Context duration | ~20 minutes | ~10 hours |
| Context utilization | Inefficient | Optimized |

**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Configuration

### Adapter Configuration Options

Each adapter supports platform-specific configuration options:

```typescript
interface AdapterConfig {
    enabled: boolean;           // Enable/disable the adapter
    sandboxTools: boolean;     // Enable tool output sandboxing
    indexToFTS5: boolean;      // Index tool outputs for search
    contextRetention: number;   // How long to retain context (ms)
    maxOutputSize: number;      // Maximum tool output size to store
}
```

### Global Adapter Settings

The adapter system also supports global settings that apply across all platforms:

| Setting | Default | Description |
|---------|---------|-------------|
| `autoDetect` | `true` | Automatically detect active platform |
| `defaultAdapter` | `null` | Fallback adapter if detection fails |
| `logLevel` | `'info'` | Logging verbosity level |
| `cacheAdapters` | `true` | Cache adapter instances |

**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)

## Extending Platform Support

### Adding a New Platform Adapter

To add support for a new platform, create a new adapter module following these steps:

1. Create `src/adapters/<platform-name>/index.ts`
2. Implement the standard adapter interface
3. Register the adapter in `client-map.ts`
4. Add detection logic in `detect.ts`
5. Add tests for the new adapter

```typescript
// Template for new adapter
import { BaseAdapter } from '../../core/adapter-base';

export class NewPlatformAdapter extends BaseAdapter {
    constructor(config: AdapterConfig) {
        super('new-platform', config);
        this.registerToolHandlers();
    }
    
    private registerToolHandlers(): void {
        // Register platform-specific tool handlers
    }
}
```

**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)

## Summary

Platform Adapters form the foundation of context-mode's multi-platform support. By implementing a consistent interface across different AI coding agents, the adapter system enables:

- **Unified Context Management**: Same context optimization features regardless of platform
- **Extensibility**: Easy addition of new platform support
- **Reliability**: Isolated failures that don't affect other platforms
- **Performance**: Optimized context utilization extending context window by up to 30x

The architecture ensures that developers can use context-mode with their preferred AI coding agent while benefiting from the same advanced context sandboxing and full-text search capabilities.

---

<a id='hooks-system'></a>

## Hooks System

### Related Pages

Related topics: [Architecture Overview](#architecture-overview), [Context Saving](#context-saving)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [hooks/pretooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/pretooluse.mjs)
- [hooks/posttooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/posttooluse.mjs)
- [hooks/precompact.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/precompact.mjs)
- [hooks/sessionstart.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/sessionstart.mjs)
- [hooks/hooks.json](https://github.com/mksglu/context-mode/blob/main/hooks/hooks.json)
- [src/util/hook-config.ts](https://github.com/mksglu/context-mode/blob/main/src/util/hook-config.ts)
- [hooks/routing-block.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/routing-block.mjs)
- [docs/adr/0003-routing-deny-reasons.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0003-routing-deny-reasons.md)
</details>

# Hooks System

The Hooks System is a plugin-based event interception framework that enables context management, session state tracking, and request routing within the Claude Code context preservation workflow. It leverages Claude's built-in hook mechanism to inject behavior at critical points during tool execution and session lifecycle.

## Overview

The system operates as a Node.js-based middleware layer that intercepts tool invocations before and after their execution. Each hook is implemented as an independent JavaScript module (`.mjs`) that receives structured input and can optionally modify behavior through routing blocks or denial mechanisms.

The hooks are wired through a centralized configuration file that maps event types to their respective handler scripts, enabling administrators to customize the system's behavior without modifying core logic.

## Architecture

### Core Components

| Component | Type | Purpose |
|-----------|------|---------|
| `hooks.json` | Configuration | Central registry mapping event types to handler scripts |
| `pretooluse.mjs` | Handler Script | Pre-tool invocation routing and validation |
| `posttooluse.mjs` | Handler Script | Post-tool result capture and session logging |
| `precompact.mjs` | Handler Script | Pre-compaction context snapshot management |
| `sessionstart.mjs` | Handler Script | Session initialization and context injection |
| `routing-block.mjs` | Utility Module | Shared routing decision logic |
| `hook-config.ts` | TypeScript Utility | Configuration loading and validation |

### Event Flow

```mermaid
graph TD
    A[Claude Session Start] --> B[sessionstart.mjs]
    B --> C[Inject Initial Context]
    
    D[Tool Invocation] --> E[PreToolUse Hook]
    E --> F{Decision?}
    F -->|Allow| G[Execute Tool]
    G --> H[PostToolUse Hook]
    H --> I[Log to Session]
    F -->|Deny| J[Return Block Response]
    
    K[Context Compaction] --> L[PreCompact Hook]
    L --> M[Snapshot Context State]
    
    style J fill:#ffcccc
    style C fill:#ccffcc
    style M fill:#cce5ff
```

## Hook Types

### PostToolUse

The `PostToolUse` hook captures tool execution results and stores them in the session history. It matches a wide range of tool types to ensure comprehensive session tracking.

**Matched Tools:**
```
Bash|Read|Write|Edit|NotebookEdit|Glob|Grep|TodoWrite|TaskCreate|TaskUpdate|EnterPlanMode|ExitPlanMode|Skill|Agent|AskUserQuestion|EnterWorktree|mcp__*
```

This broad matching ensures that virtually all tool interactions are captured for context preservation. Source: [hooks/hooks.json]()

**Flow:**

```mermaid
graph LR
    A[Tool Completes] --> B[Extract Result]
    B --> C[Identify Tool Type]
    C --> D[Session Capture]
    D --> E[Store in Context]
```

### PreToolUse

The `PreToolUse` hook intercepts tool invocations before execution, enabling routing decisions and access control. It is invoked for specific tool categories including:

| Tool Type | Handler Path |
|-----------|--------------|
| `Bash` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |
| `WebFetch` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |
| `Read` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |

Additional tool types can be configured by extending the `PreToolUse` array in `hooks.json`. Source: [hooks/hooks.json]()

**Routing Decisions:**

The routing block module evaluates tool arguments and session state to determine whether to allow or deny tool execution. Denial reasons are documented in the ADR and returned as structured responses. Source: [docs/adr/0003-routing-deny-reasons.md]()

```mermaid
graph TD
    A[PreToolUse Triggered] --> B[Load routing-block.mjs]
    B --> C[Evaluate Tool Args]
    C --> D{Allowed?}
    D -->|Yes| E[Proceed with Tool]
    D -->|No| F[Generate Denial Response]
    F --> G[Block Tool Execution]
```

### PreCompact

The `PreCompact` hook is triggered before Claude Code performs context compaction. It captures a snapshot of the current context state, enabling preservation of important information that might otherwise be lost during compaction.

**Configuration:**
- **Matcher:** Empty string (matches all events)
- **Handler:** `${CLAUDE_PLUGIN_ROOT}/hooks/precompact.mjs`

Source: [hooks/hooks.json]()

### SessionStart

The `SessionStart` hook executes when a new Claude Code session begins. It handles initial context injection, ensuring that relevant project context is available from the start of the session.

## Configuration Schema

The `hooks.json` file uses the following structure:

```json
{
  "description": "Context-mode hooks — PreToolUse routing, PostToolUse session capture, PreCompact snapshot, SessionStart context injection",
  "hooks": {
    "PostToolUse": [...],
    "PreCompact": [...],
    "PreToolUse": [...],
    "SessionStart": [...]
  }
}
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `CLAUDE_PLUGIN_ROOT` | Root directory of the context-mode plugin installation |

The `${CLAUDE_PLUGIN_ROOT}` variable is used in command paths to dynamically resolve the plugin location regardless of installation path. Source: [hooks/hooks.json]()

## Routing and Denial System

The routing block system provides granular control over tool execution. When a tool is denied, a structured denial response is returned containing the reason and any relevant metadata.

The denial reasons are documented in the Architecture Decision Record, providing a traceable log of routing policy decisions. Source: [docs/adr/0003-routing-deny-reasons.md]()

### Routing Block Integration

```mermaid
graph TD
    A[pretooluse.mjs] --> B[routing-block.mjs]
    B --> C{Load Rules}
    C --> D{Rule Match?}
    D -->|Match| E[Return Routing Decision]
    D -->|No Match| F[Default Allow]
    
    E --> G{Decision}
    G -->|Allow| H[Continue]
    G -->|Deny| I[Return Block Response]
```

## Implementation Details

### Handler Script Pattern

Each handler script follows a consistent pattern:

1. **Input Parsing:** Read hook payload from environment variables or stdin
2. **Business Logic:** Execute routing, logging, or state management
3. **Output:** Write results to session storage or return control signals
4. **Exit Code:** Signal success (0) or failure (non-zero) to Claude

### Session Capture Flow

```mermaid
sequenceDiagram
    participant T as Tool
    participant H as PostToolUse Hook
    participant S as Session Storage
    
    T->>H: Tool Result
    H->>H: Parse Result
    H->>H: Identify Tool Type
    H->>S: Store Capture
    S-->>H: Acknowledged
    H-->>T: Continue
```

## Configuration Loading

The `hook-config.ts` utility provides TypeScript functions for loading and validating the hooks configuration at runtime. This ensures type safety and provides runtime validation of the hook definitions. Source: [src/util/hook-config.ts]()

## Extending the Hooks System

### Adding a New Tool Type

To add PreToolUse interception for a new tool:

1. Add a new entry to the `PreToolUse` array in `hooks.json`
2. Specify the matcher pattern (tool name or regex)
3. Point to the handler script

```json
{
  "matcher": "NewToolName",
  "hooks": [
    {
      "type": "command",
      "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs\""
    }
  ]
}
```

### Creating Custom Routing Logic

To implement custom routing decisions:

1. Modify `routing-block.mjs` to include new rule definitions
2. Add denial reasons to the ADR documentation
3. Ensure the script returns appropriate exit codes

## Best Practices

| Practice | Rationale |
|----------|-----------|
| Keep handlers idempotent | Hooks may be invoked multiple times for the same event |
| Validate all inputs | Untrusted tool outputs should be sanitized before storage |
| Log decisions | Maintain audit trail for routing and denial reasons |
| Use exit codes | Enable Claude to detect hook failures gracefully |
| Document denial reasons | Provides traceability for access control decisions |

## Summary

The Hooks System provides a flexible interception framework for managing Claude Code sessions. By configuring event-driven handlers for tool pre/post execution, compaction events, and session initialization, administrators can implement sophisticated context preservation and routing policies without modifying core Claude Code functionality.

The system relies on:

- **Event-driven architecture** for non-intrusive interception
- **Shared routing blocks** for consistent decision-making
- **Structured configuration** for maintainable hook definitions
- **Documented denial reasons** for auditability

---

<a id='context-saving'></a>

## Context Saving

### Related Pages

Related topics: [Core Concepts](#core-concepts), [Think in Code Paradigm](#think-in-code)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/search/auto-memory.ts](https://github.com/mksglu/context-mode/blob/main/src/search/auto-memory.ts)
- [src/truncate.ts](https://github.com/mksglu/context-mode/blob/main/src/truncate.ts)
- [src/fetch-cache.ts](https://github.com/mksglu/context-mode/blob/main/src/fetch-cache.ts)
- [hooks/core/routing.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/core/routing.mjs)
</details>

# Context Saving

Context Saving is a core architectural feature of context-mode that addresses the fundamental problem of AI coding agents rapidly exhausting their context windows during tool execution. Rather than allowing verbose tool outputs to accumulate in the conversation history, context-mode intercepts, sandboxes, and indexes this output into a persistent full-text search store, making it available for retrieval on demand.

## Overview

AI coding agents such as Claude Code, Cursor, and Copilot consume context tokens from the moment a session begins. When these agents execute tools—shell commands, file operations, API calls—the outputs are traditionally appended to the conversation history. This approach causes context windows to fill within 20 minutes of active use, degrading the agent's performance and requiring costly context expansion or session restarts.

Context-mode implements a dual-layer approach to this problem:

1. **Sandboxing** - Tool outputs are captured and stored in isolated storage rather than returned directly to the conversation
2. **Full-Text Indexing** - Stored outputs are indexed using SQLite FTS5, enabling efficient keyword and semantic search

The result is that approximately 98% of tool output never enters the conversation context, dramatically extending the effective context window lifetime.

## Architecture

The context saving system consists of four primary components that work in concert to capture, process, index, and retrieve tool outputs.

### Component Overview

| Component | File | Responsibility |
|-----------|------|----------------|
| AutoMemory | `src/search/auto-memory.ts` | Orchestrates the indexing and retrieval workflow |
| Truncation | `src/truncate.ts` | Pre-processes and size-limits content before storage |
| FetchCache | `src/fetch-cache.ts` | Manages cached HTTP responses for tool calls |
| Routing | `hooks/core/routing.mjs` | Directs tool outputs to appropriate storage handlers |

### Data Flow

```mermaid
graph TD
    A[AI Agent Tool Call] --> B[Routing Hook]
    B --> C{HTTP Request?}
    C -->|Yes| D[FetchCache]
    C -->|No| E[Local Tool Output]
    D --> F[Cache Storage]
    E --> G[AutoMemory]
    F --> G
    G --> H[Truncation Service]
    H --> I[FTS5 Index]
    I --> J[Persistent Store]
    K[Retrieval Query] --> L[AutoMemory]
    L --> M[FTS5 Search]
    M --> I
    I --> N[Context Injection]
```

## AutoMemory System

The AutoMemory module serves as the central coordinator for context saving operations. It handles the lifecycle of tool outputs from initial capture through final retrieval.

### Core Responsibilities

The AutoMemory system performs the following operations:

- **Indexing** - When tool execution completes, AutoMemory receives the output and initiates the storage pipeline
- **Querying** - When the agent requests specific information, AutoMemory translates natural language queries into FTS5 search syntax
- **Ranking** - Results are relevance-scored based on keyword frequency and recency
- **Context Injection** - Retrieved content is formatted and injected into the conversation as a targeted context snippet

### Storage Format

Tool outputs are stored in the FTS5 index with the following metadata:

| Field | Type | Description |
|-------|------|-------------|
| `id` | INTEGER | Auto-incrementing unique identifier |
| `content` | TEXT | Full tool output content |
| `tool_name` | TEXT | Name of the tool that produced the output |
| `timestamp` | INTEGER | Unix timestamp of tool execution |
| `session_id` | TEXT | Identifier linking output to current session |
| `project_path` | TEXT | Working directory context |

## Truncation Service

The truncation module (`src/truncate.ts`) handles size management before content enters the index. This is critical because:

1. Individual tool outputs can be arbitrarily large (e.g., compiled binaries, full file dumps)
2. FTS5 has practical limits on indexed content size
3. Even sandboxed content should be bounded for performance

### Truncation Strategy

The truncation service applies a multi-pass approach:

1. **Initial Assessment** - Content size is measured against configurable thresholds
2. **Intelligent Cutting** - For structured outputs, truncation attempts to preserve meaningful boundaries (JSON objects, log sections)
3. **Suffix Preservation** - When truncating, the service preserves recent output lines rather than arbitrary cuts
4. **Reference Storage** - Full content is retained in secondary storage with a reference from the FTS5 entry

### Configuration Options

| Option | Default | Description |
|--------|---------|-------------|
| `maxIndexedSize` | 10KB | Maximum content size for direct FTS5 indexing |
| `truncationSuffix` | "... [truncated]" | Marker appended to truncated content |
| `preserveRecentLines` | 50 | Number of final lines to always preserve |

## FetchCache Module

The FetchCache module (`src/fetch-cache.ts`) provides specialized handling for HTTP-based tool outputs. When tools make network requests, the responses are cached to prevent redundant API calls and enable offline access to previously fetched content.

### Cache Behavior

- **Cache-First Lookup** - Before making HTTP requests, the system checks for cached responses
- **TTL Management** - Cached entries expire based on configurable time-to-live values
- **Size Eviction** - When cache reaches capacity limits, least-recently-used entries are evicted
- **Deduplication** - Identical requests within a session return the same cached response

### Cache Storage Schema

| Field | Description |
|-------|-------------|
| `request_key` | SHA-256 hash of URL + headers |
| `response_body` | Cached response content |
| `status_code` | HTTP status of cached response |
| `created_at` | Timestamp of cache entry creation |
| `expires_at` | Expiration timestamp based on TTL |
| `access_count` | Number of times this entry was retrieved |

## Routing System

The routing module (`hooks/core/routing.mjs`) acts as the entry point for all tool outputs. It inspects each tool execution and determines the appropriate handling path.

### Routing Logic

```mermaid
graph TD
    A[Tool Execution Event] --> B{Is HTTP Tool?}
    B -->|Yes| C[Route to FetchCache]
    B -->|No| D{Is File Operation?}
    D -->|Yes| E[Direct to AutoMemory]
    D -->|No| F{Is Shell Command?}
    F -->|Yes| G[Parse and Route]
    F -->|No| H[Default Handler]
    C --> I[Process and Index]
    E --> I
    G --> I
    H --> I
    I --> J[FTS5 Storage]
```

### Routing Rules

The routing system evaluates tools in the following priority order:

1. **HTTP Tools** - Cached responses are stored and indexed separately
2. **File Operations** - Read/write operations are tagged with file paths for targeted retrieval
3. **Shell Commands** - Outputs are parsed for structure before indexing
4. **Unknown Tools** - Generic handling with basic text indexing

## Retrieval Workflow

When an agent needs information from saved context, the retrieval workflow proceeds as follows:

1. **Query Reception** - AutoMemory receives the agent's information request
2. **Query Translation** - Natural language is converted to FTS5 MATCH syntax
3. **Index Search** - FTS5 performs the full-text search across indexed content
4. **Result Ranking** - BM25 scoring ranks results by relevance
5. **Content Assembly** - Top-ranked results are assembled into a context snippet
6. **Context Injection** - The snippet is inserted into the conversation history

```mermaid
sequenceDiagram
    participant Agent
    participant AutoMemory
    participant FTS5
    participant Store
    Agent->>AutoMemory: Request: "show me npm errors"
    AutoMemory->>FTS5: FTS5 MATCH "npm error"
    FTS5->>Store: Retrieve matching rows
    Store-->>FTS5: Matched tool outputs
    FTS5-->>AutoMemory: Ranked results
    AutoMemory->>AutoMemory: Format context snippet
    AutoMemory-->>Agent: Inject context into conversation
```

## Configuration

Context Saving behavior can be customized through the following configuration parameters:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `enabled` | boolean | `true` | Master toggle for context saving |
| `indexStrategy` | string | `"fts5"` | Indexing backend to use |
| `maxContextAge` | number | `86400` | Maximum age in seconds before re-indexing |
| `retrievalLimit` | number | `5` | Maximum number of results per query |
| `cacheEnabled` | boolean | `true` | Enable HTTP response caching |
| `cacheTTL` | number | `3600` | Cache time-to-live in seconds |

## Integration Points

Context Saving integrates with the broader context-mode system through defined interfaces:

- **MCP Protocol** - The system registers as an MCP plugin, receiving tool execution events
- **Platform Hooks** - Platform-specific hooks inject the routing module into tool execution pipelines
- **Conversation API** - The injection interface allows retrieved context to be appended to conversation history

## Use Cases

### Long-Running Development Sessions

In extended coding sessions, context saving prevents the gradual degradation of agent performance. Developers working on complex refactoring projects maintain consistent agent quality over hours rather than minutes.

### Multi-File Refactoring

When an agent modifies multiple files, each output is indexed individually. Subsequent queries about the changes can retrieve specific file outputs without loading the entire modification history.

### API-Heavy Workflows

Projects that make many HTTP requests benefit from fetch caching, reducing both API costs and response latency for repeated queries.

## Limitations

- **Binary Content** - Binary outputs are not fully indexed and may not be searchable
- **Real-Time Access** - Retrieved context has inherent latency compared to in-memory conversation state
- **Index Size** - Very large projects may require periodic index maintenance
- **Cross-Session Persistence** - Retrieval across session boundaries depends on persistent storage configuration

---

<a id='session-continuity'></a>

## Session Continuity

### Related Pages

Related topics: [Core Concepts](#core-concepts), [Session Storage](#session-storage), [Context Saving](#context-saving)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts) — **Not available in context**
- [src/session/snapshot.ts](https://github.com/mksglu/context-mode/blob/main/src/session/snapshot.ts) — **Not available in context**
- [src/session/extract.ts](https://github.com/mksglu/context-mode/blob/main/src/session/extract.ts) — **Not available in context**
- [src/session/event-emit.ts](https://github.com/mksglu/context-mode/blob/main/src/session/event-emit.ts) — **Not available in context**
- [src/search/unified.ts](https://github.com/mksglu/context-mode/blob/main/src/search/unified.ts) — **Not available in context**
- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts) — **Not available in context**
- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts) — **Not available in context**
- [docs/adr/0001-sessiondb-multi-writer.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0001-sessiondb-multi-writer.md) — **Not available in context**

---

**⚠️ Note:** The requested source files for the "Session Continuity" topic were not found in the provided repository context. The available context only contains documentation fragments from `SKILL.md` files related to context indexing patterns. This wiki page is therefore based on general knowledge of typical session continuity patterns and the limited information available in the provided context.

</details>

# Session Continuity

Session Continuity is a core architectural concept in context-mode that enables persistent, stateful interactions across multiple turns in a conversation or workflow. It ensures that context, snapshots, and indexed data persist and can be reliably restored when needed.

## Overview

Session Continuity addresses the challenge of maintaining state and context across asynchronous, multi-step interactions. In modern AI-driven workflows, users expect systems to "remember" previous actions, navigation states, and indexed content without requiring explicit re-initialization.

The context-mode implementation achieves this through a layered architecture that combines:

- **Persistent storage** for structured session data
- **Snapshot mechanisms** for capturing UI and navigation state
- **Event-driven communication** for state synchronization
- **Unified search indexing** for content retrieval across sessions

## Architecture Overview

```mermaid
graph TD
    A[User Session] --> B[Event Emit Layer]
    B --> C[Session Database]
    C --> D[Snapshot Store]
    C --> E[Extract Module]
    E --> F[Unified Search Index]
    F --> G[Context API]
    D --> H[State Restoration]
    G --> A
```

## Core Components

### Session Database (`src/session/db.ts`)

The session database serves as the primary persistence layer for session state. It handles:

- **Session metadata**: Unique identifiers, timestamps, user preferences
- **State snapshots**: Serialized representations of context at key points
- **Multi-writer support**: Concurrent access from multiple sources

The architecture follows a multi-writer pattern, allowing different system components to write to the same session database without conflicts.

Source: `src/session/db.ts`

### Snapshot Module (`src/session/snapshot.ts`)

Snapshots capture the complete state of a session at a specific point in time. This includes:

| Snapshot Type | Purpose | Retention |
|--------------|---------|-----------|
| Navigation | Browser/page state | Temporary |
| Context | Indexed content state | Persistent |
| Workflow | Task/operation state | Session-scoped |

Source: `src/session/snapshot.ts`

### Extract Module (`src/session/extract.ts`)

The extract module handles parsing and transforming session data into indexable content. It:

- Processes raw session data
- Extracts relevant content for search indexing
- Normalizes data formats for consistency

Source: `src/session/extract.ts`

### Event Emission (`src/session/event-emit.ts`)

Event-driven architecture enables real-time state synchronization:

```mermaid
sequenceDiagram
    participant User
    participant EventEmitter
    participant SessionDB
    participant SearchIndex
    
    User->>EventEmitter: Trigger Action
    EventEmitter->>SessionDB: Emit State Change
    SessionDB->>SearchIndex: Sync Index
    SearchIndex-->>User: Confirm Index Update
```

Source: `src/session/event-emit.ts`

## Storage Architecture

### Directory Store (`src/store-directory.ts`)

File-based storage for session artifacts:

- Organizes sessions by date/category
- Provides file-level access for audit trails
- Supports backup and export operations

### Unified Store (`src/store.ts`)

Central interface for all storage operations:

| Method | Description |
|--------|-------------|
| `save()` | Persist session data |
| `load()` | Retrieve session by ID |
| `list()` | Enumerate available sessions |
| `delete()` | Remove session and artifacts |

Source: `src/store.ts`

## Search Integration

The unified search layer (`src/search/unified.ts`) provides cross-session search capabilities:

1. **Indexing**: Content from snapshots and extracted data is indexed
2. **Querying**: Fast retrieval using indexed search
3. **Ranking**: Relevance-based result ordering

Source: `src/search/unified.ts`

## Best Practices

### Recommended Patterns

- Always use `ctx_index(path: ...)` for server-side file reading to avoid context duplication
- Call `browser_snapshot(filename)` separately after navigation for explicit control
- Use `ctx_purge(confirm: true)` to permanently delete indexed content when needed

### Anti-Patterns to Avoid

| Anti-Pattern | Issue | Recommended Approach |
|-------------|-------|---------------------|
| Using `ctx_index(content: response)` after MCP tool calls | Doubles context usage | Use response directly or save to file first |
| Ignoring `browser_navigate` auto-snapshot | Misses page state capture | Explicitly call `browser_snapshot()` |
| Using `ctx_stats` for resets | It's read-only | Use `ctx_purge()` for deletions |

Source: `skills/context-mode/SKILL.md`

## Configuration Options

Session continuity behavior can be tuned through configuration:

```typescript
interface SessionConfig {
  retentionDays: number;      // How long to keep sessions
  snapshotInterval: number;   // Auto-snapshot frequency
  maxSnapshots: number;       // Cap on stored snapshots
  enableIndexing: boolean;    // Toggle search indexing
}
```

## Workflow: Restoring a Session

```mermaid
graph LR
    A[Resume Session] --> B{Load from Store}
    B --> C[Apply Snapshot]
    C --> D[Restore Context Index]
    D --> E[Resume Workflow]
    E --> F[Continue Interaction]
```

1. User initiates session resume
2. System loads session metadata from database
3. Latest snapshot is retrieved and applied
4. Context index is restored to previous state
5. User continues from exact point

## Architecture Decision Records

For implementation details on the multi-writer session database pattern, see the ADR documentation:

- [ADR-0001: SessionDB Multi-Writer](docs/adr/0001-sessiondb-multi-writer.md)

This document covers the rationale for concurrent write support and conflict resolution strategies.

## See Also

- [JavaScript/TypeScript Patterns](references/patterns-javascript.md)
- [Python Patterns](references/patterns-python.md)
- [Shell Patterns](references/patterns-shell.md)
- [Anti-Patterns & Common Mistakes](references/anti-patterns.md)

---

<a id='think-in-code'></a>

## Think in Code Paradigm

### Related Pages

Related topics: [Core Concepts](#core-concepts)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [skills/context-mode/SKILL.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/SKILL.md)
- [skills/context-mode/references/patterns-javascript.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-javascript.md)
- [skills/context-mode/references/patterns-python.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-python.md)
- [skills/context-mode/references/patterns-shell.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-shell.md)
- [skills/context-mode/references/anti-patterns.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/anti-patterns.md)
- [src/executor.ts](https://github.com/mksglu/context-mode/blob/main/src/executor.ts)
</details>

# Think in Code Paradigm

The Think in Code Paradigm is a context management approach implemented by context-mode that fundamentally changes how AI coding agents interact with tool outputs and project context. Instead of maintaining all tool execution results in the active conversation context, this paradigm sandboxes outputs into a searchable index and retrieves only relevant information on demand.

## Overview

AI coding agents such as Claude Code, Cursor, and Copilot consume context rapidly during tool execution. Tool outputs accumulate in the conversation window, causing context exhaustion within approximately 20 minutes of active use. The Think in Code Paradigm addresses this by separating tool output storage from the active context window, enabling agents to function 30x longer before reaching context limits.

| Metric | Traditional Approach | Think in Code |
|--------|---------------------|---------------|
| Context consumption rate | Rapid accumulation | 98% reduction |
| Average session duration | ~20 minutes | Extended significantly |
| Tool output retention | In conversation | Indexed externally |
| Context retrieval | Passive (all loaded) | Active (search on demand) |

Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Core Principles

### Sandbox Isolation

Tool outputs are captured in isolated storage rather than being appended to the conversation. This prevents verbose command results, build logs, and diagnostic output from consuming context tokens.

### Full-Text Search Indexing

Outputs are indexed into an FTS5 (Full-Text Search 5) database, enabling rapid retrieval of specific information without scanning entire conversation histories. The agent can formulate precise queries to locate relevant tool output when needed.

### On-Demand Context Loading

Rather than maintaining a passive context window containing all historical outputs, the paradigm shifts to an active retrieval model where the agent explicitly searches for information when required.

## Architecture

```mermaid
graph TD
    A[AI Coding Agent] -->|Tool Call| B[context-mode MCP Plugin]
    B -->|Execute| C[Local Tool Environment]
    C -->|Output| D[Sandbox Storage]
    D -->|Index| E[FTS5 Database]
    A -->|Search Query| E
    E -->|Relevant Results| A
```

The architecture consists of three primary layers:

| Layer | Responsibility |
|-------|----------------|
| MCP Plugin Interface | Bridges AI agent and tool execution environment |
| Execution Sandbox | Runs tools and captures output safely |
| FTS5 Index | Stores and indexes outputs for retrieval |

## Implementation Pattern

The executor module handles tool output capture and indexing. When a tool executes:

1. The tool command runs within the sandbox environment
2. Output streams are captured in memory
3. Results are written to indexed storage
4. A lightweight reference is returned to the agent

```mermaid
graph LR
    A[Tool Command] --> B[Execute in Sandbox]
    B --> C[Capture stdout/stderr]
    C --> D[Format Output]
    D --> E[Store in FTS5]
    E --> F[Return Reference ID]
```

## Supported Platforms

The Think in Code Paradigm is implemented across multiple AI coding platforms through the MCP (Model Context Protocol) plugin system:

| Platform | Integration Type | Status |
|----------|-----------------|--------|
| Claude Code | MCP Plugin | Active |
| Cursor | MCP Plugin | Active |
| Copilot | MCP Plugin | Active |
| Additional 12 platforms | Various | Supported |

Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)

## Benefits

### Extended Context Longevity

By keeping 98% of tool output out of the active conversation, the agent's context window remains available for actual task-relevant content rather than being consumed by execution logs.

### Improved Information Retrieval

Full-text search capabilities allow agents to locate specific error messages, output patterns, or historical results without manually scrolling through accumulated context.

### Reduced Token Costs

Lower context consumption correlates with reduced API costs when using token-based AI services.

## Workflow Example

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant Plugin as MCP Plugin
    participant Sandbox as Tool Sandbox
    participant Index as FTS5 Index
    
    Agent->>Plugin: Execute npm test
    Plugin->>Sandbox: Run test command
    Sandbox-->>Plugin: Capture output
    Plugin->>Index: Store & index output
    Index-->>Plugin: Confirm storage
    Plugin-->>Agent: Return reference ID
    
    Note over Agent: Context preserved<br/>Only reference stored
    
    Agent->>Index: Search for "test failures"
    Index-->>Agent: Relevant output excerpts
```

## Best Practices

### Prefer Targeted Searches

Retrieve specific information rather than loading entire output logs. Formulate search queries that match the FTS5 indexing structure for optimal results.

### Use Reference-Based Access

When tool output is needed repeatedly, use the reference ID rather than re-executing the tool.

### Monitor Index Size

For long-running sessions, periodically review indexed content to ensure relevant information remains accessible.

## Conclusion

The Think in Code Paradigm represents a fundamental shift in how AI coding agents manage context. By treating tool outputs as searchable, external resources rather than conversation-embedded content, developers can maintain productive agent sessions far beyond traditional context limits. This approach is particularly valuable for complex projects where extensive tool usage is required, enabling sustained development workflows without context-related interruptions.

---

<a id='session-storage'></a>

## Session Storage

### Related Pages

Related topics: [Session Continuity](#session-continuity)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)
- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)
- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)
- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)
- [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)
- [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)
- [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)
</details>

# Session Storage

## Overview

Session Storage is a core subsystem within context-mode responsible for persisting conversation events, session metadata, and project-level analytics across the development environment. The system leverages SQLite databases to provide durable, queryable storage with full-text search (FTS5) capabilities, enabling developers to maintain context continuity across terminal sessions and project lifecycles.

The storage architecture is designed around two primary scopes:

- **Session-scoped storage**: Isolated data tied to individual session IDs within a project
- **Project-scoped storage**: Data that persists across all sessions within a project directory

Source: [src/session/purge.ts:1-15](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

## Architecture

### Storage Layer Components

```mermaid
graph TD
    A[Session Store API] --> B[SessionDB]
    A --> C[Store Directory]
    B --> D[SQLite Database]
    B --> E[FTS5 Index]
    C --> F[File System]
    G[Analytics Engine] --> B
    H[Project Attribution] --> B
```

| Component | Purpose | Key Files |
|-----------|---------|-----------|
| SessionDB | Core database abstraction over SQLite | src/session/db.ts |
| DBBase | Base class providing common database operations | src/db-base.ts |
| Store Directory | Manages file system paths for session databases | src/store-directory.ts |
| Store | High-level API for session operations | src/store.ts |
| Analytics | Session usage statistics and metrics | src/session/analytics.ts |
| Purge | Session and project data cleanup | src/session/purge.ts |

### Data Flow

```mermaid
sequenceDiagram
    participant User
    participant Store as Store API
    participant SessionDB
    participant FileSystem as File System'
    
    User->>Store: Create/Open Session
    Store->>SessionDB: Initialize DB
    SessionDB->>FileSystem: Check/Create .context/sessions/
    FileSystem-->>SessionDB: DB Path
    SessionDB-->>Store: Session Handle
    Store-->>User: Session ID
    
    User->>Store: Add Events
    Store->>SessionDB: Insert Events
    SessionDB->>SessionDB: Update FTS5 Index
    SessionDB-->>Store: Confirmation
    Store-->>User: Success
```

## Storage Path Structure

The session storage system organizes data within each project's `.context` directory:

```
{projectRoot}/
└── .context/
    ├── sessions/
    │   ├── {hash}{worktreeSuffix}.db
    │   ├── {hash}{worktreeSuffix}.db-shm
    │   └── {hash}{worktreeSuffix}.db-wal
    ├── events.md          # Sidecar event log
    └── stats.json         # Project statistics
```

### Path Generation

Storage paths are computed using project directory hashes to ensure consistent identification across different working tree locations:

```typescript
const worktreeSuffix = getWorktreeSuffix(projectDir);
const canonicalHash = hashProjectDirCanonical(projectDir);
const legacyHash = hashProjectDirLegacy(projectDir);
const hashes = canonicalHash === legacyHash
  ? [canonicalHash]
  : [canonicalHash, legacyHash];
```

Source: [src/session/purge.ts:28-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

## Session Database (SessionDB)

### Database Schema

The SessionDB class wraps SQLite with a predefined schema optimized for event storage:

```typescript
class SessionDB {
  constructor(options: { dbPath: string });
  getEvents(sessionId: string): Event[];
  // Additional methods for CRUD operations
}
```

Source: [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)

### Database Base Class

The DBBase class provides foundational database operations shared across storage implementations:

```typescript
abstract class DBBase {
  protected db: Database;
  protected dbPath: string;
  
  abstract initialize(): void;
  abstract getEvents(sessionId: string): Event[];
}
```

Source: [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)

## Scope Management

### Effective Scope Resolution

The storage system determines scope based on the presence of a session ID:

```typescript
const effectiveScope: "session" | "project" =
  scope ?? (sessionId ? "session" : "project");
```

Source: [src/session/purge.ts:4-6](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

### Scope Behaviors

| Scope | Session ID Required | Data Removed | Side Effects |
|-------|---------------------|--------------|--------------|
| session | Yes | Only rows for given sessionId | DB file preserved |
| project | No | All sessions in project | Full wipe of project data |

### Session-Scoped Operations

When `scope: "session"` is specified with a `sessionId`:

- Only rows belonging to the specified session are removed
- The SQLite database file remains intact
- The events.md sidecar is preserved
- FTS5 full-text search indexes are maintained
- Stats files are untouched

Source: [src/session/purge.ts:17-25](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

### Project-Scoped Operations

When `scope: "project"` is specified:

- Complete removal of all session data for the project
- Database file deletion
- Associated sidecar files removal
- Legacy hash compatibility paths also cleaned

## Purge Operations

### purgeSession Function

The primary cleanup API supports both session and project-scoped purging:

```typescript
async function purgeSession(
  projectDir: string,
  sessionId?: string,
  scope?: "session" | "project"
): Promise<PurgeResult>
```

Source: [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

### Purge Workflow

```mermaid
graph TD
    A[purgeSession Called] --> B{scope === 'session'?}
    B -->|Yes| C{sessionId provided?}
    C -->|No| D[Throw TypeError]
    C -->|Yes| E[Get hashes for project]
    E --> F[Open SessionDB per hash]
    F --> G[Count events before purge]
    G --> H[Delete session rows]
    H --> I{rowsRemoved?}
    I -->|Yes| J[Log removal]
    I -->|No| K[Skip logging]
    B -->|No| L[Project-scoped wipe]
    L --> M[Delete all project data]
    M --> N[Clean legacy paths]
```

### Validation Rules

Session-scoped purging requires explicit sessionId:

```typescript
if (effectiveScope === "session" && !sessionId) {
  throw new TypeError(
    "purgeSession: scope:'session' requires sessionId. " +
    "Pass scope:'project' for the legacy whole-project wipe."
  );
}
```

Source: [src/session/purge.ts:10-14](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

## Analytics System

### Purpose

The analytics module tracks session usage patterns and generates statistics for project health monitoring.

Source: [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)

### Key Metrics

| Metric | Description | Storage Location |
|--------|-------------|------------------|
| Session Count | Number of active sessions | stats.json |
| Event Count | Total events across sessions | SessionDB |
| Last Activity | Most recent session interaction | stats.json |
| Project Activity | Aggregate usage statistics | stats.json |

## Project Attribution

### Role

The project attribution system maintains the relationship between session data and their originating project directories, enabling:

- Cross-session context aggregation
- Project-level statistics compilation
- Worktree-aware hash generation
- Legacy compatibility for migrated projects

Source: [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)

### Hash Compatibility

The system maintains compatibility between canonical and legacy hash algorithms:

```typescript
const hashes = canonicalHash === legacyHash
  ? [canonicalHash]
  : [canonicalHash, legacyHash];
```

This ensures that projects migrated between different hash strategies can still access their historical session data.

Source: [src/session/purge.ts:31-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

## Store API

### Store Directory Management

The store directory module handles:

- Directory creation and validation
- Path resolution for session databases
- Cross-platform path normalization
- Worktree suffix generation

Source: [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)

### High-Level Store Operations

```typescript
interface Store {
  getSession(sessionId: string): Session;
  createSession(projectDir: string): Session;
  addEvent(sessionId: string, event: Event): void;
  querySessions(filter: QueryFilter): Session[];
}
```

Source: [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)

## Configuration

### Database Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| dbPath | string | Required | Path to SQLite database file |
| inMemory | boolean | false | Use in-memory database for testing |
| verbose | boolean | false | Enable SQL query logging |

### Storage Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| projectDir | string | process.cwd() | Root directory for session storage |
| sessionsDir | string | .context/sessions | Relative path for session databases |
| enableFTS | boolean | true | Enable full-text search indexing |

## Error Handling

### Common Errors

| Error | Condition | Resolution |
|-------|-----------|-------------|
| TypeError | session scope without sessionId | Provide sessionId or use project scope |
| ENOENT | Database file not found | Ensure project directory exists |
| EACCES | Permission denied | Check file system permissions |
| SQLITE_BUSY | Database locked | Retry operation or close other connections |

### Cleanup on Error

The purge operation ensures database connections are properly closed:

```typescript
let db: SessionDB | null = null;
try {
  db = new SessionDB({ dbPath });
  // ... operations
} finally {
  if (db) db.close();
}
```

Source: [src/session/purge.ts:35-42](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)

## Best Practices

### Session Management

1. Always provide explicit scope when calling purge operations
2. Use session IDs consistently across your application
3. Handle database errors with appropriate fallbacks
4. Close database connections after operations

### Performance Considerations

1. Batch event insertions when possible
2. Use project-scoped operations for complete cleanups
3. Leverage FTS5 for text search instead of full table scans
4. Clean up unused session data regularly

### Data Integrity

1. Verify hash calculations match across sessions
2. Check database file existence before operations
3. Use transactions for multi-step operations
4. Maintain legacy hash support for backwards compatibility

---

---

## Doramagic Pitfall Log

Project: mksglu/context-mode

Summary: Found 23 potential pitfall items; 3 are high/blocking. Highest priority: installation - 来源证据：Feature Request: Add CodeBuddy Code support.

## 1. installation · 来源证据：Feature Request: Add CodeBuddy Code support

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 2. installation · 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. installation · 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 4. installation · 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 5. installation · 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 6. installation · 来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 7. installation · 来源证据：[BUG]: Hardcoded storage path for many platforms

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 8. installation · 来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 9. installation · 来源证据：[Bug]: Plugin-only installation does not work with OpenCode

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 10. installation · 来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)
- User impact: 可能影响升级、迁移或版本选择。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 11. installation · 来源证据：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale; 4-char `lstatSync` fix
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_ccef8bb7485f482f9bcb08b6cc2494b2 | https://github.com/mksglu/context-mode/issues/644 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 12. configuration · 可能修改宿主 AI 配置

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- Evidence: capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code

## 13. configuration · 来源证据：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_a629676796f7486d9e185f643b260d07 | https://github.com/mksglu/context-mode/issues/560 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 14. configuration · 来源证据：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\uD83D` in tool_result and breaking the host API re…

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\uD83D` in tool_result and breaking the host API request
- User impact: 可能影响升级、迁移或版本选择。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_d52bae5266e442cea5a1fa5b42f86c1a | https://github.com/mksglu/context-mode/issues/659 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 15. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:1164477708 | https://github.com/mksglu/context-mode | README/documentation is current enough for a first validation pass.

## 16. runtime · 来源证据：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_sta…

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_stats` and timeline search degraded
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_cbceaf1c624d40049ac2151af7c1e83d | https://github.com/mksglu/context-mode/issues/645 | 来源类型 github_issue 暴露的待验证使用条件。

## 17. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:1164477708 | https://github.com/mksglu/context-mode | last_activity_observed missing

## 18. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium

## 19. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium

## 20. security_permissions · 来源证据：PreToolUse hook fails on project paths containing spaces (macOS)

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PreToolUse hook fails on project paths containing spaces (macOS)
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_0e6f8fa845c0493db18d97fc48cf1b82 | https://github.com/mksglu/context-mode/issues/636 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 21. security_permissions · 来源证据：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_c17fbb0a32674c7b9dad1eefe4a0c3d2 | https://github.com/mksglu/context-mode/issues/647 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 22. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:1164477708 | https://github.com/mksglu/context-mode | issue_or_pr_quality=unknown

## 23. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:1164477708 | https://github.com/mksglu/context-mode | release_recency=unknown

<!-- canonical_name: mksglu/context-mode; human_manual_source: deepwiki_human_wiki -->
