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.
@@ -0,0 +1,474 @@
1
+ /**
2
+ * init/mcp-register.ts — register NREKI as an MCP server in the project
3
+ * config each agent reads, with the project folder pinned.
4
+ *
5
+ * NREKI indexes the folder it starts in. Where each host starts a project
6
+ * server (measured or documented on 2026-11-26):
7
+ * - Claude Code (.mcp.json): in the project.
8
+ * - Antigravity (.agents/mcp_config.json): in the project (measured; a
9
+ * global plugin's server starts in the plugin folder instead).
10
+ * - Codex (.codex/config.toml): documented `cwd` field, set here. Codex reads
11
+ * this file only for trusted projects.
12
+ * - Cursor (.cursor/mcp.json) and VS Code (.vscode/mcp.json): undocumented, so
13
+ * the entry passes NREKI_PROJECT_ROOT (see project-root.ts).
14
+ *
15
+ * Every entry pins `nreki@<version>`, the version that wrote the instructions.
16
+ * An entry NREKI wrote (its args launch `nreki` or `nreki@x`) is updated in
17
+ * place, keeping fields the user added; an entry named `nreki` that NREKI did
18
+ * not write is left alone unless --force. Never writes through a link.
19
+ */
20
+
21
+ import fs from "fs";
22
+ import path from "path";
23
+ import { unsafeWriteTarget } from "../utils/path-jail.js";
24
+
25
+ export type McpHost = "claude" | "codex" | "antigravity" | "cursor" | "copilot";
26
+
27
+ export const MCP_HOSTS: readonly McpHost[] = ["claude", "codex", "antigravity", "cursor", "copilot"];
28
+
29
+ /** Project-relative config file each host reads. */
30
+ export const MCP_CONFIG_PATH: Record<McpHost, string> = {
31
+ claude: ".mcp.json",
32
+ codex: path.join(".codex", "config.toml"),
33
+ antigravity: path.join(".agents", "mcp_config.json"),
34
+ cursor: path.join(".cursor", "mcp.json"),
35
+ copilot: path.join(".vscode", "mcp.json"),
36
+ };
37
+
38
+ export interface McpRegisterOptions {
39
+ /** Project root (absolute). */
40
+ cwd: string;
41
+ /** NREKI version pinned in the launch command. */
42
+ version: string;
43
+ /** true: set NREKI_SEMANTIC=voyage; false: remove it; undefined: keep what is there. */
44
+ voyage?: boolean;
45
+ /** Replace an entry named `nreki` that NREKI did not write. */
46
+ force?: boolean;
47
+ dryRun?: boolean;
48
+ platform?: NodeJS.Platform;
49
+ }
50
+
51
+ export interface McpAction {
52
+ path: string;
53
+ op: "created" | "merged" | "rewritten" | "skipped" | "removed";
54
+ note?: string;
55
+ }
56
+
57
+ /** How a host launches NREKI. On Windows npx is a .cmd shim, so it goes through cmd /c. */
58
+ export function launchCommand(version: string, platform: NodeJS.Platform = process.platform): { command: string; args: string[] } {
59
+ const spec = `nreki@${version}`;
60
+ return platform === "win32"
61
+ ? { command: "cmd", args: ["/c", "npx", "-y", spec] }
62
+ : { command: "npx", args: ["-y", spec] };
63
+ }
64
+
65
+ const NREKI_SPEC = /^nreki(@\S+)?$/;
66
+
67
+ /** True when a JSON entry's args launch the published nreki package. */
68
+ function launchesNreki(entry: unknown): boolean {
69
+ if (!entry || typeof entry !== "object") return false;
70
+ const args = (entry as { args?: unknown }).args;
71
+ return Array.isArray(args) && args.some((a) => typeof a === "string" && NREKI_SPEC.test(a));
72
+ }
73
+
74
+ /** JSON with sorted keys, for "is this already what we would write" checks. */
75
+ function canonical(value: unknown): string {
76
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
77
+ if (value && typeof value === "object") {
78
+ const obj = value as Record<string, unknown>;
79
+ return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${canonical(obj[k])}`).join(",")}}`;
80
+ }
81
+ return JSON.stringify(value);
82
+ }
83
+
84
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
85
+ return !!v && typeof v === "object" && !Array.isArray(v);
86
+ }
87
+
88
+ function ensureDir(dir: string): void {
89
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
90
+ }
91
+
92
+ /**
93
+ * Remove `dir` and its parents while they are empty, stopping at the project
94
+ * root (never removed) and at the first folder that still holds something.
95
+ */
96
+ export function removeEmptyDirs(cwd: string, dir: string): void {
97
+ const root = path.resolve(cwd);
98
+ let current = path.resolve(dir);
99
+ while (current !== root && current.startsWith(root + path.sep)) {
100
+ try {
101
+ if (fs.lstatSync(current).isSymbolicLink() || fs.readdirSync(current).length > 0) return;
102
+ fs.rmdirSync(current);
103
+ } catch {
104
+ return;
105
+ }
106
+ current = path.dirname(current);
107
+ }
108
+ }
109
+
110
+ function writeText(abs: string, text: string): void {
111
+ ensureDir(path.dirname(abs));
112
+ fs.writeFileSync(abs, text, "utf-8");
113
+ }
114
+
115
+ // ─── JSON hosts (claude, antigravity, cursor, copilot) ─────────────────────
116
+
117
+ type JsonHost = Exclude<McpHost, "codex">;
118
+
119
+ function rootKeyOf(host: JsonHost): "mcpServers" | "servers" {
120
+ return host === "copilot" ? "servers" : "mcpServers";
121
+ }
122
+
123
+ /** The entry NREKI writes for a JSON host, before merging with an existing one. */
124
+ function freshJsonEntry(host: JsonHost, opts: McpRegisterOptions): Record<string, unknown> {
125
+ const { command, args } = launchCommand(opts.version, opts.platform);
126
+ const entry: Record<string, unknown> = host === "claude" || host === "copilot"
127
+ ? { type: "stdio", command, args }
128
+ : { command, args };
129
+ const env: Record<string, string> = {};
130
+ if (host === "cursor") env.NREKI_PROJECT_ROOT = path.resolve(opts.cwd);
131
+ if (host === "copilot") env.NREKI_PROJECT_ROOT = "${workspaceFolder}";
132
+ if (opts.voyage === true) env.NREKI_SEMANTIC = "voyage";
133
+ if (Object.keys(env).length > 0) entry.env = env;
134
+ return entry;
135
+ }
136
+
137
+ /** Overlay NREKI's fields on an entry it wrote before, keeping the user's additions. */
138
+ function mergeJsonEntry(existing: Record<string, unknown>, fresh: Record<string, unknown>, voyage: boolean | undefined): Record<string, unknown> {
139
+ const merged: Record<string, unknown> = { ...existing, ...fresh };
140
+ const env: Record<string, unknown> = {
141
+ ...(isPlainObject(existing.env) ? existing.env : {}),
142
+ ...(isPlainObject(fresh.env) ? fresh.env : {}),
143
+ };
144
+ if (voyage === false) delete env.NREKI_SEMANTIC;
145
+ if (Object.keys(env).length > 0) merged.env = env;
146
+ else delete merged.env;
147
+ return merged;
148
+ }
149
+
150
+ function readJson(abs: string): { text: string; doc: Record<string, unknown> } | { text: string; error: string } {
151
+ const text = fs.readFileSync(abs, "utf-8");
152
+ try {
153
+ const parsed = JSON.parse(text.replace(/^/, "")) as unknown;
154
+ if (!isPlainObject(parsed)) return { text, error: "is not a JSON object" };
155
+ return { text, doc: parsed };
156
+ } catch {
157
+ return { text, error: "is not valid JSON (comments are not supported)" };
158
+ }
159
+ }
160
+
161
+ function serializeJson(doc: unknown, previous: string | null): string {
162
+ const eol = previous !== null && previous.includes("\r\n") ? "\r\n" : "\n";
163
+ return JSON.stringify(doc, null, 2).replace(/\n/g, eol) + eol;
164
+ }
165
+
166
+ function registerJson(host: JsonHost, opts: McpRegisterOptions): McpAction {
167
+ const rel = MCP_CONFIG_PATH[host];
168
+ const abs = path.join(opts.cwd, rel);
169
+ const unsafe = unsafeWriteTarget(opts.cwd, rel);
170
+ if (unsafe) return { path: rel, op: "skipped", note: `${unsafe}: not touched` };
171
+
172
+ const rootKey = rootKeyOf(host);
173
+ const fresh = freshJsonEntry(host, opts);
174
+ let previous: string | null = null;
175
+ let doc: Record<string, unknown> = {};
176
+ if (fs.existsSync(abs)) {
177
+ const read = readJson(abs);
178
+ if ("error" in read) {
179
+ return {
180
+ path: rel,
181
+ op: "skipped",
182
+ note: `${read.error}; add this by hand: ${JSON.stringify({ [rootKey]: { nreki: fresh } })}`,
183
+ };
184
+ }
185
+ previous = read.text;
186
+ doc = read.doc;
187
+ }
188
+
189
+ const servers = doc[rootKey];
190
+ if (servers !== undefined && !isPlainObject(servers)) {
191
+ return { path: rel, op: "skipped", note: `"${rootKey}" is not an object; not touched` };
192
+ }
193
+ const existing = isPlainObject(servers) ? servers.nreki : undefined;
194
+
195
+ let next: Record<string, unknown>;
196
+ let op: McpAction["op"];
197
+ if (existing !== undefined) {
198
+ const ours = isPlainObject(existing) && launchesNreki(existing);
199
+ if (!ours && !opts.force) {
200
+ return { path: rel, op: "skipped", note: "a \"nreki\" entry NREKI did not write is present (use --force to replace it)" };
201
+ }
202
+ next = ours ? mergeJsonEntry(existing as Record<string, unknown>, fresh, opts.voyage) : fresh;
203
+ if (canonical(existing) === canonical(next)) {
204
+ return { path: rel, op: "skipped", note: `already registered (nreki@${opts.version})` };
205
+ }
206
+ op = "rewritten";
207
+ } else {
208
+ next = fresh;
209
+ op = previous === null ? "created" : "merged";
210
+ }
211
+
212
+ if (!opts.dryRun) {
213
+ const out = { ...doc, [rootKey]: { ...(isPlainObject(servers) ? servers : {}), nreki: next } };
214
+ writeText(abs, serializeJson(out, previous));
215
+ }
216
+ return { path: rel, op, note: op === "rewritten" ? `updated to nreki@${opts.version}` : undefined };
217
+ }
218
+
219
+ function unregisterJson(host: JsonHost, cwd: string, dryRun: boolean): McpAction | null {
220
+ const rel = MCP_CONFIG_PATH[host];
221
+ const abs = path.join(cwd, rel);
222
+ if (!fs.existsSync(abs)) return null;
223
+ const unsafe = unsafeWriteTarget(cwd, rel);
224
+ if (unsafe) return { path: rel, op: "skipped", note: `${unsafe}: not touched` };
225
+ const read = readJson(abs);
226
+ if ("error" in read) return null;
227
+ const rootKey = rootKeyOf(host);
228
+ const servers = read.doc[rootKey];
229
+ if (!isPlainObject(servers) || !launchesNreki(servers.nreki)) return null;
230
+
231
+ const rest = { ...servers };
232
+ delete rest.nreki;
233
+ const doc = { ...read.doc, [rootKey]: rest };
234
+ // The file only held NREKI's entry: it was written by `nreki init`, remove it.
235
+ const onlyOurs = Object.keys(rest).length === 0 && Object.keys(read.doc).length === 1;
236
+ if (!dryRun) {
237
+ if (onlyOurs) {
238
+ fs.unlinkSync(abs);
239
+ removeEmptyDirs(cwd, path.dirname(abs));
240
+ } else {
241
+ fs.writeFileSync(abs, serializeJson(doc, read.text), "utf-8");
242
+ }
243
+ }
244
+ return { path: rel, op: "removed", note: onlyOurs ? "file deleted (it only held nreki)" : "nreki entry removed" };
245
+ }
246
+
247
+ // ─── TOML host (codex) ─────────────────────────────────────────────────────
248
+
249
+ const CODEX_MARKER = "# nreki: added by `nreki init`";
250
+ const CODEX_MANAGED = new Set(["command", "args", "cwd", "startup_timeout_sec", "tool_timeout_sec", "env_vars"]);
251
+ const TABLE_HEADER = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
252
+
253
+ /** TOML basic string: JSON string escapes are valid TOML. */
254
+ function tomlString(s: string): string {
255
+ return JSON.stringify(s);
256
+ }
257
+
258
+ /** Normalized table name, or null when the line is not a table header. */
259
+ function tableName(line: string): string | null {
260
+ const m = TABLE_HEADER.exec(line);
261
+ if (!m) return null;
262
+ return m[1].replace(/\s+/g, "").replace(/(^|\.)(["'])([^"']*)\2(?=\.|$)/g, "$1$3");
263
+ }
264
+
265
+ function isNrekiTable(name: string): boolean {
266
+ return name === "mcp_servers.nreki" || name.startsWith("mcp_servers.nreki.");
267
+ }
268
+
269
+ /** Net bracket depth of a TOML line, ignoring brackets inside strings and comments. */
270
+ function bracketDelta(line: string): number {
271
+ const code = line.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, "").replace(/#.*$/, "");
272
+ let d = 0;
273
+ for (const ch of code) {
274
+ if (ch === "[" || ch === "{") d++;
275
+ else if (ch === "]" || ch === "}") d--;
276
+ }
277
+ return d;
278
+ }
279
+
280
+ interface ParsedEntries { entries: Array<{ key: string; lines: string[] }>; }
281
+
282
+ /** Split a table body into key = value entries (values may span lines). */
283
+ function parseEntries(body: string[]): ParsedEntries {
284
+ const entries: ParsedEntries["entries"] = [];
285
+ let depth = 0;
286
+ for (const line of body) {
287
+ if (depth > 0) {
288
+ entries[entries.length - 1].lines.push(line);
289
+ depth += bracketDelta(line);
290
+ continue;
291
+ }
292
+ const m = /^\s*("[^"]*"|'[^']*'|[A-Za-z0-9_-]+)\s*=/.exec(line);
293
+ if (!m) {
294
+ if (line.trim()) entries.push({ key: "", lines: [line] }); // comment: kept as is
295
+ continue;
296
+ }
297
+ entries.push({ key: m[1].replace(/^["']|["']$/g, ""), lines: [line] });
298
+ depth = bracketDelta(line);
299
+ }
300
+ return { entries };
301
+ }
302
+
303
+ interface CodexScan {
304
+ lines: string[];
305
+ eol: string;
306
+ /** Index range of every nreki table (header included), plus our marker line. */
307
+ ranges: Array<{ start: number; end: number; name: string }>;
308
+ /** nreki defined as a dotted key or inline table: not editable here. */
309
+ foreign: boolean;
310
+ }
311
+
312
+ function scanCodex(text: string): CodexScan {
313
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
314
+ const lines = text.split(/\r?\n/);
315
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
316
+ const ranges: CodexScan["ranges"] = [];
317
+ let foreign = false;
318
+ let current: string | null = "";
319
+ for (let i = 0; i < lines.length; i++) {
320
+ const name = tableName(lines[i]);
321
+ if (name !== null) {
322
+ current = name;
323
+ if (isNrekiTable(name)) {
324
+ let start = i;
325
+ if (ranges.length === 0 && i > 0 && lines[i - 1].startsWith(CODEX_MARKER)) start = i - 1;
326
+ let end = i + 1;
327
+ while (end < lines.length && tableName(lines[end]) === null) end++;
328
+ ranges.push({ start, end, name });
329
+ i = end - 1;
330
+ }
331
+ continue;
332
+ }
333
+ const keyLine = lines[i].trim();
334
+ if (current === "" && /^mcp_servers\s*\.\s*["']?nreki["']?\s*[.=]/.test(keyLine)) foreign = true;
335
+ if (current === "mcp_servers" && /^["']?nreki["']?\s*[.=]/.test(keyLine)) foreign = true;
336
+ }
337
+ return { lines, eol, ranges, foreign };
338
+ }
339
+
340
+ function codexSection(opts: McpRegisterOptions, keptMain: string[], envLines: string[], subtables: string[][]): string[] {
341
+ const { command, args } = launchCommand(opts.version, opts.platform);
342
+ const out = [
343
+ `${CODEX_MARKER}. cwd pins the project NREKI indexes; Codex reads this file only for trusted projects.`,
344
+ "[mcp_servers.nreki]",
345
+ `command = ${tomlString(command)}`,
346
+ `args = [${args.map(tomlString).join(", ")}]`,
347
+ `cwd = ${tomlString(path.resolve(opts.cwd))}`,
348
+ "startup_timeout_sec = 120",
349
+ "tool_timeout_sec = 120",
350
+ `env_vars = ["NREKI_VOYAGE_API_KEY", "VOYAGE_API_KEY"]`,
351
+ ...keptMain,
352
+ ];
353
+ if (envLines.length > 0) out.push("", "[mcp_servers.nreki.env]", ...envLines);
354
+ for (const table of subtables) out.push("", ...table);
355
+ return out;
356
+ }
357
+
358
+ function registerCodex(opts: McpRegisterOptions): McpAction {
359
+ const rel = MCP_CONFIG_PATH.codex;
360
+ const abs = path.join(opts.cwd, rel);
361
+ const unsafe = unsafeWriteTarget(opts.cwd, rel);
362
+ if (unsafe) return { path: rel, op: "skipped", note: `${unsafe}: not touched` };
363
+
364
+ const previous = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8").replace(/^/, "") : null;
365
+ const scan = scanCodex(previous ?? "");
366
+ if (scan.foreign) {
367
+ return { path: rel, op: "skipped", note: "nreki is defined as an inline table or dotted key; edit it by hand" };
368
+ }
369
+
370
+ const keptMain: string[] = [];
371
+ const envLines: string[] = [];
372
+ const subtables: string[][] = [];
373
+ if (scan.ranges.length > 0) {
374
+ const sectionText = scan.ranges.map((r) => scan.lines.slice(r.start, r.end).join("\n")).join("\n");
375
+ const ours = /["']nreki(@[^"'\s]*)?["']/.test(sectionText);
376
+ if (!ours && !opts.force) {
377
+ return { path: rel, op: "skipped", note: "a [mcp_servers.nreki] table NREKI did not write is present (use --force to replace it)" };
378
+ }
379
+ if (ours) {
380
+ for (const r of scan.ranges) {
381
+ const headerAt = scan.lines.slice(r.start, r.end).findIndex((l) => tableName(l) !== null) + r.start;
382
+ const body = scan.lines.slice(headerAt + 1, r.end).filter((l, idx, arr) => !(l.trim() === "" && idx === arr.length - 1));
383
+ if (r.name === "mcp_servers.nreki") {
384
+ for (const e of parseEntries(body).entries) {
385
+ if (e.key && CODEX_MANAGED.has(e.key)) continue;
386
+ keptMain.push(...e.lines);
387
+ }
388
+ } else if (r.name === "mcp_servers.nreki.env") {
389
+ for (const e of parseEntries(body).entries) {
390
+ if (e.key === "NREKI_SEMANTIC" && opts.voyage !== undefined) continue;
391
+ envLines.push(...e.lines);
392
+ }
393
+ } else {
394
+ subtables.push(scan.lines.slice(headerAt, r.end).filter((l, idx, arr) => !(l.trim() === "" && idx === arr.length - 1)));
395
+ }
396
+ }
397
+ }
398
+ }
399
+ if (opts.voyage === true) envLines.unshift(`NREKI_SEMANTIC = "voyage"`);
400
+
401
+ const section = codexSection(opts, keptMain.filter((l) => l.trim() !== ""), envLines, subtables);
402
+ let outLines: string[];
403
+ if (scan.ranges.length > 0) {
404
+ const first = scan.ranges[0].start;
405
+ const removed = new Set<number>();
406
+ for (const r of scan.ranges) for (let i = r.start; i < r.end; i++) removed.add(i);
407
+ outLines = [];
408
+ for (let i = 0; i < scan.lines.length; i++) {
409
+ if (i === first) {
410
+ outLines.push(...section);
411
+ // keep one blank line between our section and the next table
412
+ if (i < scan.lines.length && scan.ranges[scan.ranges.length - 1].end < scan.lines.length) outLines.push("");
413
+ }
414
+ if (!removed.has(i)) outLines.push(scan.lines[i]);
415
+ }
416
+ // collapse a blank line we might have doubled
417
+ outLines = outLines.filter((l, i, arr) => !(l === "" && arr[i - 1] === ""));
418
+ } else {
419
+ outLines = [...scan.lines];
420
+ while (outLines.length > 0 && outLines[outLines.length - 1].trim() === "") outLines.pop();
421
+ if (outLines.length > 0) outLines.push("");
422
+ outLines.push(...section);
423
+ }
424
+ const next = outLines.join(scan.eol) + scan.eol;
425
+
426
+ if (previous !== null && next === (previous.endsWith("\n") ? previous : previous + scan.eol)) {
427
+ return { path: rel, op: "skipped", note: `already registered (nreki@${opts.version})` };
428
+ }
429
+ if (!opts.dryRun) writeText(abs, next);
430
+ const op: McpAction["op"] = previous === null ? "created" : scan.ranges.length > 0 ? "rewritten" : "merged";
431
+ return { path: rel, op, note: op === "rewritten" ? `updated to nreki@${opts.version}` : undefined };
432
+ }
433
+
434
+ function unregisterCodex(cwd: string, dryRun: boolean): McpAction | null {
435
+ const rel = MCP_CONFIG_PATH.codex;
436
+ const abs = path.join(cwd, rel);
437
+ if (!fs.existsSync(abs)) return null;
438
+ const unsafe = unsafeWriteTarget(cwd, rel);
439
+ if (unsafe) return { path: rel, op: "skipped", note: `${unsafe}: not touched` };
440
+ const text = fs.readFileSync(abs, "utf-8").replace(/^/, "");
441
+ const scan = scanCodex(text);
442
+ if (scan.ranges.length === 0) return null;
443
+ const sectionText = scan.ranges.map((r) => scan.lines.slice(r.start, r.end).join("\n")).join("\n");
444
+ if (!/["']nreki(@[^"'\s]*)?["']/.test(sectionText)) return null;
445
+ const removed = new Set<number>();
446
+ for (const r of scan.ranges) for (let i = r.start; i < r.end; i++) removed.add(i);
447
+ const rest = scan.lines.filter((_, i) => !removed.has(i));
448
+ while (rest.length > 0 && rest[rest.length - 1].trim() === "") rest.pop();
449
+ const empty = rest.every((l) => l.trim() === "");
450
+ if (!dryRun) {
451
+ if (empty) {
452
+ fs.unlinkSync(abs);
453
+ removeEmptyDirs(cwd, path.dirname(abs));
454
+ } else {
455
+ fs.writeFileSync(abs, rest.join(scan.eol) + scan.eol, "utf-8");
456
+ }
457
+ }
458
+ return { path: rel, op: "removed", note: empty ? "file deleted (it only held nreki)" : "[mcp_servers.nreki] removed" };
459
+ }
460
+
461
+ // ─── Public API ────────────────────────────────────────────────────────────
462
+
463
+ export function registerMcp(host: McpHost, opts: McpRegisterOptions): McpAction {
464
+ return host === "codex" ? registerCodex(opts) : registerJson(host, opts);
465
+ }
466
+
467
+ /** Remove the entry NREKI wrote for `host`. Null when there is none. */
468
+ export function unregisterMcp(host: McpHost, cwd: string, dryRun = false): McpAction | null {
469
+ return host === "codex" ? unregisterCodex(cwd, dryRun) : unregisterJson(host, cwd, dryRun);
470
+ }
471
+
472
+ export function isMcpHost(agent: string): agent is McpHost {
473
+ return (MCP_HOSTS as readonly string[]).includes(agent);
474
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * project-root.ts — NREKI_PROJECT_ROOT names the project folder explicitly.
3
+ *
4
+ * NREKI treats the folder it starts in (process.cwd()) as the project. Some
5
+ * MCP hosts start servers elsewhere: measured on 2026-11-26, Antigravity starts
6
+ * a global plugin's server in the plugin's own folder, and Cursor and VS Code
7
+ * do not document the folder they use. `nreki init` therefore pins the project
8
+ * in each registration, either with the host's own `cwd` field or with
9
+ * NREKI_PROJECT_ROOT, and the server switches to that folder before any module
10
+ * reads process.cwd() (see bootstrap-root.ts).
11
+ */
12
+
13
+ import fs from "fs";
14
+ import path from "path";
15
+
16
+ export type ProjectRootDecision =
17
+ | { kind: "unset" }
18
+ | { kind: "apply"; dir: string }
19
+ | { kind: "ignore"; reason: string };
20
+
21
+ function isDirectory(p: string): boolean {
22
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
23
+ }
24
+
25
+ /**
26
+ * Decide what to do with a NREKI_PROJECT_ROOT value. An unusable value is
27
+ * ignored with a reason instead of failing the server: the host may not have
28
+ * expanded a variable such as ${workspaceFolder}.
29
+ */
30
+ export function decideProjectRoot(
31
+ raw: string | undefined,
32
+ statDir: (p: string) => boolean = isDirectory,
33
+ ): ProjectRootDecision {
34
+ const value = (raw ?? "").trim();
35
+ if (!value) return { kind: "unset" };
36
+ if (value.includes("${")) {
37
+ return { kind: "ignore", reason: `NREKI_PROJECT_ROOT="${value}" was not expanded by the MCP host` };
38
+ }
39
+ if (!path.isAbsolute(value)) {
40
+ return { kind: "ignore", reason: `NREKI_PROJECT_ROOT must be an absolute path (got "${value}")` };
41
+ }
42
+ if (!statDir(value)) {
43
+ return { kind: "ignore", reason: `NREKI_PROJECT_ROOT "${value}" is not an existing folder` };
44
+ }
45
+ return { kind: "apply", dir: path.resolve(value) };
46
+ }
47
+
48
+ /**
49
+ * Switch to NREKI_PROJECT_ROOT when it names an existing folder. Writes to
50
+ * stderr only: stdout carries the MCP protocol.
51
+ */
52
+ export function applyProjectRoot(env: NodeJS.ProcessEnv = process.env): ProjectRootDecision {
53
+ const decision = decideProjectRoot(env.NREKI_PROJECT_ROOT);
54
+ if (decision.kind === "apply") {
55
+ if (path.resolve(process.cwd()) !== decision.dir) process.chdir(decision.dir);
56
+ } else if (decision.kind === "ignore") {
57
+ process.stderr.write(`[NREKI] ${decision.reason}; using ${process.cwd()} as the project.\n`);
58
+ }
59
+ return decision;
60
+ }