Doramagic Project Pack · Human Manual

context-mode

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 modi...

Introduction to Context Mode

Related topics: Core Concepts, Getting Started

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Concepts

Continue reading this section for the full explanation and source context.

Section Key Features

Continue reading this section for the full explanation and source context.

Section Components

Continue reading this section for the full explanation and source context.

Related topics: Core Concepts, Getting Started

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

FeatureDescription
Plugin ArchitectureExtensible system for loading custom rule handlers
Rule Freshness TrackingMonitors when rules were last used or updated
Load CountingTracks how frequently each rule is accessed
Health MonitoringProvides insights into rule maintenance status

System Architecture

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

MetricDescriptionData Source
Total RulesNumber of active rules in the systemrulesFreshness.length
Most LoadedRule with highest usage counttop.load_count
Load CountNumber of times a rule has been invokedr.load_count
Last SeenTimestamp of last rule accessr.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:

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

Results are displayed as:

DaysDisplay
0"today"
1"1d ago"
>1"{N}d ago"

Source: insight/src/routes/index.tsx:1-40

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:

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:

FieldTypePurpose
rule_pathstringFull path to the rule file
load_countnumberNumber of times the rule was loaded
last_seentimestampWhen 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:

{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.

Source: https://github.com/mksglu/context-mode / Human Manual

Core Concepts

Related topics: Context Saving, Session Continuity, Think in Code Paradigm

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Requirements

Continue reading this section for the full explanation and source context.

Section Environment Setup

Continue reading this section for the full explanation and source context.

Section Plugin Architecture

Continue reading this section for the full explanation and source context.

Related topics: Context Saving, Session Continuity, Think in Code Paradigm

The provided context only contains the web/index.html landing page file repeated multiple times. The actual source code files listed in the `

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:

AttributeValue
ArchitecturePlugin-based modular system
LanguageTypeScript, React
UI Frameworkshadcn/ui components
RoutingDynamic routes with hash-based identifiers
Data ModelChunk-based content retrieval

Source: 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

# 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

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:

PluginPurpose
claude-codeIntegration for Claude Code AI assistant
gemini-cliIntegration 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 Source: configs/gemini-cli/GEMINI.md

Running the Application

Development Mode

To start the development server:

pnpm dev

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

Build for Production

pnpm build

Preview Production Build

pnpm preview

Source: 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:

<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:

PropertyValuePurpose
Containermax-h-80 overflow-y-autoScrollable with max height
Borderborder-border/50Subtle border styling
Texttext-xs font-monoMonospace code display
Whitespacewhitespace-pre-wrapPreserve formatting

Source: insight/src/routes/knowledge_.$dbHash.$sourceId.tsx

Dynamic Routing

The application uses file-based routing with dynamic parameters:

Route Pattern

/knowledge/:dbHash/:sourceId
ParameterDescription
dbHashDatabase hash identifier for the knowledge source
sourceIdUnique identifier for the specific content source

Data Flow

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

Gemini CLI Configuration

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

Source: 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

# Run unit tests
pnpm test

# Run linting
pnpm lint

Source: 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:

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:

FieldTypeDescription
contentstringThe actual content text
titlestringDisplay title for the chunk
metadataobjectAdditional contextual information

Troubleshooting

Common Issues

IssueSolution
Dependencies fail to installClear pnpm cache: pnpm store prune
Build errorsEnsure Node.js version is 18+
UI components not renderingCheck 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:

Source: https://github.com/mksglu/context-mode / Human Manual

Architecture Overview

Related topics: Platform Adapters, Hooks System

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Context Window Optimization

Continue reading this section for the full explanation and source context.

Section MCP Integration

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Related topics: Platform Adapters, Hooks System

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

Supported Platforms

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

PlatformStatus
Claude CodePrimary
CursorSupported
CopilotSupported
15+ additional platformsSupported

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

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

System Architecture

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:

ComponentPurpose
MCP ServerHandles protocol communication with AI agents
Adapter LayerProvides platform-specific integrations
FTS5 DatabaseStores and indexes tool outputs
Sandbox EnvironmentExecutes 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

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

Source: https://github.com/mksglu/context-mode / Human Manual

Platform Adapters

Related topics: Architecture Overview, Hooks System

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Adapter Pattern Design

Continue reading this section for the full explanation and source context.

Section Supported Platforms

Continue reading this section for the full explanation and source context.

Section Automatic Detection Mechanism

Continue reading this section for the full explanation and source context.

Related topics: Architecture Overview, Hooks System

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

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
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

Supported Platforms

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

PlatformAdapter ModuleStatus
Claude Codesrc/adapters/claude-code/index.tsActive
Cursorsrc/adapters/cursor/index.tsActive
Codexsrc/adapters/codex/index.tsActive
Gemini CLIsrc/adapters/gemini-cli/index.tsActive
OpenClawsrc/adapters/openclaw/index.tsActive
OpenCodesrc/adapters/opencode/index.tsActive
GitHub Copilot(integrated via MCP)Active
+ 8 more platformsVariousActive

Source: 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.

// 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

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

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.

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

Adapter Initialization

Each platform adapter follows a consistent initialization pattern:

PhaseDescription
1. ImportLoad platform-specific dependencies
2. ConfigureSet up platform-specific options
3. RegisterRegister tool handlers and callbacks
4. ActivateEnable context sandboxing for the platform
5. MonitorTrack active tool invocations

Source: 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

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

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

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

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

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

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
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

Context Window Optimization

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

MetricWithout context-modeWith context-mode
Tool output in context100%~2%
Context duration~20 minutes~10 hours
Context utilizationInefficientOptimized

Source: web/index.html

Configuration

Adapter Configuration Options

Each adapter supports platform-specific configuration options:

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:

SettingDefaultDescription
autoDetecttrueAutomatically detect active platform
defaultAdapternullFallback adapter if detection fails
logLevel'info'Logging verbosity level
cacheAdapterstrueCache adapter instances

Source: 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
// 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

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.

Source: https://github.com/mksglu/context-mode / Human Manual

Hooks System

Related topics: Architecture Overview, Context Saving

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Event Flow

Continue reading this section for the full explanation and source context.

Section PostToolUse

Continue reading this section for the full explanation and source context.

Related topics: Architecture Overview, Context Saving

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

ComponentTypePurpose
hooks.jsonConfigurationCentral registry mapping event types to handler scripts
pretooluse.mjsHandler ScriptPre-tool invocation routing and validation
posttooluse.mjsHandler ScriptPost-tool result capture and session logging
precompact.mjsHandler ScriptPre-compaction context snapshot management
sessionstart.mjsHandler ScriptSession initialization and context injection
routing-block.mjsUtility ModuleShared routing decision logic
hook-config.tsTypeScript UtilityConfiguration loading and validation

Event Flow

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:

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 TypeHandler 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

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:

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

Environment Variables

VariableDescription
CLAUDE_PLUGIN_ROOTRoot 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

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

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
{
  "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

PracticeRationale
Keep handlers idempotentHooks may be invoked multiple times for the same event
Validate all inputsUntrusted tool outputs should be sanitized before storage
Log decisionsMaintain audit trail for routing and denial reasons
Use exit codesEnable Claude to detect hook failures gracefully
Document denial reasonsProvides 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

Source: https://github.com/mksglu/context-mode / Human Manual

Context Saving

Related topics: Core Concepts, Think in Code Paradigm

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section Core Responsibilities

Continue reading this section for the full explanation and source context.

Related topics: Core Concepts, Think in Code Paradigm

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

ComponentFileResponsibility
AutoMemorysrc/search/auto-memory.tsOrchestrates the indexing and retrieval workflow
Truncationsrc/truncate.tsPre-processes and size-limits content before storage
FetchCachesrc/fetch-cache.tsManages cached HTTP responses for tool calls
Routinghooks/core/routing.mjsDirects tool outputs to appropriate storage handlers

Data Flow

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:

FieldTypeDescription
idINTEGERAuto-incrementing unique identifier
contentTEXTFull tool output content
tool_nameTEXTName of the tool that produced the output
timestampINTEGERUnix timestamp of tool execution
session_idTEXTIdentifier linking output to current session
project_pathTEXTWorking 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

OptionDefaultDescription
maxIndexedSize10KBMaximum content size for direct FTS5 indexing
truncationSuffix"... [truncated]"Marker appended to truncated content
preserveRecentLines50Number 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

FieldDescription
request_keySHA-256 hash of URL + headers
response_bodyCached response content
status_codeHTTP status of cached response
created_atTimestamp of cache entry creation
expires_atExpiration timestamp based on TTL
access_countNumber 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

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
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:

ParameterTypeDefaultDescription
enabledbooleantrueMaster toggle for context saving
indexStrategystring"fts5"Indexing backend to use
maxContextAgenumber86400Maximum age in seconds before re-indexing
retrievalLimitnumber5Maximum number of results per query
cacheEnabledbooleantrueEnable HTTP response caching
cacheTTLnumber3600Cache 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

Source: https://github.com/mksglu/context-mode / Human Manual

Session Continuity

Related topics: Core Concepts, Session Storage, Context Saving

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Session Database (src/session/db.ts)

Continue reading this section for the full explanation and source context.

Section Snapshot Module (src/session/snapshot.ts)

Continue reading this section for the full explanation and source context.

Section Extract Module (src/session/extract.ts)

Continue reading this section for the full explanation and source context.

Related topics: Core Concepts, Session Storage, Context Saving

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

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 TypePurposeRetention
NavigationBrowser/page stateTemporary
ContextIndexed content statePersistent
WorkflowTask/operation stateSession-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:

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:

MethodDescription
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

  • 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-PatternIssueRecommended Approach
Using ctx_index(content: response) after MCP tool callsDoubles context usageUse response directly or save to file first
Ignoring browser_navigate auto-snapshotMisses page state captureExplicitly call browser_snapshot()
Using ctx_stats for resetsIt's read-onlyUse ctx_purge() for deletions

Source: skills/context-mode/SKILL.md

Configuration Options

Session continuity behavior can be tuned through configuration:

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

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:

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

See Also

Source: https://github.com/mksglu/context-mode / Human Manual

Think in Code Paradigm

Related topics: Core Concepts

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Sandbox Isolation

Continue reading this section for the full explanation and source context.

Section Full-Text Search Indexing

Continue reading this section for the full explanation and source context.

Section On-Demand Context Loading

Continue reading this section for the full explanation and source context.

Related topics: Core Concepts

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.

MetricTraditional ApproachThink in Code
Context consumption rateRapid accumulation98% reduction
Average session duration~20 minutesExtended significantly
Tool output retentionIn conversationIndexed externally
Context retrievalPassive (all loaded)Active (search on demand)

Source: 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

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:

LayerResponsibility
MCP Plugin InterfaceBridges AI agent and tool execution environment
Execution SandboxRuns tools and captures output safely
FTS5 IndexStores 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
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:

PlatformIntegration TypeStatus
Claude CodeMCP PluginActive
CursorMCP PluginActive
CopilotMCP PluginActive
Additional 12 platformsVariousSupported

Source: 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

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.

Source: https://github.com/mksglu/context-mode / Human Manual

Session Storage

Related topics: Session Continuity

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Storage Layer Components

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section Path Generation

Continue reading this section for the full explanation and source context.

Related topics: Session Continuity

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

Architecture

Storage Layer Components

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
ComponentPurposeKey Files
SessionDBCore database abstraction over SQLitesrc/session/db.ts
DBBaseBase class providing common database operationssrc/db-base.ts
Store DirectoryManages file system paths for session databasessrc/store-directory.ts
StoreHigh-level API for session operationssrc/store.ts
AnalyticsSession usage statistics and metricssrc/session/analytics.ts
PurgeSession and project data cleanupsrc/session/purge.ts

Data Flow

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:

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

Session Database (SessionDB)

Database Schema

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

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

Source: src/session/db.ts

Database Base Class

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

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

Source: src/db-base.ts

Scope Management

Effective Scope Resolution

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

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

Source: src/session/purge.ts:4-6

Scope Behaviors

ScopeSession ID RequiredData RemovedSide Effects
sessionYesOnly rows for given sessionIdDB file preserved
projectNoAll sessions in projectFull 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

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:

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

Source: src/session/purge.ts

Purge Workflow

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:

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

Analytics System

Purpose

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

Source: src/session/analytics.ts

Key Metrics

MetricDescriptionStorage Location
Session CountNumber of active sessionsstats.json
Event CountTotal events across sessionsSessionDB
Last ActivityMost recent session interactionstats.json
Project ActivityAggregate usage statisticsstats.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

Hash Compatibility

The system maintains compatibility between canonical and legacy hash algorithms:

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

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

High-Level Store Operations

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

Source: src/store.ts

Configuration

Database Options

OptionTypeDefaultDescription
dbPathstringRequiredPath to SQLite database file
inMemorybooleanfalseUse in-memory database for testing
verbosebooleanfalseEnable SQL query logging

Storage Options

OptionTypeDefaultDescription
projectDirstringprocess.cwd()Root directory for session storage
sessionsDirstring.context/sessionsRelative path for session databases
enableFTSbooleantrueEnable full-text search indexing

Error Handling

Common Errors

ErrorConditionResolution
TypeErrorsession scope without sessionIdProvide sessionId or use project scope
ENOENTDatabase file not foundEnsure project directory exists
EACCESPermission deniedCheck file system permissions
SQLITE_BUSYDatabase lockedRetry operation or close other connections

Cleanup on Error

The purge operation ensures database connections are properly closed:

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

Source: src/session/purge.ts:35-42

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

Source: https://github.com/mksglu/context-mode / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Feature Request: Add CodeBuddy Code support

First-time setup may fail or require extra isolation and rollback planning.

high ctx_batch_execute corrupts heredoc commands by appending stderr redirection

First-time setup may fail or require extra isolation and rollback planning.

high v1.0.146: plugin.json points to wrong skills path and stale MCP server path

First-time setup may fail or require extra isolation and rollback planning.

medium OpenCode plugin registers hooks only -- never registers ctx_* tools

First-time setup may fail or require extra isolation and rollback planning.

Doramagic Pitfall Log

Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.

1. Installation risk: Feature Request: Add CodeBuddy Code support

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Feature Request: Add CodeBuddy Code support. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/651

2. Installation risk: ctx_batch_execute corrupts heredoc commands by appending stderr redirection

  • Severity: high
  • Finding: Installation risk is backed by a source signal: ctx_batch_execute corrupts heredoc commands by appending stderr redirection. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/656

3. Installation risk: v1.0.146: plugin.json points to wrong skills path and stale MCP server path

  • Severity: high
  • Finding: Installation risk is backed by a source signal: v1.0.146: plugin.json points to wrong skills path and stale MCP server path. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/658

4. Installation risk: OpenCode plugin registers hooks only -- never registers ctx_* tools

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: OpenCode plugin registers hooks only -- never registers ctx_* tools. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/637

5. Installation risk: Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/561

6. Installation risk: Pi subagent fails: DatabaseLockedError - another context-mode server is already running

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: Pi subagent fails: DatabaseLockedError - another context-mode server is already running. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/562

7. Installation risk: [BUG]: Hardcoded storage path for many platforms

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: [BUG]: Hardcoded storage path for many platforms. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/649

8. Installation risk: [BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: [BUG]: ctx_search source filter does not escape LIKE wildcards — unintended cross-source result leakage. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/646

9. Installation risk: [Bug]: Plugin-only installation does not work with OpenCode

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: [Bug]: Plugin-only installation does not work with OpenCode. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/652

10. Installation risk: ctx-upgrade leaves old server process running (zombie instance on upgrade)

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: ctx-upgrade leaves old server process running (zombie instance on upgrade). Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/559

11. Installation risk: sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: sessionstart.mjs age-gated cleanup uses statSync (follows symlinks) — deletes fresh symlinks whose targets are stale;…. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/mksglu/context-mode/issues/644

12. Configuration risk: Configuration risk needs validation

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: Configuration risk needs validation. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using context-mode with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence