Skip to content

Commit f38576e

Browse files
rruvnet
andcommitted
feat(doctor): flag better-sqlite3 copies built against Node 24.19+ headers on 24.19-24.21 (ruvnet#4055)
Read-only check: reads build/config.gypi of each better-sqlite3 copy in the resolved tree (never loads an addon), warns when a locally compiled copy used 24.19+ headers while the runtime is 24.19-24.21 (nodejs/node#65446), with the documented workarounds. Prebuilt copies carry no config.gypi and pass. Co-Authored-By: RuFlo <[email protected]>
1 parent a3e53ca commit f38576e

5 files changed

Lines changed: 271 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- `ruflo doctor` reports `better-sqlite3` copies compiled against Node 24.19+ headers when running Node 24.19–24.21, where they can abort the process (`Assertion failed: (env) != nullptr`, nodejs/node#65446), with the documented workarounds. `doctor --component native-addon` runs it alone (#4055, reported by @ronmikailov).
13+
1014
### Fixed
1115

1216
Batch of reviewed fixes from @rudycelekli (PRs #4020-#4026, #4028-#4030, #4032, #4033, #4035, #4037; #4027 and #4034 landed earlier):

‎docs/USERGUIDE.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2846,6 +2846,7 @@ Run `npx ruflo@latest doctor` to diagnose and fix common issues.
28462846
| **MCP servers** | Responsive | ✅ Restarts unresponsive servers |
28472847
| **Disk space** | >100MB free | ❌ Manual cleanup required |
28482848
| **TypeScript** | Installed | ✅ Installs if missing |
2849+
| **Native addon headers** | No `better-sqlite3` built against Node 24.19+ headers while running Node 24.19–24.21 | ❌ See below |
28492850

28502851
**Commands:**
28512852

@@ -2863,6 +2864,14 @@ npx ruflo@latest doctor --component memory
28632864
npx ruflo@latest doctor --verbose
28642865
```
28652866

2867+
**Node 24.19–24.21 abort (#4055).** A native addon compiled against Node 24.19+ headers can abort the process with `Assertion failed: (env) != nullptr` in `node::RemoveEnvironmentCleanupHook` (nodejs/node#65446; the fix, PR #65943, is in no release through 24.21.0). Prebuilt binaries are not affected, only copies compiled locally, which carry a `build/config.gypi` naming the headers they used. `doctor --component native-addon` reads those files (it never loads an addon) and lists each affected copy. Workarounds, any one of:
2868+
2869+
- run Node 22, or Node 24.18.1, or a Node release that contains the fix;
2870+
- rebuild the listed copy against older headers: `cd <copy> && npx node-gyp rebuild --release --nodedir=<node 24.18.1 headers>`;
2871+
- install the 12.x prebuilt in the project: `npm install better-sqlite3@12`.
2872+
2873+
ruflo opens AgentDB through its own prebuilt 12.x copy (since 3.56.4), so a flagged nested copy under `agentdb` or `agentic-flow` matters only to code that loads it directly. npm ignores `overrides` in a dependency's package.json, so the nested 11.x copies cannot be removed from inside the published package.
2874+
28662875
**Output Example:**
28672876

28682877
```
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/** #4055: native addons built against Node >=24.19 headers abort on Node 24.19-24.21 (nodejs/node#65446). */
2+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4+
import { tmpdir } from 'node:os';
5+
import { join } from 'node:path';
6+
import {
7+
checkNativeAddonHeaders,
8+
headersVersionFromGypi,
9+
isAffectedNodeVersion,
10+
} from '../src/commands/doctor-native-addon.js';
11+
12+
let root: string;
13+
beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'ruflo-4055-')); });
14+
afterEach(() => { rmSync(root, { recursive: true, force: true }); });
15+
16+
const gypi = (nodedir: string) => `# Do not edit. File was generated by node-gyp's "configure" step
17+
{
18+
"target_defaults": { "cflags": [], "default_configuration": "Release" },
19+
"variables": {
20+
"napi_build_version": "0",
21+
"nodedir": "${nodedir}",
22+
"node_module_version": 137
23+
}
24+
}
25+
`;
26+
27+
function addon(dir: string, version: string, nodedir: string | null) {
28+
mkdirSync(join(dir, 'build'), { recursive: true });
29+
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'better-sqlite3', version }));
30+
if (nodedir !== null) writeFileSync(join(dir, 'build', 'config.gypi'), gypi(nodedir));
31+
}
32+
33+
describe('isAffectedNodeVersion', () => {
34+
it.each([
35+
['24.18.1', false], ['24.19.0', true], ['24.20.1', true], ['24.21.0', true],
36+
['24.21.5', true], ['22.23.2', false], ['25.0.0', false], ['20.11.0', false],
37+
])('%s -> %s', (v, expected) => expect(isAffectedNodeVersion(v)).toBe(expected));
38+
});
39+
40+
describe('headersVersionFromGypi', () => {
41+
it('reads the version out of the node-gyp cache nodedir', () => {
42+
expect(headersVersionFromGypi(gypi('/home/u/.cache/node-gyp/24.20.0'))).toBe('24.20.0');
43+
});
44+
it('reads a node-vXX source-tree nodedir', () => {
45+
expect(headersVersionFromGypi(gypi('/opt/node-v24.21.0'))).toBe('24.21.0');
46+
});
47+
it('returns null when no version can be read', () => {
48+
expect(headersVersionFromGypi(gypi('/usr/include/node'))).toBeNull();
49+
expect(headersVersionFromGypi('not a gypi')).toBeNull();
50+
});
51+
});
52+
53+
describe('checkNativeAddonHeaders', () => {
54+
it('warns for a copy built against 24.20 headers on Node 24.21', async () => {
55+
const bad = join(root, 'node_modules', 'agentdb', 'node_modules', 'better-sqlite3');
56+
addon(bad, '11.10.0', '/home/u/.cache/node-gyp/24.20.0');
57+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.21.0', copies: [bad] });
58+
expect(r.status).toBe('warn');
59+
expect(r.message).toContain('11.10.0');
60+
expect(r.message).toContain('24.20.0');
61+
expect(r.message).toContain(bad);
62+
expect(r.fix).toMatch(/24\.18\.1/);
63+
expect(r.fix).toMatch(/node-gyp rebuild/);
64+
expect(r.fix).toMatch(/nodedir/);
65+
});
66+
67+
it('passes for a prebuilt copy (no config.gypi) on an affected Node', async () => {
68+
const pre = join(root, 'node_modules', 'better-sqlite3');
69+
addon(pre, '12.11.1', null);
70+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.21.0', copies: [pre] });
71+
expect(r.status).toBe('pass');
72+
});
73+
74+
it('passes for a copy rebuilt against 24.18.1 headers', async () => {
75+
const ok = join(root, 'node_modules', 'better-sqlite3');
76+
addon(ok, '11.10.0', '/home/u/.cache/node-gyp/24.18.1');
77+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.21.0', copies: [ok] });
78+
expect(r.status).toBe('pass');
79+
});
80+
81+
it('is not applicable off the affected Node range', async () => {
82+
const bad = join(root, 'node_modules', 'better-sqlite3');
83+
addon(bad, '11.10.0', '/home/u/.cache/node-gyp/24.20.0');
84+
for (const nodeVersion of ['22.23.2', '24.18.1', '25.0.0']) {
85+
const r = await checkNativeAddonHeaders({ nodeVersion, copies: [bad] });
86+
expect(r.status).toBe('pass');
87+
expect(r.message).toMatch(/not affected|not in the affected/i);
88+
}
89+
});
90+
91+
it('reports every bad copy, not just the first', async () => {
92+
const a = join(root, 'node_modules', 'agentdb', 'node_modules', 'better-sqlite3');
93+
const b = join(root, 'node_modules', 'agentic-flow', 'node_modules', 'better-sqlite3');
94+
addon(a, '11.10.0', '/c/node-gyp/24.20.0');
95+
addon(b, '11.10.0', '/c/node-gyp/24.19.0');
96+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.20.0', copies: [a, b] });
97+
expect(r.status).toBe('warn');
98+
expect(r.message).toContain(a);
99+
expect(r.message).toContain(b);
100+
});
101+
102+
it('discovers nested copies under node_modules by walking up from a start dir', async () => {
103+
const top = join(root, 'node_modules', 'better-sqlite3');
104+
const nested = join(root, 'node_modules', 'agentdb', 'node_modules', 'better-sqlite3');
105+
addon(top, '12.11.1', null);
106+
addon(nested, '11.10.0', '/c/node-gyp/24.20.0');
107+
const start = join(root, 'node_modules', '@claude-flow', 'cli', 'dist', 'src', 'commands');
108+
mkdirSync(start, { recursive: true });
109+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.21.0', startDirs: [start] });
110+
expect(r.status).toBe('warn');
111+
expect(r.message).toContain(nested);
112+
expect(r.message).not.toContain(`${top} `);
113+
});
114+
115+
it('never throws on unreadable or malformed files', async () => {
116+
const weird = join(root, 'node_modules', 'better-sqlite3');
117+
mkdirSync(join(weird, 'build'), { recursive: true });
118+
writeFileSync(join(weird, 'package.json'), '{not json');
119+
writeFileSync(join(weird, 'build', 'config.gypi'), '\u0000\u0001');
120+
const r = await checkNativeAddonHeaders({ nodeVersion: '24.21.0', copies: [weird, join(root, 'missing')] });
121+
expect(['pass', 'warn']).toContain(r.status);
122+
});
123+
});
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/**
2+
* #4055: native addons compiled against Node >= 24.19 headers abort when a
3+
* garbage-collected ObjectWrap (a better-sqlite3 Statement) calls
4+
* RemoveEnvironmentCleanupHook() with no Environment (nodejs/node#65446).
5+
* The fix (abe1b673e9b, PR #65943) was in no release through v24.21.0.
6+
*
7+
* Only copies that were COMPILED LOCALLY carry a build/config.gypi naming the
8+
* headers they were built against; prebuilt binaries (prebuild-install) do not,
9+
* so they are never flagged. The check is read-only and never loads an addon.
10+
*/
11+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
12+
import { dirname, join, resolve } from 'node:path';
13+
import { fileURLToPath } from 'node:url';
14+
15+
export interface NativeAddonCheck {
16+
name: string;
17+
status: 'pass' | 'warn' | 'fail';
18+
message: string;
19+
fix?: string;
20+
}
21+
22+
const NAME = 'Native addon headers (Node 24)';
23+
24+
function parse(v: string): [number, number, number] | null {
25+
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v);
26+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
27+
}
28+
29+
/** Node 24.19.0 up to, but not including, 24.22.0. Re-check this bound when a release ships the fix. */
30+
export function isAffectedNodeVersion(version: string): boolean {
31+
const v = parse(version);
32+
if (!v || v[0] !== 24) return false;
33+
return v[1] >= 19 && v[1] <= 21;
34+
}
35+
36+
/** The Node version of the headers a copy was built against, from its config.gypi. */
37+
export function headersVersionFromGypi(gypi: string): string | null {
38+
const field = /["']node_version["']\s*:\s*["']v?(\d+\.\d+\.\d+)["']/.exec(gypi);
39+
if (field) return field[1];
40+
const dir = /["']nodedir["']\s*:\s*["']([^"']*)["']/.exec(gypi);
41+
if (!dir) return null;
42+
const all = [...dir[1].matchAll(/(\d+)\.(\d+)\.(\d+)/g)];
43+
const last = all[all.length - 1];
44+
return last ? `${last[1]}.${last[2]}.${last[3]}` : null;
45+
}
46+
47+
function readJson(path: string): Record<string, unknown> | null {
48+
try { return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>; } catch { return null; }
49+
}
50+
51+
function listDir(path: string): string[] {
52+
try { return readdirSync(path); } catch { return []; }
53+
}
54+
55+
/** `better-sqlite3` copies in node_modules next to, or one level under, each ancestor of the start dirs. */
56+
export function findBetterSqlite3Copies(startDirs: string[], maxDepth = 12): string[] {
57+
const found = new Set<string>();
58+
const add = (dir: string) => {
59+
if (!existsSync(join(dir, 'package.json'))) return;
60+
try { found.add(realpathSync(dir)); } catch { /* unreadable */ }
61+
};
62+
const scanNodeModules = (nm: string) => {
63+
add(join(nm, 'better-sqlite3'));
64+
for (const entry of listDir(nm)) {
65+
if (entry.startsWith('.') || entry === 'better-sqlite3') continue;
66+
if (entry.startsWith('@')) {
67+
for (const sub of listDir(join(nm, entry))) add(join(nm, entry, sub, 'node_modules', 'better-sqlite3'));
68+
} else {
69+
add(join(nm, entry, 'node_modules', 'better-sqlite3'));
70+
}
71+
}
72+
};
73+
for (const start of startDirs) {
74+
let dir = resolve(start);
75+
for (let i = 0; i < maxDepth; i++) {
76+
scanNodeModules(join(dir, 'node_modules'));
77+
const parent = dirname(dir);
78+
if (parent === dir) break;
79+
dir = parent;
80+
}
81+
}
82+
return [...found].sort();
83+
}
84+
85+
export interface NativeAddonCheckDeps {
86+
/** Runtime version, default process.versions.node. */
87+
nodeVersion?: string;
88+
/** Exact better-sqlite3 package directories to inspect (skips discovery). */
89+
copies?: string[];
90+
/** Directories to walk up from when discovering copies. */
91+
startDirs?: string[];
92+
}
93+
94+
const FIX = [
95+
'Use a Node release that contains nodejs/node#65946 (not in any release through 24.21.0), or Node 22 / 24.18.1;',
96+
'or rebuild each listed copy against 24.18.1 headers:',
97+
'cd <copy> && npx node-gyp rebuild --release --nodedir=<path to node 24.18.1 headers> ;',
98+
'or install the 12.x prebuilt (npm install better-sqlite3@12 in the project).',
99+
'ruflo itself opens AgentDB through its own prebuilt 12.x copy, so a flagged nested copy matters only to code that loads it directly.',
100+
].join(' ');
101+
102+
/** Read-only: warn when a locally compiled better-sqlite3 was built against Node >= 24.19 headers on an affected runtime. */
103+
export async function checkNativeAddonHeaders(deps: NativeAddonCheckDeps = {}): Promise<NativeAddonCheck> {
104+
const nodeVersion = deps.nodeVersion ?? process.versions.node;
105+
if (!isAffectedNodeVersion(nodeVersion)) {
106+
return { name: NAME, status: 'pass', message: `Node ${nodeVersion} is not in the affected range (24.19.0-24.21.x)` };
107+
}
108+
const here = dirname(fileURLToPath(import.meta.url));
109+
const copies = deps.copies ?? findBetterSqlite3Copies(deps.startDirs ?? [here, process.cwd()]);
110+
if (copies.length === 0) {
111+
return { name: NAME, status: 'pass', message: `Node ${nodeVersion}: no better-sqlite3 copy found to inspect` };
112+
}
113+
const bad: string[] = [];
114+
for (const copy of copies) {
115+
let gypi: string;
116+
try { gypi = readFileSync(join(copy, 'build', 'config.gypi'), 'utf8'); } catch { continue; }
117+
const headers = headersVersionFromGypi(gypi);
118+
const parsed = headers ? parse(headers) : null;
119+
if (!parsed || parsed[0] !== 24 || parsed[1] < 19) continue;
120+
const version = readJson(join(copy, 'package.json'))?.version;
121+
bad.push(`${copy} (better-sqlite3 ${typeof version === 'string' ? version : '?'}, built against Node ${headers} headers)`);
122+
}
123+
if (bad.length === 0) {
124+
return { name: NAME, status: 'pass', message: `Node ${nodeVersion}: ${copies.length} better-sqlite3 cop${copies.length === 1 ? 'y' : 'ies'} checked, none built against 24.19+ headers` };
125+
}
126+
return {
127+
name: NAME,
128+
status: 'warn',
129+
message: `Node ${nodeVersion} can abort ("Assertion failed: (env) != nullptr", nodejs/node#65446) in: ${bad.join('; ')}`,
130+
fix: FIX,
131+
};
132+
}

‎v3/@claude-flow/cli/src/commands/doctor.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { join, dirname } from 'path';
1212
import { fileURLToPath, pathToFileURL } from 'url';
1313
import { createHash } from 'crypto';
1414
import { ownInstallAncestors } from '../plugins/own-install.js';
15+
import { checkNativeAddonHeaders } from './doctor-native-addon.js';
1516
import { execSync, exec, execFile } from 'child_process';
1617
import { promisify } from 'util';
1718
import { decodeKey, isEncryptionEnabled } from '../encryption/vault.js';
@@ -2669,6 +2670,7 @@ export const doctorCommand: Command = {
26692670
checkMemoryCritiqueCoverage, // #2677 check 6: feedback carries lessons
26702671
]; },
26712672
'memory-package': checkMemoryPackageVersion, // #3392
2673+
'native-addon': () => checkNativeAddonHeaders(), // #4055
26722674
'learning': checkLearningBridge, // #2545
26732675
'learning-bridge': checkLearningBridge, // #2545
26742676
'api': checkApiKeys,
@@ -2794,6 +2796,7 @@ export const doctorCommand: Command = {
27942796
checkMemoryPersistenceDriver, // #2968/#3321 — read-only native capability probe
27952797
checkLearningBridge, // #2545 — can the auto-memory hook actually load @claude-flow/memory?
27962798
checkMemoryPackageVersion, // #3392 — loaded @claude-flow/memory must satisfy the CLI's declared range
2799+
() => checkNativeAddonHeaders(), // #4055 — better-sqlite3 built against Node 24.19+ headers on 24.19-24.21
27972800
checkApiKeys,
27982801
checkMcpServers,
27992802
checkMcpSchemaOverhead, // #2726 — fixed tools/list prompt cost

0 commit comments

Comments
 (0)