Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): a brain that opted out of embedding never sends fact text to the provider

garrytan833d1d02a3cd
diff --git a/src/core/embedding-disabled.ts b/src/core/embedding-disabled.ts
index 65ca22088c..fe3ef6cbcd 100644
--- a/src/core/embedding-disabled.ts
+++ b/src/core/embedding-disabled.ts
@@ -4,7 +4,8 @@
* (doctor, onboard, features, jobs): the file-plane `embedding_disabled`
* sentinel, or the DB-plane row init also writes. Never throws.
*/
-import { loadConfig } from './config.ts';
+import { loadConfig, type GBrainConfig } from './config.ts';
+import type { BrainEngine } from './engine.ts';
export async function embeddingsDisabled(engine?: { getConfig(key: string): Promise<string | null> } | null): Promise<boolean> {
try {
@@ -17,3 +18,20 @@ export async function embeddingsDisabled(engine?: { getConfig(key: string): Prom
return false;
}
}
+
+/**
+ * May a fact write send its text to the embedding provider? No when the
+ * effective config disables embedding (the caller's config, else the config
+ * this process's persistence consumer prepares with) or the brain itself does
+ * (file or DB plane). A brain keyless by choice never sends fact text to a
+ * provider, even when a key sits in the environment. Never throws.
+ */
+export async function factEmbeddingDisabled(engine: BrainEngine | null | undefined, config?: GBrainConfig | null): Promise<boolean> {
+ let effective = config ?? null;
+ if (!effective && engine) {
+ const { persistenceConsumerConfig } = await import('./persistence/service.ts');
+ effective = persistenceConsumerConfig(engine) ?? null;
+ }
+ if (effective?.embedding_disabled === true) return true;
+ return embeddingsDisabled(engine);
+}
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 2c6d9b42d7..768989093f 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -638,6 +638,10 @@ export async function extractFactsFromTurnWithOutcome(
const facts: ExtractedFact[] = [];
let junkSkipped = 0;
+ // A caller that resolved the brain's signature passes it (or null); otherwise a brain that opted out of embedding
+ // never has its fact text sent to the provider.
+ const { factEmbeddingDisabled } = await import('../embedding-disabled.ts');
+ const embedFacts = input.embedding !== null && (input.embedding !== undefined || !await factEmbeddingDisabled(input.engine));
for (const candidate of parsedRaw.slice(0, cap)) {
if (input.abortSignal?.aborted) {
const e = new Error('aborted');
@@ -673,7 +677,7 @@ export async function extractFactsFromTurnWithOutcome(
let embedding: Float32Array | null = null;
let embeddingModel: string | null = null;
try {
- if (input.embedding !== null) {
+ if (embedFacts) {
embeddingModel = input.embedding?.model ?? getEmbeddingModel();
embedding = await embedOne(factText, { abortSignal: input.abortSignal, inputType: 'document', embeddingModel,
...(input.embedding ? { embeddingModel: input.embedding.model, dimensions: input.embedding.dimensions } : {}) });
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 2fd0d3a5b9..6de6a01ce6 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -10,10 +10,10 @@ export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded';
export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
}
-/** Provider work belongs to preparation, never to a page/source transaction. */
-export async function prepareFactEmbedding(fact: string, signal?: AbortSignal): Promise<{ embedding: Float32Array | null; embedding_model: string | null; degraded: boolean }> {
+/** Provider work belongs to preparation, never to a page/source transaction. `disabled`: the brain opted out of embedding. */
+export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, disabled = false): Promise<{ embedding: Float32Array | null; embedding_model: string | null; degraded: boolean }> {
signal?.throwIfAborted();
- if (isAvailable('embedding')) {
+ if (!disabled && isAvailable('embedding')) {
try {
const model = getEmbeddingModel();
return { embedding: await embedOne(fact, { abortSignal: signal, embeddingModel: model, inputType: 'document' }), embedding_model: model, degraded: false };
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index 982a4d79d4..7cf54496d3 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -115,7 +115,8 @@ export async function writeSingleFact(
let embedding: Float32Array | null = null;
let embeddingModel: string | null = null;
let degradedDedup = false;
- if (isAvailable('embedding')) {
+ const { factEmbeddingDisabled } = await import('../embedding-disabled.ts');
+ if (!await factEmbeddingDisabled(engine) && isAvailable('embedding')) {
try {
embeddingModel = getEmbeddingModel();
embedding = await embedOne(factText, { embeddingModel, inputType: 'document' });
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 458dd9b5d9..4f4ef0f0f6 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -8,6 +8,7 @@ import { assertPageRevision } from '../page-state/types.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { assertFactNotWithdrawn, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';
+import { factEmbeddingDisabled } from '../embedding-disabled.ts';
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
import { preparePageMutation } from './page-prepare.ts';
import type { PreparedMutation } from './coordinator.ts';
@@ -61,7 +62,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
signal?.throwIfAborted();
const embeddingConfigSql = "SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions') ORDER BY key";
const observedEmbeddingConfig = JSON.stringify(await engine.executeRaw(embeddingConfigSql));
- const { embedding, embedding_model, degraded } = await prepareFactEmbedding(input.fact, signal);
+ const { embedding, embedding_model, degraded } = await prepareFactEmbedding(input.fact, signal, await factEmbeddingDisabled(engine, config));
signal?.throwIfAborted();
// #5836: an inferred link dedups exact text only, so it never supersedes or drops a similar fact.
const dedupEmbedding = p.entity_inferred ? null : embedding;
diff --git a/test/e2e/fact-embedding-opt-out.test.ts b/test/e2e/fact-embedding-opt-out.test.ts
new file mode 100644
index 0000000000..8f632c7d88
--- /dev/null
+++ b/test/e2e/fact-embedding-opt-out.test.ts
@@ -0,0 +1,4 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// The PostgreSQL arm of test/fact-embedding-opt-out.test.ts: no fact text reaches the embedder on an opted-out brain.
+await registerPostgresTests(() => import('../fact-embedding-opt-out.test.ts'));
diff --git a/test/fact-embedding-opt-out.test.ts b/test/fact-embedding-opt-out.test.ts
new file mode 100644
index 0000000000..5f2bb14131
--- /dev/null
+++ b/test/fact-embedding-opt-out.test.ts
@@ -0,0 +1,107 @@
+/**
+ * A brain that opts out of embedding (embedding_disabled in the caller's or
+ * the running consumer's config, or in the brain's DB plane) never sends fact
+ * text to the embedding provider, even when a key sits in the environment.
+ * Covers every fact write path that embeds: writeSingleFact (unmanaged and
+ * managed), remember (prepared by the consumer) and turn extraction (the facts
+ * backstop and conversation extraction). A fake embedder records every call.
+ * PostgreSQL arm: test/e2e/fact-embedding-opt-out.test.ts.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { configureGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';
+import { startPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const ENTITY = 'people/opt-out-example';
+const CLAIM = 'Opt Out Example prefers written agendas.';
+let embedded: string[] = [];
+
+beforeEach(() => {
+ embedded = [];
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'fixture-key', ANTHROPIC_API_KEY: 'fixture-key' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return { embeddings: values.map(() => [1, ...Array(LEGACY_EMBEDDING_CONFIG.embedding_dimensions - 1).fill(0)]) };
+ }) as never);
+ __setChatTransportForTests(async () => ({
+ text: JSON.stringify({ facts: [{ fact: CLAIM, kind: 'preference', entity: ENTITY, confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test',
+ }) as never);
+});
+afterEach(() => { __setEmbedTransportForTests(null); __setChatTransportForTests(null); });
+
+async function seedEntity(engine: BrainEngine, root: string): Promise<void> {
+ const person = await engine.putPage(ENTITY, { type: 'person', title: 'Opt Out Example', compiled_truth: '# Opt Out Example' }, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${ENTITY}.md`, person.id]);
+ const snapshot = (await engine.readPageSnapshot(ENTITY, { sourceId: 'default' }))!;
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, `${ENTITY}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`fact writes on a brain that opted out of embedding send nothing to the provider (${backend})`, () => {
+ // Unmanaged brain shared by the unmanaged cases; each case sets the embedding_disabled row it needs.
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (databaseUrl) {
+ ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ await engine.putPage(ENTITY, { type: 'person', title: 'Opt Out Example', compiled_truth: '# Opt Out Example' });
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('unmanaged writeSingleFact with embedding_disabled on the brain', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ const written = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: ENTITY, kind: 'preference' });
+ expect(written).toMatchObject({ status: 'inserted', degraded_dedup: true });
+ expect(embedded).toEqual([]);
+ await engine.setConfig('embedding_disabled', 'false');
+ await writeSingleFact(engine, 'default', { fact: 'Opt Out Example books rooms early.', provenance: 'fixture', entity: ENTITY, kind: 'preference' });
+ expect(embedded).toEqual(['Opt Out Example books rooms early.']);
+ }, 120_000);
+
+ test('managed writeSingleFact and remember under a keyless consumer', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ expect(ctx.config.embedding_disabled).toBe(true);
+ startPersistenceConsumer(engine, ctx.config);
+ const written = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: ENTITY, kind: 'preference' });
+ expect(written).toMatchObject({ status: 'inserted', entity_slug: ENTITY });
+ const remembered = await operationsByName.remember!.handler(ctx, { fact: 'Opt Out Example reviews notes on Fridays.', provenance: 'fixture',
+ entity: ENTITY, request_id: randomUUID() }) as Record<string, unknown>;
+ expect(remembered).toMatchObject({ state: 'committed', degraded_dedup: true });
+ expect(embedded).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE embedding IS NOT NULL')).toEqual([]);
+ }, { databaseUrl, setup: ({ engine, root }) => seedEntity(engine, root) });
+ }, 180_000);
+
+ test('turn extraction (facts backstop, conversation extraction) with embedding_disabled on the brain', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ const outcome = await extractFactsFromTurnWithOutcome({ turnText: `${CLAIM} They said so in the planning chat.`, source: 'test', engine });
+ expect(outcome).toMatchObject({ ok: true });
+ expect(outcome.ok && outcome.facts.map(f => [f.fact, f.embedding ?? null])).toEqual([[CLAIM, null]]);
+ expect(embedded).toEqual([]);
+ }, 120_000);
+ });
+}
diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.ts
index 6e657bc24b..e34a3f9c63 100644
--- a/test/repair-extractor-facts.test.ts
+++ b/test/repair-extractor-facts.test.ts
@@ -415,7 +415,8 @@ for (const backend of testBackends()) {
startPersistenceConsumer(engine, ctx.config);
const written = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: ENTITY, kind: 'commitment' });
expect(written).toMatchObject({ status: 'inserted', entity_slug: ENTITY });
- expect(embedded).toEqual([CLAIM]);
+ // The keyless consumer's config is the effective config: the claim never reaches the embedder.
+ expect(embedded).toEqual([]);
const [row] = await engine.executeRaw<{ has_vector: boolean }>('SELECT embedding IS NOT NULL AS has_vector FROM facts WHERE id=$1', [written.id]);
expect(row.has_vector).toBe(false);
}, { databaseUrl, setup: async ({ engine, root }) => {