Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

doctor stale_mentions: name each stale link's stored link_type

garrytane584208df895
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a5e0ad09f..3466c65a3b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `timeline_history`: on a brain with more than 10,000 pages carrying database-only timeline rows, a pass keeps only the first 10,000 for its final recount. It used to report that recount as exact, and a pass whose kept pages had been repaired was recorded as clean while the rest still held database-only rows. Such a pass now reports its counts as a lower bound ("at least"), keeps warning, and is never trusted as clean. Reported by @Masashi-Ono0611 (#8511).
- `conversation_format_coverage`: the sample now includes pages stored under the granular conversation types the extractor already reads (`slack-thread`, `slack-dm-day`, `email-digest`), so unparseable transcripts on a brain that never ran the type-consolidation pack are reported instead of silently skipped. Reported by @Masashi-Ono0611 (#8519).
- `minions_migration` under `gbrain doctor --fast`: a migration the brain's config can decline (v0.53.0, `shared_skills.migration.enabled`) is no longer listed as not run. Without a database connection the check cannot read that setting, and `gbrain apply-migrations --yes` skips a declined migration, so the warning could never clear. The full `gbrain doctor` still reports it when it is not declined. Reported by @Masashi-Ono0611 (#8721).
+- `stale_mentions`: each stale example now carries its own `gbrain unlink` command with the link type the row is stored under. The hint used to say `--link-type mentions` for every row, which removes nothing for a typed link stored under a verb such as `founded`. Reported by @Masashi-Ono0611 (#8817).
## [0.60.620.0] - 2026-11-09
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 8828f96ab3..9320166a50 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 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 name written only in Katakana (ー included) must be a whole contiguous Katakana run (`hasKatakanaMatchBoundary`): Katakana, small and supplementary kana, ー and voicing marks continue it, Hiragana, Han, Latin, punctuation and ・ end it, so デン matches 喫茶デン and デン・カフェ but not インシデント. 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 name written only in Katakana (ー included) must be a whole contiguous Katakana run (`hasKatakanaMatchBoundary`): Katakana, small and supplementary kana, ー and voicing marks continue it, Hiragana, Han, Latin, punctuation and ・ end it, so デン matches 喫茶デン and デン・カフェ but not インシデント. 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; each example carries the row's stored `link_type` (a verb on `typed_ner` rows), which doctor `stale_mentions` puts in that example's own `gbrain unlink … --link-type <type> --link-source mentions` hint (#8814).
- `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/commands/doctor/checks/stale-mentions.ts b/src/commands/doctor/checks/stale-mentions.ts
index f915affc0d..c2a321b696 100644
--- a/src/commands/doctor/checks/stale-mentions.ts
+++ b/src/commands/doctor/checks/stale-mentions.ts
@@ -51,7 +51,7 @@ export async function staleMentionsCheck(engine: BrainEngine): Promise<Check> {
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, n]) => `${n} ${k}`)
.join(', ');
- const eg = res.examples.map(e => `${e.from} -> ${e.to}`).join(', ');
+ const eg = res.examples.map(e => `${e.from} -> ${e.to}: gbrain unlink ${e.from} ${e.to} --link-type ${e.link_type} --link-source mentions`).join('; ');
// An empty gazetteer makes EVERY mentions row unreproducible, which is
// a different diagnosis from ordinary drift — name it, or the operator
// reads "everything is stale" and starts deleting real links.
@@ -64,8 +64,7 @@ export async function staleMentionsCheck(engine: BrainEngine): Promise<Check> {
message:
`${res.staleLinks} of ${res.linksScanned} by-mention link(s) no longer follow from the current gazetteer${coverage} (${kinds}). ` +
`${why}Re-running the scan will NOT remove them — the write path is additive. ` +
- `Remove individually with: gbrain unlink <from> <to> --link-type mentions --link-source mentions. ` +
- `e.g. ${eg}`,
+ `Remove each one with its own command, which names the link type it is stored under (typed links use a verb): ${eg}`,
};
} catch (e) {
return {
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 6e5a211a63..b4e291fe99 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -906,6 +906,8 @@ export interface StaleMention {
to: string;
/** `link_kind` as stored; NULL rows (legacy / pre-v98) report as 'plain'. */
kind: string;
+ /** `link_type` as stored (a verb on typed_ner rows), which `gbrain unlink --link-type` must name. */
+ link_type: string;
}
export interface StaleMentionsScan {
@@ -1011,11 +1013,11 @@ export async function scanStaleMentions(
const rows = await engine.executeRaw<{
from_id: number; from_slug: string; to_slug: string;
- to_source_id: string | null; link_kind: string | null;
+ to_source_id: string | null; link_kind: string | null; link_type: string;
}>(
`${scannedCte}
SELECT l.from_page_id AS from_id, f.slug AS from_slug,
- t.slug AS to_slug, t.source_id AS to_source_id, l.link_kind
+ t.slug AS to_slug, t.source_id AS to_source_id, l.link_kind, l.link_type
FROM links l
JOIN scanned s ON s.id = l.from_page_id
JOIN pages f ON f.id = l.from_page_id
@@ -1056,7 +1058,7 @@ export async function scanStaleMentions(
const kind = row.link_kind ?? 'plain';
staleByKind[kind] = (staleByKind[kind] ?? 0) + 1;
if (examples.length < STALE_MENTIONS_MAX_EXAMPLES) {
- examples.push({ from: page.slug, to: row.to_slug, kind });
+ examples.push({ from: page.slug, to: row.to_slug, kind, link_type: row.link_type });
}
}
}
diff --git a/test/doctor-stale-mentions-link-type-8814.test.ts b/test/doctor-stale-mentions-link-type-8814.test.ts
new file mode 100644
index 0000000000..acfb2bd65e
--- /dev/null
+++ b/test/doctor-stale-mentions-link-type-8814.test.ts
@@ -0,0 +1,38 @@
+/**
+ * #8814: the stale_mentions hint told users to run
+ * `gbrain unlink <from> <to> --link-type mentions --link-source mentions` for
+ * every stale row, but typed_ner rows are stored under a verb link_type
+ * (e.g. `founded`), so that command removed nothing. Each example now
+ * carries its exact unlink command with the stored link_type.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { staleMentionsCheck } from '../src/commands/doctor/checks/stale-mentions.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+test('the suggested unlink removes a stale typed_ner link', async () => {
+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'Acme Example is a company.', timeline: '', frontmatter: {} });
+ await engine.putPage('notes/meeting', { type: 'note', title: 'notes/meeting', compiled_truth: 'Quiet day.', timeline: '', frontmatter: {} });
+ await engine.addLinksBatch([{ from_slug: 'notes/meeting', to_slug: 'companies/acme-example', link_type: 'founded', link_source: 'mentions', link_kind: 'typed_ner' }]);
+
+ const check = await staleMentionsCheck(engine);
+ expect(check.status).toBe('warn');
+ const suggested = check.message.match(/--link-type (\S+) --link-source (\S+?)\.?(?:\s|$)/);
+ expect(suggested).not.toBeNull();
+
+ const ctx = { engine, remote: false, config: {}, logger: console, dryRun: false } as unknown as OperationContext;
+ const removed = await operationsByName.remove_link!.handler(ctx, { from: 'notes/meeting', to: 'companies/acme-example', link_type: suggested![1], link_source: suggested![2] });
+ expect(removed).toMatchObject({ removed: 1 });
+ expect(check.message).toContain('gbrain unlink notes/meeting companies/acme-example --link-type founded --link-source mentions');
+ expect(await engine.executeRaw("SELECT 1 FROM links WHERE link_source = 'mentions'")).toHaveLength(0);
+});
diff --git a/test/doctor-stale-mentions.test.ts b/test/doctor-stale-mentions.test.ts
index 0484c1b9fb..7eda78bf12 100644
--- a/test/doctor-stale-mentions.test.ts
+++ b/test/doctor-stale-mentions.test.ts
@@ -97,7 +97,7 @@ describe('scanStaleMentions', () => {
expect(res.staleLinks).toBe(1);
expect(res.staleByKind).toEqual({ plain: 1 });
expect(res.examples).toEqual([
- { from: 'notes/meeting', to: 'companies/acme-example', kind: 'plain' },
+ { from: 'notes/meeting', to: 'companies/acme-example', kind: 'plain', link_type: 'mentions' },
]);
});