OpenCode Plugin Memory System - Verifiable Context Protection, Tool Firewall, Rolling Compaction & Semantic Retrieval
| You want | Run | What lands on disk |
|---|---|---|
| Agent Install (Recommended) | Let your LLM Agent read the install guide and execute | DB init + plugin registration + diagnostics, one shot |
| Manual Install | git clone -> pnpm install -> pnpm run build -> node dist/cli.js setup |
Same, full control over each step |
Strongly recommended: let an LLM agent install this for you. Database initialization, plugin registration, and diagnostic checks - an agent reads the guide once and walks every step correctly.
Paste this prompt into OpenCode, Cursor, Claude Code, or any agent:
Install and configure Context Chronicle by following the instructions here:
https://raw.githubusercontent.com/github-yjc/context-chronicle/main/docs/INSTALL.md
If you prefer manual installation:
git clone https://github.com/github-yjc/context-chronicle.git
cd context-chronicle
pnpm install
pnpm run build
node dist/cli.js setupsetup auto-completes: DB init -> plugin registration -> diagnostics. Done. It protects your context silently in the background.
After setup, use these in your AI coding tool - no CLI needed:
| Command | What it does |
|---|---|
/memory-search <query> |
Search your project memory (keyword, semantic, or hybrid) |
/memory-remember <rule> |
Remember a constraint or decision |
/memory-rules |
List all active constraints |
/memory-status |
Show plugin health and stats |
/memory-graph <query> |
Search the knowledge graph |
/memory-doctor |
Run diagnostic checks |
/memory-logs |
View plugin logs (filter by level, tag, session) |
/memory-settings |
Open the TUI settings panel |
Tip: Your agent already has access to all 6 unified MCP tools under the hood. Slash commands are convenient shortcuts for the most common operations.
Fetch the full guide and follow it step by step:
curl -fsSL https://raw.githubusercontent.com/github-yjc/context-chronicle/main/docs/INSTALL.mdThe guide covers: prerequisites, DB init, plugin registration, MCP configuration, feature toggle management, embedding setup, firewall settings, compaction strategy, RAG indexing, uninstall & recovery.
Context Chronicle is an offline memory system for OpenCode's TUI mode. OpenCode TUI means the terminal UI shipped by OpenCode, not a separate product. It runs silently in the background - recording every prompt, every tool call, every constraint, every decision. Need to find "what was said before"? Full-text search finds it instantly. Context getting too long? Auto-compress and re-inject key requirements. AI trying to fake completion? Stop Gate blocks it.
| Requirement | Version / Scope |
|---|---|
| OpenCode TUI | v1.17.x; the plugin loads inside the OpenCode process and uses Bun runtime |
| Node.js | >=18 for development, build, and test; .nvmrc specifies Node 22 for contributors |
| Package manager | pnpm@9.0.0, declared by the packageManager field |
| Supported OS | Linux, macOS, Windows; verified by the CI three-platform matrix |
Optional runtime environment variables: OPENAI_API_KEY, KIMI_API_KEY, DEEPSEEK_API_KEY, MINIMAX_API_KEY, COHERE_API_KEY, CUSTOM_EMBEDDING_API_KEY, TENCENT_SECRET_ID, TENCENT_REGION, FIREWALL_MODE, COMPACTION_AUTO, CC_LOG_LEVEL, CC_LOG_RETENTION, CC_LOG_MAX_SIZE_MB, CC_LOG_BUFFER_CAP, CC_COMPACTION_LOCK_TTL_S, XDG_CONFIG_HOME.
Install once. Never think about it again. It just protects you.
| Capability | Description |
|---|---|
| Verifiable Memory | SQLite + FTS5 full-text search - records prompts, tool calls, constraints, decisions |
| Tool Firewall | 15 built-in dangerous patterns + constraint-driven block/warn/allow + word-boundary matching |
| Smart Compaction | TextRank extractive summarization + Shannon entropy + adaptive Ebbinghaus decay - zero critical info loss |
| Stop Gate | 7-dimension checks (tool loops, repeated failures, missed checks) to block fake completion |
| Hybrid Search | FTS5 keyword search + optional vector similarity (29 embedding presets). CJK trigram for Chinese/Japanese/Korean. Result merging + ranking. |
| Knowledge Graph | Entity-relationship model for agents, decisions, files - graph-aware search + SHA-256 dedup |
| Context Bridge | Multi-signal confidence scoring - recovers critical constraints after model switches |
| File Logging | JSON Lines format, daily rotation, 7-day retention - CLI + slash command + TUI access |
| Session Linking | Soft-link multiple sessions for cross-session search (FTS5 + vector + KG) |
| One-Command Setup | node dist/cli.js setup - DB init + plugin reg + diagnostics |
| TUI Settings Panel | Open Ctrl+P -> "Context Chronicle Settings" - interactive panel with bilingual EN/ZH, feature toggles, embedding presets, keyboard navigation |
| Memory Decay System | Context-distance-based exponential decay on constraints. Configurable half-life (7 presets: 30-Infinity turns). Reinforcement/topic-drift factors. Ebbinghaus time-decay for message importance. |
| Subagent Templates | 8 verified templates (RERANK, ENTITY_EXTRACT, CONFLICT_RESOLUTION, RAG_AUDIT, STALE_CONSTRAINT, FACT_CHECK, DECISION_AUDIT, SESSION_SUMMARY). Shared NO_TOOLS_PREAMBLE + THINKING_INSTRUCTION. buildPrompt() runtime assembler. |
| 10-Section Reinjection | Structured context reinjection after compaction: Compaction Summary, Current Work, User Messages, Files & Code, Errors & Fixes, Task Status, Subagent Status, Active Constraints, System Directives, Embedding Status. |
| Memory Retention TUI | 7 half-life presets (Tight -> Never decay), bilingual EN/ZH labels, hot-reload indicators ([>] immediate / [*] restart), keyboard navigation in settings panel. |
| Slash Commands | /memory-search, /memory-remember, /memory-graph - no CLI memorization needed |
After context-chronicle setup, your agent can build a project knowledge graph:
Add entities:
Agent: "Remember that we use React for frontend"
-> memoryManage { action: "entity", entity: { entityType: "decision", name: "React for frontend" } }
Agent: "Record that src/components/Button.tsx is part of the UI layer"
-> memoryManage { action: "entity", entity: { entityType: "project_file", name: "src/components/Button.tsx" } }
Agent: "Link the React decision to Button.tsx"
-> memoryManage { action: "relation", relation: { relationType: "decision_affects", sourceName: "React for frontend", targetName: "src/components/Button.tsx" } }
Search and explore:
Agent: "What decisions affect Button.tsx?"
-> memoryManage { action: "get-entity", entityName: "src/components/Button.tsx", depth: 1 }
-> Returns: { entity, relations: [{ relationType: "decision_affects", ... }], count: 1 }
Agent: "Find everything about React"
-> memorySearch { query: "React", mode: "graph", limit: 5 }
-> Returns: { query: "React", count: 2, results: [...] }
Audit health:
Agent: "How's the knowledge graph doing?"
-> memoryStatus { includeGraph: true }
-> Returns: { entityCount: 42, relationCount: 15, byType: [...], ... }
Tip: CJK queries like
"搜索React"automatically use trigram tokenizer for accurate Chinese search.
| Tool | Description |
|---|---|
memorySearch |
Search memory, knowledge graph, or both. Modes: keyword, semantic, hybrid, graph |
memoryManage |
Add/list constraints, trace decisions, manage KG entities/relations, link/unlink sessions (/memory-remember, /memory-rules) |
memoryStatus |
Plugin health: events, constraints, audits, embedding, KG stats (/memory-status) |
memoryCompact |
Trigger context compaction to free context window |
guardedBash |
Execute shell commands protected by the tool firewall |
memoryHistory |
Firewall logs, model switch history, config reload |
Knowledge Graph operations are exposed through memoryManage actions (entity, relation, get-entity) and memorySearch { mode: "graph" } - no separate graph tools.
Context Chronicle provides hybrid search combining keyword and vector approaches:
- FTS5 Full-Text Search - fast keyword matching across all event and memory content
- Optional Vector Similarity - cosine-similarity via configurable embedding providers (cloud/local)
- CJK Trigram Tokenizer - auto-routed Chinese/Japanese/Korean support
- Result Ranking - rule-based relevance scoring with deduplication
- Graph-Aware Expansion - knowledge graph entities enrich search results
Note: This is a local-first hybrid search system with optional LLM re-ranking and heuristic entity extraction. The vector component requires an embedding provider.
The search index can be audited and maintained via context-chronicle rag audit/clean/backfill.
Context Chronicle writes structured logs to ~/.opencode/context-chronicle/logs/cc-YYYY-MM-DD.log in JSON Lines format. Every plugin event - audits, search queries, firewall blocks, compaction runs - is recorded with a timestamp, severity level, subsystem tag, and session ID.
View logs:
- Slash command:
/memory-logs(returns recent entries with optional--level,--tag,--tailfilters) - CLI:
context-chronicle logs --tail 100 --level error --tag Audit - TUI panel: Storage section ->
[Open Logs]button opens the log directory in your file manager
Automatic management: Daily rotation, 7-day retention, 50MB total size cap. Set CC_LOG_LEVEL=debug for verbose output.
Soft-link multiple sessions for cross-session search and retrieval. When sessions A and B are linked, search queries in A automatically include results from B (FTS5, vector, knowledge graph - all modes).
# Link session B to session A
memoryManage { action: "link-session", sessionId: "B", dbPath: "/path/to/B.sqlite" }
# Search across linked sessions
memorySearch { query: "React decision", crossSession: true }Links are stored in the session_links table (no data migration). Unlinking removes the association without deleting data. Vector search across linked sessions uses parallel SqliteVecBackend instances with RRF result merging. Cycle detection prevents infinite loops from circular links.
29 verified presets (all validated against official docs):
| Category | Count | Providers |
|---|---|---|
| Cloud Providers | 28 | OpenAI, Azure, Voyage, Cohere, Jina, Google, Mistral, Upstage, Alibaba, SiliconFlow, Zhipu, Volcengine, Baidu, Tencent |
| ONNX Local | 1 | Qwen Embed |
For local Ollama or any OpenAI-compatible service, use context-chronicle embedding custom <baseUrl> <model> <dim>. For example: context-chronicle embedding custom http://localhost:11434/v1 nomic-embed-text 768.
AI Client (OpenCode/Cursor/Windsurf)
| MCP JSON-RPC / stdio
v
+----------------------------------+
| Context Chronicle MCP Server |
| 6 unified tools with modular |
| handlers + router (src/mcp/) |
+----------------------------------+
| TUI Settings Panel |
| Ctrl+P palette + route config |
+----------------------------------+
| HybridSearch, Firewall, |
| RollingCompaction, Stop Gate, |
| ContextBridge, Memory Decay, |
| PerfTracker |
+----------------------------------+
| Subagent Templates (8) |
| 10-Section Reinjection |
+----------------------------------+
| SQLite WAL, FTS5, vector index |
| SHA256 integrity chain |
+----------------------------------+
Storage has been split into focused modules: src/storage/events.ts, packets.ts, decisions.ts, kg-store.ts, fts-utils.ts alongside sqlite-backend.ts. The TUI plugin (src/tui/) provides a Ctrl+P-accessible settings panel with bilingual EN/ZH support. The Memory Decay system (src/compaction/decay.ts) implements context-distance-based constraint decay with 7 configurable half-life presets. Subagent templates (src/plugin/subagent-templates.ts) provide 8 verified prompt templates with shared preambles and a runtime assembler. Context reinjection (src/compaction/reinjection.ts) uses a 10-section structured template.
See ARCHITECTURE.md for full details.
git clone https://github.com/github-yjc/context-chronicle.git
cd context-chronicle
pnpm install
pnpm run build
pnpm test # 91 test files, 1273 documented tests| Document | Audience |
|---|---|
| INSTALL.md | LLM Agents - complete installation guide |
| USER_GUIDE.md | Developers - configuration, algorithms, architecture |
| ARCHITECTURE.md | Developers - system design and data flow |
| MCP_TOOLS.md | Developers - 6 unified MCP tools with CJK search |
| TESTING.md | Contributors - fast/full validation paths, suite map |
| CODEBASE_MAP.md | Contributors - subsystem entry points, extension points |
| CONTRIBUTING.md | Contributors - code standards, testing, PR process |
| SECURITY.md | Security - data handling, vulnerability reporting |
| TROUBLESHOOTING.md | Users - common problems and solutions |
| PERFORMANCE.md | All - benchmark data |
| ROADMAP.md | All - future plans |
| CHANGELOG.md | All - version history |
| What | Where |
|---|---|
| SQLite database | ~/.opencode/context-chronicle/db.sqlite |
| Plugin config | ~/.opencode/context-chronicle/config.json |
| Plugin code | Your git clone directory |
Footprint: ~5MB baseline, ~300MB at 100K events (including CJK FTS5 dual tables). WAL files auto-merge on checkpoint. No manual cleanup needed.
node dist/cli.js uninstallRemoves plugin registration from OpenCode config. Database is preserved - reinstall picks up where you left off. Delete ~/.opencode/context-chronicle/ manually if you want a full reset.
Context Chronicle manages agent memory, context compaction, and tool firewall. Installing multiple plugins that do the same thing can cause hook conflicts, duplicate event recording, or context corruption.
Do NOT install alongside any of these:
| Plugin | Why it conflicts |
|---|---|
opencode-supermemory |
Also manages persistent memory across sessions |
opencode-dynamic-context-pruning |
Also manages context window compaction |
claude-mem |
Also hooks Claude Code memory events |
mem0 |
Competing memory layer (hook interference) |
opencode-memory |
Generic memory plugin conflicts |
context-keeper |
Context preservation overlaps |
opencode-mnemosyne |
Competing memory/compaction hooks |
opencode-memoir |
Competing memory persistence |
Run context-chronicle doctor to automatically detect conflicts.
Rule of thumb: One memory/compaction plugin per OpenCode installation. Context Chronicle already includes memory, compaction, firewall, and knowledge graph - you don't need another.
- Cloud embedding providers require API keys and network access
- CJK trigram tables ~2x FTS storage (15-25MB per 100K events)
- Database unencrypted on disk - use filesystem encryption for sensitive projects
- Plugin runs with user's filesystem permissions (no sandboxing)
- Short CJK queries (1-2 characters) use slower LIKE fallback
Apache-2.0 - see LICENSE.