@ruso-0/nreki 7.1.1 → 7.3.0

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