nemu-cli 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.2
4
+
5
+ After an update, the CLI checks once whether what setup installed still matches what this version
6
+ needs: the Nemu hooks for Claude Code and Codex, and the nemu entry in each editor. Only Nemu's own
7
+ entries that actually differ are rewritten, with every other hook and setting left as it was, and
8
+ nothing is printed when everything already matches. This runs on the first command after an
9
+ update, right after `nemu update` installs a new version, and quietly at the start of a session.
10
+ `nemu repair` runs the same check any time. Each check is a small migration in
11
+ `src/migrations.ts`, so a future release that changes setup adds one there.
12
+
13
+ Commands are started with cross-spawn instead of a shell on Windows, which removes Node's
14
+ DEP0190 deprecation warning and escapes arguments properly.
15
+
3
16
  ## 1.3.1
4
17
 
5
18
  Fixes "hook failed, exited with code 1" for Codex on Windows. Codex starts hooks through a Windows
package/README.md CHANGED
@@ -166,6 +166,7 @@ file that cannot be parsed is never touched.
166
166
  | `nemu context projects` / `export --out file` | List projects, or export everything as JSON |
167
167
  | `nemu status` | Sign in, this device, global install, and each client's setup |
168
168
  | `nemu uninstall [client\|all]` | Remove exactly what setup added, for any client or editor |
169
+ | `nemu repair` | Bring the Nemu hooks and editor entries up to date for this version; also runs by itself once after each update |
169
170
  | `nemu update [--yes]` | Check for a newer version and install it. The CLI also asks by itself, at most once a day; `NEMU_NO_UPDATE_CHECK=1` turns that off |
170
171
  | `nemu token [--header]` | Print a fresh access token |
171
172
 
@@ -4,7 +4,7 @@ import { basename, join } from "node:path";
4
4
  import { CliError } from "../errors.js";
5
5
  import { run, which } from "../system.js";
6
6
  import { MCP_NAME } from "./registry.js";
7
- import { read_entry, remove_entry, set_entry } from "./jsonc.js";
7
+ import { read_entry, remove_entry, same_json, set_entry } from "./jsonc.js";
8
8
  async function exists(path) {
9
9
  try {
10
10
  await access(path);
@@ -75,6 +75,7 @@ function file_editor(id, label, config_path, keys, detect, value, after_setup) {
75
75
  config_path,
76
76
  keys,
77
77
  detect,
78
+ expected: value,
78
79
  add: async (nemu) => {
79
80
  await guard_foreign(config_path(), keys());
80
81
  return set_entry(config_path(), keys(), value(nemu));
@@ -93,11 +94,12 @@ export const EDITORS = {
93
94
  config_path: () => join(vscode_user_dir(), "mcp.json"),
94
95
  keys: () => ["servers", MCP_NAME],
95
96
  detect: () => any_present(["code"], [vscode_user_dir()]),
97
+ expected: (nemu) => ({ type: "stdio", ...bridge(nemu, "vscode") }),
96
98
  add: async (nemu) => {
97
99
  const entry = { type: "stdio", ...bridge(nemu, "vscode") };
98
100
  const path = join(vscode_user_dir(), "mcp.json");
99
101
  const before = await guard_foreign(path, ["servers", MCP_NAME]);
100
- if (JSON.stringify(before) === JSON.stringify(entry))
102
+ if (same_json(before, entry))
101
103
  return { change: "unchanged", backup: null };
102
104
  if ((await which("code")) !== null) {
103
105
  const result = await run("code", ["--add-mcp", JSON.stringify({ name: MCP_NAME, ...entry })], {
@@ -144,3 +146,15 @@ export async function require_editor(spec) {
144
146
  throw new CliError(`${spec.label} was not found on this computer. Install it first, or print the config with: nemu mcp config ${spec.id}`, "client_missing");
145
147
  }
146
148
  }
149
+ export async function editor_outdated(spec, nemu) {
150
+ const current = await read_entry(spec.config_path(), spec.keys());
151
+ if (!is_nemu_entry(current))
152
+ return false;
153
+ return !same_json(current, spec.expected(nemu));
154
+ }
155
+ export async function refresh_editor(spec, nemu) {
156
+ if (!(await editor_outdated(spec, nemu)))
157
+ return false;
158
+ const result = await set_entry(spec.config_path(), spec.keys(), spec.expected(nemu));
159
+ return result.change !== "unchanged";
160
+ }
@@ -145,3 +145,44 @@ export async function installed_hooks(path) {
145
145
  .filter(([, groups]) => groups.some((group) => (group.hooks ?? []).some((handler) => is_own_command(handler.command))))
146
146
  .map(([event]) => event);
147
147
  }
148
+ function refreshed(config, nemu, client, platform) {
149
+ const specs = HOOK_SPECS[client];
150
+ const hooks = {};
151
+ for (const [event, groups] of Object.entries(config.hooks ?? {})) {
152
+ const spec = specs.find((candidate) => candidate.event === event);
153
+ const kept = groups
154
+ .map((group) => {
155
+ const own = (group.hooks ?? []).filter((handler) => is_own_command(handler.command));
156
+ if (own.length === 0)
157
+ return group;
158
+ if (spec === undefined) {
159
+ return { ...group, hooks: (group.hooks ?? []).filter((handler) => !is_own_command(handler.command)) };
160
+ }
161
+ const handlers = (group.hooks ?? []).map((handler) => is_own_command(handler.command)
162
+ ? { ...handler, type: "command", command: hook_command(nemu, spec.hook, client, platform), timeout: spec.timeout }
163
+ : handler);
164
+ const only_own = handlers.every((handler) => is_own_command(handler.command));
165
+ const { matcher: _matcher, ...rest } = group;
166
+ return only_own
167
+ ? { ...(spec.matcher !== undefined ? { matcher: spec.matcher } : {}), ...rest, hooks: handlers }
168
+ : { ...group, hooks: handlers };
169
+ })
170
+ .filter((group) => (group.hooks ?? []).length > 0);
171
+ if (kept.length > 0)
172
+ hooks[event] = kept;
173
+ }
174
+ const { hooks: _previous, ...rest } = config;
175
+ return Object.keys(hooks).length > 0 ? { ...rest, hooks } : rest;
176
+ }
177
+ export async function hooks_outdated(path, nemu, client, platform = process.platform) {
178
+ if ((await installed_hooks(path)).length === 0)
179
+ return false;
180
+ const config = await read_config(path);
181
+ return stable(refreshed(config, nemu, client, platform)) !== stable(config);
182
+ }
183
+ export async function refresh_hooks(path, nemu, client, platform = process.platform) {
184
+ if (!(await hooks_outdated(path, nemu, client, platform)))
185
+ return false;
186
+ await write_config(path, refreshed(await read_config(path), nemu, client, platform));
187
+ return true;
188
+ }
@@ -3,6 +3,20 @@ import { dirname } from "node:path";
3
3
  import { applyEdits, findNodeAtLocation, getNodeValue, modify, parseTree } from "jsonc-parser";
4
4
  import { CliError } from "../errors.js";
5
5
  export const BACKUP_SUFFIX = ".nemu-backup";
6
+ export function same_json(left, right) {
7
+ const stable = (value) => {
8
+ if (Array.isArray(value))
9
+ return `[${value.map(stable).join(",")}]`;
10
+ if (value !== null && typeof value === "object") {
11
+ return `{${Object.keys(value)
12
+ .sort()
13
+ .map((key) => `${JSON.stringify(key)}:${stable(value[key])}`)
14
+ .join(",")}}`;
15
+ }
16
+ return JSON.stringify(value) ?? "undefined";
17
+ };
18
+ return stable(left) === stable(right);
19
+ }
6
20
  async function read_text(path) {
7
21
  try {
8
22
  return await readFile(path, "utf-8");
@@ -104,12 +118,12 @@ export async function set_entry(path, keys, value) {
104
118
  const text = original === null || original.trim().length === 0 ? "{}" : original;
105
119
  const tree = parse_object(path, text);
106
120
  const existing = findNodeAtLocation(tree, keys);
107
- if (existing !== undefined && JSON.stringify(getNodeValue(existing)) === JSON.stringify(value)) {
121
+ if (existing !== undefined && same_json(getNodeValue(existing), value)) {
108
122
  return { change: "unchanged", backup: null };
109
123
  }
110
124
  const next = insert_entry(text, keys, value);
111
125
  const written = findNodeAtLocation(parse_object(path, next), keys);
112
- if (written === undefined || JSON.stringify(getNodeValue(written)) !== JSON.stringify(value)) {
126
+ if (written === undefined || !same_json(getNodeValue(written), value)) {
113
127
  throw new CliError(`${path} could not be updated safely, so nothing was changed.`, "config_unreadable");
114
128
  }
115
129
  const backup = await write_atomic(path, next.endsWith("\n") ? next : `${next}\n`, original);
@@ -9,6 +9,7 @@ import { staleness } from "../context/stale.js";
9
9
  import { current_project } from "../context/project.js";
10
10
  import { snapshot } from "../context/snapshot.js";
11
11
  import { repository } from "../git.js";
12
+ import { migrate_after_update } from "../migrations.js";
12
13
  const MAX_CONTEXT = { "claude-code": 9000, codex: 7500 };
13
14
  const CHECKPOINT_EDITS = 3;
14
15
  const ASK_INTERVAL_MS = 10 * 60_000;
@@ -286,6 +287,7 @@ export async function hook(args) {
286
287
  switch (event) {
287
288
  case "start":
288
289
  await on_start(client, input);
290
+ await migrate_after_update("session-start");
289
291
  break;
290
292
  case "tool":
291
293
  await on_tool(client, input);
@@ -0,0 +1,23 @@
1
+ import { update_settings } from "../config.js";
2
+ import { run_migrations } from "../migrations.js";
3
+ import { emit, is_json_mode } from "../output.js";
4
+ import { dim, fail, out, success } from "../ui.js";
5
+ import { VERSION } from "../version.js";
6
+ export async function repair() {
7
+ const report = await run_migrations();
8
+ if (report.failed.length === 0)
9
+ await update_settings({ setup_version: VERSION });
10
+ if (is_json_mode()) {
11
+ emit({ ok: report.failed.length === 0, version: VERSION, ...report });
12
+ return report.failed.length === 0 ? 0 : 1;
13
+ }
14
+ if (report.applied.length === 0 && report.failed.length === 0) {
15
+ out(dim(` Your setup is up to date for nemu ${VERSION}.`));
16
+ return 0;
17
+ }
18
+ for (const line of report.applied)
19
+ success(line);
20
+ for (const line of report.failed)
21
+ fail(`${line} did not finish. Details are in ~/.nemu/hooks.log`);
22
+ return report.failed.length === 0 ? 0 : 1;
23
+ }
package/dist/config.js CHANGED
@@ -24,6 +24,7 @@ const settings_schema = z.object({
24
24
  update_latest: z.string().max(64).optional(),
25
25
  update_declined_version: z.string().max(64).optional(),
26
26
  update_declined_at: z.number().optional(),
27
+ setup_version: z.string().max(64).optional(),
27
28
  });
28
29
  export function api_url() {
29
30
  return (process.env.NEMU_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
package/dist/index.js CHANGED
@@ -18,6 +18,8 @@ import { config_command } from "./commands/settings.js";
18
18
  import { client_command } from "./commands/client.js";
19
19
  import { send_report } from "./report.js";
20
20
  import { maybe_offer_update, update_command } from "./update.js";
21
+ import { migrate_after_update } from "./migrations.js";
22
+ import { repair } from "./commands/repair.js";
21
23
  import { CliError } from "./errors.js";
22
24
  import { VERSION } from "./version.js";
23
25
  import { bold, dim, fail, out } from "./ui.js";
@@ -54,6 +56,7 @@ const COMMANDS = {
54
56
  context,
55
57
  config: config_command,
56
58
  update: update_command,
59
+ repair,
57
60
  };
58
61
  const HELP = `
59
62
  ${bold("nemu")} ${dim(VERSION)}
@@ -80,6 +83,7 @@ const HELP = `
80
83
  token [--header] Print a fresh access token
81
84
  config get | set reports on|off Error reports sent after a failure
82
85
  update [--yes] Check for a new version and install it
86
+ repair Bring hooks and editor entries up to date
83
87
 
84
88
  ${bold("Account")}
85
89
  login [--force] [--no-browser] Sign in with the device flow
@@ -185,6 +189,13 @@ async function main() {
185
189
  return 0;
186
190
  }
187
191
  await maybe_offer_update(command);
192
+ const migrated = await migrate_after_update(command);
193
+ if (migrated !== null && migrated.applied.length > 0 && !is_json_mode()) {
194
+ out(dim(` Updated your setup for nemu ${VERSION}:`));
195
+ for (const line of migrated.applied)
196
+ out(dim(` ${line}`));
197
+ out();
198
+ }
188
199
  return await handler(args);
189
200
  }
190
201
  async function report_failure(error) {
@@ -0,0 +1,70 @@
1
+ import { CLIENTS } from "./clients/registry.js";
2
+ import { EDITORS, editor_outdated, refresh_editor } from "./clients/editors.js";
3
+ import { hooks_outdated, refresh_hooks } from "./clients/hooks.js";
4
+ import { read_settings, update_settings, config_dir } from "./config.js";
5
+ import { resolve_nemu_binary } from "./commands/setup.js";
6
+ import { VERSION } from "./version.js";
7
+ import { appendFile, mkdir } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ const QUIET_COMMANDS = new Set(["hook", "mcp", "token", "uninstall", "repair", "update"]);
10
+ export const MIGRATIONS = [
11
+ ...Object.values(CLIENTS).map((spec) => ({
12
+ id: `hooks:${spec.id}`,
13
+ label: `${spec.label}: updated the Nemu hooks`,
14
+ needed: (nemu) => hooks_outdated(spec.hooks_path(), nemu, spec.id),
15
+ apply: (nemu) => refresh_hooks(spec.hooks_path(), nemu, spec.id),
16
+ })),
17
+ ...Object.values(EDITORS).map((editor) => ({
18
+ id: `mcp:${editor.id}`,
19
+ label: `${editor.label}: updated the nemu server entry`,
20
+ needed: (nemu) => editor_outdated(editor, nemu),
21
+ apply: (nemu) => refresh_editor(editor, nemu),
22
+ })),
23
+ ];
24
+ async function log_failure(id, error) {
25
+ const message = error instanceof Error ? error.message : String(error);
26
+ await mkdir(config_dir(), { recursive: true }).catch(() => undefined);
27
+ await appendFile(join(config_dir(), "hooks.log"), `${new Date().toISOString()} migration ${id} ${message.replace(/\s+/g, " ").slice(0, 300)}\n`).catch(() => undefined);
28
+ }
29
+ export async function run_migrations(migrations = MIGRATIONS) {
30
+ const report = { applied: [], failed: [] };
31
+ const nemu = await resolve_nemu_binary(false).catch(() => null);
32
+ if (nemu === null)
33
+ return report;
34
+ for (const migration of migrations) {
35
+ try {
36
+ if (!(await migration.needed(nemu)))
37
+ continue;
38
+ if (await migration.apply(nemu))
39
+ report.applied.push(migration.label);
40
+ }
41
+ catch (error) {
42
+ report.failed.push(migration.label);
43
+ await log_failure(migration.id, error);
44
+ }
45
+ }
46
+ return report;
47
+ }
48
+ export function migrations_due(command, setup_version) {
49
+ return !QUIET_COMMANDS.has(command) && setup_version !== VERSION;
50
+ }
51
+ export async function migrate_after_update(command) {
52
+ try {
53
+ const settings = await read_settings();
54
+ if (!migrations_due(command, settings.setup_version))
55
+ return null;
56
+ if (process.env.NEMU_BIN === undefined && !is_global_run())
57
+ return null;
58
+ const report = await run_migrations();
59
+ if (report.failed.length === 0)
60
+ await update_settings({ setup_version: VERSION });
61
+ return report;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ function is_global_run() {
68
+ const script = (process.argv[1] ?? "").replaceAll("\\", "/");
69
+ return !script.includes("/_npx/") && !script.includes("/.bun/install/cache/");
70
+ }
package/dist/system.js CHANGED
@@ -1,31 +1,49 @@
1
- import { execFile, spawn } from "node:child_process";
1
+ import spawn from "cross-spawn";
2
2
  import { access, constants } from "node:fs/promises";
3
3
  import { delimiter, join } from "node:path";
4
+ const MAX_OUTPUT = 4 * 1024 * 1024;
4
5
  export function run(command, args, options = {}) {
5
6
  return new Promise((resolve) => {
6
- execFile(command, args, {
7
+ const stdout = [];
8
+ const stderr = [];
9
+ let size = 0;
10
+ let settled = false;
11
+ const finish = (code) => {
12
+ if (settled)
13
+ return;
14
+ settled = true;
15
+ clearTimeout(timer);
16
+ resolve({
17
+ code,
18
+ stdout: Buffer.concat(stdout).toString("utf-8"),
19
+ stderr: Buffer.concat(stderr).toString("utf-8"),
20
+ });
21
+ };
22
+ const collect = (target) => (chunk) => {
23
+ if (size >= MAX_OUTPUT)
24
+ return;
25
+ size += chunk.length;
26
+ target.push(chunk);
27
+ };
28
+ const child = spawn(command, args, {
7
29
  env: options.env ?? process.env,
8
30
  cwd: options.cwd,
9
- timeout: options.timeout_ms ?? 30_000,
10
- maxBuffer: 4 * 1024 * 1024,
11
31
  windowsHide: true,
12
- shell: process.platform === "win32",
13
- }, (error, stdout, stderr) => {
14
- const code = error === null
15
- ? 0
16
- : typeof error.code === "number"
17
- ? (error.code)
18
- : 127;
19
- resolve({ code, stdout: stdout.toString(), stderr: stderr.toString() });
32
+ stdio: ["ignore", "pipe", "pipe"],
20
33
  });
34
+ const timer = setTimeout(() => {
35
+ child.kill();
36
+ finish(127);
37
+ }, options.timeout_ms ?? 30_000);
38
+ child.stdout?.on("data", collect(stdout));
39
+ child.stderr?.on("data", collect(stderr));
40
+ child.on("error", () => finish(127));
41
+ child.on("close", (code) => finish(code ?? 127));
21
42
  });
22
43
  }
23
44
  export function launch(command, args) {
24
45
  return new Promise((resolve) => {
25
- const child = spawn(command, args, {
26
- stdio: "inherit",
27
- shell: process.platform === "win32",
28
- });
46
+ const child = spawn(command, args, { stdio: "inherit" });
29
47
  child.on("error", () => resolve(127));
30
48
  child.on("exit", (code, signal) => resolve(code ?? (signal !== null ? 1 : 0)));
31
49
  });
package/dist/update.js CHANGED
@@ -6,6 +6,7 @@ import { emit, is_json_mode } from "./output.js";
6
6
  import { bool_flag } from "./args.js";
7
7
  import { VERSION } from "./version.js";
8
8
  const PACKAGE = "nemu-cli";
9
+ const PACKAGE_BINARY = "nemu";
9
10
  const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
10
11
  const FETCH_TIMEOUT_MS = 1500;
11
12
  const QUIET_COMMANDS = new Set(["hook", "mcp", "token", "update"]);
@@ -83,6 +84,10 @@ async function install(version) {
83
84
  return false;
84
85
  }
85
86
  success(`Updated to ${version}.`);
87
+ const repaired = await run(PACKAGE_BINARY, ["repair"], { timeout_ms: 60_000 });
88
+ const lines = repaired.stdout.trimEnd();
89
+ if (repaired.code === 0 && lines.length > 0 && !lines.includes("up to date"))
90
+ out(lines);
86
91
  return true;
87
92
  }
88
93
  async function offer(latest, now) {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "1.3.1";
1
+ export const VERSION = "1.3.2";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemu-cli",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "Command line access to Nemu, and portable project memory for Claude Code, Codex and any MCP client.",
5
5
  "bin": {
6
6
  "nemu": "./dist/index.js"
@@ -31,6 +31,7 @@
31
31
  "author": "hiraeeth",
32
32
  "license": "MIT",
33
33
  "devDependencies": {
34
+ "@types/cross-spawn": "6.0.6",
34
35
  "@types/node": "^20.0.0",
35
36
  "typescript": "^5"
36
37
  },
@@ -40,6 +41,7 @@
40
41
  "homepage": "https://docs.nemu.cc",
41
42
  "dependencies": {
42
43
  "@nemu-ai/sdk": "^1.1.0",
44
+ "cross-spawn": "7.0.6",
43
45
  "jsonc-parser": "3.3.1",
44
46
  "zod": "^4.1.0"
45
47
  }