Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(memory): saved facts reach the entity card, recall and search for accounts with identity siblings

garrytanf393b79bac13
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index db2204e89e..dab50f46b9 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -82,7 +82,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 4cfa88e778..b13baa95a6 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -397,7 +397,7 @@ title prefix, shown, never merged; more than 3 is `capped` with an
`identity_siblings_capped` notice); `identity_excerpt[]` (`{ slug, line }`,
verbatim name-like lines from the remote-sanitized body, 600 characters per
page and 1,200 per card, `identity_excerpt_omitted[]`); `alias_guidance`
-(`{ text, requires_surface? }`).
+(`{ text, requires_surface? }`). `recent_facts[]` (`{ id, fact, kind, valid_from, entity_slug? }`, the 5 newest active saved facts, also those saved under an identity sibling or the bare subject slug, which carry that `entity_slug`); `active_fact_count` and `recall {entity}` cover the same slugs.
#### entity open_threads loop backing (additive)
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index e6809bef99..6a204122e4 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -21,6 +21,8 @@
* unprefixed holding path rather than guessing from connection count.
*/
+import { siblingCanonical } from '../mentions/siblings.ts';
+import { loadLinkableTypes } from '../mentions/policy.ts';
import type { BrainEngine } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { foldNonDecomposingLatin } from '../latin-fold.ts';
@@ -173,7 +175,7 @@ async function tryAliasExact(engine: BrainEngine, source_id: string, raw: string
[source_id, [...new Set(hits.map((h) => h.slug))]],
);
const live = [...new Set(rows.map((r) => r.slug))];
- return live.length === 1 ? live[0] : null;
+ return live.length === 1 ? live[0] : await siblingCanonical(engine, source_id, live);
} catch (err) {
if (!isUndefinedTableError(err) && !aliasExactWarned) {
aliasExactWarned = true;
@@ -277,7 +279,10 @@ export async function resolveEntitySlugWithSource(
const aliased = await tryAliasExact(engine, source_id, trimmed);
if (aliased) return { slug: aliased, source: 'alias_exact' };
- if (basenames.length > 1) return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };
+ if (basenames.length > 1) {
+ const sibling = await siblingCanonical(engine, source_id, basenames.map(b => b.slug));
+ return sibling ? { slug: sibling, source: 'fuzzy_match' } : { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };
+ }
if (isBareName(trimmed)) {
const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, trimmed);
@@ -330,26 +335,36 @@ export async function resolveStrictEntityReference(
WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug = ANY($2::text[]) ${privacy}`,
[source_id, [...new Set(slugs)]],
);
- const pick = (rows: Array<{ slug: string; type: string | null }>, arm: StrictResolutionArm): StrictResolution | null => {
- if (rows.length > 1) return { slug: null, miss: 'ambiguous' };
+ // The source pack's linkable entity types (accounts, CRM records, ...) are fact entities too.
+ let linkable: Set<string> | null = null;
+ const isEntity = async (r: { slug: string; type: string | null }) => {
+ if (isFactEntityPage(r.slug, r.type)) return true;
+ linkable ??= new Set((await loadLinkableTypes(engine, source_id).catch(() => ({ types: [] as string[] }))).types);
+ return r.type != null && linkable.has(r.type);
+ };
+ const pick = async (rows: Array<{ slug: string; type: string | null }>, arm: StrictResolutionArm): Promise<StrictResolution | null> => {
+ if (rows.length > 1) {
+ const sibling = await siblingCanonical(engine, source_id, rows.map(r => r.slug), { excludePrivate: opts.excludePrivate });
+ return sibling ? { slug: sibling, arm } : { slug: null, miss: 'ambiguous' };
+ }
if (rows.length === 0) return null;
- return isFactEntityPage(rows[0].slug, rows[0].type) ? { slug: rows[0].slug, arm } : { slug: null, miss: 'not_entity' };
+ return await isEntity(rows[0]) ? { slug: rows[0].slug, arm } : { slug: null, miss: 'not_entity' };
};
if (looksLikeSlug(trimmed)) {
- const exact = pick(await live([trimmed]), 'exact_page');
+ const exact = await pick(await live([trimmed]), 'exact_page');
if (exact) return exact;
}
const token = slugify(trimmed);
if (!trimmed.includes('/') && token.includes('-')) {
- const basename = pick(await live([...PREFIX_EXPANSION_DIRS, 'concepts'].map(dir => `${dir}/${token}`)), 'basename');
+ const basename = await pick(await live([...PREFIX_EXPANSION_DIRS, 'concepts'].map(dir => `${dir}/${token}`)), 'basename');
if (basename) return basename;
}
const norm = normalizeAlias(trimmed);
if (norm) {
try {
const hits = (await engine.resolveAliases([norm], { sourceId: source_id })).get(norm) ?? [];
- const aliased = pick(await live(hits.map(h => h.slug)), 'alias_exact');
+ const aliased = await pick(await live(hits.map(h => h.slug)), 'alias_exact');
if (aliased) return aliased;
} catch (err) {
if (!isUndefinedTableError(err)) throw err;
@@ -365,7 +380,7 @@ export async function resolveStrictEntityReference(
LIMIT 5`,
[source_id, trimmed.toLowerCase(), token],
);
- const named = pick(rows.filter(row => isFactEntityPage(row.slug, row.type) && sameEntityName(trimmed, row.title, row.slug)), 'same_name');
+ const named = await pick(rows.filter(row => isFactEntityPage(row.slug, row.type) && sameEntityName(trimmed, row.title, row.slug)), 'same_name');
if (named) return named;
} catch (err) {
if (!isMissingTrigramError(err)) throw err;
diff --git a/src/core/mentions/siblings.ts b/src/core/mentions/siblings.ts
index 52cc39de82..4ec1a47492 100644
--- a/src/core/mentions/siblings.ts
+++ b/src/core/mentions/siblings.ts
@@ -90,3 +90,47 @@ export async function readIdentitySiblings(engine: BrainEngine, sourceId: string
return { pages: [], capped: false };
}
}
+
+/**
+ * The page facts about an identity-sibling group are attributed to: when
+ * `slugs` (two or three live pages one name resolved to) form one group, the
+ * lowest slug; otherwise null (a real ambiguity). Fact writers use it so a
+ * name both siblings claim ("Telostra Robotics" for its account sheet and
+ * CRM record) resolves instead of falling back to a slug no page has.
+ */
+export async function siblingCanonical(engine: BrainEngine, sourceId: string, slugs: string[], opts: { excludePrivate?: boolean } = {}): Promise<string | null> {
+ const unique = [...new Set(slugs)].sort();
+ if (unique.length < 2 || unique.length > SIBLING_GROUP_CAP) return null;
+ try {
+ const policy = await readMentionPolicy(engine);
+ if (!policy.siblingMerge) return null;
+ const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const rows = await engine.executeRaw<{ slug: string; title: string | null; type: string | null; identity: unknown }>(
+ `SELECT slug, title, type, frontmatter->>'identity' AS identity FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])${opts.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : ''}`,
+ [sourceId, unique]);
+ if (rows.length !== unique.length) return null;
+ const pack = await loadSourcePack(engine, sourceId);
+ const types = new Set(linkableTypesFor(pack, policy));
+ if (!rows.every(r => r.type != null && types.has(r.type))) return null;
+ return siblingVerdict(rows, pack, policy) === 'group' ? unique[0]! : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every `entity_slug` facts about this page may be stored under: the page,
+ * its identity siblings and the slug of its title subject (what a fact saved
+ * by name got before its siblings resolved). The entity card and recall read
+ * all of them, so a saved fact shows up whichever sibling a reader asks for.
+ */
+export async function factEntitySlugs(engine: BrainEngine, sourceId: string, slug: string, opts: { excludePrivate?: boolean } = {}): Promise<string[]> {
+ const [page] = await engine.executeRaw<{ title: string | null }>(
+ 'SELECT title FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]).catch(() => []);
+ if (!page) return [slug];
+ const siblings = await readIdentitySiblings(engine, sourceId, { slug, title: page.title }, { excludePrivate: opts.excludePrivate ?? true });
+ const { slugify } = await import('../entities/resolve.ts');
+ const subject = slugify(titleName(page.title ?? ''));
+ return [...new Set([slug, ...siblings.pages.map(p => p.slug), ...(subject && subject !== slug ? [subject] : [])])];
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 8c85954a65..8418a6684b 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -353,21 +353,23 @@ const recall: Operation = {
// in this session) since T" is a question about when the underlying
// events occurred, not about when a batch extraction wrote the rows.
const { resolveEntitySlug } = await import('../entities/resolve.ts');
- const lists = await Promise.all(factSources.map(async (src) => {
- const entitySlug = entityParam
- ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam)
- : undefined;
- return ctx.engine.listFactsSince(src, since, { ...listOpts, eventTime: true, entitySlug, sessionId: sessionParam ?? undefined });
+ const resolvedLists = await Promise.all(factSources.map(async (src) => {
+ const entitySlug = entityParam ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam) : undefined;
+ const rows = await readEntityFacts(ctx, src, entitySlug, limit,
+ s => ctx.engine.listFactsSince(src, since, { ...listOpts, eventTime: true, entitySlug: s, sessionId: sessionParam ?? undefined }));
+ return { slug: entitySlug, rows };
}));
- ambiguousEntity = entityParam ? await unlinkedNamesakes(ctx.engine, lists) : null;
+ const lists = resolvedLists.map(l => l.rows);
+ ambiguousEntity = entityParam ? await unlinkedNamesakes(ctx.engine, resolvedLists.map(l => l.rows.map(r => ({ ...r, entity_slug: l.slug ?? r.entity_slug })))) : null;
rows = ambiguousEntity ? [] : mergeNewest(lists, byEventTime);
} else if (entityParam) {
const { resolveEntitySlug } = await import('../entities/resolve.ts');
- const lists = await Promise.all(factSources.map(async (src) => {
+ const resolvedLists = await Promise.all(factSources.map(async (src) => {
const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;
- return ctx.engine.listFactsByEntity(src, slug, listOpts);
+ return { slug, rows: await readEntityFacts(ctx, src, slug, limit, s => ctx.engine.listFactsByEntity(src, s!, listOpts)) };
}));
- ambiguousEntity = await unlinkedNamesakes(ctx.engine, lists);
+ const lists = resolvedLists.map(l => l.rows);
+ ambiguousEntity = await unlinkedNamesakes(ctx.engine, resolvedLists.map(l => l.rows.map(r => ({ ...r, entity_slug: l.slug }))));
rows = ambiguousEntity ? [] : mergeNewest(lists, (rec) => rec.valid_from ?? rec.created_at);
} else if (sessionParam) {
rows = mergeNewest(
@@ -577,6 +579,19 @@ const recall: Operation = {
},
};
+/**
+ * One source's facts about an entity, read under every slug they may be saved
+ * under (the page, its identity siblings and its bare subject slug,
+ * mentions/siblings.ts), newest event first, cut at `limit`.
+ */
+async function readEntityFacts<R extends { valid_from?: Date | string | null; created_at?: Date | string | null }>(ctx: OperationContext, src: string,
+ slug: string | undefined, limit: number, read: (slug: string | undefined) => Promise<R[]>): Promise<R[]> {
+ const { factEntitySlugs } = await import('../mentions/siblings.ts');
+ const slugs = slug ? await factEntitySlugs(ctx.engine, src, slug, { excludePrivate: ctx.remote !== false }).catch(() => [slug]) : [undefined];
+ const time = (r: R) => { const v = r.valid_from ?? r.created_at; return (v instanceof Date ? v.getTime() : v ? Date.parse(String(v)) : 0) || 0; };
+ return (await Promise.all(slugs.map(read))).flat().sort((a, b) => time(b) - time(a)).slice(0, limit);
+}
+
type EntityCandidate = { source_id: string; entity_slug: string };
const AMBIGUOUS_ENTITY_SUGGESTION = 'These are different entities in different sources. Pass source_id to read one, or link them with entity_identity_link if they are the same.';
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 6e011d896e..3aecdf03e8 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -41,7 +41,8 @@ import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts'
import { pageReadFilter } from '../search/read-policy-sql.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';
import { declaredNames, titleName } from '../mentions/aliases.ts';
-import { withAliasFanOut, type FanoutMeta } from '../search/alias-fanout.ts';
+import { withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';
+import { entitySavedFacts } from '../search/entity-facts.ts';
import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';
import { keepEnumeratedRows, keywordCountMeta, parseSearchPaging, readKeywordPage, startKeywordCount, withCountMeta } from '../search/keyword-paging.ts';
import { searchLimitCap } from '../search/eval-pool-depth.ts';
@@ -418,7 +419,7 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search' } = {},
+ opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search'; entity?: ResolvedEntity } = {},
): Promise<Record<string, unknown>> {
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
@@ -436,7 +437,9 @@ async function buildRetrievalResponseMeta(
excludeSlugPrefixes,
});
const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);
- const savedFacts = await matchingSavedFacts(ctx, scope, queryText, aliases);
+ // Facts saved about the entity the query names come first (newest first, one hop through entities they name).
+ const entityFacts = opts.entity && ctx.emitResponseMeta ? await entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : [];
+ const savedFacts = [...entityFacts, ...(await matchingSavedFacts(ctx, scope, queryText, aliases)).filter(m => !entityFacts.some(e => e.id === m.id))];
const heldFiles = await stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []);
const heldNotice = heldFilesNotice(heldFiles, ctx.remote !== false);
if (heldNotice) ctx.emitNotice?.(heldNotice);
@@ -749,7 +752,7 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
keywordCountMeta(await keywordCount, offset + limit)));
},
scope: 'read', mutating: false,
@@ -1149,7 +1152,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.ts
index 405e1d1528..2f40907e0a 100644
--- a/src/core/search/alias-fanout.ts
+++ b/src/core/search/alias-fanout.ts
@@ -78,11 +78,18 @@ export async function searchAliasRequired(engine: BrainEngine, alias: string, te
interface Scope { sourceId?: string; sourceIds?: string[]; excludePrivate: boolean }
+export interface ResolvedEntity { pages: Array<{ slug: string; source_id: string }>; tokens: [number, number] }
+
/** The entity the query names: its pages (one, or an identity-sibling group) and the n-gram that named it. */
-export async function resolveQueryEntity(engine: BrainEngine, query: string, scope: Scope):
- Promise<{ pages: Array<{ slug: string; source_id: string }>; tokens: [number, number] } | null> {
+export async function resolveQueryEntity(engine: BrainEngine, query: string, scope: Scope): Promise<ResolvedEntity | null> {
+ return (await resolveQueryEntities(engine, query, scope, 1))[0] ?? null;
+}
+
+/** Every entity `text` names, longest n-gram first, at most `max`. */
+export async function resolveQueryEntities(engine: BrainEngine, query: string, scope: Scope, max = 4): Promise<ResolvedEntity[]> {
+ const found: ResolvedEntity[] = [];
const tokens = queryTokens(query);
- if (!tokens.length) return null;
+ if (!tokens.length) return found;
const grams: Array<{ text: string; norm: string; from: number; to: number }> = [];
for (let n = Math.min(MAX_NGRAM, tokens.length); n >= 1; n--) {
for (let i = 0; i + n <= tokens.length; i++) {
@@ -112,15 +119,19 @@ export async function resolveQueryEntity(engine: BrainEngine, query: string, sco
if (!hits.length) continue;
const gramTokens = tokens.slice(g.from, g.to + 1).map(t => t.text);
if (!(shaped(gramTokens[0]!) && shaped(gramTokens[gramTokens.length - 1]!)) && !(gramTokens.length > 1 && hits.length === 1)) continue;
- covered.add(g.from);
for (let k = g.from; k <= g.to; k++) covered.add(k);
- if (hits.length === 1) return { pages: hits, tokens: [g.from, g.to] };
const [first] = hits;
- const sib = await readIdentitySiblings(engine, first!.source_id, { slug: first!.slug, title: await titleOf(engine, first!) }, { excludePrivate: scope.excludePrivate });
- const group = new Set([first!.slug, ...sib.pages.map(p => p.slug)]);
- if (hits.every(h => h.source_id === first!.source_id && group.has(h.slug))) return { pages: hits, tokens: [g.from, g.to] };
+ let pages: ResolvedEntity['pages'] | null = hits.length === 1 ? hits : null;
+ if (!pages) {
+ const sib = await readIdentitySiblings(engine, first!.source_id, { slug: first!.slug, title: await titleOf(engine, first!) }, { excludePrivate: scope.excludePrivate });
+ const group = new Set([first!.slug, ...sib.pages.map(p => p.slug)]);
+ if (hits.every(h => h.source_id === first!.source_id && group.has(h.slug))) pages = hits;
+ }
+ if (!pages) continue;
+ if (!found.some(f => f.pages.some(p => pages!.some(q => q.slug === p.slug && q.source_id === p.source_id)))) found.push({ pages, tokens: [g.from, g.to] });
+ if (found.length >= max) break;
}
- return null;
+ return found;
}
async function titleOf(engine: BrainEngine, ref: { slug: string; source_id: string }): Promise<string | null> {
@@ -165,10 +176,10 @@ export async function aliasFanoutMax(engine: BrainEngine): Promise<number> {
* resolves. Fail-soft: any error returns `results` unchanged.
*/
export async function withAliasFanOut(engine: BrainEngine, results: SearchResult[], queryText: string, scope: Scope, searchOpts: SearchOpts,
- fallback: () => Array<{ name: string; alias: string; slug: string }>): Promise<{ results: SearchResult[]; fanout?: FanoutMeta }> {
+ fallback: () => Array<{ name: string; alias: string; slug: string }>): Promise<{ results: SearchResult[]; fanout?: FanoutMeta; entity?: ResolvedEntity }> {
try {
const max = await aliasFanoutMax(engine);
- if (max === 0) return { results };
+ if (max === 0) return { results, ...(await resolveEntityQuiet(engine, queryText, scope)) };
const words = (text: string) => normalizeAlias(text).split(/[^\p{L}\p{N}]+/u).filter(Boolean);
const queryWords = words(queryText);
const inQuery = (name: string) => {
@@ -186,7 +197,8 @@ export async function withAliasFanOut(engine: BrainEngine, results: SearchResult
}
const seenNames = new Set<string>();
names = names.filter(n => { const k = normalizeAlias(n.alias); if (seenNames.has(k)) return false; seenNames.add(k); return true; });
- if (!names.length) return { results };
+ const entity = resolved ?? undefined;
+ if (!names.length) return { results, ...(entity ? { entity } : {}) };
const tokens = queryTokens(queryText);
const terms = tokens.filter((_, i) => !usedTokens || i < usedTokens[0] || i > usedTokens[1]).map(t => t.text)
.filter(t => !STOPWORDS.has(t.toLowerCase()) && t.length >= 2 && !names.some(n => normalizeAlias(n.alias).split(' ').includes(t.toLowerCase())));
@@ -210,9 +222,14 @@ export async function withAliasFanOut(engine: BrainEngine, results: SearchResult
aliases_skipped: skipped,
truncated: skipped.length > 0,
};
- if (!fresh.length) return { results, fanout };
- return { results: [...results.slice(0, 2), ...fresh, ...results.slice(2)], fanout };
+ if (!fresh.length) return { results, fanout, ...(entity ? { entity } : {}) };
+ return { results: [...results.slice(0, 2), ...fresh, ...results.slice(2)], fanout, ...(entity ? { entity } : {}) };
} catch {
return { results };
}
}
+
+async function resolveEntityQuiet(engine: BrainEngine, query: string, scope: Scope): Promise<{ entity?: ResolvedEntity }> {
+ const entity = await resolveQueryEntity(engine, query, scope).catch(() => null);
+ return entity ? { entity } : {};
+}
diff --git a/src/core/search/entity-facts.ts b/src/core/search/entity-facts.ts
new file mode 100644
index 0000000000..3f5f76104d
--- /dev/null
+++ b/src/core/search/entity-facts.ts
@@ -0,0 +1,71 @@
+/**
+ * Saved facts about the entity a search names. Facts saved with `remember`
+ * live in the facts table, not in page chunks, so a search whose words differ
+ * from the fact's ("discount code for ONSO" against "Ondresso Systems is being
+ * folded into Dovalto Energy") never found them by word overlap, and agents
+ * answered from older documents instead of the newer saved correction.
+ *
+ * When the query names an entity (search/alias-fanout.ts), its newest active
+ * facts (also those saved under an identity sibling or its bare name) are
+ * returned first. One hop: an entity a returned fact names ("folded into
+ * Dovalto Energy", "uses Dovalto Energy's discount code") contributes its own
+ * newest facts, tagged `linked_from`, so a redirection reaches the value it
+ * points to. Same source scope, active-fact and visibility rules as recall.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
+import { privateProvenanceFilterFragment } from './private-visibility.ts';
+import { factEntitySlugs } from '../mentions/siblings.ts';
+import { resolveQueryEntities, type ResolvedEntity } from './alias-fanout.ts';
+
+export const ENTITY_FACTS_CAP = 5;
+export const LINKED_FACTS_CAP = 3;
+const LINKED_ENTITIES_CAP = 2;
+
+export interface EntityFact { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string; linked_from?: string }
+
+async function newestFacts(engine: BrainEngine, sourceId: string, slugs: string[], remote: boolean, limit: number): Promise<EntityFact[]> {
+ const visibility = remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : '';
+ const rows = await engine.executeRaw<EntityFact>(
+ `SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source
+ FROM facts f
+ WHERE f.source_id = $1 AND f.entity_slug = ANY($2::text[])
+ AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
+ AND f.source != ALL($3::text[])
+ ${visibility}
+ ORDER BY f.valid_from DESC, f.id DESC
+ LIMIT ${limit}`,
+ [sourceId, slugs, [...AUDIT_ROW_SOURCES]]);
+ return rows.map(r => ({ ...r, id: Number(r.id) }));
+}
+
+/** The named entity's newest facts, then those of entities its facts name. Fail-soft: errors return []. */
+export async function entitySavedFacts(engine: BrainEngine, entity: ResolvedEntity, opts: { remote: boolean; excludePrivate: boolean }): Promise<EntityFact[]> {
+ try {
+ const sourceId = entity.pages[0]!.source_id;
+ const own = new Set<string>();
+ for (const p of entity.pages) for (const s of await factEntitySlugs(engine, sourceId, p.slug, { excludePrivate: opts.excludePrivate })) own.add(s);
+ const facts = await newestFacts(engine, sourceId, [...own], opts.remote, ENTITY_FACTS_CAP);
+ const out: EntityFact[] = [...facts];
+ const seenEntities = new Set(own);
+ let linked = 0;
+ for (const f of facts) {
+ if (linked >= LINKED_ENTITIES_CAP) break;
+ for (const other of await resolveQueryEntities(engine, f.fact, { sourceId, excludePrivate: opts.excludePrivate })) {
+ if (linked >= LINKED_ENTITIES_CAP || other.pages.some(p => seenEntities.has(p.slug))) continue;
+ const slugs = new Set<string>();
+ for (const p of other.pages) for (const s of await factEntitySlugs(engine, sourceId, p.slug, { excludePrivate: opts.excludePrivate })) slugs.add(s);
+ if ([...slugs].some(s => seenEntities.has(s))) continue;
+ for (const s of slugs) seenEntities.add(s);
+ linked++;
+ for (const g of await newestFacts(engine, sourceId, [...slugs], opts.remote, LINKED_FACTS_CAP)) {
+ if (!out.some(x => x.id === g.id)) out.push({ ...g, linked_from: f.entity_slug ?? entity.pages[0]!.slug });
+ }
+ }
+ }
+ return out;
+ } catch {
+ return [];
+ }
+}
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 6dfa87c169..24ca50eccc 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -32,12 +32,14 @@ import { loadLinkableTypes } from '../mentions/policy.ts';
import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';
import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';
import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';
+import { factEntitySlugs } from '../mentions/siblings.ts';
const EDGE_CAP = 10;
const OPEN_THREADS_CAP = 3;
const OPEN_THREAD_TIMELINE_WINDOW_DAYS = 90;
const SUGGESTION_CAP = 3;
const FACT_FETCH_CAP = 100;
+const RECENT_FACTS_CAP = 5;
export interface EntityCardEdge {
type: string;
@@ -85,6 +87,8 @@ export interface EntityCard {
backlink_count: number;
/** Exact active-fact count (indexed COUNT, not payload length); visibility-filtered for remote. */
active_fact_count: number;
+ /** The newest active saved facts about this entity (also those saved under an identity sibling or its bare name, with that `entity_slug`). */
+ recent_facts?: Array<{ id: string; fact: string; kind: string; valid_from: string | null; entity_slug?: string }>;
/**
* Current and ended state relationships of this entity, rendered for agents
* ("now: works_at widget-co (since 2025-03-01); ended: works_at acme-example
@@ -333,6 +337,8 @@ async function assembleCard(
): Promise<EntityCard> {
const pageSlug = row.slug;
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
+ // Facts saved about this entity may sit under a sibling page or the bare subject slug (siblings.ts).
+ const factSlugs = await factEntitySlugs(engine, sourceId, pageSlug, { excludePrivate }).catch(() => [pageSlug]);
const { privatePagesFilterFragment, privateLinkOriginFilterFragment } = await import('../search/private-visibility.ts');
const inboundPrivacy = excludePrivate
? ` AND ${privatePagesFilterFragment('f')} AND ${privateLinkOriginFilterFragment('l')}`
@@ -387,12 +393,12 @@ async function assembleCard(
.then(rs => Number(rs[0]?.n ?? 0))
.catch(() => 0),
engine.getTimeline(pageSlug, { limit: 5, sourceId, excludePrivate }).catch(() => []),
- engine
- .listFactsByEntity(sourceId, pageSlug, {
- activeOnly: true,
- limit: FACT_FETCH_CAP,
- ...(visibility ? { visibility } : {}),
- })
+ Promise.all(factSlugs.map(slug => engine.listFactsByEntity(sourceId, slug, {
+ activeOnly: true,
+ limit: FACT_FETCH_CAP,
+ ...(visibility ? { visibility } : {}),
+ })))
+ .then(lists => lists.flat().sort((a, b) => factTime(b) - factTime(a)).slice(0, FACT_FETCH_CAP))
.catch(() => [] as FactRow[]),
// Exact active-fact count: the payload fetch above is capped at
// FACT_FETCH_CAP, so facts.length silently reports the cap for bigger
@@ -403,9 +409,9 @@ async function assembleCard(
.executeRaw<{ n: string | number }>(
`SELECT COUNT(*) AS n
FROM facts
- WHERE source_id = $1 AND entity_slug = $2
+ WHERE source_id = $1 AND entity_slug = ANY($2::text[])
AND expired_at IS NULL${remote ? ` AND visibility = 'world'` : ''}`,
- [sourceId, pageSlug],
+ [sourceId, factSlugs],
)
.then(rs => Number(rs[0]?.n ?? 0))
.catch(() => null),
@@ -516,9 +522,17 @@ async function assembleCard(
backlink_count: backlinkCount,
active_fact_count: activeFactCount ?? facts.length,
...(relationshipNote ? { relationship_note: relationshipNote } : {}),
+ ...(facts.length ? { recent_facts: facts.slice(0, RECENT_FACTS_CAP).map(f => ({
+ id: String(f.id), fact: f.fact, kind: f.kind, valid_from: f.valid_from ? toIso(f.valid_from as Date | string) : null,
+ ...(f.entity_slug && f.entity_slug !== pageSlug ? { entity_slug: f.entity_slug } : {}),
+ })) } : {}),
};
}
+function factTime(f: FactRow): number {
+ return toMs((f.valid_from ?? f.created_at ?? null) as Date | string | null);
+}
+
/**
* Near-miss suggestions on a total miss (E5 delight): keyword search top-N
* with evidence-derived create_safety so a typo'd name becomes a next move
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 6b57bdfc27..2da3b3901c 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -381,7 +381,7 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri
const r = retrieval as {
type_filter_notice?: unknown;
other_names?: Array<{ name: string; alias: string; slug: string }>;
- saved_facts?: Array<{ fact: string; entity_slug: string | null; valid_from: string; source: string }>;
+ saved_facts?: Array<{ fact: string; entity_slug: string | null; valid_from: string; source: string; linked_from?: string }>;
answer_id?: unknown;
feedback?: { rateable?: boolean; how_to_rate?: string };
};
@@ -393,8 +393,8 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri
blocks.push(`${text}${more ? ` (+${more} more)` : ''}.`);
}
if (r.saved_facts?.length) {
- const { text, more } = wholeItemsWithin('Saved facts (remember) matching this query, newest first; recall returns more:\n',
- r.saved_facts.map(f => `- ${f.fact} [entity: ${f.entity_slug ?? 'none'}; saved ${String(f.valid_from).slice(0, 10)}; provenance: ${f.source}]`),
+ const { text, more } = wholeItemsWithin('Saved facts (remember): about the entity this query names (newest first), then facts those point to, then matches for its words; recall returns more:\n',
+ r.saved_facts.map(f => `- ${f.fact} [entity: ${f.entity_slug ?? 'none'}; saved ${String(f.valid_from).slice(0, 10)}; provenance: ${f.source}${f.linked_from ? `; named in a saved fact about ${f.linked_from}` : ''}]`),
'\n', SAVED_FACTS_NOTICE_MAX_CHARS);
blocks.push(more ? `${text}\n(+${more} more; recall returns them)` : text);
}
diff --git a/test/fixtures/goldens/search-c5/notices.json b/test/fixtures/goldens/search-c5/notices.json
index db372b73e5..f560a87689 100644
--- a/test/fixtures/goldens/search-c5/notices.json
+++ b/test/fixtures/goldens/search-c5/notices.json
@@ -4,7 +4,7 @@
"content": [
"[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"effective_date_source\":\"fallback\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"effective_date_source\":\"fallback\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"effective_date_source\":\"fallback\",\"matched_alias\":\"Numbat Labs\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"}]",
"Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in contracts/numbat-labs-msa).",
- "Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]",
+ "Saved facts (remember): about the entity this query names (newest first), then facts those point to, then matches for its words; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]",
"[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".",
"[gbrain dates] effective_date by effective_date_source: fallback = fallback (page created/imported, not from its text). Never a contract's effective or validity date (read the text).",
"[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
@@ -125,7 +125,7 @@
"content": [
"[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"effective_date_source\":\"fallback\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"effective_date_source\":\"fallback\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
"Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight).",
- "Saved facts (remember) matching this query, newest first; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]",
+ "Saved facts (remember): about the entity this query names (newest first), then facts those point to, then matches for its words; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]",
"[gbrain search] Rows are a ranked top-K, not proof of coverage. Keyword matches: 1 page (pages matching the query's keywords, not a count of these rows). List every keyword match with match: \"keyword\".",
"[gbrain dates] effective_date by effective_date_source: fallback = fallback (page created/imported, not from its text). Never a contract's effective or validity date (read the text).",
"[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
diff --git a/test/memory-sibling-facts.test.ts b/test/memory-sibling-facts.test.ts
new file mode 100644
index 0000000000..97a3c7f7fb
--- /dev/null
+++ b/test/memory-sibling-facts.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Saved facts about an entity that has identity siblings (Cat 40 Hard
+ * development round 1): a name both siblings claim resolves for `remember`,
+ * and the entity card, recall and search read facts saved under any sibling
+ * or the bare subject slug.
+ *
+ * Protects: `remember` with entity "Widget Co" fell back to a slug no page
+ * has (the account sheet and the CRM record both claim the name), so the card
+ * showed 0 facts and recall by the CRM slug missed them; agents re-saved and
+ * forgot facts, then answered from older documents. Search now puts the named
+ * entity's newest saved facts first and follows one redirection ("folded into
+ * Kite Co" then Kite Co's corrected code).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { resolveEntitySlugWithSource, resolveStrictEntityReference } from '../src/core/entities/resolve.ts';
+import { mentionBrain, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+const local = { remote: false, sourceId: 'default', config: { engine: 'pglite' } };
+
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); await engine.executeRaw('DELETE FROM facts'); });
+
+async function put(slug: string, type: string, title: string, body: string) {
+ await importFromContent(engine, slug, serializeMarkdown({}, body, '', { type, title, tags: [] }), { noEmbed: true, forceRechunk: true });
+}
+async function call(op: string, args: Record<string, unknown>) {
+ const r = await dispatchToolCall(engine, op, args, local as never);
+ if (r.isError) throw new Error(r.content[0].text);
+ return { json: JSON.parse(r.content[0].text!), text: r.content.map(c => c.text ?? '').join('\n') };
+}
+const siblings = async () => {
+ await put('accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Account: Widget Co. Nickname used by the team: Copper Fox.');
+ await put('crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO. Billing contact: Dana Example.');
+ await sweep(engine);
+};
+
+describe('facts about an entity with identity siblings', () => {
+ test('a name both siblings claim resolves to the group (lowest slug), not a slug no page has', async () => {
+ await siblings();
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Widget Co')).toMatchObject({ slug: 'accounts/widget-co' });
+ expect(await resolveStrictEntityReference(engine, 'default', 'Widget Co')).toMatchObject({ slug: 'accounts/widget-co' });
+ await put('companies/other-example', 'company', 'Other Example', 'x');
+ await put('people/other-example', 'person', 'Other Example', 'y');
+ expect(await resolveStrictEntityReference(engine, 'default', 'Other Example')).toMatchObject({ slug: null, miss: 'ambiguous' });
+ });
+
+ test('remember by name links the fact; the card of either sibling and recall by either slug show it, newest first', async () => {
+ await siblings();
+ const first = await call('remember', { fact: 'Lior Example is the procurement lead at Widget Co.', entity: 'Widget Co', provenance: 'team update' });
+ expect(first.json.entity_slug).toBe('accounts/widget-co');
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from) VALUES
+ ('default', 'widget-co', 'Older: the Widget Co discount code is DISC-OLD1.', 'fact', 'world', 'team update', now() - interval '2 days')`);
+ await call('remember', { fact: 'Correction: Lena Example is now the procurement lead at Widget Co.', entity: 'crm/widget-co', provenance: 'team correction' });
+ const card = (await call('entity', { name: 'WGCO' })).json.card;
+ expect(card.entity.slug).toBe('crm/widget-co');
+ expect(card.active_fact_count).toBe(3);
+ expect(card.recent_facts.map((f: { fact: string }) => f.fact)[0]).toContain('Lena Example');
+ expect(card.recent_facts.some((f: { entity_slug?: string }) => f.entity_slug === 'widget-co')).toBe(true);
+ for (const entity of ['crm/widget-co', 'accounts/widget-co', 'Widget Co']) {
+ const facts = (await call('recall', { entity })).json.facts.map((f: { fact: string }) => f.fact);
+ expect(facts).toHaveLength(3);
+ expect(facts[0]).toContain('Lena Example');
+ }
+ });
+
+ test('remember without an entity infers the sibling group the text names (no NO_ENTITY, nothing to re-save)', async () => {
+ await siblings();
+ const r = await call('remember', { fact: 'Widget Co renewal invoices go to the procurement lead from now on.', provenance: 'team decision' });
+ expect(r.json.entity_slug).toBe('accounts/widget-co');
+ expect(r.json.warnings).toBeUndefined();
+ });
+
+ test('search names the entity: its saved facts come first, then the facts of an entity they point to', async () => {
+ await siblings();
+ await put('crm/kite-co', 'crm', 'CRM record: Kite Co', 'Account code: KTCO.');
+ await put('mail/old-code', 'email', 'Discount code: Widget Co', 'The discount code on file for Widget Co orders is DISC-OLD9.');
+ await sweep(engine);
+ await call('remember', { fact: 'Widget Co is being folded into Kite Co; its orders use Kite Co\'s discount code.', entity: 'Widget Co', provenance: 'team update' });
+ await call('remember', { fact: 'Correction: the discount code for Kite Co is DISC-NEW2.', entity: 'Kite Co', provenance: 'team correction' });
+ const { text } = await call('search', { query: 'Widget Co discount code' });
+ const block = text.slice(text.indexOf('Saved facts (remember)'));
+ expect(block).toContain('folded into Kite Co');
+ expect(block).toContain('DISC-NEW2');
+ expect(block).toContain('named in a saved fact about accounts/widget-co');
+ expect(block.indexOf('folded into Kite Co')).toBeLessThan(block.indexOf('DISC-NEW2'));
+ });
+});