@ruso-0/nreki 7.1.2 → 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 (87) hide show
  1. package/CHANGELOG.md +805 -774
  2. package/README.md +308 -442
  3. package/dist/ast-sandbox.d.ts.map +1 -1
  4. package/dist/ast-sandbox.js +17 -1
  5. package/dist/ast-sandbox.js.map +1 -1
  6. package/dist/audit.d.ts.map +1 -1
  7. package/dist/audit.js +10 -4
  8. package/dist/audit.js.map +1 -1
  9. package/dist/chronos-memory.d.ts.map +1 -1
  10. package/dist/chronos-memory.js +10 -2
  11. package/dist/chronos-memory.js.map +1 -1
  12. package/dist/compressor.d.ts.map +1 -1
  13. package/dist/compressor.js +13 -1
  14. package/dist/compressor.js.map +1 -1
  15. package/dist/database.d.ts +12 -1
  16. package/dist/database.d.ts.map +1 -1
  17. package/dist/database.js +81 -29
  18. package/dist/database.js.map +1 -1
  19. package/dist/embedder.d.ts.map +1 -1
  20. package/dist/embedder.js +7 -2
  21. package/dist/embedder.js.map +1 -1
  22. package/dist/handlers/code.d.ts.map +1 -1
  23. package/dist/handlers/code.js +198 -243
  24. package/dist/handlers/code.js.map +1 -1
  25. package/dist/handlers/guard.d.ts.map +1 -1
  26. package/dist/handlers/guard.js +10 -1
  27. package/dist/handlers/guard.js.map +1 -1
  28. package/dist/hologram/shadow-generator.d.ts.map +1 -1
  29. package/dist/hologram/shadow-generator.js +20 -1
  30. package/dist/hologram/shadow-generator.js.map +1 -1
  31. package/dist/kernel/backends/lsp-sidecar-base.d.ts +49 -5
  32. package/dist/kernel/backends/lsp-sidecar-base.d.ts.map +1 -1
  33. package/dist/kernel/backends/lsp-sidecar-base.js +209 -69
  34. package/dist/kernel/backends/lsp-sidecar-base.js.map +1 -1
  35. package/dist/kernel/backends/ts-compiler-wrapper.d.ts +1 -1
  36. package/dist/kernel/backends/ts-compiler-wrapper.d.ts.map +1 -1
  37. package/dist/kernel/backends/ts-compiler-wrapper.js +7 -4
  38. package/dist/kernel/backends/ts-compiler-wrapper.js.map +1 -1
  39. package/dist/kernel/backends/ts-corsa-sidecar.d.ts +26 -0
  40. package/dist/kernel/backends/ts-corsa-sidecar.d.ts.map +1 -0
  41. package/dist/kernel/backends/ts-corsa-sidecar.js +30 -0
  42. package/dist/kernel/backends/ts-corsa-sidecar.js.map +1 -0
  43. package/dist/kernel/nreki-kernel.d.ts +37 -0
  44. package/dist/kernel/nreki-kernel.d.ts.map +1 -1
  45. package/dist/kernel/nreki-kernel.js +669 -290
  46. package/dist/kernel/nreki-kernel.js.map +1 -1
  47. package/dist/kernel/spectral-topology.d.ts.map +1 -1
  48. package/dist/kernel/spectral-topology.js +32 -16
  49. package/dist/kernel/spectral-topology.js.map +1 -1
  50. package/dist/middleware/circuit-breaker.d.ts.map +1 -1
  51. package/dist/middleware/circuit-breaker.js +18 -2
  52. package/dist/middleware/circuit-breaker.js.map +1 -1
  53. package/dist/middleware/file-lock.d.ts.map +1 -1
  54. package/dist/middleware/file-lock.js +8 -3
  55. package/dist/middleware/file-lock.js.map +1 -1
  56. package/dist/monitor.d.ts.map +1 -1
  57. package/dist/monitor.js +1 -0
  58. package/dist/monitor.js.map +1 -1
  59. package/dist/parser.d.ts.map +1 -1
  60. package/dist/parser.js +19 -2
  61. package/dist/parser.js.map +1 -1
  62. package/dist/pin-memory.d.ts +2 -2
  63. package/dist/pin-memory.d.ts.map +1 -1
  64. package/dist/pin-memory.js.map +1 -1
  65. package/dist/repo-map.d.ts.map +1 -1
  66. package/dist/repo-map.js +26 -0
  67. package/dist/repo-map.js.map +1 -1
  68. package/dist/router.d.ts.map +1 -1
  69. package/dist/router.js +58 -18
  70. package/dist/router.js.map +1 -1
  71. package/dist/undo.js +1 -1
  72. package/dist/undo.js.map +1 -1
  73. package/dist/utils/imports.d.ts.map +1 -1
  74. package/dist/utils/imports.js +8 -4
  75. package/dist/utils/imports.js.map +1 -1
  76. package/dist/utils/latency-tracker.d.ts +22 -0
  77. package/dist/utils/latency-tracker.d.ts.map +1 -0
  78. package/dist/utils/latency-tracker.js +49 -0
  79. package/dist/utils/latency-tracker.js.map +1 -0
  80. package/dist/utils/logger.d.ts +5 -2
  81. package/dist/utils/logger.d.ts.map +1 -1
  82. package/dist/utils/logger.js +29 -6
  83. package/dist/utils/logger.js.map +1 -1
  84. package/dist/utils/path-jail.d.ts.map +1 -1
  85. package/dist/utils/path-jail.js +3 -0
  86. package/dist/utils/path-jail.js.map +1 -1
  87. package/package.json +96 -79
package/README.md CHANGED
@@ -1,442 +1,308 @@
1
- # NREKI - 3 Tools. 704 Tests. Pre-write validation for AI agents.
2
-
3
- <p align="center">
4
- <img src="https://img.shields.io/badge/MCP-Plugin-blue?style=for-the-badge" alt="MCP Plugin">
5
- <img src="https://img.shields.io/badge/Tools-3-blueviolet?style=for-the-badge" alt="3 Tools">
6
- <img src="https://img.shields.io/badge/Tests-704-brightgreen?style=for-the-badge" alt="704 Tests">
7
- <img src="https://img.shields.io/badge/Cloud-Zero-orange?style=for-the-badge" alt="Zero Cloud">
8
- <img src="https://img.shields.io/badge/License-Apache_2.0-yellow?style=for-the-badge" alt="Apache 2.0 License">
9
- <img src="https://img.shields.io/badge/TypeScript-5.9-3178C6?style=for-the-badge" alt="TypeScript 5.9">
10
- <img src="https://img.shields.io/badge/Node-%3E%3D20-339933?style=for-the-badge" alt="Node >=20">
11
- </p>
12
-
13
- <p align="center">
14
- <b>MCP server that validates AI agent edits in RAM before they reach disk. Cross-file semantic checks, auto-fixes for structural errors, and type regression detection.</b>
15
- </p>
16
-
17
- ---
18
-
19
- ## What's New in v7.0: Software Physics Engine
20
-
21
- NREKI v7.0 turns the spectral topology gate into a full physics engine. Every proposed edit now produces eigenvector coordinates — Fiedler vectors (v2) map bridge fragility, third eigenvectors (v3) map topological stress, and gauge fixing ensures deterministic sign across commits (critical for ML pipelines).
22
-
23
- Key additions:
24
- - **Fiedler Vector (v2)**: Full eigenvector extraction — per-node bridge fragility map
25
- - **Third eigenvalue (λ₃) + eigenvector (v3)**: Spectral gap ∇(λ₃ - λ₂) enables predictive analysis
26
- - **Gauge Fixing**: Deterministic phase canonicalization prevents sign ambiguity across commits
27
- - **Monorepo workspace resolution**: `buildFastLookup` resolves `@org/package` imports via O(1) string math
28
- - **Adaptive Shotgun Surgery**: Threshold scales with repo size — no more false positives on large codebases
29
- - **Modern module extensions**: Full `.mts`, `.cts`, `.mjs`, `.cjs` support across all subsystems
30
- - **32+ audit fixes**: VFS zombie state, WASM race conditions, extractName regex purge, and more (see CHANGELOG)
31
-
32
- ---
33
-
34
- ## What's New in v6.0: JIT Holography
35
-
36
- When an LLM forgets an import, drops an `async` keyword, or leaves an interface incomplete, NREKI now **auto-corrects the error in RAM** using TypeScript's CodeFix API - the same engine behind VS Code's "Quick Fix" lightbulb. The LLM never sees the error. Zero tokens wasted on fix-retry loops.
37
-
38
- ```
39
- LLM proposes edit
40
- |
41
- v
42
- NREKI intercepts in RAM
43
- |
44
- v
45
- Triple Shield (Global -> Syntactic -> Semantic)
46
- |
47
- +-- No errors? --> Two-Phase Atomic Commit to disk
48
- |
49
- +-- Errors found?
50
- |
51
- v
52
- Auto-Heal: getCodeFixesAtPosition()
53
- |
54
- +-- Apply 1 fix --> Recompile (~20ms) --> Errors decreased?
55
- | +-- Yes --> Accept fix, loop for next error
56
- | +-- No --> Micro-rollback this fix, blacklist it
57
- |
58
- +-- All errors resolved? --> Commit to disk (safe: true)
59
- +-- Some remain? --> Full rollback, return errors to LLM (safe: false)
60
- ```
61
-
62
- **8 structural fixes** in the whitelist: `import`, `fixMissingImport`, `fixAwaitInSyncFunction`, `fixPromiseResolve`, `fixMissingProperties`, `fixClassDoesntImplementInheritedAbstractMember`, `fixAddMissingMember`, `fixAddOverrideModifier`. Business logic is never mutated.
63
-
64
- See [CHANGELOG.md](CHANGELOG.md) for full details.
65
-
66
- ### Performance Modes (v6.0)
67
-
68
- NREKI auto-selects validation depth based on project size. No configuration needed.
69
-
70
- | Mode | Files | What it checks | Boot | RAM |
71
- |------|-------|---------------|------|-----|
72
- | Syntax | < 50 | Syntax only (Tree-sitter) | < 100ms | ~30MB |
73
- | Project | 50-1000 | Full cross-file semantic validation | 1-10s | 200MB-1GB |
74
- | Hologram | > 1000 | Full cross-file via .d.ts shadows | ~1-2s | ~350MB |
75
-
76
- **Hologram mode (v6.0):** For large projects (>1000 files), NREKI replaces full `.ts` source files with lightweight `.d.ts` shadow stubs in the TypeScript compiler's VFS. Only the currently-edited file and its import subgraph are loaded. A symbiotic harvester replaces heuristic shadows with compiler-grade `.d.ts` during idle cycles.
77
-
78
- Override in package.json: `{ "nreki": { "mode": "project" } }`
79
-
80
- ### VSCode Benchmark (5,584 files)
81
-
82
- | Metric | Project mode | File mode | Hologram (JIT) |
83
- |--------|-------------|-----------|----------------|
84
- | Boot | 111s | 91.6s | 1.94s |
85
- | First edit | 644ms | 55ms | 1384ms |
86
- | Total (boot + edit) | ~112s | ~92s | 3.32s |
87
- | RAM | OOM (16GB) | 4.5GB | ~350MB |
88
- | Files loaded | 5,584 | 5,584 | 642 on-demand |
89
- | Cross-file checking | Full cascade | Edited only | Via shadows |
90
- | VSCode files modified | 0 | 0 | 0 |
91
-
92
- Hologram mode uses domain separation: the holographic kernel validates edits via shadows,
93
- while Layer 1 AST navigator handles reference queries and refactoring.
94
-
95
- **vs Project Corsa:** Microsoft's [TypeScript 7 native port](https://devblogs.microsoft.com/typescript/progress-on-typescript-7-december-2025/) (Go, multi-threaded) reports 8.74s for VSCode type-checking. NREKI JIT Holography achieves 3.32s total (boot + first edit) in single-threaded JavaScript by skipping 88% of files via on-demand shadow classification.
96
-
97
- ### Type Regression Detection (v5.3)
98
-
99
- Detects when an agent weakens types silently. TypeScript approves `RetryConfig` changed
100
- to `any` because `any` accepts everything. NREKI catches it.
101
-
102
- Compares pre-edit and post-edit type signatures using toxicity scoring.
103
- Detects structural collapse (`Promise<any>` to `any`) and wrapper primitives
104
- (`string` to `String`).
105
-
106
- ---
107
-
108
- ## The Problem
109
-
110
- AI coding agents (Claude Code, Cursor, Copilot Workspace) edit files autonomously. When they change a function signature in one file, they break every file that depends on it. You find out when tests fail - or worse, in production. The agent then burns thousands of tokens reading error output, guessing fixes, and retrying - a doom loop that wastes your context window.
111
-
112
- ---
113
-
114
- ## The Solution
115
-
116
- | What you do now | What NREKI does | Savings |
117
- |-----------------|-----------------|---------|
118
- | `cat file.ts` (full file read) | `nreki_code action:"read"` (smart compression) | ~60-80% fewer tokens |
119
- | Native `edit_file` (blind write) | `nreki_code action:"edit"` (symbol-targeted + ACID validation) | Zero broken writes |
120
- | Read error → fix → retry → repeat | Auto-Healing L3.3 fixes structural errors in RAM | Zero doom loop tokens |
121
- | Manual `find_references` per file | `nreki_navigate action:"prepare_refactor"` (blast radius) | Prevents cascade breaks |
122
- | Agent manages 16 tool definitions | 3 tools, 19 actions | 81% less tool definition overhead |
123
-
124
- ---
125
-
126
- ## The 3 Tools
127
-
128
- ### `nreki_navigate` - Find and understand code
129
-
130
- | Action | What It Does |
131
- |--------|-------------|
132
- | `search` | Hybrid BM25 + semantic search (Pro) or keyword search (Lite) |
133
- | `definition` | Go-to-definition by symbol name |
134
- | `references` | Find all references cross-project |
135
- | `outline` | List symbols in a file with signatures |
136
- | `map` | Static repo map with PageRank scoring and pinned rules |
137
- | `prepare_refactor` | Shows which files depend on a symbol before you edit it |
138
-
139
- ### `nreki_code` - Read, write, and validate code
140
-
141
- | Action | What It Does |
142
- |--------|-------------|
143
- | `read` | Smart file reading with auto-compression |
144
- | `compress` | 3 levels (light/medium/aggressive) or 6 granular tiers |
145
- | `edit` | Surgical edit by symbol name. Validated by Tree-sitter AST + NREKI Kernel |
146
- | `batch_edit` | Multi-file atomic edit with two-phase file locking. All-or-nothing |
147
- | `undo` | Restore last edit from backup |
148
- | `filter_output` | Filter and compress terminal output |
149
-
150
- ### `nreki_guard` - Safety controls and session management
151
-
152
- | Action | What It Does |
153
- |--------|-------------|
154
- | `pin` | Add persistent rules injected into every map response |
155
- | `unpin` | Remove a pinned rule |
156
- | `status` | Token burn rate and depletion prediction |
157
- | `report` | Session receipt with USD cost estimates |
158
- | `reset` | Reset session counters |
159
- | `set_plan` | Store a plan file for context heartbeat |
160
- | `memorize` | Store scratchpad notes for context survival |
161
-
162
- **3 tools, 19 actions.** ~660 tokens of tool definitions instead of ~3,520. 81% reduction in fixed overhead.
163
-
164
- ---
165
-
166
- ## Invisible Middleware
167
-
168
- These layers run automatically on every edit. You never call them directly.
169
-
170
- | Layer | What It Does |
171
- |-------|-------------|
172
- | **AST Validation** | Tree-sitter parses the proposed code before any write. Catches syntax errors in sub-millisecond time. Works for TS, JS, Python, Go. |
173
- | **Circuit Breaker** | Detects doom loops (repeated failures on the same file). 3-level escalation: Rewrite strategy → Decompose → Hard Stop. |
174
- | **NREKI Kernel (L2)** | Cross-file semantic validation in RAM via TypeScript Compiler API. Triple Shield: Global → Syntactic → Semantic. ACID rollback on failure. |
175
- | **Auto-Healing** | When the kernel detects structural errors, attempts repair using `ts.LanguageService.getCodeFixesAtPosition()`. Each fix must reduce error count or it is reverted. |
176
-
177
- ---
178
-
179
- ## Architecture
180
-
181
- ```
182
- +---------------------------------------------------------+
183
- | Claude Code Agent |
184
- | (nreki_navigate, nreki_code, nreki_guard) |
185
- +----------------------------+----------------------------+
186
- |
187
- v
188
- +---------------------------------------------------------+
189
- | NREKI Router (src/router.ts) |
190
- | Context Heartbeat | Circuit Breaker | File Lock |
191
- +----------------------------+----------------------------+
192
- |
193
- +---------+-----------+
194
- v v
195
- +------------------+ +-------------------------------+
196
- | Layer 1 | | Layer 2 |
197
- | Tree-sitter | | NREKI Kernel |
198
- | (syntax) | | (cross-file semantics) |
199
- | | | |
200
- | Sub-ms AST | | TypeScript Compiler API |
201
- | validation | | hijacked with VFS in RAM |
202
- | | | |
203
- | All languages | | TS/JS only (tsconfig.json) |
204
- +------------------+ | |
205
- | * Global + syntax + semantic |
206
- | diagnostics |
207
- | * Auto-fix via CodeFix API |
208
- | (8 structural fix types) |
209
- | * ACID transactions |
210
- | * Two-phase atomic commit |
211
- | * Reference analysis |
212
- | * Import graph scoring |
213
- | * ~50ms rollback |
214
- | * Performance modes |
215
- | (syntax/file/project) |
216
- +-------------------------------+
217
- ```
218
-
219
- ---
220
-
221
- ## Installation
222
-
223
- ```bash
224
- # Quick start
225
- npx @ruso-0/nreki
226
-
227
- # Or install globally
228
- npm install -g @ruso-0/nreki
229
- ```
230
-
231
- ### Claude Code CLI
232
-
233
- ```bash
234
- # Lite mode (default - instant startup, BM25 search)
235
- claude mcp add nreki -- npx @ruso-0/nreki
236
-
237
- # Pro mode (hybrid semantic + BM25 search, ~5-10s startup)
238
- claude mcp add nreki -- npx @ruso-0/nreki --enable-embeddings
239
- ```
240
-
241
- ### Manual Configuration
242
-
243
- Add to `.claude/settings.json`:
244
-
245
- ```json
246
- {
247
- "mcpServers": {
248
- "nreki": {
249
- "command": "npx",
250
- "args": ["@ruso-0/nreki"]
251
- }
252
- }
253
- }
254
- ```
255
-
256
- ### Modes
257
-
258
- | | Lite (Default) | Pro (Opt-in) |
259
- |---|---|---|
260
- | **Startup** | Instant (~100ms) | ~5-10s (ONNX model load) |
261
- | **Search** | BM25 keyword search | Hybrid semantic + BM25 with RRF |
262
- | **Layer 2** | Active if tsconfig.json present | Active if tsconfig.json present |
263
- | **Enable** | Default | `--enable-embeddings` flag |
264
-
265
- Layer 2 (NREKI Kernel) activates automatically in any TypeScript/JavaScript project with a `tsconfig.json`. Non-TypeScript projects operate with Layer 1 (Tree-sitter syntax validation) only.
266
-
267
- ---
268
-
269
- ## Quick Start
270
-
271
- ```bash
272
- # Search for a function
273
- nreki_navigate action:"search" query:"getUserId"
274
-
275
- # Read a file with compression
276
- nreki_code action:"read" file:"src/auth.ts"
277
-
278
- # Surgically edit a function (NREKI validates before writing)
279
- nreki_code action:"edit" file:"src/auth.ts" symbol:"getUserId" new_code:"..."
280
-
281
- # Atomic multi-file edit
282
- nreki_code action:"batch_edit" edits:[{path:"src/auth.ts", symbol:"getUserId", new_code:"..."}, ...]
283
-
284
- # Check blast radius before refactoring
285
- nreki_navigate action:"prepare_refactor" file:"src/auth.ts" symbol:"getUserId"
286
-
287
- # Pin a persistent rule
288
- nreki_guard action:"pin" text:"Never use 'any' type in this project"
289
-
290
- # Check token budget
291
- nreki_guard action:"status"
292
- ```
293
-
294
- ---
295
-
296
- ## Tests
297
-
298
- **704 tests across 43 suites. Zero failures.**
299
-
300
- | Suite | Tests | What It Covers |
301
- |-------|-------|---------------|
302
- | nreki-kernel | 28 | Boot, semantic validation, syntactic shield, baseline tolerance, file operations, ACID, concurrency, edge cases, precision |
303
- | auto-healing | 6 | Missing import heal, await/async heal, cascade micro-rollback, business logic rejection, healingStats, clean code passthrough |
304
- | nreki-integration | 8 | Zero-disk-touch path, type-breaking block, batch dryRun, atomic commit, path traversal rejection |
305
- | router | 32 | All 19 actions across 3 tools, error handling, parameter validation |
306
- | security | 48 | Path traversal, symlink escape, injection, sensitive file blocking, circuit breaker, pin sanitization |
307
- | circuit-breaker | 45 | 3-level escalation, reset behavior, threshold detection |
308
- | stress | 37 | Concurrent operations, large file handling, memory pressure |
309
- | semantic-edit | 24 | Symbol targeting, mode switching, edge cases |
310
- | audit-fixes | 54 | All 30 audit findings verified resolved |
311
- | repo-map | 22 | PageRank scoring, import graph, classification |
312
- | Other suites | 261 | Engine, middleware, terminal filter, pin memory, compressor, AST, batch edit, backward compat, heartbeat, file lock, auto-context, v4 bugfixes, e2e breaker, parser-pool, mutex, document-registry, tsbuildinfo-cache |
313
- | mode-detection | 20 | Mode auto-detection, syntax/file/project behavior, elastic threshold, early exit recovery |
314
- | ttrd-silent-crime | 1 | Silent type degradation caught by TTRD |
315
- | ttrd | 19 | Type regression detection, toxicity scoring, barrel guards |
316
- | chronos-memory | 16 | Cross-session friction tracking, health score |
317
- | hologram | 45 | Shadow generation, VFS integration, lazy subgraph, domain separation, harvester, full cycle |
318
- | jit-holography | 15 | JIT on-demand classification, cache, rollback, interceptAtomicBatch |
319
-
320
- ---
321
-
322
- ## Real-World Benchmark: OpenDota (148 files, 1,600+ stars)
323
-
324
- | Test | Result | Latency | Details |
325
- |------|--------|---------|---------|
326
- | Boot | SUCCESS | 7.39s | 148 files tracked, 0 baseline errors |
327
- | Valid edit | PASS | 2,062ms | Appending a comment - no false positive |
328
- | Type break | **CAUGHT** | 7,230ms | Changed `getPGroup()` return type - cross-file error caught |
329
- | Syntax break | **CAUGHT** | 3,774ms | `return const let;` - blocked |
330
- | File delete | PASS | 1,596ms | Leaf file deletion - correctly allowed |
331
- | Non-TS file | PASS | 2,907ms | README.md - correctly ignored |
332
-
333
- **6/6 correct verdicts** against a real TypeScript project. Zero false positives. Zero false negatives.
334
-
335
- ---
336
-
337
- ## Security
338
-
339
- - **Zero cloud, zero telemetry, zero network calls** - everything runs locally
340
- - **Embeddings computed locally** via ONNX Runtime (optional `@xenova/transformers`)
341
- - **Path traversal protection** - `safePath()` in middleware + kernel-level path jail in `interceptAtomicBatch()`
342
- - **Sensitive file blocking** - `.env`, `.pem`, `.key`, `id_rsa`, `id_ed25519` rejected by VFS hijack
343
- - **SQLite storage** - all data in local `.nreki.db`, no external services
344
- - **WASM memory safety** - `safeParse()` with cleanup for Tree-sitter parsers
345
- - **30/30 audit findings resolved** in v5.0.0 (see `tests/audit-fixes.test.ts`)
346
-
347
- ---
348
-
349
- ## Numbers
350
-
351
- | Metric | Value |
352
- |--------|-------|
353
- | Tests | 704 (43 suites) |
354
- | Failure modes sealed | 32 (P1-P32) |
355
- | Audit findings resolved | 30/30 |
356
- | OpenDota benchmark | 6/6 correct verdicts |
357
- | Auto-Healing safe fixes | 8 CodeFix types |
358
- | Boot time (148 files) | 7.39s |
359
- | Warm-path rollback | ~50ms |
360
- | Blast radius query | ~20ms |
361
- | PageRank convergence (1,000 files) | < 50ms |
362
- | Tool definition overhead | ~660 tokens (81% reduction from v2) |
363
- | VSCode benchmark (5,584 files) | JIT boot 1.94s, total 3.32s, 642 files on-demand |
364
- | Mode detection | 85ms for 5,584 files |
365
-
366
- ---
367
-
368
- ## Honest Limitations
369
-
370
- ### Small Projects Don't Need the Kernel
371
-
372
- NREKI auto-detects project size. Projects under 50 files run in syntax mode (Tree-sitter only, no compiler). The kernel only boots for projects with 50+ files where cross-file validation matters.
373
-
374
- ### TypeScript Compiler API Dependency
375
-
376
- The NREKI Kernel depends on `ts.createEmitAndSemanticDiagnosticsBuilderProgram` and `ts.LanguageService`. These are public APIs but Microsoft modifies them between major TypeScript versions. NREKI pins `typescript@^5.9.3` and tests against each release. If TypeScript 6.0 introduces breaking changes, NREKI will require updates.
377
-
378
- ### Auto-Healing Is Conservative
379
-
380
- The healer only applies 8 structural fix types from a strict whitelist. It will not fix business logic errors, type mismatches, or architectural mistakes. If the healer cannot resolve ALL errors, it rolls back completely and returns the original errors to the LLM. This is by design - partial healing could mask bugs.
381
-
382
- ### Token Savings Are Estimates
383
-
384
- Token savings reported in tool responses use a `characters / 3.5` heuristic, not actual BPE tokenization. Real savings may differ by 20-40% depending on code density. The savings are real - the exact numbers are approximate.
385
-
386
- ### Language Coverage
387
-
388
- | Language | Layer 1 (Syntax) | Layer 2 (Semantics) | Auto-Healing (L3.3) |
389
- |----------|:-:|:-:|:-:|
390
- | TypeScript | Yes | Yes | Yes |
391
- | JavaScript | Yes | Yes | Yes |
392
- | Python | Yes | No | No |
393
- | Go | Yes | No | No |
394
-
395
- Layer 2 and Auto-Healing require `tsconfig.json`. Python and Go projects operate with Layer 1 syntax validation only.
396
-
397
- ---
398
-
399
- ## Technical Deep Dive
400
-
401
- ### The Intercept Cycle
402
-
403
- 1. **Inject** - All edits enter VFS staging simultaneously (atomic batch)
404
- 2. **Compile** - Incremental builder evaluates proposed future state
405
- 3. **Shield 1** - Global diagnostics (TS6053, TS2307)
406
- 4. **Shield 2** - Syntactic diagnostics on edited files only
407
- 5. **Shield 3** - Semantic diagnostics on all affected files (cross-file blast radius)
408
- 6. **Auto-Heal** - If errors found, attempt structural repair via CodeFix API (L3.3)
409
- 7. **Verdict** - Errors resolved by healer → SAFE. Errors remain → BLOCK + full rollback
410
- 8. **Commit** - Two-phase atomic write (backup → temp+rename → cleanup)
411
-
412
- ### Known Failure Modes (P1-P32)
413
-
414
- | Category | Problems |
415
- |----------|----------|
416
- | Compiler Cache | P8 (monotonic clock), P11 (periodic GC), P17 (zombie AST) |
417
- | Error Tracking | P9 (topological cardinality), P15 (path sanitization), P28 (syntactic blindness) |
418
- | Concurrency | P10 (FIFO mutex), P21 (multi-file deadlock), P25 (idempotent undo-log) |
419
- | File Operations | P4 (dynamic rootNames), P5 (tombstone deletion), P27 (recursive mkdir), P29 (TS6053 ghost), P30 (non-TS filter) |
420
- | Path Handling | P26 (POSIX normalization), P31 (virtual directories) |
421
- | Physical I/O | P2 (atomic commit), P18 (destruction & resurrection), P32 (physical rollback) |
422
- | Security | A1 (path jail), A5 (node_modules regex), A10 (sensitive file filter) |
423
-
424
- ### How Auto-Healing Decides
425
-
426
- Each fix must reduce the total error count. If applying a fix leaves the same number of errors or more, the fix is reverted and blacklisted. If all errors are resolved, the edit is committed. If some remain, everything is rolled back and the original errors are returned to the agent.
427
-
428
- ---
429
-
430
- ## Contributing
431
-
432
- See [CONTRIBUTING.md](CONTRIBUTING.md).
433
-
434
- ## License
435
-
436
- Apache-2.0 - see [LICENSE](LICENSE).
437
-
438
- ## Author
439
-
440
- **Jherson Eddie Tintaya Holguin** ([@Ruso-0](https://github.com/Ruso-0))
441
-
442
- Cusco, Peru.
1
+ # NREKI Bulletproof Shield for AI Coding Agents
2
+
3
+ <p align="center">
4
+ <img src="https://img.shields.io/npm/v/@ruso-0/nreki?style=for-the-badge&color=blue" alt="npm version">
5
+ <img src="https://img.shields.io/badge/Tests-712-brightgreen?style=for-the-badge" alt="712 Tests">
6
+ <img src="https://img.shields.io/badge/AHI-9.7%2F10-brightgreen?style=for-the-badge" alt="AHI 9.7/10">
7
+ <img src="https://img.shields.io/badge/Languages-TS%20%7C%20JS%20%7C%20Go%20%7C%20Python-blue?style=for-the-badge" alt="Multi-language">
8
+ <img src="https://img.shields.io/badge/Cloud-Zero-orange?style=for-the-badge" alt="Zero Cloud">
9
+ <img src="https://img.shields.io/badge/License-Apache_2.0-yellow?style=for-the-badge" alt="Apache 2.0">
10
+ </p>
11
+
12
+ **MCP plugin that validates AI agent edits in RAM before they touch disk.** When Claude Code, Cursor, or Copilot changes a function signature in one file and breaks 30 others, NREKI catches it in milliseconds — the file is never written. If the error is structural (missing import, forgotten `await`), NREKI auto-fixes it in RAM. Zero tokens wasted on fix-retry doom loops.
13
+
14
+ ```
15
+ AI proposes edit → NREKI intercepts in RAM → Compiler/LSP validates
16
+ │ │
17
+ │ ┌──────── No errors ──────────────────────→ Two-Phase Atomic Commit to disk ✓
18
+ │ │
19
+ │ └──────── Errors found ─→ Auto-Heal (CodeFix API + LSP codeAction)
20
+ │ │
21
+ │ Fixed all? ────────→ Commit to disk
22
+ │ Some remain? ──────→ Full rollback. Disk untouched. Errors returned to agent.
23
+ ```
24
+
25
+ 3 tools. 712 tests. 4 languages. Works with any MCP-compatible agent. Apache 2.0.
26
+
27
+ ---
28
+
29
+ ## Install (30 seconds)
30
+
31
+ ```bash
32
+ # Claude Code
33
+ claude mcp add nreki npx @ruso-0/nreki
34
+
35
+ # Cursor / any MCP client
36
+ npx @ruso-0/nreki
37
+ ```
38
+
39
+ That's it. NREKI auto-detects your project size and languages. No config needed.
40
+
41
+ ```bash
42
+ # Optional: create optimized CLAUDE.md instructions
43
+ npx @ruso-0/nreki init
44
+ ```
45
+
46
+ ---
47
+
48
+ ## What It Actually Does
49
+
50
+ | Without NREKI | With NREKI | Result |
51
+ |---------------|-----------|--------|
52
+ | `cat file.ts` dumps entire file | `nreki_code action:"read"` compresses to signatures | 60-80% fewer tokens |
53
+ | Agent writes broken code to disk | Edit validated in RAM before write | Zero broken files on disk |
54
+ | Error read output → guess fix retry repeat | Auto-Healing fixes structural errors in RAM | Zero doom loop tokens |
55
+ | Agent manages 16+ tool calls | 3 tools, 19 actions | 81% less tool overhead |
56
+ | No idea what breaks when you rename | `prepare_refactor` shows blast radius first | Zero cascade surprises |
57
+ | Types silently degrade to `any` | TTRD catches type regressions in real-time | Zero silent debt |
58
+ | Only TypeScript validated | Go (gopls) + Python (pyright) validated too | Zero cross-language blind spots |
59
+
60
+ ---
61
+
62
+ ## The Architecture
63
+
64
+ NREKI has 3 validation layers with multi-language support:
65
+
66
+ **Layer 1 Syntax (Tree-sitter).** Every edit is parsed by Tree-sitter WASM before anything else. Catches syntax errors in TypeScript, JavaScript, Python, and Go. Always on.
67
+
68
+ **Layer 2 Semantics.** Language-specific validation in RAM:
69
+ - **TypeScript/JavaScript:** Full incremental TypeScript compiler with VFS. Cross-file type errors caught before disk writes. ACID rollback.
70
+ - **Go:** gopls spawned as LSP sidecar process. JSON-RPC 2.0 over stdio. Pull diagnostics (LSP 3.17+).
71
+ - **Python:** pyright spawned as LSP sidecar. Same architecture as Go.
72
+ - **Cross-language:** If a `batch_edit` touches `.ts` + `.go`, both backends must approve or the entire batch is rolled back.
73
+
74
+ **Layer 3 Auto-Healing (Dual Cascade).** When Layer 2 finds errors, NREKI attempts automatic repair:
75
+ - **TypeScript:** CodeFix API (same engine as VS Code's "Quick Fix"). 8 whitelisted fix types.
76
+ - **Go/Python:** LSP `codeAction/resolve` requests. Structural fixes only.
77
+ - **Ice Wall (Muro de Hielo):** Whitelist of safe fix kinds. Business logic is never touched.
78
+ - Each fix must reduce the total error count or it's micro-rolled-back.
79
+
80
+ ---
81
+
82
+ ## The 3 Tools
83
+
84
+ ### `nreki_navigate` Find and understand code
85
+
86
+ | Action | What It Does |
87
+ |--------|-------------|
88
+ | `search` | T-RAG: Topology-Aware search that ranks results by blast radius, not just text similarity |
89
+ | `definition` | Go-to-definition by symbol name with auto-injected dependency signatures |
90
+ | `references` | Find all references cross-project |
91
+ | `outline` | List all symbols in a file with signatures |
92
+ | `map` | Deterministic repo map with PageRank tiers (core/logic/leaf) and pinned rules |
93
+ | `prepare_refactor` | Predictive blast radius: shows every file that breaks if you rename a symbol |
94
+
95
+ ### `nreki_code` Read, write, and validate code
96
+
97
+ | Action | What It Does |
98
+ |--------|-------------|
99
+ | `read` | Smart file reading with 3-level compression + Chronos friction warnings |
100
+ | `compress` | Light/medium/aggressive compression with per-section breakdown |
101
+ | `edit` | Surgical edit by symbol name — validated by Tree-sitter + Compiler/LSP + Auto-Healer |
102
+ | `batch_edit` | Atomic multi-file, multi-language edit. All files pass or none are written. |
103
+ | `undo` | Restore last edit from backup |
104
+ | `filter_output` | Strip ANSI, deduplicate errors, compress terminal output |
105
+
106
+ ### `nreki_guard` — Safety and session management
107
+
108
+ | Action | What It Does |
109
+ |--------|-------------|
110
+ | `pin` / `unpin` | Persistent rules injected into every `map` response |
111
+ | `status` | Token burn rate, depletion prediction, model recommendation |
112
+ | `report` | Full session receipt with USD savings estimate |
113
+ | `reset` | Clear circuit breaker after doom loop recovery |
114
+ | `set_plan` | Anchor a plan file — survives context compaction via Context Heartbeat |
115
+ | `memorize` | Save progress notes to NREKI's active scratchpad |
116
+ | `audit` | Architecture Health Index: 5-signal deterministic score (1-10) with recovery plan |
117
+
118
+ ---
119
+
120
+ ## Language Support
121
+
122
+ | Language | Layer 1 (Syntax) | Layer 2 (Semantics) | Layer 3 (Auto-Heal) | TTRD |
123
+ |----------|:---:|:---:|:---:|:---:|
124
+ | TypeScript | ✅ | ✅ Compiler API | ✅ CodeFix API | ✅ TypeFlags |
125
+ | JavaScript | ✅ | ✅ Compiler API | ✅ CodeFix API | ✅ TypeFlags |
126
+ | Go | ✅ | ✅ gopls LSP | ✅ codeAction | ✅ Syntactic v2 |
127
+ | Python | ✅ | ✅ pyright LSP | ✅ codeAction | ✅ Syntactic v2 |
128
+
129
+ Go/Python require gopls/pyright in PATH. If not found, NREKI degrades gracefully to Layer 1.
130
+
131
+ **TTRD Syntactic v2** (v7.3): For Go and Python, NREKI detects type regressions using structural signature analysis with toxicity scoring and bracket-balanced extraction — no type checker required.
132
+
133
+ ---
134
+
135
+ ## Performance
136
+
137
+ NREKI auto-selects validation depth. No configuration needed.
138
+
139
+ | Mode | Project Size | What It Checks | Boot Time | RAM |
140
+ |------|-------------|----------------|-----------|-----|
141
+ | Syntax | < 50 files | Tree-sitter AST only | < 100ms | ~30MB |
142
+ | File | 50-200 files | Semantic checks on touched files | 1-3s | ~150MB |
143
+ | Project | 200-1000 files | Full cross-file cascade | 3-10s | 200MB-1GB |
144
+ | Hologram | > 1000 files | Full cascade via .d.ts shadows (JIT) | ~2s | ~350MB |
145
+
146
+ ### VSCode Benchmark (5,584 files)
147
+
148
+ | Metric | Hologram (JIT) | Project | File |
149
+ |--------|---------------|---------|------|
150
+ | Boot | **1.94s** | 111s | 91.6s |
151
+ | First edit | 1384ms | 644ms | 55ms |
152
+ | Total | **3.32s** | ~112s | ~92s |
153
+ | RAM | ~350MB | OOM (16GB) | 4.5GB |
154
+ | Files loaded | 642 on-demand | 5,584 | 5,584 |
155
+
156
+ ### Spectral Topology Benchmark (11 projects, 55 test cases)
157
+
158
+ | Project | Files | Nodes | Edges | Max Latency | Result |
159
+ |---------|-------|-------|-------|-------------|--------|
160
+ | Zod | 195 | 2,251 | 6,242 | 32.2ms | 55/55 PASS |
161
+ | tRPC | 89 | 828 | 1,790 | 41.3ms | 55/55 PASS |
162
+ | Prisma | 1,970 | 3,546 | 5,319 | 7.7ms | 55/55 PASS |
163
+ | Next.js | 1,445 | 5,024 | 7,589 | 27.0ms | 55/55 PASS |
164
+ | VS Code | 4,697 | 24,204 | 111,994 | 29.1ms | 55/55 PASS |
165
+ | Effect | 362 | 10,935 | 72,723 | 95.8ms | 55/55 PASS |
166
+
167
+ 0 false positives across 55 test cases and 11 real projects.
168
+
169
+ ---
170
+
171
+ ## Key Features
172
+
173
+ ### T-RAG Topology-Aware Retrieval (v7.1)
174
+
175
+ Standard RAG returns the most textually similar code. T-RAG re-ranks results using the project's dependency graph:
176
+
177
+ ```
178
+ TRS = RRF × G(d) × B(d,q)
179
+
180
+ G(d) = Gravity: PageRank tier weight + log₂(1 + inDegree)
181
+ B(d,q) = Blast Radius resonance: 1.5× if the file imports the search epicenter
182
+ ```
183
+
184
+ ### Architecture Health Index (v7.1)
185
+
186
+ `nreki_guard action:"audit"` computes a deterministic 1-10 score from 5 signals: Spectral Integrity (λ₂/avgDegree), Bus Factor (Shannon Entropy), Type Safety, Core Coverage, and Stability (Chronos CFI). Includes recovery plan simulated in RAM.
187
+
188
+ ### Auto-Healing Dual Cascade (v7.3)
189
+
190
+ When validation fails, NREKI attempts repair through two cascading systems:
191
+
192
+ 1. **TypeScript:** CodeFix API — 8 whitelisted structural fixes (imports, async/await, interface implementation)
193
+ 2. **Go/Python:** LSP `codeAction` — structural fixes from gopls/pyright filtered through the Ice Wall whitelist
194
+
195
+ Each fix must reduce total errors. If a fix fails, it's micro-rolled-back and blacklisted. If all errors are resolved, the edit commits. If some remain, full rollback — disk untouched.
196
+
197
+ ### TTRD — Type Regression Detection
198
+
199
+ **TypeScript:** TypeFlags-based toxicity scoring (any=10, unknown=2, Function=5). Compares pre/post type contracts within the ACID transaction. Tracks type debt across sessions.
200
+
201
+ **Go/Python (v7.3):** Syntactic v2 — structural signature analysis with bracket-balanced extraction and toxicity pattern matching. Detects regressions without a type checker.
202
+
203
+ ### Chronos Memory
204
+
205
+ Cross-session file fragility tracking. CFI scoring (trip=10, error=3, heal=1). Session decay 0.85. Successful edits halve the friction score. High-CFI files require uncompressed read before editing.
206
+
207
+ ### Context Heartbeat
208
+
209
+ Re-injects 4-layer session state every ~15 tool calls to survive context compaction. Respects prompt cache physics — map output stays at token position 0.
210
+
211
+ ---
212
+
213
+ ## Security
214
+
215
+ - **Zero cloud, zero telemetry, zero network calls.** Everything runs locally.
216
+ - **Path traversal protection** at middleware + kernel level with POSIX normalization.
217
+ - **Sensitive file blocking** — `.env`, `.pem`, `.key`, `id_rsa` are rejected by the VFS.
218
+ - **ACID transactions** — partial writes are impossible. Backup → temp → rename → cleanup.
219
+ - **48 security tests** covering traversal, symlink escape, injection, and circuit breaker abuse.
220
+ - **LSP Anti-Zombie Guard** — stdin pipe suffocation + SIGKILL kills the entire process tree (tsx wrappers, grandchildren). SSOT `cleanupState()` cleans all timers, pending requests, and listeners in one idempotent call.
221
+
222
+ ---
223
+
224
+ ## Numbers
225
+
226
+ | Metric | Value |
227
+ |--------|-------|
228
+ | Tests | 712 (44 suites) |
229
+ | Architecture Health Index | 9.7/10 (self-scored) |
230
+ | Languages | 4 (TypeScript, JavaScript, Go, Python) |
231
+ | Failure modes sealed | 32 (P1-P32) |
232
+ | Audit findings resolved | 30/30 + 22 additional |
233
+ | Auto-Healing fix types | 8 CodeFix (TS) + LSP codeAction (Go/Py) |
234
+ | Spectral benchmark | 11 projects, 55/55 correct, 0 false positives |
235
+ | OpenDota benchmark | 6/6 correct verdicts |
236
+ | VSCode (5,584 files) | JIT boot 1.94s, total 3.32s |
237
+ | Router | 319 lines (87% reduction from 2,485) |
238
+ | Tool overhead | ~660 tokens (3 tools replace 16) |
239
+
240
+ ---
241
+
242
+ ## Honest Limitations
243
+
244
+ **Small projects don't need the kernel.** Projects under 50 files run in syntax mode (Tree-sitter only). The kernel boots for 50+ file projects where cross-file validation matters.
245
+
246
+ **TypeScript Compiler API dependency.** Uses `ts.createEmitAndSemanticDiagnosticsBuilderProgram` and `ts.LanguageService`. Pinned to `typescript@^5.9.3`.
247
+
248
+ **Auto-Healing is conservative.** Structural fixes only. Business logic errors are returned to the agent, never auto-fixed. If the healer can't resolve ALL errors, everything rolls back.
249
+
250
+ **Go/Python TTRD is syntactic.** Without a type checker exposing resolved types, TTRD v2 uses structural pattern matching — accurate for signature changes, blind to inferred type regressions.
251
+
252
+ **Token savings are estimates.** Uses `characters / 3.5` heuristic, not BPE tokenization. Real savings vary ~20-40%.
253
+
254
+ ---
255
+
256
+ ## How It Works Internally
257
+
258
+ ### The Intercept Cycle
259
+
260
+ 1. **Inject** All edits enter VFS simultaneously (atomic batch)
261
+ 2. **Compile** Incremental TypeScript builder evaluates proposed future state
262
+ 3. **Shield 1-3** Global Syntactic Semantic diagnostics
263
+ 4. **LSP Sidecars** Go/Python files validated via gopls/pyright (Pull diagnostics LSP 3.17+)
264
+ 5. **Auto-Heal** — Dual Cascade: CodeFix API (TS) + LSP codeAction (Go/Py) through Ice Wall whitelist
265
+ 6. **TTRD** Compare pre/post type contracts (TypeFlags for TS, Syntactic v2 for Go/Py)
266
+ 7. **Verdict** — All clear → Two-Phase Atomic Commit. Errors remain → Full rollback.
267
+
268
+ ### Architecture (v7.3 post-Strangler Fig)
269
+
270
+ ```
271
+ NrekiKernel (Orchestrator)
272
+ ├── VFS (Map<string, string|null>), ACID rollback, mutex, logical clock
273
+ ├── TsCompilerWrapper (TypeScript backend)
274
+ │ ├── CompilerHost + DocumentRegistry + LanguageService
275
+ │ ├── Incremental builder with corruption recovery
276
+ │ ├── TTRD: TypeFlags toxicity scoring
277
+ │ └── Auto-Healer: 8 whitelisted CodeFix types
278
+ ├── LspSidecarBase (Go/Python backends)
279
+ │ ├── JSON-RPC 2.0 over stdio, Pull diagnostics (LSP 3.17+)
280
+ │ ├── requestCodeActions + Ice Wall whitelist
281
+ │ ├── TTRD Syntactic v2 (toxicity + bracket balancer)
282
+ │ ├── SSOT cleanupState() one idempotent funnel for all death paths
283
+ │ └── Anti-Zombie: stdin suffocation + SIGKILL (kills entire process tree)
284
+ ├── GoLspSidecar gopls (22 lines)
285
+ ├── PythonLspSidecar pyright (24 lines)
286
+ └── TypeScriptCorsaBackend → tsgo (Project Corsa placeholder)
287
+
288
+ Router (319 lines, 3 facades)
289
+ ├── nreki_navigate → handlers/navigate.ts
290
+ ├── nreki_code handlers/code.ts
291
+ └── nreki_guard → handlers/guard.ts
292
+ ```
293
+
294
+ ---
295
+
296
+ ## Contributing
297
+
298
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
299
+
300
+ ## License
301
+
302
+ Apache-2.0 see [LICENSE](LICENSE).
303
+
304
+ ## Author
305
+
306
+ **Jherson Eddie Tintaya Holguin** ([@Ruso-0](https://github.com/Ruso-0))
307
+
308
+ Arequipa, Peru.