Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(doctor): report missing native sqlite bindings

dajiaohuang5c676fe242e8
diff --git a/v3/@claude-flow/cli/__tests__/doctor-native-binding-2968.test.ts b/v3/@claude-flow/cli/__tests__/doctor-native-binding-2968.test.ts
new file mode 100644
index 0000000000..add05f3538
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/doctor-native-binding-2968.test.ts
@@ -0,0 +1,75 @@
+/**
+ * Regression coverage for #2968: better-sqlite3's JavaScript wrapper can be
+ * installed while its native addon is absent because postinstall did not run.
+ * Doctor must report capability loss, not accuse the database of corruption.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+vi.mock('better-sqlite3', () => ({
+ default: class MissingNativeBinding {
+ constructor() {
+ throw new Error('Could not locate the bindings file. Tried:\n β†’ better_sqlite3.node');
+ }
+ },
+}));
+
+import { doctorCommand } from '../src/commands/doctor.js';
+import { _resetMemoryRootCache } from '../src/memory/memory-initializer.js';
+
+type HealthCheck = { name: string; status: 'pass' | 'warn' | 'fail'; message: string };
+type DoctorData = { results: HealthCheck[] };
+
+const originalCwd = process.cwd();
+let workdir: string;
+
+async function runDoctor(component?: string) {
+ const ctx = {
+ flags: component ? { component } : {},
+ args: [],
+ config: {} as Record<string, unknown>,
+ } as unknown as Parameters<NonNullable<typeof doctorCommand.action>>[0];
+ return doctorCommand.action!(ctx);
+}
+
+function findCheck(results: HealthCheck[], name: string): HealthCheck | undefined {
+ return results.find((result) => result.name.includes(name));
+}
+
+describe('doctor #2968 β€” missing better-sqlite3 native binding', () => {
+ beforeEach(() => {
+ workdir = mkdtempSync(join(tmpdir(), 'doctor-2968-'));
+ process.chdir(workdir);
+ mkdirSync(join(workdir, '.swarm'), { recursive: true });
+ writeFileSync(join(workdir, '.swarm', 'memory.db'), Buffer.from('SQLite format 3\0'.padEnd(256, '\0'), 'binary'));
+ _resetMemoryRootCache();
+ });
+
+ afterEach(() => {
+ process.chdir(originalCwd);
+ _resetMemoryRootCache();
+ rmSync(workdir, { recursive: true, force: true });
+ });
+
+ it('warns in the default structural check without reporting malformed data', async () => {
+ const result = await runDoctor();
+ const check = findCheck((result.data as DoctorData).results, 'Memory Structural Integrity');
+
+ expect(check?.status).toBe('warn');
+ expect(check?.message).toMatch(/native binding is unavailable/i);
+ expect(check?.message).toMatch(/durable WAL-backed persistence unavailable/i);
+ expect(check?.message).not.toMatch(/malformed/i);
+ expect(check?.message).not.toContain('Tried:');
+ }, 20000);
+
+ it('warns in `doctor --component memory` instead of returning a fallback pass', async () => {
+ const result = await runDoctor('memory');
+ const check = findCheck((result.data as DoctorData).results, 'Memory Integrity');
+
+ expect(check?.status).toBe('warn');
+ expect(check?.message).toMatch(/native binding is unavailable/i);
+ expect(check?.message).not.toMatch(/malformed/i);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts
index ce1b030475..9408d0f209 100644
--- a/v3/@claude-flow/cli/src/commands/doctor.ts
+++ b/v3/@claude-flow/cli/src/commands/doctor.ts
@@ -387,6 +387,40 @@ function isMemoryDbEncryptedAtRest(dbPath: string): boolean {
}
}
+/**
+ * Distinguish an unavailable native addon from a database that the native
+ * driver opened and found malformed. Importing better-sqlite3 can succeed even
+ * when its postinstall script was skipped: the JavaScript wrapper loads, then
+ * the first Database construction throws because better_sqlite3.node is absent
+ * or incompatible with the active Node ABI.
+ */
+function isNativeSqliteBindingUnavailable(error: unknown): boolean {
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
+ return [
+ /Could not locate the bindings file/i,
+ /better_sqlite3\.node/i,
+ /NODE_MODULE_VERSION/i,
+ /compiled against a different Node\.js version/i,
+ /ERR_DLOPEN_FAILED/i,
+ /invalid ELF header/i,
+ /wrong ELF class/i,
+ /not a valid Win32 application/i,
+ /Module did not self-register/i,
+ /no suitable image found/i,
+ ].some((pattern) => pattern.test(message));
+}
+
+function nativeBindingUnavailableCheck(name: string, dbPath: string, error: unknown, suffix: string): HealthCheck {
+ const details = error instanceof Error ? error.message : String(error);
+ const summary = details.split(/\r?\n/, 1)[0].replace(/\s+Tried:\s*$/i, '');
+ return {
+ name,
+ status: 'warn',
+ message: `${dbPath} β€” better-sqlite3 package found, but its native binding is unavailable: ${summary} ${suffix}`,
+ fix: 'reinstall with npm install scripts enabled or run `npm rebuild better-sqlite3`; then rerun this check',
+ };
+}
+
// #2737 part 1 β€” bare `doctor` (no --component flag) never actually opened
// memory.db: checkMemoryDatabase above is existsSync()+statSync() only, so
// it PASSES on any file that exists and can be stat'd, corrupt or not, and
@@ -443,8 +477,8 @@ async function checkMemoryStructuralIntegrity(): Promise<HealthCheck> {
return {
name: NAME,
status: 'warn',
- message: `${dbPath} β€” better-sqlite3 not installed; structural-only check skipped (optional native module)`,
- fix: 'npm install better-sqlite3 (enables WAL-aware structural checks on every `doctor` run)',
+ message: `${dbPath} β€” better-sqlite3 not installed; native WAL-backed persistence and the structural-only check are unavailable`,
+ fix: 'install better-sqlite3 with npm install scripts enabled, then rerun this check',
};
}
@@ -452,6 +486,14 @@ async function checkMemoryStructuralIntegrity(): Promise<HealthCheck> {
try {
db = new Database(dbPath, { readonly: true, fileMustExist: true });
} catch (e) {
+ if (isNativeSqliteBindingUnavailable(e)) {
+ return nativeBindingUnavailableCheck(
+ NAME,
+ dbPath,
+ e,
+ '[structural-only; durable WAL-backed persistence unavailable]',
+ );
+ }
const msg = (e as Error).message || String(e);
// Encryption already ruled out above β€” an unencrypted file
// better-sqlite3 can't even open is definitive corruption.
@@ -523,9 +565,9 @@ async function checkMemoryIntegrity(): Promise<HealthCheck> {
// Prefer native better-sqlite3 (WAL-aware, full integrity_check). Module
// load is isolated in its own try/catch so ONLY "not installed" falls
- // through to the sql.js fallback below β€” once the module loaded, any
- // open/query failure is resolved (fail) right here, not silently
- // reclassified as "sql.js fallback, main-image-only" by an outer catch.
+ // through to the sql.js fallback below. A loaded JavaScript wrapper can
+ // still lack its native binding (#2968); that capability failure is a warn,
+ // while genuine open/query failures remain authoritative failures here.
let Database: any;
try {
Database = ((await import('better-sqlite3')) as any).default;
@@ -538,6 +580,14 @@ async function checkMemoryIntegrity(): Promise<HealthCheck> {
try {
db = new Database(dbPath, { readonly: true, fileMustExist: true });
} catch (e) {
+ if (isNativeSqliteBindingUnavailable(e)) {
+ return nativeBindingUnavailableCheck(
+ 'Memory Integrity',
+ dbPath,
+ e,
+ '[native WAL-backed persistence unavailable]',
+ );
+ }
const msg = (e as Error).message || String(e);
return {
name: 'Memory Integrity',
@@ -594,7 +644,12 @@ async function checkMemoryIntegrity(): Promise<HealthCheck> {
const res = db.exec('PRAGMA integrity_check');
const rows: string[] = res[0]?.values?.map((v: any[]) => String(v[0])) ?? [];
if (rows.length === 1 && rows[0] === 'ok') {
- return { name: 'Memory Integrity', status: 'pass', message: `${dbPath} β€” PRAGMA integrity_check: ok [main-image-only fallback β€” sql.js can't see WAL-only data; install better-sqlite3 for full coverage]` };
+ return {
+ name: 'Memory Integrity',
+ status: 'warn',
+ message: `${dbPath} β€” PRAGMA integrity_check: ok, but only for the main image [sql.js fallback; native WAL-backed persistence unavailable]`,
+ fix: 'install better-sqlite3 with npm install scripts enabled, then rerun this check',
+ };
}
return {
name: 'Memory Integrity',