π 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(memory): atomic DB flushes + backup auto-restore for AgentDB corruption (#2584) (#2585)
rUv626bb7993192
diff --git a/.claude/helpers/metrics-db.mjs b/.claude/helpers/metrics-db.mjsindex 3e883eb507..db713ea3f2 100755--- a/.claude/helpers/metrics-db.mjs+++ b/.claude/helpers/metrics-db.mjs@@ -6,7 +6,7 @@*/import initSqlJs from 'sql.js';-import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'fs';+import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync, openSync, writeSync, fsyncSync, closeSync, renameSync, rmSync } from 'fs';import { dirname, join, basename } from 'path';import { fileURLToPath } from 'url';import { execSync } from 'child_process';@@ -138,7 +138,22 @@ async function initDatabase() {function persist() {const data = db.export();const buffer = Buffer.from(data);- writeFileSync(DB_PATH, buffer);+ // Atomic write (issue #2584): temp β fsync β rename so a kill/OOM mid-flush+ // or a concurrent writer can't leave a torn, malformed metrics.db image.+ const tmp = `${DB_PATH}.tmp-${process.pid}-${Date.now().toString(36)}`;+ let fd;+ try {+ fd = openSync(tmp, 'wx');+ if (buffer.length > 0) writeSync(fd, buffer, 0, buffer.length, 0);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(tmp, DB_PATH);+ } catch (e) {+ if (fd !== undefined) { try { closeSync(fd); } catch { /* */ } }+ try { rmSync(tmp, { force: true }); } catch { /* */ }+ throw e;+ }}/**diff --git a/v3/@claude-flow/cli/.claude/helpers/metrics-db.mjs b/v3/@claude-flow/cli/.claude/helpers/metrics-db.mjsindex 510ada9c73..f38440fb63 100755--- a/v3/@claude-flow/cli/.claude/helpers/metrics-db.mjs+++ b/v3/@claude-flow/cli/.claude/helpers/metrics-db.mjs@@ -6,7 +6,7 @@*/import initSqlJs from 'sql.js';-import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'fs';+import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync, openSync, writeSync, fsyncSync, closeSync, renameSync, rmSync } from 'fs';import { dirname, join, basename } from 'path';import { fileURLToPath } from 'url';import { execSync } from 'child_process';@@ -138,7 +138,22 @@ async function initDatabase() {function persist() {const data = db.export();const buffer = Buffer.from(data);- writeFileSync(DB_PATH, buffer);+ // Atomic write (issue #2584): temp β fsync β rename so a kill/OOM mid-flush+ // or a concurrent writer can't leave a torn, malformed metrics.db image.+ const tmp = `${DB_PATH}.tmp-${process.pid}-${Date.now().toString(36)}`;+ let fd;+ try {+ fd = openSync(tmp, 'wx');+ if (buffer.length > 0) writeSync(fd, buffer, 0, buffer.length, 0);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(tmp, DB_PATH);+ } catch (e) {+ if (fd !== undefined) { try { closeSync(fd); } catch { /* */ } }+ try { rmSync(tmp, { force: true }); } catch { /* */ }+ throw e;+ }}/**diff --git a/v3/@claude-flow/cli/__tests__/memory-durability-2584.test.ts b/v3/@claude-flow/cli/__tests__/memory-durability-2584.test.tsnew file mode 100644index 0000000000..fb87ac01c3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-durability-2584.test.ts@@ -0,0 +1,132 @@+/**+ * Data-durability regression tests for issue #2584 β AgentDB (sql.js) corruption+ * under torn/concurrent full-image flushes.+ *+ * Covers:+ * 1. writeFileAtomic() β the tempβfsyncβrename primitive that makes every+ * full-image DB flush crash-safe (no torn image, no leftover temp).+ * 2. restoreMemoryDbFromBackup() + recoverMemoryDatabase() β the missing+ * recovery half: when the live image is torn badly enough that an in-place+ * rebuild salvages nothing (the exact ruvultra failure mode), recovery must+ * fall back to the newest integrity-ok backup instead of erroring forever.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { writeFileAtomic } from '../src/fs-secure.js';+import { backupMemoryDb, restoreMemoryDbFromBackup } from '../src/services/memory-backup.js';+import { recoverMemoryDatabase } from '../src/memory/memory-initializer.js';++async function loadSqlite(): Promise<any | null> {+ try { const mod = 'better-sqlite3'; return (await import(mod)).default; } catch { return null; }+}++function makeMemoryDb(Database: any, file: string, rows: number): void {+ const db = new Database(file);+ db.exec('CREATE TABLE memory_entries (id TEXT PRIMARY KEY, namespace TEXT, value TEXT, embedding BLOB)');+ const ins = db.prepare('INSERT INTO memory_entries (id, namespace, value) VALUES (?,?,?)');+ const tx = db.transaction((n: number) => { for (let i = 0; i < n; i++) ins.run('k' + i, 'default', 'v' + i); });+ tx(rows);+ db.close();+}++let tmp: string;+beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'agentdb-2584-')); });+afterEach(() => { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* */ } });++describe('writeFileAtomic (#2584)', () => {+ it('writes content and leaves no temp file behind', () => {+ const p = path.join(tmp, 'a.bin');+ writeFileAtomic(p, Buffer.from('hello'));+ expect(fs.readFileSync(p, 'utf8')).toBe('hello');+ expect(fs.readdirSync(tmp).filter(f => f.includes('.tmp-'))).toHaveLength(0);+ });++ it('overwrites atomically β the new image fully replaces the old', () => {+ const p = path.join(tmp, 'a.bin');+ writeFileAtomic(p, Buffer.alloc(4096, 1));+ writeFileAtomic(p, Buffer.from('x'));+ expect(fs.statSync(p).size).toBe(1);+ expect(fs.readFileSync(p, 'utf8')).toBe('x');+ });++ it('cleans up the temp file if the write throws (bad target dir)', () => {+ // Writing into a non-existent directory throws; no temp should survive.+ const bad = path.join(tmp, 'does-not-exist', 'a.bin');+ expect(() => writeFileAtomic(bad, Buffer.from('x'))).toThrow();+ expect(fs.readdirSync(tmp)).not.toContain('does-not-exist');+ });+});++describe('backup auto-restore fallback (#2584)', () => {+ it('recoverMemoryDatabase restores the newest good backup when the live image is torn', async () => {+ const Database = await loadSqlite();+ if (!Database) return; // native recovery dep absent β nothing to exercise++ const dbPath = path.join(tmp, '.swarm', 'memory.db');+ fs.mkdirSync(path.dirname(dbPath), { recursive: true });+ makeMemoryDb(Database, dbPath, 25);++ // A real, consistent backup via the shipped backup service.+ const bk = await backupMemoryDb({ dbPath, timestamp: 1000 });+ expect(bk.backedUp).toBe(true);++ // Tear the live image: overwrite the header + first pages with 0xFF so+ // integrity_check fails and an in-place rebuild salvages nothing β i.e. the+ // ruvultra case where `sqlite3 .recover` produced 0 rows.+ const size = fs.statSync(dbPath).size;+ const n = Math.min(size, 16384);+ const fd = fs.openSync(dbPath, 'r+');+ fs.writeSync(fd, Buffer.alloc(n, 0xff), 0, n, 0);+ fs.closeSync(fd);++ const rec = await recoverMemoryDatabase(dbPath, { verbose: false });+ expect(rec.recovered).toBe(true);+ expect(rec.restoredFromBackup).toBe(true);++ // The restored DB is healthy and has the data back.+ const db = new Database(dbPath, { readonly: true });+ const integ = String(db.pragma('integrity_check', { simple: true }));+ const count = (db.prepare('SELECT COUNT(*) AS c FROM memory_entries').get() as { c: number }).c;+ db.close();+ expect(integ.toLowerCase()).toBe('ok');+ expect(count).toBe(25);++ // The corrupt original was parked, not silently discarded.+ const parked = fs.readdirSync(path.dirname(dbPath)).some(f => f.startsWith('memory.db.corrupt-'));+ expect(parked).toBe(true);+ });++ it('restoreMemoryDbFromBackup reports no-backups when the dir is empty', async () => {+ const Database = await loadSqlite();+ if (!Database) return;+ const dbPath = path.join(tmp, '.swarm', 'memory.db');+ fs.mkdirSync(path.dirname(dbPath), { recursive: true });+ makeMemoryDb(Database, dbPath, 3);+ const r = await restoreMemoryDbFromBackup(dbPath);+ expect(r.restored).toBe(false);+ expect(r.skipped).toMatch(/no-backups/);+ });++ it('restoreMemoryDbFromBackup skips a corrupt backup and picks an older good one', async () => {+ const Database = await loadSqlite();+ if (!Database) return;+ const dbPath = path.join(tmp, '.swarm', 'memory.db');+ const backups = path.join(tmp, '.swarm', 'backups');+ fs.mkdirSync(backups, { recursive: true });+ makeMemoryDb(Database, dbPath, 10);++ // Older good backup, newer torn backup β restore must pick the older good one.+ const good = path.join(backups, 'memory-2020-01-01T00-00-00-000Z.db');+ const bad = path.join(backups, 'memory-2020-01-02T00-00-00-000Z.db');+ makeMemoryDb(Database, good, 10);+ makeMemoryDb(Database, bad, 10);+ const fd = fs.openSync(bad, 'r+'); fs.writeSync(fd, Buffer.alloc(16384, 0xff), 0, 16384, 0); fs.closeSync(fd);++ const r = await restoreMemoryDbFromBackup(dbPath, { timestamp: 2000 });+ expect(r.restored).toBe(true);+ expect(r.from).toBe(good);+ expect(r.rows).toBe(10);+ });+});diff --git a/v3/@claude-flow/cli/src/fs-secure.ts b/v3/@claude-flow/cli/src/fs-secure.tsindex a4e5b69158..9985a5088f 100644--- a/v3/@claude-flow/cli/src/fs-secure.ts+++ b/v3/@claude-flow/cli/src/fs-secure.ts@@ -17,7 +17,18 @@* incremental migration.*/-import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ closeSync,+ fsyncSync,+ mkdirSync,+ openSync,+ readFileSync,+ renameSync,+ unlinkSync,+ writeSync,+} from 'node:fs';+import { basename, dirname, join } from 'node:path';import {decryptBuffer,encryptBuffer,@@ -26,6 +37,74 @@ import {isEncryptionEnabled,} from './encryption/vault.js';+/**+ * Crash-safe atomic file write (issue #2584).+ *+ * A plain `writeFileSync(dbPath, db.export())` of a large sql.js image is NOT+ * crash-safe: a kill/OOM mid-write β or a second process rewriting the same+ * path concurrently β leaves a half-written image, and reopening it yields+ * `database disk image is malformed`. The corruption window scales with file+ * size, so a 185 MB monolithic flush is especially exposed.+ *+ * This writes to a unique temp sibling, fsyncs the bytes to disk, then+ * `rename()`s over the target. rename() is atomic on POSIX within one+ * filesystem, so a reader/reopen sees either the old complete image or the new+ * complete image β never a torn one. The directory entry is best-effort fsynced+ * so the rename itself survives a crash. On any failure the temp file is+ * removed and the original is left untouched.+ */+export function writeFileAtomic(+ path: string,+ data: Buffer,+ opts: { mode?: number } = {},+): void {+ const mode = opts.mode ?? 0o600;+ const dir = dirname(path);+ const tmp = join(+ dir,+ `.${basename(path)}.tmp-${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,+ );+ let fd: number | undefined;+ try {+ fd = openSync(tmp, 'wx', mode);+ if (data.length > 0) writeSync(fd, data, 0, data.length, 0);+ fsyncSync(fd); // durability: force bytes to disk BEFORE the rename+ closeSync(fd);+ fd = undefined;+ renameSync(tmp, path); // atomic swap β readers never see a torn image+ try {+ chmodSync(path, mode);+ } catch {+ // Windows / FS without POSIX modes β silently skip.+ }+ // Best-effort: fsync the directory so the rename survives a power loss.+ try {+ const dfd = openSync(dir, 'r');+ try {+ fsyncSync(dfd);+ } finally {+ closeSync(dfd);+ }+ } catch {+ // Directory fsync unsupported (e.g. Windows) β the rename is still atomic.+ }+ } catch (e) {+ if (fd !== undefined) {+ try {+ closeSync(fd);+ } catch {+ /* already closed */+ }+ }+ try {+ unlinkSync(tmp);+ } catch {+ /* temp never created / already gone */+ }+ throw e;+ }+}+/*** Create a directory tree with mode 0700 (owner-only). No-op if exists.* Uses recursive: true so missing parents are created with the same mode.@@ -77,19 +156,11 @@ export function writeFileRestricted(payload = encryptBuffer(plaintext, getKey());}- // For encrypted payloads we always have a Buffer β pass through without an- // encoding so writeFileSync doesn't try to text-decode it.- if (Buffer.isBuffer(payload)) {- writeFileSync(path, payload);- } else {- writeFileSync(path, payload, encoding);- }-- try {- chmodSync(path, 0o600);- } catch {- // Windows / FS without POSIX modes β silently skip.- }+ // Atomic write (temp β fsync β rename) so a torn/concurrent flush can never+ // leave a half-written file β the failure mode behind issue #2584. Buffers go+ // straight through; strings are encoded first (default utf-8).+ const buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, encoding);+ writeFileAtomic(path, buf, { mode: 0o600 });}/**diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.tsindex c6ef105cc2..e8f839cac4 100644--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts@@ -12,7 +12,8 @@import * as fs from 'fs';import * as path from 'path';import { createRequire } from 'node:module';-import { readFileMaybeEncrypted, writeFileRestricted } from '../fs-secure.js';+import { readFileMaybeEncrypted, writeFileAtomic, writeFileRestricted } from '../fs-secure.js';+import { restoreMemoryDbFromBackup } from '../services/memory-backup.js';/*** #2356 β cached, synchronous capability probe for @ruvector/core. `getHNSWStatus`@@ -1368,9 +1369,20 @@ async function activateControllerRegistry(export async function recoverMemoryDatabase(dbPath: string,opts: { verbose?: boolean } = {},-): Promise<{ recovered: boolean; backupPath?: string; rows?: number; reason?: string }> {+): Promise<{ recovered: boolean; backupPath?: string; rows?: number; reason?: string; restoredFromBackup?: boolean; from?: string; restoreReason?: string }> {if (!dbPath || !fs.existsSync(dbPath)) return { recovered: false, reason: 'no-db' };+ // Fallback for when the in-place rebuild can't produce a verified DB (issue+ // #2584): rebuild-from-corrupt salvages nothing when the damage is total, so+ // restore the newest integrity-ok backup instead of leaving the store dead.+ const restoreFromBackup = async (reason: string) => {+ const r = await restoreMemoryDbFromBackup(dbPath, { verbose: opts.verbose });+ if (r.restored) {+ return { recovered: true, restoredFromBackup: true, backupPath: r.corruptBackupPath, rows: r.rows, from: r.from };+ }+ return { recovered: false, reason, restoreReason: r.skipped };+ };+let Database: any;try {// Module name behind a variable so TS does not statically resolve the@@ -1378,7 +1390,7 @@ export async function recoverMemoryDatabase(const mod: string = 'better-sqlite3';Database = (await import(mod)).default;} catch {- return { recovered: false, reason: 'no-native' };+ return await restoreFromBackup('no-native');}const ts = Date.now();@@ -1457,9 +1469,9 @@ export async function recoverMemoryDatabase(if (integ.toLowerCase() !== 'ok' || dstRows < srcRows) {try { fs.rmSync(tmpPath, { force: true }); } catch { /* */ }if (opts.verbose) {- console.log(`memory DB auto-recovery aborted (integrity=${integ}, rows ${dstRows}/${srcRows}) β original untouched`);+ console.log(`memory DB rebuild-in-place failed (integrity=${integ}, rows ${dstRows}/${srcRows}) β trying newest good backup`);}- return { recovered: false, reason: 'verify-failed' };+ return await restoreFromBackup('verify-failed');}// Back up the corrupt DB, then atomically swap in the verified rebuild.@@ -1476,8 +1488,8 @@ export async function recoverMemoryDatabase(try { src?.exec('ROLLBACK'); } catch { /* */ }try { src?.close(); } catch { /* */ }try { fs.rmSync(tmpPath, { force: true }); } catch { /* */ }- if (opts.verbose) console.log(`memory DB auto-recovery error: ${(e as Error)?.message ?? e}`);- return { recovered: false, reason: 'error' };+ if (opts.verbose) console.log(`memory DB rebuild-in-place error (${(e as Error)?.message ?? e}) β trying newest good backup`);+ return await restoreFromBackup('error');}}@@ -1945,9 +1957,9 @@ export async function applyTemporalDecay(dbPath?: string): Promise<{const changes = db.getRowsModified();- // Save+ // Save (atomic β issue #2584: a torn full-image flush corrupts the store)const data = db.export();- fs.writeFileSync(path_, Buffer.from(data));+ writeFileAtomic(path_, Buffer.from(data));db.close();return {diff --git a/v3/@claude-flow/cli/src/services/memory-backup.ts b/v3/@claude-flow/cli/src/services/memory-backup.tsindex a6e754f773..44ae4d9a57 100644--- a/v3/@claude-flow/cli/src/services/memory-backup.ts+++ b/v3/@claude-flow/cli/src/services/memory-backup.ts@@ -108,3 +108,103 @@ export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupRe}return { backedUp: true, path: destPath, sizeBytes, rotatedAway, gcsUri };}++export interface RestoreResult {+ restored: boolean;+ /** The backup file that was restored. */+ from?: string;+ /** memory_entries count in the restored DB (-1 if it couldn't be verified). */+ rows?: number;+ /** Where the corrupt live DB was parked before the swap. */+ corruptBackupPath?: string;+ skipped?: string;+}++/**+ * Restore the newest integrity-ok backup over a corrupt/malformed memory DB+ * (issue #2584).+ *+ * The in-place rebuild path (`recoverMemoryDatabase`) rebuilds FROM the corrupt+ * image, so when the damage is bad enough that `sqlite3 .recover` salvages+ * nothing, that rebuild also salvages nothing and every `memory_store` keeps+ * erroring. This is the missing fallback: scan `<db dir>/backups/` newest-first,+ * pick the newest snapshot that passes `PRAGMA integrity_check` (and has rows),+ * park the corrupt live DB at `<db>.corrupt-<ts>.bak`, then ATOMICALLY install+ * the good backup (copy β fsync β rename, no full-image buffer in memory). Drops+ * stale -wal/-shm. Non-destructive on failure: the live DB is only replaced once+ * a verified backup is in hand.+ */+export async function restoreMemoryDbFromBackup(+ dbPath: string,+ opts: { destDir?: string; timestamp?: number; verbose?: boolean } = {},+): Promise<RestoreResult> {+ if (!dbPath) return { restored: false, skipped: 'no-db-path' };+ const destDir = opts.destDir ?? path.join(path.dirname(dbPath), 'backups');++ let snaps: string[];+ try {+ snaps = fs+ .readdirSync(destDir)+ .filter(f => /^memory-.*\.db$/.test(f))+ .map(f => path.join(destDir, f))+ .sort() // ISO-stamped names sort chronologically+ .reverse(); // newest first+ } catch {+ return { restored: false, skipped: 'no-backups-dir' };+ }+ if (!snaps.length) return { restored: false, skipped: 'no-backups' };++ // better-sqlite3 verifies a candidate's integrity. Absent (WASM-only host) β+ // accept the newest non-empty snapshot, flagged rows=-1 (unverified).+ let Database: any = null;+ try {+ const mod: string = 'better-sqlite3';+ Database = (await import(mod)).default;+ } catch {+ /* verifier unavailable β trust newest non-empty */+ }++ let chosen: { file: string; rows: number } | null = null;+ for (const file of snaps) {+ try {+ if (Database) {+ const db = new Database(file, { readonly: true });+ const integ = String(db.pragma('integrity_check', { simple: true }) ?? '');+ let rows = 0;+ try {+ rows = (db.prepare('SELECT COUNT(*) AS c FROM memory_entries').get() as { c: number })?.c ?? 0;+ } catch { /* no entries table β not a usable memory DB */ }+ db.close();+ if (integ.toLowerCase() === 'ok' && rows > 0) { chosen = { file, rows }; break; }+ } else if (fs.statSync(file).size > 0) {+ chosen = { file, rows: -1 };+ break;+ }+ } catch { /* unreadable snapshot β try the next-older one */ }+ }+ if (!chosen) return { restored: false, skipped: 'no-integrity-ok-backup' };++ const ts = opts.timestamp ?? Date.now();+ const corruptBackupPath = `${dbPath}.corrupt-${ts}.bak`;+ const tmp = `${dbPath}.restoring-${ts}`;+ try {+ if (fs.existsSync(dbPath)) fs.copyFileSync(dbPath, corruptBackupPath);+ fs.copyFileSync(chosen.file, tmp); // stream copy β no 185MB buffer+ const fd = fs.openSync(tmp, 'r+');+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } // durable before swap+ fs.renameSync(tmp, dbPath); // atomic install+ for (const s of ['-wal', '-shm']) { try { fs.rmSync(`${dbPath}${s}`, { force: true }); } catch { /* */ } }+ } catch (e) {+ try { fs.rmSync(tmp, { force: true }); } catch { /* */ }+ return { restored: false, skipped: `install failed: ${(e as Error)?.message ?? e}` };+ }++ if (opts.verbose) {+ console.log(+ `memory DB restored from backup ${path.basename(chosen.file)}` ++ (chosen.rows >= 0 ? ` (${chosen.rows} rows)` : ' (unverified)') ++ `. Corrupt original saved to ${corruptBackupPath}`,+ );+ }+ return { restored: true, from: chosen.file, rows: chosen.rows, corruptBackupPath };+}diff --git a/v3/@claude-flow/mcp/.claude/helpers/metrics-db.mjs b/v3/@claude-flow/mcp/.claude/helpers/metrics-db.mjsindex 510ada9c73..f38440fb63 100755--- a/v3/@claude-flow/mcp/.claude/helpers/metrics-db.mjs+++ b/v3/@claude-flow/mcp/.claude/helpers/metrics-db.mjs@@ -6,7 +6,7 @@*/import initSqlJs from 'sql.js';-import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'fs';+import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync, openSync, writeSync, fsyncSync, closeSync, renameSync, rmSync } from 'fs';import { dirname, join, basename } from 'path';import { fileURLToPath } from 'url';import { execSync } from 'child_process';@@ -138,7 +138,22 @@ async function initDatabase() {function persist() {const data = db.export();const buffer = Buffer.from(data);- writeFileSync(DB_PATH, buffer);+ // Atomic write (issue #2584): temp β fsync β rename so a kill/OOM mid-flush+ // or a concurrent writer can't leave a torn, malformed metrics.db image.+ const tmp = `${DB_PATH}.tmp-${process.pid}-${Date.now().toString(36)}`;+ let fd;+ try {+ fd = openSync(tmp, 'wx');+ if (buffer.length > 0) writeSync(fd, buffer, 0, buffer.length, 0);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(tmp, DB_PATH);+ } catch (e) {+ if (fd !== undefined) { try { closeSync(fd); } catch { /* */ } }+ try { rmSync(tmp, { force: true }); } catch { /* */ }+ throw e;+ }}/**