Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(aliases): store a declared name only when its cue attaches to the page itself
garrytan03e60d71fd40
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f05a928d75..bc73210d42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,7 @@ On a company brain, most records never repeat a customer's full name. They use a| Instructions and `search` | The answering clause keeps separate parts of a question in separate searches but batches lists of names or codes (`entity` with `names`, or one keyword `search` for `"A" OR "B" OR …`) and asks for independent calls in the same turn; `search` says keyword mode takes OR across quoted names. In the development rounds the reader that wrote keyword OR searches solved as many cells in a third of the calls of one that searched one name at a time. || `entity` names | `names` (up to 50 names, codes or aliases) resolves a whole list in one call, one compact row per name with the page, its names, its opening lines (`lead`) and its identity siblings. Opus resolved account codes and nicknames from handoff mails one search at a time and ran out of turns; on the development world's account pages one call resolved the 43 names one such run looked up separately, in 1.4 s. || `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."), 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. |+| 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. A cue counts as one of the page's names only when it attaches to the page itself ("Widget Co (formerly Gearbox Labs)", "The company is also known as ..."), so another company's old name, a place or a product nickname in the page's prose is not stored: on one real brain that took stored aliases from 47 correct of 72 to 25 of 25. || 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. |diff --git a/docs/designs/ALIAS_CONVENTIONS.md b/docs/designs/ALIAS_CONVENTIONS.mdindex c8ae7f0cb8..b47747fa42 100644--- a/docs/designs/ALIAS_CONVENTIONS.md+++ b/docs/designs/ALIAS_CONVENTIONS.md@@ -52,6 +52,31 @@ A capture is rejected when:A single-token alias matches only as written (`case_sensitive`); a multi-wordalias matches case-insensitively, like a multi-word title.+### Anchored declarations (stored aliases and the card)++A page's prose names many other things with the same cues: another company's+old name (`Dana Example (formerly Globex) joined`), a place (`a street known as+Market Lane`), a product nickname, a concept, a tagline. So the names a page+stores as its own aliases, and the identity lines its card shows, need a+declaration anchored to the page itself:++- a prose cue counts only when the clause before it names nothing but the page:+ its own name or title subject (after corporate suffixes, `& Co.`, a trailing+ `and`/`or` and any parenthetical), a name another cue declared earlier in the+ same sentence (`doing business as Acme Snacks (formerly Old Acme)`), a self+ pronoun (`it`, `this company`) or `the company` / `the account` / ..., or, on+ a person page, the first name alone or the full name with a middle name;+- a cue with nothing before it counts only at the start of a line or in label+ form (`Also known as: X`), not mid-paragraph (`Nicknamed the Hammer, it set a+ record` declares nothing);+- the quoted `calls it "X"` cue counts only when its sentence names the page;+- a quoted parenthetical without a cue (`Acme Example ("Snacks for everyone")`)+ is not a stored name.++Label and value forms are unchanged. Search's per-result declaration scan+(`aliasDeclarations`) keeps reading every declaration as written above, because+it reports evidence for one query and stores nothing.+## Prose cuesA cue is followed by an optional `:`, `,`, `(` or `-`, an optional article@@ -161,6 +186,16 @@ as written, as a whole token: "Call with JOF" links, "jof" does not.## Changelog+- 2026-10-11: stored aliases and card identity lines need an anchored+ declaration (above). Origin: the alias precision gate of the Cat 40 Hard fix+ wave. On one real brain the unanchored rule stored 47 correct of 72 derived+ aliases, nearly every wrong one a cue attached to another name in the page's+ prose; anchored, 25 of 25. On held-out English Wikipedia prose, 50 of 198+ before and 20 of 25 after. The Cat 40 Hard confirmation, calibration and v1+ worlds derive exactly the same aliases, search-time declarations and card+ lines as before. The label-form exception (`Also known as: X` mid-line) was+ found on the confirmation world's account sheets.+- 2026-10-08: short codes (2-3 characters) the page declares for itself with analias label or an `also called` / `a.k.a.` / `known as` / `short for` cue, witha stoplist of common capitals and acronyms. Origin: the Program Primary Harddiff --git a/src/core/mentions/aliases.ts b/src/core/mentions/aliases.tsindex a0acd5992e..980793b78d 100644--- a/src/core/mentions/aliases.ts+++ b/src/core/mentions/aliases.ts@@ -21,6 +21,10 @@* ...") declares another entity's name and is skipped. Stored with* `origin='declared'`. A single-token declaration matches only as written* (`case_sensitive`), so "aka Mark" never links lowercase "mark".+ * - Anchoring: stored aliases and the card's identity lines read declarations+ * with `anchored: true`, so a cue counts only when it attaches to the page+ * itself (docs/designs/ALIAS_CONVENTIONS.md, "Anchored declarations");+ * search's per-result scan reads every declaration.* - Escape hatches: `mentions.alias_deny` and frontmatter `alias_deny:` drop a* derived name; `mentions.multiword_aliases=false` keeps one-token captures.*@@ -48,6 +52,8 @@ const QUOTED_CUE_RE = /(?<![A-Za-z])(?:calls?|called|call) it\s+/gi;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;+/** Anchored mode also accepts "the company", "the account", ... as the page itself. */+const SELF_NOUN_RE = /^the (?:company|account|customer|client|project|team|firm|startup|fund|organization|business)$/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;@@ -69,6 +75,13 @@ export interface DeclarationOpts {multiword?: boolean;/** Other names of the page (frontmatter aliases) that may introduce a parenthetical defined term. */ownNames?: string[];+ /**+ * Keep only declarations anchored to the page itself: a prose cue counts only when the clause before it+ * names nothing but the page (its own name, its first name, a self pronoun or "the company"), a quoted+ * "calls it" only when the sentence names the page, and a quoted parenthetical without a cue is not a+ * name. Stored aliases and the card's identity lines use it; search's per-result scan does not.+ */+ anchored?: boolean;}/**@@ -156,6 +169,17 @@ export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declar};const ownNames = (opts.ownNames ?? []).filter(Boolean);const ownLower = ownNames.map(n => n.toLowerCase());+ const anchored = opts.anchored === true;+ /** Whether `text` mentions one of the page's own names as a whole word. */+ const mentionsOwnName = (text: string): boolean => {+ const lower = text.toLowerCase();+ return ownLower.some(n => {+ for (let at = lower.indexOf(n); at >= 0; at = lower.indexOf(n, at + 1)) {+ if (!/[\p{L}\p{N}]/u.test(lower.charAt(at - 1)) && !/[\p{L}\p{N}]/u.test(lower.charAt(at + n.length))) return true;+ }+ return false;+ });+ };/** Whether `before` ends with one of the page's own names, after any corporate suffixes and a trailing comma. */const endsWithOwnName = (before: string): boolean => {const endsWithName = (t: string) => {@@ -203,16 +227,51 @@ export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declarconst subject = sentenceBefore(at).trim().replace(/[,(\-\u2013\u2014]+$/, '').trim().replace(/\s+(?:is|was)$/i, '').trim();return subject === '' || SELF_SUBJECT_RE.test(subject) || endsWithOwnName(subject);};+ /** Start of the sentence holding `at`, ignoring '. ' and '; ' inside parentheses. */+ const sentenceStart = (at: number) => {+ let start = 0, depth = 0;+ for (let k = 0; k < at; k++) {+ const c = plain[k];+ if (c === '(') depth++;+ else if (c === ')') depth = Math.max(0, depth - 1);+ else if (depth === 0 && (c === '.' || c === ';') && plain[k + 1] === ' ') start = k + 2;+ }+ return start;+ };+ const anchoredToSelf = (at: number, cueLength: number) => {+ const start = sentenceStart(at);+ const labelForm = /^\s*:/.test(plain.slice(at + cueLength));+ const chained = chain.filter(c => c.start === start).map(c => c.name);+ ownLower.push(...chained);+ try { return anchoredSubject(plain.slice(start, at), start === 0 || labelForm); } finally { ownLower.splice(ownLower.length - chained.length, chained.length); }+ };+ const anchoredSubject = (raw: string, lineFirst: boolean) => {+ let subject = raw;+ for (let k = 0; k < 3 && /\([^()]*\)/.test(subject); k++) subject = subject.replace(/\s*\([^()]*\)/g, '');+ subject = subject.trim().replace(/[,;(\-\u2013\u2014]+$/, '').trim().replace(/\s+(?:and|or)$/i, '').replace(/\s+(?:is|was)$/i, '')+ .replace(/\s*&\s*Co\.?$/i, '').trim();+ if (subject === '') return lineFirst;+ if (SELF_SUBJECT_RE.test(subject) || SELF_NOUN_RE.test(subject) || endsWithOwnName(subject)) return true;+ const words = subject.toLowerCase().split(/\s+/);+ return ownLower.some(n => {+ const own = n.split(/\s+/);+ return own.length > 1 && (words.length === 1 ? words[0] === own[0] : words[0] === own[0] && words.at(-1) === own.at(-1) && words.length <= own.length + 2);+ });+ };+ const chain: Array<{ name: string; start: number }> = [];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, SHORT_CODE_CUE_RE.test(m[0]) && namesOnlySelf(m.index!));+ if (RELATIONAL_NOUN_RE.test(sentenceBefore(m.index!)) || (anchored && !anchoredToSelf(m.index!, m[0].length))) continue;+ const name = captureName(plain.slice(m.index! + m[0].length), { multiword });+ push(name, i, SHORT_CODE_CUE_RE.test(m[0]) && namesOnlySelf(m.index!));+ if (anchored && name) chain.push({ name: name.toLowerCase(), start: sentenceStart(m.index!) });}for (const m of plain.matchAll(QUOTED_CUE_RE)) {const rest = plain.slice(m.index! + m[0].length);if (!QUOTES[rest[0] ?? ''] || RELATIONAL_NOUN_RE.test(sentenceBefore(m.index!))) continue;+ if (anchored && !mentionsOwnName(sentenceBefore(m.index!))) continue;push(captureName(rest, { multiword }), i);}- if (ownLower.length) {+ if (ownLower.length && !anchored) {for (const m of plain.matchAll(PAREN_TERM_RE)) {if (!endsWithOwnName(plain.slice(0, m.index))) continue;push(captureName(`"${m[1]}"`, { multiword }), i);@@ -323,7 +382,7 @@ export function deriveEntityAliases(const textLines = text.split('\n');const ownNames = frontmatterList(page.frontmatter?.aliases);const own = name.toLowerCase();- for (const d of declarationsIn(text, { multiword: opts.multiword, ownNames: [name, ...ownNames] })) {+ for (const d of declarationsIn(text, { multiword: opts.multiword, ownNames: [name, ...ownNames], anchored: true })) {if (d.alias.toLowerCase() === own) continue;push(d.alias, 'declared', tokenizeTitle(d.alias).length === 1, textLines[d.line]?.trim(), d.selfCode === true);}diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.tsindex 037915da4c..cec5ade431 100644--- a/src/core/verbs/entity-card-identity.ts+++ b/src/core/verbs/entity-card-identity.ts@@ -69,7 +69,7 @@ function labelValue(line: string, next: string | undefined): { label: string; vaexport function excerptLines(body: string, title: string, budget = EXCERPT_PAGE_CHARS): string[] {const subject = titleName(title);const lines = body.split('\n');- const declared = new Set(declarationsIn(body, { ownNames: [subject] }).map(d => d.line));+ const declared = new Set(declarationsIn(body, { ownNames: [subject], anchored: true }).map(d => d.line));const tiers: Array<Array<{ i: number; text: string }>> = [[], [], [], []];for (let i = 0; i < lines.length; i++) {const text = lines[i]!.trim();diff --git a/test/mentions-policy-aliases.test.ts b/test/mentions-policy-aliases.test.tsindex 319ddc3397..03dc93b845 100644--- a/test/mentions-policy-aliases.test.ts+++ b/test/mentions-policy-aliases.test.ts@@ -245,14 +245,17 @@ describe('short codes (2-3 characters) the page declares for itself', () => {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)']);+ // Four characters and up need the same anchor: a cue in another entity's sentence declares nothing for this page.+ expect(derived('Widget Co, also called WICO, is a reseller.')).toEqual([]);+ expect(derived('Joffrey Foods, also called JOFO, buys seats.')).toEqual(['JOFO (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' })]));+ expect(other.rejected.map(r => r.alias)).not.toContain('JOF');+ const own = deriveEntityAliases({ title: 'Company: Joffrey Foods', compiled_truth: 'Joffrey Foods, also called JOF, is a customer.' });+ expect(own.aliases.map(a => a.alias_text)).toEqual(['Joffrey Foods', 'JOF']);});test('a short code after a cue outside the short-code list stays out', () => {@@ -274,3 +277,66 @@ describe('short codes (2-3 characters) the page declares for itself', () => {expect([...SHORT_CODE_STOPLIST].every(c => c === c.toUpperCase())).toBe(true);});});++describe('stored aliases need a declaration anchored to the page itself', () => {+ const stored = (body: string, title = 'Acme Example') =>+ deriveEntityAliases({ title, compiled_truth: body }).aliases.filter(a => a.origin === 'declared').map(a => a.alias_text);++ test.each([+ ['a person\'s former employer', 'Dana Example (formerly Globex) joined as CFO.'],+ ['a hire\'s former employer', 'We hired Lee Example from Initech, formerly Globex Corp.'],+ ['an investor\'s old name', 'Fund A Example (formerly Old Fund Name) led the round.'],+ ['another startup\'s old name', 'Rival Example (formerly Old Rival Name, applied before) is in the batch.'],+ ['an agency\'s old name', 'Our agency, Brand Shop (fka Old Agency), sent the deck.'],+ ['a competitor\'s other name', 'Competitor One, aka Competitor Two for the U.S., raised prices.'],+ ['a place', 'The office is on a street known as Market Lane.'],+ ['a band', 'The founder plays in a band known as Night Owls.'],+ ['a protocol', 'Sync moved to a protocol often called "Wirefast".'],+ ['a concept', 'Access runs on what is known as Zero Trust Access.'],+ ['an acronym gloss', 'They adopted SSO (aka SAML - Security Assertion Markup Language).'],+ ['quoted jargon', 'The plan relies on rapid scaling (AKA "Hypergrowth").'],+ ['a founder\'s nickname', 'Dana Example aka Dee founded the company.'],+ ['a product nickname', 'Our robot nicknamed the Rover ships in May.'],+ ['a tagline after the name', 'Acme Example ("Snacks for everyone") makes chips.'],+ ['"calls it" about something else', 'The team built a robot and calls it "Rover".'],+ ['a sentence-initial cue mid-paragraph', 'The car was fast. Nicknamed the Hammer, it set a record.'],+ ])('%s is not an alias of the page', (_label, body) => {+ expect(stored(body)).toEqual([]);+ });++ test.each([+ ['heading form', '# Acme Example (formerly Old Acme)', ['Old Acme']],+ ['fka after the name', 'Acme Example (fka Old Acme) is a supplier.', ['Old Acme']],+ ['aka after the name', 'Acme Example (aka Acme Snacks) is a supplier.', ['Acme Snacks']],+ ['DBA after the name', 'Acme Example (DBA Acme Snacks) is a supplier.', ['Acme Snacks']],+ ['appositive after the name', 'Acme Example, formerly Old Acme, is a supplier.', ['Old Acme']],+ ['previously known as', 'Acme Example (previously known as Old Acme) renewed.', ['Old Acme']],+ ['the name as subject', 'Acme Example was formerly known as Old Acme.', ['Old Acme']],+ ['"the company" as subject', 'The company is also known as Acme Snacks.', ['Acme Snacks']],+ ['a sentence-initial cue', 'Also known as Acme Snacks.', ['Acme Snacks']],+ ['a label line', 'Internal nickname: Copper Fox', ['Copper Fox']],+ ['"calls it" naming the page', 'The Acme Example team calls it "Copper Fox".', ['Copper Fox']],+ ['a second cue chained to the first', 'Acme Example, LLC (often referred to as Acme Snacks and formerly known as Old Acme) is a supplier.', ['Acme Snacks', 'Old Acme']],+ ['a cue after a name it just declared', 'Acme Example Holdings LLC, doing business as Acme Snacks (formerly Old Acme), is a supplier.', ['Acme Snacks', 'Old Acme']],+ ['a parenthetical between the name and the cue', 'Acme Example Limited (AEL), formerly Old Acme, is a supplier.', ['Old Acme']],+ ['"& Co." after the name', 'Acme Example & Co., also known as Acme Snacks, is a supplier.', ['Acme Snacks']],+ ['a cue label mid-line', 'Account: Acme Example. Also known as: Acme Snacks.', ['Acme Snacks']],+ ])('%s stays', (_label, body, want) => {+ expect(stored(body)).toEqual(want);+ });++ test('a name declared in one sentence does not anchor a cue in the next', () => {+ expect(stored('Acme Example (formerly Old Acme) is a supplier. Old Acme Labs, formerly Globex, is a customer.')).toEqual(['Old Acme']);+ });++ test('a person page: full name with a middle name, or the first name, anchors the cue', () => {+ const person = (body: string) => deriveEntityAliases({ title: 'Dana Example', compiled_truth: body }).aliases.map(a => a.alias_text);+ expect(person('Dana Lee Example (born 1970), also known as Dee Example, is an engineer.')).toEqual(['Dee Example']);+ expect(person('Dana, aka Didi, runs sales.')).toEqual(['Didi']);+ expect(person('Her mother, Ruth Example (née Other), taught school.')).toEqual([]);+ });++ test('search\'s per-result scan keeps reading unanchored declarations', () => {+ expect(declaredNames('As of May, Old Co (account code OLDC) operates as New Co, account code NEWC.', 'Old Co')).toContain('NEWC');+ });+});