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

feat(memory): add native immutable conditional append controls

Stuart Kerr148f03820d30
diff --git a/docs/memory/conditional-append.md b/docs/memory/conditional-append.md
new file mode 100644
index 0000000000..ef99915099
--- /dev/null
+++ b/docs/memory/conditional-append.md
@@ -0,0 +1,38 @@
+Updated: 2026-10-05 EDT | Version 0.1.0
+Created: 2026-10-05 EDT
+
+# Native conditional append for structured continuity records
+
+This source candidate adds explicit controls to `memory store`. Existing calls retain their
+embedding, upsert and backend fallback behavior. It is not an installed or published capability.
+
+- `--no-embedding` avoids embedding structured records.
+- `--require-native` refuses WASM and whole-image sql.js fallback before writing a record.
+- `--append-only` never replaces active records or resurrects tombstones.
+- `--append-conditions '<JSON array>'` requires both native and append-only controls. One to eight
+ predicates run inside the same native immediate transaction as the record insertion.
+
+A record predicate `{namespace, key, sha256}` checks the exact UTF-8 stored content digest and active
+status. Optional `latestPrefix` requires that key to be the latest slot with the literal prefix.
+The latest lookup includes tombstones so deleting an authority epoch cannot rewind authority.
+`{namespace, absent:true, latestPrefix}` requires no slot with that prefix, including tombstones.
+`{namespace, count, keysSha256}` checks complete active key membership; the digest covers
+`JSON.stringify(sortedKeys)`. It reads keys only, never historical content.
+
+An append-only publication should use one project-wide next-sequence key and predicates binding the
+exact immutable candidate, current parent publication, current authority epoch and retained legacy
+membership. Parent existence alone does not establish tip authority: use `latestPrefix`. Genesis
+uses the absent-prefix predicate. Authority withdrawal must first commit a newer epoch through the
+canonical provider. A former writer then fails its publication transaction even when its earlier
+work was still in flight. A failed contender remains pending and must rebase; this primitive never
+acknowledges or silently merges competing candidates.
+
+No second store or writer is introduced. `memory store` remains the public entry point and writes
+its explicit canonical `--path`. Immutable inserts without embeddings leave namespace vector totals
+unchanged, so this path avoids a lifetime namespace vector recount.
+
+Validation: focused native/CLI tests, full referenced TypeScript workspace build, and the built
+local standard CLI against a disposable canonical memory.db. The CLI rejected a stale epoch with
+exit 1 and no publication row; current-epoch publication returned exit 0 with exact independent
+SQLite readback and NULL embedding. This does not prove installation, upstream publication or
+production continuity cutover.
diff --git a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts
index 24bdce8e4f..a6527b4559 100644
--- a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts
+++ b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts
@@ -50,6 +50,15 @@ beforeEach(() => {
afterAll(() => rmSync(tempDir, { recursive: true, force: true }));
describe('namespace path-traversal validation on write paths (#3570)', () => {
+ it('passes explicit structured native append controls and preserves default embeddings', async () => {
+ await storeCommand.action!({ args: [], flags: { key: 'structured', value: 'state', embedding: false,
+ requireNative: true, appendOnly: true, appendConditions: JSON.stringify([{ namespace: 'project', absent: true, latestPrefix: 'published-' }]) } } as any);
+ expect(mocks.storeEntry).toHaveBeenLastCalledWith(expect.objectContaining({ generateEmbeddingFlag: false,
+ requireNative: true, appendOnly: true, appendConditions: [{ namespace: 'project', absent: true, latestPrefix: 'published-' }] }));
+ await storeCommand.action!({ args: [], flags: { key: 'ordinary', value: 'text' } } as any);
+ expect(mocks.storeEntry).toHaveBeenLastCalledWith(expect.objectContaining({ generateEmbeddingFlag: true,
+ requireNative: false, appendOnly: false }));
+ });
it('memory export already rejects the traversal namespace (the reference behaviour)', async () => {
await expect(
exportTool.handler({ outputPath: join(tempDir, 'x.json'), namespace: '../../..' }),
diff --git a/v3/@claude-flow/cli/__tests__/memory-structured-append.test.ts b/v3/@claude-flow/cli/__tests__/memory-structured-append.test.ts
new file mode 100644
index 0000000000..2ad710a4c1
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-structured-append.test.ts
@@ -0,0 +1,133 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import Database from 'better-sqlite3';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { bridgeStoreEntry, __setMemoryBridgeRegistryForTests } from '../src/memory/memory-bridge.js';
+
+const root = mkdtempSync(join(tmpdir(), 'ruflo-structured-append-'));
+const dbPath = join(root, 'memory.db');
+const db = new Database(dbPath);
+db.exec(`CREATE TABLE memory_entries (
+ id TEXT PRIMARY KEY, key TEXT NOT NULL, namespace TEXT DEFAULT 'default', content TEXT NOT NULL,
+ type TEXT, embedding TEXT, embedding_dimensions INTEGER, embedding_model TEXT, tags TEXT,
+ metadata TEXT, provenance_type TEXT, created_at INTEGER, updated_at INTEGER, expires_at INTEGER,
+ status TEXT DEFAULT 'active', UNIQUE(namespace,key));
+ CREATE TABLE vector_indexes (id TEXT PRIMARY KEY, name TEXT UNIQUE, dimensions INTEGER,
+ total_vectors INTEGER DEFAULT 0, updated_at INTEGER);
+ INSERT INTO vector_indexes(id,name,dimensions,total_vectors) VALUES('fixture','fixture',384,1);
+ INSERT INTO memory_entries(id,key,namespace,content,embedding,status)
+ VALUES('vector','historical-vector','fixture','preserved','[1]','active');`);
+const embed = vi.fn();
+const sql: string[] = [];
+const prepare = db.prepare.bind(db);
+db.prepare = ((statement: string) => { sql.push(statement); return prepare(statement); }) as typeof db.prepare;
+beforeEach(() => {
+ sql.length = 0; embed.mockClear();
+ __setMemoryBridgeRegistryForTests({ getAgentDB: () => ({ database: db, embedder: { embed } }), get: () => null });
+});
+afterAll(() => { __setMemoryBridgeRegistryForTests(null); db.close(); rmSync(root, { recursive: true, force: true }); });
+const append = (key: string, value = 'exact redacted state') => bridgeStoreEntry({
+ key, value, namespace: 'fixture', dbPath, generateEmbeddingFlag: false,
+ requireNative: true, appendOnly: true, upsert: true, provenanceType: 'system_observation',
+});
+
+describe('native structured immutable append', () => {
+ it('stores exact content and provenance without embedding or lifetime vector recount', async () => {
+ const result = await append('new');
+ expect(result?.success).toBe(true);
+ expect(prepare('SELECT content,embedding,provenance_type FROM memory_entries WHERE key=?').get('new'))
+ .toEqual({ content: 'exact redacted state', embedding: null, provenance_type: 'system_observation' });
+ expect(embed).not.toHaveBeenCalled();
+ expect(sql.some(s => /UPDATE vector_indexes SET[\s\S]*COUNT/.test(s))).toBe(false);
+ expect(prepare('SELECT total_vectors FROM vector_indexes WHERE name=?').get('fixture')).toEqual({ total_vectors: 1 });
+ });
+ it('never overwrites an active or deleted key, even when upsert was also requested', async () => {
+ expect((await append('new', 'overwrite'))?.success).not.toBe(true);
+ expect(prepare('SELECT content FROM memory_entries WHERE key=?').get('new')).toEqual({ content: 'exact redacted state' });
+ prepare("UPDATE memory_entries SET status='deleted' WHERE key=?").run('historical-vector');
+ expect((await append('historical-vector', 'resurrection'))?.success).not.toBe(true);
+ expect(prepare('SELECT content,status,embedding FROM memory_entries WHERE key=?').get('historical-vector'))
+ .toEqual({ content: 'preserved', status: 'deleted', embedding: '[1]' });
+ });
+ it('refuses a WASM bridge before any write or embedding', async () => {
+ __setMemoryBridgeRegistryForTests({ getAgentDB: () => ({ database: db, isWasm: true, embedder: { embed } }), get: () => null });
+ const result = await append('wasm-refused');
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/non-native bridge/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('wasm-refused')).toBeUndefined();
+ expect(embed).not.toHaveBeenCalled();
+ expect(sql.some(s => /INSERT INTO memory_entries/.test(s))).toBe(false);
+ });
+});
+
+import { createHash } from 'node:crypto';
+const sha = (value: string) => createHash('sha256').update(value).digest('hex');
+const conditioned = (key: string, epochKey: string, epochValue: string) => bridgeStoreEntry({
+ key, value: 'publication', namespace: 'fixture', dbPath, generateEmbeddingFlag: false,
+ requireNative: true, appendOnly: true,
+ appendConditions: [{ namespace: 'fixture', key: epochKey, sha256: sha(epochValue), latestPrefix: 'epoch-' }],
+});
+describe('native atomic publication authority', () => {
+ it('checks exact authority bytes and the latest epoch in the insertion transaction', async () => {
+ expect((await append('epoch-0001', 'first'))?.success).toBe(true);
+ expect((await conditioned('published-0001', 'epoch-0001', 'first'))?.success).toBe(true);
+ expect((await append('epoch-0002', 'second'))?.success).toBe(true);
+ expect(await conditioned('stale-publication', 'epoch-0001', 'first'))
+ .toMatchObject({ success: false, error: expect.stringMatching(/newer parent\/authority/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('stale-publication')).toBeUndefined();
+ expect(await conditioned('wrong-body', 'epoch-0002', 'forged'))
+ .toMatchObject({ success: false, error: expect.stringMatching(/bytes changed/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('wrong-body')).toBeUndefined();
+ });
+ it('cannot rewind authority by deleting its newest epoch', async () => {
+ prepare("UPDATE memory_entries SET status='deleted' WHERE key=?").run('epoch-0002');
+ expect((await conditioned('rewound-publication', 'epoch-0001', 'first'))?.success).toBe(false);
+ expect((await conditioned('deleted-authority-publication', 'epoch-0002', 'second'))?.success).toBe(false);
+ });
+ it('refuses conditions without the native and immutable prerequisites', async () => {
+ const result = await bridgeStoreEntry({ key: 'unsafe-condition', value: 'unsafe', namespace: 'fixture', dbPath,
+ generateEmbeddingFlag: false, appendConditions: [{ namespace: 'fixture', key: 'epoch-0001', sha256: sha('first') }] });
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/requires native append-only/) });
+ });
+});
+
+describe('transactional genesis and legacy membership', () => {
+ it('allows one project-wide genesis slot and refuses a second migration identity', async () => {
+ const conditions = [{ namespace: 'fixture', absent: true as const, latestPrefix: 'genesis-' }];
+ const first = await bridgeStoreEntry({ key: 'genesis-0001', value: 'one', namespace: 'fixture', dbPath,
+ generateEmbeddingFlag: false, requireNative: true, appendOnly: true, appendConditions: conditions });
+ expect(first?.success).toBe(true);
+ const second = await bridgeStoreEntry({ key: 'genesis-0002', value: 'two', namespace: 'fixture', dbPath,
+ generateEmbeddingFlag: false, requireNative: true, appendOnly: true, appendConditions: conditions });
+ expect(second).toMatchObject({ success: false, error: expect.stringMatching(/newer parent\/authority/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('genesis-0002')).toBeUndefined();
+ });
+ it('refuses publication when an unsequenced legacy writer changes covered membership', async () => {
+ const keys = prepare("SELECT key FROM memory_entries WHERE namespace='fixture' AND (status='active' OR status IS NULL)")
+ .all().map((row: any) => row.key).sort();
+ expect((await append('unsequenced-addition'))?.success).toBe(true);
+ const result = await bridgeStoreEntry({ key: 'legacy-race-publication', value: 'unsafe', namespace: 'fixture', dbPath,
+ generateEmbeddingFlag: false, requireNative: true, appendOnly: true,
+ appendConditions: [{ namespace: 'fixture', count: keys.length, keysSha256: sha(JSON.stringify(keys)) }] });
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/membership changed/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('legacy-race-publication')).toBeUndefined();
+ });
+});
+
+describe('withdrawn authority while an older writer is inflight', () => {
+ it('rejects the old publication when its delayed work resumes after a newer epoch commits', async () => {
+ expect((await append('inflight-epoch-0001', 'first'))?.success).toBe(true);
+ let resume!: (vector: number[]) => void;
+ let entered!: () => void;
+ const waiting = new Promise<void>(resolve => { entered = resolve; });
+ embed.mockImplementationOnce(() => { entered(); return new Promise<number[]>(resolve => { resume = resolve; }); });
+ const old = bridgeStoreEntry({ key: 'inflight-stale-publication', value: 'old', namespace: 'fixture', dbPath,
+ generateEmbeddingFlag: true, requireNative: true, appendOnly: true,
+ appendConditions: [{ namespace: 'fixture', key: 'inflight-epoch-0001', sha256: sha('first'), latestPrefix: 'inflight-epoch-' }] });
+ await waiting;
+ expect((await append('inflight-epoch-0002', 'second'))?.success).toBe(true);
+ resume([1, 2, 3]);
+ expect(await old).toMatchObject({ success: false, error: expect.stringMatching(/newer parent\/authority/) });
+ expect(prepare('SELECT 1 FROM memory_entries WHERE key=?').get('inflight-stale-publication')).toBeUndefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index 4c9aa1e6c9..0c9ad8b3f1 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -1,3 +1,4 @@
+import { validateAppendConditions } from '../memory/append-conditions.js';
/**
* V3 CLI Memory Command
* Memory operations for AgentDB integration
@@ -117,6 +118,10 @@ const storeCommand: Command = {
type: 'boolean',
default: false
},
+ { name: 'embedding', type: 'boolean', description: 'Generate an embedding (default true; --no-embedding stores structured data only)' },
+ { name: 'append-conditions', type: 'string', description: 'JSON predicates checked atomically with a native append-only write' },
+ { name: 'require-native', type: 'boolean', description: 'Refuse whole-image and in-memory fallback memory writers' },
+ { name: 'append-only', type: 'boolean', description: 'Immutable insert; never update or resurrect an existing key' },
{
name: 'upsert',
short: 'u',
@@ -249,7 +254,7 @@ const storeCommand: Command = {
output.printInfo(`Storing in ${namespace}/${key}...`);
- // Use direct sql.js storage with automatic embedding generation
+ // Use the canonical provider; embedding and native immutable append controls are explicit.
try {
const { storeEntry, resolveDbPath: _rdbStore } = await import('../memory/memory-initializer.js');
const dbPath = _rdbStore(ctx.flags.path as string | undefined);
@@ -262,7 +267,10 @@ const storeCommand: Command = {
key,
value,
namespace,
- generateEmbeddingFlag: true, // Always generate embeddings for semantic search
+ generateEmbeddingFlag: ctx.flags.embedding !== false,
+ requireNative: ctx.flags.requireNative === true,
+ appendOnly: ctx.flags.appendOnly === true,
+ ...(typeof ctx.flags.appendConditions === 'string' ? { appendConditions: validateAppendConditions(JSON.parse(ctx.flags.appendConditions)) } : {}),
tags,
ttl,
upsert,
diff --git a/v3/@claude-flow/cli/src/memory/append-conditions.ts b/v3/@claude-flow/cli/src/memory/append-conditions.ts
new file mode 100644
index 0000000000..848074c1fd
--- /dev/null
+++ b/v3/@claude-flow/cli/src/memory/append-conditions.ts
@@ -0,0 +1,59 @@
+/** Native append predicates checked in the SAME write transaction as an immutable insert. */
+import { createHash } from 'node:crypto';
+export type AppendCondition = { namespace: string } & (
+ | { key: string; sha256: string; latestPrefix?: string }
+ | { absent: true; latestPrefix: string }
+ | { keysSha256: string; count: number }
+);
+export class AppendConditionFailed extends Error {}
+const text = (value: unknown, limit: number) => typeof value === 'string' && value.length > 0 && value.length <= limit;
+const digest = (value: unknown) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
+export function validateAppendConditions(input: unknown): AppendCondition[] {
+ if (!Array.isArray(input) || input.length < 1 || input.length > 8) throw new TypeError('append conditions must contain 1-8 predicates');
+ return input.map(condition => {
+ if (!condition || typeof condition !== 'object' || Array.isArray(condition)) throw new TypeError('invalid append condition');
+ const row = condition as Record<string, unknown>;
+ const fields = Object.keys(row).sort().join(',');
+ const validRecord = ['key,namespace,sha256', 'key,latestPrefix,namespace,sha256'].includes(fields)
+ && text(row.key, 1024) && digest(row.sha256) && (row.latestPrefix === undefined || text(row.latestPrefix, 1024));
+ const validAbsent = fields === 'absent,latestPrefix,namespace' && row.absent === true && text(row.latestPrefix, 1024);
+ const validKeys = fields === 'count,keysSha256,namespace' && digest(row.keysSha256)
+ && Number.isSafeInteger(row.count) && (row.count as number) >= 0 && (row.count as number) <= 100_000;
+ if (!text(row.namespace, 256) || !(validRecord || validAbsent || validKeys)) throw new TypeError('invalid append condition');
+ return row as AppendCondition;
+ });
+}
+interface NativeReader {
+ prepare(sql: string): { all(...parameters: string[]): Array<{ key: string; content: string; status: string | null }> };
+}
+const sha = (value: string) => createHash('sha256').update(value).digest('hex');
+export function assertAppendConditions(db: NativeReader, conditions: AppendCondition[]): void {
+ for (const condition of conditions) {
+ if ('keysSha256' in condition) {
+ const rows = db.prepare("SELECT key FROM memory_entries WHERE namespace = ? AND (status = 'active' OR status IS NULL)")
+ .all(condition.namespace);
+ const keys = rows.map(row => row.key).sort();
+ if (keys.length !== condition.count || sha(JSON.stringify(keys)) !== condition.keysSha256) {
+ throw new AppendConditionFailed('immutable append rejected: namespace membership changed');
+ }
+ continue;
+ }
+ if ('key' in condition) {
+ const rows = db.prepare('SELECT key, content, status FROM memory_entries WHERE namespace = ? AND key = ?')
+ .all(condition.namespace, condition.key);
+ if (rows.length !== 1 || !['active', null].includes(rows[0].status)
+ || typeof rows[0].content !== 'string' || sha(rows[0].content) !== condition.sha256) {
+ throw new AppendConditionFailed('immutable append rejected: expected parent/authority bytes changed or absent');
+ }
+ }
+ if (condition.latestPrefix !== undefined) {
+ // Include tombstones: deleting a new authority slot must never rewind to an older authority.
+ const pattern = condition.latestPrefix.replace(/[\\%_]/g, character => `\\${character}`) + '%';
+ const latest = db.prepare("SELECT key, content, status FROM memory_entries WHERE namespace = ? AND key LIKE ? ESCAPE '\\' ORDER BY key COLLATE BINARY DESC LIMIT 1")
+ .all(condition.namespace, pattern);
+ if ('absent' in condition ? latest.length !== 0 : latest.length !== 1 || latest[0].key !== condition.key) {
+ throw new AppendConditionFailed('immutable append rejected: newer parent/authority slot exists');
+ }
+ }
+ }
+}
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index df0252ca75..b9718daf34 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -1,3 +1,4 @@
+import { AppendConditionFailed, assertAppendConditions, validateAppendConditions, type AppendCondition } from './append-conditions.js';
/**
* Memory Bridge — Routes CLI memory operations through ControllerRegistry + AgentDB v3
*
@@ -1034,6 +1035,9 @@ export async function bridgeStoreEntry(options: {
ttl?: number;
dbPath?: string;
upsert?: boolean;
+ requireNative?: boolean;
+ appendOnly?: boolean;
+ appendConditions?: AppendCondition[];
/** ADR-323: defaults to 'unknown' when omitted. */
provenanceType?: string;
}): Promise<{
@@ -1075,13 +1079,20 @@ export async function bridgeStoreEntry(options: {
const ctx = getDb(registry);
if (!ctx) return null;
+ if (options.appendConditions && (!options.requireNative || !options.appendOnly)) {
+ return { success: false, id: "", error: "Conditional append requires native append-only storage" };
+ }
+ if (options.requireNative && (ctx.agentdb?.isWasm === true || typeof ctx.db.inTransaction !== 'boolean' || typeof ctx.db.transaction !== "function")) {
+ return { success: false, id: '', error: 'Native memory writer required; refusing non-native bridge driver' };
+ }
+
try {
const { key, value, namespace = 'default', tags = [], ttl } = options;
let provenanceType = options.provenanceType ?? 'unknown';
// An omitted type on an upsert means "update the value", not "erase the
// existing trust label". New rows still receive the backward-compatible
// unknown default.
- if (options.upsert && options.provenanceType === undefined) {
+ if (options.upsert && !options.appendOnly && options.provenanceType === undefined) {
try {
const existing = ctx.db.prepare(
'SELECT provenance_type FROM memory_entries WHERE namespace = ? AND key = ? LIMIT 1'
@@ -1143,7 +1154,12 @@ export async function bridgeStoreEntry(options: {
// below → typed "already exists"
// error, NEVER a null demotion).
// Upsert path (INSERT OR REPLACE) is unchanged.
- const insertSql = options.upsert
+ const immutableInsertSql = `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')`;
+ const insertSql = options.appendOnly ? immutableInsertSql : options.upsert
? `INSERT OR REPLACE INTO memory_entries (
id, key, namespace, content, type,
embedding, embedding_dimensions, embedding_model,
@@ -1181,7 +1197,7 @@ export async function bridgeStoreEntry(options: {
} catch { /* vector_indexes may not exist on legacy DBs — fall through */ }
const stmt = ctx.db.prepare(insertSql);
- const runResult = stmt.run(
+ const insert = () => stmt.run(
id, key, namespace, value,
embeddingJson, dimensions || null, model,
tags.length > 0 ? JSON.stringify(tags) : null,
@@ -1191,6 +1207,21 @@ export async function bridgeStoreEntry(options: {
ttl ? now + (ttl * 1000) : null
);
+ let runResult;
+ try {
+ runResult = options.appendConditions
+ ? ctx.db.transaction(() => {
+ assertAppendConditions(ctx.db, validateAppendConditions(options.appendConditions));
+ return insert();
+ }).immediate()
+ : insert();
+ } catch (error) {
+ if (error instanceof AppendConditionFailed || error instanceof TypeError) {
+ return { success: false, id: '', error: error.message };
+ }
+ throw error;
+ }
+
// A completed native write proves the bridge is currently healthy. Do not
// retain a diagnostic from an earlier transient failure and append it to a
// later, unrelated sql.js fallback refusal.
@@ -1209,9 +1240,11 @@ export async function bridgeStoreEntry(options: {
};
}
+ // A non-vector immutable INSERT cannot change the vector count, even with concurrent
+ // writers. Unlike historical strict mode, it never resurrects a vector tombstone.
// #2558: keep `vector_indexes.total_vectors` accurate so status/tooling
// stop reporting "HNSW index: 0 vectors" while embedded entries exist.
- try {
+ if (!(options.appendOnly && embeddingJson === null)) try {
ctx.db
.prepare(
`UPDATE vector_indexes SET
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index a2600fd649..00e6547599 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -1,3 +1,4 @@
+import type { AppendCondition } from './append-conditions.js';
/**
* V3 Memory Initializer
* Properly initializes the memory database with sql.js (WASM SQLite)
@@ -2889,6 +2890,9 @@ export async function storeEntry(options: {
ttl?: number;
dbPath?: string;
upsert?: boolean;
+ requireNative?: boolean;
+ appendOnly?: boolean;
+ appendConditions?: AppendCondition[];
/** ADR-323: defaults to 'unknown' when omitted. */
provenanceType?: string;
}): Promise<{
@@ -2936,6 +2940,10 @@ export async function storeEntry(options: {
}
}
+ if (options.requireNative || options.appendConditions) {
+ return { success: false, id: '', error: 'Native memory writer required; refusing whole-image sql.js fallback' };
+ }
+
// Fallback: raw sql.js
const {
key,
@@ -2945,9 +2953,10 @@ export async function storeEntry(options: {
tags = [],
ttl,
dbPath: customPath,
- upsert = false,
+ upsert: requestedUpsert = false,
provenanceType
} = options;
+ const upsert = requestedUpsert && !options.appendOnly;
const swarmDir = getMemoryRoot();
const dbPath = customPath ? path.resolve(customPath) : path.join(swarmDir, 'memory.db');