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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| 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
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] --> DComponents
The system consists of several interconnected components:
- Core Engine - Handles request routing and rule application
- Plugin Registry - Maintains registered plugins and their configurations
- Rule Loader - Dynamically loads and parses rule definitions
- Health Monitor - Tracks system metrics and rule usage statistics
- 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:
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
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:
| 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:
- The system identifies relevant rules based on context
- Rules are loaded and merged into the instruction prompt
- The enhanced prompt is sent to the AI model
- 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| 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
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:
| 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 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:
| 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
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
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
- Create a feature branch from
main - Make your changes following the project's code style
- Test locally using
pnpm dev - 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
- Create a new directory under
configs/ - Add configuration files specific to the AI tool
- 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:
| 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:
Source: https://github.com/mksglu/context-mode / Human Manual
Architecture Overview
Related topics: Platform Adapters, Hooks System
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| 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
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:
- Sandboxing: Tool outputs are captured and stored locally rather than in the conversation context
- Full-Text Indexing: Outputs are indexed into SQLite with FTS5 for fast retrieval
- On-Demand Search: The AI can query the index when specific tool output is needed
- 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| ATechnical 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
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 OutputKey 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| 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
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:
- Environment Variable Inspection: Checks for platform-specific environment variables
- Process Analysis: Identifies running processes associated with specific platforms
- Configuration File Detection: Looks for platform configuration files in the workspace
- 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 --> DSource: 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
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:
- Captures tool output at the adapter level
- Stores output in the FTS5 indexed database
- Returns a reference/pointer instead of full content
- 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:
| 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
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:
| 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
Extending Platform Support
Adding a New Platform Adapter
To add support for a new platform, create a new adapter module following these steps:
- Create
src/adapters/<platform-name>/index.ts - Implement the standard adapter interface
- Register the adapter in
client-map.ts - Add detection logic in
detect.ts - 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| 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
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:#cce5ffHook 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 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
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
| 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
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:
- Input Parsing: Read hook payload from environment variables or stdin
- Business Logic: Execute routing, logging, or state management
- Output: Write results to session storage or return control signals
- 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: ContinueConfiguration 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:
- Add a new entry to the
PreToolUsearray inhooks.json - Specify the matcher pattern (tool name or regex)
- 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:
- Modify
routing-block.mjsto include new rule definitions - Add denial reasons to the ADR documentation
- 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
Source: https://github.com/mksglu/context-mode / Human Manual
Context Saving
Related topics: Core Concepts, Think in Code Paradigm
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
- Sandboxing - Tool outputs are captured and stored in isolated storage rather than returned directly to the conversation
- 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
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:
- Individual tool outputs can be arbitrarily large (e.g., compiled binaries, full file dumps)
- FTS5 has practical limits on indexed content size
- Even sandboxed content should be bounded for performance
Truncation Strategy
The truncation service applies a multi-pass approach:
- Initial Assessment - Content size is measured against configurable thresholds
- Intelligent Cutting - For structured outputs, truncation attempts to preserve meaningful boundaries (JSON objects, log sections)
- Suffix Preservation - When truncating, the service preserves recent output lines rather than arbitrary cuts
- 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
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:
- HTTP Tools - Cached responses are stored and indexed separately
- File Operations - Read/write operations are tagged with file paths for targeted retrieval
- Shell Commands - Outputs are parsed for structure before indexing
- Unknown Tools - Generic handling with basic text indexing
Retrieval Workflow
When an agent needs information from saved context, the retrieval workflow proceeds as follows:
- Query Reception - AutoMemory receives the agent's information request
- Query Translation - Natural language is converted to FTS5 MATCH syntax
- Index Search - FTS5 performs the full-text search across indexed content
- Result Ranking - BM25 scoring ranks results by relevance
- Content Assembly - Top-ranked results are assembled into a context snippet
- 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 conversationConfiguration
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
Source: https://github.com/mksglu/context-mode / Human Manual
Session Continuity
Related topics: Core Concepts, Session Storage, Context Saving
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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 --> ACore 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:
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 UpdateSource: 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:
- Indexing: Content from snapshots and extracted data is indexed
- Querying: Fast retrieval using indexed search
- 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:
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]- User initiates session resume
- System loads session metadata from database
- Latest snapshot is retrieved and applied
- Context index is restored to previous state
- 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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.
| 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
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| AThe 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:
- The tool command runs within the sandbox environment
- Output streams are captured in memory
- Results are written to indexed storage
- 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:
| 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
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 excerptsBest 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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| 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
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: SuccessStorage 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
| 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
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
| 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
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
| 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:
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
- Always provide explicit scope when calling purge operations
- Use session IDs consistently across your application
- Handle database errors with appropriate fallbacks
- Close database connections after operations
Performance Considerations
- Batch event insertions when possible
- Use project-scoped operations for complete cleanups
- Leverage FTS5 for text search instead of full table scans
- Clean up unused session data regularly
Data Integrity
- Verify hash calculations match across sessions
- Check database file existence before operations
- Use transactions for multi-step operations
- 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.
First-time setup may fail or require extra isolation and rollback planning.
First-time setup may fail or require extra isolation and rollback planning.
First-time setup may fail or require extra isolation and rollback planning.
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_searchsource 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.
Count of project-level external discussion links exposed on this manual page.
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.
- v1.0.146: plugin.json points to wrong skills path and stale MCP server p - github / github_issue
- Preview truncation slices UTF-16 surrogate pairs, producing orphan `\uD8 - github / github_issue
- [[Bug]: Plugin-only installation does not work with OpenCode](https://github.com/mksglu/context-mode/issues/652) - github / github_issue
- ctx_batch_execute corrupts heredoc commands by appending stderr redirect - github / github_issue
- v1.0.146: Plugin error 'Path not found: .claude/skills' — actual path is - github / github_issue
- Feature Request: Add CodeBuddy Code support - github / github_issue
- [[BUG]: Hardcoded storage path for many platforms](https://github.com/mksglu/context-mode/issues/649) - github / github_issue
- [[BUG]: MCP bridge silently degrades on slow
initialize— retry on time](https://github.com/mksglu/context-mode/issues/647) - github / github_issue - [[BUG]:
ctx_searchsource filter does not escape LIKE wildcards — unint](https://github.com/mksglu/context-mode/issues/646) - github / github_issue - [[BUG]:Pi and OMP adapters write SessionDB to
context-mode.dbbut MCP s](https://github.com/mksglu/context-mode/issues/645) - github / github_issue - sessionstart.mjs age-gated cleanup uses
statSync(follows symlinks) — - github / github_issue - PreToolUse hook fails on project paths containing spaces (macOS) - github / github_issue
Source: Project Pack community evidence and pitfall evidence