CogZ
Use CogZ as a local MCP server to maintain project memory and provide code-aware context, search, and cognition for AI coding agents.
Create, query, list, update, verify, and reject observations, rules, and knowledge entities.
Run consolidation to promote supported observations and merge duplicates.
Capture lifecycle events for hook-driven context injection, reindexing, and session consolidation.
Search code and knowledge with hybrid lexical/semantic retrieval and graph expansion.
Build scoped, token-budgeted context packs for tasks.
Analyze the code graph for callers, transitive impact, and orphan/dead-code candidates.
Check index/model/DB status and mine recent sessions for observation suggestions.
Integrates with GitHub Copilot as a supported coding agent, enabling it to use CogZ's persistent repository knowledge, contextual retrieval, and code cognition via MCP and lifecycle hooks.
CogZ
Local-first, code-aware engineering cognition for AI coding agents.
CogZ gives a coding agent persistent memory, contextual retrieval, and continuous cognition about a software repository — all running locally on your machine, no cloud services required.
Works with Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot, Devin, and any MCP-compatible agent.
What it looks like
Real output from CogZ running on its own codebase:
$ cogz context --mode task "token budget estimation and context pack compression"
Context pack (mode: task)
Query: token budget estimation and context pack compression
Search mode: hybrid
Sections: 91
Token estimate: 8188
Dropped: 6 sections over token budget
---
## 1. [rule] New expansion channels: emit early, filter before seen-mark, sort deterministically, never displace directs (relevance: 0.5148)
Conventions proven across the sibling and co-change channels:
1. Emit before the generic expansion loops — candidates emitted
later get claimed-and-floored by graph traversal …
2. Apply entity-type/test filters BEFORE `seen.insert` …
…
## 2. [rule] cfg-gated code must be typechecked per-target before release (relevance: 0.4690)
Code behind #[cfg(unix)]/cfg(target_os = ...) is invisible to host
builds, tests, and clippy — a compile error in a cfg'd branch ships
silently until a real target build sees it. The v0.5.0 Windows leg
failure is the canonical example.
## 3. [rule] Degradation must be loud, never silent (relevance: 0.3680)
Every degraded or failed code path must surface a signal …
## 4. [identity] CogZ (relevance: —)
Project: CogZ
## 5. [file] assemble.rs (relevance: 0.6993)
//! Context pack assembly — the tiered-push pipeline.
//! Tier 0 (baseline: identity + top rules) always ships for task and
//! escalation packs …
… 86 more sections …That's not a text chunk from a vector search. The pack leads with validated rules — one learned from a release failure on this very project — plus the identity baseline and the actual source file, all ranked, traceable, and budgeted.
This repository already contains real dogfooding knowledge — CogZ has been used on its own codebase throughout development. You can clone it, install CogZ, and try the commands above against it directly.
Related MCP server: Serena
What it does
CogZ maintains a project-specific knowledge layer that connects what an agent learns to the code it is working with.
Memory
CogZ stores three kinds of project knowledge:
Observations — things an agent has learned or noticed. Raw, unvalidated experience: bugs found, decisions made, patterns noticed.
Rules — validated knowledge that should influence future work. Coding standards, design decisions, confirmed patterns.
Knowledge — structured information about the codebase. Architecture explanations, module responsibilities, trade-off rationale.
These are stored as Markdown files with YAML frontmatter, linked to each other and to code entities in the repository. The files are the canonical source of truth — SQLite is a derived index, disposable and rebuildable. Your knowledge is portable, version-controlled, and editable by hand.
Context
Instead of giving an agent everything it knows, CogZ builds scoped context packs for the current situation. A context pack combines relevant rules, observations, knowledge, and code structures — ranked by relevance, traceable through the code graph, and limited by a token budget so the agent gets what matters for the task rather than the entire project history.
Cognition
CogZ periodically consolidates what has been learned: deduplicates entries, detects contradictions, promotes well-supported observations to rules, merges superseded entries, and flags knowledge as stale when the code it references changes.
Quick start
Linux / macOS / Windows (Git Bash):
# Install
curl -fsSL https://raw.githubusercontent.com/balaianu/CogZ/master/install.sh | bash
# Initialize in a repo (add --configure auto to wire MCP + hooks for detected agents)
cd ~/your-project
cogz init
# Index (downloads models on first run, or use --no-download for FTS-only)
cogz index
# Verify it's working — entity counts, model status, DB stats
cogz statusWindows (PowerShell):
# Install
irm https://raw.githubusercontent.com/balaianu/CogZ/master/install.ps1 | iex
# Initialize in a repo
cd your-project
cogz init
cogz indexSee Getting Started for the mental model and a complete walkthrough.
MCP integration
CogZ runs as a stateless MCP server over stdio. Every tool call specifies which repo it targets via a required repo parameter — no Roots, no session state, no fallbacks.
{
"mcpServers": {
"cogz": {
"command": "cogz",
"args": ["mcp-stdio"]
}
}
}The server exposes 15 tools: create_entity, update_knowledge, verify_knowledge, reject_entity, query_entities, search, get_context, get_status, list_entities, consolidate, capture_event, get_callers, get_impact, find_orphans, suggest_observations.
See MCP Tools for full parameter reference and example responses. See Agent Setup for per-agent config files, hook formats, and verified capability notes for all six supported agents — or just run cogz configure auto.
Hook integration
Hooks capture lifecycle events and inject context packs into agent sessions. CogZ's binary is the hook handler — no wrapper scripts needed.
{
"hooks": {
"SessionStart": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "cogz capture-event session_start --hook-json",
"timeout": 15
}]
}]
}
}See Hooks for all 7 event types and per-agent wiring guides.
CLI commands
Normal operation is automatic: hooks fire on lifecycle events, the agent drives CogZ through MCP. The CLI is not needed for day-to-day use — it's available for setup, manual exploration, and automation if you want or need it.
Command | Description |
| Initialize |
| Write agent MCP + hook config ( |
| Sync files to DB + index source code |
| Incremental reindex (changed files only) |
| Hybrid FTS + vector + graph search |
| Assemble context pack |
| DB stats, entity counts, model status |
| Run promotion and merge |
| List mined observation candidates |
| Re-stamp a drifted entity's provenance |
| Mark an entity rejected ( |
| Capture lifecycle event from hooks |
| Model management |
| Health check, policy violations, usage metrics |
| Self-update from GitHub releases |
| Drop DB (optionally purge observations) |
| Run MCP server over stdio |
See CLI Reference for all flags and options.
Requirements
Minimum (FTS-only mode)
Resource | Requirement |
RAM | 256 MB free |
Disk | 50 MB (binary + DB, no models) |
CPU | any x86_64 or ARM64 |
Works without ONNX Runtime or model downloads. All hooks, FTS search, context packs, consolidation, doctor, and prune are functional. Vector search, embedding-based dedup, and contradiction detection are not available.
Recommended (hybrid search mode)
Resource | Requirement |
RAM | 2 GB free |
Disk | 550 MB (binary + ONNX Runtime + 3 models + DB) |
CPU | any x86_64 or ARM64, 4+ cores speeds up batch embedding |
Full functionality including vector search, semantic dedup, and NLI contradiction detection. Models auto-download on first use and auto-unload after 5 min idle (RAM drops back to ~11 MB). See Evaluations for the full resource consumption profile.
Benchmarks
CogZ ships a reproducible suite (benchmark/) run on pinned public corpora — httpx, cobra, clap, each injected with memory seeds mined from its real git history — plus this repository's own .cogz corpus. Seeded ground truth:
Corpus | P@5 | MRR | Recall@20 |
cobra | 0.200 | 0.523 | 0.867 |
httpx | 0.160 | 0.364 | 0.867 |
clap | 0.169 | 0.259 | 0.789 |
Channel ablations on commit queries: removing graph expansion costs 3–15pt recall@20; FTS-only mode is competitive on commit-intent queries (0.34–0.47 R@20 vs hybrid's 0.31–0.47) — the vector channel's lift concentrates on semantic queries while expansion dilutes under the row cap (tracked as the top ranking issue). Context packs keep 0.49–0.89 expected-entity recall at the default 8K budget. Reruns are byte-identical. Full methodology, per-phase numbers, and the raw artifacts: benchmark/README.md.
What using it buys (measured): in a 14-task agent replay, the seeded-knowledge arm finished ~2x faster than bare (871s vs 1748s average) and completed more runs (14/14 vs 10/14) at equal correctness. Consolidation machinery is precise: dedup precision/recall 1.0, NLI contradiction detection 4/4 with zero false alarms, drift marking exact.
Honest limits: top-5 precision is weak on mixed corpora (P@5 <= 0.20; code entities outrank knowledge at the top of the ranking), commit-intent queries reach 0.31–0.53 recall@20, adjacent-domain negative queries still leak confident hits (silence-gate clean rate 0.47–0.73 across corpora), and at n=14 tasks there is no measurable task-correctness lift yet.
Architecture
Single Rust binary — no runtime dependencies except optional ONNX models for vector search.
Files are canonical — all entities are Markdown files. The SQLite DB is a derived index, disposable and rebuildable.
Code-aware — tree-sitter indexes source code as first-class graph entities. Supported languages: Rust, Python, Go, JavaScript, TypeScript, TSX, Bash.
Graceful degradation — works without ML models in FTS-only mode.
Local-first — no cloud, no telemetry, no accounts. The only network access is optional model downloads.
See Architecture for the full system design.
Compatibility
Platform | Support | Embeddings | FTS-only | Install |
Linux x86_64 | Full | Auto-download | Yes |
|
Linux aarch64 | Full | Auto-download | Yes |
|
macOS arm64 (Apple Silicon) | Full | Auto-download | Yes |
|
macOS x86_64 (Intel) | Not supported | — | — | — |
Windows x86_64 | Full | Auto-download | Yes |
|
macOS Intel is not supported because Microsoft dropped ONNX Runtime macOS Intel binaries after v1.22. Intel Mac users can run the arm64 binary under Rosetta 2 (with a compatible ORT build) or use cargo install cogz for FTS-only mode.
Windows 10+ is required (bsdtar is bundled since build 17063, needed for ONNX Runtime auto-extraction).
Cross-platform team collaboration is supported: code entity UUIDs use forward-slash path normalization so the same source file produces the same entity ID on all platforms.
Documentation
User guides:
Getting Started — mental model and walkthrough
Configuration — full
config.tomlreferenceCLI Reference — every command and flag
Integration:
MCP Tools — all 15 tool signatures and response shapes
Hooks — lifecycle events and output format
Agent Setup — all six agents + generic MCP, with per-agent effect coverage
Design:
Architecture — system overview and module map
Entity Model — entity types, frontmatter, state machine
Search — hybrid FTS + vector, RRF, graph expansion
Consolidation — dedup, contradiction, promotion, merge
Degradation — FTS-only mode and fallback behavior
Contributing:
Building — build, release, cross-compile
Testing — test categories and mock models
Conventions — code patterns and invariants
Dependencies — pinned versions and supply-chain policy
Schema — DB schema and migrations
Contributing
See CONTRIBUTING.md for build, test, and PR guidelines.
License
MIT — see LICENSE.
Support
If you find this tool useful, consider buying me a coffee:
Available Tools
15 toolscapture_eventA
Capture a lifecycle event — called by hook scripts, not intended for direct use. session_start/prompt_submit return context packs; file_save reindexes and may return rules governing the edited file; session_end runs consolidation.
Inputs: repo (required), event_type (required), prompt, file_path, +2 more.
consolidateA
Run deferred consolidation — promote supported observations to rules, merge confirmed duplicates. Housekeeping, not a write path; dedup and contradiction checks already run on every insert.
Inputs: repo (required), dry_run.
create_entityA
Create a knowledge-layer entity. entity_type picks the lifecycle, not the topic — ask what the entry IS: 'observation' = something that happened (bug found, surprising behavior, decision noticed) — raw, append-only, unvalidated; consolidation promotes the good ones to rules. 'rule' = a verified directive agents must always follow (conventions, constraints) — pushed into every context pack; change via supersede, not edits. 'knowledge' = a curated reference doc (architecture, gotchas, design decisions) — the only editable type (update_knowledge). Requires: content always; title+category for knowledge.
Inputs: repo (required), content (required), entity_type (required), tags, +6 more.
find_orphansA
Find code entities with no incoming calls/imports/extends edges — dead-code candidates. Use during cleanup audits. Entry points like main() surface by design; test code is excluded.
Inputs: repo (required), limit, entity_type.
get_callersA
Find entities that call this function — answers 'who calls X?' with resolved call edges, not text matches. Use instead of grepping for the name when you need real callers (not comments, strings, or same-named functions).
Inputs: repo (required), entity_id (required), limit.
get_contextA
Assemble a context pack — a scoped, ranked bundle of orientation, rules, relevant code, and knowledge for a task query. Use at the start of substantial work on a topic instead of reading files broadly — narrower than a session-start pack, broader than a single search.
Inputs: repo (required), mode, query, record, +2 more.
get_impactA
Transitive dependents of an entity — what breaks or needs updating when it changes (incoming calls/imports/extends up to max_depth hops), plus knowledge that references it. Use before renaming, deleting, or changing a signature.
Inputs: repo (required), entity_id (required), limit, max_depth.
get_statusA
CogZ system status — entity counts, DB stats, model availability, staleness. Use to check the index is fresh and retrieval is at full capability before relying on it.
Inputs: repo (required).
list_entitiesA
List IDs and titles for all entities of a type. Use to enumerate a type or resolve an entity_id for get_callers/get_impact — returns no content; for substance use search or query_* tools.
Inputs: repo (required), entity_type (required), status.
query_entitiesA
Browse knowledge-layer entities of one type — 'observation' (raw findings, recency order), 'rule' (verified directives, confidence order), or 'knowledge' (curated docs). Use to enumerate what exists before writing (avoid duplicates) or to review a type — for ranked retrieval on a question use search; for code entities use list_entities or search.
Inputs: repo (required), entity_type (required), tags, limit, +3 more.
reject_entityA
Reject a knowledge-layer entity — writes status: rejected (and an optional rejected_reason) into its canonical file, then syncs so the status lattice validates the transition. Only active entities can be rejected; verify a stale one first if it must be ruled wrong. This is a verdict, not an edit — do not use it for content changes. Rejected entities stay on record: retrieval filters them out, and dedup can warn when a matching claim resurfaces.
Inputs: id (required), repo (required), reason.
searchB
Ranked search across all entities — code (functions, files, classes) plus rules, observations, and knowledge — using hybrid lexical + semantic retrieval with graph expansion. Use when you know the concept but not the exact name, or want related entities surfaced automatically. For exact identifier/text matches, grep is faster and equally precise.
Inputs: repo (required), query (required), limit, before, +5 more.
suggest_observationsA
Mine recent session usage for observation candidates — zero-hit packs followed by edits, hot files, error→fix sequences. Use at natural stopping points to capture what the session learned; confirm salient suggestions via create_entity.
Inputs: repo (required), days, limit.
update_knowledgeA
Update an existing knowledge entry's content — use to correct or extend documentation when facts change. The only entity type allowing in-place edits; observations and rules are append-only.
Inputs: id (required), repo (required), content (required), tags, +3 more.
verify_knowledgeA
Re-verify a knowledge entity against its referenced code — re-stamps verified_against provenance, clears drift annotations, and reactivates the entity if it was stale. Use after reading drift-flagged or stale knowledge and confirming it is still accurate — not for changing content (use update_knowledge instead).
Inputs: id (required), repo (required), allow_dead_refs.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 15 tools
Most tools target distinct operations such as status checks, search, context assembly, knowledge lifecycle management, and code-graph analysis. The main overlap is between list_entities and query_entities, and to a lesser extent search/query_entities, but the descriptions largely clarify when each should be used.
Names are consistently snake_case and predominantly follow a verb_noun pattern (get_status, list_entities, create_entity, get_callers, etc.). A few deviations are single-verb or less patterned names like search and consolidate, but the overall convention is predictable.
At 15 tools, the set is well-scoped for a knowledge/code-graph server covering status, retrieval, lifecycle management, and graph queries. Each tool maps to a meaningful operation, including hook-driven and housekeeping tools, without excessive surface area.
The server covers core knowledge lifecycle (create, update, reject, verify, consolidate), retrieval (search, query_entities, get_context), and code-graph analysis (get_callers, get_impact, find_orphans). Minor gaps exist, such as no direct get_entity-by-id for full content and no outgoing dependency/callee query, but agents can work around them via search and existing browse tools.
Maintenance
Related MCP Connectors
Persistent engineering memory designed to follow developers across coding agents.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Persistent memory and knowledge graphs for AI agents. Hybrid search, context checkpoints, and more.
Persistent memory, inline redaction, per-agent access, and code localization for AI agents.
Related MCP Servers
- AlicenseAqualityBmaintenanceBasic Memory is a knowledge management system that allows you to build a persistent semantic graph from conversations with AI assistants. All knowledge is stored in standard Markdown files on your computer, giving you full control and ownership of your data. Integrates directly with Obsidan.md21210,713 PyPI4,572AGPL 3.0
- AlicenseAqualityDmaintenanceA coding agent toolkit that provides IDE-like semantic code retrieval and editing tools, enabling LLMs to efficiently navigate and modify codebases at the symbol level rather than working with entire files.29MIT
- AlicenseNot gradedqualityDmaintenanceLocal-first memory, pipelines, learning, feedback, and safe code tools for AI coding agents.MIT
- FlicenseAqualityDmaintenanceA lightweight, local memory server for AI coding assistants that stores durable knowledge (decisions, facts, gotchas) in a tree structure, enabling persistent context across sessions with efficient retrieval via summaries and FTS5 search.94-