@ruso-0/nreki 7.1.2 → 7.3.1

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 (87) hide show
  1. package/CHANGELOG.md +825 -774
  2. package/README.md +308 -442
  3. package/dist/ast-sandbox.d.ts.map +1 -1
  4. package/dist/ast-sandbox.js +17 -1
  5. package/dist/ast-sandbox.js.map +1 -1
  6. package/dist/audit.d.ts.map +1 -1
  7. package/dist/audit.js +10 -4
  8. package/dist/audit.js.map +1 -1
  9. package/dist/chronos-memory.d.ts.map +1 -1
  10. package/dist/chronos-memory.js +10 -2
  11. package/dist/chronos-memory.js.map +1 -1
  12. package/dist/compressor.d.ts.map +1 -1
  13. package/dist/compressor.js +13 -1
  14. package/dist/compressor.js.map +1 -1
  15. package/dist/database.d.ts +12 -1
  16. package/dist/database.d.ts.map +1 -1
  17. package/dist/database.js +74 -29
  18. package/dist/database.js.map +1 -1
  19. package/dist/embedder.d.ts.map +1 -1
  20. package/dist/embedder.js +7 -2
  21. package/dist/embedder.js.map +1 -1
  22. package/dist/handlers/code.d.ts.map +1 -1
  23. package/dist/handlers/code.js +198 -243
  24. package/dist/handlers/code.js.map +1 -1
  25. package/dist/handlers/guard.d.ts.map +1 -1
  26. package/dist/handlers/guard.js +10 -1
  27. package/dist/handlers/guard.js.map +1 -1
  28. package/dist/hologram/shadow-generator.d.ts.map +1 -1
  29. package/dist/hologram/shadow-generator.js +20 -1
  30. package/dist/hologram/shadow-generator.js.map +1 -1
  31. package/dist/kernel/backends/lsp-sidecar-base.d.ts +49 -5
  32. package/dist/kernel/backends/lsp-sidecar-base.d.ts.map +1 -1
  33. package/dist/kernel/backends/lsp-sidecar-base.js +252 -79
  34. package/dist/kernel/backends/lsp-sidecar-base.js.map +1 -1
  35. package/dist/kernel/backends/ts-compiler-wrapper.d.ts +1 -1
  36. package/dist/kernel/backends/ts-compiler-wrapper.d.ts.map +1 -1
  37. package/dist/kernel/backends/ts-compiler-wrapper.js +7 -4
  38. package/dist/kernel/backends/ts-compiler-wrapper.js.map +1 -1
  39. package/dist/kernel/backends/ts-corsa-sidecar.d.ts +26 -0
  40. package/dist/kernel/backends/ts-corsa-sidecar.d.ts.map +1 -0
  41. package/dist/kernel/backends/ts-corsa-sidecar.js +30 -0
  42. package/dist/kernel/backends/ts-corsa-sidecar.js.map +1 -0
  43. package/dist/kernel/nreki-kernel.d.ts +44 -0
  44. package/dist/kernel/nreki-kernel.d.ts.map +1 -1
  45. package/dist/kernel/nreki-kernel.js +712 -292
  46. package/dist/kernel/nreki-kernel.js.map +1 -1
  47. package/dist/kernel/spectral-topology.d.ts.map +1 -1
  48. package/dist/kernel/spectral-topology.js +32 -16
  49. package/dist/kernel/spectral-topology.js.map +1 -1
  50. package/dist/middleware/circuit-breaker.d.ts.map +1 -1
  51. package/dist/middleware/circuit-breaker.js +18 -2
  52. package/dist/middleware/circuit-breaker.js.map +1 -1
  53. package/dist/middleware/file-lock.d.ts.map +1 -1
  54. package/dist/middleware/file-lock.js +8 -3
  55. package/dist/middleware/file-lock.js.map +1 -1
  56. package/dist/monitor.d.ts.map +1 -1
  57. package/dist/monitor.js +1 -0
  58. package/dist/monitor.js.map +1 -1
  59. package/dist/parser.d.ts.map +1 -1
  60. package/dist/parser.js +19 -2
  61. package/dist/parser.js.map +1 -1
  62. package/dist/pin-memory.d.ts +2 -2
  63. package/dist/pin-memory.d.ts.map +1 -1
  64. package/dist/pin-memory.js.map +1 -1
  65. package/dist/repo-map.d.ts.map +1 -1
  66. package/dist/repo-map.js +26 -0
  67. package/dist/repo-map.js.map +1 -1
  68. package/dist/router.d.ts.map +1 -1
  69. package/dist/router.js +58 -18
  70. package/dist/router.js.map +1 -1
  71. package/dist/undo.js +1 -1
  72. package/dist/undo.js.map +1 -1
  73. package/dist/utils/imports.d.ts.map +1 -1
  74. package/dist/utils/imports.js +8 -4
  75. package/dist/utils/imports.js.map +1 -1
  76. package/dist/utils/latency-tracker.d.ts +22 -0
  77. package/dist/utils/latency-tracker.d.ts.map +1 -0
  78. package/dist/utils/latency-tracker.js +49 -0
  79. package/dist/utils/latency-tracker.js.map +1 -0
  80. package/dist/utils/logger.d.ts +5 -2
  81. package/dist/utils/logger.d.ts.map +1 -1
  82. package/dist/utils/logger.js +29 -6
  83. package/dist/utils/logger.js.map +1 -1
  84. package/dist/utils/path-jail.d.ts.map +1 -1
  85. package/dist/utils/path-jail.js +10 -1
  86. package/dist/utils/path-jail.js.map +1 -1
  87. package/package.json +96 -79
package/CHANGELOG.md CHANGED
@@ -1,774 +1,825 @@
1
- # Changelog
2
-
3
- All notable changes to NREKI will be documented in this file.
4
-
5
- ## v7.1.2 - 9 Critical Patches
6
-
7
- ### Fixed
8
- - **Ghost Deletion** (`nreki-kernel.ts`): `mutatedFiles` now cleaned on rollback — prevents `commitToDisk()` from deleting real files that belonged to failed transactions
9
- - **searchRawCode exact match** (`database.ts`): Replaced `String.includes()` with `Set.has()` eliminates false positives (e.g. "id" no longer matches "width") and changes complexity from O(N) to O(1)
10
- - **Arrow function angleDepth** (`parser.ts`): `=>` operator no longer decrements `angleDepth` below 0 — prevents extracting entire arrow function bodies as "signatures" in the repo map
11
- - **Circuit Breaker exception visibility** (`circuit-breaker.ts`): `wrapWithCircuitBreaker` now catches handler exceptions via try/catch and converts them to `McpToolResponse` with `isError: true` — breaker is no longer blind to ENOENT loops and timeout cascades
12
- - **Prompt cache preservation** (`router.ts`): Context Heartbeat now injected AFTER original text for all actions (not just `map`) — preserves Anthropic prefix cache hit rate
13
- - **clearChunks files table** (`database.ts`): `clearChunks()` now also deletes from `files` table prevents permanent invisibility when a file is deleted and recreated with the same content
14
- - **splitParams string-aware** (`shadow-generator.ts`): `splitParams()` now tracks string state (single, double, backtick quotes) — prevents splitting on commas inside string literals that produce broken `.d.ts` output
15
- - **LSP sidecar listener cleanup** (`lsp-sidecar-base.ts`): `proc.on("error")` handler now removes exit/SIGINT/SIGTERM listeners — prevents `MaxListenersExceededWarning` and memory leak on repeated spawn failures
16
- - **macOS case-insensitive file lock** (`file-lock.ts`): `normalizeLockKey` now treats `darwin` same as `win32` (lowercase) — prevents file corruption from parallel locks on `App.ts` vs `app.ts` on macOS APFS
17
-
18
- ### Changed
19
- - Tests: 696 704 (8 new tests for patch coverage)
20
- - CI: replaced hardcoded `grep "696 passed"` with JSON reporter validation (no more brittle test count checks)
21
-
22
- ## v7.0.0 - Software Physics Engine
23
-
24
- ### Added
25
- - **Fiedler Vector extraction**: `analyzeTopology` now returns the full eigenvector `v2` (bridge fragility map)
26
- - **Third eigenvalue (λ₃)**: Enables spectral gap computation ∇(λ₃ - λ₂) for predictive analysis
27
- - **Third eigenvector (v3)**: Topological stress coordinates per node
28
- - **Gauge Fixing**: Deterministic phase canonicalization prevents sign ambiguity across commits (critical for ML pipelines)
29
- - **Gram-Schmidt deflation**: Reusable `powerIteration()` function extracts arbitrary eigenvectors
30
- - **nodeIndex passthrough**: `SpectralTopologist.analyze()` now returns the symbol→index mapping
31
- - **Monorepo workspace resolution**: `buildFastLookup` resolves `@org/package` imports via O(1) string math (supports packages/, workspaces/, libs/, apps/)
32
- - **Adaptive Shotgun Surgery threshold**: Scales with repo size via `Math.max(8, floor(N × 0.015))` no more false positives on large codebases
33
- - **Modern module extensions**: Full `.mts`, `.cts`, `.mjs`, `.cjs` support across parser, kernel, repo-map, and JIT holography
34
-
35
- ### Fixed
36
- - **VFS zombie state**: `commitToDisk()` now purges VFS on disk write failure, preventing ghost content desync
37
- - **WASM race conditions**: Serialized language loading via `loadGate` in parser.ts, ast-sandbox.ts, parser-pool.ts
38
- - **Power iteration seed**: Uses data-dependent post-mutation seed for deterministic convergence
39
- - **extractName regex purge**: Replaced 20 fragile regex patterns across 2 files with AST-first keyword-stripping word splitter
40
- - **32 audit fixes (v6.1.x)**: Shadow codegen, TTRD amnesty bypass, orphan .tmp leak, Python indentation, splice duplicate detection, WeakMap middleware, syncTechDebt phantom accumulation, undo key normalization, APFS locks, allocUnsafe, SharedArrayBuffer isolation, OOM streaming iterator, and more
41
-
42
- ### Changed
43
- - License changed from MIT to Apache 2.0
44
- - Tests: 696 tests (→ 704 in v7.1.2)
45
- - Vitest upgraded from 3.0.7 to 4.1.1
46
- - `detectMode` now returns "file" mode for 50-200 file projects (correct performance scaling)
47
- - `isTypeScriptFile` respects `allowJs` config (prevents false errors in strict projects)
48
- - Circuit breaker tool detection updated for v3.0+ action names
49
- - File lock timeout extended to 5 minutes for large batch edits
50
-
51
- ### Internal
52
- - `SpectralResult` interface extended with optional `v2`, `lambda3`, `v3`, `nodeIndex` fields (backward compatible)
53
- - Power iteration limit raised from 100 to 150 (convergence guard unchanged at 1e-7)
54
- - Chronos Miner v2: Tree-sitter based temporal dataset extractor (zero node_modules, resumable, architectural dispersion ground truth)
55
- - Worktree isolation: each miner uses `/tmp/nreki-wt-{repo}` for parallel mining
56
-
57
- ## v6.1.0 - Spectral Gate + Surgical Architecture (2026-03-22)
58
-
59
- ### Performance
60
- - CSR sparse matrix with fused Rayleigh quotient in SpMV power iteration (L1 cache friendly)
61
- - Pre-computed sourceFile/targetFile on TopologicalEdge eliminates millions of split("::") allocations
62
- - fd-based incremental log reading in TokenMonitor (no more full-file readFileSync)
63
- - In-place ring buffer (shift) and TTL eviction (splice) in CircuitBreakerzero array allocations per tool call
64
- - Radical AST pruning in findDependencies: 8 node types short-circuited, arrow/fn bodies skipped
65
- - Eliminated redundant extractConstraintGraph calls in benchmark O(E) RAM filtering
66
-
67
- ### Spectral Gate
68
- - Density-weighted Phi = lambda2 * (2V / (N*(N-1))) for star topology detection
69
- - Conditional formula: density when N unchanged (ghost/expansion), original lambda2/N when N decreases (decoupling)
70
- - 11/11 real-world projects ALL PASS: 55/55 detection, 0/55 false positives, max 95.8ms
71
-
72
- ### Security
73
- - NFC Unicode normalization in safePath prevents macOS NFD bypass of .env blocklist
74
- - Removed settings.py and wp-config.php from sensitive file blocklist (false positives for Django/WordPress)
75
- - healingStats encapsulated behind private field + readonly getter
76
- - CircuitBreaker accepts projectRoot in constructor instead of dynamic process.cwd()
77
- - Middleware singletons encapsulated in CircuitBreakerMiddleware class
78
-
79
- ### Bug Fixes
80
- - Hologram Shield 2 now evaluates semantic diagnostics on dependents, not just edited files
81
- - TTRD: removed truncated typeStr bypass TypeFlags toxicity is sole authority
82
- - applySemanticSplice: closest-match indexOf picks nearest occurrence to AST offset
83
- - stripCallStatements: regex lastIndex advanced to prevent overlapping matches on nested calls
84
- - Surgical JIT cache invalidation in rollbackAll only edit targets cleared, not entire cache
85
- - DocumentRegistry + LanguageService recreated on corruption to prevent OOM
86
- - Safe slice in applySemanticSplice caps indent stripping at actual whitespace
87
- - jitClassifyFile size guard (150KB) prevents event loop blocking on auto-generated files
88
- - perFileFailures GC synced with history TTL eviction
89
- - Centralized backup files in .nreki/transactions/ directory
90
- - Windows fingerprint POSIX normalization in getFingerprint
91
- - BOM-safe readSource in jitClassifyFile
92
-
93
- ### Code Quality
94
- - PorterStemmer extracted to src/utils/porter-stemmer.ts
95
- - Deduplicated escapeRegex in database.ts (uses escapeRegExp from utils/imports)
96
- - detectMode filters .d.mts/.d.cts files
97
- - detectLanguage supports .mts/.cts/.mjs/.cjs extensions
98
- - Deprecation warnings on TokenGuardEngine and TokenGuardDB aliases
99
- - CLAUDE.md externalized to templates/CLAUDE.md
100
- - noUnusedLocals and noUnusedParameters enabled 14 dead code items removed
101
- - Test parallelism enabled (fileParallelism: true)
102
- - CI: npm audit, npm run lint, continue-on-error for Node 24
103
- - inferSimpleType returns "unknown" instead of "any" in shadow generation
104
- - Cache format versioning (CACHE_FORMAT_VERSION) in repo-map
105
- - mtimeMs included in computeFileDigest for stale cache detection
106
- - isEnvironmentFile uses exact basename matching instead of substring
107
-
108
- ### Benchmarks (11 projects, 55 test cases)
109
-
110
- | Project | Files | Nodes | Edges | Max Latency | FN | FP | Result |
111
- |---------|-------|-------|-------|-------------|----|----|--------|
112
- | NREKI | 38 | 195 | 373 | 44.0ms | 0/5 | 0/5 | ALL PASS |
113
- | Zod | 195 | 2,251 | 6,242 | 32.2ms | 0/5 | 0/5 | ALL PASS |
114
- | tRPC | 89 | 828 | 1,790 | 41.3ms | 0/5 | 0/5 | ALL PASS |
115
- | Prisma | 1,970 | 3,546 | 5,319 | 7.7ms | 0/5 | 0/5 | ALL PASS |
116
- | ts-pattern | 18 | 360 | 1,425 | 10.0ms | 0/5 | 0/5 | ALL PASS |
117
- | Next.js | 1,445 | 5,024 | 7,589 | 27.0ms | 0/5 | 0/5 | ALL PASS |
118
- | Hono | 186 | 1,414 | 10,188 | 35.7ms | 0/5 | 0/5 | ALL PASS |
119
- | Drizzle ORM | 447 | 3,521 | 17,021 | 70.3ms | 0/5 | 0/5 | ALL PASS |
120
- | date-fns | 1,238 | 1,905 | 3,129 | 15.2ms | 0/5 | 0/5 | ALL PASS |
121
- | VS Code | 4,697 | 24,204 | 111,994 | 29.1ms | 0/5 | 0/5 | ALL PASS |
122
- | Effect | 362 | 10,935 | 72,723 | 95.8ms | 0/5 | 0/5 | ALL PASS |
123
-
124
- ## [6.0.1] - 2026-03-21
125
-
126
- ### Fixed
127
- - `NrekiDB.save()` and `NrekiDB.close()` guard against double-close during graceful shutdown
128
- - `file-lock.test.ts` platform guard for case-insensitive path test (macOS/Linux CI)
129
- - CI matrix expanded to Node 20, 22, 24
130
-
131
- ## [6.0.0] - 2026-03-19
132
-
133
- ### Added
134
- - **Holographic Pruning**: New performance mode for large projects (>1000 files).
135
- Replaces full `.ts` source files with lightweight `.d.ts` shadow stubs in the
136
- TypeScript compiler's VFS, dramatically reducing boot time and memory usage.
137
- - Shadow Generator (`src/hologram/shadow-generator.ts`): Tree-sitter based file
138
- classifier and `.d.ts` generator. Classifies exports as prunable (explicit types)
139
- or unprunable (inferred types). Uses AST walking, not regex.
140
- - Shadow Cache (`src/hologram/shadow-cache.ts`): Disk persistence for shadows
141
- with mtime/hash staleness detection and version guard invalidation.
142
- - Symbiotic Harvester (`src/hologram/harvester.ts`): Extracts real `.d.ts` from
143
- the TypeScript compiler during idle time, replacing heuristic shadows with
144
- compiler-grade ones. Cooperative scheduler with epoch-aware abort.
145
- - Lazy Subgraph Loading: Kernel boots with only ambient files in rootNames.
146
- Target files are added dynamically during `interceptAtomicBatch()`.
147
- - Pre-warming: Background shadow scan starts after MCP handshake, before first edit.
148
- - Domain Separation: `predictBlastRadius` disabled in hologram mode (use Layer 1
149
- AST navigator for reference queries).
150
- - **JIT Holography**: Eliminates upfront `scanProject()`. Shadows generated
151
- on-demand when TypeScript's module resolver requests files. Cold boot
152
- drops from 22.96s to 1.94s on VSCode (5,584 files). Only 642 of 5,584
153
- files are ever classified the rest are never touched.
154
- - `NrekiKernel.setShadows()` - receive shadow scan results before boot
155
- - `NrekiKernel.hasShadows()` - check if shadows are loaded
156
- - `NrekiKernel.setJitParser()` - inject Tree-sitter parser for on-demand use
157
- - `NrekiKernel.setJitClassifier()` - inject classification function
158
- - `NrekiKernel.hasJitHologram()` - check if JIT mode is available
159
- - `NrekiKernel.getJitCacheSize()` - report on-demand classification count
160
- - `NrekiKernel.getLogicalTime()` - monotonic clock for harvester epoch detection
161
- - `NrekiKernel.getProgram()` - access TypeScript Program for harvester .d.ts emission
162
- - `NrekiMode` type extended with `"hologram"`
163
- - `detectMode()` returns `"hologram"` for projects with >1000 source files
164
-
165
- ### Changed
166
- - VFS hooks in `NrekiKernel.boot()` now include hologram intercepts (BEFORE existing
167
- VFS checks) for `fileExists`, `readFile`, and `getScriptSnapshot`
168
- - `getFatalErrors()` semantic cascade evaluation now runs for both `project` and
169
- `hologram` modes
170
- - `RouterDependencies.nrekiMode` type includes `"hologram"`
171
- - Deferred boot in router handles hologram mode (scan before boot if pre-warm incomplete)
172
-
173
- ### Tests
174
- - 60 new tests across 7 test files:
175
- - `tests/hologram-shadow-generator.test.ts` (19 tests)
176
- - `tests/hologram-vfs.test.ts` (8 tests)
177
- - `tests/hologram-lazy-subgraph.test.ts` (5 tests)
178
- - `tests/hologram-domain-separation.test.ts` (3 tests)
179
- - `tests/hologram-harvester.test.ts` (6 tests)
180
- - `tests/hologram-integration.test.ts` (4 tests)
181
- - `tests/jit-holography.test.ts` (15 tests)
182
-
183
- ## [5.3.0] - 2026-03-18
184
-
185
- ### Added
186
- - **Temporal Type Regression Detection (TTRD)**: Detects when an AI agent weakens
187
- type contracts to bypass the TypeScript compiler.
188
- - Uses TypeChecker API to read compiler-resolved types, not AST text. Catches
189
- inferred type escape (`as any` in expressions) and alias weakening
190
- (`type X = any` where function signatures stay identical).
191
- - Pre/Post comparison within the same ACID transaction. No global baseline needed.
192
- - Barrel file guard: skips re-exported symbols, processes local declarations only.
193
- - Type string safety: default truncation (no NoTruncation flag), 500-char hard limit.
194
- - Submodular penalty: log2 scaling prevents cascading errors from blocking files.
195
- - Debt ledger: stores original strict types for future restoration guidance.
196
- - Debt payment: restoring strict types clears debt records and reduces friction.
197
- - Ghost debt cleanup: deleted symbols cancel their debt automatically.
198
- - Per-file regression tracking in batch edits (no friendly fire).
199
- - `NrekiKernel.extractCanonicalTypes()` - TypeChecker-based export type extraction
200
- - `NrekiKernel.computeTypeRegressions()` - Pre/Post contract comparison
201
- - `NrekiKernel.resolvePosixPath()` - public path normalization
202
- - `ChronosMemory.recordRegressions()` - submodular penalty with debt ledger
203
- - `ChronosMemory.assessDebtPayments()` - debt forgiveness on type restoration or deletion
204
- - `NrekiInterceptResult.regressions` - regression evidence per intercept
205
- - `NrekiInterceptResult.postContracts` - post-edit type contracts for debt assessment
206
- - `TypeRegression.filePath` - per-file attribution for batch edit accuracy
207
-
208
- ### Tests
209
- - 19 new tests in `tests/ttrd.test.ts`
210
- - extractCanonicalTypes, regression detection, false positive guards, barrel file guard,
211
- type string limits, submodular penalty, debt ledger persistence, debt payment,
212
- ghost debt, JIT warnings, happy path detection, pre/post baseline, healed path,
213
- batch edit attribution, batch debt payment, no-success-on-regression
214
- - **Performance Modes**: Auto-detection of validation depth based on project size.
215
- - `syntax` mode (< 50 files): Kernel disabled. Tree-sitter only.
216
- - `project` mode (50-1000 files): Full cross-file semantic validation with early exit.
217
- - `file` mode (> 1000 files): Semantic checks on edited files only. No cascade.
218
- - Mode auto-detected via bounded DFS file counter in ~85ms.
219
- - Deferred boot: kernel boots on first edit, not at startup. MCP server starts in 0ms.
220
- - Early exit in project mode: stops evaluating after threshold errors (50 + 20 per edited file).
221
- - Corrupted builder recovery via warm rebuild (~2-5s) after early exit.
222
- - Global noise filter: ignores diagnostic noise from missing @types when editing source files.
223
- - Toxicity scoring for TTRD: detects parameter-level regressions (RetryConfig to any).
224
- - Structural collapse detection: catches Promise<any> to any.
225
- - **VSCode Benchmark (file mode)**: 5,584 files, 91.6s boot, 4.5GB RAM, 0 OOM crashes.
226
- - Test A (safe edit): PASS, 23s
227
- - Test B (local type break): CAUGHT, 25 errors in event.ts, 55s
228
- - Test C (TTRD): CAUGHT via compilation, 1 error, 41s
229
- - Test D (IDisposable): CAUGHT, 29 local errors in lifecycle.ts, 98s
230
- - Previous project mode: 644s latency, 35,704 errors, OOM crashes
231
-
232
- ### Tests
233
- - 20 new tests in `tests/mode-modes.test.ts` (mode detection, syntax/file/project behavior, early exit, recovery, elastic threshold, global noise, TTRD toxicity)
234
- - 1 new test in `tests/ttrd-silent-crime.test.ts` (silent type degradation)
235
- - Total: 590 tests across 29 suites, 0 failures
236
-
237
- ---
238
-
239
- ## [5.2.0] - 2026-03-18
240
-
241
- ### Added
242
- - **Chronos Memory**: Cross-session file error tracking with Cognitive Friction Index (CFI)
243
- - Exponential decay (λ=0.85) - file friction reduces 15% per clean session
244
- - Success discount - successful edits on high-friction files halve their CFI score
245
- - JIT warnings - error history appears only when reading/editing affected files
246
- - Edit gating - high-friction files require uncompressed read before editing
247
- - Blast radius tracking - error penalties go to files where errors occur, not the edited file
248
- - Dead file cleanup - deleted files are removed from tracking on session start
249
- - Baseline cache reuse - O(1) error counting without compiler invocation
250
- - Crash-safe persistence with debounced atomic writes
251
- - `NrekiKernel.getInitialErrorCount()` - immutable boot-time error snapshot
252
- - `NrekiKernel.getCurrentErrorCount()` - O(1) via baseline cache
253
- - Global Health Delta tracking (ΔH = current errors - boot errors)
254
- - **Chronos Health Score** in `nreki_guard action:"report"` output
255
- - Circuit breaker trips now feed Chronos CFI automatically
256
-
257
- ### Tests
258
-
259
- - 16 new tests in `tests/chronos-memory.test.ts`
260
- - Constructor, recordTrip/Error/Heal/Success, isHighFriction, passive decay, GC, dead file cleanup, persistence, health report, blast radius tracking
261
-
262
- ---
263
-
264
- ## v5.1.0 - Zero-Token Error Correction (2026-03-17)
265
-
266
- ### New: NREKI L3.3 Auto-Healing Engine
267
-
268
- When the LLM's edit introduces structural errors (missing imports, forgotten `async` keyword, incomplete interface implementations), NREKI now **auto-corrects them in RAM** using TypeScript's CodeFix API - the same engine that powers VS Code's "Quick Fix" lightbulb. The LLM never sees the error. Zero tokens wasted.
269
-
270
- - **`attemptAutoHealing()`**: Iterative fix-recompile loop inside `interceptAtomicBatch()`. Applies one CodeFix at a time, recompiles the universe (~20ms), checks if errors decreased, and either accepts or micro-rollbacks.
271
- - **Error reduction rule**: Every fix must reduce total error count. If a fix leaves the same errors or more, it is reverted and blacklisted.
272
- - **SAFE_FIXES whitelist**: Only deterministic structural fixes are applied - never type mutations or business logic changes:
273
- - `import` / `fixMissingImport` - adds forgotten imports
274
- - `fixAwaitInSyncFunction` - adds `async` when LLM wrote `await` without it
275
- - `fixPromiseResolve` - wraps returns in `Promise.resolve()`
276
- - `fixMissingProperties` - auto-implements required interface properties
277
- - `fixClassDoesntImplementInheritedAbstractMember` - implements abstract methods
278
- - `fixAddMissingMember` - declares missing class properties
279
- - `fixAddOverrideModifier` - adds `override` keyword
280
- - **Micro-rollback per fix**: Each fix has its own undo-log. Failed fixes revert without affecting successful ones.
281
- - **Macro-rollback on partial failure**: If not ALL errors are resolved, the entire healing attempt is undone and the original errors are returned to the LLM intact.
282
- - **Patch protection**: On successful healing, the response tells the agent not to overwrite the auto-applied fixes in the next edit.
283
- - **`healedFiles` in response**: Router creates `nreki_undo` backups for collateral files the healer touched.
284
- - **`healingStats`**: Public counter tracking `applied` and `failed` healing attempts.
285
-
286
- ### New: `getFatalErrors()` - Centralized Triple Shield
287
-
288
- Extracted the 3-shield evaluation logic (Global → Syntactic → Semantic) into a reusable private method. Both `interceptAtomicBatch()` and `attemptAutoHealing()` use it, eliminating code duplication.
289
-
290
- ### Bug Fixes
291
-
292
- - **`ts.emptyOptions` doesn't exist in TS 5.9**: Replaced with `{} as ts.UserPreferences`.
293
-
294
- ### Tests
295
-
296
- - **526 tests**, 25 suites, zero failures, zero regressions
297
- - New: `tests/auto-healing.test.ts` -6 tests covering:
298
- - Missing import auto-healed `safe: true` disk has import
299
- - `await` without `async`, callers healthy auto-healed `safe: true`
300
- - `await` without `async`, callers break cascade detected micro-rollback → `safe: false`
301
- - Business logic error (no CodeFix) → healing skipped → `safe: false`
302
- - `healingStats` counter verification
303
- - Clean code healing not triggered → `safe: true` without heal text
304
-
305
- ---
306
-
307
- ## v5.0.0 - The NREKI Kernel (2026-03-16)
308
-
309
- ### New: NREKI Kernel (Layer 2 - Cross-File Semantic Verification)
310
-
311
- - **VFS-LSP Kernel**: Hijacks TypeScript Compiler API with a Virtual File System in RAM. Edits are validated against the entire project's type system before reaching disk.
312
- - **True ACID Transactions**: `interceptAtomicBatch()` validates in RAM; `commitToDisk()` writes via two-phase atomic commit (backup → temp+rename → cleanup) with physical rollback on OS failure.
313
- - **Zero Disk Touch**: When the kernel is active, `semanticEdit()` operates in `dryRun` mode. The disk is immutable until semantic validation passes.
314
- - **Triple Shield**: Global diagnostics → Syntactic diagnostics → Semantic diagnostics. Catches broken syntax AND cross-file type errors.
315
- - **Predictive Blast Radius**: `predictBlastRadius()` uses `ts.LanguageService.findReferences()` to show what will break and WHY before the agent edits. ~20ms per query.
316
- - **PageRank Architecture Scoring**: Files classified by recursive importance via Markov Chain Power Iteration (damping factor 0.85, 20 iterations, <8ms convergence for 1,000 files). Replaces naive inDegree classification.
317
- - **Warm-Path Optimization**: Failed intercepts advance the monotonic clock instead of destroying the builder program. Rollback drops from ~10s to ~50ms.
318
- - **Path Jail at Kernel Level**: `interceptAtomicBatch()` rejects paths that resolve outside the project root.
319
- - **O(1) Virtual Directory Resolution**: `vfsDirectories` Set replaces O(n) VFS scan in `directoryExists`.
320
- - **LanguageService Integration**: VS Code's reference engine connected to the VFS for JIT lazy evaluation.
321
-
322
- ### Renamed: TokenGuard NREKI
323
-
324
- - npm package: `@ruso-0/tokenguard` `@ruso-0/nreki`
325
- - Tool names: `tg_navigate` `nreki_navigate`, `tg_code` `nreki_code`, `tg_guard` `nreki_guard`
326
- - Database: `.tokenguard.db` `.nreki.db`
327
- - Pins: `.tokenguard-pins.json` `.nreki-pins.json`
328
- - Backups: `.tokenguard-backup/` `.nreki-backup/`
329
- - Server name: `TokenGuard` `NREKI`
330
-
331
- ### Security Hardening (30/30 Audit Findings Resolved)
332
-
333
- - **A1**: Kernel path jail blocks traversal attempts (`../../etc/passwd`)
334
- - **A2**: Write-Then-Validate eliminated - now Validate-Then-Write via dryRun
335
- - **A3**: Zombie mutex (`withTimeout`/`Promise.race`) deleted entirely
336
- - **A4**: Sensitive file blocklist expanded (+8 patterns: docker, kube, netrc, htpasswd, etc.)
337
- - **A5**: `node_modules` filter uses path segment regex, not substring match
338
- - **A6**: Kernel returns relative paths in error messages, not absolute
339
- - **A8**: Pin sanitization adds Unicode normalization (NFKC) + null byte rejection
340
- - **A9**: Prototype pollution guard on pin JSON.parse
341
- - **A10**: Kernel readFile blocks sensitive files (.env, .pem, .key) in disk fallback
342
- - **B1**: `commitToDisk()` resurrected as the only write path when kernel is active
343
- - **B2**: `isTypeScriptFile` regex expanded to `.mts`, `.cts`, `.mjs`, `.cjs`, `.d.mts`, `.d.cts`
344
- - **B4**: Double-boot guard added to `boot()`
345
- - **B5**: Pre-boot guard added to `interceptAtomicBatch()`
346
- - **B6**: `logicalTime` saved and restored on rollback
347
- - **B7**: Fingerprint hash upgraded from MD5 to SHA-256
348
- - **B8**: GC threshold made configurable (`gcThreshold` property)
349
- - **C4**: Heartbeat skipped during circuit breaker escalation 2
350
- - **C5**: Version read from `package.json` at runtime (no hardcoded string)
351
- - **D1**: Pin file writes use atomic temp+rename pattern
352
- - **D2**: Orphaned `.nreki-bak-*` files cleaned on kernel boot
353
- - **D4**: Token estimation margin documented (20-40% variance)
354
- - **E1**: `directoryExists` uses O(1) Set lookup instead of O(n) VFS scan
355
-
356
- ### Tests
357
-
358
- - **520 tests**, 24 suites, zero failures
359
- - New: `tests/nreki-kernel.test.ts` -22 kernel unit tests (boot, semantic validation, syntactic shield, baseline tolerance, file operations, ACID, concurrency, edge cases)
360
- - New: `tests/nreki-integration.test.ts` -8 integration tests (dryRun, full commit path, type-break blocked, batch VFS, path traversal rejection)
361
- - New: PageRank tests (recursive importance, convergence <50ms for 1,000 files)
362
- - New: Precision tests (VFS staging leak, node_modules filtering, restore failure handling)
363
-
364
- ### Benchmark: OpenDota (148 files, 1,600+ stars)
365
-
366
- - 6/6 correct verdicts (valid edit, type break, syntax break, file delete, non-TS file)
367
- - Zero false positives, zero false negatives
368
- - Boot: 10.68s | Type break detection: 12.6s | Syntax detection: 11.4s
369
-
370
- ### 32 Sealed Failure Modes (P1-P32)
371
-
372
- P2 (atomic commit), P4 (dynamic rootNames), P5 (tombstone), P8 (monotonic clock), P9 (topological cardinality), P10 (FIFO mutex), P11 (periodic GC), P15 (path sanitization), P17 (zombie AST), P18 (destruction & resurrection), P19 (counter reset), P21 (multi-file deadlock), P25 (idempotent undo-log), P26 (POSIX normalization), P27 (recursive mkdir), P28 (syntactic blindness), P29 (TS6053 ghost), P30 (non-TS filter), P31 (virtual directories), P32 (physical rollback).
373
-
374
- ## [4.0.2] - 2026-03-13
375
-
376
- ### Fixed (Logic)
377
- - **Blind Sniper**: `prepare_refactor` only searched function signatures (BM25 shorthand index), missing symbols used inside function bodies. Now uses exhaustive `raw_code` SQL scan for 100% coverage. Also added `property_identifier` and `shorthand_property_identifier` to the AST node type filter.
378
- - **Batch Edit Race Condition**: `batch_edit` had no file locks. Concurrent `edit` + `batch_edit` on the same file could corrupt it. Added two-phase locking (acquire all or rollback all, release in finally).
379
- - **indexOf Wrong Function**: `applySemanticSplice` fallback searched from byte 0, could edit the wrong function when duplicates exist. Now searches in a ±500 byte local window around the AST-reported position first.
380
- - **extractSignature String Confusion**: `{` inside string literals (e.g., `msg = "{"`) was mistaken for function body start, truncating signatures. Added string-state tracking to skip characters inside quotes.
381
- - **Silent Plan Amnesia**: Plans exceeding 15,000 characters were silently dropped. Now injects a visible WARNING telling Claude to summarize the plan.
382
-
383
- ### Fixed (Documentation)
384
- - Updated `index.ts` docstring from v3.3.0 to v4.0.2.
385
- - Rewrote `skills/SKILL.md` with v4 tool names and features (batch_edit, prepare_refactor, blast radius, architecture tiers).
386
- - Updated `getClaudeMdContent()` (CLAUDE.md init) with v4 features.
387
- - Changed "vs full file rewrite" to "vs native read+edit" in response messages.
388
- - Changed "Saves 98%" claim to "60-80%" in semantic-edit docstring.
389
- - Eliminated double file read in handleEdit by returning oldRawCode from semanticEdit.
390
- - Updated preToolUse.ts docstring to use v4 tool names.
391
-
392
- ## [4.0.1] - 2026-03-13
393
-
394
- ### Fixed
395
- - **Inflated `tokensAvoided` metric**: `semanticEdit()` was computing savings as `fullFile × 2 - newCode`, which double-counted the file read. Corrected to `fullFile + oldSymbol - newCode` (read file + old symbol code that Claude would have sent).
396
- - **Router docstring version**: Updated from v3.3.0 to v4.0.0 and added `batch_edit` and `prepare_refactor` to the tool action listings.
397
- - **Batch edit blast radius missing dependents**: `handleBatchEdit()` now queries the dependency graph to list files that import edited modules, matching the behavior of single-file `handleEdit()`.
398
-
399
- ## [4.0.0] - 2026-03-12
400
-
401
- ### BREAKING CHANGES
402
- - **`symbolName` extracted from AST**: Parser now uses tree-sitter `@_name` captures instead of ~10 fragile regexes. `ParsedChunk` interface adds `symbolName: string`. Database schema adds `symbol_name`, `start_index`, `end_index` columns (auto-migrated for existing DBs).
403
-
404
- ### Added
405
- - **`nreki_code action:"batch_edit"`**: Atomically edit multiple symbols across multiple files. Uses Virtual File System in RAM with reverse splice ordering (descending startIndex) to avoid byte offset corruption. All-or-nothing: if ANY file fails AST validation, NOTHING is written to disk.
406
- - **Architecture Map**: `nreki_navigate action:"map"` now includes dependency graph with import centrality classification. Files are tiered by in-degree percentile: P75+ = "core", P50-P75 = "logic", <P50 = "leaf". Uses O(1) FastLookup index for import resolution (relative paths, `@/` aliases, extensionless, index.ts implicit).
407
- - **Blast Radius Detection**: When `nreki_code action:"edit"` changes a function's signature (parameters, return type), NREKI warns which files import that symbol. Suggests `batch_edit` to update dependents. Also applies to `batch_edit`.
408
- - **`nreki_navigate action:"prepare_refactor"`**: AST-based confidence classification for safe renaming. Walks tree-sitter syntax nodes and classifies each occurrence as "high" confidence (safe to rename) or "review" (inside strings, comments, object keys, JSX text). Returns a formatted report with two sections.
409
- - **`parseRaw<T>()`**: Public method on `ASTParser` for raw tree-sitter tree access via callback pattern with guaranteed WASM memory cleanup.
410
- - **`DependencyGraph` interface**: `importedBy`, `inDegree`, and `tiers` maps exported from `repo-map.ts`.
411
- - **`buildFastLookup()`**: O(1) import resolution mapping extensionless, src/-stripped, and index-collapsed variants to actual file paths.
412
- - **`detectSignatureChange()`**: Pure function comparing old/new signatures to detect parameter and return type changes.
413
- - **`findChunkBySymbol()`**: Extracted pure function preferring `chunk.symbolName` (AST) with `extractName()` regex fallback.
414
- - **`applySemanticSplice()`**: Extracted pure splice function for reuse in both single and batch edits.
415
-
416
- ### Fixed
417
- - **Bug A - Stale docstring**: `engine.ts` header incorrectly referenced "sqlite-vec + FTS5". Updated to reflect actual implementation (pure-JS VectorIndex + BM25 KeywordIndex).
418
- - **Bug B - Multi-line console.log stripping**: Regex-based `console.log()` removal failed on multi-line calls. Replaced with `stripCallStatements()` using balanced parenthesis tracking. Same fix applied to Python `print()`.
419
- - **Bug C - Python `#` in strings**: Comment stripping destroyed `#` inside string literals (e.g., `color = "#FF0000"`). Fixed by reordering (triple-quotes first) and protecting single/double-quoted strings with placeholders before stripping comments.
420
- - **Bug D - Simplistic glob matching**: `walkDirectory` converted `**/node_modules/**` to `node_modules` via string replace, failing for patterns like `**/*.min.js`. Replaced with `picomatch` for proper glob matching.
421
-
422
- ### Changed
423
- - `semantic-edit.ts` refactored: extracted `applySemanticSplice()`, `findChunkBySymbol()`, `detectSignatureChange()` as pure functions.
424
- - `repo-map.ts` extended: `generateRepoMap()` now builds and caches dependency graph alongside repo map. `repoMapToText()` appends architecture tier summary.
425
- - Database schema: `chunks` table now stores `start_index`, `end_index`, `symbol_name` with migration for existing DBs.
426
- - Test count: 464 → 473 tests across 21 test suites.
427
-
428
- ### Dependencies
429
- - Added `picomatch` (runtime) and `@types/picomatch` (dev) for proper glob matching.
430
-
431
- ## [3.3.0] - 2026-03-13
432
-
433
- ### Added
434
- - **Context Heartbeat**: Silently re-injects critical session state
435
- every ~15 tool calls to survive Claude Code's context compaction. Uses 4-layer
436
- state re-injection:
437
- - Layer 1 (Plan File): Anchored plan document via `set_plan`
438
- - Layer 2 (Scratchpad): Claude's progress notes via `memorize` + pinned rules
439
- - Layer 3 (Recent Edits): Files modified in this session
440
- - Layer 4 (Circuit Breaker): Active escalation alerts if in Break & Build
441
- - **`nreki_guard action:"set_plan"`**: Anchor a master plan file (PLAN.md, schemas).
442
- Includes Bankruptcy Shield rejecting plans >4000 tokens to prevent context bloat.
443
- - **`nreki_guard action:"memorize"`**: Claude writes progress notes to persistent scratchpad.
444
- Notes survive context compaction and are re-injected during heartbeat.
445
- - **Top-injection pattern**: Heartbeat injects state ABOVE the tool response, keeping the
446
- immediate result at the bottom to respect the LLM's U-shaped attention curve.
447
- - **Read-only filter**: Heartbeat only fires during context-gathering actions
448
- (read, search, map, status, definition, references, outline). Never during
449
- edit, undo, or filter_output to avoid distracting Claude during critical operations.
450
- - **Restart Detection**: Heartbeat detects MCP server restarts (currentCalls < lastInjectCalls)
451
- and resets the injection counter to prevent permanent heartbeat death.
452
-
453
- ## [3.2.0] - 2026-03-13
454
-
455
- ### Added
456
- - **Auto-Context Inlining**: When Claude requests a definition or reads a file, NREKI
457
- automatically resolves signatures of imported dependencies and injects them in the response.
458
- Reduces follow-up tool calls by providing "X-ray vision" in a single turn.
459
- - Import extraction supports ESM (named + default), CommonJS require, Python from-import,
460
- and Go namespace inference.
461
- - "Gold Filter": only injects dependencies actually used in the function body, using the
462
- local alias name (not the original export name) for accurate matching.
463
- - Security filter: signatures containing passwords, API keys, auth tokens, or encryption
464
- keys are automatically excluded from injection.
465
- - Anti-prompt-injection: JSDoc comments and NREKI stubs are stripped from signatures
466
- before injection, preventing malicious content from entering Claude's context.
467
- - Homonym disambiguation: BM25 searches combine symbol name + import path hint to find
468
- the correct signature even when multiple files export the same name.
469
- - 150ms hard timeout prevents event loop blocking on large codebases.
470
- - `auto_context: false` parameter available on both `nreki_navigate` and `nreki_code` to disable.
471
- - Session report tracks `autoContextInjections` count.
472
- - **Go import support**: Auto-Context infers exported symbols from Go namespace usage patterns
473
- (e.g., `utils.HashPassword()` resolves to `HashPassword` in the `utils` package).
474
- - **Preloaded content in compressFileAdvanced**: Eliminates double file I/O when both
475
- auto-context and compression are active on the same read.
476
-
477
- ### Changed
478
- - `CompressionLevel` type is now used explicitly instead of `as any` for level casting.
479
- - `handleRead` reads the file exactly once and reuses the content for both auto-context
480
- extraction and compression.
481
-
482
- ## [3.1.3] - 2026-03-12
483
-
484
- ### Fixed
485
- - **Path normalization in Circuit Breaker**: All file paths are now resolved to absolute + forward slashes before recording. Prevents split counters where `"src/app.ts"` and `"/abs/path/src/app.ts"` were tracked as different files, causing Pattern 4 to never trigger.
486
- - **Ghost data after file deletion**: `db.save()` is now called after the watcher's `unlink` event, ensuring deleted files don't reappear from disk on next session.
487
- - **Plaintext fallback for unsupported languages**: Files with unsupported extensions (.rs, .java, .cpp, etc.) are now indexed as single plaintext chunks. BM25 keyword search works on all file types as documented in the README. AST features (validation, structural compression, semantic edit) still require TS/JS/Python/Go.
488
-
489
- ## [3.1.2] - 2026-03-12
490
-
491
- ### Fixed
492
- - **Duplicate JSDoc on softReset**: Removed stale v3.0 comment that contradicted actual behavior.
493
- - **Inflated grepEstimate**: Replaced arbitrary 3` multiplier with per-unique-file estimation. Added "(estimated)" to savings output.
494
- - **@xenova/transformers moved to optionalDependencies**: `npm install` no longer downloads ~200MB of ONNX runtime for Lite mode users. Pro mode users can install it separately with `npm install @xenova/transformers`.
495
-
496
- ## [3.1.1] - 2026-03-12
497
-
498
- ### Fixed
499
- - **Circuit breaker `redirectsIssued`**: No longer counts Level 3 hard stops as redirects.
500
- - **Circuit breaker `softReset` amnesia total**: Purges all history entries for the tripped file, giving Claude 3 clean attempts with the new strategy instead of 1.
501
- - **Breaker payloads instruct `compress:false`**: Level 1 and Level 2 redirects now tell Claude to read uncompressed code so it can understand the logic before rewriting.
502
- - **Smart rebase for Python/Go**: Auto-indentation now strips Claude's indent and rebases to the target context, fixing IndentationError in Python and tab corruption in Go.
503
- - **CRLF support**: Line start detection skips `\r` on Windows files.
504
- - **Cross-platform byte indices**: Verifies tree-sitter byte offsets against actual content, falls back to indexOf if they differ across platforms.
505
-
506
- ### Added
507
- - **Behavioral Advisor (PreToolUseHook)**: Connected to `handleRead` - when Claude reads a file raw (compress:false), it gets a suggestion showing how many tokens it wasted and the exact command to compress next time.
508
- - **Danger Zones in status**: `nreki_guard action:"status"` now shows the 5 heaviest unread files with estimated token counts. Files already read (raw or compressed) are filtered out dynamically.
509
- - **CLI `--help` and `--version`**: Standard CLI hygiene. Version sourced from single `VERSION` constant.
510
- - **Telemetry via social sharing**: Session report footer invites users to share their receipt on GitHub Discussions.
511
- - **E2E breaker test**: Full integration test simulating 3 failures → Level 1 redirect → grace period → recovery with insert_after.
512
- - **5 topological edit tests**: insert_after, insert_before, auto-indent nested, syntax rejection, last-symbol edge case.
513
-
514
- ### Removed
515
- - `evaluateGrepOperation` and `countFiles` from PreToolUseHook (unreachable via MCP).
516
- - `src/schemas.ts` (dead v2 code, zero imports).
517
- - All "BOMBA" comments replaced with professional descriptions.
518
-
519
- ### Changed
520
- - CLAUDE.md point 3 now includes quantitative advice (5,000 tokens vs 1,200 tokens).
521
- - `RouterDependencies.hook` is optional for backward compatibility.
522
- - `engine.markFileRead()` called in both compress and raw read branches.
523
-
524
- ## [3.1.0] - 2026-03-11
525
-
526
- ### Added
527
- - **Creative Circuit Breaker ("Break & Build")**: 3-level escalation system that redirects Claude with increasingly specific strategies instead of just blocking. Level 1: rewrite from scratch. Level 2: decompose into helpers. Level 3: hard stop, ask the human.
528
- - **`nreki_guard action:"reset"`**: Escape hatch for humans to clear the circuit breaker and let Claude retry with a new approach.
529
- - **`npx nreki init`**: CLI subcommand that generates a `CLAUDE.md` file with collaborative-tone instructions for Claude Code to prefer NREKI tools.
530
- - **Redirect statistics**: Session report now tracks `redirectsIssued` and `redirectsSuccessful` to measure creative breaker effectiveness.
531
-
532
- ### Performance
533
- - **Batch SQL queries**: `searchHybrid`, `searchKeywordOnly`, and `searchVector` now use `WHERE id IN (...)` batch queries instead of N+1 individual queries per chunk ID.
534
- - **BM25 TF precompute**: Term frequencies are precomputed at index time for O(1) lookup during search, replacing O(n) `filter()` scans.
535
-
536
- ### Changed
537
- - Circuit breaker `ToolCallRecord` now includes `symbolName` for contextual redirect payloads.
538
- - Circuit breaker `trip()` now escalates `escalationLevel` (0→3) instead of just setting a boolean.
539
- - `softReset()` preserves escalation level across retries, enabling progressive escalation.
540
- - All version strings aligned to 3.1.0.
541
-
542
- ### Tests
543
- - 438 tests (was 423). Added 15 new tests for escalation levels, redirect payloads, symbolName tracking, and soft/hard reset behavior.
544
-
545
- ---
546
-
547
- ## [3.0.3] - 2026-03-11
548
-
549
- ### Fixed
550
- - **CI macOS/Windows**: `safePath` now calls `realpathSync` on the workspace root as well as the resolved path, fixing false-positive "Symlink escape blocked" errors on macOS where `/tmp` is a symlink to `/private/tmp`. All 423 tests pass on all platforms.
551
-
552
- ---
553
-
554
- ## [3.0.2] - 2026-03-10
555
-
556
- ### Headline
557
- docs: fix README Quick Start syntax, update test count to 423, update keywords, add security documentation.
558
-
559
- ### Fixed
560
- - **README Quick Start**: Replaced v2 `options:{}` syntax with v3 flat params (`text:`, `symbol:`, `new_code:`, `output:`).
561
- - **README Quick Start**: Replaced `target:` with correct param names (`query:`, `symbol:`).
562
- - **README**: Renamed `terminal` `filter_output` in nreki_code actions table, comparison table, architecture diagram, and Quick Start.
563
- - **README**: Updated test count from 361 423 in title, badges, stress test section, and real-world validation.
564
- - **README**: Updated test suites from 14 → 16.
565
-
566
- ### Added
567
- - **README Security section**: Documented symlink resolution, sensitive file blocklist, pin sanitization, and file-level mutex.
568
-
569
- ### Changed
570
- - **package.json**: Updated keywords to reflect v3 security focus (`code-safety`, `ast-validation`, `circuit-breaker`, `defensive-coding`, `ai-safety`, `surgical-edit`).
571
- - **package.json**: Set author to `Ruso-0 (https://github.com/Ruso-0)`.
572
- - **package.json**: Version bumped to 3.0.2.
573
-
574
- ---
575
-
576
- ## [3.0.0] - 2026-03-10
577
-
578
- ### Headline
579
- NREKI v3.0 - Architecture overhaul. 16 tools collapsed to 3 routers. Invisible middleware. Lite/Pro mode. 81% reduction in tool definition overhead.
580
-
581
- ### BREAKING CHANGES
582
- - **16 tools → 3 router tools**: All MCP tool names have changed. LLMs must use the new `nreki_navigate`, `nreki_code`, `nreki_guard` tool names with `action` parameters.
583
- - **`nreki_validate` removed from MCP**: Now runs automatically as invisible middleware inside `nreki_code action:"edit"`. No manual calls needed.
584
- - **`nreki_circuit_breaker` removed from MCP**: Now runs as passive middleware monitoring all tool calls. Auto-resets after 60s inactivity or when a different action is called.
585
- - **`nreki_audit` removed from MCP**: Moved to CLI only. Use `npx @ruso-0/nreki --audit`.
586
-
587
- ### Added - Router Pattern
588
- - **`nreki_navigate`** - Unified navigation tool replacing `nreki_search`, `nreki_def`, `nreki_refs`, `nreki_outline`, `nreki_map`. Actions: `search`, `definition`, `references`, `outline`, `map`.
589
- - **`nreki_code`** - Unified code tool replacing `nreki_read`, `nreki_compress`, `nreki_semantic_edit`, `nreki_undo`, `nreki_terminal`. Actions: `read`, `compress`, `edit`, `undo`, `terminal` (renamed to `filter_output` in v3.0.2).
590
- - **`nreki_guard`** - Unified safety tool replacing `nreki_pin`, `nreki_status`, `nreki_session_report`. Actions: `pin`, `unpin`, `status`, `report`.
591
- - `src/router.ts` - Central dispatcher mapping `{tool, action}` to handler functions (~700 lines).
592
-
593
- ### Added - Invisible Middleware
594
- - `src/middleware/validator.ts` - AST validation wrapper. Validates code via tree-sitter before disk writes inside `nreki_code action:"edit"`.
595
- - `src/middleware/circuit-breaker.ts` - Passive circuit breaker. Wraps all handlers, records tool call results, trips on destructive patterns, auto-resets on action diversity or 60s inactivity.
596
-
597
- ### Added - Lite / Pro Mode
598
- - **Lite mode (default)**: Instant startup (~100ms). BM25 keyword-only search. No ONNX model dependency.
599
- - **Pro mode (`--enable-embeddings`)**: Hybrid semantic + BM25 search with RRF fusion. Requires ONNX Runtime for jina-v2-small embeddings.
600
- - `searchKeywordOnly()` method added to `NREKIDB` for Lite mode BM25 search.
601
- - Engine methods (`indexFile`, `indexDirectory`, `search`, `getRepoMap`) now branch based on `enableEmbeddings` config.
602
-
603
- ### Changed
604
- - **`src/index.ts`**: Rewritten from ~1,479 lines (16 tool registrations) to ~180 lines (3 router registrations).
605
- - **Tool definition overhead**: ~3,520 tokens → ~660 tokens (81% reduction).
606
- - **Test count**: 305 → 361 tests across 14 test suites.
607
- - **`package.json`**: Version bumped to 3.0.0. Description updated.
608
- - **`README.md`**: Complete rewrite for v3.0 architecture.
609
-
610
- ### Added - Tests
611
- - `tests/router.test.ts` - 30 tests for router dispatch correctness across all 14 `{tool, action}` pairs.
612
- - `tests/middleware.test.ts` - 13 tests for validator and circuit breaker middleware behavior.
613
- - `tests/backward-compat.test.ts` - 13 tests verifying all 16 original tool behaviors work through the new 3-tool API.
614
-
615
- ---
616
-
617
- ## [2.1.2] - 2026-03-10
618
-
619
- ### Headline
620
- NREKI v2.1.2 - Lazy ONNX loading fixes MCP handshake timeout for real-world users.
621
-
622
- ### Fixed
623
- - **CRITICAL - MCP handshake timeout**: `engine.initialize()` was eagerly loading the ONNX embedding model (~5-10s) during startup, blocking ALL tool calls until the model was ready. Real users connecting via Claude Code would experience timeouts or slow first responses. Split initialization into two phases:
624
- - **Fast path** (`initialize()`): SQLite + Tree-sitter only (~100ms). Used by 12/16 tools.
625
- - **Embedder path** (`initializeEmbedder()`): Adds ONNX model load. Used only by `nreki_search`, `nreki_map`, and indexing operations.
626
- - **`nreki_def` first-call latency**: Was 465ms because it waited for the embedder to load (which it doesn't use). Now completes in ~50ms on first call.
627
- - Removed background `engine.initialize()` from `main()` - tools now self-initialize at the correct level when first called.
628
-
629
- ### Changed
630
- - **package.json**: Version bumped to 2.1.2.
631
-
632
- ---
633
-
634
- ## [2.1.1] - 2026-03-10
635
-
636
- ### Headline
637
- NREKI v2.1.1 - Final audit fixes, nreki_undo, 16 tools, 305 tests.
638
-
639
- ### Added - New Tool
640
- - **`nreki_undo`** - Undo the last `nreki_semantic_edit` on a file. Auto-restores from backup with one-shot semantics (backup is consumed after restore).
641
-
642
- ### Added - New Module
643
- - `src/undo.ts` - Backup/restore engine using base64url-encoded file paths. Stores pre-edit snapshots in `.nreki/backups/`.
644
- - `src/utils/read-source.ts` - Shared BOM-safe file reader. Strips U+FEFF byte order marks from Windows-created source files.
645
-
646
- ### Security
647
- - **FIX 2 - XML injection prevention**: Pin content is now escaped (`&`, `<`, `>`, `"`, `'`) before storage to prevent prompt injection via pinned rules.
648
-
649
- ### Fixed
650
- - **FIX 1 - BOM stripping**: All source file readers now use `readSource()` to strip U+FEFF BOM, fixing parse failures on Windows-created files.
651
- - **FIX 3 - Code tokenizer**: Rewritten to correctly handle `$scope`, `__proto__`, `_privateVar`, and other edge-case identifiers with `$`/`_` prefixes.
652
- - **FIX 4 - Fast dot product**: Replaced cosine similarity with direct dot product for L2-normalized vectors. Removes sqrt/division overhead; mathematically equivalent for unit vectors.
653
- - **FIX 6 - Pin order**: Pinned rules now appear AFTER repo map text (was before). Preserves Anthropic prompt cache hits since the static map stays at the start of context.
654
- - **FIX 7 - Circuit breaker normalization**: `hashError()` now normalizes ISO timestamps and improved memory address normalization. Added 5-minute TTL eviction to prevent stale errors from tripping the breaker.
655
- - **FIX 8 - ASCII receipt**: Replaced all Unicode box-drawing characters and emojis in session receipt and reports with ASCII equivalents for terminal compatibility.
656
-
657
- ### Changed
658
- - **Tool count**: 15 -> 16 MCP tools.
659
- - **Test count**: 282 -> 305 tests across 11 test suites.
660
- - **nreki_map**: Pinned rules now appended after repo map (was prepended before).
661
- - **package.json**: Version bumped to 2.1.1.
662
-
663
- ---
664
-
665
- ## [2.1.0] - 2026-03-10
666
-
667
- ### Headline
668
- NREKI v2.1 - 15 MCP tools, 282 tests, circuit breaker, surgical edit, pin memory, session receipt.
669
-
670
- ### Added - New Tools
671
- - **`nreki_semantic_edit`** - Surgically edit a function/class/interface by name without reading or rewriting the entire file. Finds the exact AST node, replaces only those bytes, validates syntax before saving. Saves 98% of output tokens vs full file rewrites.
672
- - **`nreki_circuit_breaker`** - Detects infinite failure loops (same error 3+ times, same file 5+ times, write-test-fail cycles). When tripped, forces Claude to stop and ask the human for guidance. Prevents doom loops that burn through remaining context.
673
- - **`nreki_pin`** - Pin important rules Claude should never forget. Pinned items are injected into every `nreki_map` response, keeping project conventions permanently in Claude's attention window. Max 10 pins, 200 chars each, persisted to disk.
674
-
675
- ### Added - New Modules
676
- - `src/semantic-edit.ts` - Zero-read surgical AST patching. Symbol name lookup, byte-level splice, syntax validation before write.
677
- - `src/circuit-breaker.ts` - Loop detection engine with sliding window analysis, consecutive failure tracking, and automatic trip/reset.
678
- - `src/pin-memory.ts` - Persistent pinned rules with deterministic output (sorted by id) for prompt cache compatibility.
679
-
680
- ### Added - Session Receipt
681
- - `nreki_session_report` now generates an ASCII receipt showing input tokens saved, output tokens avoided, search queries, surgical edits, syntax errors blocked, doom loops prevented, pinned rules active, estimated USD savings, and model info.
682
-
683
- ### Changed
684
- - **Tool count**: 12 -> 15 MCP tools.
685
- - **Test count**: 194 -> 282 tests across 11 test suites.
686
- - **nreki_map**: Now prepends pinned rules at the top of the repo map output.
687
- - **README**: Complete rewrite for v2.1 with comparison table, 3 unique features highlight, receipt preview, and updated architecture diagram.
688
- - **package.json**: Version bumped to 2.1.0.
689
-
690
- ### Architecture
691
- - **Pin memory layer**: Pinned rules are stored in `.nreki/pins.json` and prepended to every `nreki_map` response. Deterministic output (sorted by id) preserves prompt cache compatibility.
692
- - **Circuit breaker integration**: `nreki_terminal` automatically feeds errors to the circuit breaker for proactive loop detection.
693
-
694
- ## [2.0.0] - 2026-03-10
695
-
696
- ### Headline
697
- NREKI v2.0 - 12 MCP tools, 194 tests, cache-aware two-layer architecture.
698
-
699
- ### Added - New Tools
700
- - **`nreki_def`** - Go-to-definition by symbol name. AST-based, 100% precise, returns full source body with signature.
701
- - **`nreki_refs`** - Find all references to a symbol across the project. Cross-file word-boundary matching with context.
702
- - **`nreki_outline`** - List all symbols in a file with kind, signature, export status, and line ranges. Like VS Code Outline.
703
- - **`nreki_validate`** - AST sandbox validator. Parses code with tree-sitter before disk write. Catches missing commas, unclosed braces, invalid syntax with exact line/column and fix suggestions. Prevents the "write broken code see error → retry" token burn loop.
704
-
705
- ### Added - New Modules
706
- - `src/ast-navigator.ts` - AST navigation engine for nreki_def, nreki_refs, nreki_outline. Walks project files, extracts symbols, signatures, export status.
707
- - `src/ast-sandbox.ts` - AST sandbox validator with `validateCode()` and `validateDiff()`. Recursive tree walk with `hasError` subtree pruning for large-file performance.
708
- - `src/terminal-filter.ts` - Terminal entropy filter. Strips ANSI codes, deduplicates stack traces, extracts unique errors and affected files. 89% token reduction on error output.
709
- - `src/repo-map.ts` - Static deterministic repo map for Anthropic prompt cache optimization. Identical output for same repo state enables $0.30/M caching vs $3.00/M input.
710
-
711
- ### Changed
712
- - **Embeddings**: Migrated from all-MiniLM-L6-v2 (384-dim) to jina-embeddings-v2-small-en (512-dim) for 3x better code search precision.
713
- - **BM25 tuning**: Optimized k1=1.8, b=0.35 for code (vs default k1=1.2, b=0.75 for prose).
714
- - **RRF tuning**: k=10 for sharper rank fusion (vs k=60 default).
715
- - **Code tokenizer**: camelCase, snake_case, PascalCase identifiers split into sub-tokens for better BM25 matching.
716
- - **Tool count**: 6 → 12 MCP tools.
717
- - **Test count**: 90 → 194 tests across 8 test suites.
718
- - **README**: Complete rewrite with self-benchmark results, two-layer architecture docs, and updated comparison table.
719
-
720
- ### Architecture
721
- - **Two-layer design**: Layer 1 (static repo map, prompt-cacheable) + Layer 2 (dynamic context, per-query).
722
- - **Cache-friendly**: nreki_map output is deterministic - same repo state produces identical text, enabling Anthropic prompt caching.
723
-
724
- ### Performance (Self-Benchmark)
725
- - nreki_search: 10 results in 16ms (hybrid RRF fusion)
726
- - nreki_def: Definition lookup in 128ms across 22 files
727
- - nreki_refs: 20 references found in 11ms
728
- - nreki_outline: 25 symbols extracted in 7ms
729
- - nreki_compress: 5,502 1,753 tokens (68% reduction, medium level)
730
- - nreki_terminal: 11,967 → 1,276 tokens (89% reduction)
731
- - nreki_validate: Syntax error detection with line/column in <1ms
732
- - nreki_map: 22 files mapped, 4,677 tokens, 169ms
733
-
734
- ## [1.2.0] - 2026-03-10
735
-
736
- ### Security
737
- - **Path traversal protection**: All file operations now validate paths stay within workspace root (`safePath`)
738
- - **Input validation**: All tool inputs validated with Zod schemas before processing
739
- - **File size limits**: Files > 500KB and binary/minified files are automatically skipped
740
-
741
- ### Fixed
742
- - **WASM memory leaks**: Tree-sitter parse trees now guaranteed cleanup via `safeParse` try/finally wrapper
743
- - **Event loop blocking**: Large indexing operations now yield every 100 files via `setImmediate`
744
- - **Aggressive compression stubs**: Functions now show line count, key references, and expand commands instead of empty bodies
745
- - **Search tokenization**: Code identifiers (camelCase, snake_case, PascalCase) are now split into sub-tokens for better matching
746
- - **Vector search accuracy**: Cosine similarity now uses proper norm computation instead of raw dot product
747
- - **RRF scoring**: Verified correct rank-based fusion (was already using positions, not scores)
748
-
749
- ### Added
750
- - `src/utils/path-jail.ts` - Path traversal protection
751
- - `src/utils/safe-parse.ts` - WASM memory-safe parsing
752
- - `src/utils/file-filter.ts` - File size and extension filtering
753
- - `src/utils/code-tokenizer.ts` - Code-aware identifier tokenization
754
- - `src/schemas.ts` - Zod validation schemas for all tools
755
- - `.github/workflows/ci.yml` - CI/CD with matrix testing (3 OSes × 3 Node versions)
756
- - `CONTRIBUTING.md` - Contributor guide
757
- - `CHANGELOG.md` - This file
758
- - `.github/ISSUE_TEMPLATE/bug_report.md`
759
- - `.github/ISSUE_TEMPLATE/feature_request.md`
760
- - Comprehensive test suite for all new utilities
761
-
762
- ### Performance
763
- - Pre-computed vector norms at index time (avoids recalculation during search)
764
- - Proper cosine similarity with normalized vectors
765
-
766
- ## [1.1.1] - 2026-03-09
767
-
768
- ### Initial Release
769
- - MCP server with 6 tools: nreki_search, nreki_audit, nreki_compress, nreki_status, nreki_session_report, nreki_read
770
- - Hybrid RRF search (BM25 + vector similarity)
771
- - Three-tier classic compression + LLMLingua-2-inspired advanced compression
772
- - Real-time file watching with chokidar
773
- - Token consumption monitoring and burn rate prediction
774
- - Pre-tool-use interception hook
1
+ # Changelog
2
+
3
+ All notable changes to NREKI will be documented in this file.
4
+
5
+ ## 7.3.1 (2026-03-30)
6
+
7
+ ### Security
8
+ - **Path Jail:** Block `.git/hooks/` (RCE vector), `.envrc` (direnv RCE), `.age/` directories
9
+ - **Path Jail:** Fail-closed on parent resolution errors (was fail-open on EACCES/ELOOP)
10
+ - **LSP Sidecars:** ENV whitelist secrets no longer leak to gopls/pyright child processes
11
+
12
+ ### Fixed
13
+ - **TTRD Python:** `^\s*def` captures indented class methods (was `^def` — missed all methods inside classes)
14
+ - **TTRD Python:** Triple-quoted docstrings no longer corrupt bracket balancer
15
+ - **TTRD Go:** Private functions now tracked (was exported-only)
16
+ - **Auto-Healer:** Global error comparison replaces per-file (prevents collateral damage approval)
17
+ - **Auto-Healer:** Micro/macro rollbacks are synchronous (cures LSP split-brain)
18
+ - **Pull Diagnostics:** Cross-file error collection from all open files
19
+ - **Pull Diagnostics:** Push notifications suppressed in pull mode (race condition fix)
20
+ - **WAL:** Atomic write via temp+rename (prevents truncation on crash)
21
+ - **Hologram:** `currentEditTargets` cleared on rollback (prevents ghost unpruning)
22
+ - **Process Kill:** `kill(-pid)` on POSIX kills entire process group (prevents zombie workers)
23
+ - **VectorIndex:** Always deep-copy on deserialize (prevents buffer sharing with WASM)
24
+
25
+ ## v7.3.0 - Multi-Language Auto-Healing (2026-03-29)
26
+
27
+ ### Added Multi-Language (9 Surgeries)
28
+ - **LSP Auto-Healing Dual Cascade** (`nreki-kernel.ts`): Go (gopls) and Python (pyright) errors auto-fixed via `textDocument/codeAction`. Conservative whitelist: only import-related fixes. Ice Wall filter blocks "remove"/"delete" actions. TypeScript heals first (~20ms), then LSP (~300ms, max 2 iterations). Split-brain rollback re-syncs sidecar VFS on micro-rollback
29
+ - **TTRD Syntactic v2** (`nreki-kernel.ts`): Hybrid micro-scanner (regex anchor + bracket balancer) extracts signatures from Python/Go. Detects toxic `Any`/`interface{}` injection, lost return types (`->`), and stripped parameter annotations. Zero false positives on clean refactors (e.g. `Dict[str, Union[...]]` `ConfigPayload`)
30
+ - **Pull Diagnostics LSP 3.17+** (`lsp-sidecar-base.ts`): `textDocument/diagnostic` replaces 150ms settle timer. Deterministic — NREKI waits for server response, not a timer. Falls back to push model for older LSP servers
31
+ - **Python import resolution** (`repo-map.ts`): Dot-notation (`app.core.auth`) converted to slashes (`app/core/auth`) with progressive strip fallback. Real edges in dependency graph
32
+ - **Go import resolution** (`repo-map.ts`): Suffix matching for `github.com/org/project/utils` local `utils/`. Real edges in dependency graph
33
+ - **`requestCodeActions()` + title** (`lsp-sidecar-base.ts`): LSP `textDocument/codeAction` exposed with action title for whitelist filtering. Supports both `WorkspaceEdit.changes` and `documentChanges` formats
34
+ - **LSP coordinate translator** (`nreki-kernel.ts`): `getLspOffset()` converts LSP line/character (0-indexed) to byte offsets. Survives `\r\n` (Windows)
35
+ - **Mock LSP Server** (`tests/mock-lsp-server.ts`): Full JSON-RPC 2.0 test server. 8 scenarios: `missing_import`, `clean`, `unfixable`, `destructive`, `multi_error`, `slow_response`. Responds to `initialize`, `textDocument/didOpen`, `textDocument/diagnostic`, `textDocument/codeAction`
36
+ - **TypeScript Corsa Backend placeholder** (`ts-corsa-sidecar.ts`): Ready for Microsoft Project Corsa (TypeScript 7.0 in Go). Inherits `LspSidecarBase`. Strangler Fig hot-swap when Corsa ships
37
+
38
+ ### Added Lifecycle Hardening
39
+ - **SSOT `cleanupState()`** (`lsp-sidecar-base.ts`): Single idempotent embudo for all process death paths. `if (this.isDead) return` guard prevents double-cleanup when `forceKill()` and `exit` event collide
40
+ - **Explicit timer tracking** (`lsp-sidecar-base.ts`): `PendingRequest` now stores `timer: NodeJS.Timeout`. `cleanupState()` kills all timers directly no closure indirection
41
+ - **`forceKill()` with stdin destroy** (`lsp-sidecar-base.ts`): Destroys stdin pipe before SIGKILL, forcing OS to propagate closure to entire process tree (kills tsx wrappers and grandchildren)
42
+ - **`spawnEnv` injection** (`lsp-sidecar-base.ts`): Optional 4th constructor parameter for isolated env vars. Tests no longer mutate `process.env` globally
43
+
44
+ ### Added Miner
45
+ - **Chronos Miner v10 Turbine Oracle** (`chronos-miner.ts`): `git cat-file --batch` streaming (single process per chunk). Dynamic `import()` extraction. Pure TS/JS scope (`.mjs`, `.cjs` included). `node_modules/` and `dist/` filtered by regex segment. 512MB maxBuffer
46
+
47
+ ### Changed
48
+ - Tests: 704 712 (44 suites). +8 LSP sidecar tests, +1 kernel CRLF test
49
+ - `LspSidecarBase`: `request()`, `toPosix()`, `workspaceUri`, `realProjectRoot` changed from `private` to `protected`
50
+ - `LspPosition` and `LspRange` interfaces exported for kernel consumption
51
+ - `shutdown()` now delegates entirely to `forceKill()` → `cleanupState()`
52
+ - Boot error handler, exit handler, and initialize catch all route through `cleanupState()` zero asymmetric cleanup
53
+ - Healing message now groups TypeScript fixes and LSP fixes separately in output
54
+ - `interceptAtomicBatch()` uses Dual Cascade: TS healing first, then LSP healing only if TS succeeded
55
+
56
+ ## v7.1.2 - 9 Critical Patches
57
+
58
+ ### Fixed
59
+ - **Ghost Deletion** (`nreki-kernel.ts`): `mutatedFiles` now cleaned on rollback — prevents `commitToDisk()` from deleting real files that belonged to failed transactions
60
+ - **searchRawCode exact match** (`database.ts`): Replaced `String.includes()` with `Set.has()` eliminates false positives (e.g. "id" no longer matches "width") and changes complexity from O(N) to O(1)
61
+ - **Arrow function angleDepth** (`parser.ts`): `=>` operator no longer decrements `angleDepth` below 0 — prevents extracting entire arrow function bodies as "signatures" in the repo map
62
+ - **Circuit Breaker exception visibility** (`circuit-breaker.ts`): `wrapWithCircuitBreaker` now catches handler exceptions via try/catch and converts them to `McpToolResponse` with `isError: true` — breaker is no longer blind to ENOENT loops and timeout cascades
63
+ - **Prompt cache preservation** (`router.ts`): Context Heartbeat now injected AFTER original text for all actions (not just `map`)preserves Anthropic prefix cache hit rate
64
+ - **clearChunks files table** (`database.ts`): `clearChunks()` now also deletes from `files` table — prevents permanent invisibility when a file is deleted and recreated with the same content
65
+ - **splitParams string-aware** (`shadow-generator.ts`): `splitParams()` now tracks string state (single, double, backtick quotes) prevents splitting on commas inside string literals that produce broken `.d.ts` output
66
+ - **LSP sidecar listener cleanup** (`lsp-sidecar-base.ts`): `proc.on("error")` handler now removes exit/SIGINT/SIGTERM listeners — prevents `MaxListenersExceededWarning` and memory leak on repeated spawn failures
67
+ - **macOS case-insensitive file lock** (`file-lock.ts`): `normalizeLockKey` now treats `darwin` same as `win32` (lowercase) — prevents file corruption from parallel locks on `App.ts` vs `app.ts` on macOS APFS
68
+
69
+ ### Changed
70
+ - Tests: 696 704 (8 new tests for patch coverage)
71
+ - CI: replaced hardcoded `grep "696 passed"` with JSON reporter validation (no more brittle test count checks)
72
+
73
+ ## v7.0.0 - Software Physics Engine
74
+
75
+ ### Added
76
+ - **Fiedler Vector extraction**: `analyzeTopology` now returns the full eigenvector `v2` (bridge fragility map)
77
+ - **Third eigenvalue (λ₃)**: Enables spectral gap computation ∇(λ₃ - λ₂) for predictive analysis
78
+ - **Third eigenvector (v3)**: Topological stress coordinates per node
79
+ - **Gauge Fixing**: Deterministic phase canonicalization prevents sign ambiguity across commits (critical for ML pipelines)
80
+ - **Gram-Schmidt deflation**: Reusable `powerIteration()` function extracts arbitrary eigenvectors
81
+ - **nodeIndex passthrough**: `SpectralTopologist.analyze()` now returns the symbol→index mapping
82
+ - **Monorepo workspace resolution**: `buildFastLookup` resolves `@org/package` imports via O(1) string math (supports packages/, workspaces/, libs/, apps/)
83
+ - **Adaptive Shotgun Surgery threshold**: Scales with repo size via `Math.max(8, floor(N × 0.015))` — no more false positives on large codebases
84
+ - **Modern module extensions**: Full `.mts`, `.cts`, `.mjs`, `.cjs` support across parser, kernel, repo-map, and JIT holography
85
+
86
+ ### Fixed
87
+ - **VFS zombie state**: `commitToDisk()` now purges VFS on disk write failure, preventing ghost content desync
88
+ - **WASM race conditions**: Serialized language loading via `loadGate` in parser.ts, ast-sandbox.ts, parser-pool.ts
89
+ - **Power iteration seed**: Uses data-dependent post-mutation seed for deterministic convergence
90
+ - **extractName regex purge**: Replaced 20 fragile regex patterns across 2 files with AST-first keyword-stripping word splitter
91
+ - **32 audit fixes (v6.1.x)**: Shadow codegen, TTRD amnesty bypass, orphan .tmp leak, Python indentation, splice duplicate detection, WeakMap middleware, syncTechDebt phantom accumulation, undo key normalization, APFS locks, allocUnsafe, SharedArrayBuffer isolation, OOM streaming iterator, and more
92
+
93
+ ### Changed
94
+ - License changed from MIT to Apache 2.0
95
+ - Tests: 696 tests ( 704 in v7.1.2)
96
+ - Vitest upgraded from 3.0.7 to 4.1.1
97
+ - `detectMode` now returns "file" mode for 50-200 file projects (correct performance scaling)
98
+ - `isTypeScriptFile` respects `allowJs` config (prevents false errors in strict projects)
99
+ - Circuit breaker tool detection updated for v3.0+ action names
100
+ - File lock timeout extended to 5 minutes for large batch edits
101
+
102
+ ### Internal
103
+ - `SpectralResult` interface extended with optional `v2`, `lambda3`, `v3`, `nodeIndex` fields (backward compatible)
104
+ - Power iteration limit raised from 100 to 150 (convergence guard unchanged at 1e-7)
105
+ - Chronos Miner v2: Tree-sitter based temporal dataset extractor (zero node_modules, resumable, architectural dispersion ground truth)
106
+ - Worktree isolation: each miner uses `/tmp/nreki-wt-{repo}` for parallel mining
107
+
108
+ ## v6.1.0 - Spectral Gate + Surgical Architecture (2026-03-22)
109
+
110
+ ### Performance
111
+ - CSR sparse matrix with fused Rayleigh quotient in SpMV power iteration (L1 cache friendly)
112
+ - Pre-computed sourceFile/targetFile on TopologicalEdge eliminates millions of split("::") allocations
113
+ - fd-based incremental log reading in TokenMonitor (no more full-file readFileSync)
114
+ - In-place ring buffer (shift) and TTL eviction (splice) in CircuitBreaker zero array allocations per tool call
115
+ - Radical AST pruning in findDependencies: 8 node types short-circuited, arrow/fn bodies skipped
116
+ - Eliminated redundant extractConstraintGraph calls in benchmark O(E) RAM filtering
117
+
118
+ ### Spectral Gate
119
+ - Density-weighted Phi = lambda2 * (2V / (N*(N-1))) for star topology detection
120
+ - Conditional formula: density when N unchanged (ghost/expansion), original lambda2/N when N decreases (decoupling)
121
+ - 11/11 real-world projects ALL PASS: 55/55 detection, 0/55 false positives, max 95.8ms
122
+
123
+ ### Security
124
+ - NFC Unicode normalization in safePath prevents macOS NFD bypass of .env blocklist
125
+ - Removed settings.py and wp-config.php from sensitive file blocklist (false positives for Django/WordPress)
126
+ - healingStats encapsulated behind private field + readonly getter
127
+ - CircuitBreaker accepts projectRoot in constructor instead of dynamic process.cwd()
128
+ - Middleware singletons encapsulated in CircuitBreakerMiddleware class
129
+
130
+ ### Bug Fixes
131
+ - Hologram Shield 2 now evaluates semantic diagnostics on dependents, not just edited files
132
+ - TTRD: removed truncated typeStr bypass — TypeFlags toxicity is sole authority
133
+ - applySemanticSplice: closest-match indexOf picks nearest occurrence to AST offset
134
+ - stripCallStatements: regex lastIndex advanced to prevent overlapping matches on nested calls
135
+ - Surgical JIT cache invalidation in rollbackAll only edit targets cleared, not entire cache
136
+ - DocumentRegistry + LanguageService recreated on corruption to prevent OOM
137
+ - Safe slice in applySemanticSplice caps indent stripping at actual whitespace
138
+ - jitClassifyFile size guard (150KB) prevents event loop blocking on auto-generated files
139
+ - perFileFailures GC synced with history TTL eviction
140
+ - Centralized backup files in .nreki/transactions/ directory
141
+ - Windows fingerprint POSIX normalization in getFingerprint
142
+ - BOM-safe readSource in jitClassifyFile
143
+
144
+ ### Code Quality
145
+ - PorterStemmer extracted to src/utils/porter-stemmer.ts
146
+ - Deduplicated escapeRegex in database.ts (uses escapeRegExp from utils/imports)
147
+ - detectMode filters .d.mts/.d.cts files
148
+ - detectLanguage supports .mts/.cts/.mjs/.cjs extensions
149
+ - Deprecation warnings on TokenGuardEngine and TokenGuardDB aliases
150
+ - CLAUDE.md externalized to templates/CLAUDE.md
151
+ - noUnusedLocals and noUnusedParameters enabled 14 dead code items removed
152
+ - Test parallelism enabled (fileParallelism: true)
153
+ - CI: npm audit, npm run lint, continue-on-error for Node 24
154
+ - inferSimpleType returns "unknown" instead of "any" in shadow generation
155
+ - Cache format versioning (CACHE_FORMAT_VERSION) in repo-map
156
+ - mtimeMs included in computeFileDigest for stale cache detection
157
+ - isEnvironmentFile uses exact basename matching instead of substring
158
+
159
+ ### Benchmarks (11 projects, 55 test cases)
160
+
161
+ | Project | Files | Nodes | Edges | Max Latency | FN | FP | Result |
162
+ |---------|-------|-------|-------|-------------|----|----|--------|
163
+ | NREKI | 38 | 195 | 373 | 44.0ms | 0/5 | 0/5 | ALL PASS |
164
+ | Zod | 195 | 2,251 | 6,242 | 32.2ms | 0/5 | 0/5 | ALL PASS |
165
+ | tRPC | 89 | 828 | 1,790 | 41.3ms | 0/5 | 0/5 | ALL PASS |
166
+ | Prisma | 1,970 | 3,546 | 5,319 | 7.7ms | 0/5 | 0/5 | ALL PASS |
167
+ | ts-pattern | 18 | 360 | 1,425 | 10.0ms | 0/5 | 0/5 | ALL PASS |
168
+ | Next.js | 1,445 | 5,024 | 7,589 | 27.0ms | 0/5 | 0/5 | ALL PASS |
169
+ | Hono | 186 | 1,414 | 10,188 | 35.7ms | 0/5 | 0/5 | ALL PASS |
170
+ | Drizzle ORM | 447 | 3,521 | 17,021 | 70.3ms | 0/5 | 0/5 | ALL PASS |
171
+ | date-fns | 1,238 | 1,905 | 3,129 | 15.2ms | 0/5 | 0/5 | ALL PASS |
172
+ | VS Code | 4,697 | 24,204 | 111,994 | 29.1ms | 0/5 | 0/5 | ALL PASS |
173
+ | Effect | 362 | 10,935 | 72,723 | 95.8ms | 0/5 | 0/5 | ALL PASS |
174
+
175
+ ## [6.0.1] - 2026-03-21
176
+
177
+ ### Fixed
178
+ - `NrekiDB.save()` and `NrekiDB.close()` guard against double-close during graceful shutdown
179
+ - `file-lock.test.ts` platform guard for case-insensitive path test (macOS/Linux CI)
180
+ - CI matrix expanded to Node 20, 22, 24
181
+
182
+ ## [6.0.0] - 2026-03-19
183
+
184
+ ### Added
185
+ - **Holographic Pruning**: New performance mode for large projects (>1000 files).
186
+ Replaces full `.ts` source files with lightweight `.d.ts` shadow stubs in the
187
+ TypeScript compiler's VFS, dramatically reducing boot time and memory usage.
188
+ - Shadow Generator (`src/hologram/shadow-generator.ts`): Tree-sitter based file
189
+ classifier and `.d.ts` generator. Classifies exports as prunable (explicit types)
190
+ or unprunable (inferred types). Uses AST walking, not regex.
191
+ - Shadow Cache (`src/hologram/shadow-cache.ts`): Disk persistence for shadows
192
+ with mtime/hash staleness detection and version guard invalidation.
193
+ - Symbiotic Harvester (`src/hologram/harvester.ts`): Extracts real `.d.ts` from
194
+ the TypeScript compiler during idle time, replacing heuristic shadows with
195
+ compiler-grade ones. Cooperative scheduler with epoch-aware abort.
196
+ - Lazy Subgraph Loading: Kernel boots with only ambient files in rootNames.
197
+ Target files are added dynamically during `interceptAtomicBatch()`.
198
+ - Pre-warming: Background shadow scan starts after MCP handshake, before first edit.
199
+ - Domain Separation: `predictBlastRadius` disabled in hologram mode (use Layer 1
200
+ AST navigator for reference queries).
201
+ - **JIT Holography**: Eliminates upfront `scanProject()`. Shadows generated
202
+ on-demand when TypeScript's module resolver requests files. Cold boot
203
+ drops from 22.96s to 1.94s on VSCode (5,584 files). Only 642 of 5,584
204
+ files are ever classified the rest are never touched.
205
+ - `NrekiKernel.setShadows()` - receive shadow scan results before boot
206
+ - `NrekiKernel.hasShadows()` - check if shadows are loaded
207
+ - `NrekiKernel.setJitParser()` - inject Tree-sitter parser for on-demand use
208
+ - `NrekiKernel.setJitClassifier()` - inject classification function
209
+ - `NrekiKernel.hasJitHologram()` - check if JIT mode is available
210
+ - `NrekiKernel.getJitCacheSize()` - report on-demand classification count
211
+ - `NrekiKernel.getLogicalTime()` - monotonic clock for harvester epoch detection
212
+ - `NrekiKernel.getProgram()` - access TypeScript Program for harvester .d.ts emission
213
+ - `NrekiMode` type extended with `"hologram"`
214
+ - `detectMode()` returns `"hologram"` for projects with >1000 source files
215
+
216
+ ### Changed
217
+ - VFS hooks in `NrekiKernel.boot()` now include hologram intercepts (BEFORE existing
218
+ VFS checks) for `fileExists`, `readFile`, and `getScriptSnapshot`
219
+ - `getFatalErrors()` semantic cascade evaluation now runs for both `project` and
220
+ `hologram` modes
221
+ - `RouterDependencies.nrekiMode` type includes `"hologram"`
222
+ - Deferred boot in router handles hologram mode (scan before boot if pre-warm incomplete)
223
+
224
+ ### Tests
225
+ - 60 new tests across 7 test files:
226
+ - `tests/hologram-shadow-generator.test.ts` (19 tests)
227
+ - `tests/hologram-vfs.test.ts` (8 tests)
228
+ - `tests/hologram-lazy-subgraph.test.ts` (5 tests)
229
+ - `tests/hologram-domain-separation.test.ts` (3 tests)
230
+ - `tests/hologram-harvester.test.ts` (6 tests)
231
+ - `tests/hologram-integration.test.ts` (4 tests)
232
+ - `tests/jit-holography.test.ts` (15 tests)
233
+
234
+ ## [5.3.0] - 2026-03-18
235
+
236
+ ### Added
237
+ - **Temporal Type Regression Detection (TTRD)**: Detects when an AI agent weakens
238
+ type contracts to bypass the TypeScript compiler.
239
+ - Uses TypeChecker API to read compiler-resolved types, not AST text. Catches
240
+ inferred type escape (`as any` in expressions) and alias weakening
241
+ (`type X = any` where function signatures stay identical).
242
+ - Pre/Post comparison within the same ACID transaction. No global baseline needed.
243
+ - Barrel file guard: skips re-exported symbols, processes local declarations only.
244
+ - Type string safety: default truncation (no NoTruncation flag), 500-char hard limit.
245
+ - Submodular penalty: log2 scaling prevents cascading errors from blocking files.
246
+ - Debt ledger: stores original strict types for future restoration guidance.
247
+ - Debt payment: restoring strict types clears debt records and reduces friction.
248
+ - Ghost debt cleanup: deleted symbols cancel their debt automatically.
249
+ - Per-file regression tracking in batch edits (no friendly fire).
250
+ - `NrekiKernel.extractCanonicalTypes()` - TypeChecker-based export type extraction
251
+ - `NrekiKernel.computeTypeRegressions()` - Pre/Post contract comparison
252
+ - `NrekiKernel.resolvePosixPath()` - public path normalization
253
+ - `ChronosMemory.recordRegressions()` - submodular penalty with debt ledger
254
+ - `ChronosMemory.assessDebtPayments()` - debt forgiveness on type restoration or deletion
255
+ - `NrekiInterceptResult.regressions` - regression evidence per intercept
256
+ - `NrekiInterceptResult.postContracts` - post-edit type contracts for debt assessment
257
+ - `TypeRegression.filePath` - per-file attribution for batch edit accuracy
258
+
259
+ ### Tests
260
+ - 19 new tests in `tests/ttrd.test.ts`
261
+ - extractCanonicalTypes, regression detection, false positive guards, barrel file guard,
262
+ type string limits, submodular penalty, debt ledger persistence, debt payment,
263
+ ghost debt, JIT warnings, happy path detection, pre/post baseline, healed path,
264
+ batch edit attribution, batch debt payment, no-success-on-regression
265
+ - **Performance Modes**: Auto-detection of validation depth based on project size.
266
+ - `syntax` mode (< 50 files): Kernel disabled. Tree-sitter only.
267
+ - `project` mode (50-1000 files): Full cross-file semantic validation with early exit.
268
+ - `file` mode (> 1000 files): Semantic checks on edited files only. No cascade.
269
+ - Mode auto-detected via bounded DFS file counter in ~85ms.
270
+ - Deferred boot: kernel boots on first edit, not at startup. MCP server starts in 0ms.
271
+ - Early exit in project mode: stops evaluating after threshold errors (50 + 20 per edited file).
272
+ - Corrupted builder recovery via warm rebuild (~2-5s) after early exit.
273
+ - Global noise filter: ignores diagnostic noise from missing @types when editing source files.
274
+ - Toxicity scoring for TTRD: detects parameter-level regressions (RetryConfig to any).
275
+ - Structural collapse detection: catches Promise<any> to any.
276
+ - **VSCode Benchmark (file mode)**: 5,584 files, 91.6s boot, 4.5GB RAM, 0 OOM crashes.
277
+ - Test A (safe edit): PASS, 23s
278
+ - Test B (local type break): CAUGHT, 25 errors in event.ts, 55s
279
+ - Test C (TTRD): CAUGHT via compilation, 1 error, 41s
280
+ - Test D (IDisposable): CAUGHT, 29 local errors in lifecycle.ts, 98s
281
+ - Previous project mode: 644s latency, 35,704 errors, OOM crashes
282
+
283
+ ### Tests
284
+ - 20 new tests in `tests/mode-modes.test.ts` (mode detection, syntax/file/project behavior, early exit, recovery, elastic threshold, global noise, TTRD toxicity)
285
+ - 1 new test in `tests/ttrd-silent-crime.test.ts` (silent type degradation)
286
+ - Total: 590 tests across 29 suites, 0 failures
287
+
288
+ ---
289
+
290
+ ## [5.2.0] - 2026-03-18
291
+
292
+ ### Added
293
+ - **Chronos Memory**: Cross-session file error tracking with Cognitive Friction Index (CFI)
294
+ - Exponential decay (λ=0.85) - file friction reduces 15% per clean session
295
+ - Success discount - successful edits on high-friction files halve their CFI score
296
+ - JIT warnings - error history appears only when reading/editing affected files
297
+ - Edit gating - high-friction files require uncompressed read before editing
298
+ - Blast radius tracking - error penalties go to files where errors occur, not the edited file
299
+ - Dead file cleanup - deleted files are removed from tracking on session start
300
+ - Baseline cache reuse - O(1) error counting without compiler invocation
301
+ - Crash-safe persistence with debounced atomic writes
302
+ - `NrekiKernel.getInitialErrorCount()` - immutable boot-time error snapshot
303
+ - `NrekiKernel.getCurrentErrorCount()` - O(1) via baseline cache
304
+ - Global Health Delta tracking (ΔH = current errors - boot errors)
305
+ - **Chronos Health Score** in `nreki_guard action:"report"` output
306
+ - Circuit breaker trips now feed Chronos CFI automatically
307
+
308
+ ### Tests
309
+
310
+ - 16 new tests in `tests/chronos-memory.test.ts`
311
+ - Constructor, recordTrip/Error/Heal/Success, isHighFriction, passive decay, GC, dead file cleanup, persistence, health report, blast radius tracking
312
+
313
+ ---
314
+
315
+ ## v5.1.0 - Zero-Token Error Correction (2026-03-17)
316
+
317
+ ### New: NREKI L3.3 Auto-Healing Engine
318
+
319
+ When the LLM's edit introduces structural errors (missing imports, forgotten `async` keyword, incomplete interface implementations), NREKI now **auto-corrects them in RAM** using TypeScript's CodeFix API - the same engine that powers VS Code's "Quick Fix" lightbulb. The LLM never sees the error. Zero tokens wasted.
320
+
321
+ - **`attemptAutoHealing()`**: Iterative fix-recompile loop inside `interceptAtomicBatch()`. Applies one CodeFix at a time, recompiles the universe (~20ms), checks if errors decreased, and either accepts or micro-rollbacks.
322
+ - **Error reduction rule**: Every fix must reduce total error count. If a fix leaves the same errors or more, it is reverted and blacklisted.
323
+ - **SAFE_FIXES whitelist**: Only deterministic structural fixes are applied - never type mutations or business logic changes:
324
+ - `import` / `fixMissingImport` - adds forgotten imports
325
+ - `fixAwaitInSyncFunction` - adds `async` when LLM wrote `await` without it
326
+ - `fixPromiseResolve` - wraps returns in `Promise.resolve()`
327
+ - `fixMissingProperties` - auto-implements required interface properties
328
+ - `fixClassDoesntImplementInheritedAbstractMember` - implements abstract methods
329
+ - `fixAddMissingMember` - declares missing class properties
330
+ - `fixAddOverrideModifier` - adds `override` keyword
331
+ - **Micro-rollback per fix**: Each fix has its own undo-log. Failed fixes revert without affecting successful ones.
332
+ - **Macro-rollback on partial failure**: If not ALL errors are resolved, the entire healing attempt is undone and the original errors are returned to the LLM intact.
333
+ - **Patch protection**: On successful healing, the response tells the agent not to overwrite the auto-applied fixes in the next edit.
334
+ - **`healedFiles` in response**: Router creates `nreki_undo` backups for collateral files the healer touched.
335
+ - **`healingStats`**: Public counter tracking `applied` and `failed` healing attempts.
336
+
337
+ ### New: `getFatalErrors()` - Centralized Triple Shield
338
+
339
+ Extracted the 3-shield evaluation logic (Global Syntactic Semantic) into a reusable private method. Both `interceptAtomicBatch()` and `attemptAutoHealing()` use it, eliminating code duplication.
340
+
341
+ ### Bug Fixes
342
+
343
+ - **`ts.emptyOptions` doesn't exist in TS 5.9**: Replaced with `{} as ts.UserPreferences`.
344
+
345
+ ### Tests
346
+
347
+ - **526 tests**, 25 suites, zero failures, zero regressions
348
+ - New: `tests/auto-healing.test.ts` -6 tests covering:
349
+ - Missing import auto-healed `safe: true` disk has import
350
+ - `await` without `async`, callers healthy auto-healed `safe: true`
351
+ - `await` without `async`, callers break cascade detected → micro-rollback → `safe: false`
352
+ - Business logic error (no CodeFix) healing skipped → `safe: false`
353
+ - `healingStats` counter verification
354
+ - Clean code healing not triggered `safe: true` without heal text
355
+
356
+ ---
357
+
358
+ ## v5.0.0 - The NREKI Kernel (2026-03-16)
359
+
360
+ ### New: NREKI Kernel (Layer 2 - Cross-File Semantic Verification)
361
+
362
+ - **VFS-LSP Kernel**: Hijacks TypeScript Compiler API with a Virtual File System in RAM. Edits are validated against the entire project's type system before reaching disk.
363
+ - **True ACID Transactions**: `interceptAtomicBatch()` validates in RAM; `commitToDisk()` writes via two-phase atomic commit (backup → temp+rename → cleanup) with physical rollback on OS failure.
364
+ - **Zero Disk Touch**: When the kernel is active, `semanticEdit()` operates in `dryRun` mode. The disk is immutable until semantic validation passes.
365
+ - **Triple Shield**: Global diagnostics → Syntactic diagnostics → Semantic diagnostics. Catches broken syntax AND cross-file type errors.
366
+ - **Predictive Blast Radius**: `predictBlastRadius()` uses `ts.LanguageService.findReferences()` to show what will break and WHY before the agent edits. ~20ms per query.
367
+ - **PageRank Architecture Scoring**: Files classified by recursive importance via Markov Chain Power Iteration (damping factor 0.85, 20 iterations, <8ms convergence for 1,000 files). Replaces naive inDegree classification.
368
+ - **Warm-Path Optimization**: Failed intercepts advance the monotonic clock instead of destroying the builder program. Rollback drops from ~10s to ~50ms.
369
+ - **Path Jail at Kernel Level**: `interceptAtomicBatch()` rejects paths that resolve outside the project root.
370
+ - **O(1) Virtual Directory Resolution**: `vfsDirectories` Set replaces O(n) VFS scan in `directoryExists`.
371
+ - **LanguageService Integration**: VS Code's reference engine connected to the VFS for JIT lazy evaluation.
372
+
373
+ ### Renamed: TokenGuard → NREKI
374
+
375
+ - npm package: `@ruso-0/tokenguard` → `@ruso-0/nreki`
376
+ - Tool names: `tg_navigate` → `nreki_navigate`, `tg_code` → `nreki_code`, `tg_guard` → `nreki_guard`
377
+ - Database: `.tokenguard.db` `.nreki.db`
378
+ - Pins: `.tokenguard-pins.json` `.nreki-pins.json`
379
+ - Backups: `.tokenguard-backup/` `.nreki-backup/`
380
+ - Server name: `TokenGuard` `NREKI`
381
+
382
+ ### Security Hardening (30/30 Audit Findings Resolved)
383
+
384
+ - **A1**: Kernel path jail blocks traversal attempts (`../../etc/passwd`)
385
+ - **A2**: Write-Then-Validate eliminated - now Validate-Then-Write via dryRun
386
+ - **A3**: Zombie mutex (`withTimeout`/`Promise.race`) deleted entirely
387
+ - **A4**: Sensitive file blocklist expanded (+8 patterns: docker, kube, netrc, htpasswd, etc.)
388
+ - **A5**: `node_modules` filter uses path segment regex, not substring match
389
+ - **A6**: Kernel returns relative paths in error messages, not absolute
390
+ - **A8**: Pin sanitization adds Unicode normalization (NFKC) + null byte rejection
391
+ - **A9**: Prototype pollution guard on pin JSON.parse
392
+ - **A10**: Kernel readFile blocks sensitive files (.env, .pem, .key) in disk fallback
393
+ - **B1**: `commitToDisk()` resurrected as the only write path when kernel is active
394
+ - **B2**: `isTypeScriptFile` regex expanded to `.mts`, `.cts`, `.mjs`, `.cjs`, `.d.mts`, `.d.cts`
395
+ - **B4**: Double-boot guard added to `boot()`
396
+ - **B5**: Pre-boot guard added to `interceptAtomicBatch()`
397
+ - **B6**: `logicalTime` saved and restored on rollback
398
+ - **B7**: Fingerprint hash upgraded from MD5 to SHA-256
399
+ - **B8**: GC threshold made configurable (`gcThreshold` property)
400
+ - **C4**: Heartbeat skipped during circuit breaker escalation ≥ 2
401
+ - **C5**: Version read from `package.json` at runtime (no hardcoded string)
402
+ - **D1**: Pin file writes use atomic temp+rename pattern
403
+ - **D2**: Orphaned `.nreki-bak-*` files cleaned on kernel boot
404
+ - **D4**: Token estimation margin documented (20-40% variance)
405
+ - **E1**: `directoryExists` uses O(1) Set lookup instead of O(n) VFS scan
406
+
407
+ ### Tests
408
+
409
+ - **520 tests**, 24 suites, zero failures
410
+ - New: `tests/nreki-kernel.test.ts` -22 kernel unit tests (boot, semantic validation, syntactic shield, baseline tolerance, file operations, ACID, concurrency, edge cases)
411
+ - New: `tests/nreki-integration.test.ts` -8 integration tests (dryRun, full commit path, type-break blocked, batch VFS, path traversal rejection)
412
+ - New: PageRank tests (recursive importance, convergence <50ms for 1,000 files)
413
+ - New: Precision tests (VFS staging leak, node_modules filtering, restore failure handling)
414
+
415
+ ### Benchmark: OpenDota (148 files, 1,600+ stars)
416
+
417
+ - 6/6 correct verdicts (valid edit, type break, syntax break, file delete, non-TS file)
418
+ - Zero false positives, zero false negatives
419
+ - Boot: 10.68s | Type break detection: 12.6s | Syntax detection: 11.4s
420
+
421
+ ### 32 Sealed Failure Modes (P1-P32)
422
+
423
+ P2 (atomic commit), P4 (dynamic rootNames), P5 (tombstone), P8 (monotonic clock), P9 (topological cardinality), P10 (FIFO mutex), P11 (periodic GC), P15 (path sanitization), P17 (zombie AST), P18 (destruction & resurrection), P19 (counter reset), P21 (multi-file deadlock), P25 (idempotent undo-log), P26 (POSIX normalization), P27 (recursive mkdir), P28 (syntactic blindness), P29 (TS6053 ghost), P30 (non-TS filter), P31 (virtual directories), P32 (physical rollback).
424
+
425
+ ## [4.0.2] - 2026-03-13
426
+
427
+ ### Fixed (Logic)
428
+ - **Blind Sniper**: `prepare_refactor` only searched function signatures (BM25 shorthand index), missing symbols used inside function bodies. Now uses exhaustive `raw_code` SQL scan for 100% coverage. Also added `property_identifier` and `shorthand_property_identifier` to the AST node type filter.
429
+ - **Batch Edit Race Condition**: `batch_edit` had no file locks. Concurrent `edit` + `batch_edit` on the same file could corrupt it. Added two-phase locking (acquire all or rollback all, release in finally).
430
+ - **indexOf Wrong Function**: `applySemanticSplice` fallback searched from byte 0, could edit the wrong function when duplicates exist. Now searches in a ±500 byte local window around the AST-reported position first.
431
+ - **extractSignature String Confusion**: `{` inside string literals (e.g., `msg = "{"`) was mistaken for function body start, truncating signatures. Added string-state tracking to skip characters inside quotes.
432
+ - **Silent Plan Amnesia**: Plans exceeding 15,000 characters were silently dropped. Now injects a visible WARNING telling Claude to summarize the plan.
433
+
434
+ ### Fixed (Documentation)
435
+ - Updated `index.ts` docstring from v3.3.0 to v4.0.2.
436
+ - Rewrote `skills/SKILL.md` with v4 tool names and features (batch_edit, prepare_refactor, blast radius, architecture tiers).
437
+ - Updated `getClaudeMdContent()` (CLAUDE.md init) with v4 features.
438
+ - Changed "vs full file rewrite" to "vs native read+edit" in response messages.
439
+ - Changed "Saves 98%" claim to "60-80%" in semantic-edit docstring.
440
+ - Eliminated double file read in handleEdit by returning oldRawCode from semanticEdit.
441
+ - Updated preToolUse.ts docstring to use v4 tool names.
442
+
443
+ ## [4.0.1] - 2026-03-13
444
+
445
+ ### Fixed
446
+ - **Inflated `tokensAvoided` metric**: `semanticEdit()` was computing savings as `fullFile × 2 - newCode`, which double-counted the file read. Corrected to `fullFile + oldSymbol - newCode` (read file + old symbol code that Claude would have sent).
447
+ - **Router docstring version**: Updated from v3.3.0 to v4.0.0 and added `batch_edit` and `prepare_refactor` to the tool action listings.
448
+ - **Batch edit blast radius missing dependents**: `handleBatchEdit()` now queries the dependency graph to list files that import edited modules, matching the behavior of single-file `handleEdit()`.
449
+
450
+ ## [4.0.0] - 2026-03-12
451
+
452
+ ### BREAKING CHANGES
453
+ - **`symbolName` extracted from AST**: Parser now uses tree-sitter `@_name` captures instead of ~10 fragile regexes. `ParsedChunk` interface adds `symbolName: string`. Database schema adds `symbol_name`, `start_index`, `end_index` columns (auto-migrated for existing DBs).
454
+
455
+ ### Added
456
+ - **`nreki_code action:"batch_edit"`**: Atomically edit multiple symbols across multiple files. Uses Virtual File System in RAM with reverse splice ordering (descending startIndex) to avoid byte offset corruption. All-or-nothing: if ANY file fails AST validation, NOTHING is written to disk.
457
+ - **Architecture Map**: `nreki_navigate action:"map"` now includes dependency graph with import centrality classification. Files are tiered by in-degree percentile: P75+ = "core", P50-P75 = "logic", <P50 = "leaf". Uses O(1) FastLookup index for import resolution (relative paths, `@/` aliases, extensionless, index.ts implicit).
458
+ - **Blast Radius Detection**: When `nreki_code action:"edit"` changes a function's signature (parameters, return type), NREKI warns which files import that symbol. Suggests `batch_edit` to update dependents. Also applies to `batch_edit`.
459
+ - **`nreki_navigate action:"prepare_refactor"`**: AST-based confidence classification for safe renaming. Walks tree-sitter syntax nodes and classifies each occurrence as "high" confidence (safe to rename) or "review" (inside strings, comments, object keys, JSX text). Returns a formatted report with two sections.
460
+ - **`parseRaw<T>()`**: Public method on `ASTParser` for raw tree-sitter tree access via callback pattern with guaranteed WASM memory cleanup.
461
+ - **`DependencyGraph` interface**: `importedBy`, `inDegree`, and `tiers` maps exported from `repo-map.ts`.
462
+ - **`buildFastLookup()`**: O(1) import resolution mapping extensionless, src/-stripped, and index-collapsed variants to actual file paths.
463
+ - **`detectSignatureChange()`**: Pure function comparing old/new signatures to detect parameter and return type changes.
464
+ - **`findChunkBySymbol()`**: Extracted pure function preferring `chunk.symbolName` (AST) with `extractName()` regex fallback.
465
+ - **`applySemanticSplice()`**: Extracted pure splice function for reuse in both single and batch edits.
466
+
467
+ ### Fixed
468
+ - **Bug A - Stale docstring**: `engine.ts` header incorrectly referenced "sqlite-vec + FTS5". Updated to reflect actual implementation (pure-JS VectorIndex + BM25 KeywordIndex).
469
+ - **Bug B - Multi-line console.log stripping**: Regex-based `console.log()` removal failed on multi-line calls. Replaced with `stripCallStatements()` using balanced parenthesis tracking. Same fix applied to Python `print()`.
470
+ - **Bug C - Python `#` in strings**: Comment stripping destroyed `#` inside string literals (e.g., `color = "#FF0000"`). Fixed by reordering (triple-quotes first) and protecting single/double-quoted strings with placeholders before stripping comments.
471
+ - **Bug D - Simplistic glob matching**: `walkDirectory` converted `**/node_modules/**` to `node_modules` via string replace, failing for patterns like `**/*.min.js`. Replaced with `picomatch` for proper glob matching.
472
+
473
+ ### Changed
474
+ - `semantic-edit.ts` refactored: extracted `applySemanticSplice()`, `findChunkBySymbol()`, `detectSignatureChange()` as pure functions.
475
+ - `repo-map.ts` extended: `generateRepoMap()` now builds and caches dependency graph alongside repo map. `repoMapToText()` appends architecture tier summary.
476
+ - Database schema: `chunks` table now stores `start_index`, `end_index`, `symbol_name` with migration for existing DBs.
477
+ - Test count: 464 → 473 tests across 21 test suites.
478
+
479
+ ### Dependencies
480
+ - Added `picomatch` (runtime) and `@types/picomatch` (dev) for proper glob matching.
481
+
482
+ ## [3.3.0] - 2026-03-13
483
+
484
+ ### Added
485
+ - **Context Heartbeat**: Silently re-injects critical session state
486
+ every ~15 tool calls to survive Claude Code's context compaction. Uses 4-layer
487
+ state re-injection:
488
+ - Layer 1 (Plan File): Anchored plan document via `set_plan`
489
+ - Layer 2 (Scratchpad): Claude's progress notes via `memorize` + pinned rules
490
+ - Layer 3 (Recent Edits): Files modified in this session
491
+ - Layer 4 (Circuit Breaker): Active escalation alerts if in Break & Build
492
+ - **`nreki_guard action:"set_plan"`**: Anchor a master plan file (PLAN.md, schemas).
493
+ Includes Bankruptcy Shield rejecting plans >4000 tokens to prevent context bloat.
494
+ - **`nreki_guard action:"memorize"`**: Claude writes progress notes to persistent scratchpad.
495
+ Notes survive context compaction and are re-injected during heartbeat.
496
+ - **Top-injection pattern**: Heartbeat injects state ABOVE the tool response, keeping the
497
+ immediate result at the bottom to respect the LLM's U-shaped attention curve.
498
+ - **Read-only filter**: Heartbeat only fires during context-gathering actions
499
+ (read, search, map, status, definition, references, outline). Never during
500
+ edit, undo, or filter_output to avoid distracting Claude during critical operations.
501
+ - **Restart Detection**: Heartbeat detects MCP server restarts (currentCalls < lastInjectCalls)
502
+ and resets the injection counter to prevent permanent heartbeat death.
503
+
504
+ ## [3.2.0] - 2026-03-13
505
+
506
+ ### Added
507
+ - **Auto-Context Inlining**: When Claude requests a definition or reads a file, NREKI
508
+ automatically resolves signatures of imported dependencies and injects them in the response.
509
+ Reduces follow-up tool calls by providing "X-ray vision" in a single turn.
510
+ - Import extraction supports ESM (named + default), CommonJS require, Python from-import,
511
+ and Go namespace inference.
512
+ - "Gold Filter": only injects dependencies actually used in the function body, using the
513
+ local alias name (not the original export name) for accurate matching.
514
+ - Security filter: signatures containing passwords, API keys, auth tokens, or encryption
515
+ keys are automatically excluded from injection.
516
+ - Anti-prompt-injection: JSDoc comments and NREKI stubs are stripped from signatures
517
+ before injection, preventing malicious content from entering Claude's context.
518
+ - Homonym disambiguation: BM25 searches combine symbol name + import path hint to find
519
+ the correct signature even when multiple files export the same name.
520
+ - 150ms hard timeout prevents event loop blocking on large codebases.
521
+ - `auto_context: false` parameter available on both `nreki_navigate` and `nreki_code` to disable.
522
+ - Session report tracks `autoContextInjections` count.
523
+ - **Go import support**: Auto-Context infers exported symbols from Go namespace usage patterns
524
+ (e.g., `utils.HashPassword()` resolves to `HashPassword` in the `utils` package).
525
+ - **Preloaded content in compressFileAdvanced**: Eliminates double file I/O when both
526
+ auto-context and compression are active on the same read.
527
+
528
+ ### Changed
529
+ - `CompressionLevel` type is now used explicitly instead of `as any` for level casting.
530
+ - `handleRead` reads the file exactly once and reuses the content for both auto-context
531
+ extraction and compression.
532
+
533
+ ## [3.1.3] - 2026-03-12
534
+
535
+ ### Fixed
536
+ - **Path normalization in Circuit Breaker**: All file paths are now resolved to absolute + forward slashes before recording. Prevents split counters where `"src/app.ts"` and `"/abs/path/src/app.ts"` were tracked as different files, causing Pattern 4 to never trigger.
537
+ - **Ghost data after file deletion**: `db.save()` is now called after the watcher's `unlink` event, ensuring deleted files don't reappear from disk on next session.
538
+ - **Plaintext fallback for unsupported languages**: Files with unsupported extensions (.rs, .java, .cpp, etc.) are now indexed as single plaintext chunks. BM25 keyword search works on all file types as documented in the README. AST features (validation, structural compression, semantic edit) still require TS/JS/Python/Go.
539
+
540
+ ## [3.1.2] - 2026-03-12
541
+
542
+ ### Fixed
543
+ - **Duplicate JSDoc on softReset**: Removed stale v3.0 comment that contradicted actual behavior.
544
+ - **Inflated grepEstimate**: Replaced arbitrary `× 3` multiplier with per-unique-file estimation. Added "(estimated)" to savings output.
545
+ - **@xenova/transformers moved to optionalDependencies**: `npm install` no longer downloads ~200MB of ONNX runtime for Lite mode users. Pro mode users can install it separately with `npm install @xenova/transformers`.
546
+
547
+ ## [3.1.1] - 2026-03-12
548
+
549
+ ### Fixed
550
+ - **Circuit breaker `redirectsIssued`**: No longer counts Level 3 hard stops as redirects.
551
+ - **Circuit breaker `softReset` amnesia total**: Purges all history entries for the tripped file, giving Claude 3 clean attempts with the new strategy instead of 1.
552
+ - **Breaker payloads instruct `compress:false`**: Level 1 and Level 2 redirects now tell Claude to read uncompressed code so it can understand the logic before rewriting.
553
+ - **Smart rebase for Python/Go**: Auto-indentation now strips Claude's indent and rebases to the target context, fixing IndentationError in Python and tab corruption in Go.
554
+ - **CRLF support**: Line start detection skips `\r` on Windows files.
555
+ - **Cross-platform byte indices**: Verifies tree-sitter byte offsets against actual content, falls back to indexOf if they differ across platforms.
556
+
557
+ ### Added
558
+ - **Behavioral Advisor (PreToolUseHook)**: Connected to `handleRead` - when Claude reads a file raw (compress:false), it gets a suggestion showing how many tokens it wasted and the exact command to compress next time.
559
+ - **Danger Zones in status**: `nreki_guard action:"status"` now shows the 5 heaviest unread files with estimated token counts. Files already read (raw or compressed) are filtered out dynamically.
560
+ - **CLI `--help` and `--version`**: Standard CLI hygiene. Version sourced from single `VERSION` constant.
561
+ - **Telemetry via social sharing**: Session report footer invites users to share their receipt on GitHub Discussions.
562
+ - **E2E breaker test**: Full integration test simulating 3 failures Level 1 redirect grace period recovery with insert_after.
563
+ - **5 topological edit tests**: insert_after, insert_before, auto-indent nested, syntax rejection, last-symbol edge case.
564
+
565
+ ### Removed
566
+ - `evaluateGrepOperation` and `countFiles` from PreToolUseHook (unreachable via MCP).
567
+ - `src/schemas.ts` (dead v2 code, zero imports).
568
+ - All "BOMBA" comments replaced with professional descriptions.
569
+
570
+ ### Changed
571
+ - CLAUDE.md point 3 now includes quantitative advice (5,000 tokens vs 1,200 tokens).
572
+ - `RouterDependencies.hook` is optional for backward compatibility.
573
+ - `engine.markFileRead()` called in both compress and raw read branches.
574
+
575
+ ## [3.1.0] - 2026-03-11
576
+
577
+ ### Added
578
+ - **Creative Circuit Breaker ("Break & Build")**: 3-level escalation system that redirects Claude with increasingly specific strategies instead of just blocking. Level 1: rewrite from scratch. Level 2: decompose into helpers. Level 3: hard stop, ask the human.
579
+ - **`nreki_guard action:"reset"`**: Escape hatch for humans to clear the circuit breaker and let Claude retry with a new approach.
580
+ - **`npx nreki init`**: CLI subcommand that generates a `CLAUDE.md` file with collaborative-tone instructions for Claude Code to prefer NREKI tools.
581
+ - **Redirect statistics**: Session report now tracks `redirectsIssued` and `redirectsSuccessful` to measure creative breaker effectiveness.
582
+
583
+ ### Performance
584
+ - **Batch SQL queries**: `searchHybrid`, `searchKeywordOnly`, and `searchVector` now use `WHERE id IN (...)` batch queries instead of N+1 individual queries per chunk ID.
585
+ - **BM25 TF precompute**: Term frequencies are precomputed at index time for O(1) lookup during search, replacing O(n) `filter()` scans.
586
+
587
+ ### Changed
588
+ - Circuit breaker `ToolCallRecord` now includes `symbolName` for contextual redirect payloads.
589
+ - Circuit breaker `trip()` now escalates `escalationLevel` (0→3) instead of just setting a boolean.
590
+ - `softReset()` preserves escalation level across retries, enabling progressive escalation.
591
+ - All version strings aligned to 3.1.0.
592
+
593
+ ### Tests
594
+ - 438 tests (was 423). Added 15 new tests for escalation levels, redirect payloads, symbolName tracking, and soft/hard reset behavior.
595
+
596
+ ---
597
+
598
+ ## [3.0.3] - 2026-03-11
599
+
600
+ ### Fixed
601
+ - **CI macOS/Windows**: `safePath` now calls `realpathSync` on the workspace root as well as the resolved path, fixing false-positive "Symlink escape blocked" errors on macOS where `/tmp` is a symlink to `/private/tmp`. All 423 tests pass on all platforms.
602
+
603
+ ---
604
+
605
+ ## [3.0.2] - 2026-03-10
606
+
607
+ ### Headline
608
+ docs: fix README Quick Start syntax, update test count to 423, update keywords, add security documentation.
609
+
610
+ ### Fixed
611
+ - **README Quick Start**: Replaced v2 `options:{}` syntax with v3 flat params (`text:`, `symbol:`, `new_code:`, `output:`).
612
+ - **README Quick Start**: Replaced `target:` with correct param names (`query:`, `symbol:`).
613
+ - **README**: Renamed `terminal` `filter_output` in nreki_code actions table, comparison table, architecture diagram, and Quick Start.
614
+ - **README**: Updated test count from 361 → 423 in title, badges, stress test section, and real-world validation.
615
+ - **README**: Updated test suites from 14 → 16.
616
+
617
+ ### Added
618
+ - **README Security section**: Documented symlink resolution, sensitive file blocklist, pin sanitization, and file-level mutex.
619
+
620
+ ### Changed
621
+ - **package.json**: Updated keywords to reflect v3 security focus (`code-safety`, `ast-validation`, `circuit-breaker`, `defensive-coding`, `ai-safety`, `surgical-edit`).
622
+ - **package.json**: Set author to `Ruso-0 (https://github.com/Ruso-0)`.
623
+ - **package.json**: Version bumped to 3.0.2.
624
+
625
+ ---
626
+
627
+ ## [3.0.0] - 2026-03-10
628
+
629
+ ### Headline
630
+ NREKI v3.0 - Architecture overhaul. 16 tools collapsed to 3 routers. Invisible middleware. Lite/Pro mode. 81% reduction in tool definition overhead.
631
+
632
+ ### BREAKING CHANGES
633
+ - **16 tools → 3 router tools**: All MCP tool names have changed. LLMs must use the new `nreki_navigate`, `nreki_code`, `nreki_guard` tool names with `action` parameters.
634
+ - **`nreki_validate` removed from MCP**: Now runs automatically as invisible middleware inside `nreki_code action:"edit"`. No manual calls needed.
635
+ - **`nreki_circuit_breaker` removed from MCP**: Now runs as passive middleware monitoring all tool calls. Auto-resets after 60s inactivity or when a different action is called.
636
+ - **`nreki_audit` removed from MCP**: Moved to CLI only. Use `npx @ruso-0/nreki --audit`.
637
+
638
+ ### Added - Router Pattern
639
+ - **`nreki_navigate`** - Unified navigation tool replacing `nreki_search`, `nreki_def`, `nreki_refs`, `nreki_outline`, `nreki_map`. Actions: `search`, `definition`, `references`, `outline`, `map`.
640
+ - **`nreki_code`** - Unified code tool replacing `nreki_read`, `nreki_compress`, `nreki_semantic_edit`, `nreki_undo`, `nreki_terminal`. Actions: `read`, `compress`, `edit`, `undo`, `terminal` (renamed to `filter_output` in v3.0.2).
641
+ - **`nreki_guard`** - Unified safety tool replacing `nreki_pin`, `nreki_status`, `nreki_session_report`. Actions: `pin`, `unpin`, `status`, `report`.
642
+ - `src/router.ts` - Central dispatcher mapping `{tool, action}` to handler functions (~700 lines).
643
+
644
+ ### Added - Invisible Middleware
645
+ - `src/middleware/validator.ts` - AST validation wrapper. Validates code via tree-sitter before disk writes inside `nreki_code action:"edit"`.
646
+ - `src/middleware/circuit-breaker.ts` - Passive circuit breaker. Wraps all handlers, records tool call results, trips on destructive patterns, auto-resets on action diversity or 60s inactivity.
647
+
648
+ ### Added - Lite / Pro Mode
649
+ - **Lite mode (default)**: Instant startup (~100ms). BM25 keyword-only search. No ONNX model dependency.
650
+ - **Pro mode (`--enable-embeddings`)**: Hybrid semantic + BM25 search with RRF fusion. Requires ONNX Runtime for jina-v2-small embeddings.
651
+ - `searchKeywordOnly()` method added to `NREKIDB` for Lite mode BM25 search.
652
+ - Engine methods (`indexFile`, `indexDirectory`, `search`, `getRepoMap`) now branch based on `enableEmbeddings` config.
653
+
654
+ ### Changed
655
+ - **`src/index.ts`**: Rewritten from ~1,479 lines (16 tool registrations) to ~180 lines (3 router registrations).
656
+ - **Tool definition overhead**: ~3,520 tokens → ~660 tokens (81% reduction).
657
+ - **Test count**: 305 → 361 tests across 14 test suites.
658
+ - **`package.json`**: Version bumped to 3.0.0. Description updated.
659
+ - **`README.md`**: Complete rewrite for v3.0 architecture.
660
+
661
+ ### Added - Tests
662
+ - `tests/router.test.ts` - 30 tests for router dispatch correctness across all 14 `{tool, action}` pairs.
663
+ - `tests/middleware.test.ts` - 13 tests for validator and circuit breaker middleware behavior.
664
+ - `tests/backward-compat.test.ts` - 13 tests verifying all 16 original tool behaviors work through the new 3-tool API.
665
+
666
+ ---
667
+
668
+ ## [2.1.2] - 2026-03-10
669
+
670
+ ### Headline
671
+ NREKI v2.1.2 - Lazy ONNX loading fixes MCP handshake timeout for real-world users.
672
+
673
+ ### Fixed
674
+ - **CRITICAL - MCP handshake timeout**: `engine.initialize()` was eagerly loading the ONNX embedding model (~5-10s) during startup, blocking ALL tool calls until the model was ready. Real users connecting via Claude Code would experience timeouts or slow first responses. Split initialization into two phases:
675
+ - **Fast path** (`initialize()`): SQLite + Tree-sitter only (~100ms). Used by 12/16 tools.
676
+ - **Embedder path** (`initializeEmbedder()`): Adds ONNX model load. Used only by `nreki_search`, `nreki_map`, and indexing operations.
677
+ - **`nreki_def` first-call latency**: Was 465ms because it waited for the embedder to load (which it doesn't use). Now completes in ~50ms on first call.
678
+ - Removed background `engine.initialize()` from `main()` - tools now self-initialize at the correct level when first called.
679
+
680
+ ### Changed
681
+ - **package.json**: Version bumped to 2.1.2.
682
+
683
+ ---
684
+
685
+ ## [2.1.1] - 2026-03-10
686
+
687
+ ### Headline
688
+ NREKI v2.1.1 - Final audit fixes, nreki_undo, 16 tools, 305 tests.
689
+
690
+ ### Added - New Tool
691
+ - **`nreki_undo`** - Undo the last `nreki_semantic_edit` on a file. Auto-restores from backup with one-shot semantics (backup is consumed after restore).
692
+
693
+ ### Added - New Module
694
+ - `src/undo.ts` - Backup/restore engine using base64url-encoded file paths. Stores pre-edit snapshots in `.nreki/backups/`.
695
+ - `src/utils/read-source.ts` - Shared BOM-safe file reader. Strips U+FEFF byte order marks from Windows-created source files.
696
+
697
+ ### Security
698
+ - **FIX 2 - XML injection prevention**: Pin content is now escaped (`&`, `<`, `>`, `"`, `'`) before storage to prevent prompt injection via pinned rules.
699
+
700
+ ### Fixed
701
+ - **FIX 1 - BOM stripping**: All source file readers now use `readSource()` to strip U+FEFF BOM, fixing parse failures on Windows-created files.
702
+ - **FIX 3 - Code tokenizer**: Rewritten to correctly handle `$scope`, `__proto__`, `_privateVar`, and other edge-case identifiers with `$`/`_` prefixes.
703
+ - **FIX 4 - Fast dot product**: Replaced cosine similarity with direct dot product for L2-normalized vectors. Removes sqrt/division overhead; mathematically equivalent for unit vectors.
704
+ - **FIX 6 - Pin order**: Pinned rules now appear AFTER repo map text (was before). Preserves Anthropic prompt cache hits since the static map stays at the start of context.
705
+ - **FIX 7 - Circuit breaker normalization**: `hashError()` now normalizes ISO timestamps and improved memory address normalization. Added 5-minute TTL eviction to prevent stale errors from tripping the breaker.
706
+ - **FIX 8 - ASCII receipt**: Replaced all Unicode box-drawing characters and emojis in session receipt and reports with ASCII equivalents for terminal compatibility.
707
+
708
+ ### Changed
709
+ - **Tool count**: 15 -> 16 MCP tools.
710
+ - **Test count**: 282 -> 305 tests across 11 test suites.
711
+ - **nreki_map**: Pinned rules now appended after repo map (was prepended before).
712
+ - **package.json**: Version bumped to 2.1.1.
713
+
714
+ ---
715
+
716
+ ## [2.1.0] - 2026-03-10
717
+
718
+ ### Headline
719
+ NREKI v2.1 - 15 MCP tools, 282 tests, circuit breaker, surgical edit, pin memory, session receipt.
720
+
721
+ ### Added - New Tools
722
+ - **`nreki_semantic_edit`** - Surgically edit a function/class/interface by name without reading or rewriting the entire file. Finds the exact AST node, replaces only those bytes, validates syntax before saving. Saves 98% of output tokens vs full file rewrites.
723
+ - **`nreki_circuit_breaker`** - Detects infinite failure loops (same error 3+ times, same file 5+ times, write-test-fail cycles). When tripped, forces Claude to stop and ask the human for guidance. Prevents doom loops that burn through remaining context.
724
+ - **`nreki_pin`** - Pin important rules Claude should never forget. Pinned items are injected into every `nreki_map` response, keeping project conventions permanently in Claude's attention window. Max 10 pins, 200 chars each, persisted to disk.
725
+
726
+ ### Added - New Modules
727
+ - `src/semantic-edit.ts` - Zero-read surgical AST patching. Symbol name lookup, byte-level splice, syntax validation before write.
728
+ - `src/circuit-breaker.ts` - Loop detection engine with sliding window analysis, consecutive failure tracking, and automatic trip/reset.
729
+ - `src/pin-memory.ts` - Persistent pinned rules with deterministic output (sorted by id) for prompt cache compatibility.
730
+
731
+ ### Added - Session Receipt
732
+ - `nreki_session_report` now generates an ASCII receipt showing input tokens saved, output tokens avoided, search queries, surgical edits, syntax errors blocked, doom loops prevented, pinned rules active, estimated USD savings, and model info.
733
+
734
+ ### Changed
735
+ - **Tool count**: 12 -> 15 MCP tools.
736
+ - **Test count**: 194 -> 282 tests across 11 test suites.
737
+ - **nreki_map**: Now prepends pinned rules at the top of the repo map output.
738
+ - **README**: Complete rewrite for v2.1 with comparison table, 3 unique features highlight, receipt preview, and updated architecture diagram.
739
+ - **package.json**: Version bumped to 2.1.0.
740
+
741
+ ### Architecture
742
+ - **Pin memory layer**: Pinned rules are stored in `.nreki/pins.json` and prepended to every `nreki_map` response. Deterministic output (sorted by id) preserves prompt cache compatibility.
743
+ - **Circuit breaker integration**: `nreki_terminal` automatically feeds errors to the circuit breaker for proactive loop detection.
744
+
745
+ ## [2.0.0] - 2026-03-10
746
+
747
+ ### Headline
748
+ NREKI v2.0 - 12 MCP tools, 194 tests, cache-aware two-layer architecture.
749
+
750
+ ### Added - New Tools
751
+ - **`nreki_def`** - Go-to-definition by symbol name. AST-based, 100% precise, returns full source body with signature.
752
+ - **`nreki_refs`** - Find all references to a symbol across the project. Cross-file word-boundary matching with context.
753
+ - **`nreki_outline`** - List all symbols in a file with kind, signature, export status, and line ranges. Like VS Code Outline.
754
+ - **`nreki_validate`** - AST sandbox validator. Parses code with tree-sitter before disk write. Catches missing commas, unclosed braces, invalid syntax with exact line/column and fix suggestions. Prevents the "write broken code → see error → retry" token burn loop.
755
+
756
+ ### Added - New Modules
757
+ - `src/ast-navigator.ts` - AST navigation engine for nreki_def, nreki_refs, nreki_outline. Walks project files, extracts symbols, signatures, export status.
758
+ - `src/ast-sandbox.ts` - AST sandbox validator with `validateCode()` and `validateDiff()`. Recursive tree walk with `hasError` subtree pruning for large-file performance.
759
+ - `src/terminal-filter.ts` - Terminal entropy filter. Strips ANSI codes, deduplicates stack traces, extracts unique errors and affected files. 89% token reduction on error output.
760
+ - `src/repo-map.ts` - Static deterministic repo map for Anthropic prompt cache optimization. Identical output for same repo state enables $0.30/M caching vs $3.00/M input.
761
+
762
+ ### Changed
763
+ - **Embeddings**: Migrated from all-MiniLM-L6-v2 (384-dim) to jina-embeddings-v2-small-en (512-dim) for 3x better code search precision.
764
+ - **BM25 tuning**: Optimized k1=1.8, b=0.35 for code (vs default k1=1.2, b=0.75 for prose).
765
+ - **RRF tuning**: k=10 for sharper rank fusion (vs k=60 default).
766
+ - **Code tokenizer**: camelCase, snake_case, PascalCase identifiers split into sub-tokens for better BM25 matching.
767
+ - **Tool count**: 6 → 12 MCP tools.
768
+ - **Test count**: 90 → 194 tests across 8 test suites.
769
+ - **README**: Complete rewrite with self-benchmark results, two-layer architecture docs, and updated comparison table.
770
+
771
+ ### Architecture
772
+ - **Two-layer design**: Layer 1 (static repo map, prompt-cacheable) + Layer 2 (dynamic context, per-query).
773
+ - **Cache-friendly**: nreki_map output is deterministic - same repo state produces identical text, enabling Anthropic prompt caching.
774
+
775
+ ### Performance (Self-Benchmark)
776
+ - nreki_search: 10 results in 16ms (hybrid RRF fusion)
777
+ - nreki_def: Definition lookup in 128ms across 22 files
778
+ - nreki_refs: 20 references found in 11ms
779
+ - nreki_outline: 25 symbols extracted in 7ms
780
+ - nreki_compress: 5,502 → 1,753 tokens (68% reduction, medium level)
781
+ - nreki_terminal: 11,967 → 1,276 tokens (89% reduction)
782
+ - nreki_validate: Syntax error detection with line/column in <1ms
783
+ - nreki_map: 22 files mapped, 4,677 tokens, 169ms
784
+
785
+ ## [1.2.0] - 2026-03-10
786
+
787
+ ### Security
788
+ - **Path traversal protection**: All file operations now validate paths stay within workspace root (`safePath`)
789
+ - **Input validation**: All tool inputs validated with Zod schemas before processing
790
+ - **File size limits**: Files > 500KB and binary/minified files are automatically skipped
791
+
792
+ ### Fixed
793
+ - **WASM memory leaks**: Tree-sitter parse trees now guaranteed cleanup via `safeParse` try/finally wrapper
794
+ - **Event loop blocking**: Large indexing operations now yield every 100 files via `setImmediate`
795
+ - **Aggressive compression stubs**: Functions now show line count, key references, and expand commands instead of empty bodies
796
+ - **Search tokenization**: Code identifiers (camelCase, snake_case, PascalCase) are now split into sub-tokens for better matching
797
+ - **Vector search accuracy**: Cosine similarity now uses proper norm computation instead of raw dot product
798
+ - **RRF scoring**: Verified correct rank-based fusion (was already using positions, not scores)
799
+
800
+ ### Added
801
+ - `src/utils/path-jail.ts` - Path traversal protection
802
+ - `src/utils/safe-parse.ts` - WASM memory-safe parsing
803
+ - `src/utils/file-filter.ts` - File size and extension filtering
804
+ - `src/utils/code-tokenizer.ts` - Code-aware identifier tokenization
805
+ - `src/schemas.ts` - Zod validation schemas for all tools
806
+ - `.github/workflows/ci.yml` - CI/CD with matrix testing (3 OSes × 3 Node versions)
807
+ - `CONTRIBUTING.md` - Contributor guide
808
+ - `CHANGELOG.md` - This file
809
+ - `.github/ISSUE_TEMPLATE/bug_report.md`
810
+ - `.github/ISSUE_TEMPLATE/feature_request.md`
811
+ - Comprehensive test suite for all new utilities
812
+
813
+ ### Performance
814
+ - Pre-computed vector norms at index time (avoids recalculation during search)
815
+ - Proper cosine similarity with normalized vectors
816
+
817
+ ## [1.1.1] - 2026-03-09
818
+
819
+ ### Initial Release
820
+ - MCP server with 6 tools: nreki_search, nreki_audit, nreki_compress, nreki_status, nreki_session_report, nreki_read
821
+ - Hybrid RRF search (BM25 + vector similarity)
822
+ - Three-tier classic compression + LLMLingua-2-inspired advanced compression
823
+ - Real-time file watching with chokidar
824
+ - Token consumption monitoring and burn rate prediction
825
+ - Pre-tool-use interception hook