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: silent memory-write loss + daemon lock cwd bypass (#2887, #2878, #2877) (#2966)

rUv1d365d4a6548
diff --git a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
index 87c00a5050..e02d6aa514 100644
--- a/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
+++ b/v3/@claude-flow/cli/__tests__/daemon-autostart.test.ts
@@ -9,6 +9,7 @@ import {
ensureDaemonRunning,
isDaemonAlive,
isRufloProject,
+ resolveDaemonProjectRoot,
} from '../src/services/daemon-autostart.js';
import { applyChampion } from '../src/config/harness-feedback-applier.js';
@@ -141,6 +142,95 @@ describe('ensureDaemonRunning', () => {
});
});
+describe('resolveDaemonProjectRoot (#2877)', () => {
+ const saved = process.env.RUFLO_DAEMON_AUTOSTART;
+ beforeEach(() => { delete process.env.RUFLO_DAEMON_AUTOSTART; });
+ afterEach(() => { if (saved === undefined) delete process.env.RUFLO_DAEMON_AUTOSTART; else process.env.RUFLO_DAEMON_AUTOSTART = saved; });
+
+ it('resolves the project root to itself', () => {
+ const root = project();
+ expect(resolveDaemonProjectRoot(root)).toBe(root);
+ });
+
+ it('resolves a nested subdirectory to the owning project root', () => {
+ const root = project();
+ const sub = join(root, 'packages', 'foo');
+ mkdirSync(sub, { recursive: true });
+ expect(resolveDaemonProjectRoot(sub)).toBe(root);
+ });
+
+ it('keeps an independently-initialized sub-project on its own root (nearest marker wins)', () => {
+ const root = project();
+ const sub = join(root, 'packages', 'independent');
+ mkdirSync(join(sub, '.claude-flow'), { recursive: true });
+ writeFileSync(join(sub, '.claude-flow', 'config.yaml'), 'version: 3\n');
+ expect(resolveDaemonProjectRoot(sub)).toBe(sub);
+ });
+
+ it('stops at the repository boundary instead of escaping into an ancestor project', () => {
+ const outer = project();
+ const repo = join(outer, 'vendor', 'unrelated-repo');
+ mkdirSync(join(repo, '.git'), { recursive: true });
+ const inside = join(repo, 'src');
+ mkdirSync(inside, { recursive: true });
+ expect(resolveDaemonProjectRoot(inside)).toBe(inside);
+ });
+
+ it('returns the start directory unchanged when no marker is found', () => {
+ const plain = mkdtempSync(join(tmpdir(), 'no-marker-'));
+ expect(resolveDaemonProjectRoot(plain)).toBe(plain);
+ });
+
+ it('autostart from the root spawns a daemon keyed to the root', () => {
+ const root = project();
+ const spawnedFor: string[] = [];
+ const r = ensureDaemonRunning(root, { isAlive: () => false, spawnFn: (p) => { spawnedFor.push(p); } });
+ expect(r.started).toBe(true);
+ expect(spawnedFor).toEqual([root]);
+ });
+
+ it('autostart from a subdirectory does NOT spawn a duplicate for the same project', () => {
+ const root = project();
+ const sub = join(root, 'packages', 'foo');
+ mkdirSync(sub, { recursive: true });
+
+ // A live daemon already holds the ROOT's pidfile. Before #2877 the
+ // subdirectory read `<sub>/.claude-flow/daemon.pid` β€” a different key β€”
+ // saw nothing, and spawned a second daemon for the same project.
+ writeFileSync(join(root, '.claude-flow', 'daemon.pid'), String(process.ppid));
+
+ let spawned = 0;
+ const r = ensureDaemonRunning(sub, { spawnFn: () => { spawned++; } });
+ expect(r).toEqual({ started: false, reason: 'already running' });
+ expect(spawned).toBe(0);
+ expect(existsSync(join(sub, '.claude-flow'))).toBe(false);
+ });
+
+ it('a genuinely separate project still gets its own daemon', () => {
+ const projectA = project();
+ const projectB = project();
+ writeFileSync(join(projectA, '.claude-flow', 'daemon.pid'), String(process.ppid));
+
+ const spawnedFor: string[] = [];
+ const r = ensureDaemonRunning(projectB, { spawnFn: (p) => { spawnedFor.push(p); } });
+ expect(r.started).toBe(true);
+ expect(spawnedFor).toEqual([projectB]);
+ });
+
+ it('reads the project-local opt-out from the root when invoked from a subdirectory', () => {
+ const root = project();
+ writeFileSync(join(root, 'claude-flow.config.json'), JSON.stringify({ daemon: { autostart: false } }));
+ const sub = join(root, 'packages', 'foo');
+ mkdirSync(sub, { recursive: true });
+
+ let spawned = 0;
+ const r = ensureDaemonRunning(sub, { isAlive: () => false, spawnFn: () => { spawned++; } });
+ expect(r.started).toBe(false);
+ expect(r.reason).toMatch(/disabled/);
+ expect(spawned).toBe(0);
+ });
+});
+
describe('isDaemonAlive', () => {
it('false + cleans a stale pidfile for a dead pid', () => {
const cwd = project();
diff --git a/v3/@claude-flow/cli/__tests__/hierarchical-store-durability-2887.test.ts b/v3/@claude-flow/cli/__tests__/hierarchical-store-durability-2887.test.ts
new file mode 100644
index 0000000000..306e1a6509
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hierarchical-store-durability-2887.test.ts
@@ -0,0 +1,105 @@
+/**
+ * agentdb_hierarchical-store durability contract (#2887).
+ *
+ * agentdb removed its `HierarchicalMemory` export at 3.0.0-alpha.17, so every
+ * hierarchical-store call lands in @claude-flow/memory's TieredMemoryStore
+ * fallback. While that fallback was purely in-process, the bridge still
+ * reported `success: true` for writes that never reached disk and were never
+ * recallable β€” silent data loss.
+ *
+ * These tests pin the decision the bridge makes about a store's durability:
+ * a volatile backing store must never be described as durable, and every
+ * result must name the controller actually in use plus why it was chosen.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { describeHierarchicalStore } from '../src/memory/memory-bridge.js';
+import { agentdbHierarchicalStore, agentdbTools } from '../src/mcp-tools/agentdb-tools.js';
+
+/** Minimal TieredMemoryStore stand-in with a switchable durability mode. */
+function fakeTieredStore(durable: boolean) {
+ return {
+ isDurable: () => durable,
+ getPersistence: () => (durable ? 'sqlite' : 'volatile'),
+ countPersisted: () => (durable ? 1 : null),
+ };
+}
+
+describe('describeHierarchicalStore β€” durability contract (#2887)', () => {
+ it('marks a SQLite-backed fallback durable and names its cause', () => {
+ const info = describeHierarchicalStore(fakeTieredStore(true), {
+ reason: 'agentdb-export-missing',
+ });
+
+ expect(info).toEqual({
+ controller: 'tieredMemoryStore',
+ fallbackFrom: 'agentdb-export-missing',
+ durable: true,
+ persistence: 'sqlite',
+ });
+ });
+
+ it('never describes a volatile fallback as durable', () => {
+ const info = describeHierarchicalStore(fakeTieredStore(false), {
+ reason: 'agentdb-unavailable',
+ });
+
+ expect(info.durable).toBe(false);
+ expect(info.persistence).toBe('volatile');
+ expect(info.controller).toBe('tieredMemoryStore');
+ });
+
+ it('still names the fallback when the registry cannot report a reason', () => {
+ const info = describeHierarchicalStore(fakeTieredStore(true), null);
+
+ expect(info.controller).toBe('tieredMemoryStore');
+ expect(info.fallbackFrom).toBe('hierarchicalMemory');
+ });
+
+ it('treats a native agentdb controller (no isDurable) as the durable path', () => {
+ const nativeHm = { getStats: () => ({}), promote: () => {}, store: async () => 'id' };
+
+ const info = describeHierarchicalStore(nativeHm, null);
+
+ expect(info).toEqual({
+ controller: 'hierarchicalMemory',
+ durable: true,
+ persistence: 'agentdb',
+ });
+ });
+});
+
+describe('agentdb_hierarchical-store MCP surface (#2887)', () => {
+ it('is registered as an MCP tool', () => {
+ expect(agentdbTools.map((t) => t.name)).toContain('agentdb_hierarchical-store');
+ });
+
+ it('rejects an invalid tier without claiming a write happened', async () => {
+ const result = await agentdbHierarchicalStore.handler({
+ key: 'k',
+ value: 'v',
+ tier: 'not-a-real-tier',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/tier/i);
+ });
+
+ it('never returns a bare success β€” a durability verdict always accompanies it', async () => {
+ const result = await agentdbHierarchicalStore.handler({
+ key: 'durability-contract-probe',
+ value: 'probe',
+ tier: 'working',
+ });
+
+ // The bridge may be unavailable in a bare test env; what must never happen
+ // is success:true with no statement about whether the write is durable.
+ if (result.success === true) {
+ expect(result.durable).toBe(true);
+ expect(typeof result.persistence).toBe('string');
+ expect(typeof result.controller).toBe('string');
+ } else {
+ expect(typeof result.error).toBe('string');
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/memory-concurrent-write-loss-2878.test.ts b/v3/@claude-flow/cli/__tests__/memory-concurrent-write-loss-2878.test.ts
new file mode 100644
index 0000000000..2d4a848f6f
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-concurrent-write-loss-2878.test.ts
@@ -0,0 +1,180 @@
+/**
+ * Regression guard for issue #2878 β€” concurrent sql.js whole-image writes
+ * were acknowledged and then silently lost.
+ *
+ * sql.js has no incremental persistence: every mutator loads the entire db
+ * image into memory, mutates it, and writes the whole image back. Two
+ * writers whose load→mutate→persist windows overlap therefore both start
+ * from the same predecessor image, and the last one to flush silently
+ * discards the other's row β€” while both return `success: true`.
+ * `PRAGMA integrity_check` still passes, because the file isn't corrupt;
+ * the data is simply gone.
+ *
+ * #2666 introduced `withMemoryDbLock` but only `purgeNamespace` opted in.
+ * These tests assert the whole-image read-modify-write paths now serialize
+ * through it, so a success acknowledgement means the mutation is durable.
+ *
+ * Reproducing it needs an `await` between the image read and the image
+ * write. `storeEntry` has one β€” embedding generation sits between them β€” so
+ * N concurrent stores with embeddings enabled all read the same predecessor
+ * image before any of them flushes. That is the exact lost-update shape the
+ * issue reported with 12 processes, and it exercises the same `O_EXCL` lock
+ * file (which is process-agnostic, so in-process contention is real
+ * contention).
+ */
+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 {
+ initializeMemoryDatabase,
+ storeEntry,
+ listEntries,
+ getEntry,
+ deleteEntry,
+ withMemoryDbLock,
+} from '../src/memory/memory-initializer.js';
+
+let tmp: string;
+let dbPath: string;
+
+beforeEach(async () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'concurrent-write-2878-'));
+ dbPath = path.join(tmp, 'memory.db');
+ const init = await initializeMemoryDatabase({ dbPath, force: true, migrate: false });
+ expect(init.success).toBe(true);
+});
+
+afterEach(() => {
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* */ }
+});
+
+describe('concurrent memory.db writes (#2878)', () => {
+ it('persists every acknowledged storeEntry when 12 writers overlap', async () => {
+ const N = 12;
+ const results = await Promise.all(
+ Array.from({ length: N }, (_, i) =>
+ storeEntry({
+ key: `concurrent-${i}`,
+ value: `value for concurrent writer number ${i}`,
+ namespace: 'concurrency',
+ dbPath,
+ // Embedding generation is the await that opens the read→write
+ // window every concurrent writer used to race through.
+ generateEmbeddingFlag: true,
+ })
+ )
+ );
+
+ expect(results.filter((r) => r.success).length).toBe(N);
+
+ const listed = await listEntries({ namespace: 'concurrency', dbPath, limit: 100 });
+ const keys = new Set(listed.entries.map((e) => e.key));
+ const missing = Array.from({ length: N }, (_, i) => `concurrent-${i}`).filter((k) => !keys.has(k));
+
+ // Every acknowledged write must be on disk β€” no silent loss.
+ expect(missing).toEqual([]);
+ expect(listed.total).toBe(N);
+ }, 60_000);
+
+ it('does not lose a concurrent store while other writers hold the image', async () => {
+ const [storeResults, lateResult] = await Promise.all([
+ Promise.all(
+ Array.from({ length: 6 }, (_, i) =>
+ storeEntry({
+ key: `batch-${i}`,
+ value: `batch value ${i}`,
+ namespace: 'concurrency',
+ dbPath,
+ generateEmbeddingFlag: true,
+ })
+ )
+ ),
+ storeEntry({
+ key: 'written-during-batch',
+ value: 'must survive',
+ namespace: 'concurrency',
+ dbPath,
+ generateEmbeddingFlag: true,
+ }),
+ ]);
+
+ expect(storeResults.every((r) => r.success)).toBe(true);
+ expect(lateResult.success).toBe(true);
+
+ const listed = await listEntries({ namespace: 'concurrency', dbPath, limit: 100 });
+ const keys = new Set(listed.entries.map((e) => e.key));
+ expect(keys.has('written-during-batch')).toBe(true);
+ expect(listed.total).toBe(7);
+ }, 60_000);
+
+ it('serializes getEntry access_count bumps instead of losing them', async () => {
+ await storeEntry({
+ key: 'read-me',
+ value: 'seed',
+ namespace: 'concurrency',
+ dbPath,
+ generateEmbeddingFlag: false,
+ });
+
+ // getEntry rewrites the whole image to bump access_count, so N concurrent
+ // reads are N concurrent writers. Every bump must land.
+ const N = 8;
+ const reads = await Promise.all(
+ Array.from({ length: N }, () => getEntry({ key: 'read-me', namespace: 'concurrency', dbPath }))
+ );
+ expect(reads.every((r) => r.success && r.found)).toBe(true);
+
+ const final = await getEntry({ key: 'read-me', namespace: 'concurrency', dbPath });
+ // N concurrent bumps + this one; a lost update would leave it lower.
+ expect(final.entry?.accessCount).toBe(N + 1);
+ }, 60_000);
+
+ it('does not resurrect concurrently deleted entries', async () => {
+ const N = 6;
+ for (let i = 0; i < N; i++) {
+ const r = await storeEntry({
+ key: `del-${i}`,
+ value: `v${i}`,
+ namespace: 'concurrency',
+ dbPath,
+ generateEmbeddingFlag: false,
+ });
+ expect(r.success).toBe(true);
+ }
+
+ const deletes = await Promise.all(
+ Array.from({ length: N }, (_, i) =>
+ deleteEntry({ key: `del-${i}`, namespace: 'concurrency', dbPath })
+ )
+ );
+ expect(deletes.filter((d) => d.success && d.deleted).length).toBe(N);
+
+ const listed = await listEntries({ namespace: 'concurrency', dbPath, limit: 100 });
+ // A lost delete resurrects a tombstoned row from a stale predecessor image.
+ expect(listed.entries.map((e) => e.key)).toEqual([]);
+ }, 60_000);
+
+ it('withMemoryDbLock is reentrant, so nested critical sections do not self-deadlock', async () => {
+ // storeEntry/deleteEntry/purgeNamespace all call ensureSchemaColumns from
+ // inside their own critical section. A non-reentrant O_EXCL lock would
+ // block there until the acquire timeout.
+ const inner = await withMemoryDbLock(dbPath, async () =>
+ withMemoryDbLock(dbPath, async () => 'reached')
+ );
+ expect(inner).toBe('reached');
+ // Lock file released on the way out.
+ expect(fs.existsSync(`${dbPath}.lock`)).toBe(false);
+ }, 20_000);
+
+ it('normalizes the lock path so relative and absolute callers contend on one lock', async () => {
+ const relative = path.relative(process.cwd(), dbPath);
+ let innerRan = false;
+ await withMemoryDbLock(dbPath, async () => {
+ // Same file, different spelling β€” must be seen as already held, not as
+ // a second independent lock.
+ await withMemoryDbLock(relative, async () => { innerRan = true; });
+ });
+ expect(innerRan).toBe(true);
+ }, 20_000);
+});
diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.ts
index 1b579b4e7b..dbbdbc67f3 100644
--- a/v3/@claude-flow/cli/src/commands/daemon.ts
+++ b/v3/@claude-flow/cli/src/commands/daemon.ts
@@ -6,6 +6,7 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { WorkerDaemon, getDaemon, startDaemon, stopDaemon, type WorkerType, type DaemonConfig } from '../services/worker-daemon.js';
+import { resolveDaemonProjectRoot } from '../services/daemon-autostart.js';
import { spawn, execFile, fork } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join, resolve, isAbsolute } from 'path';
@@ -64,7 +65,11 @@ const startCommand: Command = {
}
// #1914: a forked daemon child receives --workspace <root>; the launcher
// and interactive invocations have no flag and fall back to cwd.
- const projectRoot = resolveWorkspaceFlag(ctx.flags.workspace) ?? process.cwd();
+ // #2877: that cwd fallback is normalized to the owning project root, so
+ // `daemon start` from a subdirectory contends for the SAME lock/PID file
+ // as one from the root instead of silently keying its own pair.
+ const projectRoot = resolveWorkspaceFlag(ctx.flags.workspace)
+ ?? resolveDaemonProjectRoot(process.cwd());
const isDaemonProcess = process.env.CLAUDE_FLOW_DAEMON === '1';
// Parse resource threshold overrides from CLI flags
@@ -627,7 +632,7 @@ const stopCommand: Command = {
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const quiet = ctx.flags.quiet as boolean;
- const projectRoot = process.cwd();
+ const projectRoot = resolveDaemonProjectRoot(process.cwd());
// #2661: `stop --all` β€” the containment lever for daemon fanout across
// Git worktrees. Only processes positively identified as ruflo daemons
@@ -682,7 +687,7 @@ async function stopAllDaemons(quiet: boolean): Promise<CommandResult> {
// Stop any in-process daemon plus this workspace's tracked daemon first,
// matching plain `daemon stop` semantics for the current directory.
try { await stopDaemon(); } catch { /* not running in-process */ }
- await killBackgroundDaemon(process.cwd());
+ await killBackgroundDaemon(resolveDaemonProjectRoot(process.cwd()));
const daemons = await scanRunningDaemons();
if (daemons.length === 0) {
@@ -1203,7 +1208,7 @@ const statusCommand: Command = {
if (ctx.flags.all as boolean) {
return renderAllDaemonsStatus();
}
- const projectRoot = process.cwd();
+ const projectRoot = resolveDaemonProjectRoot(process.cwd());
try {
const daemon = getDaemon(projectRoot);
@@ -1370,7 +1375,7 @@ const triggerCommand: Command = {
// execution of THIS run (still governed by the global AI budget).
// Without the flag, config.json / env opt-in still applies.
const daemon = getDaemon(
- process.cwd(),
+ resolveDaemonProjectRoot(process.cwd()),
ctx.flags.headless === true ? { aiWorkersEnabled: true } : undefined
);
@@ -1421,7 +1426,7 @@ const enableCommand: Command = {
}
try {
- const daemon = getDaemon(process.cwd());
+ const daemon = getDaemon(resolveDaemonProjectRoot(process.cwd()));
daemon.setWorkerEnabled(workerType, !disable);
output.printSuccess(`Worker ${workerType} ${disable ? 'disabled' : 'enabled'}`);
@@ -1475,7 +1480,7 @@ const installSupervisorCommand: Command = {
const force = ctx.flags.force === true;
const load = ctx.flags.load !== false;
const dryRun = ctx.flags['dry-run'] === true || ctx.flags.dryRun === true;
- const projectRoot = process.cwd();
+ const projectRoot = resolveDaemonProjectRoot(process.cwd());
const platform = process.platform;
if (platform === 'win32') {
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index b4dc2d94cb..fe96cb9883 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -2755,6 +2755,14 @@ export async function bridgeHealthCheck(
controllers: Array<{ name: string; enabled: boolean; level: number }>;
attestationCount?: number;
cacheStats?: { size: number; hits: number; misses: number };
+ hierarchicalMemory?: {
+ controller: string;
+ durable: boolean;
+ persistence: string;
+ /** Real row count in the backing table β€” null when nothing is on disk. */
+ persistedRows: number | null;
+ fallbackFrom?: string;
+ };
} | null> {
const registry = await getRegistry(dbPath);
if (!registry) return null;
@@ -2777,7 +2785,19 @@ export async function bridgeHealthCheck(
cacheStats = { size: s.size ?? 0, hits: s.hits ?? 0, misses: s.misses ?? 0 };
}
- return { available: true, controllers, attestationCount, cacheStats };
+ // #2887: cacheStats alone let a "successful" hierarchical-store coexist
+ // with an empty store. Report the backing table's real row count so the
+ // inconsistency is visible instead of inferred.
+ let hierarchicalMemory;
+ const hm = registry.get('hierarchicalMemory');
+ if (hm) {
+ hierarchicalMemory = {
+ ...describeHierarchicalStore(hm, getHierarchicalFallback(registry)),
+ persistedRows: typeof hm.countPersisted === 'function' ? hm.countPersisted() : null,
+ };
+ }
+
+ return { available: true, controllers, attestationCount, cacheStats, hierarchicalMemory };
} catch {
return null;
}
@@ -2803,6 +2823,39 @@ export async function bridgeHealthCheck(
* temporal fields are stored in metadata, and supersede is reported as
* unsupported (no public update API) rather than silently dropped.
*/
+/**
+ * Describe which store `agentdb_hierarchical-*` actually landed on and
+ * whether its writes survive the process (#2887).
+ *
+ * agentdb removed its `HierarchicalMemory` export at 3.0.0-alpha.17, so the
+ * @claude-flow/memory TieredMemoryStore fallback is the live path. It is only
+ * durable when it was handed a SQLite connection β€” callers must not report a
+ * volatile write as a success.
+ */
+export function describeHierarchicalStore(
+ hm: any,
+ fallback: { reason: string } | null,
+): { controller: string; fallbackFrom?: string; durable: boolean; persistence: string } {
+ // Only the tiered fallback exposes isDurable(); the native controller
+ // (should agentdb reintroduce it) writes to agentdb's own tables.
+ if (typeof hm?.isDurable !== 'function') {
+ return { controller: 'hierarchicalMemory', durable: true, persistence: 'agentdb' };
+ }
+ return {
+ controller: 'tieredMemoryStore',
+ fallbackFrom: fallback?.reason ?? 'hierarchicalMemory',
+ durable: hm.isDurable() === true,
+ persistence: typeof hm.getPersistence === 'function' ? hm.getPersistence() : 'unknown',
+ };
+}
+
+/** Read `getHierarchicalFallback()` off a registry that may predate it. */
+function getHierarchicalFallback(registry: any): { reason: string } | null {
+ return typeof registry?.getHierarchicalFallback === 'function'
+ ? registry.getHierarchicalFallback()
+ : null;
+}
+
export async function bridgeHierarchicalStore(params: {
key: string; value: string; tier?: string; importance?: number;
validFrom?: string; validUntil?: string; supersedes?: string;
@@ -2825,7 +2878,10 @@ export async function bridgeHierarchicalStore(params: {
metadata,
tags: [params.key],
});
- const result: any = { success: true, id, key: params.key, tier };
+ const result: any = {
+ success: true, id, key: params.key, tier,
+ controller: 'hierarchicalMemory', durable: true, persistence: 'agentdb',
+ };
if (params.supersedes) {
// No public update/invalidate API on agentdb HierarchicalMemory β€”
// surface the limitation honestly instead of silently dropping it.
@@ -2834,17 +2890,28 @@ export async function bridgeHierarchicalStore(params: {
}
return result;
}
- // TieredMemoryStore fallback (temporal-aware) / legacy stub
+ // TieredMemoryStore fallback (temporal-aware) / legacy stub.
+ // agentdb dropped its HierarchicalMemory export at 3.0.0-alpha.17, so
+ // this is the live path β€” and it is only trustworthy when the store is
+ // backed by SQLite. A volatile write must NOT report success (#2887).
const storeResult = hm.store(params.key, params.value, tier, {
validFrom: params.validFrom,
validUntil: params.validUntil,
supersedes: params.supersedes,
});
- if (storeResult && typeof storeResult === 'object') {
- return { success: true, ...storeResult };
+ const info = describeHierarchicalStore(hm, getHierarchicalFallback(registry));
+ const base = {
+ ...info,
+ ...(storeResult && typeof storeResult === 'object' ? storeResult : { key: params.key, tier }),
+ };
+ if (!info.durable) {
+ return {
+ ...base,
+ success: false,
+ error: `hierarchical-store is running on the ${info.persistence} tiered fallback (${info.fallbackFrom}); the entry is NOT persisted to disk and will be lost when this process exits. Use memory_store for durable key-value persistence.`,
+ };
}
- // Legacy stub (returns void) β€” temporal options were ignored
- return { success: true, key: params.key, tier };
+ return { success: true, ...base };
} catch (e: any) { return { success: false, error: e.message }; }
}
@@ -2905,7 +2972,7 @@ export async function bridgeHierarchicalRecall(params: { query: string; tier?: s
const filtered = params.tier
? results.filter((r: any) => r.tier === params.tier)
: results;
- return { results: filtered, controller: 'hierarchicalMemory' };
+ return { results: filtered, ...describeHierarchicalStore(hm, getHierarchicalFallback(registry)) };
} catch (e: any) { return { results: [], error: e.message }; }
}
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index b94d5d5766..86032d37ce 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -11,6 +11,7 @@
import * as fs from 'fs';
import * as path from 'path';
+import { AsyncLocalStorage } from 'node:async_hooks';
import { createRequire } from 'node:module';
import { readFileMaybeEncrypted, writeFileAtomic, writeFileRestricted } from '../fs-secure.js';
import { restoreMemoryDbFromBackup } from '../services/memory-backup.js';
@@ -1273,79 +1274,84 @@ export async function ensureSchemaColumns(dbPath: string): Promise<{
return { success: true, columnsAdded: [] };
}
- const initSqlJs = (await import('sql.js')).default;
- const SQL = await initSqlJs();
+ // #2878: the ALTER/backfill below is a whole-image read-modify-write like
+ // every other mutator here. Reentrant, so the callers that run this from
+ // inside their own critical section don't self-deadlock.
+ return await withMemoryDbLock(dbPath, async () => {
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
- const fileBuffer = readFileMaybeEncrypted(dbPath, null);
- const db = new SQL.Database(fileBuffer);
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
+ const db = new SQL.Database(fileBuffer);
- // Get current columns in memory_entries
- const tableInfo = db.exec("PRAGMA table_info(memory_entries)");
- const existingColumns = new Set(
- tableInfo[0]?.values?.map(row => row[1] as string) || []
- );
+ // Get current columns in memory_entries
+ const tableInfo = db.exec("PRAGMA table_info(memory_entries)");
+ const existingColumns = new Set(
+ tableInfo[0]?.values?.map(row => row[1] as string) || []
+ );
+
+ // Required columns that may be missing in older schemas
+ // Issue #977: 'type' column was missing from this list, causing store failures on older DBs
+ const requiredColumns: Array<{ name: string; definition: string }> = [
+ { name: 'content', definition: "content TEXT DEFAULT ''" },
+ { name: 'type', definition: "type TEXT DEFAULT 'semantic'" },
+ { name: 'embedding', definition: 'embedding TEXT' },
+ { name: 'embedding_model', definition: "embedding_model TEXT DEFAULT 'local'" },
+ { name: 'embedding_dimensions', definition: 'embedding_dimensions INTEGER' },
+ { name: 'tags', definition: 'tags TEXT' },
+ { name: 'metadata', definition: 'metadata TEXT' },
+ { name: 'owner_id', definition: 'owner_id TEXT' },
+ { name: 'expires_at', definition: 'expires_at INTEGER' },
+ { name: 'last_accessed_at', definition: 'last_accessed_at INTEGER' },
+ { name: 'access_count', definition: 'access_count INTEGER DEFAULT 0' },
+ { name: 'status', definition: "status TEXT DEFAULT 'active'" },
+ // ADR-323: older DBs predate provenance typing entirely β€” backfilled
+ // as 'unknown' via the DEFAULT, same convention as 'type'/'status'
+ // above (no CHECK on the ALTER; enforcement happens in storeEntry()/
+ // bridgeStoreEntry() so an invalid value gets a CLI-friendly error
+ // instead of a raw SQLite constraint failure).
+ { name: 'provenance_type', definition: "provenance_type TEXT DEFAULT 'unknown'" }
+ ];
+
+ let modified = false;
+ for (const col of requiredColumns) {
+ if (!existingColumns.has(col.name)) {
+ try {
+ db.run(`ALTER TABLE memory_entries ADD COLUMN ${col.definition}`);
+ columnsAdded.push(col.name);
+ modified = true;
+ } catch (e) {
+ // Column might already exist or other error - continue
+ }
+ }
+ }
- // Required columns that may be missing in older schemas
- // Issue #977: 'type' column was missing from this list, causing store failures on older DBs
- const requiredColumns: Array<{ name: string; definition: string }> = [
- { name: 'content', definition: "content TEXT DEFAULT ''" },
- { name: 'type', definition: "type TEXT DEFAULT 'semantic'" },
- { name: 'embedding', definition: 'embedding TEXT' },
- { name: 'embedding_model', definition: "embedding_model TEXT DEFAULT 'local'" },
- { name: 'embedding_dimensions', definition: 'embedding_dimensions INTEGER' },
- { name: 'tags', definition: 'tags TEXT' },
- { name: 'metadata', definition: 'metadata TEXT' },
- { name: 'owner_id', definition: 'owner_id TEXT' },
- { name: 'expires_at', definition: 'expires_at INTEGER' },
- { name: 'last_accessed_at', definition: 'last_accessed_at INTEGER' },
- { name: 'access_count', definition: 'access_count INTEGER DEFAULT 0' },
- { name: 'status', definition: "status TEXT DEFAULT 'active'" },
- // ADR-323: older DBs predate provenance typing entirely β€” backfilled
- // as 'unknown' via the DEFAULT, same convention as 'type'/'status'
- // above (no CHECK on the ALTER; enforcement happens in storeEntry()/
- // bridgeStoreEntry() so an invalid value gets a CLI-friendly error
- // instead of a raw SQLite constraint failure).
- { name: 'provenance_type', definition: "provenance_type TEXT DEFAULT 'unknown'" }
- ];
-
- let modified = false;
- for (const col of requiredColumns) {
- if (!existingColumns.has(col.name)) {
+ // #2120 β€” Belt-and-suspenders backfill. `ALTER TABLE ADD COLUMN
+ // status TEXT DEFAULT 'active'` should populate existing rows with
+ // 'active' in modern SQLite, but: (a) some auto-memory bridge writes
+ // happen via INSERT paths that pass an explicit NULL, (b) some
+ // historical sql.js builds skipped the DEFAULT backfill, (c)
+ // entries can be migrated in from older snapshots. After ensuring
+ // the column exists, force-backfill any remaining NULL β†’ 'active'.
+ // Safe on already-correct DBs (0 rows updated).
+ if (columnsAdded.includes('status') || existingColumns.has('status')) {
try {
- db.run(`ALTER TABLE memory_entries ADD COLUMN ${col.definition}`);
- columnsAdded.push(col.name);
+ db.run(`UPDATE memory_entries SET status = 'active' WHERE status IS NULL`);
modified = true;
- } catch (e) {
- // Column might already exist or other error - continue
+ } catch {
+ /* table is read-only or doesn't exist β€” skip */
}
}
- }
- // #2120 β€” Belt-and-suspenders backfill. `ALTER TABLE ADD COLUMN
- // status TEXT DEFAULT 'active'` should populate existing rows with
- // 'active' in modern SQLite, but: (a) some auto-memory bridge writes
- // happen via INSERT paths that pass an explicit NULL, (b) some
- // historical sql.js builds skipped the DEFAULT backfill, (c)
- // entries can be migrated in from older snapshots. After ensuring
- // the column exists, force-backfill any remaining NULL β†’ 'active'.
- // Safe on already-correct DBs (0 rows updated).
- if (columnsAdded.includes('status') || existingColumns.has('status')) {
- try {
- db.run(`UPDATE memory_entries SET status = 'active' WHERE status IS NULL`);
- modified = true;
- } catch {
- /* table is read-only or doesn't exist β€” skip */
+ if (modified) {
+ // Save updated database
+ const data = db.export();
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
}
- }
-
- if (modified) {
- // Save updated database
- const data = db.export();
- writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
- }
- db.close();
- return { success: true, columnsAdded };
+ db.close();
+ return { success: true, columnsAdded };
+ });
} catch (error) {
return {
success: false,
@@ -2088,37 +2094,41 @@ export async function applyTemporalDecay(dbPath?: string): Promise<{
const path_ = dbPath || path.join(swarmDir, 'memory.db');
try {
- const initSqlJs = (await import('sql.js')).default;
- const SQL = await initSqlJs();
+ // #2878: decays `patterns` but rewrites the whole memory.db image, so it
+ // races the memory_entries writers over the same file.
+ return await withMemoryDbLock(path_, async () => {
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
- const fileBuffer = fs.readFileSync(path_);
- const db = new SQL.Database(fileBuffer);
+ const fileBuffer = fs.readFileSync(path_);
+ const db = new SQL.Database(fileBuffer);
- // Apply decay: confidence *= exp(-decay_rate * days_since_last_use)
- const now = Date.now();
- const decayQuery = `
- UPDATE patterns
- SET
- confidence = confidence * (1.0 - decay_rate * ((? - COALESCE(last_matched_at, created_at)) / 86400000.0)),
- updated_at = ?
- WHERE status = 'active'
- AND confidence > 0.1
- AND (? - COALESCE(last_matched_at, created_at)) > 86400000
- `;
-
- db.run(decayQuery, [now, now, now]);
-
- const changes = db.getRowsModified();
-
- // Save (atomic β€” issue #2584: a torn full-image flush corrupts the store)
- const data = db.export();
- writeFileAtomic(path_, Buffer.from(data));
- db.close();
+ // Apply decay: confidence *= exp(-decay_rate * days_since_last_use)
+ const now = Date.now();
+ const decayQuery = `
+ UPDATE patterns
+ SET
+ confidence = confidence * (1.0 - decay_rate * ((? - COALESCE(last_matched_at, created_at)) / 86400000.0)),
+ updated_at = ?
+ WHERE status = 'active'
+ AND confidence > 0.1
+ AND (? - COALESCE(last_matched_at, created_at)) > 86400000
+ `;
- return {
- success: true,
- patternsDecayed: changes
- };
+ db.run(decayQuery, [now, now, now]);
+
+ const changes = db.getRowsModified();
+
+ // Save (atomic β€” issue #2584: a torn full-image flush corrupts the store)
+ const data = db.export();
+ writeFileAtomic(path_, Buffer.from(data));
+ db.close();
+
+ return {
+ success: true,
+ patternsDecayed: changes
+ };
+ });
} catch (error) {
return {
success: false,
@@ -2852,33 +2862,14 @@ export async function storeEntry(options: {
};
}
- // Ensure schema has all required columns (migration for older DBs)
- await ensureSchemaColumns(dbPath);
-
- const initSqlJs = (await import('sql.js')).default;
- const SQL = await initSqlJs();
-
- const fileBuffer = readFileMaybeEncrypted(dbPath, null);
- const db = new SQL.Database(fileBuffer);
- let persistedProvenance = provenanceType ?? 'unknown';
- if (upsert && provenanceType === undefined) {
- try {
- const stmt = db.prepare(
- 'SELECT provenance_type FROM memory_entries WHERE namespace = ? AND key = ? LIMIT 1'
- );
- stmt.bind([namespace, key]);
- if (stmt.step()) {
- const existingType = stmt.get()[0];
- persistedProvenance = isValidProvenanceType(existingType) ? existingType : 'unknown';
- }
- stmt.free();
- } catch { /* legacy schema or new row β€” keep unknown */ }
- }
-
const id = `entry_${Date.now()}_${Math.random().toString(36).substring(7)}`;
const now = Date.now();
- // Generate embedding if requested
+ // Generate embedding if requested.
+ // #2878: deliberately BEFORE the lock. Embedding generation can take
+ // hundreds of ms (ONNX), and it needs nothing from the database β€” running
+ // it inside the critical section would hold every other writer off for
+ // its whole duration and push them toward the acquire timeout.
let embeddingJson: string | null = null;
let embeddingDimensions: number | null = null;
let embeddingModel: string | null = null;
@@ -2890,51 +2881,87 @@ export async function storeEntry(options: {
embeddingModel = embResult.model;
}
- // #1941: provision a `vector_indexes` row for this namespace before the
- // entry insert. The HNSW lookup uses this table to find which namespaces
- // are indexed β€” without a row, `memory_search({namespace:"X"})` returns
- // 0 even when memory_entries holds matching rows. INSERT OR IGNORE
- // preserves the existing `default` / `patterns` rows.
- try {
- db.run(
- `INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES (?, ?, ?)`,
- [namespace, namespace, embeddingDimensions ?? 384]
- );
- } catch { /* vector_indexes may not exist on legacy DBs β€” fall through */ }
-
- // Insert or update entry (upsert mode uses REPLACE)
- const insertSql = upsert
- ? `INSERT OR REPLACE INTO memory_entries (
- id, key, namespace, content, type,
- embedding, embedding_dimensions, embedding_model,
- tags, metadata, provenance_type, created_at, updated_at, expires_at, status
- ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')`
- : `INSERT INTO memory_entries (
- id, key, namespace, content, type,
- embedding, embedding_dimensions, embedding_model,
- tags, metadata, provenance_type, created_at, updated_at, expires_at, status
- ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')`;
-
- db.run(insertSql, [
- id,
- key,
- namespace,
- value,
- embeddingJson,
- embeddingDimensions,
- embeddingModel,
- tags.length > 0 ? JSON.stringify(tags) : null,
- '{}',
- persistedProvenance,
- now,
- now,
- ttl ? now + (ttl * 1000) : null
- ]);
-
- // Save
- const data = db.export();
- writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
- db.close();
+ // #2878: load β†’ mutate β†’ persist must be atomic against other writers.
+ // Without this, two concurrent stores both read the same predecessor
+ // image and the last flush silently drops the other's row while still
+ // reporting success.
+ await withMemoryDbLock(dbPath, async () => {
+ // Ensure schema has all required columns (migration for older DBs)
+ await ensureSchemaColumns(dbPath);
+
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
+
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
+ const db = new SQL.Database(fileBuffer);
+ let persistedProvenance = provenanceType ?? 'unknown';
+ if (upsert && provenanceType === undefined) {
+ try {
+ const stmt = db.prepare(
+ 'SELECT provenance_type FROM memory_entries WHERE namespace = ? AND key = ? LIMIT 1'
+ );
+ stmt.bind([namespace, key]);
+ if (stmt.step()) {
+ const existingType = stmt.get()[0];
+ persistedProvenance = isValidProvenanceType(existingType) ? existingType : 'unknown';
+ }
+ stmt.free();
+ } catch { /* legacy schema or new row β€” keep unknown */ }
+ }
+
+ // #1941: provision a `vector_indexes` row for this namespace before the
+ // entry insert. The HNSW lookup uses this table to find which namespaces
+ // are indexed β€” without a row, `memory_search({namespace:"X"})` returns
+ // 0 even when memory_entries holds matching rows. INSERT OR IGNORE
+ // preserves the existing `default` / `patterns` rows.
+ try {
+ db.run(
+ `INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES (?, ?, ?)`,
+ [namespace, namespace, embeddingDimensions ?? 384]
+ );
+ } catch { /* vector_indexes may not exist on legacy DBs β€” fall through */ }
+
+ // Insert or update entry (upsert mode uses REPLACE)
+ const insertSql = upsert
+ ? `INSERT OR REPLACE INTO memory_entries (
+ id, key, namespace, content, type,
+ embedding, embedding_dimensions, embedding_model,
+ tags, metadata, provenance_type, created_at, updated_at, expires_at, status
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')`
+ : `INSERT INTO memory_entries (
+ id, key, namespace, content, type,
+ embedding, embedding_dimensions, embedding_model,
+ tags, metadata, provenance_type, created_at, updated_at, expires_at, status
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')`;
+
+ try {
+ db.run(insertSql, [
+ id,
+ key,
+ namespace,
+ value,
+ embeddingJson,
+ embeddingDimensions,
+ embeddingModel,
+ tags.length > 0 ? JSON.stringify(tags) : null,
+ '{}',
+ persistedProvenance,
+ now,
+ now,
+ ttl ? now + (ttl * 1000) : null
+ ]);
+ } catch (e) {
+ // Don't leave the handle open (and the lock held) on a constraint
+ // failure β€” the outer catch turns this into the caller's error.
+ db.close();
+ throw e;
+ }
+
+ // Save
+ const data = db.export();
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
+ db.close();
+ });
// Add to HNSW index for faster future searches
if (embeddingJson) {
@@ -3499,78 +3526,85 @@ export async function getEntry(options: {
};
}
- // Ensure schema has all required columns (migration for older DBs)
- await ensureSchemaColumns(dbPath);
+ // #2878: this is a mutator, not a reader β€” the access_count bump below
+ // rewrites the whole image, so an unlocked "get" concurrent with a store
+ // flushes a predecessor image over it and silently drops the new row.
+ // There is no cheaper granularity available: the read and the bump share
+ // one image, so the lock has to span both.
+ return await withMemoryDbLock(dbPath, async () => {
+ // Ensure schema has all required columns (migration for older DBs)
+ await ensureSchemaColumns(dbPath);
- const initSqlJs = (await import('sql.js')).default;
- const SQL = await initSqlJs();
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
- const fileBuffer = readFileMaybeEncrypted(dbPath, null);
- const db = new SQL.Database(fileBuffer);
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
+ const db = new SQL.Database(fileBuffer);
- // Find entry by key
- const getStmt = db.prepare(`
- SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, tags
- FROM memory_entries
- WHERE ${ACTIVE_MEMORY_ROW_SQL}
- AND key = ?
- AND namespace = ?
- LIMIT 1
- `);
- getStmt.bind([key, namespace]);
- const getRows: unknown[][] = [];
- while (getStmt.step()) {
- getRows.push(getStmt.get());
- }
- getStmt.free();
- const result = getRows.length > 0 ? [{ values: getRows }] : [];
-
- if (!result[0]?.values?.[0]) {
- db.close();
- return { success: true, found: false };
- }
+ // Find entry by key
+ const getStmt = db.prepare(`
+ SELECT id, key, namespace, content, embedding, access_count, created_at, updated_at, tags
+ FROM memory_entries
+ WHERE ${ACTIVE_MEMORY_ROW_SQL}
+ AND key = ?
+ AND namespace = ?
+ LIMIT 1
+ `);
+ getStmt.bind([key, namespace]);
+ const getRows: unknown[][] = [];
+ while (getStmt.step()) {
+ getRows.push(getStmt.get());
+ }
+ getStmt.free();
+ const result = getRows.length > 0 ? [{ values: getRows }] : [];
- const [id, entryKey, ns, content, embedding, accessCount, createdAt, updatedAt, tagsJson] = result[0].values[0] as [
- string, string, string, string, string | null, number, string, string, string | null
- ];
+ if (!result[0]?.values?.[0]) {
+ db.close();
+ return { success: true, found: false };
+ }
- // Update access count
- db.run(`
- UPDATE memory_entries
- SET access_count = access_count + 1, last_accessed_at = strftime('%s', 'now') * 1000
- WHERE id = ?
- `, [String(id)]);
+ const [id, entryKey, ns, content, embedding, accessCount, createdAt, updatedAt, tagsJson] = result[0].values[0] as [
+ string, string, string, string, string | null, number, string, string, string | null
+ ];
- // Save updated database
- const data = db.export();
- writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
+ // Update access count
+ db.run(`
+ UPDATE memory_entries
+ SET access_count = access_count + 1, last_accessed_at = strftime('%s', 'now') * 1000
+ WHERE id = ?
+ `, [String(id)]);
- db.close();
+ // Save updated database
+ const data = db.export();
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
- let tags: string[] = [];
- if (tagsJson) {
- try {
- tags = JSON.parse(tagsJson);
- } catch {
- // Invalid JSON
- }
- }
+ db.close();
- return {
- success: true,
- found: true,
- entry: {
- id: String(id),
- key: entryKey || String(id),
- namespace: ns || 'default',
- content: content || '',
- accessCount: (accessCount || 0) + 1,
- createdAt: createdAt || new Date().toISOString(),
- updatedAt: updatedAt || new Date().toISOString(),
- hasEmbedding: !!embedding && embedding.length > 10,
- tags
+ let tags: string[] = [];
+ if (tagsJson) {
+ try {
+ tags = JSON.parse(tagsJson);
+ } catch {
+ // Invalid JSON
+ }
}
- };
+
+ return {
+ success: true,
+ found: true,
+ entry: {
+ id: String(id),
+ key: entryKey || String(id),
+ namespace: ns || 'default',
+ content: content || '',
+ accessCount: (accessCount || 0) + 1,
+ createdAt: createdAt || new Date().toISOString(),
+ updatedAt: updatedAt || new Date().toISOString(),
+ hasEmbedding: !!embedding && embedding.length > 10,
+ tags
+ }
+ };
+ });
} catch (error) {
return {
success: false,
@@ -3645,80 +3679,84 @@ export async function deleteEntry(options: {
};
}
- // Ensure schema has all required columns (migration for older DBs)
- await ensureSchemaColumns(dbPath);
+ // #2878: whole-image read-modify-write β€” without the lock a concurrent
+ // writer's flush resurrects the row this call just tombstoned.
+ return await withMemoryDbLock(dbPath, async () => {
+ // Ensure schema has all required columns (migration for older DBs)
+ await ensureSchemaColumns(dbPath);
- const initSqlJs = (await import('sql.js')).default;
- const SQL = await initSqlJs();
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
- const fileBuffer = readFileMaybeEncrypted(dbPath, null);
- const db = new SQL.Database(fileBuffer);
+ const fileBuffer = readFileMaybeEncrypted(dbPath, null);
+ const db = new SQL.Database(fileBuffer);
+
+ // Check if entry exists first
+ const checkStmt = db.prepare(`
+ SELECT id FROM memory_entries
+ WHERE ${ACTIVE_MEMORY_ROW_SQL}
+ AND key = ?
+ AND namespace = ?
+ LIMIT 1
+ `);
+ checkStmt.bind([key, namespace]);
+ const checkRows: unknown[][] = [];
+ while (checkStmt.step()) {
+ checkRows.push(checkStmt.get());
+ }
+ checkStmt.free();
+ const checkResult = checkRows.length > 0 ? [{ values: checkRows }] : [];
+
+ if (!checkResult[0]?.values?.[0]) {
+ // Get remaining count before closing
+ const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE ${ACTIVE_MEMORY_ROW_SQL}`);
+ const remainingEntries = countResult[0]?.values?.[0]?.[0] as number || 0;
+ db.close();
+ return {
+ success: true,
+ deleted: false,
+ key,
+ namespace,
+ remainingEntries,
+ error: `Key '${key}' not found in namespace '${namespace}'`
+ };
+ }
- // Check if entry exists first
- const checkStmt = db.prepare(`
- SELECT id FROM memory_entries
- WHERE ${ACTIVE_MEMORY_ROW_SQL}
- AND key = ?
- AND namespace = ?
- LIMIT 1
- `);
- checkStmt.bind([key, namespace]);
- const checkRows: unknown[][] = [];
- while (checkStmt.step()) {
- checkRows.push(checkStmt.get());
- }
- checkStmt.free();
- const checkResult = checkRows.length > 0 ? [{ values: checkRows }] : [];
-
- if (!checkResult[0]?.values?.[0]) {
- // Get remaining count before closing
+ // Delete the entry (soft delete by setting status to 'deleted')
+ // Also null out the embedding to clean up vector data from SQLite
+ db.run(`
+ UPDATE memory_entries
+ SET status = 'deleted',
+ embedding = NULL,
+ updated_at = strftime('%s', 'now') * 1000
+ WHERE key = ?
+ AND namespace = ?
+ AND ${ACTIVE_MEMORY_ROW_SQL}
+ `, [key, namespace]);
+
+ // Get remaining count
const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE ${ACTIVE_MEMORY_ROW_SQL}`);
const remainingEntries = countResult[0]?.values?.[0]?.[0] as number || 0;
+
+ // Save updated database
+ const data = db.export();
+ writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
+
db.close();
+
+ // Clean up in-memory HNSW index so ghost vectors don't appear in searches.
+ // Remove the entry from the HNSW entries map and invalidate the index.
+ // The next search will rebuild the HNSW index from the remaining DB rows.
+ if (hnswIndex?.entries) removeHNSWEntriesByKey(key, namespace);
+
return {
success: true,
- deleted: false,
+ deleted: true,
key,
namespace,
- remainingEntries,
- error: `Key '${key}' not found in namespace '${namespace}'`
+ remainingEntries
};
- }
-
- // Delete the entry (soft delete by setting status to 'deleted')
- // Also null out the embedding to clean up vector data from SQLite
- db.run(`
- UPDATE memory_entries
- SET status = 'deleted',
- embedding = NULL,
- updated_at = strftime('%s', 'now') * 1000
- WHERE key = ?
- AND namespace = ?
- AND ${ACTIVE_MEMORY_ROW_SQL}
- `, [key, namespace]);
-
- // Get remaining count
- const countResult = db.exec(`SELECT COUNT(*) FROM memory_entries WHERE ${ACTIVE_MEMORY_ROW_SQL}`);
- const remainingEntries = countResult[0]?.values?.[0]?.[0] as number || 0;
-
- // Save updated database
- const data = db.export();
- writeFileRestricted(dbPath, Buffer.from(data), { encrypt: true });
-
- db.close();
-
- // Clean up in-memory HNSW index so ghost vectors don't appear in searches.
- // Remove the entry from the HNSW entries map and invalidate the index.
- // The next search will rebuild the HNSW index from the remaining DB rows.
- if (hnswIndex?.entries) removeHNSWEntriesByKey(key, namespace);
-
- return {
- success: true,
- deleted: true,
- key,
- namespace,
- remainingEntries
- };
+ });
} catch (error) {
return {
success: false,
@@ -3751,30 +3789,52 @@ export async function deleteEntry(options: {
// which is the concrete case this feature needs to be safe against.
const MEMORY_DB_LOCK_STALE_MS = 10_000;
+const MEMORY_DB_LOCK_ACQUIRE_TIMEOUT_MS = 15_000;
function delayMs(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
+/**
+ * Locks this call stack already holds, keyed by resolved db path. #2878: the
+ * mutators below call each other (every one runs `ensureSchemaColumns`, which
+ * takes the same lock), and an O_EXCL lock is not reentrant β€” a nested
+ * acquire would spin against our own lock file until the acquire timeout and
+ * then throw. AsyncLocalStorage lets a nested acquire recognise the lock as
+ * already held and run inline, while genuinely independent callers (separate
+ * `Promise.all` branches, separate processes) still contend normally.
+ */
+const heldMemoryDbLocks = new AsyncLocalStorage<ReadonlySet<string>>();
+
/**
* Advisory O_EXCL lock scoped to a single memory.db file (`<dbPath>.lock`),
- * same stale-takeover pattern as services/global-ai-budget.ts. Only
- * meaningful between callers that opt into it (purgeNamespace does); it
- * cannot coordinate against writers that don't call this helper.
+ * same stale-takeover pattern as services/global-ai-budget.ts.
+ *
+ * #2878: sql.js persists by rewriting the whole database image, so every
+ * `load β†’ mutate β†’ export β†’ write` sequence is a read-modify-write that a
+ * concurrent writer can clobber β€” both callers report success and the loser's
+ * rows vanish, with `PRAGMA integrity_check` still clean. Every such sequence
+ * in this module now runs inside this lock. It is advisory, so it still
+ * cannot coordinate against a writer that bypasses this module entirely
+ * (a native WAL connection β€” see hasNativeWalSidecars).
*/
export async function withMemoryDbLock<T>(dbPath: string, fn: () => Promise<T> | T): Promise<T> {
- const lockFile = `${dbPath}.lock`;
- const deadline = Date.now() + 5000;
+ // Callers spell the same file both ways (`storeEntry` resolves, `getEntry`
+ // does not). Normalise, or two spellings would take two different locks and
+ // serialize against nothing.
+ const resolved = path.resolve(dbPath);
+ const held = heldMemoryDbLocks.getStore();
+ if (held?.has(resolved)) return await fn();
+
+ const nested = new Set(held ?? []);
+ nested.add(resolved);
+
+ const lockFile = `${resolved}.lock`;
+ const deadline = Date.now() + MEMORY_DB_LOCK_ACQUIRE_TIMEOUT_MS;
for (;;) {
+ let fd: number;
try {
- const fd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
- fs.writeSync(fd, String(process.pid));
- fs.closeSync(fd);
- try {
- return await fn();
- } finally {
- try { fs.unlinkSync(lockFile); } catch { /* already gone */ }
- }
+ fd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
try {
@@ -3788,6 +3848,15 @@ export async function withMemoryDbLock<T>(dbPath: string, fn: () => Promise<T> |
throw new Error(`timed out acquiring memory.db lock: ${lockFile}`);
}
await delayMs(25);
+ continue;
+ }
+
+ fs.writeSync(fd, String(process.pid));
+ fs.closeSync(fd);
+ try {
+ return await heldMemoryDbLocks.run(nested, fn);
+ } finally {
+ try { fs.unlinkSync(lockFile); } catch { /* already gone */ }
}
}
}
diff --git a/v3/@claude-flow/cli/src/services/daemon-autostart.ts b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
index 6c2f880531..d45fa17dff 100644
--- a/v3/@claude-flow/cli/src/services/daemon-autostart.ts
+++ b/v3/@claude-flow/cli/src/services/daemon-autostart.ts
@@ -104,6 +104,41 @@ export function isRufloProject(projectRoot: string): boolean {
return false;
}
+/**
+ * #2877: Normalize a working directory to the project root that owns the
+ * daemon lock/PID key.
+ *
+ * The lock (`<root>/.claude-flow/daemon.lock`) and PID file
+ * (`<root>/.claude-flow/daemon.pid`) were keyed to the raw cwd, so invoking
+ * the CLI from `/proj` and from `/proj/packages/foo` produced two different
+ * keys for one logical project β€” bypassing the atomic-lockfile dedup added
+ * for #2407/#2484 entirely (each cwd races against a different lock file)
+ * and leaving two daemons supervising the same tree.
+ *
+ * Resolution walks up from `startDir` and returns the NEAREST enclosing
+ * directory carrying a durable Ruflo marker (`isRufloProject`). Nearest-wins
+ * is what keeps a monorepo's independently-initialized sub-project on its own
+ * daemon: it matches its own marker before the walk ever reaches the parent.
+ *
+ * A `.git` directory is a hard stop β€” the repository boundary. Without it the
+ * walk could escape into an unrelated ancestor (a Ruflo project living at
+ * `$HOME`, say) and hand every repo below it the same daemon.
+ *
+ * Returns the resolved `startDir` unchanged when no marker is found, so a
+ * non-Ruflo directory still fails `isRufloProject` and declines autostart.
+ */
+export function resolveDaemonProjectRoot(startDir: string): string {
+ const start = path.resolve(startDir);
+ let dir = start;
+ for (;;) {
+ if (isRufloProject(dir)) return dir;
+ if (fs.existsSync(path.join(dir, '.git'))) return start;
+ const parent = path.dirname(dir);
+ if (parent === dir) return start;
+ dir = parent;
+ }
+}
+
export interface EnsureResult { started: boolean; reason?: string }
/** Spawn `daemon start` detached, reusing all its lock/TTL machinery. Injectable for tests. */
@@ -121,14 +156,19 @@ const defaultSpawn: SpawnDaemonFn = (projectRoot) => {
};
/**
- * Ensure a daemon is running for `projectRoot`. No-op when disabled or when one
- * is already alive. Best-effort; never throws.
+ * Ensure a daemon is running for the project enclosing `startDir`. No-op when
+ * disabled or when one is already alive. Best-effort; never throws.
+ *
+ * #2877: `startDir` is normalized to the owning project root first, so a call
+ * from a subdirectory reads the same config, pidfile, and lock as a call from
+ * the root and cannot spawn a second daemon for the same project.
*/
export function ensureDaemonRunning(
- projectRoot: string,
+ startDir: string,
opts: { spawnFn?: SpawnDaemonFn; isAlive?: (root: string) => boolean } = {},
): EnsureResult {
try {
+ const projectRoot = resolveDaemonProjectRoot(startDir);
if (autostartDisabled(projectRoot)) return { started: false, reason: 'disabled (RUFLO_DAEMON_AUTOSTART=0 or project config)' };
if (!isRufloProject(projectRoot)) {
return { started: false, reason: 'not a ruflo project' };
diff --git a/v3/@claude-flow/memory/src/controller-registry.test.ts b/v3/@claude-flow/memory/src/controller-registry.test.ts
index 225fe93d75..412d375721 100644
--- a/v3/@claude-flow/memory/src/controller-registry.test.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.test.ts
@@ -723,6 +723,23 @@ describe('ControllerRegistry', () => {
// Just verify the listener doesn't break anything
});
+ it('should emit controller:degraded with the reason hierarchicalMemory fell back (#2887)', async () => {
+ const degraded: Array<{ name: string; reason: string; persistence: string }> = [];
+ registry.on('controller:degraded', (e: any) => degraded.push(e));
+
+ await registry.initialize({
+ backend: mockBackend,
+ controllers: { hierarchicalMemory: true },
+ });
+
+ // agentdb dropped its HierarchicalMemory export at 3.0.0-alpha.17, so the
+ // tiered fallback is the live path. Taking it must be announced, not silent.
+ const hmDegraded = degraded.find((e) => e.name === 'hierarchicalMemory');
+ expect(hmDegraded).toBeDefined();
+ expect(hmDegraded!.reason).toBeTruthy();
+ expect(registry.getHierarchicalFallback()).toMatchObject({ reason: hmDegraded!.reason });
+ });
+
it('should emit all lifecycle events', async () => {
const events: string[] = [];
registry.on('initialized', () => events.push('initialized'));
diff --git a/v3/@claude-flow/memory/src/controller-registry.ts b/v3/@claude-flow/memory/src/controller-registry.ts
index a0b60e57af..060cda8440 100644
--- a/v3/@claude-flow/memory/src/controller-registry.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.ts
@@ -231,6 +231,7 @@ export class ControllerRegistry extends EventEmitter {
private config: RuntimeConfig = {};
private initialized = false;
private initTimeMs = 0;
+ private hierarchicalFallback: { reason: string; persistence: string } | null = null;
/**
* Initialize all controllers in level-based order.
@@ -881,19 +882,25 @@ export class ControllerRegistry extends EventEmitter {
return null;
case 'hierarchicalMemory': {
- // HierarchicalMemory exported from agentdb 3.0.0-alpha.10 (ADR-066 Phase P2-3)
- // Constructor: (db, embedder, vectorBackend?, graphBackend?, config?)
- if (!this.agentdb) return this.createTieredMemoryStub();
+ // HierarchicalMemory was exported by agentdb 3.0.0-alpha.10 (ADR-066
+ // Phase P2-3) and REMOVED again at alpha.17 β€” so the fallback below is
+ // the live path, not an edge case. Every fallback records why, because
+ // taking it silently is what made stores look successful while landing
+ // nowhere (#2887).
+ if (!this.agentdb) return this.tieredMemoryFallback('agentdb-unavailable');
try {
const agentdbModule: any = await import('agentdb');
const HM = agentdbModule.HierarchicalMemory;
- if (!HM) return this.createTieredMemoryStub();
+ if (typeof HM !== 'function') {
+ return this.tieredMemoryFallback('agentdb-export-missing');
+ }
const embedder = this.createEmbeddingService();
const hm = new HM(this.agentdb.database, embedder);
await hm.initializeDatabase();
return hm;
- } catch {
- return this.createTieredMemoryStub();
+ } catch (error) {
+ const msg = error instanceof Error ? error.message : String(error);
+ return this.tieredMemoryFallback(`agentdb-init-failed: ${msg.substring(0, 120)}`);
}
}
@@ -1191,16 +1198,44 @@ export class ControllerRegistry extends EventEmitter {
}
/**
- * Lightweight in-memory tiered store (fallback when HierarchicalMemory
- * cannot be initialized from agentdb).
+ * Tiered store used when agentdb's HierarchicalMemory is unavailable.
*
- * Promoted to the first-class {@link TieredMemoryStore} module, which
- * adds Zep/Graphiti-style temporal validity (validFrom / validUntil /
- * supersededBy) while keeping the legacy duck-typed API:
- * store(key, value, tier) / recall(query, topK) / getTierStats().
+ * Since agentdb 3.0.0-alpha.17 dropped the `HierarchicalMemory` export
+ * entirely, this is the ONLY backing store for `agentdb_hierarchical-*`
+ * in practice β€” so it is handed AgentDB's SQLite connection and writes
+ * through to it. Without a connection it stays volatile and reports
+ * `isDurable() === false` so callers can refuse to claim success (#2887).
+ *
+ * Keeps the legacy duck-typed API β€” store(key, value, tier) /
+ * recall(query, topK) / getTierStats() β€” plus Zep/Graphiti-style temporal
+ * validity (validFrom / validUntil / supersededBy).
*/
private createTieredMemoryStub(): TieredMemoryStore {
- return new TieredMemoryStore();
+ const db = this.agentdb?.database ?? null;
+ const usable = db && typeof db.prepare === 'function' && typeof db.exec === 'function'
+ ? db
+ : null;
+ return new TieredMemoryStore({ db: usable });
+ }
+
+ /** Build the tiered fallback and record/emit why the native one was skipped. */
+ private tieredMemoryFallback(reason: string): TieredMemoryStore {
+ const store = this.createTieredMemoryStub();
+ this.hierarchicalFallback = { reason, persistence: store.getPersistence() };
+ this.emit('controller:degraded', {
+ name: 'hierarchicalMemory',
+ reason,
+ persistence: store.getPersistence(),
+ });
+ return store;
+ }
+
+ /**
+ * Why `hierarchicalMemory` is served by the tiered fallback, and whether
+ * that fallback is durable. Null when the native controller is in use.
+ */
+ getHierarchicalFallback(): { reason: string; persistence: string } | null {
+ return this.hierarchicalFallback;
}
/**
diff --git a/v3/@claude-flow/memory/src/tiered-memory.test.ts b/v3/@claude-flow/memory/src/tiered-memory.test.ts
index 281af40e33..e4f1b59a5c 100644
--- a/v3/@claude-flow/memory/src/tiered-memory.test.ts
+++ b/v3/@claude-flow/memory/src/tiered-memory.test.ts
@@ -6,7 +6,11 @@
* entries without temporal fields.
*/
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import Database from 'better-sqlite3';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
import { TieredMemoryStore, isTemporallyValid } from './tiered-memory.js';
describe('TieredMemoryStore β€” legacy behavior (backward compatibility)', () => {
@@ -186,3 +190,79 @@ describe('isTemporallyValid', () => {
expect(isTemporallyValid({ validUntil: '2026-07-03T12:00:00Z' }, now)).toBe(false);
});
});
+
+describe('TieredMemoryStore β€” durability (#2887)', () => {
+ const dbs: Database.Database[] = [];
+ const dirs: string[] = [];
+
+ function freshDbPath(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tiered-durability-'));
+ dirs.push(dir);
+ return path.join(dir, 'agentdb-memory.db');
+ }
+
+ function open(dbPath: string): Database.Database {
+ const db = new Database(dbPath);
+ dbs.push(db);
+ return db;
+ }
+
+ afterEach(() => {
+ for (const db of dbs.splice(0)) { try { db.close(); } catch { /* already closed */ } }
+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('a successful store is queryable on disk, not just in the maps', () => {
+ const dbPath = freshDbPath();
+ const store = new TieredMemoryStore({ db: open(dbPath) });
+
+ const result = store.store('durable-key', 'DURABLE_VALUE', 'semantic');
+
+ expect(result.durable).toBe(true);
+ expect(result.persistence).toBe('sqlite');
+
+ // Read through an INDEPENDENT connection β€” proves the row is committed,
+ // not merely sitting in the writer's in-memory maps.
+ const rows = open(dbPath)
+ .prepare('SELECT key, value, tier FROM tiered_memory WHERE key = ?')
+ .all('durable-key');
+ expect(rows).toEqual([{ key: 'durable-key', value: 'DURABLE_VALUE', tier: 'semantic' }]);
+ });
+
+ it('rehydrates persisted entries into a brand-new store instance', () => {
+ const dbPath = freshDbPath();
+ new TieredMemoryStore({ db: open(dbPath) }).store('survives', 'ACROSS_INSTANCES', 'working');
+
+ const reopened = new TieredMemoryStore({ db: open(dbPath) });
+
+ expect(reopened.recall('ACROSS_INSTANCES')).toHaveLength(1);
+ expect(reopened.countPersisted()).toBe(1);
+ });
+
+ it('reports durable:false β€” never a bare success β€” when there is no backing db', () => {
+ const store = new TieredMemoryStore();
+
+ const result = store.store('volatile-key', 'LOST_ON_EXIT');
+
+ expect(store.isDurable()).toBe(false);
+ expect(result.durable).toBe(false);
+ expect(result.persistence).toBe('volatile');
+ // No table exists to count, so health checks can't be told a row landed.
+ expect(store.countPersisted()).toBeNull();
+ });
+
+ it('superseded entries stay auditable on disk, and removal deletes the row', () => {
+ const dbPath = freshDbPath();
+ const store = new TieredMemoryStore({ db: open(dbPath) });
+ const first = store.store('fact', 'v1', 'semantic');
+ store.store('fact', 'v2', 'semantic', { supersedes: first.id });
+
+ expect(store.countPersisted()).toBe(2);
+ expect(store.recall('fact', 5, { includeExpired: true })).toHaveLength(2);
+
+ expect(store.remove('fact')).toBe(true);
+ expect(
+ open(dbPath).prepare('SELECT COUNT(*) AS n FROM tiered_memory WHERE archived = 0').get(),
+ ).toEqual({ n: 0 });
+ });
+});
diff --git a/v3/@claude-flow/memory/src/tiered-memory.ts b/v3/@claude-flow/memory/src/tiered-memory.ts
index ce89cd28bf..500fdda31a 100644
--- a/v3/@claude-flow/memory/src/tiered-memory.ts
+++ b/v3/@claude-flow/memory/src/tiered-memory.ts
@@ -1,5 +1,6 @@
/**
- * Tier-aware in-memory store with Zep/Graphiti-style temporal validity.
+ * Tier-aware store with Zep/Graphiti-style temporal validity, durable when
+ * given a SQLite handle.
*
* This is the store backing `agentdb_hierarchical-store` / `-recall` when
* agentdb's native HierarchicalMemory is unavailable (previously an inline
@@ -14,6 +15,14 @@
* is the audit escape hatch.
* - Entries without temporal fields behave exactly as before (always valid).
*
+ * Durability (#2887): agentdb dropped its `HierarchicalMemory` export at
+ * 3.0.0-alpha.17, so this store β€” not the native controller β€” is what every
+ * `agentdb_hierarchical-store` call actually lands in. Purely in-memory, that
+ * made every such write a silent no-op that still reported success. Pass a
+ * better-sqlite3-compatible handle and the store writes through to a
+ * `tiered_memory` table and rehydrates from it on construction; without a
+ * handle it stays volatile and says so via {@link TieredMemoryStore.isDurable}.
+ *
* API shape is kept duck-type compatible with the previous stub so the CLI
* memory-bridge keeps working unchanged:
* store(key, value, tier) recall(query, topK) getTierStats()
@@ -67,6 +76,68 @@ export interface TieredStoreResult {
tier: string;
/** Set when `supersedes` matched an existing entry. */
superseded?: { id: string; key: string; validUntil: string } | null;
+ /** True when the entry was written through to the backing SQLite table. */
+ durable: boolean;
+ /** Where the entry lives: a real table, or process memory only. */
+ persistence: TieredPersistence;
+}
+
+/** Durability mode of a {@link TieredMemoryStore}. */
+export type TieredPersistence = 'sqlite' | 'volatile';
+
+/**
+ * Minimal better-sqlite3-shaped handle. Only the calls this store makes are
+ * required, so any driver exposing the same synchronous surface works.
+ */
+export interface TieredMemoryDb {
+ exec(sql: string): unknown;
+ prepare(sql: string): {
+ run(...params: unknown[]): unknown;
+ all(...params: unknown[]): unknown[];
+ get(...params: unknown[]): unknown;
+ };
+}
+
+const TABLE_DDL = `
+CREATE TABLE IF NOT EXISTS tiered_memory (
+ id TEXT PRIMARY KEY,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL,
+ tier TEXT NOT NULL,
+ ts INTEGER NOT NULL,
+ valid_from TEXT,
+ valid_until TEXT,
+ superseded_by TEXT,
+ archived INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX IF NOT EXISTS idx_tiered_memory_key ON tiered_memory(key);
+CREATE INDEX IF NOT EXISTS idx_tiered_memory_tier ON tiered_memory(tier, archived);
+`;
+
+interface TieredMemoryRow {
+ id: string;
+ key: string;
+ value: string;
+ tier: string;
+ ts: number;
+ valid_from: string | null;
+ valid_until: string | null;
+ superseded_by: string | null;
+ archived: number;
+}
+
+function rowToEntry(row: TieredMemoryRow): TieredMemoryEntry {
+ const entry: TieredMemoryEntry = {
+ id: row.id,
+ key: row.key,
+ value: row.value,
+ tier: row.tier,
+ ts: Number(row.ts),
+ };
+ if (row.valid_from) entry.validFrom = row.valid_from;
+ if (row.valid_until) entry.validUntil = row.valid_until;
+ if (row.superseded_by) entry.supersededBy = row.superseded_by;
+ return entry;
}
const VALID_TIERS = ['working', 'episodic', 'semantic'] as const;
@@ -119,6 +190,105 @@ export class TieredMemoryStore {
*/
private archived: TieredMemoryEntry[] = [];
+ private db: TieredMemoryDb | null = null;
+
+ /**
+ * @param options.db better-sqlite3-compatible handle. When supplied the
+ * store writes through to `tiered_memory` and rehydrates from it, so
+ * entries survive the process. Without it the store is volatile and
+ * {@link isDurable} returns false β€” callers must treat a write as lost
+ * on exit rather than reporting success (#2887).
+ */
+ constructor(options?: { db?: TieredMemoryDb | null }) {
+ const db = options?.db ?? null;
+ if (!db) return;
+ try {
+ db.exec(TABLE_DDL);
+ this.db = db;
+ this.hydrate();
+ } catch {
+ // Schema creation failed β€” stay volatile and report it honestly via
+ // isDurable() rather than pretending the handle works.
+ this.db = null;
+ }
+ }
+
+ /** True when writes are persisted to the backing table. */
+ isDurable(): boolean {
+ return this.db !== null;
+ }
+
+ /** Durability mode, for surfacing to MCP callers. */
+ getPersistence(): TieredPersistence {
+ return this.db ? 'sqlite' : 'volatile';
+ }
+
+ /**
+ * Actual row count in the backing table (not the in-memory maps), so
+ * health checks can detect a claimed-write / empty-table mismatch.
+ * Returns null when volatile β€” there is no table to count.
+ */
+ countPersisted(): number | null {
+ if (!this.db) return null;
+ try {
+ const row = this.db.prepare('SELECT COUNT(*) AS n FROM tiered_memory').get() as { n?: number } | undefined;
+ return Number(row?.n ?? 0);
+ } catch {
+ return null;
+ }
+ }
+
+ /** Load persisted rows back into the tier maps and the archive. */
+ private hydrate(): void {
+ if (!this.db) return;
+ const rows = this.db
+ .prepare('SELECT * FROM tiered_memory ORDER BY ts ASC')
+ .all() as TieredMemoryRow[];
+ for (const row of rows) {
+ const entry = rowToEntry(row);
+ if (row.archived) {
+ this.archived.push(entry);
+ if (this.archived.length > MAX_ARCHIVED) this.archived.shift();
+ continue;
+ }
+ const map = this.tiers[entry.tier] ?? this.tiers.working;
+ if (map.size >= MAX_PER_TIER) continue;
+ map.set(entry.key, entry);
+ }
+ }
+
+ /**
+ * Write-through. Throws on failure so a store that cannot be persisted
+ * fails loudly instead of reporting success for a lost write.
+ */
+ private persist(entry: TieredMemoryEntry, archived: boolean): void {
+ if (!this.db) return;
+ this.db
+ .prepare(
+ `INSERT INTO tiered_memory (id, key, value, tier, ts, valid_from, valid_until, superseded_by, archived)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ key = excluded.key, value = excluded.value, tier = excluded.tier, ts = excluded.ts,
+ valid_from = excluded.valid_from, valid_until = excluded.valid_until,
+ superseded_by = excluded.superseded_by, archived = excluded.archived`,
+ )
+ .run(
+ entry.id, entry.key, entry.value, entry.tier, entry.ts,
+ entry.validFrom ?? null, entry.validUntil ?? null,
+ entry.supersededBy ?? null, archived ? 1 : 0,
+ );
+ }
+
+ /** Drop a persisted row (used by eviction and remove()). */
+ private unpersist(id: string): void {
+ if (!this.db) return;
+ try {
+ this.db.prepare('DELETE FROM tiered_memory WHERE id = ?').run(id);
+ } catch {
+ // A failed eviction leaves a stale row; harmless next to losing a write.
+ }
+ }
+
/**
* Store an entry. Same-key stores within a tier overwrite (legacy
* behavior); use `options.supersedes` to invalidate-and-keep instead.
@@ -141,8 +311,12 @@ export class TieredMemoryStore {
// Evict oldest if at capacity
if (t.size >= MAX_PER_TIER) {
- const oldest = t.keys().next().value;
- if (oldest !== undefined) t.delete(oldest);
+ const oldestKey = t.keys().next().value;
+ if (oldestKey !== undefined) {
+ const evicted = t.get(oldestKey);
+ t.delete(oldestKey);
+ if (evicted) this.unpersist(evicted.id);
+ }
}
const entry: TieredMemoryEntry = {
@@ -155,8 +329,17 @@ export class TieredMemoryStore {
if (options?.validFrom) entry.validFrom = options.validFrom;
if (options?.validUntil) entry.validUntil = options.validUntil;
+ // Persist BEFORE publishing to the in-memory map: a throw here must not
+ // leave a value visible in-process that never reached disk (#2887).
+ const replaced = t.get(key);
+ this.persist(entry, false);
+ if (replaced && replaced.id !== entry.id) this.unpersist(replaced.id);
t.set(key, entry);
- return { id, key, tier: tierName, superseded };
+ return {
+ id, key, tier: tierName, superseded,
+ durable: this.db !== null,
+ persistence: this.getPersistence(),
+ };
}
/**
@@ -175,8 +358,12 @@ export class TieredMemoryStore {
entry.supersededBy = newId;
map.delete(entry.key);
+ this.persist(entry, true);
this.archived.push(entry);
- if (this.archived.length > MAX_ARCHIVED) this.archived.shift();
+ if (this.archived.length > MAX_ARCHIVED) {
+ const dropped = this.archived.shift();
+ if (dropped) this.unpersist(dropped.id);
+ }
return { id: entry.id, key: entry.key, validUntil: now };
}
@@ -222,7 +409,11 @@ export class TieredMemoryStore {
/** Hard-delete an active entry by key (used by hierarchical-delete). */
remove(key: string): boolean {
for (const map of Object.values(this.tiers)) {
- if (map.delete(key)) return true;
+ const entry = map.get(key);
+ if (!entry) continue;
+ map.delete(key);
+ this.unpersist(entry.id);
+ return true;
}
return false;
}