nreki 12.2.0 → 12.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +91 -0
- package/README.md +35 -29
- package/dist/bootstrap-root.d.ts +8 -0
- package/dist/bootstrap-root.d.ts.map +1 -0
- package/dist/bootstrap-root.js +9 -0
- package/dist/bootstrap-root.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +516 -275
- package/dist/index.js.map +1 -1
- package/dist/init/agent-detect.d.ts +28 -10
- package/dist/init/agent-detect.d.ts.map +1 -1
- package/dist/init/agent-detect.js +74 -31
- package/dist/init/agent-detect.js.map +1 -1
- package/dist/init/global-register.d.ts +61 -0
- package/dist/init/global-register.d.ts.map +1 -0
- package/dist/init/global-register.js +822 -0
- package/dist/init/global-register.js.map +1 -0
- package/dist/init/init-runner.d.ts +39 -3
- package/dist/init/init-runner.d.ts.map +1 -1
- package/dist/init/init-runner.js +254 -26
- package/dist/init/init-runner.js.map +1 -1
- package/dist/init/mcp-register.d.ts +55 -0
- package/dist/init/mcp-register.d.ts.map +1 -0
- package/dist/init/mcp-register.js +451 -0
- package/dist/init/mcp-register.js.map +1 -0
- package/dist/init/setup-ui.d.ts +70 -0
- package/dist/init/setup-ui.d.ts.map +1 -0
- package/dist/init/setup-ui.js +533 -0
- package/dist/init/setup-ui.js.map +1 -0
- package/dist/init/voyage-prompt.d.ts +85 -0
- package/dist/init/voyage-prompt.d.ts.map +1 -0
- package/dist/init/voyage-prompt.js +263 -0
- package/dist/init/voyage-prompt.js.map +1 -0
- package/dist/project-root.d.ts +73 -0
- package/dist/project-root.d.ts.map +1 -0
- package/dist/project-root.js +233 -0
- package/dist/project-root.js.map +1 -0
- package/dist/search/voyage.d.ts +2 -1
- package/dist/search/voyage.d.ts.map +1 -1
- package/dist/search/voyage.js +5 -2
- package/dist/search/voyage.js.map +1 -1
- package/dist/utils/voyage-key.d.ts +32 -0
- package/dist/utils/voyage-key.d.ts.map +1 -0
- package/dist/utils/voyage-key.js +89 -0
- package/dist/utils/voyage-key.js.map +1 -0
- package/package.json +2 -9
- package/scripts/download-wasm.js +5 -1
- package/src/bootstrap-root.ts +10 -0
- package/src/index.ts +516 -272
- package/src/init/agent-detect.ts +120 -72
- package/src/init/global-register.ts +862 -0
- package/src/init/init-runner.ts +254 -27
- package/src/init/mcp-register.ts +474 -0
- package/src/init/setup-ui.ts +588 -0
- package/src/init/voyage-prompt.ts +316 -0
- package/src/project-root.ts +245 -0
- package/src/search/voyage.ts +5 -2
- package/src/utils/voyage-key.ts +89 -0
- package/templates/voyage-key-dialog.ps1 +83 -0
package/dist/index.js
CHANGED
|
@@ -15,9 +15,13 @@
|
|
|
15
15
|
*
|
|
16
16
|
* All processing is local. Zero cloud dependencies.
|
|
17
17
|
*/
|
|
18
|
+
// First import: switches to NREKI_PROJECT_ROOT before any module reads process.cwd().
|
|
19
|
+
import "./bootstrap-root.js";
|
|
18
20
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
19
21
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
22
|
+
import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
20
23
|
import { z } from "zod";
|
|
24
|
+
import os from "os";
|
|
21
25
|
import path from "path";
|
|
22
26
|
import fs from "fs";
|
|
23
27
|
import { NrekiEngine } from "./engine.js";
|
|
@@ -36,6 +40,7 @@ import { detectMode as detectModePure } from "./detect-mode.js";
|
|
|
36
40
|
import { startNativeEditServer } from "./hooks/native-edit-ipc.js";
|
|
37
41
|
import { validateNativeEdit } from "./hooks/native-edit-validator.js";
|
|
38
42
|
import { ensureHologramReady } from "./handlers/code/kernel-bridge.js";
|
|
43
|
+
import { decideProjectRoot, hasProjectMarker, inferProjectRootFromPath, isNonProjectLaunchDir, isSameOrInside, pickRootsFromMcpRoots, sameDir, } from "./project-root.js";
|
|
39
44
|
// ─── Performance Mode Auto-Detection ────────────────────────────────
|
|
40
45
|
// Bounded DFS. Uses stack.pop() which is O(1) in V8.
|
|
41
46
|
// Array.shift() is O(N) in V8 because it reindexes the contiguous memory block.
|
|
@@ -56,18 +61,32 @@ NREKI v${VERSION} - Semantic validation MCP server for AI coding agents
|
|
|
56
61
|
|
|
57
62
|
Usage:
|
|
58
63
|
npx nreki Start MCP server (default)
|
|
59
|
-
npx nreki init [options] Install
|
|
60
|
-
|
|
64
|
+
npx nreki init [options] Install NREKI globally for your user across
|
|
65
|
+
Claude Code, Antigravity, Cursor, Codex & VS Code
|
|
66
|
+
(opens a setup box for your Voyage API key)
|
|
67
|
+
npx nreki key Open the Voyage API key setup box anytime
|
|
68
|
+
npx nreki deinit [--global] Safely remove NREKI hooks and MCP registrations
|
|
61
69
|
npx nreki trust-db Review and restore quarantined engrams/notes/pins
|
|
62
70
|
(interactive terminal only)
|
|
63
71
|
|
|
64
72
|
\`init\` options:
|
|
65
|
-
--
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
--
|
|
73
|
+
--global, -g Install globally at user scope for all agents (default in a terminal;
|
|
74
|
+
no per-project .mcp.json approval needed)
|
|
75
|
+
--project, --local Install inside this project folder only
|
|
76
|
+
--agent <names> Agents to install for, comma-separated:
|
|
77
|
+
claude | codex | antigravity | cursor | cline | copilot | generic
|
|
78
|
+
--voyage Turn on Voyage semantic search in the registrations
|
|
79
|
+
--no-voyage Turn it off again
|
|
80
|
+
--prompt Always open the Voyage API key setup box
|
|
81
|
+
--no-prompt Never open the Voyage API key setup box
|
|
82
|
+
--no-mcp Write the instructions only, do not register the MCP server
|
|
83
|
+
--force Rewrite existing NREKI blocks and replace custom "nreki" MCP entries
|
|
69
84
|
--dry-run Print plan only, no filesystem writes
|
|
70
85
|
|
|
86
|
+
Environment:
|
|
87
|
+
NREKI_PROJECT_ROOT Absolute path of the project folder (optional; global servers auto-detect
|
|
88
|
+
the open workspace via MCP roots/list or project_root)
|
|
89
|
+
|
|
71
90
|
Global flags:
|
|
72
91
|
--help, -h Show this help message
|
|
73
92
|
--version, -v Show version
|
|
@@ -107,8 +126,15 @@ if (args[0] === "deinit") {
|
|
|
107
126
|
delete settings.hooks.PreToolUse;
|
|
108
127
|
if (settings.hooks && Object.keys(settings.hooks).length === 0)
|
|
109
128
|
delete settings.hooks;
|
|
110
|
-
|
|
111
|
-
|
|
129
|
+
if (Object.keys(settings).length === 0) {
|
|
130
|
+
// Only NREKI's hooks were in it (init creates it when absent).
|
|
131
|
+
fs.unlinkSync(claudeSettingsPath);
|
|
132
|
+
logger.info("Deleted .claude/settings.json (it only held NREKI's hooks)");
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
fs.writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
136
|
+
logger.info("Removed NREKI hooks from .claude/settings.json");
|
|
137
|
+
}
|
|
112
138
|
modified = true;
|
|
113
139
|
}
|
|
114
140
|
}
|
|
@@ -122,6 +148,8 @@ if (args[0] === "deinit") {
|
|
|
122
148
|
if (fs.existsSync(hookPath) && touchable(hookPath)) {
|
|
123
149
|
try {
|
|
124
150
|
fs.unlinkSync(hookPath);
|
|
151
|
+
const { removeEmptyDirs } = await import("./init/mcp-register.js");
|
|
152
|
+
removeEmptyDirs(cwd, path.dirname(hookPath));
|
|
125
153
|
logger.info("Deleted .claude/hooks/nreki-enforcer.mjs");
|
|
126
154
|
modified = true;
|
|
127
155
|
}
|
|
@@ -129,58 +157,23 @@ if (args[0] === "deinit") {
|
|
|
129
157
|
logger.error(`Failed to delete hook script: ${err.message}`);
|
|
130
158
|
}
|
|
131
159
|
}
|
|
132
|
-
// 3.
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (
|
|
139
|
-
|
|
140
|
-
if (cleanedContent === "") {
|
|
141
|
-
fs.unlinkSync(claudeMdPath);
|
|
142
|
-
logger.info("Deleted empty CLAUDE.md");
|
|
143
|
-
}
|
|
144
|
-
else {
|
|
145
|
-
fs.writeFileSync(claudeMdPath, cleanedContent + "\n", "utf-8");
|
|
146
|
-
logger.info("Removed NREKI instructions from CLAUDE.md");
|
|
147
|
-
}
|
|
160
|
+
// 3-4. Instruction files `init` wrote: NREKI's block in CLAUDE.md, AGENTS.md and
|
|
161
|
+
// .github/copilot-instructions.md (the user's content is kept), and the
|
|
162
|
+
// files NREKI owns (Claude skill, Cursor rule, Cline rule).
|
|
163
|
+
try {
|
|
164
|
+
const { removeInstructions } = await import("./init/init-runner.js");
|
|
165
|
+
for (const action of removeInstructions(cwd)) {
|
|
166
|
+
if (action.op === "removed") {
|
|
167
|
+
logger.info(`${action.path}: ${action.note}`);
|
|
148
168
|
modified = true;
|
|
149
169
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
logger.error(`Failed to clean CLAUDE.md: ${err.message}`);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
// 4. Clean AGENTS.md — strip only NREKI block, preserve user own rules
|
|
156
|
-
const agentsMdPath = path.join(cwd, "AGENTS.md");
|
|
157
|
-
if (fs.existsSync(agentsMdPath) && touchable(agentsMdPath)) {
|
|
158
|
-
try {
|
|
159
|
-
const content = fs.readFileSync(agentsMdPath, "utf-8").replace(/^\uFEFF/, "");
|
|
160
|
-
const nrekiMarker = "# Instructions for AI coding agents consuming NREKI via MCP";
|
|
161
|
-
const nrekiIdx = content.indexOf(nrekiMarker);
|
|
162
|
-
if (nrekiIdx !== -1) {
|
|
163
|
-
let stripFrom = nrekiIdx;
|
|
164
|
-
const before = content.substring(0, nrekiIdx);
|
|
165
|
-
const lastH1 = before.lastIndexOf("# AGENTS.md");
|
|
166
|
-
if (lastH1 !== -1 && before.substring(lastH1).trim() === "# AGENTS.md") {
|
|
167
|
-
stripFrom = lastH1;
|
|
168
|
-
}
|
|
169
|
-
const cleanedContent = content.substring(0, stripFrom).trim();
|
|
170
|
-
if (cleanedContent === "") {
|
|
171
|
-
fs.unlinkSync(agentsMdPath);
|
|
172
|
-
logger.info("Deleted empty AGENTS.md");
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
fs.writeFileSync(agentsMdPath, cleanedContent + "\n", "utf-8");
|
|
176
|
-
logger.info("Removed NREKI instructions from AGENTS.md");
|
|
177
|
-
}
|
|
178
|
-
modified = true;
|
|
170
|
+
else {
|
|
171
|
+
logger.warn(`${action.path}: ${action.note}`);
|
|
179
172
|
}
|
|
180
173
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
}
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
logger.error(`Failed to clean instruction files: ${err.message}`);
|
|
184
177
|
}
|
|
185
178
|
// 5. Clean SKILL.md — strip only NREKI block, preserve user own rules
|
|
186
179
|
const skillMdPath = path.join(cwd, "SKILL.md");
|
|
@@ -225,6 +218,47 @@ if (args[0] === "deinit") {
|
|
|
225
218
|
logger.error(`Failed to clean session markers: ${err.message}`);
|
|
226
219
|
}
|
|
227
220
|
}
|
|
221
|
+
// 7. Remove the MCP server entries `nreki init` wrote (only entries that launch
|
|
222
|
+
// the nreki package; a user's own "nreki" entry is left alone).
|
|
223
|
+
{
|
|
224
|
+
const { MCP_HOSTS, unregisterMcp } = await import("./init/mcp-register.js");
|
|
225
|
+
for (const host of MCP_HOSTS) {
|
|
226
|
+
try {
|
|
227
|
+
const removed = unregisterMcp(host, cwd);
|
|
228
|
+
if (!removed)
|
|
229
|
+
continue;
|
|
230
|
+
if (removed.op === "removed") {
|
|
231
|
+
logger.info(`Removed NREKI MCP registration from ${removed.path} (${removed.note})`);
|
|
232
|
+
modified = true;
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
logger.warn(`${removed.path}: ${removed.note}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
logger.error(`Failed to clean ${host} MCP registration: ${err.message}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// 8. When `--global` / `-g` / `--all` is passed, also remove user-scoped registrations.
|
|
244
|
+
if (args.includes("--global") || args.includes("-g") || args.includes("--all")) {
|
|
245
|
+
try {
|
|
246
|
+
const { unregisterGlobalAll } = await import("./init/global-register.js");
|
|
247
|
+
const userHome = process.env.NREKI_USER_HOME ? path.resolve(process.env.NREKI_USER_HOME) : os.homedir();
|
|
248
|
+
for (const removed of unregisterGlobalAll(userHome)) {
|
|
249
|
+
if (removed.op === "removed") {
|
|
250
|
+
logger.info(`Removed global registration ${removed.path} (${removed.note})`);
|
|
251
|
+
modified = true;
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
logger.warn(`${removed.path}: ${removed.note}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
logger.error(`Failed to clean global registrations: ${err.message}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
228
262
|
if (modified) {
|
|
229
263
|
logger.info("NREKI deinit complete. Your environment is clean.");
|
|
230
264
|
}
|
|
@@ -240,29 +274,79 @@ if (args[0] === "trust-db") {
|
|
|
240
274
|
const { runTrustDbCli } = await import("./init/trust-db.js");
|
|
241
275
|
process.exit(await runTrustDbCli(process.cwd()));
|
|
242
276
|
}
|
|
277
|
+
// ─── Voyage Key Subcommand (`npx nreki key`) ────────────────────────
|
|
278
|
+
if (args[0] === "key") {
|
|
279
|
+
try {
|
|
280
|
+
const { promptForVoyage } = await import("./init/voyage-prompt.js");
|
|
281
|
+
const { runInit, formatAction } = await import("./init/init-runner.js");
|
|
282
|
+
const answer = await promptForVoyage();
|
|
283
|
+
for (const line of answer.lines)
|
|
284
|
+
process.stderr.write(`${line}\n`);
|
|
285
|
+
if (answer.voyage !== undefined) {
|
|
286
|
+
const userHome = process.env.NREKI_USER_HOME ? path.resolve(process.env.NREKI_USER_HOME) : os.homedir();
|
|
287
|
+
// cwd = home: changing the key only updates the user-scope entries; it
|
|
288
|
+
// must not migrate the .mcp.json of whatever folder `key` runs in.
|
|
289
|
+
const result = runInit({ global: true, home: userHome, cwd: userHome, voyage: answer.voyage });
|
|
290
|
+
for (const action of result.actions) {
|
|
291
|
+
if (action.op !== "skipped")
|
|
292
|
+
process.stderr.write(` ${formatAction(action)}\n`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
process.exit(0);
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
process.stderr.write(`nreki key failed: ${err.message}\n`);
|
|
299
|
+
process.exit(1);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
243
302
|
// ─── Init Subcommand ────────────────────────────────────────────────
|
|
244
303
|
if (args[0] === "init") {
|
|
245
|
-
// v11.3.0: agent-aware init. Detects Claude Code / Cursor / Cline /
|
|
246
|
-
// Copilot via filesystem signals and only writes the files that
|
|
247
|
-
// agent actually reads. --agent overrides detection, --force
|
|
248
|
-
// rewrites existing NREKI blocks, --dry-run previews the plan.
|
|
249
304
|
const { parseInitArgs, runInit, formatAction } = await import("./init/init-runner.js");
|
|
250
305
|
const parsed = parseInitArgs(args.slice(1));
|
|
251
306
|
if (parsed.error) {
|
|
252
307
|
process.stderr.write(`nreki init: ${parsed.error}\n`);
|
|
253
|
-
process.stderr.write("\nUsage: nreki init [--agent <claude
|
|
308
|
+
process.stderr.write("\nUsage: nreki init [--global|--project] [--agent <claude,codex,antigravity,cursor,cline,copilot,generic>]" +
|
|
309
|
+
" [--voyage|--no-voyage] [--prompt|--no-prompt] [--no-mcp] [--force] [--dry-run]\n");
|
|
254
310
|
process.exit(2);
|
|
255
311
|
}
|
|
256
312
|
try {
|
|
257
|
-
const
|
|
313
|
+
const opts = parsed.opts;
|
|
314
|
+
const userHome = process.env.NREKI_USER_HOME ? path.resolve(process.env.NREKI_USER_HOME) : os.homedir();
|
|
315
|
+
opts.home = userHome;
|
|
316
|
+
// In a person's terminal, default to the user-scope install so Claude Code,
|
|
317
|
+
// Antigravity, Cursor, and Codex work across all projects without per-repo
|
|
318
|
+
// `.mcp.json` approval prompts (`--project` opts into repo-local).
|
|
319
|
+
// --prompt/--no-prompt only control the Voyage box, never the scope.
|
|
320
|
+
const { initTerminalDefaults, promptForVoyage } = await import("./init/voyage-prompt.js");
|
|
321
|
+
const defaults = initTerminalDefaults(opts);
|
|
322
|
+
opts.global = defaults.global;
|
|
323
|
+
const interactive = defaults.showVoyageBox;
|
|
324
|
+
const voyageLines = [];
|
|
325
|
+
if (interactive && !opts.dryRun && opts.mcp !== false && opts.voyage !== false) {
|
|
326
|
+
const { availableVoyageKey } = await import("./utils/voyage-key.js");
|
|
327
|
+
if (!(opts.voyage === true && availableVoyageKey() !== null)) {
|
|
328
|
+
const answer = await promptForVoyage();
|
|
329
|
+
if (answer.voyage !== undefined)
|
|
330
|
+
opts.voyage = answer.voyage;
|
|
331
|
+
voyageLines.push(...answer.lines);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const result = runInit(opts);
|
|
335
|
+
for (const line of voyageLines)
|
|
336
|
+
process.stderr.write(`${line}\n`);
|
|
258
337
|
process.stderr.write(`nreki init: ${result.reason}\n`);
|
|
259
|
-
process.stderr.write(`
|
|
338
|
+
process.stderr.write(` agents: ${result.agents.join(", ")}${parsed.opts.dryRun ? " (dry-run)" : ""}\n`);
|
|
260
339
|
for (const action of result.actions) {
|
|
261
340
|
process.stderr.write(` ${formatAction(action)}\n`);
|
|
262
341
|
}
|
|
342
|
+
if (result.notes.length > 0) {
|
|
343
|
+
process.stderr.write("\nNext:\n");
|
|
344
|
+
for (const note of result.notes)
|
|
345
|
+
process.stderr.write(` - ${note}\n`);
|
|
346
|
+
}
|
|
263
347
|
if (result.agent === "generic" && !parsed.opts.agent) {
|
|
264
|
-
process.stderr.write("\nNo agent
|
|
265
|
-
"re-run with --agent <name
|
|
348
|
+
process.stderr.write("\nNo agent detected in this project or on this computer. If you use Claude Code / Codex /\n" +
|
|
349
|
+
"Antigravity / Cursor / Cline / Copilot, re-run with --agent <name>.\n");
|
|
266
350
|
}
|
|
267
351
|
process.exit(0);
|
|
268
352
|
}
|
|
@@ -271,74 +355,284 @@ if (args[0] === "init") {
|
|
|
271
355
|
process.exit(1);
|
|
272
356
|
}
|
|
273
357
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
nrekiMode =
|
|
296
|
-
|
|
297
|
-
|
|
358
|
+
const pinnedByEnv = decideProjectRoot(process.env.NREKI_PROJECT_ROOT).kind === "apply";
|
|
359
|
+
let currentWorkspace = null;
|
|
360
|
+
let liveTransportConnected = false;
|
|
361
|
+
let transportReady = false;
|
|
362
|
+
let clientRootDirs = [];
|
|
363
|
+
let switchChain = Promise.resolve();
|
|
364
|
+
let rootsSync = null;
|
|
365
|
+
async function buildWorkspaceRuntime(targetDir, source) {
|
|
366
|
+
const root = path.resolve(targetDir);
|
|
367
|
+
if (path.resolve(process.cwd()) !== root)
|
|
368
|
+
process.chdir(root);
|
|
369
|
+
const engine = new NrekiEngine({
|
|
370
|
+
dbPath: path.join(root, ".nreki.db"),
|
|
371
|
+
watchPaths: [root],
|
|
372
|
+
});
|
|
373
|
+
engine.setMetadata("nreki_session_start", new Date().toISOString());
|
|
374
|
+
const monitor = new TokenMonitor();
|
|
375
|
+
const sandbox = new AstSandbox();
|
|
376
|
+
const circuitBreaker = new CircuitBreaker(root);
|
|
377
|
+
const chronos = new ChronosMemory(root);
|
|
378
|
+
let kernel;
|
|
379
|
+
let nrekiMode = "syntax";
|
|
380
|
+
const hasTsConfig = fs.existsSync(path.join(root, "tsconfig.json")) ||
|
|
381
|
+
fs.existsSync(path.join(root, "jsconfig.json"));
|
|
382
|
+
const hasGoProject = fs.existsSync(path.join(root, "go.mod"));
|
|
383
|
+
const pyMarkers = ["pyproject.toml", "requirements.txt", "setup.py", "Pipfile"];
|
|
384
|
+
const hasPyProject = pyMarkers.some(f => fs.existsSync(path.join(root, f)));
|
|
385
|
+
if (hasTsConfig || hasPyProject || hasGoProject) {
|
|
386
|
+
nrekiMode = detectMode(root);
|
|
387
|
+
if (nrekiMode === "syntax") {
|
|
388
|
+
logger.info("SYNTAX mode. Kernel disabled. Layer 1 AST only.");
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
const envs = [
|
|
392
|
+
hasTsConfig ? "TS/JS" : "",
|
|
393
|
+
hasPyProject ? "Python" : "",
|
|
394
|
+
hasGoProject ? "Go" : "",
|
|
395
|
+
].filter(Boolean).join(", ");
|
|
396
|
+
logger.info(`${nrekiMode.toUpperCase()} mode detected (${envs}). Kernel boots on first edit.`);
|
|
397
|
+
kernel = new NrekiKernel();
|
|
398
|
+
}
|
|
298
399
|
}
|
|
299
400
|
else {
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
hasPyProject ? "Python" : "",
|
|
303
|
-
hasGoProject ? "Go" : "",
|
|
304
|
-
].filter(Boolean).join(", ");
|
|
305
|
-
logger.info(`${nrekiMode.toUpperCase()} mode detected (${envs}). Kernel boots on first edit.`);
|
|
306
|
-
kernel = new NrekiKernel();
|
|
401
|
+
logger.info("No project markers found (tsconfig.json / pyproject.toml / go.mod). " +
|
|
402
|
+
"Semantic verification disabled. Operating in Tree-sitter-only mode (Layer 1).");
|
|
307
403
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
try {
|
|
319
|
-
const { GoLspSidecar } = await import("./kernel/backends/go-sidecar.js");
|
|
320
|
-
kernel.registerSidecar(".go", new GoLspSidecar(cwd));
|
|
321
|
-
logger.info("Go project detected (go.mod). gopls sidecar registered.");
|
|
404
|
+
if (kernel) {
|
|
405
|
+
if (hasGoProject) {
|
|
406
|
+
try {
|
|
407
|
+
const { GoLspSidecar } = await import("./kernel/backends/go-sidecar.js");
|
|
408
|
+
kernel.registerSidecar(".go", new GoLspSidecar(root));
|
|
409
|
+
logger.info("Go project detected (go.mod). gopls sidecar registered.");
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
logger.error(`Failed to load Go sidecar: ${err.message}`);
|
|
413
|
+
}
|
|
322
414
|
}
|
|
323
|
-
|
|
324
|
-
|
|
415
|
+
if (hasPyProject) {
|
|
416
|
+
try {
|
|
417
|
+
const { PythonLspSidecar } = await import("./kernel/backends/python-sidecar.js");
|
|
418
|
+
const pySidecar = new PythonLspSidecar(root);
|
|
419
|
+
kernel.registerSidecar(".py", pySidecar);
|
|
420
|
+
logger.info(`Python project detected. ${pySidecar.command[0]} sidecar registered.`);
|
|
421
|
+
}
|
|
422
|
+
catch (err) {
|
|
423
|
+
logger.error(`Failed to load Python sidecar: ${err.message}`);
|
|
424
|
+
}
|
|
325
425
|
}
|
|
326
426
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
427
|
+
const enforcer = new CognitiveEnforcer(root);
|
|
428
|
+
const deps = { engine, monitor, sandbox, circuitBreaker, kernel, chronos, nrekiMode, enforcer };
|
|
429
|
+
engine.onExternalBatchChange(async (files) => { await kernel?.notifyExternalChange(files); });
|
|
430
|
+
let nativeEdits;
|
|
431
|
+
let removeSessionMarker = null;
|
|
432
|
+
let closed = false;
|
|
433
|
+
let backgroundStarted = false;
|
|
434
|
+
const runtime = {
|
|
435
|
+
root,
|
|
436
|
+
source,
|
|
437
|
+
deps,
|
|
438
|
+
liveBooted: false,
|
|
439
|
+
bootLive: async () => {
|
|
440
|
+
if (runtime.liveBooted || closed)
|
|
441
|
+
return;
|
|
442
|
+
runtime.liveBooted = true;
|
|
443
|
+
// ─── SESSION MARKER (read by the Claude Code enforcer hook) ───
|
|
444
|
+
const sessionMarker = path.join(root, ".nreki", "sessions", String(process.pid));
|
|
445
|
+
try {
|
|
446
|
+
if (!unsafeWriteTarget(root, sessionMarker)) {
|
|
447
|
+
const sessionsDir = path.dirname(sessionMarker);
|
|
448
|
+
if (fs.existsSync(sessionsDir)) {
|
|
449
|
+
for (const entry of fs.readdirSync(sessionsDir)) {
|
|
450
|
+
if (!/^\d+$/.test(entry))
|
|
451
|
+
continue;
|
|
452
|
+
const pid = Number(entry);
|
|
453
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid)
|
|
454
|
+
continue;
|
|
455
|
+
try {
|
|
456
|
+
process.kill(pid, 0);
|
|
457
|
+
}
|
|
458
|
+
catch (err) {
|
|
459
|
+
if (err.code === "ESRCH") {
|
|
460
|
+
const stale = path.join(sessionsDir, entry);
|
|
461
|
+
if (!unsafeWriteTarget(root, stale)) {
|
|
462
|
+
try {
|
|
463
|
+
fs.unlinkSync(stale);
|
|
464
|
+
}
|
|
465
|
+
catch { /* raced */ }
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (process.env.NREKI_NATIVE_PREFLIGHT === "1") {
|
|
472
|
+
try {
|
|
473
|
+
nativeEdits = await startNativeEditServer(root, request => validateNativeEdit(request, deps));
|
|
474
|
+
}
|
|
475
|
+
catch (ipcErr) {
|
|
476
|
+
logger.warn(`Native edit IPC server unavailable (falling back to session-only marker): ${ipcErr.message}`);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
writeStateFile(root, sessionMarker, JSON.stringify({
|
|
481
|
+
startedAt: new Date().toISOString(), token: nativeEdits?.token,
|
|
482
|
+
}));
|
|
483
|
+
fs.chmodSync(sessionMarker, 0o600);
|
|
484
|
+
removeSessionMarker = () => { try {
|
|
485
|
+
fs.unlinkSync(sessionMarker);
|
|
486
|
+
}
|
|
487
|
+
catch { /* already gone */ } };
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
try {
|
|
491
|
+
nativeEdits?.close();
|
|
492
|
+
}
|
|
493
|
+
catch { /* already closed */ }
|
|
494
|
+
}
|
|
495
|
+
// ─── AUTO-PATCH SECURITY HOOK (v10.x) ───
|
|
496
|
+
try {
|
|
497
|
+
const upgrade = upgradeEnforcerHook(root, () => fs.readFileSync(new URL("../templates/hooks/nreki-enforcer.mjs", import.meta.url), "utf-8"));
|
|
498
|
+
if (upgrade === "upgraded")
|
|
499
|
+
logger.info("Auto-patched legacy nreki-enforcer hook for security.");
|
|
500
|
+
if (upgrade === "unsafe-path")
|
|
501
|
+
logger.warn(".claude/hooks/nreki-enforcer.mjs is a symbolic link or leaves the project: not upgraded.");
|
|
502
|
+
}
|
|
503
|
+
catch { /* Fail silently, never block boot */ }
|
|
504
|
+
},
|
|
505
|
+
// v11.2.1: the watcher's first directory walk must never run before the
|
|
506
|
+
// MCP handshake (Claude Code reported the silence as "connection closed:
|
|
507
|
+
// EOF"), and it is not awaited: tool handlers index on first use.
|
|
508
|
+
startBackground: () => {
|
|
509
|
+
if (backgroundStarted || closed)
|
|
510
|
+
return;
|
|
511
|
+
backgroundStarted = true;
|
|
512
|
+
const watcherReady = engine.startWatcher();
|
|
513
|
+
watcherReady.then(() => logger.info("File watcher started (reactive mode)."), (err) => logger.error(`File watcher failed (non-fatal): ${err.message}`));
|
|
514
|
+
if (nrekiMode === "hologram" && kernel) {
|
|
515
|
+
setImmediate(async () => {
|
|
516
|
+
if (closed)
|
|
517
|
+
return;
|
|
518
|
+
try {
|
|
519
|
+
await ensureHologramReady(kernel, nrekiMode, root);
|
|
520
|
+
logger.info("WASM parser pre-loaded. JIT Holography ready.");
|
|
521
|
+
}
|
|
522
|
+
catch (err) {
|
|
523
|
+
logger.warn(`WASM pre-load failed: ${err.message}`);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
shutdown: () => {
|
|
529
|
+
if (closed)
|
|
530
|
+
return;
|
|
531
|
+
closed = true;
|
|
532
|
+
try {
|
|
533
|
+
if (kernel && kernel.isBooted()) {
|
|
534
|
+
chronos.syncTechDebt(kernel.getInitialErrorCount(), kernel.getCurrentErrorCount());
|
|
535
|
+
}
|
|
536
|
+
chronos.forcePersist();
|
|
537
|
+
}
|
|
538
|
+
catch { /* never block shutdown on telemetry */ }
|
|
539
|
+
try {
|
|
540
|
+
removeSessionMarker?.();
|
|
541
|
+
}
|
|
542
|
+
catch { /* already gone */ }
|
|
543
|
+
try {
|
|
544
|
+
nativeEdits?.close();
|
|
545
|
+
}
|
|
546
|
+
catch { /* already closed */ }
|
|
547
|
+
try {
|
|
548
|
+
engine.shutdown();
|
|
549
|
+
}
|
|
550
|
+
catch { /* swallow */ }
|
|
551
|
+
// A switched-away workspace must not keep its gopls/pyright running
|
|
552
|
+
// until the process exits (their exit hooks only fire then).
|
|
553
|
+
if (kernel)
|
|
554
|
+
void kernel.shutdownSidecars().catch(() => { });
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
return runtime;
|
|
558
|
+
}
|
|
559
|
+
function switchWorkspace(targetDir, source) {
|
|
560
|
+
const next = switchChain.then(async () => {
|
|
561
|
+
const resolved = path.resolve(targetDir);
|
|
562
|
+
if (currentWorkspace && sameDir(currentWorkspace.root, resolved)) {
|
|
563
|
+
if (liveTransportConnected && !currentWorkspace.liveBooted) {
|
|
564
|
+
await currentWorkspace.bootLive();
|
|
565
|
+
}
|
|
566
|
+
if (transportReady)
|
|
567
|
+
currentWorkspace.startBackground();
|
|
568
|
+
return;
|
|
333
569
|
}
|
|
334
|
-
|
|
335
|
-
|
|
570
|
+
if (currentWorkspace) {
|
|
571
|
+
currentWorkspace.shutdown();
|
|
572
|
+
currentWorkspace = null;
|
|
573
|
+
}
|
|
574
|
+
currentWorkspace = await buildWorkspaceRuntime(resolved, source);
|
|
575
|
+
if (liveTransportConnected) {
|
|
576
|
+
await currentWorkspace.bootLive();
|
|
336
577
|
}
|
|
578
|
+
if (transportReady)
|
|
579
|
+
currentWorkspace.startBackground();
|
|
580
|
+
logger.info(`Workspace bound to ${resolved}`);
|
|
581
|
+
});
|
|
582
|
+
switchChain = next.catch((err) => {
|
|
583
|
+
logger.error(`Workspace switch failed: ${err.message}`);
|
|
584
|
+
});
|
|
585
|
+
return next;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* The workspace a `project_root` (or a path's enclosing project) may bind, or
|
|
589
|
+
* why not. Inside the current workspace: keep it. Otherwise it must be inside
|
|
590
|
+
* one of the client's MCP roots; when the host chose the folder (pinned, its
|
|
591
|
+
* MCP roots, or started in a project) it cannot be left; a folder named by the model is
|
|
592
|
+
* never the home folder, a folder above it, a hidden folder in it or a system
|
|
593
|
+
* folder (a prompt injection would otherwise point NREKI at ~/.claude or ~/.ssh).
|
|
594
|
+
*/
|
|
595
|
+
function workspaceTarget(requested) {
|
|
596
|
+
const dir = path.resolve(requested);
|
|
597
|
+
if (currentWorkspace && isSameOrInside(dir, currentWorkspace.root)) {
|
|
598
|
+
return { dir: currentWorkspace.root, source: currentWorkspace.source };
|
|
599
|
+
}
|
|
600
|
+
if (clientRootDirs.length > 0) {
|
|
601
|
+
const root = clientRootDirs.find((r) => isSameOrInside(dir, r));
|
|
602
|
+
if (root)
|
|
603
|
+
return { dir: root, source: "roots" };
|
|
604
|
+
return {
|
|
605
|
+
error: `project_root "${dir}" is outside the workspace folders your editor shared with NREKI ` +
|
|
606
|
+
`(${clientRootDirs.join(", ")}). Open that folder in your editor to work on it.`,
|
|
607
|
+
};
|
|
337
608
|
}
|
|
609
|
+
if (currentWorkspace && currentWorkspace.source !== "guess" && currentWorkspace.source !== "explicit") {
|
|
610
|
+
const chosenBy = currentWorkspace.source === "launch" ? "the project it was started in"
|
|
611
|
+
: currentWorkspace.source === "env" ? "the project NREKI_PROJECT_ROOT names"
|
|
612
|
+
: "the project your editor opened";
|
|
613
|
+
return {
|
|
614
|
+
error: `NREKI is bound to ${currentWorkspace.root}, ${chosenBy}; ` +
|
|
615
|
+
`project_root "${dir}" is outside it. Open that folder in your editor to work on it.`,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
if (isNonProjectLaunchDir(dir)) {
|
|
619
|
+
return {
|
|
620
|
+
error: `project_root "${dir}" is a home, hidden or system folder, not a project. ` +
|
|
621
|
+
"Pass the absolute path of the project folder.",
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
return { dir, source: "explicit" };
|
|
625
|
+
}
|
|
626
|
+
// Boot immediately when started inside a folder that can be a project (or pinned
|
|
627
|
+
// by NREKI_PROJECT_ROOT). When a global host launches NREKI inside its own config
|
|
628
|
+
// dir (`~/.gemini/config/plugins/nreki`, `~`, `/`, etc.), defer until MCP
|
|
629
|
+
// roots/list or `project_root` arrives so that folder is never polluted.
|
|
630
|
+
if (pinnedByEnv) {
|
|
631
|
+
currentWorkspace = await buildWorkspaceRuntime(process.cwd(), "env");
|
|
632
|
+
}
|
|
633
|
+
else if (!isNonProjectLaunchDir(process.cwd())) {
|
|
634
|
+
currentWorkspace = await buildWorkspaceRuntime(process.cwd(), hasProjectMarker(process.cwd()) ? "launch" : "guess");
|
|
338
635
|
}
|
|
339
|
-
const enforcer = new CognitiveEnforcer(process.cwd());
|
|
340
|
-
const deps = { engine, monitor, sandbox, circuitBreaker, kernel, chronos, nrekiMode, enforcer };
|
|
341
|
-
engine.onExternalBatchChange(async (files) => { await kernel?.notifyExternalChange(files); });
|
|
342
636
|
const server = new McpServer({
|
|
343
637
|
name: "NREKI",
|
|
344
638
|
version: VERSION,
|
|
@@ -350,28 +644,60 @@ const server = new McpServer({
|
|
|
350
644
|
logger.info("NREKI edit-safety MCP. Retrieval via search (BM25 + topology, optional Voyage semantic index) + fast_grep (RAM-resident). "
|
|
351
645
|
+ "v11.0.0 removed ONNX embeddings; v12.0.0 removed hybrid_search.");
|
|
352
646
|
// ─── Tool 1: nreki_navigate ───────────────────────────────────────────
|
|
353
|
-
// Tool definitions are paid on EVERY model request (Claude Code) or printed by
|
|
354
|
-
// the agent to learn the calls (Codex code mode: ~1k tokens each time in the
|
|
355
|
-
// 2026-11-13 A/B). Only everyday parameters are declared; the advanced ones are
|
|
356
|
-
// still accepted (passthrough), validated by the handlers, and named in the
|
|
357
|
-
// descriptions. Usage guidance lives in AGENTS.md/CLAUDE.md.
|
|
358
647
|
const optStr = (v) => (typeof v === "string" ? v : undefined);
|
|
359
648
|
const optNum = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
360
649
|
const optBool = (v) => (typeof v === "boolean" ? v : undefined);
|
|
650
|
+
const MISSING_WORKSPACE = "NREKI was started outside a workspace without MCP roots. Re-run this call with " +
|
|
651
|
+
"project_root:\"<absolute workspace path>\" once to bind the active project.";
|
|
652
|
+
/** The dependencies of the workspace this call runs in, or why there is none. */
|
|
653
|
+
async function resolveWorkspaceDeps(rawArgs) {
|
|
654
|
+
if (rootsSync)
|
|
655
|
+
await rootsSync;
|
|
656
|
+
await switchChain;
|
|
657
|
+
if (!pinnedByEnv) {
|
|
658
|
+
let requested = null;
|
|
659
|
+
const explicit = optStr(rawArgs.project_root)?.trim();
|
|
660
|
+
if (explicit) {
|
|
661
|
+
const d = decideProjectRoot(explicit);
|
|
662
|
+
if (d.kind === "apply")
|
|
663
|
+
requested = d.dir;
|
|
664
|
+
}
|
|
665
|
+
else if (!currentWorkspace) {
|
|
666
|
+
const firstEditPath = Array.isArray(rawArgs.edits) && rawArgs.edits[0] && typeof rawArgs.edits[0] === "object"
|
|
667
|
+
? optStr(rawArgs.edits[0].path)
|
|
668
|
+
: undefined;
|
|
669
|
+
requested = inferProjectRootFromPath(optStr(rawArgs.path) ?? firstEditPath);
|
|
670
|
+
}
|
|
671
|
+
if (requested) {
|
|
672
|
+
const target = workspaceTarget(requested);
|
|
673
|
+
if ("error" in target)
|
|
674
|
+
return target.error;
|
|
675
|
+
await switchWorkspace(target.dir, target.source);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return currentWorkspace?.deps ?? MISSING_WORKSPACE;
|
|
679
|
+
}
|
|
680
|
+
function workspaceError(text) {
|
|
681
|
+
return { isError: true, content: [{ type: "text", text }] };
|
|
682
|
+
}
|
|
361
683
|
server.registerTool("nreki_navigate", {
|
|
362
684
|
description: "Find code. context: query = the task; returns the code it names (symbols verbatim, other mentions, importers) in one call. " +
|
|
363
685
|
"fast_grep: exact text -> file:line [symbol]. search: concept search. definition/references: by symbol. outline: symbols of path. " +
|
|
364
686
|
"type_shape: resolved TS type. prepare_refactor: occurrences to rename. map: repo overview (large). " +
|
|
365
|
-
"orphan_oracle: unreachable files. type_graph: code using type_name. Also: token_budget (context), depth, kind.",
|
|
687
|
+
"orphan_oracle: unreachable files. type_graph: code using type_name. Also: token_budget (context), depth, kind, project_root.",
|
|
366
688
|
inputSchema: z.object({
|
|
367
689
|
action: z.enum(["context", "search", "definition", "references", "outline", "map", "prepare_refactor", "orphan_oracle", "type_shape", "fast_grep", "type_graph"]),
|
|
368
690
|
query: z.string().optional(),
|
|
369
691
|
symbol: z.string().optional(),
|
|
370
692
|
path: z.string().optional(),
|
|
371
693
|
limit: z.number().optional(),
|
|
694
|
+
project_root: z.string().optional(),
|
|
372
695
|
}).passthrough(),
|
|
373
696
|
}, async (args) => {
|
|
374
697
|
const a = args;
|
|
698
|
+
const activeDeps = await resolveWorkspaceDeps(a);
|
|
699
|
+
if (typeof activeDeps === "string")
|
|
700
|
+
return workspaceError(activeDeps);
|
|
375
701
|
const params = {
|
|
376
702
|
action: args.action, query: args.query, symbol: args.symbol, path: args.path, limit: args.limit,
|
|
377
703
|
include_raw: optBool(a.include_raw), kind: optStr(a.kind), signatures: optBool(a.signatures),
|
|
@@ -379,14 +705,14 @@ server.registerTool("nreki_navigate", {
|
|
|
379
705
|
type_name: optStr(a.type_name), walk_depth: optNum(a.walk_depth), direction: optStr(a.direction),
|
|
380
706
|
max_nodes: optNum(a.max_nodes), token_budget: optNum(a.token_budget),
|
|
381
707
|
};
|
|
382
|
-
return wrapWithCircuitBreaker(circuitBreaker, "nreki_navigate", args.action, () => handleNavigate(args.action, params,
|
|
708
|
+
return wrapWithCircuitBreaker(activeDeps.circuitBreaker, "nreki_navigate", args.action, () => handleNavigate(args.action, params, activeDeps), undefined, undefined, activeDeps.chronos);
|
|
383
709
|
});
|
|
384
710
|
// ─── Tool 2: nreki_code ───────────────────────────────────────────────
|
|
385
711
|
server.registerTool("nreki_code", {
|
|
386
712
|
description: "Read and edit code. read: whole file; with focus:\"a,b\" only those symbols (also compress focus). " +
|
|
387
713
|
"edit/batch_edit: change or delete (new_code:\"\") a symbol by name; syntax and types are checked before writing, nothing is written on error. " +
|
|
388
714
|
"mode patch: replace search_text with replace_text inside the symbol (cheapest). undo: revert the last edit of path. " +
|
|
389
|
-
"filter_output: shrink terminal text (output). Also: compress:true or level for skeletons.",
|
|
715
|
+
"filter_output: shrink terminal text (output). Also: compress:true or level for skeletons, project_root.",
|
|
390
716
|
inputSchema: z.object({
|
|
391
717
|
action: z.enum(["read", "compress", "edit", "batch_edit", "undo", "filter_output"]),
|
|
392
718
|
path: z.string().optional(),
|
|
@@ -405,9 +731,13 @@ server.registerTool("nreki_code", {
|
|
|
405
731
|
replace_text: z.string().optional(),
|
|
406
732
|
}))).optional(),
|
|
407
733
|
output: z.string().optional(),
|
|
734
|
+
project_root: z.string().optional(),
|
|
408
735
|
}).passthrough(),
|
|
409
736
|
}, async (args) => {
|
|
410
737
|
const a = args;
|
|
738
|
+
const activeDeps = await resolveWorkspaceDeps(a);
|
|
739
|
+
if (typeof activeDeps === "string")
|
|
740
|
+
return workspaceError(activeDeps);
|
|
411
741
|
const params = {
|
|
412
742
|
action: args.action, path: args.path, symbol: args.symbol, focus: args.focus, mode: args.mode,
|
|
413
743
|
new_code: args.new_code, search_text: args.search_text, replace_text: args.replace_text,
|
|
@@ -416,73 +746,53 @@ server.registerTool("nreki_code", {
|
|
|
416
746
|
auto_context: optBool(a.auto_context), compute_diff: optBool(a.compute_diff),
|
|
417
747
|
_nreki_bypass: optStr(a._nreki_bypass), max_cross_file: optNum(a.max_cross_file),
|
|
418
748
|
};
|
|
419
|
-
return wrapWithCircuitBreaker(circuitBreaker, "nreki_code", args.action, () => handleCode(args.action, params,
|
|
420
|
-
// batch_edit names its targets in edits: without them the breaker told
|
|
421
|
-
// the agent to rewrite "the failing symbol" in "the current file".
|
|
422
|
-
args.path ?? args.edits?.[0]?.path, args.symbol ?? args.edits?.[0]?.symbol, chronos);
|
|
749
|
+
return wrapWithCircuitBreaker(activeDeps.circuitBreaker, "nreki_code", args.action, () => handleCode(args.action, params, activeDeps), args.path ?? args.edits?.[0]?.path, args.symbol ?? args.edits?.[0]?.symbol, activeDeps.chronos);
|
|
423
750
|
});
|
|
424
751
|
// ─── Tool 3: nreki_guard ──────────────────────────────────────────────
|
|
425
752
|
server.registerTool("nreki_guard", {
|
|
426
753
|
description: "Session memory. pin/unpin (index): standing rules. set_plan (text = plan file). memorize (text): notes that survive context compaction. " +
|
|
427
|
-
"engram (path, symbol, text): note on a symbol. status/report: token use. reset: clear the circuit breaker. audit.",
|
|
754
|
+
"engram (path, symbol, text): note on a symbol. status/report: token use. reset: clear the circuit breaker. audit. Also: project_root.",
|
|
428
755
|
inputSchema: z.object({
|
|
429
756
|
action: z.enum(["pin", "unpin", "status", "report", "reset", "set_plan", "memorize", "audit", "engram"]),
|
|
430
757
|
text: z.string().optional(),
|
|
431
758
|
path: z.string().optional(),
|
|
432
759
|
symbol: z.string().optional(),
|
|
433
760
|
index: z.number().optional(),
|
|
761
|
+
project_root: z.string().optional(),
|
|
434
762
|
}).passthrough(),
|
|
435
763
|
}, async (args) => {
|
|
436
764
|
const a = args;
|
|
765
|
+
const activeDeps = await resolveWorkspaceDeps(a);
|
|
766
|
+
if (typeof activeDeps === "string")
|
|
767
|
+
return workspaceError(activeDeps);
|
|
437
768
|
const { action, text, index, path: guardPath, symbol } = args;
|
|
438
769
|
const params = { action, text, index, id: optStr(a.id), path: guardPath, symbol };
|
|
439
|
-
return wrapWithCircuitBreaker(circuitBreaker, "nreki_guard", action, () => handleGuard(action, params,
|
|
770
|
+
return wrapWithCircuitBreaker(activeDeps.circuitBreaker, "nreki_guard", action, () => handleGuard(action, params, activeDeps), undefined, undefined, activeDeps.chronos);
|
|
440
771
|
});
|
|
441
772
|
// ─── Server Startup ─────────────────────────────────────────────────
|
|
442
773
|
async function main() {
|
|
443
774
|
const transport = new StdioServerTransport();
|
|
444
|
-
let nativeEdits;
|
|
445
|
-
// Graceful shutdown 100% SÍNCRONO.
|
|
446
|
-
// Async en shutdown path = riesgo de zombie atascado en event loop.
|
|
447
|
-
// El verdadero GC es process.exit(0) — el SO mata in-flight
|
|
448
|
-
// requests instantáneo (post v11.0.0 amputación: ya sin ONNX).
|
|
449
775
|
let _shuttingDown = false;
|
|
450
776
|
const gracefulShutdown = () => {
|
|
451
777
|
if (_shuttingDown)
|
|
452
778
|
return;
|
|
453
779
|
_shuttingDown = true;
|
|
454
780
|
try {
|
|
455
|
-
|
|
456
|
-
chronos.syncTechDebt(kernel.getInitialErrorCount(), kernel.getCurrentErrorCount());
|
|
457
|
-
}
|
|
458
|
-
chronos.forcePersist(); // sync, ~2-5ms, dentro de ventana de gracia del SO
|
|
459
|
-
}
|
|
460
|
-
catch { /* never block shutdown on telemetry */ }
|
|
461
|
-
try {
|
|
462
|
-
nativeEdits?.close();
|
|
463
|
-
}
|
|
464
|
-
catch { /* already closed */ }
|
|
465
|
-
try {
|
|
466
|
-
engine.shutdown();
|
|
781
|
+
currentWorkspace?.shutdown();
|
|
467
782
|
}
|
|
468
783
|
catch { /* swallow */ }
|
|
469
784
|
process.exit(0);
|
|
470
785
|
};
|
|
471
786
|
process.on("SIGINT", gracefulShutdown);
|
|
472
787
|
process.on("SIGTERM", gracefulShutdown);
|
|
473
|
-
process.on("SIGHUP", gracefulShutdown);
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
788
|
+
process.on("SIGHUP", gracefulShutdown);
|
|
789
|
+
process.on("exit", () => { try {
|
|
790
|
+
currentWorkspace?.shutdown();
|
|
791
|
+
}
|
|
792
|
+
catch { /* swallow */ } });
|
|
477
793
|
process.stdin.on("close", gracefulShutdown);
|
|
478
794
|
process.stdin.on("end", gracefulShutdown);
|
|
479
795
|
// ─── Parent Process Watchdog ────────────────────────────────────
|
|
480
|
-
// Fallback final cuando los signals/events del SO fallan en
|
|
481
|
-
// X-close de Windows o SIGKILL abrupto del cliente MCP.
|
|
482
|
-
// Verificado empíricamente: process.stdin EOF y SIGHUP NO se
|
|
483
|
-
// disparan al cerrar consola PowerShell con X (PID 16696
|
|
484
|
-
// sobrevivió al test manual). Polling activo del ppid es el
|
|
485
|
-
// único mecanismo confiable cross-platform.
|
|
486
796
|
const initialPpid = process.ppid;
|
|
487
797
|
if (initialPpid && initialPpid !== 1) {
|
|
488
798
|
const PARENT_CHECK_MS = 3000;
|
|
@@ -492,134 +802,65 @@ async function main() {
|
|
|
492
802
|
return;
|
|
493
803
|
}
|
|
494
804
|
try {
|
|
495
|
-
// kill(0) verifica existencia sin enviar señal de terminación.
|
|
496
805
|
process.kill(initialPpid, 0);
|
|
497
806
|
}
|
|
498
807
|
catch (err) {
|
|
499
808
|
const code = err.code;
|
|
500
|
-
// EPERM/EACCES: padre VIVO pero SO/AV deniega inspección.
|
|
501
|
-
// NO disparar shutdown — falso positivo letal.
|
|
502
809
|
if (code === "EPERM" || code === "EACCES") {
|
|
503
810
|
return;
|
|
504
811
|
}
|
|
505
|
-
// ESRCH (No such process) o cualquier otro: padre muerto.
|
|
506
812
|
clearInterval(parentWatchdog);
|
|
507
813
|
gracefulShutdown();
|
|
508
814
|
}
|
|
509
815
|
}, PARENT_CHECK_MS);
|
|
510
|
-
// Vital: permite que el event loop termine si MCP cierra limpio.
|
|
511
|
-
// Sin unref(), el setInterval mantiene NREKI vivo eternamente
|
|
512
|
-
// bloqueando el shutdown ordenado del cliente.
|
|
513
816
|
parentWatchdog.unref();
|
|
514
817
|
}
|
|
515
|
-
//
|
|
516
|
-
//
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
if (!unsafeWriteTarget(cwd, sessionMarker)) {
|
|
523
|
-
const sessionsDir = path.dirname(sessionMarker);
|
|
524
|
-
if (fs.existsSync(sessionsDir)) {
|
|
525
|
-
for (const entry of fs.readdirSync(sessionsDir)) {
|
|
526
|
-
if (!/^\d+$/.test(entry))
|
|
527
|
-
continue;
|
|
528
|
-
const pid = Number(entry);
|
|
529
|
-
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid)
|
|
530
|
-
continue;
|
|
531
|
-
try {
|
|
532
|
-
process.kill(pid, 0);
|
|
533
|
-
}
|
|
534
|
-
catch (err) {
|
|
535
|
-
if (err.code === "ESRCH") {
|
|
536
|
-
const stale = path.join(sessionsDir, entry);
|
|
537
|
-
if (!unsafeWriteTarget(cwd, stale)) {
|
|
538
|
-
try {
|
|
539
|
-
fs.unlinkSync(stale);
|
|
540
|
-
}
|
|
541
|
-
catch { /* raced */ }
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
if (process.env.NREKI_NATIVE_PREFLIGHT === "1") {
|
|
548
|
-
try {
|
|
549
|
-
nativeEdits = await startNativeEditServer(cwd, request => validateNativeEdit(request, deps));
|
|
550
|
-
}
|
|
551
|
-
catch (ipcErr) {
|
|
552
|
-
logger.warn(`Native edit IPC server unavailable (falling back to session-only marker): ${ipcErr.message}`);
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
writeStateFile(cwd, sessionMarker, JSON.stringify({
|
|
557
|
-
startedAt: new Date().toISOString(), token: nativeEdits?.token,
|
|
558
|
-
}));
|
|
559
|
-
fs.chmodSync(sessionMarker, 0o600);
|
|
560
|
-
process.on("exit", () => {
|
|
561
|
-
try {
|
|
562
|
-
nativeEdits?.close();
|
|
563
|
-
}
|
|
564
|
-
catch { /* already closed */ }
|
|
565
|
-
try {
|
|
566
|
-
fs.unlinkSync(sessionMarker);
|
|
567
|
-
}
|
|
568
|
-
catch { /* already gone */ }
|
|
569
|
-
});
|
|
570
|
-
}
|
|
571
|
-
catch {
|
|
818
|
+
// The client's roots bound the workspace from now on (see workspaceTarget).
|
|
819
|
+
// A root that is the home folder, above it or hidden in it is not a project.
|
|
820
|
+
const syncClientRoots = async () => {
|
|
821
|
+
if (pinnedByEnv)
|
|
822
|
+
return;
|
|
823
|
+
if (!server.server.getClientCapabilities()?.roots)
|
|
824
|
+
return;
|
|
572
825
|
try {
|
|
573
|
-
|
|
826
|
+
const res = await server.server.listRoots({}, { timeout: 2500 });
|
|
827
|
+
clientRootDirs = pickRootsFromMcpRoots(res?.roots).filter((dir) => !isNonProjectLaunchDir(dir));
|
|
828
|
+
const current = currentWorkspace;
|
|
829
|
+
if (clientRootDirs.length === 0)
|
|
830
|
+
return;
|
|
831
|
+
if (current && clientRootDirs.some((r) => isSameOrInside(current.root, r)))
|
|
832
|
+
return;
|
|
833
|
+
await switchWorkspace(clientRootDirs[0], "roots");
|
|
574
834
|
}
|
|
575
|
-
catch {
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
//
|
|
580
|
-
//
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
try {
|
|
586
|
-
const upgrade = upgradeEnforcerHook(process.cwd(), () => fs.readFileSync(new URL("../templates/hooks/nreki-enforcer.mjs", import.meta.url), "utf-8"));
|
|
587
|
-
if (upgrade === "upgraded")
|
|
588
|
-
logger.info("Auto-patched legacy nreki-enforcer hook for security.");
|
|
589
|
-
if (upgrade === "unsafe-path")
|
|
590
|
-
logger.warn(".claude/hooks/nreki-enforcer.mjs is a symbolic link or leaves the project: not upgraded.");
|
|
591
|
-
}
|
|
592
|
-
catch { /* Fail silently, never block boot */ }
|
|
593
|
-
// Connect and serve
|
|
594
|
-
await server.connect(transport);
|
|
595
|
-
// v11.2.1: do NOT block server startup on the file watcher's initial
|
|
596
|
-
// scan. chokidar's ready event waits for the directory walk to settle,
|
|
597
|
-
// which on real projects with heavy non-ignored trees can take tens of
|
|
598
|
-
// seconds — during which the MCP transport is alive but the watcher
|
|
599
|
-
// CPU work prevents tool handlers from making forward progress, and
|
|
600
|
-
// Claude Code surfaces the silence as "connection closed: EOF". The
|
|
601
|
-
// watcher is for reactive re-indexing; tool handlers call
|
|
602
|
-
// engine.indexDirectory() directly on first use and do not depend on
|
|
603
|
-
// it being ready.
|
|
604
|
-
if (engine) {
|
|
605
|
-
const watcherReady = engine.startWatcher();
|
|
606
|
-
watcherReady.then(() => logger.info("File watcher started (reactive mode)."), (err) => logger.error(`File watcher failed (non-fatal): ${err.message}`));
|
|
607
|
-
}
|
|
608
|
-
// Engine initialization is lazy - each tool calls engine.initialize()
|
|
609
|
-
// (db + parser). v11.0.0: single init path post-embeddings amputation.
|
|
610
|
-
// This keeps the MCP handshake under 100ms.
|
|
611
|
-
// JIT Holography: pre-load WASM parser (~50ms) without scanning project
|
|
612
|
-
if (nrekiMode === "hologram" && kernel) {
|
|
613
|
-
setImmediate(async () => {
|
|
614
|
-
try {
|
|
615
|
-
await ensureHologramReady(kernel, nrekiMode, cwd);
|
|
616
|
-
logger.info("WASM parser pre-loaded. JIT Holography ready.");
|
|
617
|
-
}
|
|
618
|
-
catch (err) {
|
|
619
|
-
logger.warn(`WASM pre-load failed: ${err.message}`);
|
|
620
|
-
}
|
|
835
|
+
catch (err) {
|
|
836
|
+
logger.warn(`MCP roots/list unavailable: ${err.message}`);
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
// Tool calls wait for a roots sync in flight (resolveWorkspaceDeps), the first
|
|
840
|
+
// one and each roots/list_changed, instead of running in the old workspace.
|
|
841
|
+
const trackRootsSync = () => {
|
|
842
|
+
const p = syncClientRoots().finally(() => {
|
|
843
|
+
if (rootsSync === p)
|
|
844
|
+
rootsSync = null;
|
|
621
845
|
});
|
|
846
|
+
rootsSync = p;
|
|
847
|
+
return p;
|
|
848
|
+
};
|
|
849
|
+
server.server.oninitialized = () => {
|
|
850
|
+
if (!pinnedByEnv && server.server.getClientCapabilities()?.roots)
|
|
851
|
+
void trackRootsSync();
|
|
852
|
+
};
|
|
853
|
+
server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
|
|
854
|
+
await trackRootsSync();
|
|
855
|
+
});
|
|
856
|
+
liveTransportConnected = true;
|
|
857
|
+
if (currentWorkspace) {
|
|
858
|
+
await currentWorkspace.bootLive();
|
|
622
859
|
}
|
|
860
|
+
await server.connect(transport);
|
|
861
|
+
// v11.2.1: the file watcher starts only after the handshake (not awaited).
|
|
862
|
+
transportReady = true;
|
|
863
|
+
currentWorkspace?.startBackground();
|
|
623
864
|
}
|
|
624
865
|
// v11.2.1: defensive process-level handlers. The MCP transport speaks
|
|
625
866
|
// JSON-RPC over stdio, so any unhandled rejection or uncaught exception
|