codebase-context 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +358 -282
  3. package/dist/analyzers/angular/index.d.ts.map +1 -1
  4. package/dist/analyzers/angular/index.js +7 -2
  5. package/dist/analyzers/angular/index.js.map +1 -1
  6. package/dist/analyzers/generic/index.d.ts +1 -0
  7. package/dist/analyzers/generic/index.d.ts.map +1 -1
  8. package/dist/analyzers/generic/index.js +89 -10
  9. package/dist/analyzers/generic/index.js.map +1 -1
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.d.ts.map +1 -1
  12. package/dist/cli.js +240 -1
  13. package/dist/cli.js.map +1 -1
  14. package/dist/constants/codebase-context.d.ts +13 -0
  15. package/dist/constants/codebase-context.d.ts.map +1 -1
  16. package/dist/constants/codebase-context.js +13 -0
  17. package/dist/constants/codebase-context.js.map +1 -1
  18. package/dist/core/index-meta.d.ts +24 -0
  19. package/dist/core/index-meta.d.ts.map +1 -0
  20. package/dist/core/index-meta.js +204 -0
  21. package/dist/core/index-meta.js.map +1 -0
  22. package/dist/core/indexer.d.ts.map +1 -1
  23. package/dist/core/indexer.js +253 -14
  24. package/dist/core/indexer.js.map +1 -1
  25. package/dist/core/search.d.ts +1 -0
  26. package/dist/core/search.d.ts.map +1 -1
  27. package/dist/core/search.js +60 -5
  28. package/dist/core/search.js.map +1 -1
  29. package/dist/core/symbol-references.d.ts +21 -0
  30. package/dist/core/symbol-references.d.ts.map +1 -0
  31. package/dist/core/symbol-references.js +91 -0
  32. package/dist/core/symbol-references.js.map +1 -0
  33. package/dist/eval/harness.d.ts +5 -0
  34. package/dist/eval/harness.d.ts.map +1 -0
  35. package/dist/eval/harness.js +153 -0
  36. package/dist/eval/harness.js.map +1 -0
  37. package/dist/eval/types.d.ts +59 -0
  38. package/dist/eval/types.d.ts.map +1 -0
  39. package/dist/eval/types.js +2 -0
  40. package/dist/eval/types.js.map +1 -0
  41. package/dist/grammars/manifest.d.ts +26 -0
  42. package/dist/grammars/manifest.d.ts.map +1 -0
  43. package/dist/grammars/manifest.js +63 -0
  44. package/dist/grammars/manifest.js.map +1 -0
  45. package/dist/index.d.ts +12 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +136 -1298
  48. package/dist/index.js.map +1 -1
  49. package/dist/preflight/evidence-lock.d.ts +6 -0
  50. package/dist/preflight/evidence-lock.d.ts.map +1 -1
  51. package/dist/preflight/evidence-lock.js +33 -1
  52. package/dist/preflight/evidence-lock.js.map +1 -1
  53. package/dist/storage/lancedb.d.ts +9 -1
  54. package/dist/storage/lancedb.d.ts.map +1 -1
  55. package/dist/storage/lancedb.js +26 -8
  56. package/dist/storage/lancedb.js.map +1 -1
  57. package/dist/tools/detect-circular-dependencies.d.ts +5 -0
  58. package/dist/tools/detect-circular-dependencies.d.ts.map +1 -0
  59. package/dist/tools/detect-circular-dependencies.js +117 -0
  60. package/dist/tools/detect-circular-dependencies.js.map +1 -0
  61. package/dist/tools/get-codebase-metadata.d.ts +5 -0
  62. package/dist/tools/get-codebase-metadata.d.ts.map +1 -0
  63. package/dist/tools/get-codebase-metadata.js +53 -0
  64. package/dist/tools/get-codebase-metadata.js.map +1 -0
  65. package/dist/tools/get-component-usage.d.ts +5 -0
  66. package/dist/tools/get-component-usage.d.ts.map +1 -0
  67. package/dist/tools/get-component-usage.js +83 -0
  68. package/dist/tools/get-component-usage.js.map +1 -0
  69. package/dist/tools/get-indexing-status.d.ts +5 -0
  70. package/dist/tools/get-indexing-status.d.ts.map +1 -0
  71. package/dist/tools/get-indexing-status.js +44 -0
  72. package/dist/tools/get-indexing-status.js.map +1 -0
  73. package/dist/tools/get-memory.d.ts +5 -0
  74. package/dist/tools/get-memory.d.ts.map +1 -0
  75. package/dist/tools/get-memory.js +89 -0
  76. package/dist/tools/get-memory.js.map +1 -0
  77. package/dist/tools/get-style-guide.d.ts +5 -0
  78. package/dist/tools/get-style-guide.d.ts.map +1 -0
  79. package/dist/tools/get-style-guide.js +151 -0
  80. package/dist/tools/get-style-guide.js.map +1 -0
  81. package/dist/tools/get-symbol-references.d.ts +5 -0
  82. package/dist/tools/get-symbol-references.d.ts.map +1 -0
  83. package/dist/tools/get-symbol-references.js +70 -0
  84. package/dist/tools/get-symbol-references.js.map +1 -0
  85. package/dist/tools/get-team-patterns.d.ts +5 -0
  86. package/dist/tools/get-team-patterns.d.ts.map +1 -0
  87. package/dist/tools/get-team-patterns.js +131 -0
  88. package/dist/tools/get-team-patterns.js.map +1 -0
  89. package/dist/tools/index.d.ts +6 -0
  90. package/dist/tools/index.d.ts.map +1 -0
  91. package/dist/tools/index.js +41 -0
  92. package/dist/tools/index.js.map +1 -0
  93. package/dist/tools/refresh-index.d.ts +5 -0
  94. package/dist/tools/refresh-index.d.ts.map +1 -0
  95. package/dist/tools/refresh-index.js +40 -0
  96. package/dist/tools/refresh-index.js.map +1 -0
  97. package/dist/tools/remember.d.ts +5 -0
  98. package/dist/tools/remember.d.ts.map +1 -0
  99. package/dist/tools/remember.js +101 -0
  100. package/dist/tools/remember.js.map +1 -0
  101. package/dist/tools/search-codebase.d.ts +5 -0
  102. package/dist/tools/search-codebase.d.ts.map +1 -0
  103. package/dist/tools/search-codebase.js +638 -0
  104. package/dist/tools/search-codebase.js.map +1 -0
  105. package/dist/tools/types.d.ts +31 -0
  106. package/dist/tools/types.d.ts.map +1 -0
  107. package/dist/tools/types.js +2 -0
  108. package/dist/tools/types.js.map +1 -0
  109. package/dist/types/index.d.ts +6 -0
  110. package/dist/types/index.d.ts.map +1 -1
  111. package/dist/utils/ast-chunker.d.ts +71 -0
  112. package/dist/utils/ast-chunker.d.ts.map +1 -0
  113. package/dist/utils/ast-chunker.js +453 -0
  114. package/dist/utils/ast-chunker.js.map +1 -0
  115. package/dist/utils/chunking.d.ts.map +1 -1
  116. package/dist/utils/chunking.js +10 -3
  117. package/dist/utils/chunking.js.map +1 -1
  118. package/dist/utils/language-detection.d.ts.map +1 -1
  119. package/dist/utils/language-detection.js +20 -0
  120. package/dist/utils/language-detection.js.map +1 -1
  121. package/dist/utils/tree-sitter.d.ts +17 -0
  122. package/dist/utils/tree-sitter.d.ts.map +1 -0
  123. package/dist/utils/tree-sitter.js +311 -0
  124. package/dist/utils/tree-sitter.js.map +1 -0
  125. package/docs/capabilities.md +169 -92
  126. package/grammars/.gitkeep +0 -0
  127. package/grammars/tree-sitter-c.wasm +0 -0
  128. package/grammars/tree-sitter-c_sharp.wasm +0 -0
  129. package/grammars/tree-sitter-cpp.wasm +0 -0
  130. package/grammars/tree-sitter-go.wasm +0 -0
  131. package/grammars/tree-sitter-java.wasm +0 -0
  132. package/grammars/tree-sitter-javascript.wasm +0 -0
  133. package/grammars/tree-sitter-python.wasm +0 -0
  134. package/grammars/tree-sitter-rust.wasm +0 -0
  135. package/grammars/tree-sitter-tsx.wasm +0 -0
  136. package/grammars/tree-sitter-typescript.wasm +0 -0
  137. package/package.json +151 -157
package/README.md CHANGED
@@ -1,282 +1,358 @@
1
- # codebase-context
2
-
3
- ## Local-first second brain for AI Agents working on your codebase
4
-
5
- [![npm version](https://img.shields.io/npm/v/codebase-context)](https://www.npmjs.com/package/codebase-context) [![license](https://img.shields.io/npm/l/codebase-context)](./LICENSE) [![node](https://img.shields.io/node/v/codebase-context)](./package.json)
6
-
7
- You're tired of AI agents writing code that 'just works' but fits like a square peg in a round hole - not your conventions, not your architecture, not your repo. Even with well-curated instructions. You correct the agent, it doesn't remember. Next session, same mistakes.
8
-
9
- This MCP gives agents _just enough_ context so they match _how_ your team codes, know _why_, and _remember_ every correction.
10
-
11
- Here's what codebase-context does:
12
-
13
- **Finds the right context** - Search that doesn't just return code. Each result comes back with analyzed and quantified coding patterns and conventions, related team memories, file relationships, and quality indicators. It knows whether you're looking for a specific file, a concept, or how things wire together - and filters out the noise (test files, configs, old utilities) before the agent sees them. The agent gets curated context, not raw hits.
14
-
15
- **Knows your conventions** - Detected from your code and git history, not only from rules you wrote. Seeks team consensus and direction by adoption percentages and trends (rising/declining), golden files. Tells the difference between code that's _common_ and code that's _current_ - what patterns the team is moving toward and what's being left behind.
16
-
17
- **Remembers across sessions** - Decisions, failures, workarounds that look wrong but exist for a reason - the battle scars that aren't in the comments. Recorded once, surfaced automatically so the agent doesn't "clean up" something you spent a week getting right. Conventional git commits (`refactor:`, `migrate:`, `fix:`) auto-extract into memory with zero effort. Stale memories decay and get flagged instead of blindly trusted.
18
-
19
- **Checks before editing** - A preflight card with risk level, patterns to use and avoid, failure warnings, and a `readyToEdit` evidence check. Catches the "confidently wrong" problem: when code, team memories, and patterns contradict each other, it tells the agent to ask instead of guess. If evidence is thin or contradictory, it says so.
20
-
21
- One tool call returns all of it. Local-first - your code never leaves your machine.
22
-
23
- <!-- TODO: Add demo GIF: search_codebase("How does this app attach the auth token to outgoing API calls?") → AuthInterceptor top result + preflight + agent proceeds or asks -->
24
- <!-- ![Demo](./docs/assets/demo.gif) -->
25
-
26
- ## Quick Start
27
-
28
- Add it to the configuration of your AI Agent of preference:
29
-
30
- ### Claude Code
31
-
32
- ```bash
33
- claude mcp add codebase-context -- npx -y codebase-context /path/to/your/project
34
- ```
35
-
36
- ### Claude Desktop
37
-
38
- Add to `claude_desktop_config.json`:
39
-
40
- ```json
41
- {
42
- "mcpServers": {
43
- "codebase-context": {
44
- "command": "npx",
45
- "args": ["-y", "codebase-context", "/path/to/your/project"]
46
- }
47
- }
48
- }
49
- ```
50
-
51
- ### VS Code (Copilot)
52
-
53
- Add `.vscode/mcp.json` to your project root:
54
-
55
- ```json
56
- {
57
- "servers": {
58
- "codebase-context": {
59
- "command": "npx",
60
- "args": ["-y", "codebase-context", "/path/to/your/project"] // Or "${workspaceFolder}"if your workspace is one project only
61
- }
62
- }
63
- }
64
- ```
65
-
66
- ### Cursor
67
-
68
- Add to `.cursor/mcp.json` in your project:
69
-
70
- ```json
71
- {
72
- "mcpServers": {
73
- "codebase-context": {
74
- "command": "npx",
75
- "args": ["-y", "codebase-context", "/path/to/your/project"]
76
- }
77
- }
78
- }
79
- ```
80
-
81
- ### Windsurf
82
-
83
- Open Settings > MCP and add:
84
-
85
- ```json
86
- {
87
- "mcpServers": {
88
- "codebase-context": {
89
- "command": "npx",
90
- "args": ["-y", "codebase-context", "/path/to/your/project"]
91
- }
92
- }
93
- }
94
- ```
95
-
96
- ## Codex
97
-
98
- Run codex mcp add codebase-context npx -y codebase-context "/path/to/your/project"
99
-
100
- ## What It Actually Does
101
-
102
- Other tools help AI find code. This one helps AI make the right decisions - by knowing what your team does, tracking where codebases are heading, and warning before mistakes happen.
103
-
104
- ### The Difference
105
-
106
- | Without codebase-context | With codebase-context |
107
- | ------------------------------------------------------- | --------------------------------------------------- |
108
- | Generates code using whatever matches or "sounds" right | Generates code following your team conventions |
109
- | Copies any example that fits | Follows your best implementations (golden files) |
110
- | Repeats mistakes you already corrected | Surfaces failure memories right before trying again |
111
- | You re-explain the same things every session | Remembers conventions and decisions automatically |
112
- | Edits confidently even when context is weak | Flags high-risk changes when evidence is thin |
113
- | Sees what the current code does and assumes | Sees how your code has evolved and why |
114
-
115
- ### The Search Tool (`search_codebase`)
116
-
117
- This is where it all comes together. One call returns:
118
-
119
- - **Code results** with `file` (path + line range), `summary`, `score`
120
- - **Type** per result: compact `componentType:layer` (e.g., `service:data`) — helps agents orient
121
- - **Pattern signals** per result: `trend` (Rising/Declining — Stable is omitted) and `patternWarning` when using legacy code
122
- - **Relationships** per result: `importedByCount` and `hasTests` (condensed)
123
- - **Related memories**: up to 3 team decisions, gotchas, and failures matched to the query
124
- - **Search quality**: `ok` or `low_confidence` with confidence score and `hint` when low
125
- - **Preflight**: `ready` (boolean) + `reason` when evidence is thin. Pass `intent="edit"` to get the full preflight card. If search quality is low, `ready` is always `false`.
126
-
127
- Snippets are opt-in (`includeSnippets: true`). Default output is lean if the agent wants code, it calls `read_file`.
128
-
129
- ```json
130
- {
131
- "searchQuality": { "status": "ok", "confidence": 0.72 },
132
- "preflight": { "ready": true },
133
- "results": [
134
- {
135
- "file": "src/auth/auth.interceptor.ts:1-20",
136
- "summary": "HTTP interceptor that attaches auth token to outgoing requests",
137
- "score": 0.72,
138
- "type": "service:core",
139
- "trend": "Rising",
140
- "relationships": { "importedByCount": 4, "hasTests": true }
141
- }
142
- ],
143
- "relatedMemories": ["Always use HttpInterceptorFn (0.97)"]
144
- }
145
- ```
146
-
147
- Lean enough to fit on one screen. If search quality is low, preflight blocks edits instead of faking confidence.
148
-
149
- ### Patterns & Conventions (`get_team_patterns`)
150
-
151
- Detects what your team actually does by analyzing the codebase:
152
-
153
- - Adoption percentages for dependency injection, state management, testing, libraries
154
- - Patterns/conventions trend direction (Rising / Stable / Declining) based on git recency
155
- - Golden files - your best implementations ranked by modern pattern density
156
- - Conflicts - when the team hasn't converged (both approaches above 20% adoption)
157
-
158
- ### Team Memory (`remember` + `get_memory`)
159
-
160
- Record a decision once. It surfaces automatically in search results and preflight cards from then on. **Your git commits also become memories** - conventional commits like `refactor:`, `migrate:`, `fix:`, `revert:` from the last 90 days are auto-extracted during indexing.
161
-
162
- - **Types**: conventions (style rules), decisions (architecture choices), gotchas (things that break), failures (we tried X, it broke because Y)
163
- - **Confidence decay**: decisions age over 180 days, gotchas and failures over 90 days. Stale memories get flagged instead of blindly trusted.
164
- - **Zero-config git extraction**: runs automatically during `refresh_index`. No setup, no manual work.
165
-
166
- ### All Tools
167
-
168
- | Tool | What it does |
169
- | ------------------------------ | -------------------------------------------------------------------------------- |
170
- | `search_codebase` | Hybrid search with enrichment + preflight. Pass `intent="edit"` for edit readiness check. |
171
- | `get_team_patterns` | Pattern frequencies, golden files, conflict detection |
172
- | `get_component_usage` | "Find Usages" - where a library or component is imported |
173
- | `remember` | Record a convention, decision, gotcha, or failure |
174
- | `get_memory` | Query team memory with confidence decay scoring |
175
- | `get_codebase_metadata` | Project structure, frameworks, dependencies |
176
- | `get_style_guide` | Style guide rules for the current project |
177
- | `detect_circular_dependencies` | Import cycles between files |
178
- | `refresh_index` | Re-index (full or incremental) + extract git memories |
179
- | `get_indexing_status` | Progress and stats for the current index |
180
-
181
- ## How the Search Works
182
-
183
- The retrieval pipeline is designed around one goal: give the agent the right context, not just any file that matches.
184
-
185
- - **Intent classification** - knows whether "AuthService" is a name lookup or "how does auth work" is conceptual. Adjusts keyword/semantic weights accordingly.
186
- - **Hybrid fusion (RRF)** - combines keyword and semantic search using Reciprocal Rank Fusion instead of brittle score averaging.
187
- - **Query expansion** - conceptual queries automatically expand with domain-relevant terms (auth login, token, session, guard).
188
- - **Contamination control** - test files are filtered/demoted for non-test queries.
189
- - **Import centrality** - files that are imported more often rank higher.
190
- - **Cross-encoder reranking** - a stage-2 reranker triggers only when top scores are ambiguous. CPU-only, bounded to top-K.
191
- - **Incremental indexing** - only re-indexes files that changed since last run (SHA-256 manifest diffing).
192
- - **Auto-heal** - if the index corrupts, search triggers a full re-index automatically.
193
-
194
- ## Language Support
195
-
196
- Over **30+ languages** are supported: TypeScript, JavaScript, Python, Java, Kotlin, C/C++, C#, Go, Rust, PHP, Ruby, Swift, Scala, Shell, and common config/markup formats.
197
- However right now only **Angular** has a specific analyzer for enriched context (signals, standalone components, control flow, DI patterns).
198
- If you need enriched context from any language or framework, please file an issue - or even better, contribute with a new analyzer
199
-
200
- Structured filters available: `framework`, `language`, `componentType`, `layer` (presentation, business, data, state, core, shared).
201
-
202
- ## Configuration
203
-
204
- | Variable | Default | Description |
205
- | ------------------------ | -------------- | --------------------------------------------------------- |
206
- | `EMBEDDING_PROVIDER` | `transformers` | `openai` (fast, cloud) or `transformers` (local, private) |
207
- | `OPENAI_API_KEY` | - | Required only if using `openai` provider |
208
- | `CODEBASE_ROOT` | - | Project root (CLI arg takes precedence) |
209
- | `CODEBASE_CONTEXT_DEBUG` | - | Set to `1` for verbose logging |
210
-
211
- ## Performance
212
-
213
- - **First indexing**: 2-5 minutes for ~30k files (embedding computation).
214
- - **Subsequent queries**: milliseconds from cache.
215
- - **Incremental updates**: `refresh_index` with `incrementalOnly: true` processes only changed files (SHA-256 manifest diffing).
216
-
217
- ## File Structure
218
-
219
- ```
220
- .codebase-context/
221
- memory.json # Team knowledge (should be persisted in git)
222
- intelligence.json # Pattern analysis (generated)
223
- index.json # Keyword index (generated)
224
- index/ # Vector database (generated)
225
- ```
226
-
227
- **Recommended `.gitignore`:**
228
-
229
- ```gitignore
230
- # Codebase Context - ignore generated files, keep memory
231
- .codebase-context/*
232
- !.codebase-context/memory.json
233
- ```
234
-
235
- ## CLI Access (Vendor-Neutral)
236
-
237
- You can manage team memory directly from the terminal without any AI agent:
238
-
239
- ```bash
240
- # List all memories
241
- npx codebase-context memory list
242
-
243
- # Filter by category or type
244
- npx codebase-context memory list --category conventions --type convention
245
-
246
- # Search memories
247
- npx codebase-context memory list --query "auth"
248
-
249
- # Add a memory
250
- npx codebase-context memory add --type convention --category tooling --memory "Use pnpm, not npm" --reason "Workspace support and speed"
251
-
252
- # Remove a memory
253
- npx codebase-context memory remove <id>
254
-
255
- # JSON output for scripting
256
- npx codebase-context memory list --json
257
- ```
258
-
259
- Set `CODEBASE_ROOT` to point to your project, or run from the project directory.
260
-
261
- ## Tip: Ensuring your AI Agent recalls memory:
262
-
263
- Add this to `.cursorrules`, `CLAUDE.md`, or `AGENTS.md`:
264
-
265
- ```
266
- ## Codebase Context
267
-
268
- **At start of each task:** Call `get_memory` to load team conventions.
269
-
270
- **When user says "remember this" or "record this":**
271
- - Call `remember` tool IMMEDIATELY before doing anything else.
272
- ```
273
-
274
- ## Links
275
-
276
- - [Motivation](./MOTIVATION.md) - Research and design rationale
277
- - [Changelog](./CHANGELOG.md) - Version history
278
- - [Contributing](./CONTRIBUTING.md) - How to add analyzers
279
-
280
- ## License
281
-
282
- MIT
1
+ # codebase-context
2
+
3
+ ## Local-first second brain for AI Agents working on your codebase
4
+
5
+ [![npm version](https://img.shields.io/npm/v/codebase-context)](https://www.npmjs.com/package/codebase-context) [![license](https://img.shields.io/npm/l/codebase-context)](./LICENSE) [![node](https://img.shields.io/node/v/codebase-context)](./package.json)
6
+
7
+ You're tired of AI agents writing code that 'just works' but fits like a square peg in a round hole - not your conventions, not your architecture, not your repo. Even with well-curated instructions. You correct the agent, it doesn't remember. Next session, same mistakes.
8
+
9
+ This MCP gives agents _just enough_ context so they match _how_ your team codes, know _why_, and _remember_ every correction.
10
+
11
+ Here's what codebase-context does:
12
+
13
+ **Finds the right context** - Search that doesn't just return code. Each result comes back with analyzed and quantified coding patterns and conventions, related team memories, file relationships, and quality indicators. It knows whether you're looking for a specific file, a concept, or how things wire together - and filters out the noise (test files, configs, old utilities) before the agent sees them. The agent gets curated context, not raw hits.
14
+
15
+ **Knows your conventions** - Detected from your code and git history, not only from rules you wrote. Seeks team consensus and direction by adoption percentages and trends (rising/declining), golden files. Tells the difference between code that's _common_ and code that's _current_ - what patterns the team is moving toward and what's being left behind.
16
+
17
+ **Remembers across sessions** - Decisions, failures, workarounds that look wrong but exist for a reason - the battle scars that aren't in the comments. Recorded once, surfaced automatically so the agent doesn't "clean up" something you spent a week getting right. Conventional git commits (`refactor:`, `migrate:`, `fix:`) auto-extract into memory with zero effort. Stale memories decay and get flagged instead of blindly trusted.
18
+
19
+ **Checks before editing** - Before editing something, you get a decision card showing whether there's enough evidence to proceed. If a symbol has four callers and only two appear in your search results, the card shows that coverage gap. If coverage is low, `whatWouldHelp` lists the specific searches to run before you touch anything. When code, team memories, and patterns contradict each other, it tells you to look deeper instead of guessing.
20
+
21
+ One tool call returns all of it. Local-first - your code never leaves your machine.
22
+
23
+ <!-- TODO: Add demo GIF: search_codebase("How does this app attach the auth token to outgoing API calls?") → AuthInterceptor top result + preflight + agent proceeds or asks -->
24
+ <!-- ![Demo](./docs/assets/demo.gif) -->
25
+
26
+ ## Quick Start
27
+
28
+ Add it to the configuration of your AI Agent of preference:
29
+
30
+ ### Claude Code
31
+
32
+ ```bash
33
+ claude mcp add codebase-context -- npx -y codebase-context /path/to/your/project
34
+ ```
35
+
36
+ ### Claude Desktop
37
+
38
+ Add to `claude_desktop_config.json`:
39
+
40
+ ```json
41
+ {
42
+ "mcpServers": {
43
+ "codebase-context": {
44
+ "command": "npx",
45
+ "args": ["-y", "codebase-context", "/path/to/your/project"]
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ### VS Code (Copilot)
52
+
53
+ Add `.vscode/mcp.json` to your project root:
54
+
55
+ ```json
56
+ {
57
+ "servers": {
58
+ "codebase-context": {
59
+ "command": "npx",
60
+ "args": ["-y", "codebase-context", "/path/to/your/project"] // Or "${workspaceFolder}"if your workspace is one project only
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ ### Cursor
67
+
68
+ Add to `.cursor/mcp.json` in your project:
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "codebase-context": {
74
+ "command": "npx",
75
+ "args": ["-y", "codebase-context", "/path/to/your/project"]
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ ### Windsurf
82
+
83
+ Open Settings > MCP and add:
84
+
85
+ ```json
86
+ {
87
+ "mcpServers": {
88
+ "codebase-context": {
89
+ "command": "npx",
90
+ "args": ["-y", "codebase-context", "/path/to/your/project"]
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ ## Codex
97
+
98
+ Run codex mcp add codebase-context npx -y codebase-context "/path/to/your/project"
99
+
100
+ ## What It Actually Does
101
+
102
+ Other tools help AI find code. This one helps AI make the right decisions - by knowing what your team does, tracking where codebases are heading, and warning before mistakes happen.
103
+
104
+ ### The Difference
105
+
106
+ | Without codebase-context | With codebase-context |
107
+ | ------------------------------------------------------- | --------------------------------------------------- |
108
+ | Generates code using whatever matches or "sounds" right | Generates code following your team conventions |
109
+ | Copies any example that fits | Follows your best implementations (golden files) |
110
+ | Repeats mistakes you already corrected | Surfaces failure memories right before trying again |
111
+ | You re-explain the same things every session | Remembers conventions and decisions automatically |
112
+ | Edits confidently even when context is weak | Flags high-risk changes when evidence is thin |
113
+ | Sees what the current code does and assumes | Sees how your code has evolved and why |
114
+
115
+ ### The Search Tool (`search_codebase`)
116
+
117
+ This is where it all comes together. One call returns:
118
+
119
+ - **Code results** with `file` (path + line range), `summary`, `score`
120
+ - **Type** per result: compact `componentType:layer` (e.g., `service:data`) — helps agents orient
121
+ - **Pattern signals** per result: `trend` (Rising/Declining — Stable is omitted) and `patternWarning` when using legacy code
122
+ - **Relationships** per result: `importedByCount` and `hasTests` (condensed) + **hints** (capped ranked callers, consumers, tests) — so you see suggested next reads and know what you haven't looked at yet
123
+ - **Related memories**: up to 3 team decisions, gotchas, and failures matched to the query
124
+ - **Search quality**: `ok` or `low_confidence` with confidence score and `hint` when low
125
+ - **Preflight**: `ready` (boolean) with decision card when `intent="edit"|"refactor"|"migrate"`. Shows `nextAction` (if not ready), `warnings`, `patterns` (do/avoid), `bestExample`, `impact` (caller coverage), and `whatWouldHelp` (next steps). If search quality is low, `ready` is always `false`.
126
+
127
+ Snippets are optional (`includeSnippets: true`). When enabled, snippets that have symbol metadata (e.g. from the Generic analyzer's AST chunking or Angular component chunks) start with a scope header so you know where the code lives (e.g. `// AuthService.getToken()` or `// SpotifyApiService`). Example:
128
+
129
+ ```ts
130
+ // AuthService.getToken()
131
+ getToken(): string {
132
+ return this.token;
133
+ }
134
+ ```
135
+
136
+ Default output is lean if the agent wants code, it calls `read_file`.
137
+
138
+ ```json
139
+ {
140
+ "searchQuality": { "status": "ok", "confidence": 0.72 },
141
+ "preflight": {
142
+ "ready": false,
143
+ "nextAction": "2 of 5 callers aren't in results — search for src/app.module.ts",
144
+ "patterns": {
145
+ "do": ["HttpInterceptorFn — 97%", "standalone components — 84%"],
146
+ "avoid": ["constructor injection — 3% (declining)"]
147
+ },
148
+ "bestExample": "src/auth/auth.interceptor.ts",
149
+ "impact": {
150
+ "coverage": "3/5 callers in results",
151
+ "files": ["src/app.module.ts", "src/boot.ts"]
152
+ },
153
+ "whatWouldHelp": [
154
+ "Search for src/app.module.ts to cover the main caller",
155
+ "Call get_team_patterns for auth/ injection patterns"
156
+ ]
157
+ },
158
+ "results": [
159
+ {
160
+ "file": "src/auth/auth.interceptor.ts:1-20",
161
+ "summary": "HTTP interceptor that attaches auth token to outgoing requests",
162
+ "score": 0.72,
163
+ "type": "service:core",
164
+ "trend": "Rising",
165
+ "relationships": { "importedByCount": 4, "hasTests": true },
166
+ "hints": {
167
+ "callers": ["src/app.module.ts", "src/boot.ts"],
168
+ "tests": ["src/auth/auth.interceptor.spec.ts"]
169
+ }
170
+ }
171
+ ],
172
+ "relatedMemories": ["Always use HttpInterceptorFn (0.97)"]
173
+ }
174
+ ```
175
+
176
+ Lean enough to fit on one screen. If search quality is low, preflight blocks edits instead of faking confidence.
177
+
178
+ ### Patterns & Conventions (`get_team_patterns`)
179
+
180
+ Detects what your team actually does by analyzing the codebase:
181
+
182
+ - Adoption percentages for dependency injection, state management, testing, libraries
183
+ - Patterns/conventions trend direction (Rising / Stable / Declining) based on git recency
184
+ - Golden files - your best implementations ranked by modern pattern density
185
+ - Conflicts - when the team hasn't converged (both approaches above 20% adoption)
186
+
187
+ ### Team Memory (`remember` + `get_memory`)
188
+
189
+ Record a decision once. It surfaces automatically in search results and preflight cards from then on. **Your git commits also become memories** - conventional commits like `refactor:`, `migrate:`, `fix:`, `revert:` from the last 90 days are auto-extracted during indexing.
190
+
191
+ - **Types**: conventions (style rules), decisions (architecture choices), gotchas (things that break), failures (we tried X, it broke because Y)
192
+ - **Confidence decay**: decisions age over 180 days, gotchas and failures over 90 days. Stale memories get flagged instead of blindly trusted.
193
+ - **Zero-config git extraction**: runs automatically during `refresh_index`. No setup, no manual work.
194
+
195
+ ### All Tools
196
+
197
+ | Tool | What it does |
198
+ | ------------------------------ | ------------------------------------------------------------------------------------------- |
199
+ | `search_codebase` | Hybrid search + decision card. Pass `intent="edit"` to get `ready`, `nextAction`, patterns, caller coverage, and `whatWouldHelp`. |
200
+ | `get_team_patterns` | Pattern frequencies, golden files, conflict detection |
201
+ | `get_symbol_references` | Find concrete references to a symbol (usageCount + top snippets). `confidence: "syntactic"` = static/source-based only; no runtime or dynamic dispatch. |
202
+ | `remember` | Record a convention, decision, gotcha, or failure |
203
+ | `get_memory` | Query team memory with confidence decay scoring |
204
+ | `get_codebase_metadata` | Project structure, frameworks, dependencies |
205
+ | `get_style_guide` | Style guide rules for the current project |
206
+ | `detect_circular_dependencies` | Import cycles between files |
207
+ | `refresh_index` | Re-index (full or incremental) + extract git memories |
208
+ | `get_indexing_status` | Progress and stats for the current index |
209
+
210
+ ## Evaluation Harness (`npm run eval`)
211
+
212
+ Reproducible evaluation with frozen fixtures so ranking/chunking changes are measured honestly and regressions get caught. **For contributors and CI:** run before releases or after changing search/ranking/chunking to guard against regressions.
213
+
214
+ - Two codebases: `npm run eval -- <codebaseA> <codebaseB>`
215
+ - Defaults: fixture A = `tests/fixtures/eval-angular-spotify.json`, fixture B = `tests/fixtures/eval-controlled.json`
216
+ - Offline smoke (no network):
217
+
218
+ ```bash
219
+ npm run eval -- tests/fixtures/codebases/eval-controlled tests/fixtures/codebases/eval-controlled \
220
+ --fixture-a=tests/fixtures/eval-controlled.json \
221
+ --fixture-b=tests/fixtures/eval-controlled.json \
222
+ --skip-reindex --no-rerank
223
+ ```
224
+
225
+ - Flags: `--help`, `--fixture-a`, `--fixture-b`, `--skip-reindex`, `--no-rerank`, `--no-redact`
226
+ - To save a report for later comparison, redirect stdout (e.g. `pnpm run eval -- <path-to-angular-spotify> --skip-reindex > internal-docs/tests/eval-runs/angular-spotify-YYYY-MM-DD.txt`).
227
+
228
+ ## How the Search Works
229
+
230
+ The retrieval pipeline is designed around one goal: give the agent the right context, not just any file that matches.
231
+
232
+ - **Definition-first ranking** - for exact-name lookups (e.g. a symbol name), the file that *defines* the symbol ranks above files that only use it.
233
+ - **Intent classification** - knows whether "AuthService" is a name lookup or "how does auth work" is conceptual. Adjusts keyword/semantic weights accordingly.
234
+ - **Hybrid fusion (RRF)** - combines keyword and semantic search using Reciprocal Rank Fusion instead of brittle score averaging.
235
+ - **Query expansion** - conceptual queries automatically expand with domain-relevant terms (auth → login, token, session, guard).
236
+ - **Contamination control** - test files are filtered/demoted for non-test queries.
237
+ - **Import centrality** - files that are imported more often rank higher.
238
+ - **Cross-encoder reranking** - a stage-2 reranker triggers only when top scores are ambiguous. CPU-only, bounded to top-K.
239
+ - **Incremental indexing** - only re-indexes files that changed since last run (SHA-256 manifest diffing).
240
+ - **Version gating** - index artifacts are versioned; mismatches trigger automatic rebuild so mixed-version data is never served.
241
+ - **Auto-heal** - if the index corrupts, search triggers a full re-index automatically.
242
+
243
+ **Index reliability:** Rebuilds write to a staging directory and swap atomically only on success, so a failed rebuild never corrupts the active index. Version mismatches or corruption trigger an automatic full re-index (no user action required).
244
+
245
+ ## Language Support
246
+
247
+ **10 languages** have full symbol extraction (Tree-sitter): TypeScript, JavaScript, Python, Java, Kotlin, C, C++, C#, Go, Rust. **30+ languages** have indexing and retrieval coverage (keyword + semantic), including PHP, Ruby, Swift, Scala, Shell, and config/markup (JSON/YAML/TOML/XML, etc.).
248
+
249
+ Enrichment is framework-specific: right now only **Angular** has a dedicated analyzer for rich conventions/context (signals, standalone components, control flow, DI patterns).
250
+
251
+ For non-Angular projects, the **Generic** analyzer uses **AST-aligned chunking** when a Tree-sitter grammar is available: symbol-bounded chunks with **scope-aware prefixes** (e.g. `// ClassName.methodName`) so snippets show where code lives. Without a grammar it falls back to safe line-based chunking.
252
+
253
+ Structured filters available: `framework`, `language`, `componentType`, `layer` (presentation, business, data, state, core, shared).
254
+
255
+ ## Configuration
256
+
257
+ | Variable | Default | Description |
258
+ | ------------------------ | -------------- | --------------------------------------------------------- |
259
+ | `EMBEDDING_PROVIDER` | `transformers` | `openai` (fast, cloud) or `transformers` (local, private) |
260
+ | `OPENAI_API_KEY` | - | Required only if using `openai` provider |
261
+ | `CODEBASE_ROOT` | - | Project root (CLI arg takes precedence) |
262
+ | `CODEBASE_CONTEXT_DEBUG` | - | Set to `1` for verbose logging |
263
+
264
+ ## Performance
265
+
266
+ - **First indexing**: 2-5 minutes for ~30k files (embedding computation).
267
+ - **Subsequent queries**: milliseconds from cache.
268
+ - **Incremental updates**: `refresh_index` with `incrementalOnly: true` processes only changed files (SHA-256 manifest diffing).
269
+
270
+ ## File Structure
271
+
272
+ ```
273
+ .codebase-context/
274
+ memory.json # Team knowledge (should be persisted in git)
275
+ index-meta.json # Index metadata and version (generated)
276
+ intelligence.json # Pattern analysis (generated)
277
+ relationships.json # File/symbol relationships (generated)
278
+ index.json # Keyword index (generated)
279
+ index/ # Vector database (generated)
280
+ ```
281
+
282
+ **Recommended `.gitignore`:**
283
+
284
+ ```gitignore
285
+ # Codebase Context - ignore generated files, keep memory
286
+ .codebase-context/*
287
+ !.codebase-context/memory.json
288
+ ```
289
+
290
+ ## CLI Reference
291
+
292
+ All MCP tools are available as CLI commands — no AI agent required. Useful for scripting, debugging, and CI workflows.
293
+
294
+ Set `CODEBASE_ROOT` to your project root, or run from the project directory.
295
+
296
+ ```bash
297
+ # Search the indexed codebase
298
+ npx codebase-context search --query "authentication middleware"
299
+ npx codebase-context search --query "auth" --intent edit --limit 5
300
+
301
+ # Project structure, frameworks, and dependencies
302
+ npx codebase-context metadata
303
+
304
+ # Index state and progress
305
+ npx codebase-context status
306
+
307
+ # Re-index the codebase
308
+ npx codebase-context reindex
309
+ npx codebase-context reindex --incremental --reason "added new service"
310
+
311
+ # Style guide rules
312
+ npx codebase-context style-guide
313
+ npx codebase-context style-guide --query "naming" --category patterns
314
+
315
+ # Team patterns (DI, state, testing, etc.)
316
+ npx codebase-context patterns
317
+ npx codebase-context patterns --category testing
318
+
319
+ # Symbol references
320
+ npx codebase-context refs --symbol "UserService"
321
+ npx codebase-context refs --symbol "handleLogin" --limit 20
322
+
323
+ # Circular dependency detection
324
+ npx codebase-context cycles
325
+ npx codebase-context cycles --scope src/features
326
+
327
+ # Memory management
328
+ npx codebase-context memory list
329
+ npx codebase-context memory list --category conventions --type convention
330
+ npx codebase-context memory list --query "auth" --json
331
+ npx codebase-context memory add --type convention --category tooling --memory "Use pnpm, not npm" --reason "Workspace support and speed"
332
+ npx codebase-context memory remove <id>
333
+ ```
334
+
335
+ All commands accept `--json` for raw JSON output suitable for piping and scripting.
336
+
337
+ ## Tip: Ensuring your AI Agent recalls memory:
338
+
339
+ Add this to `.cursorrules`, `CLAUDE.md`, or `AGENTS.md`:
340
+
341
+ ```
342
+ ## Codebase Context
343
+
344
+ **At start of each task:** Call `get_memory` to load team conventions.
345
+
346
+ **When user says "remember this" or "record this":**
347
+ - Call `remember` tool IMMEDIATELY before doing anything else.
348
+ ```
349
+
350
+ ## Links
351
+
352
+ - [Motivation](./MOTIVATION.md) - Research and design rationale
353
+ - [Changelog](./CHANGELOG.md) - Version history
354
+ - [Contributing](./CONTRIBUTING.md) - How to add analyzers
355
+
356
+ ## License
357
+
358
+ MIT