# mksglu/context-mode architecture

> Architecture diagram of the GitHub repository mksglu/context-mode, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/mksglu/context-mode
- Repository: https://github.com/mksglu/context-mode

## Overview

#### Purpose and Entry Points
Context Mode is a local Node.js/Bun context-management system for AI coding clients. It exposes MCP sandbox, indexing/search, statistics, diagnostics, upgrade, and purge tools; captures session state through client hooks; and restores concise working state after compaction or resume. Primary executable paths are `src/cli.ts`, `start.mjs`, and the MCP server in `src/server.ts`; distributable bundles are `cli.bundle.mjs` and `server.bundle.mjs`.

#### CLI, MCP Server, and Tool Execution
The CLI dispatches terminal commands, hook invocations, and MCP startup. The server publishes the `ctx_*` tool surface and routes requests into execution, search, session, and lifecycle services. Sandboxed execution runs code in subprocesses and returns bounded stdout rather than raw artifacts; batching/pooling supports concurrent work.
- `src/cli.ts`
- `src/server.ts`
- `src/executor.ts`
- `src/runPool.ts`

#### Cross-Client Adapter Boundary
Adapters isolate client-specific configuration paths, protocol shapes, hook registration, platform detection, and installation behavior behind common adapter types. Supported clients include Claude Code, Codex, Gemini, Cursor, Copilot variants, OpenCode/Kilo, Pi/OMP, OpenClaw, Kimi, Kiro, Qwen, Zed, and Antigravity. This boundary prevents core context/session semantics from depending on a particular agent runtime.
- `src/adapters/base.ts`
- `src/adapters/detect.ts`
- `src/adapters/client-map.ts`
- `src/adapters/types.ts`

#### Hook Routing and Event Capture
Client hook shims normalize lifecycle events—pre-tool routing/security decisions, post-tool capture, prompt submission, compaction, session start, and stop—into shared behavior. Pre-tool routing blocks or redirects high-output/raw-data operations where host capabilities permit; post-tool and prompt hooks generate structured session events. Platform bridges and formatters adapt each host’s stdin/stdout payload and response contract.
- `hooks/run-hook.mjs`
- `hooks/pretooluse.mjs`
- `hooks/posttooluse.mjs`
- `hooks/core/routing.mjs`
- `hooks/platform-bridge.mjs`

#### Session Continuity Pipeline
Structured tool and prompt events are persisted per project/session, classified, and later condensed into snapshots. On compaction or continuation, snapshots and relevant event history are reconstructed into a session directive rather than replaying raw transcripts. Analytics/pricing derive usage, cost, and savings reports from this same persisted state.
- `src/session/db.ts`
- `src/session/event-emit.ts`
- `src/session/extract.ts`
- `src/session/snapshot.ts`
- `src/session/analytics.ts`

#### Local Knowledge Store and Retrieval
The knowledge subsystem indexes local content and fetched pages into project-scoped SQLite FTS5 stores. Unified retrieval combines porter and trigram search, applies ranking/reranking and snippets, and limits repeated searches with a flood guard. URL fetches use a TTL cache; raw fetched content stays local while searches return selected excerpts.
- `src/store.ts`
- `src/search/unified.ts`
- `src/search/auto-memory.ts`
- `src/fetch-cache.ts`

#### Runtime, Storage, and Security
The runtime selects Bun SQLite, Node `node:sqlite`, or `better-sqlite3`; storage roots are adapter/project-aware. Security applies Claude-style allow/deny policies to sandbox commands, constrains file processing to project boundaries, and hardens network fetch targets. Native/plugin integrations run in-process where supported, notably OpenCode/Kilo, Pi/OMP, and OpenClaw.
- `src/runtime.ts`
- `src/db-base.ts`
- `src/security.ts`
- `src/store-directory.ts`
- `src/adapters/openclaw/plugin.ts`

#### Distribution and Integrations
Client-specific installable bundles, rules, skills, and hook manifests live under `configs/` and plugin directories. OpenClaw has a dedicated gateway plugin, while Pi ships an extension. The optional static `web/` content is informational/dashboard-facing, not the product’s primary runtime; all context data processing and SQLite persistence remain local.
- `configs/`
- `.openclaw-plugin/index.ts`
- `.pi/extensions/context-mode/index.ts`
- `web/worker.js`

Main entry points: [`src/server.ts`](https://github.com/mksglu/context-mode/blob/main/src/server.ts) (MCP server), [`hooks/run-hook.mjs`](https://github.com/mksglu/context-mode/blob/main/hooks/run-hook.mjs) (Hook shims), [`src/session/db.ts`](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts) (Session database), [`src/adapters/base.ts`](https://github.com/mksglu/context-mode/blob/main/src/adapters/base.ts) (Adapter contract)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_entry["Entry &amp; MCP"]
  node_cli["CLI dispatcher<br/>Node/Bun CLI<br/>[cli.ts]"]
  node_server["MCP server<br/>MCP API<br/>[server.ts]"]
  node_executor["Sandbox executor<br/>subprocess execution<br/>[executor.ts]"]
  node_run_pool["Execution pool<br/>concurrency pool<br/>[runPool.ts]"]
end

subgraph group_clients["Client Integration"]
  node_adapter_base["Adapter contract<br/>adapter boundary<br/>[base.ts]"]
  node_client_detection["Client detection<br/>adapter selection<br/>[detect.ts]"]
  node_hook_runner["Hook shims<br/>client hook entry<br/>[run-hook.mjs]"]
  node_hook_routing["Pre-tool routing<br/>hook policy<br/>[routing.mjs]"]
  node_platform_bridge["Platform bridge<br/>protocol adapter"]
  node_openclaw_plugin{{"OpenClaw plugin<br/>native integration<br/>[plugin.ts]"}}
  node_distribution["Client bundles &amp; manifests<br/>distribution assets"]
end

subgraph group_context["Context Pipeline"]
  node_session_events["Session event capture<br/>structured events<br/>[event-emit.ts]"]
  node_session_db[("Session database<br/>SQLite state<br/>[db.ts]")]
  node_snapshot["Snapshots &amp; directives<br/>continuity service<br/>[snapshot.ts]"]
  node_analytics["Usage analytics<br/>reporting<br/>[analytics.ts]"]
end

subgraph group_knowledge["Knowledge Retrieval"]
  node_knowledge_store[("Project knowledge store<br/>SQLite FTS5<br/>[store.ts]")]
  node_unified_search["Unified search<br/>retrieval pipeline<br/>[unified.ts]"]
  node_fetch_cache[("Fetch cache<br/>TTL local cache<br/>[fetch-cache.ts]")]
end

subgraph group_platform["Local Platform"]
  node_runtime["Runtime &amp; DB selection<br/>runtime abstraction<br/>[runtime.ts]"]
  node_security["Security policy<br/>sandbox policy<br/>[security.ts]"]
end

node_cli -->|"starts MCP"| node_server
node_cli -->|"selects client"| node_client_detection
node_server -->|"runs sandbox tools"| node_executor
node_executor -->|"uses"| node_run_pool
node_security -->|"authorizes commands"| node_executor
node_server -->|"serves retrieval tools"| node_unified_search
node_server -->|"serves continuity tools"| node_snapshot
node_client_detection -->|"instantiates"| node_adapter_base
node_adapter_base -->|"registers hooks"| node_hook_runner
node_hook_runner -->|"normalizes payloads"| node_platform_bridge
node_hook_runner -->|"pre-tool decisions"| node_hook_routing
node_hook_runner -->|"captures lifecycle events"| node_session_events
node_session_events -->|"persists"| node_session_db
node_session_db -->|"history source"| node_snapshot
node_snapshot -.->|"continuation directive"| node_session_events
node_session_db -->|"usage data"| node_analytics
node_unified_search -->|"queries FTS indexes"| node_knowledge_store
node_fetch_cache -->|"cached pages indexed"| node_knowledge_store
node_security -->|"hardens fetch targets"| node_fetch_cache
node_runtime -->|"provides SQLite backend"| node_session_db
node_runtime -->|"provides SQLite backend"| node_knowledge_store
node_distribution -->|"installs client assets"| node_adapter_base
node_openclaw_plugin -->|"native adapter integration"| node_adapter_base

click node_cli "https://github.com/mksglu/context-mode/blob/main/src/cli.ts"
click node_server "https://github.com/mksglu/context-mode/blob/main/src/server.ts"
click node_executor "https://github.com/mksglu/context-mode/blob/main/src/executor.ts"
click node_run_pool "https://github.com/mksglu/context-mode/blob/main/src/runPool.ts"
click node_adapter_base "https://github.com/mksglu/context-mode/blob/main/src/adapters/base.ts"
click node_client_detection "https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts"
click node_hook_runner "https://github.com/mksglu/context-mode/blob/main/hooks/run-hook.mjs"
click node_hook_routing "https://github.com/mksglu/context-mode/blob/main/hooks/core/routing.mjs"
click node_platform_bridge "https://github.com/mksglu/context-mode/blob/main/hooks/platform-bridge.mjs"
click node_session_events "https://github.com/mksglu/context-mode/blob/main/src/session/event-emit.ts"
click node_session_db "https://github.com/mksglu/context-mode/blob/main/src/session/db.ts"
click node_snapshot "https://github.com/mksglu/context-mode/blob/main/src/session/snapshot.ts"
click node_analytics "https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts"
click node_knowledge_store "https://github.com/mksglu/context-mode/blob/main/src/store.ts"
click node_unified_search "https://github.com/mksglu/context-mode/blob/main/src/search/unified.ts"
click node_fetch_cache "https://github.com/mksglu/context-mode/blob/main/src/fetch-cache.ts"
click node_runtime "https://github.com/mksglu/context-mode/blob/main/src/runtime.ts"
click node_security "https://github.com/mksglu/context-mode/blob/main/src/security.ts"
click node_openclaw_plugin "https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/plugin.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_cli,node_server,node_executor,node_run_pool toneBlue
class node_adapter_base,node_client_detection,node_hook_runner,node_hook_routing,node_platform_bridge,node_openclaw_plugin,node_distribution toneAmber
class node_session_events,node_session_db,node_snapshot,node_analytics toneMint
class node_knowledge_store,node_unified_search,node_fetch_cache toneRose
class node_runtime,node_security toneIndigo
```

## Components

### Entry & MCP

- [CLI dispatcher](https://github.com/mksglu/context-mode/blob/main/src/cli.ts): Node/Bun CLI · Dispatches commands, hooks, and MCP startup. · `src/cli.ts`
- [MCP server](https://github.com/mksglu/context-mode/blob/main/src/server.ts): MCP API · Publishes the ctx_* tool surface. · `src/server.ts`
- [Sandbox executor](https://github.com/mksglu/context-mode/blob/main/src/executor.ts): subprocess execution · Returns bounded command output. · `src/executor.ts`
- [Execution pool](https://github.com/mksglu/context-mode/blob/main/src/runPool.ts): concurrency pool · `src/runPool.ts`

### Client Integration

- [Adapter contract](https://github.com/mksglu/context-mode/blob/main/src/adapters/base.ts): adapter boundary · Keeps core semantics client-independent. · `src/adapters/base.ts`
- [Client detection](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts): adapter selection · `src/adapters/detect.ts`
- [Hook shims](https://github.com/mksglu/context-mode/blob/main/hooks/run-hook.mjs): client hook entry · Normalizes client lifecycle payloads. · `hooks/run-hook.mjs`
- [Pre-tool routing](https://github.com/mksglu/context-mode/blob/main/hooks/core/routing.mjs): hook policy · Blocks or redirects high-output operations when supported. · `hooks/core/routing.mjs`
- [Platform bridge](https://github.com/mksglu/context-mode/blob/main/hooks/platform-bridge.mjs): protocol adapter · `hooks/platform-bridge.mjs`
- [OpenClaw plugin](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/plugin.ts): native integration · `src/adapters/openclaw/plugin.ts`
- **Client bundles & manifests**: distribution assets

### Context Pipeline

- [Session event capture](https://github.com/mksglu/context-mode/blob/main/src/session/event-emit.ts): structured events · Emits tool and prompt events per project/session. · `src/session/event-emit.ts`
- [Session database](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts): SQLite state · `src/session/db.ts`
- [Snapshots & directives](https://github.com/mksglu/context-mode/blob/main/src/session/snapshot.ts): continuity service · Condenses history and reconstructs resume context. · `src/session/snapshot.ts`
- [Usage analytics](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts): reporting · Derives cost and savings from session state. · `src/session/analytics.ts`

### Knowledge Retrieval

- [Project knowledge store](https://github.com/mksglu/context-mode/blob/main/src/store.ts): SQLite FTS5 · Indexes local content and fetched pages. · `src/store.ts`
- [Unified search](https://github.com/mksglu/context-mode/blob/main/src/search/unified.ts): retrieval pipeline · Combines search, ranking, snippets, and flood control. · `src/search/unified.ts`
- [Fetch cache](https://github.com/mksglu/context-mode/blob/main/src/fetch-cache.ts): TTL local cache · `src/fetch-cache.ts`

### Local Platform

- [Runtime & DB selection](https://github.com/mksglu/context-mode/blob/main/src/runtime.ts): runtime abstraction · Selects Bun SQLite, node:sqlite, or better-sqlite3. · `src/runtime.ts`
- [Security policy](https://github.com/mksglu/context-mode/blob/main/src/security.ts): sandbox policy · Applies command, project-boundary, and fetch restrictions. · `src/security.ts`

## Connections

- CLI dispatcher → MCP server: starts MCP
- CLI dispatcher → Client detection: selects client
- MCP server → Sandbox executor: runs sandbox tools
- Sandbox executor → Execution pool: uses
- Security policy → Sandbox executor: authorizes commands
- MCP server → Unified search: serves retrieval tools
- MCP server → Snapshots & directives: serves continuity tools
- Client detection → Adapter contract: instantiates
- Adapter contract → Hook shims: registers hooks
- Hook shims → Platform bridge: normalizes payloads
- Hook shims → Pre-tool routing: pre-tool decisions
- Hook shims → Session event capture: captures lifecycle events
- Session event capture → Session database: persists
- Session database → Snapshots & directives: history source
- Snapshots & directives → Session event capture: continuation directive
- Session database → Usage analytics: usage data
- Unified search → Project knowledge store: queries FTS indexes
- Fetch cache → Project knowledge store: cached pages indexed
- Security policy → Fetch cache: hardens fetch targets
- Runtime & DB selection → Session database: provides SQLite backend
- Runtime & DB selection → Project knowledge store: provides SQLite backend
- Client bundles & manifests → Adapter contract: installs client assets
- OpenClaw plugin → Adapter contract: native adapter integration
