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/src/index.ts CHANGED
@@ -17,6 +17,8 @@
17
17
  * All processing is local. Zero cloud dependencies.
18
18
  */
19
19
 
20
+ // First import: switches to NREKI_PROJECT_ROOT before any module reads process.cwd().
21
+ import "./bootstrap-root.js";
20
22
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
21
23
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
22
24
  import { z } from "zod";
@@ -88,18 +90,29 @@ NREKI v${VERSION} - Semantic validation MCP server for AI coding agents
88
90
 
89
91
  Usage:
90
92
  npx nreki Start MCP server (default)
91
- npx nreki init [options] Install per-agent instructions
92
- npx nreki deinit Safely remove NREKI hooks before uninstall
93
+ npx nreki init [options] Install NREKI in this project: instructions for
94
+ each agent + its MCP server registration
95
+ npx nreki deinit Safely remove NREKI hooks and MCP registrations
93
96
  npx nreki trust-db Review and restore quarantined engrams/notes/pins
94
97
  (interactive terminal only)
95
98
 
96
99
  \`init\` options:
97
- --agent <name> Force agent: claude | cursor | cline | copilot | generic
98
- (default: auto-detect via .claude/, .cursor/, .clinerules,
99
- .github/copilot-instructions.md; falls back to generic)
100
- --force Rewrite existing NREKI block (default: skip if marker present)
100
+ --agent <names> Agents to install for, comma-separated:
101
+ claude | codex | antigravity | cursor | cline | copilot | generic
102
+ (default: every agent configured in this project; without any,
103
+ every agent installed on this computer; else generic AGENTS.md)
104
+ --voyage Turn on Voyage semantic search in the registrations
105
+ (this project's code is sent to Voyage once to be indexed)
106
+ --no-voyage Turn it off again
107
+ --no-mcp Write the instructions only, do not register the MCP server
108
+ --force Rewrite existing NREKI blocks and replace a "nreki" MCP entry
109
+ NREKI did not write
101
110
  --dry-run Print plan only, no filesystem writes
102
111
 
112
+ Environment:
113
+ NREKI_PROJECT_ROOT Absolute path of the project folder, for MCP hosts that start
114
+ servers in another folder (set by \`init\` for Cursor and VS Code)
115
+
103
116
  Global flags:
104
117
  --help, -h Show this help message
105
118
  --version, -v Show version
@@ -142,8 +155,14 @@ if (args[0] === "deinit") {
142
155
  if (settings.hooks.PreToolUse.length === 0) delete settings.hooks.PreToolUse;
143
156
  if (settings.hooks && Object.keys(settings.hooks).length === 0) delete settings.hooks;
144
157
 
145
- fs.writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 2), "utf-8");
146
- logger.info("Removed NREKI hooks from .claude/settings.json");
158
+ if (Object.keys(settings).length === 0) {
159
+ // Only NREKI's hooks were in it (init creates it when absent).
160
+ fs.unlinkSync(claudeSettingsPath);
161
+ logger.info("Deleted .claude/settings.json (it only held NREKI's hooks)");
162
+ } else {
163
+ fs.writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 2), "utf-8");
164
+ logger.info("Removed NREKI hooks from .claude/settings.json");
165
+ }
147
166
  modified = true;
148
167
  }
149
168
  }
@@ -157,6 +176,8 @@ if (args[0] === "deinit") {
157
176
  if (fs.existsSync(hookPath) && touchable(hookPath)) {
158
177
  try {
159
178
  fs.unlinkSync(hookPath);
179
+ const { removeEmptyDirs } = await import("./init/mcp-register.js");
180
+ removeEmptyDirs(cwd, path.dirname(hookPath));
160
181
  logger.info("Deleted .claude/hooks/nreki-enforcer.mjs");
161
182
  modified = true;
162
183
  } catch (err) {
@@ -164,55 +185,21 @@ if (args[0] === "deinit") {
164
185
  }
165
186
  }
166
187
 
167
- // 3. Clean CLAUDE.md — strip only NREKI block, preserve user's own rules
168
- const claudeMdPath = path.join(cwd, "CLAUDE.md");
169
- if (fs.existsSync(claudeMdPath) && touchable(claudeMdPath)) {
170
- try {
171
- const content = fs.readFileSync(claudeMdPath, "utf-8").replace(/^\uFEFF/, "");
172
- const markerIndex = content.indexOf("# NREKI ACTIVE");
173
- if (markerIndex !== -1) {
174
- const cleanedContent = content.substring(0, markerIndex).trim();
175
- if (cleanedContent === "") {
176
- fs.unlinkSync(claudeMdPath);
177
- logger.info("Deleted empty CLAUDE.md");
178
- } else {
179
- fs.writeFileSync(claudeMdPath, cleanedContent + "\n", "utf-8");
180
- logger.info("Removed NREKI instructions from CLAUDE.md");
181
- }
182
- modified = true;
183
- }
184
- } catch (err) {
185
- logger.error(`Failed to clean CLAUDE.md: ${(err as Error).message}`);
186
- }
187
- }
188
-
189
- // 4. Clean AGENTS.md — strip only NREKI block, preserve user own rules
190
- const agentsMdPath = path.join(cwd, "AGENTS.md");
191
- if (fs.existsSync(agentsMdPath) && touchable(agentsMdPath)) {
192
- try {
193
- const content = fs.readFileSync(agentsMdPath, "utf-8").replace(/^\uFEFF/, "");
194
- const nrekiMarker = "# Instructions for AI coding agents consuming NREKI via MCP";
195
- const nrekiIdx = content.indexOf(nrekiMarker);
196
- if (nrekiIdx !== -1) {
197
- let stripFrom = nrekiIdx;
198
- const before = content.substring(0, nrekiIdx);
199
- const lastH1 = before.lastIndexOf("# AGENTS.md");
200
- if (lastH1 !== -1 && before.substring(lastH1).trim() === "# AGENTS.md") {
201
- stripFrom = lastH1;
202
- }
203
- const cleanedContent = content.substring(0, stripFrom).trim();
204
- if (cleanedContent === "") {
205
- fs.unlinkSync(agentsMdPath);
206
- logger.info("Deleted empty AGENTS.md");
207
- } else {
208
- fs.writeFileSync(agentsMdPath, cleanedContent + "\n", "utf-8");
209
- logger.info("Removed NREKI instructions from AGENTS.md");
210
- }
188
+ // 3-4. Instruction files `init` wrote: NREKI's block in CLAUDE.md, AGENTS.md and
189
+ // .github/copilot-instructions.md (the user's content is kept), and the
190
+ // files NREKI owns (Claude skill, Cursor rule, Cline rule).
191
+ try {
192
+ const { removeInstructions } = await import("./init/init-runner.js");
193
+ for (const action of removeInstructions(cwd)) {
194
+ if (action.op === "removed") {
195
+ logger.info(`${action.path}: ${action.note}`);
211
196
  modified = true;
197
+ } else {
198
+ logger.warn(`${action.path}: ${action.note}`);
212
199
  }
213
- } catch (err) {
214
- logger.error(`Failed to clean AGENTS.md: ${(err as Error).message}`);
215
200
  }
201
+ } catch (err) {
202
+ logger.error(`Failed to clean instruction files: ${(err as Error).message}`);
216
203
  }
217
204
 
218
205
  // 5. Clean SKILL.md — strip only NREKI block, preserve user own rules
@@ -257,6 +244,26 @@ if (args[0] === "deinit") {
257
244
  }
258
245
  }
259
246
 
247
+ // 7. Remove the MCP server entries `nreki init` wrote (only entries that launch
248
+ // the nreki package; a user's own "nreki" entry is left alone).
249
+ {
250
+ const { MCP_HOSTS, unregisterMcp } = await import("./init/mcp-register.js");
251
+ for (const host of MCP_HOSTS) {
252
+ try {
253
+ const removed = unregisterMcp(host, cwd);
254
+ if (!removed) continue;
255
+ if (removed.op === "removed") {
256
+ logger.info(`Removed NREKI MCP registration from ${removed.path} (${removed.note})`);
257
+ modified = true;
258
+ } else {
259
+ logger.warn(`${removed.path}: ${removed.note}`);
260
+ }
261
+ } catch (err) {
262
+ logger.error(`Failed to clean ${host} MCP registration: ${(err as Error).message}`);
263
+ }
264
+ }
265
+ }
266
+
260
267
  if (modified) {
261
268
  logger.info("NREKI deinit complete. Your environment is clean.");
262
269
  } else {
@@ -286,7 +293,8 @@ if (args[0] === "init") {
286
293
  if (parsed.error) {
287
294
  process.stderr.write(`nreki init: ${parsed.error}\n`);
288
295
  process.stderr.write(
289
- "\nUsage: nreki init [--agent <claude|cursor|cline|copilot|generic>] [--force] [--dry-run]\n",
296
+ "\nUsage: nreki init [--agent <claude,codex,antigravity,cursor,cline,copilot,generic>]" +
297
+ " [--voyage|--no-voyage] [--no-mcp] [--force] [--dry-run]\n",
290
298
  );
291
299
  process.exit(2);
292
300
  }
@@ -294,14 +302,18 @@ if (args[0] === "init") {
294
302
  try {
295
303
  const result = runInit(parsed.opts);
296
304
  process.stderr.write(`nreki init: ${result.reason}\n`);
297
- process.stderr.write(` agent: ${result.agent}${parsed.opts.dryRun ? " (dry-run)" : ""}\n`);
305
+ process.stderr.write(` agents: ${result.agents.join(", ")}${parsed.opts.dryRun ? " (dry-run)" : ""}\n`);
298
306
  for (const action of result.actions) {
299
307
  process.stderr.write(` ${formatAction(action)}\n`);
300
308
  }
309
+ if (result.notes.length > 0) {
310
+ process.stderr.write("\nNext:\n");
311
+ for (const note of result.notes) process.stderr.write(` - ${note}\n`);
312
+ }
301
313
  if (result.agent === "generic" && !parsed.opts.agent) {
302
314
  process.stderr.write(
303
- "\nNo agent-specific config detected. If you use Claude Code / Cursor / Cline / Copilot,\n" +
304
- "re-run with --agent <name> to install the agent-specific files.\n",
315
+ "\nNo agent detected in this project or on this computer. If you use Claude Code / Codex /\n" +
316
+ "Antigravity / Cursor / Cline / Copilot, re-run with --agent <name>.\n",
305
317
  );
306
318
  }
307
319
  process.exit(0);
@@ -1,72 +1,116 @@
1
- /**
2
- * init/agent-detect.ts — detect which AI coding agent a project uses
3
- * so `nreki init` can drop instructions in the format that agent reads.
4
- *
5
- * Detection is conservative: a positive signal (config dir or rules file
6
- * already present on disk) wins. When no signal is present we fall back
7
- * to "generic" (AGENTS.md) and the caller surfaces an honest disclosure
8
- * so the user can re-run with --agent <name> if the guess is wrong.
9
- */
10
-
11
- import fs from "fs";
12
- import path from "path";
13
-
14
- export type DetectedAgent =
15
- | "claude" // Anthropic Claude Code (.claude/, CLAUDE.md, hooks)
16
- | "cursor" // Cursor (.cursor/rules/*.mdc, legacy .cursorrules)
17
- | "cline" // Cline VS Code extension (.clinerules, .clinerules/)
18
- | "copilot" // GitHub Copilot (.github/copilot-instructions.md)
19
- | "generic"; // Fallback: AGENTS.md cross-agent convention
20
-
21
- export interface AgentDetectionResult {
22
- agent: DetectedAgent;
23
- reason: string;
24
- detected: DetectedAgent[];
25
- }
26
-
27
- const exists = (p: string): boolean => {
28
- try { return fs.existsSync(p); } catch { return false; }
29
- };
30
-
31
- /**
32
- * Detect which agent(s) a project is configured for by inspecting disk.
33
- * Returns the FIRST match in priority order and the full list of signals
34
- * found so the caller can report ambiguity to the user.
35
- */
36
- export function detectAgent(cwd: string = process.cwd()): AgentDetectionResult {
37
- const detected: DetectedAgent[] = [];
38
-
39
- if (exists(path.join(cwd, ".claude")) || exists(path.join(cwd, "CLAUDE.md"))) {
40
- detected.push("claude");
41
- }
42
- if (exists(path.join(cwd, ".cursor")) || exists(path.join(cwd, ".cursorrules"))) {
43
- detected.push("cursor");
44
- }
45
- if (exists(path.join(cwd, ".clinerules"))) {
46
- detected.push("cline");
47
- }
48
- if (exists(path.join(cwd, ".github", "copilot-instructions.md"))) {
49
- detected.push("copilot");
50
- }
51
-
52
- if (detected.length === 0) {
53
- return {
54
- agent: "generic",
55
- reason: "no agent-specific config found; writing AGENTS.md (cross-agent convention)",
56
- detected: [],
57
- };
58
- }
59
-
60
- // Priority order matches the listing above: claude > cursor > cline > copilot.
61
- const agent = detected[0];
62
- const reason = detected.length === 1
63
- ? `detected ${agent}`
64
- : `detected ${detected.join(", ")}; using ${agent} (pass --agent to override)`;
65
-
66
- return { agent, reason, detected };
67
- }
68
-
69
- /** True if `name` is one of the known agent ids. */
70
- export function isKnownAgent(name: string): name is DetectedAgent {
71
- return name === "claude" || name === "cursor" || name === "cline" || name === "copilot" || name === "generic";
72
- }
1
+ /**
2
+ * init/agent-detect.ts — detect which AI coding agents a project uses
3
+ * so `nreki init` can drop instructions in the format each agent reads
4
+ * and register NREKI as an MCP server for it.
5
+ *
6
+ * Detection is conservative: a positive signal (config dir or rules file
7
+ * already present on disk) wins, and every agent with a signal in the project
8
+ * is installed. Without any project signal, v12.3.0 installs for the agents
9
+ * found in the user's home folder (Claude Code, Codex, Antigravity, Cursor),
10
+ * so a fresh project needs one command. When neither exists we fall back to
11
+ * "generic" (AGENTS.md) and the caller surfaces an honest disclosure so the
12
+ * user can re-run with --agent <name> if the guess is wrong.
13
+ */
14
+
15
+ import fs from "fs";
16
+ import os from "os";
17
+ import path from "path";
18
+
19
+ export type DetectedAgent =
20
+ | "claude" // Anthropic Claude Code (.claude/, CLAUDE.md, hooks, .mcp.json)
21
+ | "codex" // OpenAI Codex (.codex/config.toml, AGENTS.md)
22
+ | "antigravity" // Google Antigravity (.agents/, GEMINI.md, AGENTS.md)
23
+ | "cursor" // Cursor (.cursor/rules/*.mdc, legacy .cursorrules, .cursor/mcp.json)
24
+ | "cline" // Cline VS Code extension (.clinerules, .clinerules/)
25
+ | "copilot" // GitHub Copilot (.github/copilot-instructions.md, .vscode/mcp.json)
26
+ | "generic"; // Fallback: AGENTS.md cross-agent convention
27
+
28
+ /** Every agent id, in detection priority order. */
29
+ export const KNOWN_AGENTS: readonly DetectedAgent[] =
30
+ ["claude", "codex", "antigravity", "cursor", "cline", "copilot", "generic"];
31
+
32
+ export interface AgentDetectionResult {
33
+ /** First agent of `agents` (kept for callers that handle a single agent). */
34
+ agent: DetectedAgent;
35
+ /** Every agent `nreki init` installs for. */
36
+ agents: DetectedAgent[];
37
+ reason: string;
38
+ /** Agents with a signal inside the project. */
39
+ detected: DetectedAgent[];
40
+ /** Agents found in the user's home folder (consulted only without project signals). */
41
+ installed: DetectedAgent[];
42
+ }
43
+
44
+ const exists = (p: string): boolean => {
45
+ try { return fs.existsSync(p); } catch { return false; }
46
+ };
47
+
48
+ /** Agents configured inside the project, in priority order. */
49
+ export function detectProjectAgents(cwd: string): DetectedAgent[] {
50
+ const found: DetectedAgent[] = [];
51
+ if (exists(path.join(cwd, ".claude")) || exists(path.join(cwd, "CLAUDE.md"))) found.push("claude");
52
+ if (exists(path.join(cwd, ".codex"))) found.push("codex");
53
+ if (
54
+ exists(path.join(cwd, ".agents", "mcp_config.json")) ||
55
+ exists(path.join(cwd, ".agents", "rules")) ||
56
+ exists(path.join(cwd, ".agent", "rules")) ||
57
+ exists(path.join(cwd, "GEMINI.md"))
58
+ ) found.push("antigravity");
59
+ if (exists(path.join(cwd, ".cursor")) || exists(path.join(cwd, ".cursorrules"))) found.push("cursor");
60
+ if (exists(path.join(cwd, ".clinerules"))) found.push("cline");
61
+ if (exists(path.join(cwd, ".github", "copilot-instructions.md"))) found.push("copilot");
62
+ return found;
63
+ }
64
+
65
+ /**
66
+ * Agents installed for this user, from their home-folder state. Only agents
67
+ * whose MCP registration NREKI can write into the project are listed.
68
+ */
69
+ export function detectInstalledAgents(home: string): DetectedAgent[] {
70
+ const found: DetectedAgent[] = [];
71
+ if (exists(path.join(home, ".claude")) || exists(path.join(home, ".claude.json"))) found.push("claude");
72
+ if (exists(path.join(home, ".codex"))) found.push("codex");
73
+ if (exists(path.join(home, ".gemini", "antigravity")) || exists(path.join(home, ".gemini", "antigravity-ide"))) {
74
+ found.push("antigravity");
75
+ }
76
+ if (exists(path.join(home, ".cursor"))) found.push("cursor");
77
+ return found;
78
+ }
79
+
80
+ /**
81
+ * Detect which agent(s) to install for: project signals first, then the
82
+ * agents installed for this user, then the generic AGENTS.md fallback.
83
+ */
84
+ export function detectAgent(cwd: string = process.cwd(), home: string = os.homedir()): AgentDetectionResult {
85
+ const detected = detectProjectAgents(cwd);
86
+ if (detected.length > 0) {
87
+ const reason = detected.length === 1
88
+ ? `detected ${detected[0]}`
89
+ : `detected ${detected.join(", ")}; installing for each (pass --agent to choose)`;
90
+ return { agent: detected[0], agents: detected, reason, detected, installed: [] };
91
+ }
92
+
93
+ const installed = detectInstalledAgents(home);
94
+ if (installed.length > 0) {
95
+ return {
96
+ agent: installed[0],
97
+ agents: installed,
98
+ reason: `no agent config in this project; installing for the agents found on this computer: ${installed.join(", ")} (pass --agent to choose)`,
99
+ detected,
100
+ installed,
101
+ };
102
+ }
103
+
104
+ return {
105
+ agent: "generic",
106
+ agents: ["generic"],
107
+ reason: "no agent-specific config found; writing AGENTS.md (cross-agent convention)",
108
+ detected,
109
+ installed,
110
+ };
111
+ }
112
+
113
+ /** True if `name` is one of the known agent ids. */
114
+ export function isKnownAgent(name: string): name is DetectedAgent {
115
+ return (KNOWN_AGENTS as readonly string[]).includes(name);
116
+ }