Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mentions): mentions.exclude_slugs keeps a page out of the gazetteer; drop dead extraIgnore (#5829, E-N5)
time-attack43deacd710f7
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.mdindex fdfd207d9e..5878528841 100644--- a/docs/architecture/key-files/entity-recall.md+++ b/docs/architecture/key-files/entity-recall.md@@ -5,7 +5,7 @@ subject, frontmatter alias or declared code) to that entity page, keeps thelinks current from `gbrain extract --stale`, and serves them on the `entity`card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).-- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` (JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.+- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` and `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.- `src/core/mentions/aliases.ts` — derived names of an entity page. `titleSubject` (text after the last `: `), `declaredNames` (the `account code` / `also known as` / `a.k.a.` / `aka` / `short name` / `ticker` / `code name` parser shared with search's `aliasDeclarations`), `deriveEntityAliases` (subject `origin='subject'`, declarations `origin='declared'`, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`). `aliasRejection`: under 4 characters, a generic word, or the first word of the page's own multi-word name. Rejections are returned for explain. Tests: `test/mentions-policy-aliases.test.ts`.- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list) marks every page due; `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, pending count and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (due pages and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.mdindex b35f843ceb..531edab34e 100644--- a/docs/guides/entity-recall.md+++ b/docs/guides/entity-recall.md@@ -160,6 +160,7 @@ The reason codes are `ambiguous_first_word`, `below_min_length`,| `mentions.auto_link` | `true` | `false` removes mention links and derived names on the next sweep; `true` relinks everything on the next sweep. `auto_link=false` also turns it off. || `mentions.entity_types` | none | `+type` adds a linkable type, `-type` removes one (person, company, organization and entity always stay). || `mentions.ignore` | none | Names never linked, comma-separated or a JSON array. |+| `mentions.exclude_slugs` | none | Pages never linked by any of their names (title or alias), comma-separated or a JSON array of slugs. Use it for an entity whose name is also a common word, such as a person titled 인하 against "로 인하여" ("due to"). The next sweep removes mention links already written to the page. || frontmatter `mention_ignore: [names]` | none | Names not linked from that one page. |## How it stays currentdiff --git a/src/commands/extract-mentions-explain.ts b/src/commands/extract-mentions-explain.tsindex cfa6b77126..e8569d0e3b 100644--- a/src/commands/extract-mentions-explain.ts+++ b/src/commands/extract-mentions-explain.ts@@ -7,7 +7,7 @@* `ambiguous_first_word`, `below_min_length`, `generic_token`,* `alias_collision`, `case_mismatch`, `type_not_linkable`,* `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`,- * `not_a_known_name`. Only `pending` suggests a sweep; a policy rejection+ * `excluded_by_config`, `not_a_known_name`. Only `pending` suggests a sweep; a policy rejection* names the setting or the page text that would change it.*/@@ -19,7 +19,7 @@ import { deriveEntityAliases } from '../core/mentions/aliases.ts';import { MENTION_EXTRACTOR_VERSION } from '../core/mentions/pass.ts';export type ExplainReason = 'ambiguous_first_word' | 'below_min_length' | 'generic_token' | 'alias_collision' | 'case_mismatch'- | 'type_not_linkable' | 'linking_disabled' | 'pending' | 'ignored_by_page' | 'ignored_by_config' | 'not_a_known_name';+ | 'type_not_linkable' | 'linking_disabled' | 'pending' | 'ignored_by_page' | 'ignored_by_config' | 'excluded_by_config' | 'not_a_known_name';export interface MentionExplanation {query: string;@@ -35,7 +35,7 @@ export interface MentionExplanation {const DROP_REASON: Record<DroppedName['reason'], ExplainReason> = {below_min_length: 'below_min_length', generic_token: 'generic_token', alias_collision: 'alias_collision',- ambiguous_first_word: 'ambiguous_first_word', ignored: 'ignored_by_config', title_wins: 'alias_collision',+ ambiguous_first_word: 'ambiguous_first_word', ignored: 'ignored_by_config', excluded_slug: 'excluded_by_config', title_wins: 'alias_collision',};const MESSAGES: Record<ExplainReason, string> = {@@ -49,6 +49,7 @@ const MESSAGES: Record<ExplainReason, string> = {pending: 'The page changed or was never scanned since the last mention pass.',ignored_by_page: 'The page lists this name in its frontmatter `mention_ignore`.',ignored_by_config: 'The name is on an ignore list (`mentions.ignore` or the built-in ambiguous-brand list).',+ excluded_by_config: 'The page is listed in `mentions.exclude_slugs`, so none of its names link.',not_a_known_name: 'No linkable entity page has this title, title subject or alias in this source.',};diff --git a/src/core/by-mention.ts b/src/core/by-mention.tsindex 36d04a6357..4eeada96cd 100644--- a/src/core/by-mention.ts+++ b/src/core/by-mention.ts@@ -26,7 +26,8 @@* - Ignore-list applied at gazetteer-build time, not match time. Built-in* ambiguous tokens (Apple, Amazon, Square, Stripe, Box) are dropped from* the gazetteer only when no corresponding entity page exists: a page the- * user created is trusted. `mentions.ignore` names are dropped always.+ * user created is trusted. `mentions.ignore` names are dropped always;+ * pages listed in `mentions.exclude_slugs` get no entry at all (#5829).*/import { createHash } from 'crypto';@@ -152,16 +153,11 @@ export interface DroppedName {slug: string;name: string;origin: GazetteerOrigin;- reason: 'below_min_length' | 'generic_token' | 'alias_collision' | 'ambiguous_first_word' | 'ignored' | 'title_wins';+ reason: 'below_min_length' | 'generic_token' | 'alias_collision' | 'ambiguous_first_word' | 'ignored' | 'excluded_slug' | 'title_wins';}export interface BuildGazetteerOpts {- /**- * Optional user-supplied additional ignore-list entries (case-sensitive- * raw title match). Merged with DEFAULT_IGNORE_LIST.- */- extraIgnore?: string[];- /** Mention policy (types, `mentions.ignore`); read from config when absent. */+ /** Mention policy (types, `mentions.ignore`, `mentions.exclude_slugs`); read from config when absent. */policy?: MentionPolicy;/*** Authoritative build for the mention pass: a pack that fails to resolve or@@ -462,7 +458,8 @@ export function tokenizeTitle(title: string): string[] {* name in the source is dropped (an ambiguous first word never links alone).* Ignore-list applied per CK12: built-in ambiguous tokens dropped unless* the user has explicitly created the corresponding page; `mentions.ignore`- * names always drop.+ * names always drop; a page in `mentions.exclude_slugs` contributes neither+ * its title nor its aliases.** Returned gazetteer is keyed by lowercase first token; entries with the* same first token co-exist in the same bucket (e.g. "Acme" + "Acme Corp").@@ -490,14 +487,9 @@ export async function buildGazetteer([allTypes],)).filter(r => linkable(r.source_id, r.type));- // Pre-build the existing-title Set so the ignore-list rule can check- // "does this name already correspond to a real page?" in O(1).- const existingTitles = new Set<string>();- for (const r of rows) {- if (r.title) existingTitles.add(r.title);- }- const ignoreSet = new Set<string>([...DEFAULT_IGNORE_LIST, ...(opts.extraIgnore ?? [])]);+ const ignoreSet = new Set<string>(DEFAULT_IGNORE_LIST);const userIgnore = new Set(policy.ignore.map(n => tokenizeTitle(n).join(' ')).filter(Boolean));+ const excludedSlugs = new Set(policy.excludeSlugs);const gazetteer: Gazetteer = new Map();const add = (entry: GazetteerEntry) => {@@ -519,15 +511,14 @@ export async function buildGazetteer(if (!row.title) continue;const src = row.source_id ?? 'default';const base = { source_id: src, slug: row.slug, name: row.title, origin: 'title' as const };+ if (excludedSlugs.has(row.slug)) { drop({ ...base, reason: 'excluded_slug' }); continue; }if (!hasCJK(row.title) && row.title.length < MIN_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }if (hasCJK(row.title) && cjkCharCount(row.title) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }- // NOTE (v0.46.15, deliberately preserved): for TITLES this condition is- // intentionally vacuous — every row here IS a real page, so an- // ignore-listed name the user explicitly created a page for is always- // allowed (documented CK12 policy). The ignore list bites only via- // opts.extraIgnore names that have no page, and — with real teeth — on- // the ALIAS entries below, which are not user-created pages.- if (ignoreSet.has(row.title) && !existingTitles.has(row.title)) { drop({ ...base, reason: 'ignored' }); continue; }+ // CK12 policy: an ignore-listed name the user explicitly created a page+ // for is always allowed, so DEFAULT_IGNORE_LIST never drops a TITLE+ // (every row here is a real page); it bites on the ALIAS entries below,+ // which are not user-created pages. `mentions.ignore` and+ // `mentions.exclude_slugs` are the operator's levers for titles.const tokens = tokenizeTitle(row.title);if (tokens.length === 0) continue;@@ -621,6 +612,7 @@ export async function buildGazetteer(const base = { source_id: src, slug: a.slug, name: written, origin };const claim = claims.get(`${src} ${alias}`)!;if (rank(a.origin) > claim.rank) continue;+ if (excludedSlugs.has(a.slug)) { drop({ ...base, reason: 'excluded_slug' }); continue; }if (claim.slugs.size > 1) { drop({ ...base, reason: 'alias_collision' }); continue; }if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) { drop({ ...base, reason: 'below_min_length' }); continue; }if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }diff --git a/src/core/config.ts b/src/core/config.tsindex 098aff1f81..7884148d2d 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1585,8 +1585,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// reconcile-links, and sweep. The documented off-switch is `gbrain config// set auto_link false` — same unregistered-key class as auto_chronicle.'auto_link',- // Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked.- 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore',+ // Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked, pages never linked (#5829).+ 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'mentions.exclude_slugs',// #4987: the write-path timeline extractor's off switch (read by// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`// works without --force, as the compiled-truth guide documents.diff --git a/src/core/mentions/policy.ts b/src/core/mentions/policy.tsindex 28934ef28d..a32355d3b6 100644--- a/src/core/mentions/policy.ts+++ b/src/core/mentions/policy.ts@@ -12,6 +12,8 @@* resolver. Type lists reach SQL bound as `text[]`, never interpolated.** Off switches: `auto_link=false` (global) or `mentions.auto_link=false`.+ * `mentions.exclude_slugs` keeps named pages out of the gazetteer entirely+ * (#5829: an entity whose name is also a common word).*/import type { BrainEngine } from '../engine.ts';@@ -32,6 +34,8 @@ export interface MentionPolicy {typeRemoves: string[];/** Names never linked (`mentions.ignore`), matched case-insensitively. */ignore: string[];+ /** Page slugs that get no gazetteer entry, by title or alias (`mentions.exclude_slugs`, #5829). */+ excludeSlugs: string[];}const FALSE_VALUES = new Set(['false', '0', 'no', 'off']);@@ -52,9 +56,10 @@ export function parseNameList(value: unknown): string[] {}export async function readMentionPolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<MentionPolicy> {- const [global, own, types, ignore] = await Promise.all([+ const [global, own, types, ignore, excludeSlugs] = await Promise.all([engine.getConfig('auto_link'), engine.getConfig('mentions.auto_link'),engine.getConfig('mentions.entity_types'), engine.getConfig('mentions.ignore'),+ engine.getConfig('mentions.exclude_slugs'),]);const typeAdds: string[] = [];const typeRemoves: string[] = [];@@ -63,7 +68,8 @@ export async function readMentionPolicy(engine: Pick<BrainEngine, 'getConfig'>):else typeAdds.push(entry.replace(/^\+/, '').trim());}const disabledBy = isOff(global) ? 'auto_link' : isOff(own) ? 'mentions.auto_link' : null;- return { enabled: disabledBy === null, disabledBy, typeAdds: typeAdds.filter(Boolean), typeRemoves: typeRemoves.filter(Boolean), ignore: parseNameList(ignore) };+ return { enabled: disabledBy === null, disabledBy, typeAdds: typeAdds.filter(Boolean), typeRemoves: typeRemoves.filter(Boolean), ignore: parseNameList(ignore),+ excludeSlugs: parseNameList(excludeSlugs) };}/** Linkable entity types for one pack (null = no pack resolved), sorted. */diff --git a/test/by-mention.test.ts b/test/by-mention.test.tsindex e893bea354..6170d0c86e 100644--- a/test/by-mention.test.ts+++ b/test/by-mention.test.ts@@ -816,17 +816,19 @@ describe('buildGazetteer — engine integration', () => {expect(g.has('box')).toBe(false);});- test('extraIgnore — user-supplied additional ignore tokens', async () => {+ test('operator levers for a title the CK12 rule keeps: mentions.exclude_slugs (the removed extraIgnore never applied to titles)', async () => {await engine.putPage('people/john', {type: 'person', title: 'John', compiled_truth: 'b', timeline: '', frontmatter: {},});- // No companies/john exists, so adding John to extraIgnore should suppress.const g1 = await buildGazetteer(engine);- expect(g1.has('john')).toBe(true); // baseline: in gazetteer- const g2 = await buildGazetteer(engine, { extraIgnore: ['John'] });- // But title "John" IS the entity title — existingTitles.has('John') is true.- // Per CK12 rule, gazetteer presence wins → John IS still in.- expect(g2.has('john')).toBe(true);+ expect(g1.has('john')).toBe(true); // baseline: a user-created page's title is in the gazetteer+ await engine.setConfig('mentions.exclude_slugs', 'people/john');+ try {+ const g2 = await buildGazetteer(engine);+ expect(g2.has('john')).toBe(false);+ } finally {+ await engine.unsetConfig('mentions.exclude_slugs');+ }});test('LINKABLE_ENTITY_TYPES exposes the hardcoded contract', () => {diff --git a/test/mentions-exclude-slugs.test.ts b/test/mentions-exclude-slugs.test.tsnew file mode 100644index 0000000000..b6eb0d5e67--- /dev/null+++ b/test/mentions-exclude-slugs.test.ts@@ -0,0 +1,62 @@+/**+ * #5829 remainder: `mentions.exclude_slugs` keeps a page out of the mention+ * gazetteer entirely, title and aliases. Hangul word boundaries landed in+ * #5960; what they cannot fix is a name that is also a common word, like the+ * person page titled 인하 against the connective "로 인하여" ("due to"). The+ * exclude list is the operator's escape hatch, and the mention pass removes+ * links already written to the excluded page.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { buildGazetteer, findMentionedEntities, type DroppedName } from '../src/core/by-mention.ts';+import { explainMention } from '../src/commands/extract-mentions-explain.ts';+import { mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetMentionBrain(engine);+ await engine.unsetConfig('mentions.exclude_slugs');+});++const opts = { fromSlug: 'notes/n1', fromSourceId: 'default' };++describe('mentions.exclude_slugs (#5829)', () => {+ test('an excluded page contributes neither its title nor its aliases; other pages still link', async () => {+ await page(engine, 'people/inha', 'person', '인하', 'A person.');+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');+ await engine.executeRaw("INSERT INTO page_aliases (source_id, slug, alias_norm) VALUES ('default', 'people/inha', '인하씨')");+ const body = '사정으로 인하여 취소되었습니다. 인하씨와 Acme Example.';++ const before = findMentionedEntities(body, await buildGazetteer(engine), opts).map(m => m.slug);+ expect(before).toContain('people/inha');++ await engine.setConfig('mentions.exclude_slugs', '["people/inha"]');+ const dropped: DroppedName[] = [];+ const after = findMentionedEntities(body, await buildGazetteer(engine, { dropped }), opts).map(m => m.slug);+ expect(after).toEqual(['companies/acme']);+ expect(dropped.filter(d => d.slug === 'people/inha').map(d => [d.origin, d.reason]).sort()).toEqual([+ ['frontmatter', 'excluded_slug'],+ ['title', 'excluded_slug'],+ ]);+ });++ test('the mention pass removes links already written to a page once it is excluded', async () => {+ await page(engine, 'people/inha', 'person', '인하', 'A person.');+ await page(engine, 'notes/n1', 'note', 'n1', '사정으로 인하여 취소되었습니다.');+ await sweep(engine);+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> people/inha']);+ await engine.setConfig('mentions.exclude_slugs', 'people/inha');+ await sweep(engine);+ expect(await mentionLinks(engine)).toEqual([]);+ });++ test('explain names the setting', async () => {+ await page(engine, 'people/inha', 'person', '인하', 'A person.');+ await engine.setConfig('mentions.exclude_slugs', 'people/inha');+ const r = await explainMention(engine, '인하');+ expect(r.reason).toBe('excluded_by_config');+ expect(r.message).toContain('mentions.exclude_slugs');+ });+});