@nano-step/nano-brain 2026.7.1103 → 2026.7.1104

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.
@@ -6,7 +6,7 @@ const fs = require("fs");
6
6
  const path = require("path");
7
7
  const os = require("os");
8
8
  const crypto = require("crypto");
9
- const { execSync } = require("child_process");
9
+ const { execFileSync } = require("child_process");
10
10
 
11
11
  const VERSION = require("../package.json").version;
12
12
  const REPO = "nano-step/nano-brain";
@@ -24,9 +24,10 @@ function getPlatformKey() {
24
24
  const platform = PLATFORM_MAP[os.platform()];
25
25
  const arch = ARCH_MAP[os.arch()];
26
26
  if (!platform || !arch) {
27
- console.error(`Unsupported platform: ${os.platform()}-${os.arch()}`);
28
- console.error("Build from source: CGO_ENABLED=0 go build -o nano-brain ./cmd/nano-brain");
29
- process.exit(0);
27
+ // Throw (do not process.exit) so ensureBinary's "throws, never exits"
28
+ // contract holds: main() turns this into a non-fatal install exit(0),
29
+ // run.js reports it and exits 1 (#594).
30
+ throw new Error(`Unsupported platform: ${os.platform()}-${os.arch()}`);
30
31
  }
31
32
  return `${platform}-${arch}`;
32
33
  }
@@ -267,84 +268,106 @@ function tryAutoLink(srcBinPath, platform) {
267
268
  }
268
269
  }
269
270
 
270
- async function main() {
271
- const platformKey = getPlatformKey();
271
+ function binaryPath() {
272
272
  const binName = os.platform() === "win32" ? "nano-brain.exe" : "nano-brain";
273
- const binPath = path.join(__dirname, binName);
273
+ return path.join(__dirname, binName);
274
+ }
275
+
276
+ // Download-and-verify the platform binary to binaryPath() and return that path.
277
+ // THROWS on failure (never calls process.exit) so both the install-time caller
278
+ // (main) and the run-time caller (run.js) can choose their own exit behavior.
279
+ // A "SECURITY:"-prefixed error signals an integrity failure that must hard-fail.
280
+ // Progress goes to stderr so it never pollutes a command's stdout when run.js
281
+ // downloads lazily on first invocation (#594).
282
+ async function ensureBinary() {
283
+ const platformKey = getPlatformKey();
284
+ const binPath = binaryPath();
274
285
 
275
286
  const skipVerify = !!process.env.NANO_BRAIN_SKIP_SHA_VERIFY;
276
287
  if (skipVerify) {
277
- console.warn("⚠ NANO_BRAIN_SKIP_SHA_VERIFY is set; binary integrity check will be skipped.");
288
+ console.error("⚠ NANO_BRAIN_SKIP_SHA_VERIFY is set; binary integrity check will be skipped.");
278
289
  }
279
290
 
280
291
  if (fs.existsSync(binPath)) {
281
292
  try {
282
- const output = execSync(`"${binPath}" version --json`, { timeout: 5000 }).toString();
293
+ const output = execFileSync(binPath, ["version", "--json"], { timeout: 5000 }).toString();
283
294
  if (output.includes(VERSION)) {
284
- console.log(`nano-brain v${VERSION} already installed.`);
285
- return;
295
+ return binPath;
286
296
  }
287
- } catch {
288
- // Wrong version or can't run — redownload
297
+ console.error("Existing nano-brain binary is a different version; re-downloading.");
298
+ } catch (err) {
299
+ console.error(`Existing nano-brain binary failed verification (${err.message}); re-downloading.`);
289
300
  }
301
+ // Reached only when the existing binary is stale/broken. Unlink before
302
+ // overwriting: a running process keeps its handle to the old inode, so
303
+ // this avoids ETXTBSY on re-download (Linux/macOS).
304
+ safeUnlink(binPath);
290
305
  }
291
306
 
292
- console.log(`Downloading nano-brain v${VERSION} for ${platformKey}...`);
307
+ console.error(`Downloading nano-brain v${VERSION} for ${platformKey}...`);
293
308
 
294
309
  const assetName = `nano-brain-${platformKey}`;
295
310
  let lastErr;
296
- for (const tag of candidateTagsForVersion(VERSION)) {
311
+
312
+ const attempt = async (tag, suffix) => {
297
313
  const url = `https://github.com/${REPO}/releases/download/${tag}/${assetName}`;
314
+ if (skipVerify) {
315
+ await download(url, binPath);
316
+ } else {
317
+ const computedHex = await downloadWithHash(url, binPath);
318
+ await verifySHA256(tag, assetName, binPath, computedHex);
319
+ }
320
+ fs.chmodSync(binPath, 0o755);
321
+ console.error(`nano-brain v${VERSION} installed successfully from ${tag}${suffix || ""}.`);
322
+ return binPath;
323
+ };
324
+
325
+ for (const tag of candidateTagsForVersion(VERSION)) {
298
326
  try {
299
- if (skipVerify) {
300
- await download(url, binPath);
301
- } else {
302
- const computedHex = await downloadWithHash(url, binPath);
303
- await verifySHA256(tag, assetName, binPath, computedHex);
304
- }
305
- fs.chmodSync(binPath, 0o755);
306
- console.log(`nano-brain v${VERSION} installed successfully from ${tag}.`);
307
- tryAutoLink(binPath);
308
- return;
327
+ return await attempt(tag);
309
328
  } catch (err) {
310
- if (err && typeof err.message === "string" && err.message.startsWith("SECURITY:")) {
311
- console.error(err.message);
312
- process.exit(1);
313
- }
329
+ if (err && typeof err.message === "string" && err.message.startsWith("SECURITY:")) throw err;
314
330
  lastErr = err;
315
331
  }
316
332
  }
317
333
 
334
+ let apiTag;
318
335
  try {
319
- const tag = await resolveTagFromAPI(VERSION, assetName);
320
- if (tag) {
321
- const url = `https://github.com/${REPO}/releases/download/${tag}/${assetName}`;
322
- if (skipVerify) {
323
- await download(url, binPath);
324
- } else {
325
- const computedHex = await downloadWithHash(url, binPath);
326
- await verifySHA256(tag, assetName, binPath, computedHex);
327
- }
328
- fs.chmodSync(binPath, 0o755);
329
- console.log(`nano-brain v${VERSION} installed successfully from ${tag} (API fallback).`);
330
- tryAutoLink(binPath);
331
- return;
332
- }
336
+ apiTag = await resolveTagFromAPI(VERSION, assetName);
333
337
  } catch (err) {
334
- if (err && typeof err.message === "string" && err.message.startsWith("SECURITY:")) {
335
- console.error(err.message);
336
- process.exit(1);
337
- }
338
338
  lastErr = err;
339
339
  }
340
+ if (apiTag) {
341
+ // Not wrapped: a SECURITY error from the API-fallback attempt must propagate.
342
+ return await attempt(apiTag, " (API fallback)");
343
+ }
344
+
345
+ throw new Error(`Failed to download binary: ${lastErr && lastErr.message}`);
346
+ }
340
347
 
341
- console.error(`Failed to download binary: ${lastErr && lastErr.message}`);
342
- console.error("Build from source: CGO_ENABLED=0 go build -o npm/nano-brain ./cmd/nano-brain");
343
- process.exit(0);
348
+ async function main() {
349
+ try {
350
+ const bin = await ensureBinary();
351
+ // Auto-link only at install time — never from run.js's lazy path, so its
352
+ // console.log chatter can't pollute a command's stdout (#594).
353
+ tryAutoLink(bin);
354
+ } catch (err) {
355
+ const msg = err && err.message ? err.message : String(err);
356
+ if (msg.startsWith("SECURITY:")) {
357
+ console.error(msg);
358
+ process.exit(1); // integrity failure — never leave a bad binary
359
+ }
360
+ // Non-fatal at install time: don't fail `npm install`. run.js retries the
361
+ // download on first invocation, which also covers toolchains that don't
362
+ // persist postinstall-created files (#594).
363
+ console.error(msg);
364
+ console.error("Build from source: CGO_ENABLED=0 go build -o npm/nano-brain ./cmd/nano-brain");
365
+ process.exit(0);
366
+ }
344
367
  }
345
368
 
346
369
  if (require.main === module) {
347
370
  main();
348
371
  }
349
372
 
350
- module.exports = { parseSHA256Line, download, downloadWithHash, verifySHA256, tryAutoLink, safeUnlink };
373
+ module.exports = { parseSHA256Line, download, downloadWithHash, verifySHA256, tryAutoLink, safeUnlink, ensureBinary, binaryPath };
@@ -6,7 +6,60 @@ const fs = require("node:fs");
6
6
  const path = require("node:path");
7
7
  const os = require("node:os");
8
8
  const crypto = require("node:crypto");
9
- const { parseSHA256Line, tryAutoLink, safeUnlink, download, downloadWithHash } = require("./postinstall");
9
+ const { spawnSync } = require("node:child_process");
10
+ const { parseSHA256Line, tryAutoLink, safeUnlink, download, downloadWithHash, ensureBinary, binaryPath } = require("./postinstall");
11
+ const VERSION = require("../package.json").version;
12
+ const isWin = os.platform() === "win32";
13
+
14
+ // #594: when a valid binary is already at binaryPath(), ensureBinary() must
15
+ // return it WITHOUT any network download. Stub the binary with a tiny script
16
+ // that echoes the expected `version --json` payload. Any real binary already
17
+ // there is moved aside and restored so the assertion always runs (not skipped).
18
+ test("ensureBinary: returns existing binary without downloading", { skip: isWin }, async () => {
19
+ const bin = binaryPath();
20
+ const backup = `${bin}.itest.bak`;
21
+ const hadReal = fs.existsSync(bin);
22
+ if (hadReal) fs.renameSync(bin, backup);
23
+ fs.writeFileSync(bin, `#!/bin/sh\necho '{"version":"${VERSION}"}'\n`);
24
+ fs.chmodSync(bin, 0o755);
25
+ try {
26
+ const resolved = await ensureBinary();
27
+ assert.strictEqual(resolved, bin);
28
+ } finally {
29
+ safeUnlink(bin);
30
+ if (hadReal) fs.renameSync(backup, bin);
31
+ }
32
+ });
33
+
34
+ // #594 BLOCKER regression: an unsupported platform must REJECT (not process.exit),
35
+ // so run.js can report it and exit 1. getPlatformKey throws; ensureBinary propagates.
36
+ test("ensureBinary: rejects (does not exit) on unsupported platform", async () => {
37
+ const realPlatform = os.platform;
38
+ os.platform = () => "freebsd";
39
+ try {
40
+ await assert.rejects(() => ensureBinary(), /Unsupported platform/);
41
+ } finally {
42
+ os.platform = realPlatform;
43
+ }
44
+ });
45
+
46
+ // #594: run.js executes the binary NANO_BRAIN_BIN points to (override path),
47
+ // end-to-end via a subprocess — proves the wrapper's exec path works.
48
+ test("run.js: runs NANO_BRAIN_BIN target and exits 0", { skip: isWin }, () => {
49
+ const stub = path.join(os.tmpdir(), `nb-runjs-stub-${process.pid}-${Date.now()}`);
50
+ fs.writeFileSync(stub, `#!/bin/sh\necho NB_STUB_OK\n`);
51
+ fs.chmodSync(stub, 0o755);
52
+ try {
53
+ const r = spawnSync(process.execPath, [path.join(__dirname, "run.js"), "anyarg"], {
54
+ env: { ...process.env, NANO_BRAIN_BIN: stub },
55
+ encoding: "utf8",
56
+ });
57
+ assert.strictEqual(r.status, 0);
58
+ assert.match(r.stdout, /NB_STUB_OK/);
59
+ } finally {
60
+ safeUnlink(stub);
61
+ }
62
+ });
10
63
 
11
64
  // #592 regression: a request/socket error must REJECT the promise (so main()'s
12
65
  // per-tag retry loop continues), never throw synchronously or crash the
package/npm/run.js CHANGED
@@ -9,6 +9,23 @@ const os = require("os");
9
9
  const binName = os.platform() === "win32" ? "nano-brain.exe" : "nano-brain";
10
10
  const binPath = path.join(__dirname, binName);
11
11
 
12
+ function runBinary(bin) {
13
+ try {
14
+ execFileSync(bin, process.argv.slice(2), { stdio: "inherit" });
15
+ } catch (e) {
16
+ // A numeric status means the binary ran and chose that exit code (it has
17
+ // already produced its own output). A non-numeric status means we could
18
+ // not spawn it at all (arch mismatch, missing libc, ETXTBSY, perms) —
19
+ // surface that, since stdio:"inherit" shows nothing for a spawn failure.
20
+ if (typeof e.status !== "number") {
21
+ process.stderr.write(`Error: failed to execute binary at ${bin}: ${e.message}\n`);
22
+ }
23
+ process.exit(e.status || 1);
24
+ }
25
+ process.exit(0);
26
+ }
27
+
28
+ // Explicit override wins and skips any download.
12
29
  const envBin = process.env.NANO_BRAIN_BIN;
13
30
  if (envBin && envBin.trim() !== "") {
14
31
  const trimmed = envBin.trim();
@@ -16,26 +33,30 @@ if (envBin && envBin.trim() !== "") {
16
33
  process.stderr.write(`Error: NANO_BRAIN_BIN points to ${trimmed} which does not exist. Unset the variable or correct the path.\n`);
17
34
  process.exit(1);
18
35
  }
19
- const mode = fs.statSync(trimmed).mode;
20
- if ((mode & 0o111) === 0) {
36
+ if ((fs.statSync(trimmed).mode & 0o111) === 0) {
21
37
  process.stderr.write(`Error: NANO_BRAIN_BIN points to ${trimmed} which is not executable. Run: chmod +x ${trimmed}\n`);
22
38
  process.exit(1);
23
39
  }
24
- try { execFileSync(trimmed, process.argv.slice(2), { stdio: "inherit" }); }
25
- catch (e) { process.exit(e.status || 1); }
26
- process.exit(0);
40
+ runBinary(trimmed);
41
+ return; // runBinary exits; explicit return makes the branches structurally exclusive
27
42
  }
28
43
 
29
- if (!fs.existsSync(binPath)) {
30
- console.error("nano-brain binary not found at " + binPath + ".");
31
- console.error("The postinstall script may have failed during npm install.");
32
- console.error("Try: npm install -g @nano-step/nano-brain --foreground-scripts");
33
- console.error("Or build from source: CGO_ENABLED=0 go build -o npm/nano-brain ./cmd/nano-brain");
34
- process.exit(1);
44
+ if (fs.existsSync(binPath)) {
45
+ runBinary(binPath);
46
+ return;
35
47
  }
36
48
 
37
- try {
38
- execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" });
39
- } catch (e) {
40
- process.exit(e.status || 1);
41
- }
49
+ // The binary is missing — the postinstall download either failed (offline /
50
+ // proxy) or was not persisted by the package manager (some npm/node versions
51
+ // discard postinstall-created files, #594). Download it now, at run time, where
52
+ // the write always persists, then run. Progress goes to stderr.
53
+ process.stderr.write("nano-brain: binary not present; downloading on first run...\n");
54
+ require("./postinstall")
55
+ .ensureBinary()
56
+ .then((bin) => runBinary(bin))
57
+ .catch((err) => {
58
+ const msg = err && err.message ? err.message : String(err);
59
+ process.stderr.write(`nano-brain: could not obtain the binary: ${msg}\n`);
60
+ process.stderr.write("Fix: set NANO_BRAIN_BIN=/path/to/nano-brain, or build from source: CGO_ENABLED=0 go build -o npm/nano-brain ./cmd/nano-brain\n");
61
+ process.exit(1);
62
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nano-step/nano-brain",
3
- "version": "2026.7.1103",
3
+ "version": "2026.7.1104",
4
4
  "description": "Persistent memory and code intelligence for AI coding agents",
5
5
  "bin": {
6
6
  "nano-brain": "npm/run.js"