nreki 12.2.0 → 12.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## [12.3.0] - 2026-11-26
4
+
5
+ `npx nreki init` now installs NREKI in one command: it writes each agent's instructions and registers NREKI as that agent's MCP server, with the project folder pinned.
6
+
7
+ Why the folder has to be pinned. NREKI indexes the folder it starts in, and on 2026-11-26 a probe MCP server measured where hosts start servers:
8
+ - Antigravity IDE 2.9.0 starts a global plugin's server in the plugin's own folder (`~/.gemini/config/plugins/<name>`), so NREKI would have indexed the wrong folder.
9
+ - It starts a workspace `.agents/mcp_config.json` server in the project.
10
+ - It expands none of `${workspaceFolder}`, `${WORKSPACE_ROOT}` or `${PWD}`, and it does not offer MCP roots.
11
+
12
+ Changes:
13
+ - **`NREKI_PROJECT_ROOT`.** When set to an existing absolute folder, the server switches to it before any module reads `process.cwd()` (`src/bootstrap-root.ts` is the first import of `index.ts`). An unexpanded `${…}`, a relative path or a missing folder is ignored with a stderr warning.
14
+ - **`init` registers the MCP server**:
15
+ - Claude Code: `.mcp.json`.
16
+ - Codex: `.codex/config.toml`, with `cwd`, `startup_timeout_sec = 120` (the first `npx` download took 25 s; Codex's default is 10 s) and `env_vars` forwarding the Voyage key.
17
+ - Antigravity: `.agents/mcp_config.json`.
18
+ - Cursor: `.cursor/mcp.json`, with an absolute `NREKI_PROJECT_ROOT`.
19
+ - VS Code/Copilot: `.vscode/mcp.json`, with `NREKI_PROJECT_ROOT=${workspaceFolder}`.
20
+ - Every entry pins `nreki@<version>`. On Windows it launches through `cmd /c npx`.
21
+ - **Updates and refusals.**
22
+ - Re-running `init` updates NREKI's own entry to the new version and keeps fields the user added.
23
+ - An entry named `nreki` that NREKI did not write is left alone unless `--force`.
24
+ - A JSON file with comments, or a Codex inline-table definition, is never rewritten: `init` prints the entry to add by hand.
25
+ - Nothing is written through a linked folder.
26
+ - **Agent selection.**
27
+ - `init` installs for every agent configured in the project. `codex` (`.codex/`) and `antigravity` (`.agents/mcp_config.json`, `.agents/rules/`, `GEMINI.md`) are new agents. Before, only the first agent detected was installed.
28
+ - Without project signals, it installs for the agents found in the home folder (`~/.claude`, `~/.codex`, `~/.gemini/antigravity`, `~/.cursor`), then falls back to `AGENTS.md`.
29
+ - `--agent` takes a comma list.
30
+ - Codex and Antigravity share the `AGENTS.md` block: Antigravity loads a root `AGENTS.md` as an always-on rule.
31
+ - **New flags:** `--voyage` / `--no-voyage` set or remove `NREKI_SEMANTIC=voyage` in the registrations. `--no-mcp` writes the instructions only. `init` ends with the steps left in each agent (approve the server in Claude Code, trust the folder in Codex, Refresh in Antigravity).
32
+ - **`deinit`** also removes the MCP entries NREKI wrote, and deletes a config file that held nothing else and the folders left empty.
33
+ - **`deinit` bugs fixed (found while testing this release):**
34
+ - In `CLAUDE.md` it cut from `# NREKI ACTIVE` to the end of the file. That dropped the user's text after the block and left the `<!-- nreki:begin -->` sentinel behind.
35
+ - It looked for an `AGENTS.md` header that the template stopped using in v12.1, so it never removed that block.
36
+ - It left `.claude/skills/nreki-optimizer/SKILL.md`, `.cursor/rules/nreki.mdc`, `.clinerules/nreki.md` and the `.github/copilot-instructions.md` block behind.
37
+ - Now it removes exactly the block `init` wrote, recognizing both the sentinels and the legacy headers.
38
+ - It deletes `.claude/settings.json` when only NREKI's hooks were in it.
39
+ - Measured on a project with all five agents installed: the old `deinit` left 13 files; the new one leaves only the user's.
40
+
41
+ Tests: `tests/init-mcp-register.test.ts`. One of them starts the real server from an empty folder with `NREKI_PROJECT_ROOT` pointing at a project and finds a symbol there. Without the bootstrap import, that test and the import-order test fail.
42
+
3
43
  ## [12.2.0] - 2026-11-26
4
44
 
5
45
  - The npm package is renamed to `nreki` (unscoped). Releases up to 12.0.0 were published as `@ruso-0/nreki`. `npx nreki` replaces `npx @ruso-0/nreki` in the README, the CLI help and the `trust-db` hints; the `nreki` bin name is unchanged.
package/README.md CHANGED
@@ -1,219 +1,217 @@
1
- # NREKI - Bulletproof Shield for AI Coding Agents
2
-
3
- <p align="center">
4
- <img src="https://img.shields.io/npm/v/nreki?style=for-the-badge&color=blue" alt="npm version">
5
- <img src="https://img.shields.io/badge/Tests-1825-brightgreen?style=for-the-badge" alt="1825 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%20%7C%20Kotlin%20%7C%20Java%20%7C%20C%2B%2B-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 by default">
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
- **v12.2.0 — Spanish/hybrid recall, symbol deletion, and opt-in native edit preflight.** By default, NREKI writes its session marker without opening any local IPC socket or pipe: the Claude hook keeps large-file `Read` steering active and lets native `Edit`, `MultiEdit` and `Write` pass silently. Claude instructions (`CLAUDE.md`, `SKILL.md`, and MCP initialization) use native `Edit` for single-file changes and reserve `nreki_code action:"batch_edit"` for cross-file signature changes and renames (`AGENTS.md` keeps the `batch_edit` + checker workflow for Codex). `edit` and `batch_edit` also accept `mode:"replace"` with `new_code:""` to delete a symbol under full AST and compiler validation, and `context` / hybrid search bridges Spanish software/business terms into English on the lexical side while keeping exact names, paths and Voyage queries unchanged.
15
-
16
- Opting in with `NREKI_NATIVE_PREFLIGHT=1` enables the Claude hook v5 authenticated local IPC preview for native `Edit`, `MultiEdit` and `Write`: accepted edits add no hook output, and rejected edits return diagnostics before the native tool writes. That opt-in preview never writes proposed code or auto-heals, restores the kernel under the same lock, enforces comment-only Anti-Sweep checks plus an opt-in-only differential TypeScript AST zero-`any` check (`batch_edit` does not enforce zero-`any` by default), and batches external watcher refreshes without redundant compiler baseline rebuilds. Declaration surface checks strip JSDoc/comments (preserving triple-slash directives) so comment-only edits report an unchanged exported API in both `batch_edit` footers and preflight, while modules containing `export *` or `export =` are never treated as purely additive so new exports cannot silently shadow re-exported names in consumers outside the active `tsconfig`. This preflight cannot make the later native write atomic with validation: use `batch_edit` for transactional multi-file writes. The hook does not intercept shell writes.
17
-
18
- **v12.1.2 — fixes from an external audit of 12.1.1.**
19
- - Secrets are blanked across a typed or commented initializer before code is sent to the optional Voyage index.
20
- - NREKI never writes its own files (`.nreki/…`) through a link; the installed hook is v4.
21
- - `context` shows an imported helper only from the file that declares it.
22
- - The footer reports importers compiled by another tsconfig, in project mode too.
23
- - Sibling anonymous callbacks keep their own errors in the error baseline.
24
- - See [CHANGELOG.md](CHANGELOG.md#1212---2026-11-14).
25
-
26
- **v12.1.1 — context finds every issue, safer by default.**
27
- - `context` searches every issue that names no code: a named type or a capitalized word no longer cancels that search. `path` scopes it.
28
- - Importers are resolved the way the compiler resolves them, tsconfig aliases included, so the footer no longer calls an unchecked importer "no importers".
29
- - Fixes from an external audit:
30
- - no writes through symbolic links;
31
- - more sensitive files blocked;
32
- - secrets blanked before code is sent to the optional Voyage index;
33
- - auto-heal no longer reports fixes it did not make.
34
- - See [CHANGELOG.md](CHANGELOG.md#1211---2026-11-14).
35
-
36
- **v12.1.0 — fewer turns, honest footers.** `nreki_navigate action:"context"` returns, in one call, the code a task names; for a task that names no code it returns the best hits of each issue. The `[Validated]` footer says when re-running tsc is redundant. `Class.method` names work everywhere, and an optional Voyage index adds semantic search. Measured with Codex on two new projects, three pairs each: 33 % fewer tokens, then 1.8 % more (see [Token cost](#token-cost)). Also included are the fixes from two external security and integrity audits. See [CHANGELOG.md](CHANGELOG.md#1210---2026-11-13).
37
-
38
- **v12.0.0 — Edit-Safety MCP (BREAKING).** NREKI is an edit-safety layer: it validates and atomically commits agent edits, and provides local code navigation. Host agents bring their own semantic retrieval. **`hybrid_search` (NREKI + BM25 RRF fusion) was removed** — its +10pp recall did not justify the ~4.3× token cost for a use case that does not exist when the agent already has grep. `search` (BM25 keywords + dependency topology, with an optional Voyage semantic index) and `fast_grep` (RAM-resident exact substring) cover local navigation; `nreki_code` batch-edits with in-RAM compiler/LSP validation. See [CHANGELOG.md](CHANGELOG.md#1200) for the migration path. (v11.0.0 removed ONNX embeddings; v12.0.0 removed the hybrid_search fusion — same precedent.)
39
-
40
- <p align="center"><img src="docs/demo.gif" alt="NREKI outline with defect + ghost tags"></p>
41
-
42
- ## Install
43
-
44
- Since 12.2.0 the npm package is **`nreki`**. Releases up to 12.0.0 were published as `@ruso-0/nreki`; if you configured that name, replace it with `nreki` in your MCP config.
45
-
46
- ```bash
47
- # Claude Code (macOS / Linux)
48
- claude mcp add nreki -- npx -y nreki
49
-
50
- # Claude Code (Windows) — wrap with `cmd /c`, otherwise Claude Code warns
51
- # that the server failed to start (npx is a .cmd shim on Windows):
52
- claude mcp add nreki -- cmd /c npx -y nreki
53
-
54
- # Cursor / any MCP client - add to mcp.json:
55
- # macOS/Linux:
56
- { "mcpServers": { "nreki": { "command": "npx", "args": ["-y", "nreki"] } } }
57
- # Windows:
58
- { "mcpServers": { "nreki": { "command": "cmd", "args": ["/c", "npx", "-y", "nreki"] } } }
59
-
60
- # Optional: agent-aware instructions install (v11.3.0+)
61
- npx nreki init # auto-detect agent (Claude Code / Cursor / Cline / Copilot / generic)
62
- npx nreki init --agent cursor # explicit; valid: claude, cursor, cline, copilot, generic
63
- npx nreki init --dry-run # preview the plan, write nothing
64
- npx nreki init --force # rewrite an existing NREKI block (your own content in the file is kept)
65
- ```
66
-
67
- What `nreki init` writes per agent:
68
-
69
- | Agent | Detected via | Files installed |
70
- |-----------|----------------------------------------|-----------------------------------------------------------------------|
71
- | `claude` | `.claude/` or `CLAUDE.md` | `CLAUDE.md` (NREKI block), `.claude/skills/nreki-optimizer/SKILL.md`, `.claude/hooks/nreki-enforcer.mjs`, `.claude/settings.json` |
72
- | `cursor` | `.cursor/` or `.cursorrules` | `.cursor/rules/nreki.mdc` (with `alwaysApply: true` frontmatter) |
73
- | `cline` | `.clinerules` (file or dir) | `.clinerules/nreki.md` |
74
- | `copilot` | `.github/copilot-instructions.md` | `.github/copilot-instructions.md` (appended) |
75
- | `generic` | none of the above | `AGENTS.md` |
76
-
77
- First MCP run indexes the project automatically in the background — `fast_grep` returns RAM-resident substring matches immediately while NREKI's semantic index warms (v11.2.1+). Zero config for TS/JS; point a `tsconfig.json` at your code and NREKI detects the right validation mode.
78
-
79
- ## How it works
80
-
81
- ```
82
- AI proposes edit -> NREKI intercepts in RAM -> Compiler/LSP validates
83
- | |
84
- | No errors ----------------------> Two-Phase Atomic Commit to disk
85
- | Errors found --> Auto-Heal (TS CodeFix + LSP codeAction, atomic)
86
- | |
87
- | Fixed all? ---> Commit to disk
88
- | Some remain? -> Full rollback. Disk untouched. Errors returned to agent.
89
- ```
90
-
91
- Three tools (`nreki_navigate`, `nreki_code`, `nreki_guard`), 26 actions (11 navigate + 6 code + 9 guard), 4 languages (TS/JS, Go via gopls, Python via pyright). Works with any MCP-compatible agent. Apache 2.0.
92
-
93
- ### Token cost
94
-
95
- Depending on the client, an agent pays NREKI's three tool definitions (~700 tokens) on every request of a session or once when it looks them up, and every tool result again on each later request. NREKI saves tokens only when it saves more than that: fewer turns and smaller results than the agent's own tools.
96
-
97
- - `nreki_navigate action:"context" query:"<the task>"` returns, in one call, the code the task names: symbols verbatim with their line ranges, where the fields it mentions occur, and who imports each file. Exploring with `map`/grep/reads usually takes two or three turns.
98
- - `read`/`compress` with `focus:"a,b"` return only those symbols; edits return one line plus the `[Validated: …]` footer.
99
- - Measured with Codex (2026-11-13) on synthetic TypeScript projects of 30–40 files, three pairs per run. The first run cost 25 % more tokens with NREKI: `read` ignored `focus`, agents re-read what `context` returned, and took extra turns. After those fixes, a pre-registered run was a tie (+0.02 %) and a run on a new project cost +4.97 %: `context` saved the reading turns, but agents sent `batch_edit` alone and ran the checker on the next turn. With `context` now asking for the checker in the same cell, a run on another new project used **33 % fewer tokens**: 225,391 vs 336,643, 12 vs 18 turns, NREKI ahead in all 3 pairs, all 6 solutions correct. Every NREKI session took the minimum 4 turns: checker, `context`, `batch_edit` plus checker, answer. That is one project and three pairs: a measurement, not a guarantee. On a third new project (42 files) the published 12.1.0 cost 1.8 % more. In two of its three sessions `context` let one capitalized word ("Station", a type) stand for the whole task and returned none of the files to fix. 12.1.1 searches every issue that names no code. One pair on yet another new project, run on the 12.1.1 code before release, used 40.85 % fewer tokens: 449,645 vs 760,190, 21 vs 36 turns, both solutions correct. That is one session per arm, and the agents delegated differently. All runs after the fixes had the optional Voyage index on (see Privacy). In that last pair it made no query, so the default, `context` with BM25 alone, has not been measured on its own.
100
-
101
- ## Highlights
102
-
103
- - **Atomic multi-TextEdit healing.** When gopls or pyright proposes a quickfix with coupled edits (import + usage), NREKI applies every TextEdit of the chosen action together with per-file savepoints and bottom-up offset ordering. No more doom-loop retries where only the import lands and the usage stays broken.
104
- - **Tolerant Patch mode.** `nreki_code action:"edit" mode:"patch"` now retries with indent-flexible matching when the exact-indent search fails and the content is unique. The literal-`$` guarantee is preserved end-to-end (no V8 `$&` / `$$` substitution surprises).
105
- - **Cognitive Enforcer.** Agents can't `batch_edit` blindly - every edit in a batch is validated against a per-file passport (outline seen? symbol focused?). The v10.5.7 fix closed a bypass where 2+ edits could smuggle blind mutations through.
106
- - **TTRD Bounties.** Successful strict-type restoration reports the exact CFI (Cognitive Friction Index) discount to the agent. Pavlovian reinforcement that actually quantifies what improved.
107
- - **Defect radar + ghost oracle.** Four inline detectors and a 0-ext-refs tagger run during `outline` - free signals, no extra tool call.
108
- - **Executable engrams.** Pin insights to symbols. Engrams prefixed `ASSERT` survive AST mutation; everything else invalidates on body change so memory can't go stale.
109
-
110
- ## Language support (Validation + Auto-heal)
111
-
112
- | Language | Validation | Auto-heal |
113
- |----------|------------|-----------|
114
- | TypeScript / JavaScript | Full (TS Compiler API) | TS CodeFix API |
115
- | Go | gopls LSP sidecar | codeAction (atomic) |
116
- | Python | pyright / basedpyright LSP sidecar | codeAction (atomic; basedpyright only — plain pyright validates without healing) |
117
-
118
- ### What an accepted edit was checked against
119
-
120
- Semantic checking is on whenever the project root has a `tsconfig.json`/`jsconfig.json`, a Python marker (`pyproject.toml`, `requirements.txt`, `setup.py`, `Pipfile`) or a `go.mod`; without one, edits get the syntax check only. The `[Validated: …]` footer of every edit states what ran for that edit.
121
-
122
- | Project | Checked together with the edit |
123
- |---------|--------------------------------|
124
- | TypeScript, up to 200 files | the edited files and their direct importers (up to 50) |
125
- | TypeScript, 201–1000 files | the whole program |
126
- | TypeScript, over 1000 files | the edited files and their direct importers (up to 50) |
127
- | Go | the edited files, the other files of their package and the files that import them (up to 50) |
128
- | Python | the edited files and the files that import them (up to 50) |
129
-
130
- For Go and Python only the errors an edit adds are fatal: an error that was already there does not block it. Transitive importers are not checked in any row but the second; run the compiler or the tests when the footer says so.
131
-
132
- ## AST parser coverage
133
-
134
- NREKI's tree-sitter parser layer indexes additional languages for
135
- foveal compression + symbol retrieval + semantic-edit syntactic
136
- validation. These languages do **not** have LSP sidecars and
137
- therefore receive no auto-heal; otherwise their files participate
138
- in the retrieval index identically to TypeScript files.
139
-
140
- | Language | Extensions | Parser | Foveal | Syntax check | LSP auto-heal | Type Ledger |
141
- |-------------|-----------------------------------------|--------|--------|--------------|---------------|-------------|
142
- | TypeScript | .ts .tsx .mts .cts | ✓ | ✓ | ✓ | ✓ (tsc) | ✓ |
143
- | JavaScript | .js .jsx .mjs .cjs | ✓ | ✓ | ✓ | ✓ (tsc) | ✓ |
144
- | Python | .py | ✓ | ✓ | ✓ | ✓ (pyright) | — |
145
- | Go | .go | ✓ | ✓ | ✓ | ✓ (gopls) | — |
146
- | CSS | .css | ✓ | ✓ | ✓ | — | — |
147
- | JSON | .json | ✓ | ✓ | ✓ | — | — |
148
- | HTML | .html | ✓ | ✓ | ✓ | — | — |
149
- | **Kotlin** | .kt .kts | ✓ | ✓ | ✓ | — | — |
150
- | **Java** | .java | ✓ | ✓ | ✓ | — | — |
151
- | **C++** | .cpp .cc .cxx .hpp .hh .hxx .h* | ✓ | ✓ | ✓ | — | — |
152
- | **C** | .c .h* | ✓ | ✓ | ✓ | — | — |
153
-
154
- Kotlin / Java / C++ / C activation in v11.0.x covers Android development
155
- (Kotlin app layer + Java legacy + C++ NDK native layer + C NDK code) and the
156
- broader JVM / native cross-platform ecosystem.
157
-
158
- > *`.h` headers are routed at parse time: headers containing
159
- > C++ markers (template, namespace, class, `#ifdef __cplusplus`)
160
- > use the C++ grammar; pure C headers use the C grammar. Default
161
- > to C grammar for ambiguous cases.
162
-
163
- **Known limitation (v11.0.x):** cross-file import detection for
164
- Kotlin / Java / C++ / C is not yet implemented. Repo-map dependency edges
165
- for files in these languages are intra-file only until v11.0.x.1.
166
-
167
- ### Known limitations (v11.0.1)
168
-
169
- **Android XML manifests and Gradle build files are NOT yet indexed.**
170
- AndroidManifest.xml, resource XMLs (`res/layout/`, `res/values/`, etc.),
171
- and Gradle build scripts (`build.gradle` Groovy DSL) coverage is tracked
172
- for v11.0.2 (see issue #4).
173
-
174
- **WASM checksum verification deferred.** Upstream grammar upgrades may not
175
- propagate to vendor `wasm/` directory due to skip-if-exists logic in
176
- `scripts/download-wasm.js`. SHA-256 checksum verification tracked as issue #5.
177
-
178
- **chunks table lacks language column.** Retrieval language-aware scoring
179
- requires runtime path extension filtering. Breaking migration tracked as
180
- issue #6 (coordinated with v11.0.2 XML activation due to noise risk
181
- amplification).
182
-
183
- **Type Ledger (cross-file architectural dependency mapping) remains
184
- TypeScript-specific by design** - it relies on TypeScript compiler-
185
- derived type information. Multi-language Type Ledger expansion is
186
- tracked under the Phase 8 roadmap.
187
-
188
- ## Privacy: everything is local unless you opt in
189
-
190
- By default no code leaves the machine. `search` can optionally add semantic recall (find code by meaning, even when it shares no words with the question) with your own [Voyage AI](https://www.voyageai.com/) key:
191
-
192
- ```bash
193
- NREKI_SEMANTIC=voyage # explicit opt-in (required)
194
- NREKI_VOYAGE_API_KEY=pa-... # or VOYAGE_API_KEY
195
- NREKI_VOYAGE_MODEL=voyage-code-4 # optional, default shown
196
- NREKI_VOYAGE_MAX_TOKENS=20000000 # optional per-process embedding budget
197
- ```
198
-
199
- - A `VOYAGE_API_KEY` exported for another tool does **not** enable it; `NREKI_SEMANTIC=voyage` does.
200
- - **What is sent:** every indexed code chunk (project-relative path, its comments, up to 6,000 characters of code) is embedded **once**, in the background, and the vector is stored locally in `.nreki.db`. Unchanged chunks are never re-sent, also after a restart; an edited file re-sends only its changed chunks. Each `search` sends only the query. Sensitive paths (`.env`, keys, `.ssh`, …) are never sent; secrets hard-coded in ordinary source files would be.
201
- - **Cost:** about one token per 3.5 characters of code, once. A 1M-token repository is roughly $0.12 at voyage-code-4's list price, inside the free tier Voyage gives each account.
202
- - **How results change:** the dense ranking is fused with BM25 (reciprocal-rank fusion), so a chunk BM25 never retrieved can surface. Until indexing finishes, and whenever Voyage is unreachable (2.5 s timeout) or the key is rejected, search answers from BM25 alone and logs the reason once.
203
- - Check Voyage's terms for data retention/training; on self-serve accounts, opting out of training requires a payment method on file.
204
-
205
- ### Memory files are signed
206
-
207
- NREKI's memory lives in the project folder: engrams, `memorize` notes and the plan pointer (`.nreki.db`), pinned rules (`.nreki/pins.json`), file history and the map cache (`.nreki/`). The agent reads parts of it as its own notes, and a repository could ship such files, so each one is signed with a key kept in your user folder (`~/.nreki/trust.key`, never in a project). A file without a valid signature is never loaded: it is moved to `.nreki/quarantine/` and the index is rebuilt.
208
-
209
- Upgrading from 12.0.0 or earlier quarantines your old memory once. To restore it, run `npx nreki trust-db` in a terminal with the agent session closed: it lists the engrams, notes and pins it found and restores them only after you type `yes`. Without an interactive terminal it refuses, so an agent cannot run it on its own.
210
-
211
- ## Docs & links
212
-
213
- - **[CHANGELOG.md](CHANGELOG.md)** - full version history (every patch, every release, every test count).
214
- - **[templates/CLAUDE.md](templates/CLAUDE.md)** - optimized instructions auto-installed by `npx nreki init`.
215
- - **Issues / ideas** - GitHub Issues on this repo.
216
-
217
- ## License
218
-
219
- Apache 2.0. Zero cloud dependencies. Everything runs locally in the agent's process (the opt-in Voyage reranker above is the only exception).
1
+ # NREKI - Bulletproof Shield for AI Coding Agents
2
+
3
+ <p align="center">
4
+ <img src="https://img.shields.io/npm/v/nreki?style=for-the-badge&color=blue" alt="npm version">
5
+ <img src="https://img.shields.io/badge/Tests-1858-brightgreen?style=for-the-badge" alt="1858 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%20%7C%20Kotlin%20%7C%20Java%20%7C%20C%2B%2B-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 by default">
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
+ **v12.3.0 — one command installs NREKI.** Run `npx nreki init` in a project: it writes each agent's instructions and registers NREKI as that agent's MCP server (Claude Code, Codex, Antigravity, Cursor, VS Code/Copilot), with the project folder pinned so NREKI indexes the right code. Without agent files in the project it installs for the agents found on your computer. `--voyage` turns on semantic search. `NREKI_PROJECT_ROOT` names the project for hosts that start servers in another folder (measured: Antigravity starts a global plugin's server in the plugin folder). `npx nreki deinit` removes the registrations too.
15
+
16
+ **v12.2.0 — Spanish/hybrid recall, symbol deletion, and opt-in native edit preflight.** By default, NREKI writes its session marker without opening any local IPC socket or pipe: the Claude hook keeps large-file `Read` steering active and lets native `Edit`, `MultiEdit` and `Write` pass silently. Claude instructions (`CLAUDE.md`, `SKILL.md`, and MCP initialization) use native `Edit` for single-file changes and reserve `nreki_code action:"batch_edit"` for cross-file signature changes and renames (`AGENTS.md` keeps the `batch_edit` + checker workflow for Codex). `edit` and `batch_edit` also accept `mode:"replace"` with `new_code:""` to delete a symbol under full AST and compiler validation, and `context` / hybrid search bridges Spanish software/business terms into English on the lexical side while keeping exact names, paths and Voyage queries unchanged.
17
+
18
+ Opting in with `NREKI_NATIVE_PREFLIGHT=1` enables the Claude hook v5 authenticated local IPC preview for native `Edit`, `MultiEdit` and `Write`: accepted edits add no hook output, and rejected edits return diagnostics before the native tool writes. That opt-in preview never writes proposed code or auto-heals, restores the kernel under the same lock, enforces comment-only Anti-Sweep checks plus an opt-in-only differential TypeScript AST zero-`any` check (`batch_edit` does not enforce zero-`any` by default), and batches external watcher refreshes without redundant compiler baseline rebuilds. Declaration surface checks strip JSDoc/comments (preserving triple-slash directives) so comment-only edits report an unchanged exported API in both `batch_edit` footers and preflight, while modules containing `export *` or `export =` are never treated as purely additive so new exports cannot silently shadow re-exported names in consumers outside the active `tsconfig`. This preflight cannot make the later native write atomic with validation: use `batch_edit` for transactional multi-file writes. The hook does not intercept shell writes.
19
+
20
+ **v12.1.2 — fixes from an external audit of 12.1.1.**
21
+ - Secrets are blanked across a typed or commented initializer before code is sent to the optional Voyage index.
22
+ - NREKI never writes its own files (`.nreki/…`) through a link; the installed hook is v4.
23
+ - `context` shows an imported helper only from the file that declares it.
24
+ - The footer reports importers compiled by another tsconfig, in project mode too.
25
+ - Sibling anonymous callbacks keep their own errors in the error baseline.
26
+ - See [CHANGELOG.md](CHANGELOG.md#1212---2026-11-14).
27
+
28
+ **v12.1.1 — context finds every issue, safer by default.**
29
+ - `context` searches every issue that names no code: a named type or a capitalized word no longer cancels that search. `path` scopes it.
30
+ - Importers are resolved the way the compiler resolves them, tsconfig aliases included, so the footer no longer calls an unchecked importer "no importers".
31
+ - Fixes from an external audit:
32
+ - no writes through symbolic links;
33
+ - more sensitive files blocked;
34
+ - secrets blanked before code is sent to the optional Voyage index;
35
+ - auto-heal no longer reports fixes it did not make.
36
+ - See [CHANGELOG.md](CHANGELOG.md#1211---2026-11-14).
37
+
38
+ **v12.1.0 — fewer turns, honest footers.** `nreki_navigate action:"context"` returns, in one call, the code a task names; for a task that names no code it returns the best hits of each issue. The `[Validated]` footer says when re-running tsc is redundant. `Class.method` names work everywhere, and an optional Voyage index adds semantic search. Measured with Codex on two new projects, three pairs each: 33 % fewer tokens, then 1.8 % more (see [Token cost](#token-cost)). Also included are the fixes from two external security and integrity audits. See [CHANGELOG.md](CHANGELOG.md#1210---2026-11-13).
39
+
40
+ **v12.0.0 — Edit-Safety MCP (BREAKING).** NREKI is an edit-safety layer: it validates and atomically commits agent edits, and provides local code navigation. Host agents bring their own semantic retrieval. **`hybrid_search` (NREKI + BM25 RRF fusion) was removed** — its +10pp recall did not justify the ~4.3× token cost for a use case that does not exist when the agent already has grep. `search` (BM25 keywords + dependency topology, with an optional Voyage semantic index) and `fast_grep` (RAM-resident exact substring) cover local navigation; `nreki_code` batch-edits with in-RAM compiler/LSP validation. See [CHANGELOG.md](CHANGELOG.md#1200) for the migration path. (v11.0.0 removed ONNX embeddings; v12.0.0 removed the hybrid_search fusion — same precedent.)
41
+
42
+ <p align="center"><img src="docs/demo.gif" alt="NREKI outline with defect + ghost tags"></p>
43
+
44
+ ## Install
45
+
46
+ In the project folder:
47
+
48
+ ```bash
49
+ npx nreki init # instructions + MCP registration for each agent, project folder pinned
50
+ npx nreki init --voyage # same, with Voyage semantic search on (needs NREKI_VOYAGE_API_KEY; sends this project's code to Voyage once)
51
+ npx nreki init --agent codex,antigravity # choose the agents (claude, codex, antigravity, cursor, cline, copilot, generic)
52
+ npx nreki init --dry-run # preview the plan, write nothing
53
+ npx nreki init --no-mcp # instructions only
54
+ npx nreki deinit # remove NREKI's hooks, instructions and MCP registrations
55
+ ```
56
+
57
+ `init` installs for every agent configured in the project. If there is none, it installs for the agents found on this computer (`~/.claude`, `~/.codex`, `~/.gemini/antigravity`, `~/.cursor`); if there is none either, it writes `AGENTS.md`. Then it prints what is left to do in each agent, such as approving the server in Claude Code or trusting the folder in Codex. Re-running it after an upgrade updates NREKI's own entries to the new version and keeps fields you added; an entry named `nreki` that NREKI did not write is left alone unless `--force`.
58
+
59
+ | Agent | Detected in the project via | Instructions | MCP registration (project folder pinned by) |
60
+ |---------------|-----------------------------------------------------|------------------------------------------------|-------------------------------------------------------------|
61
+ | `claude` | `.claude/` or `CLAUDE.md` | `CLAUDE.md` block, skill, enforcer hook, `.claude/settings.json` | `.mcp.json` (Claude Code starts it in the project) |
62
+ | `codex` | `.codex/` | `AGENTS.md` block | `.codex/config.toml` (`cwd`; Codex reads it only for trusted projects) |
63
+ | `antigravity` | `.agents/mcp_config.json`, `.agents/rules/`, `GEMINI.md` | `AGENTS.md` block (always-on rule) | `.agents/mcp_config.json` (Antigravity starts it in the project) |
64
+ | `cursor` | `.cursor/` or `.cursorrules` | `.cursor/rules/nreki.mdc` | `.cursor/mcp.json` (`NREKI_PROJECT_ROOT`) |
65
+ | `copilot` | `.github/copilot-instructions.md` | `.github/copilot-instructions.md` block | `.vscode/mcp.json` (`NREKI_PROJECT_ROOT=${workspaceFolder}`) |
66
+ | `cline` | `.clinerules` | `.clinerules/nreki.md` | by hand: Cline keeps MCP servers in its global settings |
67
+ | `generic` | none of the above | `AGENTS.md` block | by hand |
68
+
69
+ The Codex and Cursor entries hold this computer's path to the project: keep `.codex/` and `.cursor/mcp.json` out of git. On Windows every entry launches `cmd /c npx -y nreki@<version>`, because `npx` is a `.cmd` shim there.
70
+
71
+ Registering by hand works too, from the project folder: `claude mcp add nreki -- npx -y nreki` (Windows: `claude mcp add nreki -- cmd /c npx -y nreki`), or `{ "mcpServers": { "nreki": { "command": "npx", "args": ["-y", "nreki"] } } }` in an MCP client's config. If the client starts servers in another folder, add `"env": { "NREKI_PROJECT_ROOT": "<absolute project path>" }`.
72
+
73
+ Since 12.2.0 the npm package is **`nreki`**. Releases up to 12.0.0 were published as `@ruso-0/nreki`; if you configured that name, run `npx nreki init` or replace it with `nreki` in your MCP config.
74
+
75
+ First MCP run indexes the project automatically in the background — `fast_grep` returns RAM-resident substring matches immediately while NREKI's semantic index warms (v11.2.1+). Zero config for TS/JS; point a `tsconfig.json` at your code and NREKI detects the right validation mode.
76
+
77
+ ## How it works
78
+
79
+ ```
80
+ AI proposes edit -> NREKI intercepts in RAM -> Compiler/LSP validates
81
+ | |
82
+ | No errors ----------------------> Two-Phase Atomic Commit to disk
83
+ | Errors found --> Auto-Heal (TS CodeFix + LSP codeAction, atomic)
84
+ | |
85
+ | Fixed all? ---> Commit to disk
86
+ | Some remain? -> Full rollback. Disk untouched. Errors returned to agent.
87
+ ```
88
+
89
+ Three tools (`nreki_navigate`, `nreki_code`, `nreki_guard`), 26 actions (11 navigate + 6 code + 9 guard), 4 languages (TS/JS, Go via gopls, Python via pyright). Works with any MCP-compatible agent. Apache 2.0.
90
+
91
+ ### Token cost
92
+
93
+ Depending on the client, an agent pays NREKI's three tool definitions (~700 tokens) on every request of a session or once when it looks them up, and every tool result again on each later request. NREKI saves tokens only when it saves more than that: fewer turns and smaller results than the agent's own tools.
94
+
95
+ - `nreki_navigate action:"context" query:"<the task>"` returns, in one call, the code the task names: symbols verbatim with their line ranges, where the fields it mentions occur, and who imports each file. Exploring with `map`/grep/reads usually takes two or three turns.
96
+ - `read`/`compress` with `focus:"a,b"` return only those symbols; edits return one line plus the `[Validated: …]` footer.
97
+ - Measured with Codex (2026-11-13) on synthetic TypeScript projects of 30–40 files, three pairs per run. The first run cost 25 % more tokens with NREKI: `read` ignored `focus`, agents re-read what `context` returned, and took extra turns. After those fixes, a pre-registered run was a tie (+0.02 %) and a run on a new project cost +4.97 %: `context` saved the reading turns, but agents sent `batch_edit` alone and ran the checker on the next turn. With `context` now asking for the checker in the same cell, a run on another new project used **33 % fewer tokens**: 225,391 vs 336,643, 12 vs 18 turns, NREKI ahead in all 3 pairs, all 6 solutions correct. Every NREKI session took the minimum 4 turns: checker, `context`, `batch_edit` plus checker, answer. That is one project and three pairs: a measurement, not a guarantee. On a third new project (42 files) the published 12.1.0 cost 1.8 % more. In two of its three sessions `context` let one capitalized word ("Station", a type) stand for the whole task and returned none of the files to fix. 12.1.1 searches every issue that names no code. One pair on yet another new project, run on the 12.1.1 code before release, used 40.85 % fewer tokens: 449,645 vs 760,190, 21 vs 36 turns, both solutions correct. That is one session per arm, and the agents delegated differently. All runs after the fixes had the optional Voyage index on (see Privacy). In that last pair it made no query, so the default, `context` with BM25 alone, has not been measured on its own.
98
+
99
+ ## Highlights
100
+
101
+ - **Atomic multi-TextEdit healing.** When gopls or pyright proposes a quickfix with coupled edits (import + usage), NREKI applies every TextEdit of the chosen action together with per-file savepoints and bottom-up offset ordering. No more doom-loop retries where only the import lands and the usage stays broken.
102
+ - **Tolerant Patch mode.** `nreki_code action:"edit" mode:"patch"` now retries with indent-flexible matching when the exact-indent search fails and the content is unique. The literal-`$` guarantee is preserved end-to-end (no V8 `$&` / `$$` substitution surprises).
103
+ - **Cognitive Enforcer.** Agents can't `batch_edit` blindly - every edit in a batch is validated against a per-file passport (outline seen? symbol focused?). The v10.5.7 fix closed a bypass where 2+ edits could smuggle blind mutations through.
104
+ - **TTRD Bounties.** Successful strict-type restoration reports the exact CFI (Cognitive Friction Index) discount to the agent. Pavlovian reinforcement that actually quantifies what improved.
105
+ - **Defect radar + ghost oracle.** Four inline detectors and a 0-ext-refs tagger run during `outline` - free signals, no extra tool call.
106
+ - **Executable engrams.** Pin insights to symbols. Engrams prefixed `ASSERT` survive AST mutation; everything else invalidates on body change so memory can't go stale.
107
+
108
+ ## Language support (Validation + Auto-heal)
109
+
110
+ | Language | Validation | Auto-heal |
111
+ |----------|------------|-----------|
112
+ | TypeScript / JavaScript | Full (TS Compiler API) | TS CodeFix API |
113
+ | Go | gopls LSP sidecar | codeAction (atomic) |
114
+ | Python | pyright / basedpyright LSP sidecar | codeAction (atomic; basedpyright only — plain pyright validates without healing) |
115
+
116
+ ### What an accepted edit was checked against
117
+
118
+ Semantic checking is on whenever the project root has a `tsconfig.json`/`jsconfig.json`, a Python marker (`pyproject.toml`, `requirements.txt`, `setup.py`, `Pipfile`) or a `go.mod`; without one, edits get the syntax check only. The `[Validated: …]` footer of every edit states what ran for that edit.
119
+
120
+ | Project | Checked together with the edit |
121
+ |---------|--------------------------------|
122
+ | TypeScript, up to 200 files | the edited files and their direct importers (up to 50) |
123
+ | TypeScript, 201–1000 files | the whole program |
124
+ | TypeScript, over 1000 files | the edited files and their direct importers (up to 50) |
125
+ | Go | the edited files, the other files of their package and the files that import them (up to 50) |
126
+ | Python | the edited files and the files that import them (up to 50) |
127
+
128
+ For Go and Python only the errors an edit adds are fatal: an error that was already there does not block it. Transitive importers are not checked in any row but the second; run the compiler or the tests when the footer says so.
129
+
130
+ ## AST parser coverage
131
+
132
+ NREKI's tree-sitter parser layer indexes additional languages for
133
+ foveal compression + symbol retrieval + semantic-edit syntactic
134
+ validation. These languages do **not** have LSP sidecars and
135
+ therefore receive no auto-heal; otherwise their files participate
136
+ in the retrieval index identically to TypeScript files.
137
+
138
+ | Language | Extensions | Parser | Foveal | Syntax check | LSP auto-heal | Type Ledger |
139
+ |-------------|-----------------------------------------|--------|--------|--------------|---------------|-------------|
140
+ | TypeScript | .ts .tsx .mts .cts | ✓ | ✓ | ✓ | ✓ (tsc) | ✓ |
141
+ | JavaScript | .js .jsx .mjs .cjs | ✓ | ✓ | ✓ | ✓ (tsc) | ✓ |
142
+ | Python | .py | ✓ | ✓ | ✓ | ✓ (pyright) | — |
143
+ | Go | .go | ✓ | ✓ | ✓ | ✓ (gopls) | — |
144
+ | CSS | .css | ✓ | ✓ | ✓ | — | — |
145
+ | JSON | .json | ✓ | ✓ | ✓ | — | — |
146
+ | HTML | .html | ✓ | ✓ | ✓ | — | — |
147
+ | **Kotlin** | .kt .kts | ✓ | ✓ | ✓ | — | — |
148
+ | **Java** | .java | ✓ | ✓ | ✓ | — | — |
149
+ | **C++** | .cpp .cc .cxx .hpp .hh .hxx .h* | ✓ | ✓ | ✓ | — | — |
150
+ | **C** | .c .h* | ✓ | ✓ | ✓ | — | — |
151
+
152
+ Kotlin / Java / C++ / C activation in v11.0.x covers Android development
153
+ (Kotlin app layer + Java legacy + C++ NDK native layer + C NDK code) and the
154
+ broader JVM / native cross-platform ecosystem.
155
+
156
+ > *`.h` headers are routed at parse time: headers containing
157
+ > C++ markers (template, namespace, class, `#ifdef __cplusplus`)
158
+ > use the C++ grammar; pure C headers use the C grammar. Default
159
+ > to C grammar for ambiguous cases.
160
+
161
+ **Known limitation (v11.0.x):** cross-file import detection for
162
+ Kotlin / Java / C++ / C is not yet implemented. Repo-map dependency edges
163
+ for files in these languages are intra-file only until v11.0.x.1.
164
+
165
+ ### Known limitations (v11.0.1)
166
+
167
+ **Android XML manifests and Gradle build files are NOT yet indexed.**
168
+ AndroidManifest.xml, resource XMLs (`res/layout/`, `res/values/`, etc.),
169
+ and Gradle build scripts (`build.gradle` Groovy DSL) coverage is tracked
170
+ for v11.0.2 (see issue #4).
171
+
172
+ **WASM checksum verification deferred.** Upstream grammar upgrades may not
173
+ propagate to vendor `wasm/` directory due to skip-if-exists logic in
174
+ `scripts/download-wasm.js`. SHA-256 checksum verification tracked as issue #5.
175
+
176
+ **chunks table lacks language column.** Retrieval language-aware scoring
177
+ requires runtime path extension filtering. Breaking migration tracked as
178
+ issue #6 (coordinated with v11.0.2 XML activation due to noise risk
179
+ amplification).
180
+
181
+ **Type Ledger (cross-file architectural dependency mapping) remains
182
+ TypeScript-specific by design** - it relies on TypeScript compiler-
183
+ derived type information. Multi-language Type Ledger expansion is
184
+ tracked under the Phase 8 roadmap.
185
+
186
+ ## Privacy: everything is local unless you opt in
187
+
188
+ By default no code leaves the machine. `search` can optionally add semantic recall (find code by meaning, even when it shares no words with the question) with your own [Voyage AI](https://www.voyageai.com/) key:
189
+
190
+ ```bash
191
+ NREKI_SEMANTIC=voyage # explicit opt-in (required)
192
+ NREKI_VOYAGE_API_KEY=pa-... # or VOYAGE_API_KEY
193
+ NREKI_VOYAGE_MODEL=voyage-code-4 # optional, default shown
194
+ NREKI_VOYAGE_MAX_TOKENS=20000000 # optional per-process embedding budget
195
+ ```
196
+
197
+ - A `VOYAGE_API_KEY` exported for another tool does **not** enable it; `NREKI_SEMANTIC=voyage` does.
198
+ - **What is sent:** every indexed code chunk (project-relative path, its comments, up to 6,000 characters of code) is embedded **once**, in the background, and the vector is stored locally in `.nreki.db`. Unchanged chunks are never re-sent, also after a restart; an edited file re-sends only its changed chunks. Each `search` sends only the query. Sensitive paths (`.env`, keys, `.ssh`, …) are never sent; secrets hard-coded in ordinary source files would be.
199
+ - **Cost:** about one token per 3.5 characters of code, once. A 1M-token repository is roughly $0.12 at voyage-code-4's list price, inside the free tier Voyage gives each account.
200
+ - **How results change:** the dense ranking is fused with BM25 (reciprocal-rank fusion), so a chunk BM25 never retrieved can surface. Until indexing finishes, and whenever Voyage is unreachable (2.5 s timeout) or the key is rejected, search answers from BM25 alone and logs the reason once.
201
+ - Check Voyage's terms for data retention/training; on self-serve accounts, opting out of training requires a payment method on file.
202
+
203
+ ### Memory files are signed
204
+
205
+ NREKI's memory lives in the project folder: engrams, `memorize` notes and the plan pointer (`.nreki.db`), pinned rules (`.nreki/pins.json`), file history and the map cache (`.nreki/`). The agent reads parts of it as its own notes, and a repository could ship such files, so each one is signed with a key kept in your user folder (`~/.nreki/trust.key`, never in a project). A file without a valid signature is never loaded: it is moved to `.nreki/quarantine/` and the index is rebuilt.
206
+
207
+ Upgrading from 12.0.0 or earlier quarantines your old memory once. To restore it, run `npx nreki trust-db` in a terminal with the agent session closed: it lists the engrams, notes and pins it found and restores them only after you type `yes`. Without an interactive terminal it refuses, so an agent cannot run it on its own.
208
+
209
+ ## Docs & links
210
+
211
+ - **[CHANGELOG.md](CHANGELOG.md)** - full version history (every patch, every release, every test count).
212
+ - **[templates/CLAUDE.md](templates/CLAUDE.md)** - optimized instructions auto-installed by `npx nreki init`.
213
+ - **Issues / ideas** - GitHub Issues on this repo.
214
+
215
+ ## License
216
+
217
+ Apache 2.0. Zero cloud dependencies. Everything runs locally in the agent's process (the opt-in Voyage reranker above is the only exception).
@@ -0,0 +1,8 @@
1
+ /**
2
+ * bootstrap-root.ts — imported FIRST by index.ts, for its side effect.
3
+ *
4
+ * ES modules evaluate their imports in order before the importing module's
5
+ * body, so this runs before any other NREKI module can read process.cwd().
6
+ */
7
+ export {};
8
+ //# sourceMappingURL=bootstrap-root.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap-root.d.ts","sourceRoot":"","sources":["../src/bootstrap-root.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * bootstrap-root.ts — imported FIRST by index.ts, for its side effect.
3
+ *
4
+ * ES modules evaluate their imports in order before the importing module's
5
+ * body, so this runs before any other NREKI module can read process.cwd().
6
+ */
7
+ import { applyProjectRoot } from "./project-root.js";
8
+ applyProjectRoot();
9
+ //# sourceMappingURL=bootstrap-root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap-root.js","sourceRoot":"","sources":["../src/bootstrap-root.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,gBAAgB,EAAE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -15,5 +15,6 @@
15
15
  *
16
16
  * All processing is local. Zero cloud dependencies.
17
17
  */
18
+ import "./bootstrap-root.js";
18
19
  export declare function detectMode(dir: string): "syntax" | "file" | "project" | "hologram";
19
20
  //# sourceMappingURL=index.d.ts.map