π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(cli): route the remaining better-sqlite3 opens through shared-sqlite.ts (#3883)
Nicholas Rueste6eac6786d19
diff --git a/v3/@claude-flow/cli/__tests__/shared-sqlite-remaining-sites-3883.test.ts b/v3/@claude-flow/cli/__tests__/shared-sqlite-remaining-sites-3883.test.tsnew file mode 100644index 0000000000..4f1560bd4d--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/shared-sqlite-remaining-sites-3883.test.ts@@ -0,0 +1,108 @@+/**+ * #3883 β follow-up to #3693/#3871: the remaining read-write better-sqlite3+ * opens must resolve the constructor through the shared loader+ * (`../src/memory/shared-sqlite.ts`), not a separately-imported copy of the+ * package, so the CLI shares AgentDB's native better-sqlite3 identity.+ *+ * Each fixed call site is proven to route through `loadBetterSqlite3()` by+ * mocking that export and observing an outcome the call site can only+ * produce by going through the mock (a specific skip reason / thrown+ * message, or the spy being invoked during a real, successful restore) β+ * never a direct `import('better-sqlite3')` bypassing it.+ */+import { afterEach, describe, expect, it, vi } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++let RealDatabase: any;+let haveNative = false;+try {+ RealDatabase = (await import('better-sqlite3')).default;+ haveNative = true;+} catch {+ haveNative = false;+}++const loadBetterSqlite3Spy = vi.fn(async () => RealDatabase);++vi.mock('../src/memory/shared-sqlite.js', () => ({+ loadBetterSqlite3: loadBetterSqlite3Spy,+ resolveAgentdbBetterSqlite3: () => RealDatabase,+}));++afterEach(() => {+ loadBetterSqlite3Spy.mockReset();+ loadBetterSqlite3Spy.mockImplementation(async () => RealDatabase);+});++describe('#3883 remaining shared-sqlite call sites', () => {+ it('memory-distillation.ts runDistillation() loads Database via the shared loader', async () => {+ if (!haveNative) return;+ const { runDistillation } = await import('../src/services/memory-distillation.js');+ const dir = mkdtempSync(join(tmpdir(), 'ruflo-3883-distill-'));+ const dbPath = join(dir, 'memory.db');+ writeFileSync(dbPath, '');++ const report = await runDistillation({ dbPath, dryRun: true });++ expect(loadBetterSqlite3Spy).toHaveBeenCalledTimes(1);+ expect(report.skipped).toBe('no memory_entries');+ });++ it('memory-distillation.ts maps a shared-loader failure to its own skip reason', async () => {+ if (!haveNative) return;+ loadBetterSqlite3Spy.mockImplementation(async () => {+ throw new Error('better-sqlite3 not installed');+ });+ const { runDistillation } = await import('../src/services/memory-distillation.js');+ const dir = mkdtempSync(join(tmpdir(), 'ruflo-3883-distill-skip-'));+ const dbPath = join(dir, 'memory.db');+ writeFileSync(dbPath, '');++ const report = await runDistillation({ dbPath, dryRun: true });++ expect(loadBetterSqlite3Spy).toHaveBeenCalledTimes(1);+ expect(report.skipped).toBe('better-sqlite3 unavailable');+ });++ it('distill-tuning.ts tuneDistillation() loads Database via the shared loader (no local shadow)', async () => {+ if (!haveNative) return;+ loadBetterSqlite3Spy.mockImplementation(async () => {+ throw new Error('better-sqlite3 not installed');+ });+ const { tuneDistillation } = await import('../src/services/distill-tuning.js');+ const dir = mkdtempSync(join(tmpdir(), 'ruflo-3883-tune-'));+ const dbPath = join(dir, 'memory.db');+ writeFileSync(dbPath, '');++ await expect(tuneDistillation({ dbPath })).rejects.toThrow(+ 'tuneDistillation: better-sqlite3 unavailable β cannot run the tuning harness',+ );+ expect(loadBetterSqlite3Spy).toHaveBeenCalledTimes(1);+ });++ it('memory-backup.ts restoreMemoryDbFromBackup() loads Database via the shared loader during a real restore', async () => {+ if (!haveNative) return;+ const { restoreMemoryDbFromBackup } = await import('../src/services/memory-backup.js');+ const dir = mkdtempSync(join(tmpdir(), 'ruflo-3883-backup-'));+ const destDir = join(dir, 'backups');+ mkdirSync(destDir, { recursive: true });++ // Snapshot filename must match isSnapshotFor()'s prefix + ISO-stamp regex+ // for a 'memory.db' target.+ const snapPath = join(destDir, 'memory-2024-01-01T00-00-00-000Z.db');+ const seed = new RealDatabase(snapPath);+ seed.exec('CREATE TABLE memory_entries (id TEXT)');+ seed.prepare('INSERT INTO memory_entries VALUES (?)').run('x1');+ seed.close();++ const dbPath = join(dir, 'memory.db');+ const result = await restoreMemoryDbFromBackup(dbPath, { destDir });++ expect(loadBetterSqlite3Spy).toHaveBeenCalled();+ expect(result.restored).toBe(true);+ expect(result.rows).toBe(1);+ expect(existsSync(dbPath)).toBe(true);+ });+});diff --git a/v3/@claude-flow/cli/src/services/distill-tuning.ts b/v3/@claude-flow/cli/src/services/distill-tuning.tsindex 1d2b0c6f0f..42b0f24b40 100644--- a/v3/@claude-flow/cli/src/services/distill-tuning.ts+++ b/v3/@claude-flow/cli/src/services/distill-tuning.ts@@ -44,6 +44,7 @@ import * as crypto from 'crypto';import { runDistillation, type DistillOptions } from './memory-distillation.js';import { distillTrajectoryContent } from '../memory/structured-distill.js';import { cosineSim } from '../memory/hybrid-retrieval.js';+import { loadBetterSqlite3 } from '../memory/shared-sqlite.js';// ββ Public types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -213,7 +214,21 @@ export async function tuneDistillation(options: TuneDistillationOptions): Promisthrow new Error(`tuneDistillation: source db not found at ${dbPath}`);}- const Database = await loadBetterSqlite3();+ // #3883 β resolve the SAME better-sqlite3 copy AgentDB resolves (shared-sqlite.ts),+ // not a separately-imported copy. Verified: every `new Database(...)` call in this+ // module (readCopy below, and tmpCopy inside evaluateCandidate) opens a temp file+ // copy made via fs.copyFileSync β `dbPath`/`sourceDbPath` themselves are NEVER+ // opened with a DB connection anywhere in this module (see module header+ // "Isolation" section). So the #3693 identity hazard (two better-sqlite3 copies+ // fighting over one live file's -wal/-shm sidecars) does not apply to today's+ // call sites here β AgentDB never holds a live handle on a temp copy. This swap+ // is for consistency with the shared loader's contract, not an active fix.+ let Database: any;+ try {+ Database = await loadBetterSqlite3();+ } catch {+ Database = null;+ }if (!Database) {throw new Error('tuneDistillation: better-sqlite3 unavailable β cannot run the tuning harness');}@@ -684,12 +699,3 @@ function safeUnlink(p: string): void {}}}--async function loadBetterSqlite3(): Promise<any | null> {- try {- const mod: string = 'better-sqlite3';- return (await import(mod)).default;- } catch {- return null;- }-}diff --git a/v3/@claude-flow/cli/src/services/memory-backup.ts b/v3/@claude-flow/cli/src/services/memory-backup.tsindex 06e584ad72..bf4bc57af0 100644--- a/v3/@claude-flow/cli/src/services/memory-backup.ts+++ b/v3/@claude-flow/cli/src/services/memory-backup.ts@@ -15,6 +15,7 @@import * as fs from 'fs';import * as path from 'path';import { readFileMaybeEncrypted } from '../fs-secure.js';+import { loadBetterSqlite3 } from '../memory/shared-sqlite.js';export interface BackupOptions {/** Source DB (default: <cwd>/.swarm/memory.db). */@@ -245,8 +246,7 @@ export async function restoreMemoryDbFromBackup(// encrypted snapshots and provides the same checks on WASM-only hosts.let Database: any = null;try {- const mod: string = 'better-sqlite3';- Database = (await import(mod)).default;+ Database = await loadBetterSqlite3();} catch {/* use the sql.js verifier */}diff --git a/v3/@claude-flow/cli/src/services/memory-distillation.ts b/v3/@claude-flow/cli/src/services/memory-distillation.tsindex 76e2728114..0dac703602 100644--- a/v3/@claude-flow/cli/src/services/memory-distillation.ts+++ b/v3/@claude-flow/cli/src/services/memory-distillation.ts@@ -28,6 +28,7 @@ import * as fs from 'fs';import * as path from 'path';import { distillTrajectoryContent, serialiseDistilled } from '../memory/structured-distill.js';+import { loadBetterSqlite3 } from '../memory/shared-sqlite.js';export type DistillProvenance = 'oracle:test-exec' | 'judge:fable' | 'proxy:structural';@@ -150,8 +151,7 @@ export async function runDistillation(options: DistillOptions): Promise<DistillRlet Database: any;try {- const mod: string = 'better-sqlite3';- Database = (await import(mod)).default;+ Database = await loadBetterSqlite3();} catch {return emptyReport(dryRun, { skipped: 'better-sqlite3 unavailable' });}