π 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(doctor): check native AgentDB store integrity
Rudy Celekli6096bcaebf9f
diff --git a/v3/@claude-flow/cli/__tests__/doctor-2737-memory-structural.test.ts b/v3/@claude-flow/cli/__tests__/doctor-2737-memory-structural.test.tsindex 109b8b3565..4f6594052a 100644--- a/v3/@claude-flow/cli/__tests__/doctor-2737-memory-structural.test.ts+++ b/v3/@claude-flow/cli/__tests__/doctor-2737-memory-structural.test.ts@@ -30,7 +30,7 @@* in isolation) is what's under test.*/-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+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';@@ -67,6 +67,7 @@ describe('doctor #2737 β bare `doctor` actually opens memory.db', () => {});afterEach(() => {+ vi.unstubAllEnvs();process.chdir(ORIGINAL_CWD);_resetMemoryRootCache();try {@@ -113,6 +114,58 @@ describe('doctor #2737 β bare `doctor` actually opens memory.db', () => {const presence = findCheck(data.results, 'Memory Database Presence');expect(presence?.status).toBe('pass');+ expect(findCheck(data.results, 'Native AgentDB Structural Integrity')).toBeUndefined();+ }, 20000);++ it('fails when the native AgentDB file is corrupt even though memory.db is healthy (#3195)', async () => {+ const Database = (await import('better-sqlite3')).default as any;+ mkdirSync(join(workdir, '.swarm'), { recursive: true });+ const db = new Database(join(workdir, '.swarm', 'memory.db'));+ db.exec('CREATE TABLE memory_entries (id INTEGER PRIMARY KEY, content TEXT)');+ db.close();+ const nativePath = join(workdir, '.swarm', 'agentdb-memory.db');+ writeFileSync(nativePath, Buffer.from('not a SQLite database'.repeat(8)));++ for (const component of [undefined, 'memory']) {+ const result = await runDoctor(component);+ const data = result.data as DoctorData;+ const native = findCheck(data.results, 'Native AgentDB Structural Integrity');+ expect(native?.status).toBe('fail');+ expect(native?.message).toContain(nativePath);+ expect(data.failed).toBeGreaterThan(0);+ expect(result.success).toBe(false);++ const legacy = findCheck(data.results, component ? 'Memory Integrity' : 'Memory Structural Integrity');+ expect(legacy?.status).toBe('pass');+ expect(legacy?.message).toContain('memory.db');+ }+ }, 30000);++ it('passes the native check for a healthy AgentDB sibling', async () => {+ const Database = (await import('better-sqlite3')).default as any;+ mkdirSync(join(workdir, '.swarm'), { recursive: true });+ const nativePath = join(workdir, '.swarm', 'agentdb-memory.db');+ const db = new Database(nativePath);+ db.exec('CREATE TABLE native_entries (id INTEGER PRIMARY KEY)');+ db.close();++ const result = await runDoctor('memory');+ const native = findCheck((result.data as DoctorData).results, 'Native AgentDB Structural Integrity');+ expect(native?.status).toBe('pass');+ expect(native?.message).toContain(`${nativePath} β PRAGMA quick_check: ok`);+ }, 20000);++ it('finds a native sibling next to an explicitly configured database path', async () => {+ const customDir = join(workdir, 'custom-memory');+ mkdirSync(customDir, { recursive: true });+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', join(customDir, 'custom.db'));+ const nativePath = join(customDir, 'agentdb-memory.db');+ writeFileSync(nativePath, Buffer.from('not a SQLite database'.repeat(8)));++ const result = await runDoctor('memory');+ const native = findCheck((result.data as DoctorData).results, 'Native AgentDB Structural Integrity');+ expect(native?.status).toBe('fail');+ expect(native?.message).toContain(nativePath);}, 20000);it('malformed/corrupt DB β default `doctor` run FAILS the new structural check and does not report all-healthy', async () => {diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.tsindex 5a0099f2ac..791d998a0c 100644--- a/v3/@claude-flow/cli/src/commands/doctor.ts+++ b/v3/@claude-flow/cli/src/commands/doctor.ts@@ -333,6 +333,22 @@ async function resolveMemoryDbPath(): Promise<string | null> {return null;}+/** Native AgentDB writes to a plaintext sibling of the sql.js memory file.+ * Probe only stores that already exist: projects without the native bridge+ * should not acquire an extra warning just by running doctor (#3195). */+async function existingNativeAgentDbPaths(): Promise<string[]> {+ const candidates = new Set<string>();+ try {+ const { getMemoryRoot, resolveDbPath } = await import('../memory/memory-initializer.js');+ candidates.add(join(getMemoryRoot(), 'agentdb-memory.db'));+ // Explicit CLAUDE_FLOW_DB_PATH callers may put the sibling elsewhere.+ candidates.add(join(dirname(resolveDbPath()), 'agentdb-memory.db'));+ } catch {+ candidates.add(join(process.cwd(), '.swarm', 'agentdb-memory.db'));+ }+ return [...candidates].filter((path) => existsSync(path));+}+/** Open a sql.js Database over an on-disk file, returning null when the* file can't be opened as a SQLite database (encrypted / corrupted / not* a database). Callers decide whether that's warn or fail. */@@ -539,6 +555,76 @@ async function checkMemoryStructuralIntegrity(): Promise<HealthCheck> {}}+/** Check the AgentDB authority independently from the legacy memory.db.+ * Opening read-only with SQLite keeps WAL commits visible without mutating+ * either store; the existing legacy health checks retain their own scope. */+async function checkNativeAgentDbStructuralIntegrity(dbPath: string): Promise<HealthCheck> {+ const NAME = 'Native AgentDB Structural Integrity (quick_check)';+ if (!existsSync(dbPath)) {+ return { name: NAME, status: 'warn', message: `${dbPath} disappeared before the native check could run` };+ }+ if (isMemoryDbEncryptedAtRest(dbPath)) {+ return {+ name: NAME,+ status: 'fail',+ message: `${dbPath} β RFE1-encrypted; native AgentDB requires a plaintext SQLite file`,+ fix: `back up ${dbPath} and restore a usable native AgentDB database`,+ };+ }++ let Database: any;+ try {+ Database = ((await import('better-sqlite3')) as any).default;+ } catch {+ return {+ name: NAME,+ status: 'warn',+ message: `${dbPath} β better-sqlite3 not installed; native AgentDB structural health is unverified`,+ fix: 'install better-sqlite3 with npm install scripts enabled, then rerun this check',+ };+ }++ let db: any;+ try {+ db = new Database(dbPath, { readonly: true, fileMustExist: true });+ } catch (error) {+ if (isNativeSqliteBindingUnavailable(error)) {+ return nativeBindingUnavailableCheck(NAME, dbPath, error, '[native AgentDB structural health unverified]');+ }+ const message = error instanceof Error ? error.message : String(error);+ return {+ name: NAME,+ status: 'fail',+ message: `${dbPath} β better-sqlite3 failed to open: ${message} [native AgentDB]`,+ fix: `back up ${dbPath} and its WAL sidecars, then restore a known-good native AgentDB database`,+ };+ }++ try {+ const rows = db.pragma('quick_check') as Array<Record<string, unknown>>;+ const values = rows.map((row) => String(Object.values(row)[0]));+ if (values.length === 1 && values[0] === 'ok') {+ return { name: NAME, status: 'pass', message: `${dbPath} β PRAGMA quick_check: ok [native AgentDB, WAL-aware]` };+ }+ return {+ name: NAME,+ status: 'fail',+ message: `${dbPath} β PRAGMA quick_check: ${values.slice(0, 3).join('; ')}${values.length > 3 ? ` (+${values.length - 3} more)` : ''} [native AgentDB]`,+ fix: `back up ${dbPath} and its WAL sidecars, then restore a known-good native AgentDB database`,+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return {+ name: NAME,+ status: 'fail',+ message: `${dbPath} β quick_check probe threw: ${message} [native AgentDB]`,+ fix: `back up ${dbPath} and its WAL sidecars, then restore a known-good native AgentDB database`,+ };+ } finally {+ try { db.close(); } catch { /* best-effort */ }+ }+}+// #2968/#3321 β read-only native SQLite capability probe. A skipped// postinstall can leave the wrapper importable but its binding unavailable.// Schema size cannot identify the runtime driver or the database's history:@@ -2495,6 +2581,9 @@ export const doctorCommand: Command = {output.writeln(output.dim('β'.repeat(50)));output.writeln();+ const nativeAgentDbChecks = (await existingNativeAgentDbPaths())+ .map((dbPath) => () => checkNativeAgentDbStructuralIntegrity(dbPath));+const allChecks: (() => Promise<HealthCheck>)[] = [checkVersionFreshness,checkNodeVersion,@@ -2507,6 +2596,7 @@ export const doctorCommand: Command = {checkDaemonStatus,checkMemoryDatabase,checkMemoryStructuralIntegrity, // #2737 β bounded, native quick_check on every default run+ ...nativeAgentDbChecks, // #3195 β verify each present native authority filecheckMemoryPersistenceDriver, // #2968/#3321 β read-only native capability probecheckLearningBridge, // #2545 β can the auto-memory hook actually load @claude-flow/memory?checkMemoryPackageVersion, // #3392 β loaded @claude-flow/memory must satisfy the CLI's declared range@@ -2547,6 +2637,7 @@ export const doctorCommand: Command = {'memory': [checkMemoryDatabase, // existing: exists + statable (unchanged)checkMemoryIntegrity, // #2677 check 1: sql.js open + PRAGMA integrity_check+ ...nativeAgentDbChecks, // #3195: present AgentDB authority, checked independentlycheckMemoryPersistenceDriver, // #2968/#3321: read-only native capability probecheckMemoryPackageVersion, // #3392: loaded memory package satisfies the declared rangecheckMemoryContent, // #2677 check 2: memory_entries content coverage