Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mentions): a 2-3 character code the entity page declares for itself becomes one of its names

garrytanf24ca6afe3f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b7d26b3a5..1ded6f8650 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,7 +21,7 @@ On a company brain, most records never repeat a customer's full name. They use a
| Where | What changed |
|---|---|
| `entity` card | New `identity_siblings` (pages about the same subject under another title prefix, each with its own aliases, never merged), `identity_excerpt` (verbatim lines that may carry another name, with the page they came from), `aka_sources` and `alias_guidance` (what `aka` covers, which names to search). `aka` is unchanged. |
-| Alias learning | Prose cues ("also known as", "goes by", "formerly", "doing business as", a quoted name after "calls it"), alias label lines and table rows ("Internal nickname: Copper Fox"), labels later in a line ("Account: Widget Co. Nickname used by the team: Copper Fox.") and multi-word names. A name two sibling pages share now links mentions to both instead of neither. |
+| Alias learning | Prose cues ("also known as", "goes by", "formerly", "doing business as", a quoted name after "calls it"), alias label lines and table rows ("Internal nickname: Copper Fox"), labels later in a line ("Account: Widget Co. Nickname used by the team: Copper Fox."), multi-word names, and 2-3 character codes the page declares for itself ("Also called JOF in my notes", `a.k.a.`, `known as`, `short for` or an alias label; common capitals and acronyms such as `IT`, `US`, `OK`, `AI` never count). The short-code rule comes from the Program Primary Hard root cause (gbrain-evals#109), where mails naming a customer only by its code never linked to it. A name two sibling pages share now links mentions to both instead of neither. |
| Saved facts | A fact saved by an account's name links to the account even when its sheet and CRM record share the name; the card's `recent_facts` and `recall {entity}` show facts saved under either page or the bare name, and a search naming the entity lists its newest saved facts first, then facts of an entity they point to. |
| `search` / `query` | When a query names an entity, gbrain also searches up to 4 of its other names (keyword-only, rows carry `matched_alias`). Every search adds one line: the rows are a ranked top-K, and `keyword_total` pages match the keywords (up to "10000+"). |
| `search` `match: "keyword"` | On an entity's name or alias it lists pages using any of its names in one walk. Otherwise lists every keyword match, page by page, with `total`, `truncated` and a ready-to-send `next`. Remote agents can use it. A per-call `mode` is refused with a fix naming `match: "keyword"`; an offset over 10,000 is refused. |
@@ -54,7 +54,7 @@ gbrain config set search.alias_fanout_max 0 # turn the alias fan-out o
### Things to watch
-- **One-time rescan.** The alias and mention extractor versions moved (`MENTION_EXTRACTOR_VERSION` 4, `ALIAS_DERIVATION_VERSION` 3), so every brain re-derives aliases and rescans mentions once on its next `gbrain extract --stale`; cards show `coverage: pending` until it finishes, even on a brain where no page changed.
+- **One-time rescan.** The alias and mention extractor versions moved (`MENTION_EXTRACTOR_VERSION` 5, `ALIAS_DERIVATION_VERSION` 4), so every brain re-derives aliases and rescans mentions once on its next `gbrain extract --stale`; cards show `coverage: pending` until it finishes, even on a brain where no page changed.
- **Migration v223** adds `persistence_requests.client_request_id` (nullable).
- **Search output grew** by one count line and one date line per call; the starter tool list stays within its 25,000-character budget.
- **Settings:** `mentions.multiword_aliases`, `mentions.sibling_merge`, frontmatter `identity: separate`, `search.demote_generated` (all on by default) are the off switches.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 3ca1d2da06..32ff22bde3 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -8,7 +8,8 @@ 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). 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). `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`. `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, 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`.
+- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. `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`.
+- `src/core/mentions/short-codes.ts` — `isShortCode` (2-3 letters or digits with a capital, not in `SHORT_CODE_STOPLIST` of common capitals and business acronyms, compared upper-cased). `declarationsIn` marks a short code `selfCode` when an alias label or an `also called` / `a.k.a.` / `known as` / `short for` cue declares it in a sentence naming nothing before the cue but the page (empty, a pronoun or an own name); `aliasRejection` lets it through and `by-mention.ts` keeps a `declared`, `case_sensitive` short code in the gazetteer, matched only as written. Leaf module (aliases.ts imports by-mention.ts). Tests: `test/mentions-policy-aliases.test.ts`, `test/mentions-pass.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, `mentions.alias_deny`, `mentions.multiword_aliases`, `mentions.sibling_merge`) marks every page due and recounts `pending`; the status row's `policy_fingerprint` carries the extractor versions its count reflects after the hash (`<hash>;v<mention>.<alias>`, `INDEX_VERSION_STAMP`), and a stamp that differs from the binary's recounts `pending` once (version-behind pages are already due, so nothing is invalidated); `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` (`countIndexDuePages`: mention-due pages plus linkable entity pages whose derived aliases are behind their content or `ALIAS_DERIVATION_VERSION`, counted when the source finishes or the deadline stops it) 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-coverage-version.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` (index-due pages per source, as `countIndexDuePages` counts them, 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`.
- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
diff --git a/docs/designs/ALIAS_CONVENTIONS.md b/docs/designs/ALIAS_CONVENTIONS.md
index f768a683bc..c8ae7f0cb8 100644
--- a/docs/designs/ALIAS_CONVENTIONS.md
+++ b/docs/designs/ALIAS_CONVENTIONS.md
@@ -42,9 +42,10 @@ A capture is rejected when:
`vendor`, `supplier`, `customer`, `client`, `acquirer`, `investor`) appears
between the start of the sentence and the cue (`our competitor, also known
as Blue Harbor` declares nothing for this page);
-- the existing post-filters reject it (`aliasRejection`: under 4 characters,
- a generic token, the first word of the page's own multi-word name) or it
- equals the page's own name;
+- the existing post-filters reject it (`aliasRejection`: under 4 characters
+ unless it is a short code the page declares for itself, below; a generic
+ token; the first word of the page's own multi-word name) or it equals the
+ page's own name;
- it equals another live page's exact title in the same source (the existing
reader and gazetteer guard).
@@ -113,6 +114,34 @@ parentheses elsewhere in a page names many things. A parenthetical cue
(`(aka Blue Harbor)`, `(formerly Gearbox Labs)`, `(d/b/a Northwind Ops)`) is a
prose cue and needs no name.
+## Short codes the page declares for itself
+
+A name under 4 characters is kept only as a short code (`src/core/mentions/short-codes.ts`):
+
+- **Shape.** 2 or 3 letters or digits with at least one capital letter: `JOF`,
+ `J2`, `3M`, `JoF`. Lower-case words (`it`, `us`, `and`) never qualify.
+- **Stoplist.** Capitalized English words and everyday business abbreviations
+ never qualify, compared upper-cased (`IT`, `US`, `OK`, `AI`, `HR`, `CEO`,
+ `API`, `SSO`, `SOC`, `B2B` and the rest of `SHORT_CODE_STOPLIST`).
+- **Own-page declaration.** The page's own body declares it with an alias label
+ (`Account code: JOF`, a mid-line `Short name: JOF`, a table row) or with one
+ of these cues: `also called`, `a.k.a.` / `aka`, `known as` (with `also`,
+ `better`, `widely`), `short for`. Before the cue, its sentence names nothing
+ but the page: nothing at all (`Also called JOF in my notes`), a pronoun
+ (`It is also called JOF`) or one of the page's own names (`Joffrey Foods,
+ a.k.a. JOF`). `Widget Co, also called WCO` on another entity's page declares
+ nothing for that page; other cues (`goes by`, `formerly`, `nicknamed`) never
+ declare a short code.
+
+A short code is a single token, so it is stored `case_sensitive` and links only
+as written, as a whole token: "Call with JOF" links, "jof" does not.
+
+| Positive fixture | Negative fixture |
+|---|---|
+| `Also called JOF in my notes.` | `Also called IT internally.` (stoplist) |
+| `Joffrey Foods (a.k.a. JOF) renewed.` | `Widget Co, also called WCO, is a reseller.` (another entity's sentence) |
+| `Account code: J2` | `It goes by JOF.` (cue outside the short-code list) |
+
## Escape hatches
- Brain config `mentions.alias_deny` (JSON array or comma list) and page
@@ -132,6 +161,15 @@ prose cue and needs no name.
## Changelog
+- 2026-10-08: short codes (2-3 characters) the page declares for itself with an
+ alias label or an `also called` / `a.k.a.` / `known as` / `short for` cue, with
+ a stoplist of common capitals and acronyms. Origin: the Program Primary Hard
+ root cause (gbrain-evals#109), where a company page said "Also called JOF in
+ my notes" and mails naming "JOF" never linked to the company. The Cat 40 Hard
+ development world has no codes under 4 characters, so its derived aliases are
+ unchanged (5,690 on its account pages, all correct; 5,770 declared over all
+ 55,440 documents, none under 4 characters, before and after).
+
- 2026-10-08: added labels that open a later sentence of a line and the
quoted-only "calls it" cue. Origin: the Cat 40 Hard development (calibration)
world, whose account sheets write `Nickname used by the team: X` mid-line and
diff --git a/src/commands/extract-mentions-explain.ts b/src/commands/extract-mentions-explain.ts
index 312a09d5e3..abea297ea5 100644
--- a/src/commands/extract-mentions-explain.ts
+++ b/src/commands/extract-mentions-explain.ts
@@ -50,7 +50,7 @@ const DROP_REASON: Record<DroppedName['reason'], ExplainReason> = {
const MESSAGES: Record<ExplainReason, string> = {
ambiguous_first_word: 'This single word is the first word of a longer entity name in this source, so it never links alone; write the full name.',
- below_min_length: 'Names shorter than 4 characters never link (too many false matches); write the full name or declare a longer alias.',
+ below_min_length: 'Names shorter than 4 characters never link (too many false matches), except a 2-3 character code the entity page declares for itself ("Also called JOF", "Account code: JOF"); write the full name or declare the code on the entity\'s own page.',
generic_token: 'This is a generic word (role, document or placeholder), so it never links as a single-word name.',
alias_collision: 'Another page in this source claims the same name (or it is another page\'s exact title), so the alias is dropped as ambiguous.',
case_mismatch: 'This alias is case-sensitive (a single-word declared code) and the text uses a different case.',
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b4f3ea7ea0..fd61992c29 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -356,6 +356,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.116.0', text: 'Facts saved by name about an account whose account sheet and CRM record share its name now link to that account (they used to get a slug no page has), and the entity card (`recent_facts`, `active_fact_count`) and `recall {entity}` show facts saved under either page or the bare name. A search that names an entity lists that entity\'s newest saved facts first, then facts of an entity they point to ("folded into Kite Co").' },
{ since: '0.60.116.0', text: '`search` with `match: "keyword"` on an entity\'s name or alias lists pages that use any of its names, and the count line names them; a query that is not one entity\'s name keeps its exact keywords.' },
{ since: '0.60.116.0', text: '`remember` with an entity, when the same claim is an active fact saved without one, now supersedes that copy (`status: superseded`, `superseded_fact_id`; batch receipts carry it too) instead of saving a duplicate. `forget` of a fact saved without an entity is refused with `invalid_params` and the prefix `claim_linked` while the same claim is active on entity-linked facts, which it used to withdraw as well.' },
+ { since: '0.60.116.0', text: 'An entity page can now give itself a 2 or 3 character code ("Also called JOF in my notes", "Joffrey Foods, a.k.a. JOF", "Account code: JOF"): it becomes one of the entity\'s names and pages that write it exactly as written link to the entity. Lower-case words, common capitals and acronyms (`IT`, `US`, `OK`, `AI`, `CEO`, `API` ...) and codes declared in another entity\'s sentence never qualify. Every brain re-derives aliases and rescans mentions once.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index a7ba7a685c..6ea8d1b646 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -40,6 +40,7 @@ import { stripCodeBlocks, isCrossSourceLinksEnabled } from './link-extraction.ts
import { isGenericEntityToken } from './entity-name-quality.ts';
import { ALWAYS_LINKABLE_TYPES, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './mentions/policy.ts';
import { siblingVerdict, type SiblingCandidate } from './mentions/siblings.ts';
+import { isShortCode } from './mentions/short-codes.ts';
/**
* The four types that are always linkable, whatever the schema pack says. The
@@ -628,13 +629,15 @@ export async function buildGazetteer(
if (rank(a.origin) > claim.rank) continue;
if (excludedSlugs.has(a.slug)) { drop({ ...base, reason: 'excluded_slug' }); continue; }
if (claim.slugs.size > 1 && !claim.shared) { drop({ ...base, reason: 'alias_collision' }); continue; }
- if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ // A declared 2-3 character code passed the own-page cue gate at derivation; it links only as written.
+ const shortCode = a.origin === 'declared' && !!a.case_sensitive && !!a.alias_text && isShortCode(a.alias_text);
+ if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias) && !shortCode) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (ignoreLc.has(alias.toLowerCase())) { drop({ ...base, reason: 'ignored' }); continue; }
if (titleBySource.has(`${src} ${alias.toLowerCase()}`)) { drop({ ...base, reason: 'title_wins' }); continue; }
const tokens = tokenizeTitle(alias);
if (tokens.length === 0) continue;
- if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1 && !shortCode) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
const caseTokens = a.case_sensitive && a.alias_text ? caseTokensOf(a.alias_text) : undefined;
diff --git a/src/core/mentions/aliases.ts b/src/core/mentions/aliases.ts
index 5ad3edd49b..a0acd5992e 100644
--- a/src/core/mentions/aliases.ts
+++ b/src/core/mentions/aliases.ts
@@ -32,6 +32,7 @@ import { stripTakesFence } from '../takes-fence.ts';
import { stripFactsFence } from '../facts-fence.ts';
import { isGenericEntityToken } from '../entity-name-quality.ts';
import { hasCJK, tokenizeTitle } from '../by-mention.ts';
+import { isShortCode } from './short-codes.ts';
const CUES = [
'also known as', 'a\\.k\\.a\\.?', 'aka', 'known internally as', 'internally known as', 'known to the team as', 'better known as',
@@ -43,6 +44,10 @@ const CUES = [
];
/** Cues that declare a name only when it is quoted ("the team calls it \"Copper Fox\""). */
const QUOTED_CUE_RE = /(?<![A-Za-z])(?:calls?|called|call) it\s+/gi;
+/** Cues that may declare a 2-3 character code for the page itself (mentions/short-codes.ts); labels qualify too. */
+const SHORT_CODE_CUE_RE = /^(?:also known as|better known as|widely known as|known as|a\.k\.a\.?|aka|also called|short for)$/i;
+/** A pronoun subject that names the page itself ("It is also called JOF"). */
+const SELF_SUBJECT_RE = /^(?:it|this|this (?:company|account|customer|client|project|team))$/i;
const CUE_RE = new RegExp(`(?<![A-Za-z0-9])(?:${CUES.join('|')})(?![A-Za-z0-9])`, 'gi');
const LABEL_NOUN_RE = /(?<![a-z])(?:nicknames?|alias(?:es)?|aka|a\.k\.a\.?|also known as|short name|trading name|trade name|brand name|former (?:legal )?name|previous name|legal name|display name|dba|d\/b\/a|code ?name|account code|customer code|ticker)(?![a-z])/i;
const RELATIONAL_NOUN_RE = /\b(?:competitors?|rivals?|partners?|parent(?: company)?|subsidiar(?:y|ies)|affiliates?|vendors?|suppliers?|customers?|clients?|acquirers?|investors?)\b/i;
@@ -66,8 +71,13 @@ export interface DeclarationOpts {
ownNames?: string[];
}
-/** One declared name with the line that declares it (0-based line index into the scanned text). */
-export interface Declaration { alias: string; line: number }
+/**
+ * One declared name with the line that declares it (0-based line index into the
+ * scanned text). `selfCode` marks a 2-3 character code (mentions/short-codes.ts)
+ * declared by an alias label, or by a short-code cue whose sentence names
+ * nothing before it but the page itself.
+ */
+export interface Declaration { alias: string; line: number; selfCode?: true }
const isQuarter = (t: string) => /^(?:q[1-4]|h[12]|fy\d{2,4})$/i.test(t);
const isCommon = (t: string) => COMMON_WORDS.has(t.toLowerCase()) || isQuarter(t);
@@ -137,7 +147,13 @@ export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declar
const multiword = opts.multiword !== false;
const lines = (text ?? '').split('\n');
const out: Declaration[] = [];
- const push = (alias: string | null, line: number) => { if (alias && !out.some(d => d.alias === alias)) out.push({ alias, line }); };
+ const push = (alias: string | null, line: number, selfCode = false) => {
+ if (!alias) return;
+ const prior = out.find(d => d.alias === alias);
+ const code = selfCode && isShortCode(alias);
+ if (!prior) out.push({ alias, line, ...(code ? { selfCode: true as const } : {}) });
+ else if (code && !prior.selfCode) prior.selfCode = true;
+ };
const ownNames = (opts.ownNames ?? []).filter(Boolean);
const ownLower = ownNames.map(n => n.toLowerCase());
/** Whether `before` ends with one of the page's own names, after any corporate suffixes and a trailing comma. */
@@ -161,20 +177,20 @@ export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declar
if (trimmed.startsWith('|')) {
const cells = trimmed.replace(/^\||\|$/g, '').split('|').map(c => stripLineMarkup(c));
if (cells.length >= 2 && !isTableSeparator(trimmed) && !isTableSeparator(lines[i + 1]) && isLabel(cells[0]!.replace(/:$/, ''))) {
- for (const name of labelValues(cells[1]!, multiword)) push(name, i);
+ for (const name of labelValues(cells[1]!, multiword)) push(name, i, true);
}
continue;
}
const plain = stripLineMarkup(line);
const colon = plain.indexOf(':');
if (colon > 0 && colon <= 60 && isLabel(plain.slice(0, colon))) {
- for (const name of labelValues(plain.slice(colon + 1), multiword)) push(name, i);
+ for (const name of labelValues(plain.slice(colon + 1), multiword)) push(name, i, true);
}
// A label can also open a later sentence of the line ("Account: X. Nickname used by the team: Y.").
for (const segment of plain.split(/(?<=[.;!?])\s+/).slice(1)) {
const at = segment.indexOf(':');
if (at > 0 && at <= 60 && isLeadingLabel(segment.slice(0, at))) {
- for (const name of labelValues(segment.slice(at + 1), multiword)) push(name, i);
+ for (const name of labelValues(segment.slice(at + 1), multiword)) push(name, i, true);
}
}
const sentenceBefore = (at: number) => {
@@ -182,9 +198,14 @@ export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declar
return before.slice(Math.max(before.lastIndexOf('. '), before.lastIndexOf('; '), -1) + 1);
};
CUE_RE.lastIndex = 0;
+ /** The sentence before a cue names only the page: nothing, a pronoun, or one of its own names. */
+ const namesOnlySelf = (at: number) => {
+ const subject = sentenceBefore(at).trim().replace(/[,(\-\u2013\u2014]+$/, '').trim().replace(/\s+(?:is|was)$/i, '').trim();
+ return subject === '' || SELF_SUBJECT_RE.test(subject) || endsWithOwnName(subject);
+ };
for (const m of plain.matchAll(CUE_RE)) {
if (RELATIONAL_NOUN_RE.test(sentenceBefore(m.index!))) continue;
- push(captureName(plain.slice(m.index! + m[0].length), { multiword }), i);
+ push(captureName(plain.slice(m.index! + m[0].length), { multiword }), i, SHORT_CODE_CUE_RE.test(m[0]) && namesOnlySelf(m.index!));
}
for (const m of plain.matchAll(QUOTED_CUE_RE)) {
const rest = plain.slice(m.index! + m[0].length);
@@ -243,10 +264,14 @@ export function publicBody(body: string): string {
return stripFactsFence(stripTakesFence(body ?? ''), { keepVisibility: ['world'] });
}
-/** Why a derived name can never be linked or stored; null when it can. */
-export function aliasRejection(alias: string, ownName: string): AliasRejection | null {
+/**
+ * Why a derived name can never be linked or stored; null when it can. `selfCode`
+ * (the page declares the name for itself with a short-code cue or a label) lets
+ * a 2-3 character code through (mentions/short-codes.ts).
+ */
+export function aliasRejection(alias: string, ownName: string, opts: { selfCode?: boolean } = {}): AliasRejection | null {
const tokens = tokenizeTitle(alias);
- if (!hasCJK(alias) && alias.length < MIN_ALIAS_LENGTH) return 'below_min_length';
+ if (!hasCJK(alias) && alias.length < MIN_ALIAS_LENGTH && !(opts.selfCode && isShortCode(alias))) return 'below_min_length';
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) return 'generic_token';
const first = tokenizeTitle(ownName)[0];
if (tokens.length === 1 && first && tokens[0] === first && tokenizeTitle(ownName).length > 1) return 'ambiguous_first_word';
@@ -283,10 +308,10 @@ export function deriveEntityAliases(
const lines = new Map<string, string>();
const deny = new Set([...(opts.deny ?? []), ...frontmatterList(page.frontmatter?.alias_deny)].map(normalizeAlias).filter(Boolean));
const seen = new Set<string>([normalizeAlias(title)]);
- const push = (alias: string, origin: 'declared' | 'subject', caseSensitive: boolean, line?: string) => {
+ const push = (alias: string, origin: 'declared' | 'subject', caseSensitive: boolean, line?: string, selfCode = false) => {
const norm = normalizeAlias(alias);
if (!norm || seen.has(norm)) return;
- const reason = deny.has(norm) ? 'denied' : aliasRejection(alias, name);
+ const reason = deny.has(norm) ? 'denied' : aliasRejection(alias, name, { selfCode });
if (reason) { rejected.push({ alias, origin, reason, ...(line !== undefined ? { line } : {}) }); return; }
seen.add(norm);
if (line !== undefined) lines.set(norm, line);
@@ -300,7 +325,7 @@ export function deriveEntityAliases(
const own = name.toLowerCase();
for (const d of declarationsIn(text, { multiword: opts.multiword, ownNames: [name, ...ownNames] })) {
if (d.alias.toLowerCase() === own) continue;
- push(d.alias, 'declared', tokenizeTitle(d.alias).length === 1, textLines[d.line]?.trim());
+ push(d.alias, 'declared', tokenizeTitle(d.alias).length === 1, textLines[d.line]?.trim(), d.selfCode === true);
}
return { aliases, rejected, lines };
}
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
index e3d0bb2327..6619170683 100644
--- a/src/core/mentions/pass.ts
+++ b/src/core/mentions/pass.ts
@@ -56,9 +56,9 @@ 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 = 4;
+export const MENTION_EXTRACTOR_VERSION = 5;
/** Bump to re-derive every entity page's declared aliases and title subject once. */
-export const ALIAS_DERIVATION_VERSION = 3;
+export const ALIAS_DERIVATION_VERSION = 4;
const RECONCILE_BATCH = 200;
const ALIAS_BATCH = 200;
diff --git a/src/core/mentions/short-codes.ts b/src/core/mentions/short-codes.ts
new file mode 100644
index 0000000000..9106ed90cd
--- /dev/null
+++ b/src/core/mentions/short-codes.ts
@@ -0,0 +1,35 @@
+/**
+ * Short codes (2 or 3 characters) an entity page declares for itself: "Also
+ * called JOF in my notes", "Acme Example, a.k.a. ACX", "Account code: ACX".
+ * Names under 4 characters are otherwise never derived or linked (too many
+ * false matches), so a code is kept only when its own page declares it with
+ * an explicit alias cue or label (mentions/aliases.ts) and it passes this
+ * shape and stoplist. It then links case-sensitively, as a whole token, like
+ * every single-token declared alias (by-mention.ts).
+ *
+ * Leaf module: aliases.ts and by-mention.ts both read it, and aliases.ts
+ * imports by-mention.ts.
+ */
+
+/** 2-3 letters or digits with at least one capital letter: `JOF`, `A1`, `Wx`, `3M`. */
+const SHORT_CODE_RE = /^(?=[A-Za-z0-9]*[A-Z])[A-Za-z0-9]{2,3}$/;
+
+/**
+ * Capitalized English words, everyday abbreviations and business acronyms
+ * that read as a code but name no particular entity. Compared upper-cased, so
+ * `It`, `Us` and `Ok` are rejected too.
+ */
+export const SHORT_CODE_STOPLIST: ReadonlySet<string> = new Set([
+ 'AN', 'AS', 'AT', 'BE', 'BY', 'DO', 'GO', 'HE', 'IF', 'IN', 'IS', 'IT', 'ME', 'MY', 'NO', 'OF', 'OH', 'OK', 'ON', 'OR',
+ 'SO', 'TO', 'UP', 'US', 'WE', 'AND', 'ANY', 'ARE', 'BUT', 'CAN', 'FOR', 'HER', 'HIM', 'HIS', 'HOW', 'ITS', 'NEW', 'NOT',
+ 'NOW', 'OLD', 'ONE', 'OUR', 'OUT', 'SHE', 'THE', 'TWO', 'WAS', 'WHO', 'WHY', 'YES', 'YOU',
+ 'AI', 'ML', 'IT', 'HR', 'PR', 'QA', 'VP', 'GM', 'PM', 'AM', 'ID', 'IP', 'OS', 'TV', 'UI', 'UX', 'CS', 'EU', 'UK', 'UN',
+ 'USA', 'CEO', 'CFO', 'CTO', 'COO', 'CMO', 'CPO', 'CRO', 'SVP', 'EVP', 'API', 'SDK', 'SSO', 'SOC', 'PDF', 'FAQ', 'ETA',
+ 'FYI', 'TBD', 'ARR', 'MRR', 'KPI', 'OKR', 'NDA', 'LOI', 'IPO', 'B2B', 'B2C', 'SLA', 'CRM', 'ERP', 'SEO', 'ROI', 'MVP',
+ 'URL', 'APP', 'DM', 'PO', 'HQ', 'EOD', 'EOW', 'OOO', 'ASAP',
+]);
+
+/** Whether `text` is a short code that may become a declared alias (shape and stoplist). */
+export function isShortCode(text: string): boolean {
+ return SHORT_CODE_RE.test(text) && !SHORT_CODE_STOPLIST.has(text.toUpperCase());
+}
diff --git a/test/fixtures/short-code-alias/README.md b/test/fixtures/short-code-alias/README.md
new file mode 100644
index 0000000000..81293ede34
--- /dev/null
+++ b/test/fixtures/short-code-alias/README.md
@@ -0,0 +1,6 @@
+# Short-code alias fixture
+
+Four pages copied unchanged from gbrain-evals#109
+(`docs/benchmarks/2026-10-08-program-primary-hard/root-cause/alias-fixture/`, T0b development seed 20261104).
+Every name is invented. The company page declares its short code in prose ("Also called JOF in my notes."); the call
+note and both mails name the company only as `JOF`. Used by `test/mentions-short-code-fixture.test.ts`.
diff --git a/test/fixtures/short-code-alias/companies/joronex-foods.md b/test/fixtures/short-code-alias/companies/joronex-foods.md
new file mode 100644
index 0000000000..4f0fb606a8
--- /dev/null
+++ b/test/fixtures/short-code-alias/companies/joronex-foods.md
@@ -0,0 +1,13 @@
+---
+title: "Joronex Foods"
+type: company
+date: 2026-08-01
+---
+# Joronex Foods
+
+Also called JOF in my notes. Prospect for our remote build cache.
+
+- Champion: [[people/kofi-aziz|Kofi Aziz]] (DevOps Manager)
+- Procurement: [[people/arjun-ivers|Arjun Ivers]] (Senior Buyer)
+- Engineering contact: [[people/lior-ishikawa|Lior Ishikawa]]
+- Deal: [[deals/joronex-foods]]
diff --git a/test/fixtures/short-code-alias/inbox/2026-09-26-aziz-procurement-handoff.md b/test/fixtures/short-code-alias/inbox/2026-09-26-aziz-procurement-handoff.md
new file mode 100644
index 0000000000..8cf7e317fd
--- /dev/null
+++ b/test/fixtures/short-code-alias/inbox/2026-09-26-aziz-procurement-handoff.md
@@ -0,0 +1,11 @@
+---
+title: "Procurement contact change (Kofi Aziz)"
+type: note
+date: 2026-09-26
+---
+# Procurement contact change
+
+From: Kofi Aziz (JOF)
+Date: 2026-09-26
+
+Heads up: starting Wednesday, October 7, Yusuf Lindqvist takes over vendor procurement from Arjun, who is moving to our platform team.
diff --git a/test/fixtures/short-code-alias/inbox/2026-10-09-aziz-reschedule.md b/test/fixtures/short-code-alias/inbox/2026-10-09-aziz-reschedule.md
new file mode 100644
index 0000000000..2d11790c11
--- /dev/null
+++ b/test/fixtures/short-code-alias/inbox/2026-10-09-aziz-reschedule.md
@@ -0,0 +1,13 @@
+---
+title: "Re: pilot kickoff (Kofi Aziz)"
+type: note
+date: 2026-10-09
+---
+# Re: pilot kickoff
+
+From: Kofi Aziz (JOF)
+Date: 2026-10-09
+
+> Could we push the pilot kickoff to Friday, October 30? Same time works on our side.
+
+Me: Works for me, see you Friday, October 30.
diff --git a/test/fixtures/short-code-alias/meetings/2026-10-10-joronex-call.md b/test/fixtures/short-code-alias/meetings/2026-10-10-joronex-call.md
new file mode 100644
index 0000000000..75995a49dc
--- /dev/null
+++ b/test/fixtures/short-code-alias/meetings/2026-10-10-joronex-call.md
@@ -0,0 +1,12 @@
+---
+title: "Call with JOF"
+type: meeting
+date: 2026-10-10
+---
+# Call with JOF, 2026-10-10
+
+Attendees: Kofi, me.
+
+- Their champion is busy with a reorg.
+- Pricing: the right number is $26 per seat; the $11 in the quote was a typo. Seat count unchanged.
+- Their champion is busy with a reorg.
diff --git a/test/mentions-explain.test.ts b/test/mentions-explain.test.ts
index 5a0882d597..09013558a4 100644
--- a/test/mentions-explain.test.ts
+++ b/test/mentions-explain.test.ts
@@ -18,7 +18,7 @@ beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
afterAll(async () => { await engine.disconnect(); });
beforeEach(async () => { await resetMentionBrain(engine); });
-const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. Ticker: QCO.');
+const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. It goes by QCO.');
describe('extract mentions --explain reason codes', () => {
test('a linking name reports its entry and origin', async () => {
@@ -47,6 +47,14 @@ describe('extract mentions --explain reason codes', () => {
expect((await explainMention(engine, 'QCO')).reason).toBe('below_min_length');
});
+ test('a 3-character code the page declares for itself with a label links (short codes)', async () => {
+ await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Ticker: QCO.');
+ await sweep(engine);
+ const r = await explainMention(engine, 'QCO');
+ expect(r.reason).toBeNull();
+ expect(r.entries).toEqual([{ name: 'QCO', slug: 'crm/123', origin: 'declared', case_sensitive: true }]);
+ });
+
test('generic_token', async () => {
await page(engine, 'people/will', 'person', 'Will', 'x');
expect((await explainMention(engine, 'Will')).reason).toBe('generic_token');
@@ -107,16 +115,16 @@ describe('extract mentions --explain reason codes', () => {
describe('extract mentions --explain <slug>: names, rejections and the sibling decision', () => {
test('lists each derived alias with its origin and line, each rejected candidate with its reason', async () => {
- await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. Ticker: QCO.\nInternal nickname: Copper Fox\nShort name: Quormiro');
+ await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. It goes by QCO.\nInternal nickname: Copper Fox\nShort name: Quormiro');
await sweep(engine);
const r = await explainMention(engine, 'crm/123');
expect(r.aliases).toEqual(expect.arrayContaining([
{ alias: 'Quormiro Capital', origin: 'subject' },
- { alias: 'QUCO', origin: 'declared', line: 'Account code: QUCO. Ticker: QCO.' },
+ { alias: 'QUCO', origin: 'declared', line: 'Account code: QUCO. It goes by QCO.' },
{ alias: 'Copper Fox', origin: 'declared', line: 'Internal nickname: Copper Fox' },
]));
expect(r.rejected).toEqual(expect.arrayContaining([
- { alias: 'QCO', origin: 'declared', reason: 'below_min_length', line: 'Account code: QUCO. Ticker: QCO.' },
+ { alias: 'QCO', origin: 'declared', reason: 'below_min_length', line: 'Account code: QUCO. It goes by QCO.' },
{ alias: 'Quormiro', origin: 'declared', reason: 'ambiguous_first_word', line: 'Short name: Quormiro' },
]));
expect(r.siblings).toEqual({ pages: [], capped: false, verdict: 'none' });
diff --git a/test/mentions-pass.test.ts b/test/mentions-pass.test.ts
index 35657d8e11..1746f5d010 100644
--- a/test/mentions-pass.test.ts
+++ b/test/mentions-pass.test.ts
@@ -108,6 +108,28 @@ describe('the stale sweep links mentions by default', () => {
});
});
+describe('short codes the entity page declares for itself', () => {
+ test('"Also called JOF in my notes" makes JOF a name: mails and note titles that say JOF link to the company, only as written', async () => {
+ await page(engine, 'companies/joffrey-foods', 'company', 'Joffrey Foods', 'Also called JOF in my notes. Procurement: Arjun Example.');
+ await page(engine, 'mail/m1', 'email', 'Re: pilot kickoff', 'From: Kofi Example (JOF)\nCould we push the pilot kickoff?');
+ await page(engine, 'notes/call', 'note', 'Call with JOF', 'The right number is $26 per seat.');
+ await page(engine, 'notes/lower', 'note', 'n2', 'we said jof as a joke');
+ await page(engine, 'notes/other', 'note', 'n3', 'Widget Co, also called JOF by some, is unrelated.');
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'companies/joffrey-foods')).toEqual(['declared:jof (cs)']);
+ expect(await derivedAliases(engine, 'notes/other')).toEqual([]);
+ expect(await mentionLinks(engine)).toEqual(['mail/m1 -> companies/joffrey-foods', 'notes/call -> companies/joffrey-foods', 'notes/other -> companies/joffrey-foods']);
+ });
+
+ test('a stoplisted code on the own page never becomes a name', async () => {
+ await page(engine, 'companies/acme-example', 'company', 'Acme Example', 'Also called IT internally.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Ask IT about the laptop.');
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'companies/acme-example')).toEqual([]);
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+});
+
describe('reconcile scope, off switch and failure', () => {
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.');
diff --git a/test/mentions-policy-aliases.test.ts b/test/mentions-policy-aliases.test.ts
index 3896dda410..319ddc3397 100644
--- a/test/mentions-policy-aliases.test.ts
+++ b/test/mentions-policy-aliases.test.ts
@@ -17,6 +17,7 @@ import {
} from '../src/core/mentions/policy.ts';
import { aliasRejection, captureName, declarationsIn, declaredNames, deriveEntityAliases, titleSubject } from '../src/core/mentions/aliases.ts';
import { aliasDeclarations } from '../src/core/ops/search.ts';
+import { isShortCode, SHORT_CODE_STOPLIST } from '../src/core/mentions/short-codes.ts';
const none = { typeAdds: [], typeRemoves: [] };
const pack = async (name: string) => (await loadResolvedPackByName(name)).manifest;
@@ -90,8 +91,8 @@ describe('derived aliases', () => {
expect(norms).not.toContain('secr');
});
- test('guards: 3-character code, first word of the own name, generic word', () => {
- const r = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'Ticker: QCO. Also known as Quormiro Capital.\nShort name: Quormiro\naka Staff' });
+ test('guards: 3-character code without a short-code cue, first word of the own name, generic word', () => {
+ const r = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'It goes by QCO. Also known as Quormiro Capital.\nShort name: Quormiro\naka Staff' });
expect(r.aliases.map(a => a.alias_text)).toEqual(['Quormiro Capital']);
expect(r.rejected).toEqual(expect.arrayContaining([
expect.objectContaining({ alias: 'QCO', origin: 'declared', reason: 'below_min_length' }),
@@ -213,3 +214,63 @@ describe('declared-name grammar: mid-line labels and quoted "calls it"', () => {
'Status: open. Our partner calls it "Blue Harbor".',
])('no alias: %s', text => { expect(names(text)).toEqual([]); });
});
+
+describe('short codes (2-3 characters) the page declares for itself', () => {
+ const derived = (body: string, title = 'Company: Joffrey Foods') =>
+ deriveEntityAliases({ title, compiled_truth: body }).aliases.filter(a => a.origin === 'declared').map(a => `${a.alias_text}${a.case_sensitive ? ' (cs)' : ''}`);
+
+ test('each short-code cue and label declares the code, case-sensitive', () => {
+ for (const body of [
+ 'Also called JOF in my notes. Procurement: Arjun Example.',
+ 'Joffrey Foods, also known as JOF, buys seats.',
+ 'Joffrey Foods is better known as JOF.',
+ 'Known as JOF on the sales floor.',
+ 'Joffrey Foods (a.k.a. JOF) renewed.',
+ 'Joffrey Foods aka JOF.',
+ 'JF is short for nothing; Joffrey Foods is short for JOF.',
+ 'It is also called JOF.',
+ 'Account code: JOF',
+ '| Ticker | JOF |\n',
+ 'Region: EMEA. Short name: JOF.',
+ ]) expect(derived(body)).toContain('JOF (cs)');
+ });
+
+ test('two characters, digits and mixed case with a capital are codes', () => {
+ expect(derived('Also called J2.')).toContain('J2 (cs)');
+ expect(derived('Also called 3M.')).toContain('3M (cs)');
+ expect(derived('Also called JoF.')).toContain('JoF (cs)');
+ });
+
+ test('a code another entity\'s sentence declares is not this page\'s, even with a short-code cue', () => {
+ expect(derived('Widget Co, also called WCO, is a reseller.')).toEqual([]);
+ expect(derived('Our competitor, also called WCO, cut prices.')).toEqual([]);
+ expect(derived('Widget Co is also known as WCO.')).toEqual([]);
+ // Four characters and up keep the existing rule: any cue on the page declares them.
+ expect(derived('Widget Co, also called WICO, is a reseller.')).toEqual(['WICO (cs)']);
+ });
+
+ test('a short code declared on another page is not an alias of the entity it names', () => {
+ const other = deriveEntityAliases({ title: 'Company: Widget Co', compiled_truth: 'Joffrey Foods, also called JOF, is a customer.' });
+ expect(other.aliases.map(a => a.alias_text)).toEqual(['Widget Co']);
+ expect(other.rejected).toEqual(expect.arrayContaining([expect.objectContaining({ alias: 'JOF', reason: 'below_min_length' })]));
+ });
+
+ test('a short code after a cue outside the short-code list stays out', () => {
+ for (const body of ['It goes by JOF.', 'Formerly JOF.', 'Nicknamed JOF.', 'Referred to as JOF.']) expect(derived(body)).toEqual([]);
+ });
+
+ test('lower-case short words never qualify, even with a cue', () => {
+ for (const body of ['Also called it.', 'Also known as us.', 'Short for and.', 'Account code: abc']) expect(derived(body)).toEqual([]);
+ });
+
+ test('stoplisted capitals and business acronyms never qualify, in any case', () => {
+ for (const code of ['IT', 'US', 'OK', 'AI', 'It', 'Us', 'Ok', 'CEO', 'SSO', 'API', 'SOC', 'HR', 'B2B']) {
+ expect(isShortCode(code)).toBe(false);
+ expect(derived(`Also called ${code}.`)).toEqual([]);
+ expect(derived(`Account code: ${code}`)).toEqual([]);
+ }
+ for (const code of ['JOF', 'J2', '3M', 'JoF']) expect(isShortCode(code)).toBe(true);
+ for (const text of ['J', 'JOFF', 'jo', 'J-F', 'J F']) expect(isShortCode(text)).toBe(false);
+ expect([...SHORT_CODE_STOPLIST].every(c => c === c.toUpperCase())).toBe(true);
+ });
+});
diff --git a/test/mentions-short-code-fixture.test.ts b/test/mentions-short-code-fixture.test.ts
new file mode 100644
index 0000000000..8e0887bc30
--- /dev/null
+++ b/test/mentions-short-code-fixture.test.ts
@@ -0,0 +1,58 @@
+/**
+ * Short-code aliases on the Program Primary Hard root-cause fixture
+ * (gbrain-evals#109, copied to test/fixtures/short-code-alias/, invented names).
+ *
+ * Protects: a company page that says "Also called JOF in my notes" makes `JOF`
+ * one of the company's names, so the call note titled "Call with JOF" and the
+ * two mails "From: Kofi Aziz (JOF)" link to the company (before: the company's
+ * aka list was empty, the call note had no links and each mail linked only to
+ * the person). The code links only as written, as a whole token: "Jof", "jof"
+ * and "JOFX" do not.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { derivedAliases, mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'short-code-alias');
+const PAGES = ['companies/joronex-foods', 'inbox/2026-09-26-aziz-procurement-handoff', 'inbox/2026-10-09-aziz-reschedule', 'meetings/2026-10-10-joronex-call'];
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function loadFixture() {
+ for (const slug of PAGES) {
+ await importFromContent(engine, slug, readFileSync(join(FIXTURE, `${slug}.md`), 'utf8'), { noEmbed: true, forceRechunk: true });
+ }
+ await page(engine, 'people/kofi-aziz', 'person', 'Kofi Aziz', 'DevOps Manager at Joronex Foods.');
+}
+
+describe('short-code alias fixture (gbrain-evals#109)', () => {
+ test('JOF becomes the company\'s name; the call note and both mails link to the company', async () => {
+ await loadFixture();
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'companies/joronex-foods')).toEqual(['declared:jof (cs)']);
+ const links = await mentionLinks(engine);
+ for (const from of ['meetings/2026-10-10-joronex-call', 'inbox/2026-09-26-aziz-procurement-handoff', 'inbox/2026-10-09-aziz-reschedule']) {
+ expect(links).toContain(`${from} -> companies/joronex-foods`);
+ }
+ expect(links).toContain('inbox/2026-09-26-aziz-procurement-handoff -> people/kofi-aziz');
+ expect(links).toContain('inbox/2026-10-09-aziz-reschedule -> people/kofi-aziz');
+ });
+
+ test('the code matches case-sensitively as a whole token: Jof, jof and JOFX do not link', async () => {
+ await loadFixture();
+ await page(engine, 'notes/title-case', 'note', 'Lunch notes', 'Jof brought snacks to the meeting.');
+ await page(engine, 'notes/lower-case', 'note', 'Scratch', 'we typed jof by mistake');
+ await page(engine, 'notes/longer-token', 'note', 'Codes', 'The JOFX build and the xJOF flag are unrelated.');
+ await sweep(engine);
+ const links = await mentionLinks(engine);
+ for (const from of ['notes/title-case', 'notes/lower-case', 'notes/longer-token']) {
+ expect(links.filter(l => l.startsWith(`${from} ->`))).toEqual([]);
+ }
+ });
+});