Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mentions): mask HTML comments in the mention scan and rescan once (#6740)

garrytand2bae380a915
diff --git a/docs/.wave18-fragments/lane3.md b/docs/.wave18-fragments/lane3.md
new file mode 100644
index 0000000000..b9716f0b50
--- /dev/null
+++ b/docs/.wave18-fragments/lane3.md
@@ -0,0 +1,19 @@
+# Wave 18 lane 3 fragments (integrator: apply, then delete this file)
+
+Lane 3 branch: capy/wave18-lane3. Each section names the target file, the place and the exact text. Version strings use `<WAVE>` for the wave's stamped version.
+
+## #6740 mention scan masks HTML comments
+
+### src/core/behavior-change-notice.ts (append to BEHAVIOR_CHANGES)
+
+```ts
+ { since: '<WAVE>', text: 'The entity mention scan no longer reads text inside HTML comments, so the `<!--- gbrain:... -->` fence markers stop producing `mentions` links to a page titled like a marker word (#6740). `MENTION_EXTRACTOR_VERSION` is now 6: the next `gbrain extract --stale` (or maintenance cycle) rescans every inline-body page once and removes the stale plain mention rows; `typed_ner` edges are untouched and segmented pages stay deferred as before. Entity cards and `get_backlinks` show a mention coverage notice (state `pending`) until that rescan finishes.' },
+```
+
+### CHANGELOG.md (wave entry, Fixed)
+
+- The mention scan ignores text inside HTML comments, so gbrain's own fence markers no longer link every page to a page titled "gbrain" (#6740). One rescan runs on the next extract or maintenance pass and removes the false mention links. "Discussed in" timeline bullets that the bug already wrote are not removed by this release; delete them once by hand (they no longer come back). A preview-first cleanup is deferred to the next wave.
+
+### Deferred list (PR body)
+
+- #6740: cleanup of stale "Discussed in" timeline bullets already written; preview-first repair, next wave.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index d223e3ead1..b621eee039 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 the
links current from `gbrain extract --stale`, and serves them on the `entity`
card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
-- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names (a name claimed at one origin by an identity-sibling group stays, marked `shared`), reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code with `stripCodeBlocks`, then picks the longest matching entry at each token (maximal munch), first mention per target only (a `shared` match links every sibling with those tokens, unless the scanning page is one of them), skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins, except that a connector contact stub, `connector_stub` from `google_contact_id` frontmatter, yields under `allowCrossSource` to the one canonical same-name page in another source or the one sharing its slug; #6158). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
+- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names (a name claimed at one origin by an identity-sibling group stays, marked `shared`), reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code and HTML comments (the `<!--- gbrain:... -->` fence markers included) with `stripCodeBlocks`, offsets preserved, then picks the longest matching entry at each token (maximal munch), first mention per target only (a `shared` match links every sibling with those tokens, unless the scanning page is one of them), skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins, except that a connector contact stub, `connector_stub` from `google_contact_id` frontmatter, yields under `allowCrossSource` to the one canonical same-name page in another source or the one sharing its slug; #6158). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
- `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`, `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`), `mentions.alias_deny`, `mentions.multiword_aliases` and `mentions.sibling_merge` (both default on): from the request's config snapshot when one is open (`config-snapshot.ts`), else in one keyed config read. `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/siblings.ts` — identity siblings: pages in one source naming the same normalized title subject under pairwise different prefixes, all linkable entities of one canonical type other than `person`, none excluded or `identity: separate`, at most `SIBLING_GROUP_CAP` (3; a larger group is `capped`). `siblingVerdict` is the one rule (card, search fan-out, gazetteer); `readIdentitySiblings` reads a page's group with the private-page predicate for untrusted callers. `siblingCanonical` (the group's lowest slug, for fact attribution by name) and `factEntitySlugs` (the page, its siblings and its bare subject slug, read by the entity card's facts and `recall {entity}`). Nothing is written to `entity_identities`, and aliases and references are never unioned. Tests: `test/mentions-identity-siblings.test.ts`.
- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. Stored aliases and card identity lines read declarations with `anchored: true` (a cue must attach to the page itself; search's per-result `aliasDeclarations` scan reads them all). `titleSubject` (text after the last `: `), `declarationsIn` (each declaration with its line: prose cues, label and value lines and table rows whose label names an alias field (also a label opening a later sentence of a line, alias noun within its first two words, at most 7 words), the quoted-only "calls it" cue, a quoted defined term right after the page's own name; a capture is a quoted name or a run of up to 4 capitalized or code tokens ending at punctuation, a lowercase word or the line end, rejected on a possessive, a run of only common words or a cue after a relational noun; linear in the line length), `declaredNames` (its post-filtered names, shared with search's `aliasDeclarations`), `deriveEntityAliases(page, {multiword, deny})` (subject `origin='subject'`, declarations `origin='declared'` with their lines, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`; `mentions.alias_deny` and frontmatter `alias_deny` reject as `denied`). `aliasRejection`: under 4 characters (unless a short code the page declares for itself: a declaration marked `selfCode`), a generic word, or the first word of the page's own multi-word name. Rejections are returned with their line for explain. Tests: `test/mentions-policy-aliases.test.ts`.
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index fb75b1d13f..2c81bd7461 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -125,7 +125,7 @@ export function hashGazetteer(gazetteer: Gazetteer): string {
for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);
}
// Matching semantics are part of the resume identity, not just DB contents.
- return createHash('sha256').update('shared-sibling-names-v3\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
+ return createHash('sha256').update('html-comments-masked-v4\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
}
/** One row of the saved entry set the mention pass diffs (mention_gazetteer_entries). */
@@ -739,7 +739,7 @@ function hasHangulMatchBoundary(
* - First-mention-only cap: dedup by `(entry.source_id, entry.slug)` (one
* link per target page regardless of how many body mentions there are).
*
- * Code-block stripping via `stripCodeBlocks` (preserves offsets, so the
+ * Code-block and HTML-comment stripping via `stripCodeBlocks` (preserves offsets, so the
* returned mention offsets index into the ORIGINAL text not the stripped
* text — useful for downstream debugging tools).
*/
@@ -749,7 +749,7 @@ export function findMentionedEntities(
opts: FindMentionsOpts,
): Mention[] {
if (!text || gazetteer.size === 0) return [];
- const stripped = stripCodeBlocks(text);
+ const stripped = stripCodeBlocks(text, { onHtmlComment: () => {} });
const tokens = tokenizeForScan(stripped);
if (tokens.length === 0) return [];
const ignored = new Set((opts.ignoreNames ?? []).map(n => tokenizeTitle(n).join(' ')).filter(Boolean));
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
index 233ab49829..f685cfc962 100644
--- a/src/core/mentions/pass.ts
+++ b/src/core/mentions/pass.ts
@@ -60,7 +60,7 @@ import { maintenanceAttribution } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
/** Bump to rescan every page's mentions once (gazetteer or scanner behavior change). */
-export const MENTION_EXTRACTOR_VERSION = 5;
+export const MENTION_EXTRACTOR_VERSION = 6;
/** Bump to re-derive every entity page's declared aliases and title subject once. */
export const ALIAS_DERIVATION_VERSION = 4;
diff --git a/test/by-mention.test.ts b/test/by-mention.test.ts
index d1826073d1..edc663c772 100644
--- a/test/by-mention.test.ts
+++ b/test/by-mention.test.ts
@@ -85,6 +85,21 @@ function gazetteerFromEntries(entries: Omit<GazetteerEntry, 'tokens'>[]): Gazett
// ============================================================
describe('findMentionedEntities — pure cases', () => {
+ test('text inside HTML comments is never a mention: a gbrain fence marker does not link a page titled gbrain (#6740)', () => {
+ const g = gazetteerFromEntries([
+ { slug: 'projects/gbrain', source_id: 'default', title: 'gbrain' },
+ { slug: 'companies/acme', source_id: 'default', title: 'Acme Example' },
+ ]);
+ const body = '## Facts\n<!--- gbrain:facts:begin -->\n| claim |\n<!--- gbrain:facts:end -->\n<!-- Acme Example owns this -->\nNotes.';
+ expect(findMentionedEntities(body, g, { fromSlug: 'notes/n1', fromSourceId: 'default' })).toEqual([]);
+ const prose = '<!-- Acme Example --> We shipped gbrain with Acme Example.';
+ const mentions = findMentionedEntities(prose, g, { fromSlug: 'notes/n1', fromSourceId: 'default' });
+ expect(mentions.map(m => [m.slug, m.offset])).toEqual([
+ ['projects/gbrain', prose.indexOf('gbrain')],
+ ['companies/acme', prose.lastIndexOf('Acme Example')],
+ ]);
+ });
+
test('1. single-token title match', () => {
const g = gazetteerFromEntries([
{ slug: 'companies/acme', source_id: 'default', title: 'Acme' },
diff --git a/test/mentions-pass.test.ts b/test/mentions-pass.test.ts
index 1746f5d010..9ca1e6e417 100644
--- a/test/mentions-pass.test.ts
+++ b/test/mentions-pass.test.ts
@@ -131,6 +131,21 @@ describe('short codes the entity page declares for itself', () => {
});
describe('reconcile scope, off switch and failure', () => {
+ test('a name only inside an HTML comment never links, and a row an older scanner wrote from a comment is removed on upgrade (#6740)', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Weekly notes.\n<!--- acme example:facts:begin -->\n<!--- acme example:facts:end -->');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ // The release before the comment mask (MENTION_EXTRACTOR_VERSION 5) wrote this row and stamped the page scanned.
+ await engine.addLinksBatch([{ from_slug: 'notes/n1', to_slug: 'companies/acme', link_type: 'mentions', link_source: 'mentions', context: 'Acme Example' } as never]);
+ await engine.executeRaw(`UPDATE page_mention_state SET mention_version = 5 WHERE page_id = (SELECT id FROM pages WHERE slug = 'notes/n1')`);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/acme']);
+ const r = await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ expect(r.mentions?.removed).toBe(1);
+ expect(await countMentionDuePages(engine)).toBe(0);
+ });
+
test('typed_ner rows survive a reconcile and an off/on cycle while an obsolete plain mention goes', async () => {
await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
await page(engine, 'people/alice', 'person', 'Alice Example', 'Alice works at Acme Example.');