Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(remember): infer a missing entity from an exact mention (#5836)
garrytanc9a6691beb82
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 2ea539adb5..ec753ce339 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1525 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)-src/core/config.ts 1806 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1)+src/core/config.ts 1807 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key rowsrc/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 618 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy)diff --git a/src/cli.ts b/src/cli.tsindex 0189e60a75..dfc1573546 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -57,6 +57,7 @@ import {findCliCommand,type CliDispatchContext,} from './cli/command-table.ts';+import { formatRememberResult } from './cli/remember-format.ts';// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as a@@ -1758,13 +1759,7 @@ export function formatResult(// flag, so the argv probe is safe).case 'remember': {if (process.argv.includes('--json')) break;- const r = result as any;- if (r.dry_run) return `[dry-run] would remember: ${r.fact}\n`;- const lines = [r.status_text || `${r.status} (fact #${r.id})`];- if (r.entity_slug) lines.push(` entity: ${r.entity_slug}`);- if (r.valid_until) lines.push(` expires: ${r.valid_until}`);- if (r.degraded_dedup) lines.push(' note: no embedding provider — duplicate detection degraded');- return lines.join('\n') + '\n';+ return formatRememberResult(result as Record<string, any>);}case 'entity': {if (process.argv.includes('--json')) break;diff --git a/src/cli/remember-format.ts b/src/cli/remember-format.tsnew file mode 100644index 0000000000..99e780b426--- /dev/null+++ b/src/cli/remember-format.ts@@ -0,0 +1,15 @@+/**+ * Human rendering of a `remember` result (MEMORY_VERBS v1). Kept out of+ * src/cli.ts, which sits at its module-size ceiling. `--json` is handled by+ * the caller and prints the raw envelope instead.+ */+export function formatRememberResult(r: Record<string, any>): string {+ if (r.dry_run) return `[dry-run] would remember: ${r.fact}\n`;+ const lines = [r.status_text || `${r.status} (fact #${r.id})`];+ if (r.entity_slug) lines.push(` entity: ${r.entity_slug}${r.entity_inferred ? ' (inferred from mention)' : ''}`);+ if (r.valid_until) lines.push(` expires: ${r.valid_until}`);+ if (r.degraded_dedup) lines.push(' note: no embedding provider — duplicate detection degraded');+ if (Array.isArray(r.warnings)) for (const warning of r.warnings) lines.push(` warning: ${warning}`);+ if (r.hint) lines.push(` hint: ${r.hint}`);+ return lines.join('\n') + '\n';+}diff --git a/src/core/config.ts b/src/core/config.tsindex d3d598d3c3..595ea7830d 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1411,6 +1411,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// didn't specify one: 'private' (default) | 'world'. Resolved by// src/core/facts/visibility.ts; explicit caller values always win.'facts.default_visibility',+ 'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)// Ambient memory writeback (opt-in, default OFF): 'off' | 'salient' | 'all'.// DUAL-PLANE: `gbrain config set` writes the DB plane (authoritative — the// serve-side harvest gate re-checks it) AND mirrors into the file plane'sdiff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 1ffe33ec31..95e5704c25 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -3,7 +3,10 @@ import type { OperationContext } from '../ops/contract.ts';import { OperationError, verbError } from '../ops/contract.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from '../ops/context.ts';import { isNullLikeEntity } from '../facts/write-single.ts';-import { recordFactWithdrawal } from '../facts/withdrawal.ts';+import { isFactWithdrawn, recordFactWithdrawal } from '../facts/withdrawal.ts';+import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';+import { parseFactsFence } from '../facts-fence.ts';+import { excludesPrivateWrites } from './page-visibility.ts';import { initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';import { authorizeStoredRequest, submissionAuthority } from './authority.ts';import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';@@ -45,22 +48,19 @@ async function submission(ctx: OperationContext, operation: string, params: Recoreturn { p, requestId, sourceId, principal, callerIntent, prior };}-export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {- registerMutationPreparer('remember', prepareMemoryMutation);- const sub = await submission(ctx, 'remember', params);- if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs));- const { p, sourceId, principal, callerIntent, requestId } = sub;- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(- "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);- if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');- const { parseTtlParam } = await import('../ops/facts.ts');- const validUntil = parseTtlParam(p.ttl);- const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');- const resolved = entity ? await resolveEntitySlugWithSource(ctx.engine, sourceId, entity) : null;- const entitySlug = resolved?.slug ?? null;- // A source-scoped absent identity serializes subjectless facts. Bound writers- // cannot use it to escape their namespace grant.+type RememberSource = { incarnation: string; archived: boolean; local_path: string | null; kind: string | null };+type EntityWarning = 'NO_ENTITY' | 'ENTITY_LINK_FAILED';+/** An inferred entity that fails a preflight the explicit path would throw on; the save falls back to unattributed. */+class InferredTargetRejected extends Error { constructor(readonly warning: EntityWarning) { super(warning); } }++/**+ * Every admission check for one target slug. An explicit or unattributed+ * target throws exactly as before; an inferred one (`inferred` set) runs the+ * same checks as predicates and additionally refuses withdrawn claims,+ * malformed fences and any owner claim, so it can fall back instead.+ */+async function planRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, entitySlug: string | null,+ inferred: { fact: string; visibility: string } | null) {const slug = entitySlug ?? 'memory/unattributed';validatePageSlug(slug);enforceClientSlugFence(ctx, slug, 'remember'); enforceSubagentSlugFence(ctx, slug, 'remember');@@ -70,6 +70,9 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco!await ctx.engine.readPageSnapshot(slug, { sourceId, excludePrivate: authority.excludePrivate }))) {throw new OperationError('page_not_found', 'The target entity is not writable by this caller.');}+ if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');+ if (inferred && (await isFactWithdrawn(ctx.engine, sourceId, inferred.visibility, inferred.fact, slug)+ || parseFactsFence(snapshot!.page.compiled_truth).warnings.length)) throw new InferredTargetRejected('ENTITY_LINK_FAILED');// 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;@@ -83,12 +86,60 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco// 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) {+ // 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 });}+ return { slug, authority, snapshot, fence, binding, writeThrough };+}++/**+ * #5836: a fact saved without an entity names its subject from an exact+ * mention, before admission. Any check the inferred target fails falls back+ * to the unattributed save; `warning` is ENTITY_LINK_FAILED only once the+ * target passed every scope and readability check, so a hidden page is never revealed.+ */+async function inferRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, p: Record<string, unknown>):+ Promise<{ target: Awaited<ReturnType<typeof planRememberTarget>>; via: InferredVia } | { warning: EntityWarning } | null> {+ if (p.infer_entity === false || !(await isEntityInferenceEnabled(ctx.engine))) return null;+ const fact = String(p.fact).trim();+ const inferred = await inferFactSubject(ctx.engine, sourceId,+ { fact, mode: 'write', excludePrivate: await excludesPrivateWrites(ctx.engine, ctx.remote !== false) });+ if (inferred.slug === null) return null;+ try {+ const target = await planRememberTarget(ctx, sourceId, source, inferred.slug, { fact, visibility: String(p.visibility ?? 'world') });+ return { target, via: inferred.via };+ } catch (error) {+ if (error instanceof InferredTargetRejected) return { warning: error.warning };+ if (error instanceof OperationError) return null;+ throw error;+ }+}++export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {+ registerMutationPreparer('remember', prepareMemoryMutation);+ const sub = await submission(ctx, 'remember', params);+ if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs));+ const { p, sourceId, principal, callerIntent, requestId } = sub;+ const [source] = await ctx.engine.executeRaw<RememberSource>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');+ const { parseTtlParam } = await import('../ops/facts.ts');+ const validUntil = parseTtlParam(p.ttl);+ const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;+ const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');+ const resolved = entity ? await resolveEntitySlugWithSource(ctx.engine, sourceId, entity) : null;+ const inference = entity === null ? await inferRememberTarget(ctx, sourceId, source, p) : null;+ const linked = inference && 'target' in inference ? inference : null;+ const entitySlug = linked?.target.slug ?? resolved?.slug ?? null;+ // A source-scoped absent identity serializes subjectless facts. Bound writers+ // cannot use it to escape their namespace grant.+ const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null);const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,- intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null },+ intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,+ ...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}) },authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs));}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 179c92ac70..af7eb82b7c 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -9,6 +9,8 @@ import { engineMutationPrecondition, parseMutationPrecondition } from './precondimport { preparePageMutation } from './page-prepare.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';+import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';+import { inferenceNote } from '../facts/subject-infer-write.ts';function conflict(): never { throw new OperationError('revision_conflict', 'The memory changed during semantic preparation.'); }function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): string {@@ -16,12 +18,16 @@ function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): streturn JSON.stringify([value.status, c?.id, c?.fact, c?.kind, c?.visibility,c?.valid_until ? new Date(c.valid_until).toISOString() : null, c?.source_markdown_slug, c?.row_num]);}-function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', entitySlug: string | null, validUntil: Date | string | null, degraded: boolean) {+export const NO_ENTITY_HINT = 'Saved without an entity, so entity-scoped recall will not find it. Pass `entity` (the person, company or project this fact is about) to link it.';+function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', entitySlug: string | null, validUntil: Date | string | null, degraded: boolean, p: Record<string, unknown>) {const statusText = status === 'inserted' ? `remembered as fact #${id}` : status === 'duplicate'? `already knew this — kept fact #${id}` : `updated — fact #${id} supersedes the previous version`;return { id: String(id), status, status_text: statusText, entity_slug: entitySlug,valid_until: validUntil ? new Date(validUntil).toISOString() : null,- ...(degraded ? { degraded_dedup: true } : {}), protocol_version: 1 };+ ...(degraded ? { degraded_dedup: true } : {}),+ ...(entitySlug !== null && p.entity_inferred ? { entity_inferred: p.entity_inferred as InferredVia } : {}),+ ...(entitySlug === null ? { warnings: [p.entity_warning === 'ENTITY_LINK_FAILED' ? 'ENTITY_LINK_FAILED' : 'NO_ENTITY'], hint: NO_ENTITY_HINT } : {}),+ protocol_version: 1 };}/** Every retry renders the semantic append from the latest coherent snapshot. */@@ -41,21 +47,24 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst observedEmbeddingConfig = JSON.stringify(await engine.executeRaw(embeddingConfigSql));const { embedding, embedding_model, degraded } = await prepareFactEmbedding(input.fact, signal);signal?.throwIfAborted();- const decision = await decideSingleFact(engine, row.source_id, input, embedding, embedding_model);+ // #5836: an inferred link dedups exact text only, so it never supersedes or drops a similar fact.+ const dedupEmbedding = p.entity_inferred ? null : embedding;+ const decision = await decideSingleFact(engine, row.source_id, input, dedupEmbedding, embedding_model);const validate = async (tx: BrainEngine) => {await assertFactNotWithdrawn(tx, row.source_id, input);if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict();- const current = await decideSingleFact(tx, row.source_id, input, embedding, embedding_model);+ const current = await decideSingleFact(tx, row.source_id, input, dedupEmbedding, embedding_model);if (candidateState(current) !== candidateState(decision)) conflict();};if (decision.status === 'duplicate') {const duplicate = decision.candidate!;- return { observedRevision, noop: true, validate, apply: async () => outcome(duplicate.id, 'duplicate', input.entity_slug, duplicate.valid_until, degraded) };+ return { observedRevision, noop: true, validate, apply: async () => outcome(duplicate.id, 'duplicate', input.entity_slug, duplicate.valid_until, degraded, p) };}const validUntil = p.valid_until ? new Date(String(p.valid_until)) : null;const validFrom = new Date(String(p.valid_from));+ const context = p.entity_inferred ? appendContextNote(null, inferenceNote(p.entity_inferred as InferredVia)) : undefined;const fact: NewFact = { ...input, source: String(p.provenance).trim(), valid_from: validFrom, valid_until: validUntil,- confidence: 1, embedding, embedding_model };+ confidence: 1, embedding, embedding_model, ...(context ? { context } : {}) };let page: PreparedMutation | undefined;let rowNum: number | undefined;if (p.fence === true && snapshot) {@@ -63,7 +72,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeif (parsed.warnings.length) throw new OperationError('storage_error', 'The entity facts fence is malformed; repair it before appending memory.');const appended = upsertFactRow(snapshot.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),- validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source });+ validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context });rowNum = appended.rowNum;let body = appended.body;const old = decision.candidate;@@ -91,6 +100,6 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque}if (decision.status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);- return outcome(id, decision.status, input.entity_slug, validUntil, degraded);+ return outcome(id, decision.status, input.entity_slug, validUntil, degraded, p);} };}diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 171186d01d..95d25dadfb 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -87,6 +87,11 @@ const remember: Operation = {description:'Person/company/project this fact is about (name or slug; canonicalized server-side). Set it whenever the fact has a subject — entity-scoped recall misses unattributed facts.',},+ infer_entity: {+ type: 'boolean',+ description:+ 'Default true. When `entity` is omitted, link the fact to the one entity page the text names exactly (response `entity_inferred: "mention"`); pass false to save it unattributed.',+ },kind: {type: 'string',enum: [...FACT_KINDS],@@ -484,6 +489,10 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {entity_slug: { type: ['string', 'null'] },valid_until: { type: ['string', 'null'], description: 'ISO 8601 or null (never expires).' },degraded_dedup: { type: 'boolean', description: 'Present (true) when no embedding provider — near-duplicates may insert.' },+ entity_inferred: { type: 'string', enum: ['mention'], description: 'Present when `entity` was omitted and the subject was inferred from an exact mention.' },+ warnings: { type: 'array', items: { type: 'string', enum: ['NO_ENTITY', 'ENTITY_LINK_FAILED'] },+ description: 'NO_ENTITY: saved unattributed. ENTITY_LINK_FAILED: an inferred entity could not be linked; saved unattributed.' },+ hint: { type: 'string', description: 'Present with warnings: how to attribute the fact (pass `entity`).' },write_request: WRITE_RECEIPT_SCHEMA,},},diff --git a/test/remember-entity-inference.test.ts b/test/remember-entity-inference.test.tsnew file mode 100644index 0000000000..8f4976b97b--- /dev/null+++ b/test/remember-entity-inference.test.ts@@ -0,0 +1,181 @@+/**+ * #5836 — remember infers a missing entity from one exact mention before+ * admission, and falls back to the unattributed save (with a NO_ENTITY or+ * ENTITY_LINK_FAILED warning) whenever the inferred target would fail any+ * admission check. Inferred links dedup exact text only. PGLite, synthetic+ * names only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { formatRememberResult } from '../src/cli/remember-format.ts';++let engine: PGLiteEngine;+const sourceId = 'remember-inference-test';+const context = (overrides: Partial<OperationContext> = {}): OperationContext => ({ engine, remote: false, sourceId,+ config: { engine: 'pglite' }, dryRun: false, logger: { info() {}, warn() {}, error() {} }, ...overrides });+const remember = (params: Record<string, unknown>, ctx = context()) =>+ operationsByName.remember!.handler(ctx, { provenance: 'chat 2026-09-30', ...params }) as Promise<Record<string, any>>;++async function putEntity(slug: string, title: string, type: string, body = `# ${title}`, frontmatter: Record<string, unknown> = {}) {+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>+ tx.putPage(slug, { type, title, compiled_truth: body, frontmatter }, { sourceId })));+}+async function factRow(id: string) {+ const [row] = await engine.executeRaw<{ entity_slug: string | null; context: string | null; row_num: number | null; expired_at: Date | null; superseded_by: number | null }>(+ 'SELECT entity_slug,context,row_num,expired_at,superseded_by FROM facts WHERE id=$1', [Number(id)]);+ return row!;+}+async function fenceRows(slug: string) {+ return parseFactsFence((await engine.readPageSnapshot(slug, { sourceId }))!.page.compiled_truth).facts;+}++beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await registerLocalWriter(engine, 'cli'); await registerLocalWriter(engine, 'stdio');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await putEntity('companies/acme-example', 'Acme Example', 'company');+ await putEntity('people/alice-example', 'Alice Example', 'person');+ await putEntity('people/dana-private-example', 'Dana Private-Example', 'person', '# Dana', { visibility: 'private' });+ await putEntity('companies/broken-fence-example', 'Broken Fence Example', 'company',+ '# Broken\n\n<!--- gbrain:facts:begin -->\n| # | claim |\n');+}, 60_000);+afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ resetGateway();+});++describe('remember entity inference (#5836)', () => {+ test('a fact naming one entity links to it, notes the inference in row and fence, and prints it', async () => {+ const r = await remember({ fact: 'Acme Example raised a seed round' });+ expect(r).toMatchObject({ status: 'inserted', entity_slug: 'companies/acme-example', entity_inferred: 'mention' });+ expect(r.warnings).toBeUndefined();+ const row = await factRow(r.id);+ expect(row.entity_slug).toBe('companies/acme-example');+ expect(row.context).toBe('entity inferred from mention');+ expect(row.row_num).not.toBeNull();+ const cell = (await fenceRows('companies/acme-example')).find(f => f.claim === 'Acme Example raised a seed round');+ expect(cell?.context).toBe('entity inferred from mention');+ expect(formatRememberResult(r)).toContain('entity: companies/acme-example (inferred from mention)');+ });++ test('an unattributed save warns NO_ENTITY with a hint naming the entity field', async () => {+ const r = await remember({ fact: 'prefers dark mode in every editor' });+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ expect(r.hint).toContain('`entity`');+ expect(r.entity_inferred).toBeUndefined();+ const printed = formatRememberResult(r);+ expect(printed).toContain('warning: NO_ENTITY');+ expect(printed).toContain('hint: ');+ });++ test('infer_entity:false stores the fact unattributed', async () => {+ const r = await remember({ fact: 'Acme Example opened a second office', infer_entity: false });+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ expect((await factRow(r.id)).entity_slug).toBeNull();+ });++ test('the facts.entity_inference kill switch stores the fact unattributed', async () => {+ await engine.setConfig('facts.entity_inference', 'off');+ try {+ const r = await remember({ fact: 'Acme Example moved its offsite to May' });+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ } finally { await engine.unsetConfig('facts.entity_inference'); }+ });++ test('an explicit entity is unchanged: no inference, no warning, no note', async () => {+ const r = await remember({ fact: 'Alice Example met Acme Example about pricing', entity: 'people/alice-example' });+ expect(r).toMatchObject({ status: 'inserted', entity_slug: 'people/alice-example' });+ expect(r.entity_inferred).toBeUndefined();+ expect(r.warnings).toBeUndefined();+ expect((await factRow(r.id)).context).toBeNull();+ });++ test('a client slug fence that excludes the inferred entity falls back without error', async () => {+ const clientId = `client-${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id,bound_slug_prefixes)+ VALUES($1,'fixture-hash','example-client','read write',$2,$3::text[])`, [clientId, sourceId, ['memory/']]);+ const ctx = context({ remote: true, auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId },+ scopes: ['read', 'write'], sourceId, boundSlugPrefixes: ['memory/'] } as OperationContext['auth'] });+ const r = await remember({ fact: 'Acme Example signed a new lease' }, ctx);+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ const control = await remember({ fact: 'Acme Example signed a second lease' }, context({ remote: true }));+ expect(control.entity_slug).toBe('companies/acme-example');+ });++ test('a subagent fence that excludes the inferred entity falls back without error', async () => {+ const r = await remember({ fact: 'Acme Example renewed the contract' },+ context({ viaSubagent: true, subagentId: 7, allowedSlugPrefixes: ['memory/*'] }));+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ });++ test('a remote caller never links (or learns of) a private entity', async () => {+ const r = await remember({ fact: 'Dana Private-Example is relocating' }, context({ remote: true }));+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['NO_ENTITY']);+ const local = await remember({ fact: 'Dana Private-Example is relocating soon', visibility: 'private' });+ expect(local.entity_slug).toBe('people/dana-private-example');+ });++ test('a malformed target fence warns ENTITY_LINK_FAILED and saves unattributed', async () => {+ const r = await remember({ fact: 'Broken Fence Example hired a CFO' });+ expect(r.entity_slug).toBeNull();+ expect(r.warnings).toEqual(['ENTITY_LINK_FAILED']);+ expect(formatRememberResult(r)).toContain('warning: ENTITY_LINK_FAILED');+ expect((await factRow(r.id)).entity_slug).toBeNull();+ });++ test('a replayed request id returns the original inferred link from the caller intent', async () => {+ const params = { fact: 'Acme Example hired a head of sales', request_id: randomUUID() };+ const first = await remember(params);+ expect(first).toMatchObject({ entity_slug: 'companies/acme-example', entity_inferred: 'mention' });+ await engine.setConfig('facts.entity_inference', 'off');+ try {+ expect(await remember(params)).toEqual(first);+ } finally { await engine.unsetConfig('facts.entity_inference'); }+ });++ test('an inferred link never supersedes a similar fact: both stay active', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-inference' } });+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({ embeddings: opts.values.map(() => [1, ...new Array(1535).fill(0)]) })) as never);+ try {+ const first = await remember({ fact: 'Acme Example targets 40 percent gross margin', entity: 'companies/acme-example' });+ expect(first.status).toBe('inserted');+ const second = await remember({ fact: 'Acme Example targets 45 percent gross margin' });+ expect(second).toMatchObject({ status: 'inserted', entity_slug: 'companies/acme-example', entity_inferred: 'mention' });+ const [a, b] = [await factRow(first.id), await factRow(second.id)];+ expect(a.expired_at).toBeNull();+ expect(a.superseded_by).toBeNull();+ expect(b.expired_at).toBeNull();+ const fence = await fenceRows('companies/acme-example');+ expect(fence.find(f => f.claim === 'Acme Example targets 40 percent gross margin')?.active).toBe(true);+ const exact = await remember({ fact: 'Acme Example targets 45 percent gross margin' });+ expect(exact).toMatchObject({ status: 'duplicate', id: second.id });+ } finally {+ __setEmbedTransportForTests(null);+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ }+ });++ test('facts.entity_inference is a registered config key', async () => {+ const { KNOWN_CONFIG_KEYS } = await import('../src/core/config.ts');+ expect(KNOWN_CONFIG_KEYS).toContain('facts.entity_inference');+ });+});