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.
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * init/init-runner.ts — orchestrates `nreki init` for the detected (or
3
- * explicitly chosen) AI coding agent.
3
+ * explicitly chosen) AI coding agents.
4
+ *
5
+ * v12.3.0: installs for every detected agent (project signals, else the agents
6
+ * found in the home folder) and registers NREKI as each agent's MCP server with
7
+ * the project folder pinned (see mcp-register.ts), so one command is enough.
4
8
  *
5
9
  * v11.3.0 replaces the pre-v11.3.0 "spray every template" behavior with
6
10
  * targeted per-agent installs. Templates and the Claude Code enforcer
@@ -16,10 +20,12 @@
16
20
  */
17
21
 
18
22
  import fs from "fs";
23
+ import os from "os";
19
24
  import path from "path";
20
25
  import { fileURLToPath } from "url";
21
26
  import type { DetectedAgent } from "./agent-detect.js";
22
- import { detectAgent, isKnownAgent } from "./agent-detect.js";
27
+ import { detectAgent, isKnownAgent, KNOWN_AGENTS } from "./agent-detect.js";
28
+ import { isMcpHost, launchCommand, registerMcp, removeEmptyDirs, type McpAction } from "./mcp-register.js";
23
29
  import { unsafeWriteTarget } from "../utils/path-jail.js";
24
30
 
25
31
  type WriteMode = "write" | "append" | "skip-if-marked";
@@ -46,18 +52,39 @@ export interface InitOptions {
46
52
  cwd?: string;
47
53
  /** Explicit agent override. Bypasses disk detection. */
48
54
  agent?: DetectedAgent;
55
+ /** Explicit agent list (`--agent codex,antigravity`). Bypasses disk detection. */
56
+ agents?: DetectedAgent[];
57
+ /** Home folder consulted for installed agents. Defaults to os.homedir(). */
58
+ home?: string;
49
59
  /** Overwrite existing NREKI block instead of skipping when marker present. */
50
60
  force?: boolean;
51
61
  /** Print plan and skip filesystem mutations. */
52
62
  dryRun?: boolean;
63
+ /** Register NREKI as an MCP server for each agent (default true; `--no-mcp` turns it off). */
64
+ mcp?: boolean;
65
+ /** `--voyage` sets NREKI_SEMANTIC=voyage in the registrations, `--no-voyage` removes it. */
66
+ voyage?: boolean;
67
+ /** Version pinned in the registrations. Defaults to this package's version. */
68
+ version?: string;
53
69
  }
54
70
 
55
71
  export interface InitResult {
72
+ /** First agent of `agents` (kept for callers that handle a single agent). */
56
73
  agent: DetectedAgent;
57
- /** Why this agent was chosen (detection reason or "--agent override"). */
74
+ /** Every agent installed for. */
75
+ agents: DetectedAgent[];
76
+ /** Why these agents were chosen (detection reason or "--agent override"). */
58
77
  reason: string;
59
78
  /** Per-file outcome. `op` describes what we did (or would do in dry-run). */
60
- actions: Array<{ path: string; op: "created" | "appended" | "rewritten" | "skipped" | "merged"; note?: string }>;
79
+ actions: Array<{ path: string; op: "created" | "appended" | "rewritten" | "skipped" | "merged" | "removed"; note?: string }>;
80
+ /** What the user still has to do in each agent. */
81
+ notes: string[];
82
+ }
83
+
84
+ /** Version of the installed package (dist/init → ../../package.json). */
85
+ export function packageVersion(): string {
86
+ const here = path.dirname(fileURLToPath(import.meta.url));
87
+ return (JSON.parse(fs.readFileSync(path.resolve(here, "..", "..", "package.json"), "utf-8")) as { version: string }).version;
61
88
  }
62
89
 
63
90
  /** Resolve templates/ shipped inside the installed package. */
@@ -145,6 +172,10 @@ function planForAgent(agent: DetectedAgent): FileAction[] {
145
172
  mode: "append",
146
173
  },
147
174
  ];
175
+ // Codex and Antigravity both read AGENTS.md at the project root (Antigravity
176
+ // loads it as an always-on rule, without frontmatter).
177
+ case "codex":
178
+ case "antigravity":
148
179
  case "generic":
149
180
  return [
150
181
  {
@@ -197,6 +228,63 @@ function replaceNrekiBlock(current: string, marker: string, block: string): stri
197
228
  return current.slice(0, start) + block + current.slice(end);
198
229
  }
199
230
 
231
+ /** User-owned files where `init` adds a block: `deinit` removes only that block. */
232
+ const USER_OWNED_TARGETS: Array<{ rel: string; markers: string[] }> = [
233
+ { rel: "CLAUDE.md", markers: ["# NREKI ACTIVE"] },
234
+ // The second marker is the header of the pre-v12.1 AGENTS.md template.
235
+ { rel: "AGENTS.md", markers: ["NREKI MCP instructions", "# Instructions for AI coding agents consuming NREKI via MCP"] },
236
+ { rel: path.join(".github", "copilot-instructions.md"), markers: ["NREKI MCP instructions"] },
237
+ ];
238
+
239
+ /** Files `init` owns outright: `deinit` deletes them when they still carry NREKI's marker. */
240
+ const NREKI_OWNED_TARGETS: Array<{ rel: string; marker: string }> = [
241
+ { rel: path.join(".claude", "skills", "nreki-optimizer", "SKILL.md"), marker: "name: nreki-optimizer" },
242
+ { rel: path.join(".cursor", "rules", "nreki.mdc"), marker: "# NREKI ACTIVE" },
243
+ { rel: path.join(".clinerules", "nreki.md"), marker: "# NREKI ACTIVE" },
244
+ ];
245
+
246
+ /**
247
+ * Undo the instruction files `init` wrote. Before v12.3.0 `deinit` cut
248
+ * CLAUDE.md from "# NREKI ACTIVE" to the end of the file (dropping the user's
249
+ * text after the block and leaving the begin sentinel), never matched the
250
+ * current AGENTS.md header, and left the Claude skill behind.
251
+ */
252
+ export function removeInstructions(cwd: string, dryRun = false): InitResult["actions"] {
253
+ const actions: InitResult["actions"] = [];
254
+ for (const target of USER_OWNED_TARGETS) {
255
+ const abs = path.join(cwd, target.rel);
256
+ if (!fs.existsSync(abs)) continue;
257
+ const unsafe = unsafeWriteTarget(cwd, target.rel);
258
+ if (unsafe) { actions.push({ path: target.rel, op: "skipped", note: `${unsafe}: not touched` }); continue; }
259
+ const current = fs.readFileSync(abs, "utf-8").replace(/^/, "");
260
+ let stripped: string | null = null;
261
+ for (const marker of target.markers) {
262
+ stripped = replaceNrekiBlock(current, marker, "");
263
+ if (stripped !== null) break;
264
+ }
265
+ if (stripped === null) continue;
266
+ const rest = stripped.replace(/\s+$/, "");
267
+ if (!dryRun) {
268
+ if (rest === "") fs.unlinkSync(abs);
269
+ else fs.writeFileSync(abs, rest + (current.includes("\r\n") ? "\r\n" : "\n"), "utf-8");
270
+ }
271
+ actions.push({ path: target.rel, op: "removed", note: rest === "" ? "file deleted (it only held NREKI's block)" : "NREKI block removed; your content kept" });
272
+ }
273
+ for (const target of NREKI_OWNED_TARGETS) {
274
+ const abs = path.join(cwd, target.rel);
275
+ if (!fs.existsSync(abs)) continue;
276
+ const unsafe = unsafeWriteTarget(cwd, target.rel);
277
+ if (unsafe) { actions.push({ path: target.rel, op: "skipped", note: `${unsafe}: not touched` }); continue; }
278
+ if (!fs.readFileSync(abs, "utf-8").includes(target.marker)) continue;
279
+ if (!dryRun) {
280
+ fs.unlinkSync(abs);
281
+ removeEmptyDirs(cwd, path.dirname(abs));
282
+ }
283
+ actions.push({ path: target.rel, op: "removed", note: "file deleted" });
284
+ }
285
+ return actions;
286
+ }
287
+
200
288
  function applyFileAction(
201
289
  cwd: string,
202
290
  action: FileAction,
@@ -330,31 +418,76 @@ function mergeClaudeSettings(cwd: string, dryRun: boolean): InitResult["actions"
330
418
  * mkdtemp + assert on the returned plan.
331
419
  */
332
420
  export function runInit(opts: InitOptions = {}): InitResult {
333
- const cwd = opts.cwd ?? process.cwd();
421
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
422
+ const force = opts.force === true;
423
+ const dryRun = opts.dryRun === true;
334
424
 
335
- let agent: DetectedAgent;
425
+ let agents: DetectedAgent[];
336
426
  let reason: string;
337
- if (opts.agent) {
338
- agent = opts.agent;
427
+ const explicit = [...(opts.agents ?? []), ...(opts.agent ? [opts.agent] : [])];
428
+ if (explicit.length > 0) {
429
+ agents = KNOWN_AGENTS.filter((a) => explicit.includes(a));
339
430
  reason = "--agent override";
340
431
  } else {
341
- const detection = detectAgent(cwd);
342
- agent = detection.agent;
432
+ const detection = detectAgent(cwd, opts.home ?? os.homedir());
433
+ agents = detection.agents;
343
434
  reason = detection.reason;
344
435
  }
345
436
 
346
437
  const actions: InitResult["actions"] = [];
347
- const plan = planForAgent(agent);
348
- for (const action of plan) {
349
- actions.push(applyFileAction(cwd, action, opts.force === true, opts.dryRun === true));
438
+ // Codex, Antigravity and generic share AGENTS.md: write each target once.
439
+ const planned = new Set<string>();
440
+ for (const agent of agents) {
441
+ for (const action of planForAgent(agent)) {
442
+ if (planned.has(action.targetRel)) continue;
443
+ planned.add(action.targetRel);
444
+ actions.push(applyFileAction(cwd, action, force, dryRun));
445
+ }
446
+ if (agent === "claude") actions.push(mergeClaudeSettings(cwd, dryRun));
350
447
  }
351
- if (agent === "claude") {
352
- actions.push(mergeClaudeSettings(cwd, opts.dryRun === true));
448
+
449
+ const notes: string[] = [];
450
+ const version = opts.version ?? packageVersion();
451
+ if (opts.mcp !== false) {
452
+ for (const agent of agents) {
453
+ if (!isMcpHost(agent)) continue;
454
+ const result: McpAction = registerMcp(agent, { cwd, version, voyage: opts.voyage, force, dryRun });
455
+ actions.push(result);
456
+ if (result.op !== "skipped" || /already registered/.test(result.note ?? "")) notes.push(NEXT_STEP[agent]);
457
+ }
458
+ const manual = agents.filter((a) => !isMcpHost(a));
459
+ if (manual.length > 0) {
460
+ const { command, args } = launchCommand(version);
461
+ notes.push(
462
+ `${manual.join(", ")}: register the MCP server by hand — command "${command}", args ${JSON.stringify(args)}, ` +
463
+ `started in this folder (or set NREKI_PROJECT_ROOT=${cwd}).`,
464
+ );
465
+ }
466
+ const machineSpecific = [
467
+ ...(agents.includes("codex") ? [".codex/config.toml"] : []),
468
+ ...(agents.includes("cursor") ? [".cursor/mcp.json"] : []),
469
+ ];
470
+ if (machineSpecific.length > 0) {
471
+ notes.push(`${machineSpecific.join(" and ")} hold${machineSpecific.length === 1 ? "s" : ""} this computer's path to the project: keep ${machineSpecific.length === 1 ? "it" : "them"} out of git.`);
472
+ }
473
+ const hasKey = Boolean(process.env.NREKI_VOYAGE_API_KEY || process.env.VOYAGE_API_KEY);
474
+ if (opts.voyage === undefined && hasKey) {
475
+ notes.push("A Voyage key is set: add --voyage to turn on semantic search for this project (its code is sent to Voyage once to be indexed).");
476
+ }
353
477
  }
354
478
 
355
- return { agent, reason, actions };
479
+ return { agent: agents[0], agents, reason, actions, notes };
356
480
  }
357
481
 
482
+ /** What the user still has to do after the registration, per host. */
483
+ const NEXT_STEP: Record<"claude" | "codex" | "antigravity" | "cursor" | "copilot", string> = {
484
+ claude: "Claude Code: start it in this folder and approve the project server \"nreki\" when asked (.mcp.json).",
485
+ codex: "Codex: restart Codex and open this folder as a trusted project; Codex ignores .codex/config.toml in untrusted projects.",
486
+ antigravity: "Antigravity: open \"Manage MCP servers\" and press Refresh (the server is in .agents/mcp_config.json).",
487
+ cursor: "Cursor: restart Cursor and enable \"nreki\" in its MCP settings if it is off (.cursor/mcp.json).",
488
+ copilot: "VS Code: open .vscode/mcp.json and start the \"nreki\" server for Copilot agent mode.",
489
+ };
490
+
358
491
  /**
359
492
  * Parse argv-style flags accepted by `nreki init`. Returns a usable
360
493
  * InitOptions plus an error string for invalid input so the CLI can
@@ -362,25 +495,31 @@ export function runInit(opts: InitOptions = {}): InitResult {
362
495
  */
363
496
  export function parseInitArgs(argv: string[]): { opts: InitOptions; error?: string } {
364
497
  const opts: InitOptions = {};
498
+ const addAgents = (value: string | undefined): string | undefined => {
499
+ if (!value) return "--agent requires a value";
500
+ for (const name of value.split(",").map((s) => s.trim()).filter(Boolean)) {
501
+ if (!isKnownAgent(name)) return `unknown agent "${name}"; valid: ${KNOWN_AGENTS.join(", ")}`;
502
+ opts.agents = [...(opts.agents ?? []), name];
503
+ }
504
+ if (!opts.agents || opts.agents.length === 0) return "--agent requires a value";
505
+ opts.agent = opts.agents[0];
506
+ return undefined;
507
+ };
365
508
  for (let i = 0; i < argv.length; i++) {
366
509
  const a = argv[i];
367
510
  if (a === "--force") { opts.force = true; continue; }
368
511
  if (a === "--dry-run") { opts.dryRun = true; continue; }
512
+ if (a === "--no-mcp") { opts.mcp = false; continue; }
513
+ if (a === "--voyage") { opts.voyage = true; continue; }
514
+ if (a === "--no-voyage") { opts.voyage = false; continue; }
369
515
  if (a === "--agent") {
370
- const v = argv[++i];
371
- if (!v) return { opts, error: "--agent requires a value" };
372
- if (!isKnownAgent(v)) {
373
- return { opts, error: `unknown agent "${v}"; valid: claude, cursor, cline, copilot, generic` };
374
- }
375
- opts.agent = v;
516
+ const error = addAgents(argv[++i]);
517
+ if (error) return { opts, error };
376
518
  continue;
377
519
  }
378
520
  if (a.startsWith("--agent=")) {
379
- const v = a.slice("--agent=".length);
380
- if (!isKnownAgent(v)) {
381
- return { opts, error: `unknown agent "${v}"; valid: claude, cursor, cline, copilot, generic` };
382
- }
383
- opts.agent = v;
521
+ const error = addAgents(a.slice("--agent=".length));
522
+ if (error) return { opts, error };
384
523
  continue;
385
524
  }
386
525
  return { opts, error: `unknown flag: ${a}` };
@@ -396,6 +535,7 @@ export function formatAction(a: InitResult["actions"][number]): string {
396
535
  rewritten: "[write] ",
397
536
  merged: "[merge] ",
398
537
  skipped: "[skip] ",
538
+ removed: "[remove]",
399
539
  } as const)[a.op];
400
540
  return `${tag} ${a.path}${a.note ? ` — ${a.note}` : ""}`;
401
541
  }