Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): keep extractor-named entities over inference; remember shares the fact write-target rule (#5836)

garrytane4375f44f7f0
diff --git a/src/core/facts/subject-infer-write.ts b/src/core/facts/subject-infer-write.ts
index eb82d1fbee..ec149b922b 100644
--- a/src/core/facts/subject-infer-write.ts
+++ b/src/core/facts/subject-infer-write.ts
@@ -22,6 +22,7 @@ import type { FactsBackstopCtx } from './backstop.ts';
import type { ExtractedFact } from './extract.ts';
import type { ManagedFactsSession } from '../persistence/facts-maintenance.ts';
import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from './subject-infer.ts';
+import { isNullLikeEntity } from './write-single.ts';
/** The context note an inferred link carries, in the DB row and the fence cell alike. */
export function inferenceNote(via: InferredVia): string {
@@ -33,15 +34,15 @@ export async function inferMissingSubjects(ctx: FactsBackstopCtx, facts: Extract
const engine = ctx.engine;
if (!facts.length || !(await isEntityInferenceEnabled(engine))) return facts;
if (!managed && await writesDatabaseOnly(engine, ctx.sourceId)) return facts;
- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const { excludesPrivateWrites } = await import('../persistence/page-visibility.ts');
const remote = managed ? managed.authority.remote : (ctx.operationContext?.remote ?? ctx.remote) !== false;
const excludePrivate = managed?.authority.excludePrivate === true || await excludesPrivateWrites(engine, remote);
const fromPage = remote ? pageSlug : ctx.sourceSlug ?? pageSlug;
const out: ExtractedFact[] = [];
for (const f of facts) {
- const named = f.entity_slug ? await resolveEntitySlugWithSource(engine, ctx.sourceId, f.entity_slug) : null;
- if (named && named.source !== 'fallback_slugify') { out.push(f); continue; }
+ // An extractor-named entity is kept even when it has no page: that name
+ // competes with any page the text mentions, so inference never overrides it.
+ if (!isNullLikeEntity(f.entity_slug)) { out.push(f); continue; }
const inferred = await inferFactSubject(engine, ctx.sourceId, { fact: f.fact, pageSlug: fromPage, mode: 'write', excludePrivate });
if (inferred.slug !== null && await linkAllowed(ctx, inferred.slug, f.fact, visibility, remote, managed)) {
out.push({ ...f, entity_slug: inferred.slug, entity_inferred: inferred.via });
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 95e5704c25..543c593348 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -11,8 +11,8 @@ import { initializeLocalPersistence, requestPrincipalForContext } from './page-m
import { authorizeStoredRequest, submissionAuthority } from './authority.ts';
import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';
import { assertPersistenceAccepting, registerMutationPreparer, waitForWrite, writeResponse } from './service.ts';
-import { claimWorktree, getWorktreeBinding } from './ownership.ts';
-import { isConnectorSourceKind } from './connector-identity.ts';
+import { claimWorktree } from './ownership.ts';
+import { resolveFactWriteTarget } from './fact-write-target.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { parseMutationPrecondition } from './preconditions.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -76,20 +76,19 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
// Preserve the stub guard: a fallback name remains DB-only until a real
// entity page exists. No placeholder page is created by remember.
const fence = entitySlug !== null && snapshot !== null;
- let binding = fence ? await getWorktreeBinding(ctx.engine, sourceId) : null;
const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);
const configuredWriteThrough = !/^(false|0|off|no)$/i.test(await ctx.engine.getConfig('sync.write_through') ?? 'true');
const writeThrough = configuredWriteThrough && !sandbox;
if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';
else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';
- const root = source.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);
- // An unbound connector source is database-only by design; never claim it for a fence write.
- if (fence && writeThrough && root && !binding && isConnectorSourceKind(source.kind)) authority.databaseOnlyReason = 'connector_database';
- else if (fence && writeThrough && root && !binding) {
+ const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source, { sandbox }) : null;
+ let binding = target?.kind === 'publish' ? target.binding : null;
+ if (target?.kind === 'publish' && target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;
+ if (target?.kind === 'unbound') {
// An inferred link never designates an owner or reports a missing one.
if (inferred) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
if (ctx.engine.kind !== 'pglite') throw new OperationError('owner_unavailable', 'This source has no designated canonical owner.', WRITER_INSPECTION_HINT);
- binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });
+ binding = await claimWorktree(ctx.engine, sourceId, target.root, undefined, undefined, { automatic: true });
}
return { slug, authority, snapshot, fence, binding, writeThrough };
}
diff --git a/test/helpers/managed-facts-contract.ts b/test/helpers/managed-facts-contract.ts
index 3467fcaea5..287ec17050 100644
--- a/test/helpers/managed-facts-contract.ts
+++ b/test/helpers/managed-facts-contract.ts
@@ -36,9 +36,6 @@ export async function exerciseManagedFacts(engine: BrainEngine, scenario: Case):
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
await engine.setConfig('version', '162');
await engine.setConfig('facts.default_visibility', 'private');
- // The unparented case pins the fallback-entity -> NULL path; its fixture text names a
- // registered entity, which #5836 write-time inference would otherwise link.
- if (scenario === 'unparented') await engine.setConfig('facts.entity_inference', 'off');
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
const firstSlug = 'people/alice-example', secondSlug = 'companies/acme-example';
const oldBody = upsertFactRow('A registered entity.', { claim: 'An older retained fact.', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', source: 'fixture' }).body;
@@ -187,5 +184,5 @@ export async function exerciseManagedFacts(engine: BrainEngine, scenario: Case):
expect(afterVector.vector).toBe(beforeVector.vector);
if (scenario === 'unparented') expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND entity_slug IS NULL', [sourceId])).toHaveLength(1);
});
- } finally { await disposePersistenceConsumer(engine); await engine.unsetConfig('facts.entity_inference'); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); rmSync(home, { recursive: true, force: true }); }
+ } finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); rmSync(home, { recursive: true, force: true }); }
}