mcp-code-context 3.9.1 → 3.9.2

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 (98) hide show
  1. package/CHANGELOG.md +227 -215
  2. package/INSTRUCTIONS.md +17 -11
  3. package/README.md +16 -7
  4. package/dist/src/core/engine.d.ts +1 -1
  5. package/dist/src/core/engine.js +1 -1
  6. package/dist/src/core/indexManager.d.ts +1 -1
  7. package/dist/src/core/indexManager.js +26 -26
  8. package/dist/src/core/sessionManager.d.ts +1 -1
  9. package/dist/src/core/sessionManager.js +1 -1
  10. package/dist/src/core/validator.d.ts +2 -2
  11. package/dist/src/core/validator.js +8 -2
  12. package/dist/src/core/validator.js.map +1 -1
  13. package/dist/src/index.d.ts +1 -1
  14. package/dist/src/index.js +2 -2
  15. package/dist/src/operations/astTransform.d.ts +1 -1
  16. package/dist/src/operations/astTransform.js +1 -1
  17. package/dist/src/operations/compress.d.ts +1 -1
  18. package/dist/src/operations/compress.js +1 -1
  19. package/dist/src/operations/confirmationStore.d.ts +1 -1
  20. package/dist/src/operations/confirmationStore.js +1 -1
  21. package/dist/src/operations/write.d.ts +1 -1
  22. package/dist/src/operations/write.js +1 -1
  23. package/dist/src/parsers/base.d.ts +1 -1
  24. package/dist/src/parsers/base.js +1 -1
  25. package/dist/src/parsers/csharp.d.ts +1 -1
  26. package/dist/src/parsers/csharp.js +1 -1
  27. package/dist/src/parsers/dartTreeSitter.d.ts +1 -1
  28. package/dist/src/parsers/dartTreeSitter.js +1 -1
  29. package/dist/src/parsers/go.d.ts +1 -1
  30. package/dist/src/parsers/go.js +1 -1
  31. package/dist/src/parsers/java.d.ts +1 -1
  32. package/dist/src/parsers/java.js +1 -1
  33. package/dist/src/parsers/kotlin.d.ts +1 -1
  34. package/dist/src/parsers/kotlin.js +1 -1
  35. package/dist/src/parsers/php.d.ts +1 -1
  36. package/dist/src/parsers/php.js +1 -1
  37. package/dist/src/parsers/python.d.ts +1 -1
  38. package/dist/src/parsers/python.js +1 -1
  39. package/dist/src/parsers/registry.d.ts +1 -1
  40. package/dist/src/parsers/registry.js +1 -1
  41. package/dist/src/parsers/ruby.d.ts +1 -1
  42. package/dist/src/parsers/ruby.js +1 -1
  43. package/dist/src/parsers/rust.d.ts +1 -1
  44. package/dist/src/parsers/rust.js +1 -1
  45. package/dist/src/parsers/typescript.d.ts +1 -1
  46. package/dist/src/parsers/typescript.js +1 -1
  47. package/dist/src/tools/adminHandlers.js +8 -7
  48. package/dist/src/tools/adminHandlers.js.map +1 -1
  49. package/dist/src/tools/pipeline.js +1 -1
  50. package/dist/src/tools/readHandlers.js +20 -18
  51. package/dist/src/tools/readHandlers.js.map +1 -1
  52. package/dist/src/tools/toolDefinitions.d.ts +7 -2
  53. package/dist/src/tools/toolDefinitionsAdmin.d.ts +1 -1
  54. package/dist/src/tools/toolDefinitionsAdmin.js +12 -12
  55. package/dist/src/tools/toolDefinitionsAdmin.js.map +1 -1
  56. package/dist/src/tools/toolDefinitionsCore.d.ts +6 -1
  57. package/dist/src/tools/toolDefinitionsCore.js +41 -41
  58. package/dist/src/tools/toolDefinitionsCore.js.map +1 -1
  59. package/dist/src/tools/writeHandlers.js +28 -16
  60. package/dist/src/tools/writeHandlers.js.map +1 -1
  61. package/dist/src/utils/appDir.d.ts +1 -1
  62. package/dist/src/utils/appDir.js +1 -1
  63. package/dist/src/utils/auditLogger.d.ts +1 -1
  64. package/dist/src/utils/auditLogger.js +1 -1
  65. package/dist/src/utils/backupManager.d.ts +1 -1
  66. package/dist/src/utils/backupManager.js +1 -1
  67. package/dist/src/utils/constants.d.ts +1 -1
  68. package/dist/src/utils/constants.js +1 -1
  69. package/dist/src/utils/diff.d.ts +1 -1
  70. package/dist/src/utils/diff.js +1 -1
  71. package/dist/src/utils/fileLock.d.ts +1 -1
  72. package/dist/src/utils/fileLock.js +1 -1
  73. package/dist/src/utils/fileWalker.d.ts +1 -1
  74. package/dist/src/utils/fileWalker.js +1 -1
  75. package/dist/src/utils/fileWatcher.d.ts +1 -1
  76. package/dist/src/utils/fileWatcher.js +1 -1
  77. package/dist/src/utils/fuzzySearch.d.ts +1 -1
  78. package/dist/src/utils/fuzzySearch.js +1 -1
  79. package/dist/src/utils/gemfileParser.d.ts +1 -1
  80. package/dist/src/utils/gemfileParser.js +1 -1
  81. package/dist/src/utils/logger.d.ts +1 -1
  82. package/dist/src/utils/logger.js +1 -1
  83. package/dist/src/utils/metaprogramming.d.ts +1 -1
  84. package/dist/src/utils/metaprogramming.js +1 -1
  85. package/dist/src/utils/projectRoot.d.ts +9 -0
  86. package/dist/src/utils/projectRoot.js +94 -0
  87. package/dist/src/utils/projectRoot.js.map +1 -0
  88. package/dist/src/utils/railsRoutes.d.ts +1 -1
  89. package/dist/src/utils/railsRoutes.js +1 -1
  90. package/dist/src/utils/rateLimiter.d.ts +1 -1
  91. package/dist/src/utils/rateLimiter.js +1 -1
  92. package/dist/src/utils/streaming.d.ts +1 -1
  93. package/dist/src/utils/streaming.js +1 -1
  94. package/dist/src/utils/telemetry.d.ts +1 -1
  95. package/dist/src/utils/telemetry.js +1 -1
  96. package/llms.txt +14 -6
  97. package/package.json +1 -1
  98. package/vitest.config.ts +0 -37
package/CHANGELOG.md CHANGED
@@ -1,215 +1,227 @@
1
- # Changelog
2
-
3
- ## [3.9.1] - 2026-07-17
4
-
5
- ### Fixed
6
-
7
- - **`get_rails_routes` namespace bug** — routes inside `namespace :admin do` / `namespace :api do` now correctly produce prefixed paths (`/admin/users`, `/api/v1/orders`) and namespaced controllers (`admin/users`, `api/v1/orders`). Root cause: the original regex `/^(?:namespace|scope)\s+[:'"]([^'"]+)['"]/` captured `admin do` instead of `admin` when using symbol syntax (`:admin`). Rewrote parser to handle symbol (`:admin`) and string (`'admin'`) syntax separately.
8
- - **`get_rails_routes` depth tracking** — replaced fragile `do/end` counter with indentation-based namespace stack. Parser now correctly handles nested namespaces (`api > v1`), `resources` blocks with `member do`, and `scope` blocks without false prefix leakage.
9
- - **`get_semantic_repo_map` Gemfile + Concerns injection** — repo map XML now appends `<gem>` blocks and `<concern>` entries when a Gemfile and concerns directory are present.
10
-
11
- ---
12
-
13
- ## [3.9.0] - 2026-07-17
14
-
15
- ### Added
16
-
17
- - **`get_gemfile_context`** (R7) — parses `Gemfile` and returns known gems with their implicit Rails behavior. Uses `gemDescriptions.json` lookup table (updateable without recompile). Includes mtime-keyed cache for zero re-read cost.
18
- - **`find_metaprogramming`** (R3) — scans Ruby files for dynamic method generation entry points: `define_method`, `method_missing`, `class_eval/module_eval`, `instance_eval`, `send/public_send`, `ActiveSupport::Concern`, `included do`, `attr_accessor/reader/writer`, `delegate :to =>`, `has_many :through`. Accepts single file or full directory scan.
19
- - **`get_rails_routes`** (R2) — parses `config/routes.rb` and returns a structured route map (method, path, controller, action). Supports `resources`, `resource`, explicit HTTP verbs (`get/post/patch/put/delete`), `namespace/scope` prefixing, `root`, and `do`-block nesting warnings. mtime-keyed cache.
20
- - **Concern Resolution in `analyze_impact`** (R5) — `rubyModuleResolvesToFile()` now checks `app/models/concerns` and `app/controllers/concerns` via `findRailsConcerns()` before falling back to file system candidates. Prevents false positives for stdlib mixins.
21
- - **`findRailsConcerns()`** utility — scans both concern directories and returns a `Map<moduleName, filePaths[]>` for use by impact analysis and future tools.
22
-
23
- ### Changed
24
-
25
- - `gemDescriptions.json` — new data file for gem behavior descriptions (bundled in `src/utils/`)
26
-
27
- ---
28
-
29
- ## [3.8.1] - 2026-07-16
30
-
31
- ### Added
32
-
33
- - **`insertCode` fix for brace-less languages (Ruby, Python)** — `inside_start`/`inside_end` positions now use AST-aware methods instead of `indexOf("{")` / `lastIndexOf("}")`. Added `getInsideStartIndex()` and `getInsideEndIndex()` to `BaseParser` with language-specific overrides in `RubyParser` and `PythonParser`.
34
- - **Ruby import analysis** — `extractImports` in `compress.ts` now detects `require` and `require_relative` patterns. `analyzeImpact` adds Ruby patterns with file-resolution guard (prevents false positives from stdlib mixins like `include Comparable`).
35
- - **ActiveRecord schema injection in `get_semantic_repo_map`** — repo map now includes `db_column` symbols for AR models, showing database columns alongside methods in the XML/Markdown output.
36
-
37
- ### Fixed
38
-
39
- - **`insert_symbol inside_start/inside_end` for Ruby** — previously returned wrong position (`-1`) for any Ruby class or method. Now inserts correctly after the opening header line (`inside_start`) and before the closing `end` keyword (`inside_end`).
40
- - **`insert_symbol inside_start/inside_end` for Python** — previously searched for `{`/`}` that don't exist. Now uses colon+newline and indentation-aware end position.
41
-
42
- ---
43
-
44
- ## [3.8.0] - 2026-07-15
45
-
46
- ### Added
47
-
48
- - **Ruby full support** — `RubyParser` now complete with `search()` method for `search_code_pattern` tool compatibility
49
- - **ActiveRecord Virtual Schema Extractor** — new `src/utils/railsSchema.ts` utility:
50
- - Parses `db/schema.rb` via O(n) line-by-line state machine (no backtracking risk)
51
- - mtime-keyed in-memory cache — zero I/O on repeated reads of unchanged schema
52
- - `modelToTable()` — Rails CoC PascalCase → snake_case → pluralize (`AdminUser → admin_users`, `Category → categories`)
53
- - `formatSchemaAnnotation()` — emits XML comment block with column names and types
54
- - **AR schema injection in `read_file_surgical`** — when reading `.rb` files inheriting from `ApplicationRecord` or `ActiveRecord::Base`, virtual schema columns are prepended as XML comments
55
- - Context-aware: when `symbolName` is set, reads full file to detect AR inheritance before injecting
56
- - Graceful: no-op when `db/schema.rb` is absent or table not found
57
-
58
- ### Fixed
59
-
60
- - **`RubyParser.extractSymbol` off-by-one** — `tree.rootNode.text` omits leading whitespace on Windows/WASM, causing `startIndex` drift. Fixed by adjusting indices relative to `tree.rootNode.startIndex`.
61
-
62
- ### Tests
63
-
64
- - Added `tests/unit/parsers/ruby.spec.ts` — 5 vitest specs: symbol discovery, surgical replace, `extractSymbol` scoping, `parseSchemaRb` column extraction, `modelToTable` CoC mapping
65
- - All 115 WASM parser tests passing (100%)
66
-
67
- ---
68
-
69
- ## [3.7.1] - 2026-06-18
70
-
71
- ### Fixed
72
-
73
- - **`ast_transform` wrap_with_try_catch**: Missing closing `}` for method body caused unbalanced braces and syntax errors in all TypeScript class methods
74
- - **`ast_transform` wrap_with_try_catch**: Missing newline after `try {` caused parse failure on all function types
75
-
76
- ---
77
-
78
- ## [3.7.0] - 2026-06-18
79
-
80
- ### 🚀 Production Readiness Release — Adversarial Audit Hardening
81
-
82
- This release fixes **critical architectural issues** identified through three rounds of adversarial analysis and AST-based code review. All stoppers resolved. Ready for multi-agent production deployments.
83
-
84
- ### Fixed — Critical (Production Blockers)
85
-
86
- 1. **Session State Leakage / Memory Leak**
87
- - Global state (`globalLockManager`, `globalConfirmationStore`, `rateLimiter`) accumulated across client sessions with no cleanup.
88
- - **Fix**: `SessionManager` per-client state isolation with LRU eviction and 30-min timeout cleanup.
89
-
90
- 2. **No Phase 1 Crash Recovery**
91
- - Pending operations stored in memory only. Server crash between Phase 1 → Phase 2 lost all work.
92
- - **Fix**: SQLite-backed `PendingOperationStore` — operations persist across restarts.
93
-
94
- 3. **TOCTOU in Multi-File Writes**
95
- - Phase 2 only verified hash of the primary file, not dependent files in `pendingWrites`.
96
- - **Fix**: Hash verified on all files in the write set before applying.
97
-
98
- 4. **Symlink Boundary Escape**
99
- - `path.resolve()` used for boundary validation — does not follow symlinks.
100
- - **Fix**: `fs.realpath()` in `SecurityValidator.validateFilePath()`.
101
-
102
- 5. **`new Promise(async ...)` Anti-pattern in Worker**
103
- - `runInWorker` used `new Promise(async (resolve) => ...)` — swallowed async errors.
104
- - **Fix**: Refactored to standard async/await pattern.
105
-
106
- 6. **`WORKER_FILE` Resolved at Import-Time**
107
- - Worker path calculated before `dist/` exists — crashes on fresh install.
108
- - **Fix**: Lazy `getWorkerFile()` evaluated at runtime.
109
-
110
- 7. **ReDoS in `impactAnalysis`, `rename`, `readCore`**
111
- - Dynamic `new RegExp()` constructed in main thread without timeout.
112
- - **Fix**: All operation-level regex routed through `safeRegex` worker pool.
113
-
114
- 8. **Rate Limiter Shared Globally**
115
- - Single `'global'` bucket shared across all MCP clients.
116
- - **Fix**: Per-session `SESSION_ID` (pid-based) rate limiting.
117
-
118
- 9. **`configure_file_watcher` Without `rootDir` Validation**
119
- - Watcher path not validated through `SecurityValidator`.
120
- - **Fix**: Watcher uses only validated `projectRoot`.
121
-
122
- 10. **Confirmation Token Leak Without Cleanup**
123
- - Expired tokens accumulated in memory indefinitely.
124
- - **Fix**: `setInterval` 60s cleanup in `ConfirmationStore`.
125
-
126
- 11. **Windows Path Case Sensitivity in Boundary Check**
127
- - `fs.realpath()` returns `C:\` (uppercase), `path.resolve()` returns `c:\` (lowercase).
128
- - **Fix**: `.toLowerCase()` normalization on both sides before comparison.
129
-
130
- 12. **`ast_transform` try/catch Indentation Bug**
131
- - `applyWrapTryCatch` added extra indent on top of existing indentation.
132
- - **Fix**: Correct base-indent detection using last line of rawBody as closing-indent anchor.
133
-
134
- ### Added
135
-
136
- #### 25 Tools (up from 13 in v3.6.x)
137
-
138
- New tools added in this release:
139
-
140
- | Tool | Purpose |
141
- |------|---------|
142
- | `ast_transform` | Declarative AST transforms: add_parameter, wrap_with_try_catch, add_decorator, change_return_type, extract_variable |
143
- | `search_symbols` | AST-aware symbol search by name (fuzzy-capable), not text grep |
144
- | `explain_symbol` | Signature + location + callers in one call |
145
- | `batch_read` | Read N symbols from N files in 1 round-trip |
146
- | `get_rate_limit_status` | Token balance + `canAfford` map per operation |
147
- | `get_session_stats` | Per-session diagnostics (pending ops, locks, tokens) |
148
- | `clear_session_cache` | Invalidate cache for current session only |
149
- | `list_pending_operations` | Recovery listing after crash |
150
-
151
- #### Architecture Improvements
152
-
153
- - `SessionManager`: Per-client isolated state (locks, confirmations, rate limiter, cache pool)
154
- - `safeRegexPool.ts` + `safeRegexApi.ts`: Worker pool split from monolithic `safeRegex.ts`
155
- - `toctou.ts`: TOCTOU hash helpers extracted to own module
156
- - `pendingStore.ts` + `pendingStoreInit.ts`: SQLite crash-recovery layer
157
- - `toolDefinitionsAdmin.ts` + `toolDefinitionsCore.ts`: Tool definitions split from 1000-line index
158
- - All `src/` files under 300 lines (from 1000-line monolith)
159
-
160
- #### DX / Ergonomics
161
-
162
- - `diffFormat` param on all write tools: `unified` | `compact` | `summary` | `none`
163
- - Phase 2 does NOT require re-sending `newContent`/`code` (server stores from Phase 1)
164
- - `aroundPattern` output includes `"Match found at line N (showing lines X-Y):"`
165
- - `get_cache_stats` includes `hits`, `misses`, `hitRate`
166
- - `get_file_watcher_status` includes `paths[]` (capped at 50)
167
- - `get_server_stats` includes `rateLimiter.tokensAvailable` and `operationCosts`
168
- - `MAX_FILES_REPO_MAP` = 2000 (was 500)
169
-
170
- ### Test Results
171
-
172
- - **83/83 tests passing** (100%)
173
- - Security tests: ✅
174
- - File lock tests: ✅
175
- - Rate limiter tests: ✅
176
- - WASM parser tests (TS/PHP/Python/Dart): ✅
177
- - Backup manager, diff, TOCTOU, cache, confirmation store: ✅
178
- - Multi-process concurrency tests: ✅
179
- - Performance tests: ✅
180
-
181
- ### Migration from v3.6.x
182
-
183
- - **Zero breaking changes** in the public tool API.
184
- - `parse_file` now returns `startLine`/`endLine` per symbol — additive, no breakage.
185
- - New tools are purely additive.
186
- - Session isolation is automatic — no configuration needed.
187
-
188
- ---
189
-
190
- ## [3.6.4] - 2026-05-14
191
-
192
- ### Added
193
- - Language parsers: C#, Go, Java, Kotlin, Ruby, Rust (Tree-sitter WASM)
194
- - `parse_file` returns `startLine`/`endLine` per symbol
195
- - Fuzzy search with `fuzzyMatch` + `fuzzyThreshold` parameters
196
- - Pagination via `startIndex` on `search_code_pattern`
197
- - `diffFormat` parameter on write tools
198
-
199
- ### Fixed
200
- - `parse_file` symbols missing line numbers
201
- - CVE in `@modelcontextprotocol/sdk` (updated to 1.29.0)
202
- - Incorrect TypeScript version `5.7.0` → `5.7.2`
203
-
204
- ---
205
-
206
- ## [3.6.1] - 2026-04-28
207
-
208
- ### Added
209
- - Persistent WASM SQLite cache (`CacheManager`)
210
- - Structured logging via pino (stderr-safe for MCP)
211
- - File watcher via chokidar
212
- - Multi-process file locking via proper-lockfile
213
- - Rolling 5-version backup system
214
- - `rollback_file` and `clean_backups` tools
215
- - 74 tests (unit + integration + performance + stress)
1
+ # Changelog
2
+
3
+ ## [3.9.2] - 2026-10-12
4
+
5
+ ### Fixed
6
+
7
+ - **Project Root Fallback & Boundary Resolution** — fixed critical issue where omitted or `undefined` `projectRoot` arguments were coerced to the literal string `"undefined"`, resolving to `<cwd>/undefined` and causing spurious `outside project boundary` security errors when accessing valid files.
8
+ - **Smart Root Discovery** — introduced `resolveProjectRoot` and `findProjectRoot` in `src/utils/projectRoot.ts`, which automatically walks up the directory tree to discover root markers (`.git`, `package.json`, `composer.json`, `pyproject.toml`, `requirements.txt`, `Cargo.toml`, `go.mod`, `Gemfile`, `pom.xml`, `build.gradle`), falling back cleanly to `process.cwd()`.
9
+ - **SecurityValidator Hardening** — `SecurityValidator` constructor now safely handles `undefined`, `null`, or blank inputs without generating an invalid boundary path.
10
+ - **Optional Schema Requirements** — made `projectRoot` optional in tool definitions across both `CORE_TOOLS` and `ADMIN_TOOLS`, allowing LLM agents to execute surgical reads, writes, and symbol lookups with only `filePath` or `rootDir`.
11
+ - **Startup Diagnostics** — added clear banner signature on stdio initialization: `[mcp-code-context] v3.9.2 running on stdio`.
12
+
13
+ ---
14
+
15
+ ## [3.9.1] - 2026-07-17
16
+
17
+ ### Fixed
18
+
19
+ - **`get_rails_routes` namespace bug** — routes inside `namespace :admin do` / `namespace :api do` now correctly produce prefixed paths (`/admin/users`, `/api/v1/orders`) and namespaced controllers (`admin/users`, `api/v1/orders`). Root cause: the original regex `/^(?:namespace|scope)\s+[:'"]([^'"]+)['"]/` captured `admin do` instead of `admin` when using symbol syntax (`:admin`). Rewrote parser to handle symbol (`:admin`) and string (`'admin'`) syntax separately.
20
+ - **`get_rails_routes` depth tracking** — replaced fragile `do/end` counter with indentation-based namespace stack. Parser now correctly handles nested namespaces (`api > v1`), `resources` blocks with `member do`, and `scope` blocks without false prefix leakage.
21
+ - **`get_semantic_repo_map` Gemfile + Concerns injection** — repo map XML now appends `<gem>` blocks and `<concern>` entries when a Gemfile and concerns directory are present.
22
+
23
+ ---
24
+
25
+ ## [3.9.0] - 2026-07-17
26
+
27
+ ### Added
28
+
29
+ - **`get_gemfile_context`** (R7) — parses `Gemfile` and returns known gems with their implicit Rails behavior. Uses `gemDescriptions.json` lookup table (updateable without recompile). Includes mtime-keyed cache for zero re-read cost.
30
+ - **`find_metaprogramming`** (R3) — scans Ruby files for dynamic method generation entry points: `define_method`, `method_missing`, `class_eval/module_eval`, `instance_eval`, `send/public_send`, `ActiveSupport::Concern`, `included do`, `attr_accessor/reader/writer`, `delegate :to =>`, `has_many :through`. Accepts single file or full directory scan.
31
+ - **`get_rails_routes`** (R2) — parses `config/routes.rb` and returns a structured route map (method, path, controller, action). Supports `resources`, `resource`, explicit HTTP verbs (`get/post/patch/put/delete`), `namespace/scope` prefixing, `root`, and `do`-block nesting warnings. mtime-keyed cache.
32
+ - **Concern Resolution in `analyze_impact`** (R5) — `rubyModuleResolvesToFile()` now checks `app/models/concerns` and `app/controllers/concerns` via `findRailsConcerns()` before falling back to file system candidates. Prevents false positives for stdlib mixins.
33
+ - **`findRailsConcerns()`** utility — scans both concern directories and returns a `Map<moduleName, filePaths[]>` for use by impact analysis and future tools.
34
+
35
+ ### Changed
36
+
37
+ - `gemDescriptions.json` — new data file for gem behavior descriptions (bundled in `src/utils/`)
38
+
39
+ ---
40
+
41
+ ## [3.8.1] - 2026-07-16
42
+
43
+ ### Added
44
+
45
+ - **`insertCode` fix for brace-less languages (Ruby, Python)** — `inside_start`/`inside_end` positions now use AST-aware methods instead of `indexOf("{")` / `lastIndexOf("}")`. Added `getInsideStartIndex()` and `getInsideEndIndex()` to `BaseParser` with language-specific overrides in `RubyParser` and `PythonParser`.
46
+ - **Ruby import analysis** — `extractImports` in `compress.ts` now detects `require` and `require_relative` patterns. `analyzeImpact` adds Ruby patterns with file-resolution guard (prevents false positives from stdlib mixins like `include Comparable`).
47
+ - **ActiveRecord schema injection in `get_semantic_repo_map`** — repo map now includes `db_column` symbols for AR models, showing database columns alongside methods in the XML/Markdown output.
48
+
49
+ ### Fixed
50
+
51
+ - **`insert_symbol inside_start/inside_end` for Ruby** — previously returned wrong position (`-1`) for any Ruby class or method. Now inserts correctly after the opening header line (`inside_start`) and before the closing `end` keyword (`inside_end`).
52
+ - **`insert_symbol inside_start/inside_end` for Python** — previously searched for `{`/`}` that don't exist. Now uses colon+newline and indentation-aware end position.
53
+
54
+ ---
55
+
56
+ ## [3.8.0] - 2026-07-15
57
+
58
+ ### Added
59
+
60
+ - **Ruby full support** — `RubyParser` now complete with `search()` method for `search_code_pattern` tool compatibility
61
+ - **ActiveRecord Virtual Schema Extractor** — new `src/utils/railsSchema.ts` utility:
62
+ - Parses `db/schema.rb` via O(n) line-by-line state machine (no backtracking risk)
63
+ - mtime-keyed in-memory cache — zero I/O on repeated reads of unchanged schema
64
+ - `modelToTable()` — Rails CoC PascalCase → snake_case → pluralize (`AdminUser → admin_users`, `Category → categories`)
65
+ - `formatSchemaAnnotation()` — emits XML comment block with column names and types
66
+ - **AR schema injection in `read_file_surgical`** — when reading `.rb` files inheriting from `ApplicationRecord` or `ActiveRecord::Base`, virtual schema columns are prepended as XML comments
67
+ - Context-aware: when `symbolName` is set, reads full file to detect AR inheritance before injecting
68
+ - Graceful: no-op when `db/schema.rb` is absent or table not found
69
+
70
+ ### Fixed
71
+
72
+ - **`RubyParser.extractSymbol` off-by-one** — `tree.rootNode.text` omits leading whitespace on Windows/WASM, causing `startIndex` drift. Fixed by adjusting indices relative to `tree.rootNode.startIndex`.
73
+
74
+ ### Tests
75
+
76
+ - Added `tests/unit/parsers/ruby.spec.ts` — 5 vitest specs: symbol discovery, surgical replace, `extractSymbol` scoping, `parseSchemaRb` column extraction, `modelToTable` CoC mapping
77
+ - All 115 WASM parser tests passing (100%)
78
+
79
+ ---
80
+
81
+ ## [3.7.1] - 2026-06-18
82
+
83
+ ### Fixed
84
+
85
+ - **`ast_transform` wrap_with_try_catch**: Missing closing `}` for method body caused unbalanced braces and syntax errors in all TypeScript class methods
86
+ - **`ast_transform` wrap_with_try_catch**: Missing newline after `try {` caused parse failure on all function types
87
+
88
+ ---
89
+
90
+ ## [3.7.0] - 2026-06-18
91
+
92
+ ### 🚀 Production Readiness Release — Adversarial Audit Hardening
93
+
94
+ This release fixes **critical architectural issues** identified through three rounds of adversarial analysis and AST-based code review. All stoppers resolved. Ready for multi-agent production deployments.
95
+
96
+ ### Fixed — Critical (Production Blockers)
97
+
98
+ 1. **Session State Leakage / Memory Leak**
99
+ - Global state (`globalLockManager`, `globalConfirmationStore`, `rateLimiter`) accumulated across client sessions with no cleanup.
100
+ - **Fix**: `SessionManager` per-client state isolation with LRU eviction and 30-min timeout cleanup.
101
+
102
+ 2. **No Phase 1 Crash Recovery**
103
+ - Pending operations stored in memory only. Server crash between Phase 1 → Phase 2 lost all work.
104
+ - **Fix**: SQLite-backed `PendingOperationStore` — operations persist across restarts.
105
+
106
+ 3. **TOCTOU in Multi-File Writes**
107
+ - Phase 2 only verified hash of the primary file, not dependent files in `pendingWrites`.
108
+ - **Fix**: Hash verified on all files in the write set before applying.
109
+
110
+ 4. **Symlink Boundary Escape**
111
+ - `path.resolve()` used for boundary validation — does not follow symlinks.
112
+ - **Fix**: `fs.realpath()` in `SecurityValidator.validateFilePath()`.
113
+
114
+ 5. **`new Promise(async ...)` Anti-pattern in Worker**
115
+ - `runInWorker` used `new Promise(async (resolve) => ...)` — swallowed async errors.
116
+ - **Fix**: Refactored to standard async/await pattern.
117
+
118
+ 6. **`WORKER_FILE` Resolved at Import-Time**
119
+ - Worker path calculated before `dist/` exists — crashes on fresh install.
120
+ - **Fix**: Lazy `getWorkerFile()` evaluated at runtime.
121
+
122
+ 7. **ReDoS in `impactAnalysis`, `rename`, `readCore`**
123
+ - Dynamic `new RegExp()` constructed in main thread without timeout.
124
+ - **Fix**: All operation-level regex routed through `safeRegex` worker pool.
125
+
126
+ 8. **Rate Limiter Shared Globally**
127
+ - Single `'global'` bucket shared across all MCP clients.
128
+ - **Fix**: Per-session `SESSION_ID` (pid-based) rate limiting.
129
+
130
+ 9. **`configure_file_watcher` Without `rootDir` Validation**
131
+ - Watcher path not validated through `SecurityValidator`.
132
+ - **Fix**: Watcher uses only validated `projectRoot`.
133
+
134
+ 10. **Confirmation Token Leak Without Cleanup**
135
+ - Expired tokens accumulated in memory indefinitely.
136
+ - **Fix**: `setInterval` 60s cleanup in `ConfirmationStore`.
137
+
138
+ 11. **Windows Path Case Sensitivity in Boundary Check**
139
+ - `fs.realpath()` returns `C:\` (uppercase), `path.resolve()` returns `c:\` (lowercase).
140
+ - **Fix**: `.toLowerCase()` normalization on both sides before comparison.
141
+
142
+ 12. **`ast_transform` try/catch Indentation Bug**
143
+ - `applyWrapTryCatch` added extra indent on top of existing indentation.
144
+ - **Fix**: Correct base-indent detection using last line of rawBody as closing-indent anchor.
145
+
146
+ ### Added
147
+
148
+ #### 25 Tools (up from 13 in v3.6.x)
149
+
150
+ New tools added in this release:
151
+
152
+ | Tool | Purpose |
153
+ |------|---------|
154
+ | `ast_transform` | Declarative AST transforms: add_parameter, wrap_with_try_catch, add_decorator, change_return_type, extract_variable |
155
+ | `search_symbols` | AST-aware symbol search by name (fuzzy-capable), not text grep |
156
+ | `explain_symbol` | Signature + location + callers in one call |
157
+ | `batch_read` | Read N symbols from N files in 1 round-trip |
158
+ | `get_rate_limit_status` | Token balance + `canAfford` map per operation |
159
+ | `get_session_stats` | Per-session diagnostics (pending ops, locks, tokens) |
160
+ | `clear_session_cache` | Invalidate cache for current session only |
161
+ | `list_pending_operations` | Recovery listing after crash |
162
+
163
+ #### Architecture Improvements
164
+
165
+ - `SessionManager`: Per-client isolated state (locks, confirmations, rate limiter, cache pool)
166
+ - `safeRegexPool.ts` + `safeRegexApi.ts`: Worker pool split from monolithic `safeRegex.ts`
167
+ - `toctou.ts`: TOCTOU hash helpers extracted to own module
168
+ - `pendingStore.ts` + `pendingStoreInit.ts`: SQLite crash-recovery layer
169
+ - `toolDefinitionsAdmin.ts` + `toolDefinitionsCore.ts`: Tool definitions split from 1000-line index
170
+ - All `src/` files under 300 lines (from 1000-line monolith)
171
+
172
+ #### DX / Ergonomics
173
+
174
+ - `diffFormat` param on all write tools: `unified` | `compact` | `summary` | `none`
175
+ - Phase 2 does NOT require re-sending `newContent`/`code` (server stores from Phase 1)
176
+ - `aroundPattern` output includes `"Match found at line N (showing lines X-Y):"`
177
+ - `get_cache_stats` includes `hits`, `misses`, `hitRate`
178
+ - `get_file_watcher_status` includes `paths[]` (capped at 50)
179
+ - `get_server_stats` includes `rateLimiter.tokensAvailable` and `operationCosts`
180
+ - `MAX_FILES_REPO_MAP` = 2000 (was 500)
181
+
182
+ ### Test Results
183
+
184
+ - **83/83 tests passing** (100%)
185
+ - Security tests: ✅
186
+ - File lock tests: ✅
187
+ - Rate limiter tests: ✅
188
+ - WASM parser tests (TS/PHP/Python/Dart): ✅
189
+ - Backup manager, diff, TOCTOU, cache, confirmation store: ✅
190
+ - Multi-process concurrency tests: ✅
191
+ - Performance tests: ✅
192
+
193
+ ### Migration from v3.6.x
194
+
195
+ - **Zero breaking changes** in the public tool API.
196
+ - `parse_file` now returns `startLine`/`endLine` per symbol — additive, no breakage.
197
+ - New tools are purely additive.
198
+ - Session isolation is automatic — no configuration needed.
199
+
200
+ ---
201
+
202
+ ## [3.6.4] - 2026-05-14
203
+
204
+ ### Added
205
+ - Language parsers: C#, Go, Java, Kotlin, Ruby, Rust (Tree-sitter WASM)
206
+ - `parse_file` returns `startLine`/`endLine` per symbol
207
+ - Fuzzy search with `fuzzyMatch` + `fuzzyThreshold` parameters
208
+ - Pagination via `startIndex` on `search_code_pattern`
209
+ - `diffFormat` parameter on write tools
210
+
211
+ ### Fixed
212
+ - `parse_file` symbols missing line numbers
213
+ - CVE in `@modelcontextprotocol/sdk` (updated to 1.29.0)
214
+ - Incorrect TypeScript version `5.7.0` → `5.7.2`
215
+
216
+ ---
217
+
218
+ ## [3.6.1] - 2026-04-28
219
+
220
+ ### Added
221
+ - Persistent WASM SQLite cache (`CacheManager`)
222
+ - Structured logging via pino (stderr-safe for MCP)
223
+ - File watcher via chokidar
224
+ - Multi-process file locking via proper-lockfile
225
+ - Rolling 5-version backup system
226
+ - `rollback_file` and `clean_backups` tools
227
+ - 74 tests (unit + integration + performance + stress)
package/INSTRUCTIONS.md CHANGED
@@ -71,8 +71,8 @@ This MCP server provides **surgical code editing** with Tree-sitter AST parsing.
71
71
 
72
72
  ## 🚨 Critical Rules
73
73
 
74
- ### 1. **ALWAYS Use projectRoot**
75
- Every tool requires `projectRoot` for security. Use the project's root directory.
74
+ ### 1. **Project Root (Auto-Resolved in v3.9.2)**
75
+ While `projectRoot` is supported for explicit boundary locking, in v3.9.2 it is optional and automatically resolved from `filePath` or `rootDir` by walking up to the nearest project marker (`.git`, `package.json`, etc.). You can omit it without fear of boundary errors.
76
76
 
77
77
  ### 2. **NEVER Skip Phase 1**
78
78
  Always preview diffs before applying. Tokens are stored in memory and expire on server restart.
@@ -253,14 +253,20 @@ newContent: "{ return 42; }"
253
253
 
254
254
  ---
255
255
 
256
- ## 🚀 v3.9.1 Features
256
+ ## 🚀 v3.9.2 Features
257
257
 
258
- ### New Tools
259
- - **`get_session_stats`**: Session-scoped stats (pending ops, locks held, rate limiter tokens)
260
- - **`clear_session_cache`**: Clear cache for current session only (no impact on other clients)
261
- - **`list_pending_operations`**: List all pending operations (for recovery after crash)
258
+ ### Core Improvements
259
+ - ✅ **Smart Project Root Discovery**: `resolveProjectRoot` & `findProjectRoot` automatically detect project markers (`.git`, `package.json`, `composer.json`, `pyproject.toml`, etc.), preventing boundary errors when `projectRoot` is omitted or undefined.
260
+ - ✅ **Optional Schema Requirements**: `projectRoot` is now optional across all tools in `CORE_TOOLS` and `ADMIN_TOOLS`, allowing LLM agents to execute surgical operations with just `filePath` or `rootDir`.
261
+ - ✅ **SecurityValidator Guard**: Robust handling of undefined/null boundaries, safely defaulting to `process.cwd()`.
262
+ - ✅ **Startup Diagnostics**: Stdio initialization signature `[mcp-code-context] v3.9.2 running on stdio`.
262
263
 
263
- ### Improvements
264
+ ### Previously Added in v3.9.0 - v3.9.1
265
+ - ✅ **Ruby Intelligence**: `get_gemfile_context`, `find_metaprogramming`, `get_rails_routes`, and Rails concerns resolution in `analyze_impact`.
266
+ - ✅ **Semantic Repo Map Enhancements**: Injects `<gem>` behavior blocks and `<concern>` entries when Gemfile and concerns directories exist.
267
+
268
+ ### Previously Added in v3.8.x
269
+ - ✅ **New Tools**: `get_session_stats`, `clear_session_cache`, `list_pending_operations`
264
270
  - ✅ **Session-scoped state**: No state leakage between MCP clients
265
271
  - ✅ **Crash recovery**: SQLite-backed pending operations store
266
272
  - ✅ **Expanded ReDoS protection**: 15+ patterns (was 6)
@@ -288,6 +294,6 @@ See `llms.txt` for complete API reference and technical details.
288
294
 
289
295
  ---
290
296
 
291
- **Version**: 3.9.1
292
- **Last Updated**: June 8, 2026
293
- **Status**: Production-ready with session-scoped state and crash recovery
297
+ **Version**: 3.9.2
298
+ **Last Updated**: October 12, 2026
299
+ **Status**: Production-ready with smart project root discovery and session-scoped state
package/README.md CHANGED
@@ -75,7 +75,7 @@ Built to be robust and precise. Both read and write engines are tested against r
75
75
 
76
76
  ### Production-Ready Features
77
77
 
78
- | Feature | v3.6.x | v3.9.1 | Benefit |
78
+ | Feature | v3.6.x | v3.8.0+ | Benefit |
79
79
  |---------|--------|--------|---------|
80
80
  | Multi-process safety | ✅ | ✅ | No file corruption |
81
81
  | Persistent cache | ✅ | ✅ | <100ms cache hits |
@@ -88,7 +88,16 @@ Built to be robust and precise. Both read and write engines are tested against r
88
88
 
89
89
  ## Features
90
90
 
91
- ### What's New in v3.9.1
91
+ ### What's New in v3.9.2
92
+
93
+ | Feature | Description |
94
+ |---------|-------------|
95
+ | 🛡️ **Smart Project Root Discovery** | `resolveProjectRoot` & `findProjectRoot` walk up directory trees finding `.git`, `package.json`, `composer.json`, etc. No more `outside project boundary ".../undefined"` security errors. |
96
+ | 🔓 **Optional Schema Requirements** | `projectRoot` is now optional across all tools in `CORE_TOOLS` and `ADMIN_TOOLS`. LLM agents can perform surgical reads, writes, and searches with just `filePath` or `rootDir`. |
97
+ | 🛡️ **SecurityValidator Fallback Guard** | `SecurityValidator` safely handles `undefined`/`null` inputs by falling back to `process.cwd()` instead of normalizing to literal `undefined`. |
98
+ | 📡 **Startup Diagnostics Signature** | Startup diagnostics banner prints `[mcp-code-context] v3.9.2 running on stdio` on stdio initialization. |
99
+
100
+ ### Previous: v3.9.1
92
101
 
93
102
  | Feature | Description |
94
103
  |---------|-------------|
@@ -181,7 +190,7 @@ Built to be robust and precise. Both read and write engines are tested against r
181
190
 
182
191
  ### `get_semantic_repo_map` Tool
183
192
 
184
- - **Max files**: Limited to 2000 files to prevent timeouts (increased from 500 in v3.9.1)
193
+ - **Max files**: Limited to 2000 files to prevent timeouts (increased from 500 in v3.8.0)
185
194
  - **Performance**: Synchronous I/O may take 10-30 seconds on large repositories
186
195
  - **Recommendation**: Use `@folder` syntax to target specific directories
187
196
 
@@ -208,13 +217,13 @@ npx -y mcp-code-context
208
217
 
209
218
  ---
210
219
 
211
- ## Session State (v3.9.1+)
220
+ ## Session State (v3.8.0+)
212
221
 
213
- **Important**: v3.9.1 introduces **session-scoped state** for each MCP client connection. This prevents state leakage when multiple agents (Amazon Q, Kiro, Cursor, etc.) use the same server instance.
222
+ **Important**: v3.8.0 introduced **session-scoped state** for each MCP client connection. This prevents state leakage when multiple agents (Amazon Q, Kiro, Cursor, etc.) use the same server instance.
214
223
 
215
224
  ### What Changed
216
225
 
217
- | Before (v3.6.x) | After (v3.9.1) |
226
+ | Before (v3.6.x) | After (v3.8.0+) |
218
227
  |----------------|----------------|
219
228
  | Global `LockManager` (shared by all clients) | Session-scoped `sessionStates` Map |
220
229
  | Global `ConfirmationStore` (in-memory Map) | Session-scoped confirmation store + SQLite persistence |
@@ -549,7 +558,7 @@ npm run dev
549
558
  - **Portability:** 100% WASM - no native dependencies, works on all platforms
550
559
  - **Tests:** 83 passing (unit + integration + performance + stress)
551
560
 
552
- ### v3.9.1 Key Changes
561
+ ### Architectural Evolution (v3.8.0+)
553
562
 
554
563
  | Component | Change | Benefit |
555
564
  |-----------|--------|---------|
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Core Engine - v3.9.1
2
+ * Core Engine - v3.9.2
3
3
  * ASYNC I/O: Migrated to fs.promises
4
4
  */
5
5
  import { Parser, Language } from "web-tree-sitter";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Core Engine - v3.9.1
2
+ * Core Engine - v3.9.2
3
3
  * ASYNC I/O: Migrated to fs.promises
4
4
  */
5
5
  import { Parser, Language } from "web-tree-sitter";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Index Manager - v3.9.1
2
+ * Index Manager - v3.9.2
3
3
  * Persistent symbol index and dependency graph in ~/.mcp-code-context/index/
4
4
  * Enables O(1) search_symbols and analyze_impact queries.
5
5
  */