Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
F5 owner phrases: post-transfer grammar fixes, known_as card field, ranking exclusion, rule tests
garrytancd05bd989df6
diff --git a/src/core/mentions/owner-phrase/known-as.ts b/src/core/mentions/owner-phrase/known-as.tsnew file mode 100644index 0000000000..049ec1452e--- /dev/null+++ b/src/core/mentions/owner-phrase/known-as.ts@@ -0,0 +1,50 @@+/**+ * The entity card's `known_as` rows: each owner of an account with the+ * validity window of its owner phrase ("<owner>'s <descriptor> account"),+ * read from `owner_phrase_windows`. Bounded at KNOWN_AS_MAX rows with the+ * total. Untrusted readers never see a window whose evidence includes a+ * private page. Owner phrases are never aliases: they stay out of `aka`,+ * `page_aliases` and search alias fan-out. Fail-soft: a read error returns+ * nothing.+ */++import type { BrainEngine } from '../../engine.ts';++export const KNOWN_AS_MAX = 10;++export interface KnownAsRow {+ owner: string;+ /** The words an owner phrase may use for this account ("freight" in "Alice's freight account"). */+ descriptors: string[];+ /** Inclusive first day, or null when the start is unknown and unbounded. */+ from: string | null;+ /** Inclusive last day, or null while the stint is open. */+ to: string | null;+ start_known: boolean;+ evidence: Array<{ slug: string; line: number; kind: string }>;+}++export interface KnownAs { rows: KnownAsRow[]; total: number }++export async function readKnownAs(engine: BrainEngine, sourceId: string, slug: string, opts: { excludePrivate: boolean }): Promise<{ known_as?: KnownAs }> {+ try {+ const rows = await engine.executeRaw<{ owner_name: string; descriptors: string[]; f: string | null; t: string | null; start_known: boolean; evidence: unknown; total: number }>(+ `SELECT owner_name, descriptors, valid_from::text AS f, valid_to::text AS t, start_known, evidence, count(*) OVER ()::int AS total+ FROM owner_phrase_windows+ WHERE source_id = $1 AND (group_key = $2 OR $2 = ANY(account_slugs))${opts.excludePrivate ? ' AND private_page_id IS NULL' : ''}+ ORDER BY valid_from DESC NULLS LAST, owner_name LIMIT $3`, [sourceId, slug, KNOWN_AS_MAX]);+ if (!rows.length) return {};+ return {+ known_as: {+ total: Number(rows[0]!.total),+ rows: rows.map(r => {+ const evidence = (typeof r.evidence === 'string' ? JSON.parse(r.evidence) : r.evidence) as Array<{ slug: string; line: number; kind: string }>;+ return { owner: r.owner_name, descriptors: r.descriptors ?? [], from: r.f, to: r.t, start_known: r.start_known,+ evidence: evidence.map(e => ({ slug: e.slug, line: e.line, kind: e.kind })) };+ }),+ },+ };+ } catch {+ return {};+ }+}diff --git a/src/core/mentions/owner-phrase/pass.ts b/src/core/mentions/owner-phrase/pass.tsindex e0a4fb309f..f71cb3a702 100644--- a/src/core/mentions/owner-phrase/pass.ts+++ b/src/core/mentions/owner-phrase/pass.ts@@ -34,6 +34,9 @@ import { buildNameIndex, findNames, parseStatements, type NameEntry, type Statemimport { accountDescriptors, buildWindows, resolvePhrase, type OwnerWindow } from './windows.ts';export const OWNER_PHRASE_KEY = 'mentions.owner_phrases';+/** Group key prefix of an account named in a statement that has no page (statements.ts); never stored or linked. */+const PAGELESS = 'pseudo:';+const isPageless = (slug: string) => slug.startsWith(PAGELESS);const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);const SCAN_BATCH = 500;@@ -221,7 +224,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owne}));}const windows = buildWindows(statements, groupOf);- const descriptorsOf = (g: string) => descriptors.get(g) ?? new Set<string>();+ const descriptorsOf = (g: string) => descriptors.get(g) ?? (isPageless(g) ? accountDescriptors([g.slice(PAGELESS.length)], []) : new Set<string>());const links: OwnerPhraseModel['links'] = [];const counters = { unresolved: 0, ambiguous: 0 };@@ -233,6 +236,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owneconst named = findNames(hit.owner, accountIndex);if (named.length && named[0]!.start === 0 && named[0]!.end === hit.owner.length) continue;const r = resolvePhrase(hit, s.page_date, s.readings ?? [], windows, descriptorsOf);+ if (r.linked && r.accounts.every(isPageless)) { counters.unresolved++; continue; }if (!r.linked) {if (r.reason === 'ambiguous' || r.reason === 'readings_disagree') counters.ambiguous++;else counters.unresolved++;@@ -246,7 +250,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owne}}}- return { windows, descriptors, links, counters };+ return { windows: windows.filter(w => !isPageless(w.group)), descriptors, links, counters };}function windowsHash(windows: OwnerWindow[], privateIds: Set<number>): string {diff --git a/src/core/mentions/owner-phrase/ranking.ts b/src/core/mentions/owner-phrase/ranking.tsnew file mode 100644index 0000000000..79e2b377d2--- /dev/null+++ b/src/core/mentions/owner-phrase/ranking.ts@@ -0,0 +1,10 @@+/**+ * Owner-phrase links never take part in ranking. Readers that exclude+ * `link_source='mentions'` already skip them; the ranking readers that count+ * every link (adjacency boosts, entity anchoring, generated-page demotion)+ * add this predicate, so a brain's final scores are the same with+ * `mentions.owner_phrases` on or off. Plain mention behavior is unchanged.+ */+export function rankingLinkSql(linkAlias: string): string {+ return `${linkAlias}.link_kind IS DISTINCT FROM 'owner_phrase'`;+}diff --git a/src/core/mentions/owner-phrase/scan.ts b/src/core/mentions/owner-phrase/scan.tsindex 210a882b41..4bb28cdc23 100644--- a/src/core/mentions/owner-phrase/scan.ts+++ b/src/core/mentions/owner-phrase/scan.ts@@ -47,8 +47,8 @@ export interface ScanInput {effective_date_source: string | null;}-const CUE_RE = /\b(?:owns?|owned|owner|owners|ownership|runs?|ran|running|handles?|handled|handling|manages?|managed|managing|manager|covers?|covered|covering|coverage|leads?|led|leading|takes? over|took over|taking over|taken over|hands?|handed|handing|hand-?off|handover|pass(?:es|ed)?|passing|transfer(?:s|red|ring)?|(?:re)?assign(?:s|ed|ing)?|moves?|moved|moving|transition(?:s|ed|ing)?|inherit(?:s|ed)?|picks? up|picked up|assumes?|assumed|replac(?:es|ed|ing)|roll(?:s|ed|ing)? off|step(?:s|ped|ping)? (?:away|back|down|off)|no longer|last day|joins?|joined|joining|since|until|through|correction|correcting|clarification|actually|rather than|instead of|misspoke|mistake|wrong|incorrect|ae|csm|rep|point person|goes to|went to|book)\b/i;-const OWNER_COLUMN_RE = /\b(?:owner|lead|ae|csm|manager|rep|am)\b/i;+const CUE_RE = /\b(?:owns?|owned|owner|owners|ownership|runs?|ran|running|handles?|handled|handling|manages?|managed|managing|manager|covers?|covered|covering|coverage|leads?|led|leading|takes? over|took over|taking over|taken over|hands?|handed|handing|hand-?off|handover|pass(?:es|ed)?|passing|transfer(?:s|red|ring)?|(?:re)?assign(?:s|ed|ing)?|moves?|moved|moving|transition(?:s|ed|ing)?|inherit(?:s|ed|ing)?|pick(?:s|ed|ing)? up|assum(?:es?|ed|ing)|replac(?:es|ed|ing)|roll(?:s|ed|ing)? off|step(?:s|ped|ping)? (?:away|back|down|off)|no longer|last day|joins?|joined|joining|start(?:s|ed|ing)? (?:on|with|covering)|beg[ia]ns? (?:on|with|covering)|began (?:on|with|covering)|will (?:own|run|handle|cover|lead|manage)|incoming|outgoing|since|until|through|correction|correcting|clarification|actually|rather than|instead of|misspoke|mistake|wrong|incorrect|ae|csm|rep|point person|goes to|went to|book)\b/i;+const OWNER_COLUMN_RE = /\b(?:owner|lead|ae|csm|manager|rep|am|incoming|outgoing)\b/i;const AGENT_TYPE_RE = /(?:^|[-_\s/])agent(?:$|[-_\s/])/i;/** Personal and benefit accounts: a sentence about them holds no owner phrase (contract line 8). */@@ -70,7 +70,8 @@ export const NAME_STOPWORDS: ReadonlySet<string> = new Set(`a an the this that tmr ms mrs dr csm ae am vp ceo cto cfo coo sales ops support customer success q1 q2 q3 q4 effective monday tuesday wednesday thursdayfriday saturday sunday january february march april may june july august september october november december jan feb mar apr jun jul augsep sept oct nov dec yes no ok okay good great sure all any each every some none who what when where why how if while because- following followup follow welcome hope best regards cheers new old previous current former incoming outgoing primary`.split(/\s+/).filter(Boolean));+ following followup follow welcome hope best regards cheers new old previous current former incoming outgoing primary+ is was are were be been being do does did can will would has have had shall must am`.split(/\s+/).filter(Boolean));/** Leading and trailing stop words of a capitalized run removed; empty when nothing is left. */export function trimNameRun(run: string): string {diff --git a/src/core/mentions/owner-phrase/statements.ts b/src/core/mentions/owner-phrase/statements.tsindex a67473d4ea..44db0a8796 100644--- a/src/core/mentions/owner-phrase/statements.ts+++ b/src/core/mentions/owner-phrase/statements.ts@@ -10,7 +10,7 @@*/import { tokenizeForScan } from '../../by-mention.ts';-import { RELATIVE_DATE_RE, addDays, findDates, type FoundDate } from './dates.ts';+import { RELATIVE_DATE_RE, findDates, type FoundDate } from './dates.ts';import { NAME_STOPWORDS, trimNameRun, type CueLine } from './scan.ts';export type StatementKind = 'takeover' | 'join' | 'ongoing' | 'end' | 'stint' | 'correction';@@ -158,13 +158,17 @@ const D = (g: string) => `⟦D(?<${g}>\\d+)⟧`;const ACC_CORE = `(?:the |this |our )?⟦A(?<acc>\\d+)⟧(?:'s)?(?: (?:account|relationship|book|client|customer|portfolio))?`;const ROLE = '(?:account )?(?:owner|lead|manager|executive|ae|csm|rep|representative|point person|point|primary contact|am)';const FROM = `(?: from ${P('from')})?`;+const ADV = '(?:(?:actually|officially|formally|also|already|effectively) )?';interface Pattern { kind: StatementKind; re: RegExp; reSelf: RegExp }function pattern(kind: StatementKind, template: string): Pattern {- const build = (acc: string) => new RegExp(template.replaceAll('{ACC}', acc).replaceAll('{O}', P('o')).replaceAll('{F}', P('from'))+ const build = (acc: string) => new RegExp(template.replaceAll('{ACC}', acc).replaceAll('{O} ', `${P('o')} ${ADV}`).replaceAll('{O}', P('o')).replaceAll('{F}', P('from')).replaceAll('{FROM}', FROM).replaceAll('{ROLE}', ROLE).replaceAll('{D1}', D('d1')).replaceAll('{D2}', D('d2')));- return { kind, re: build(` ${ACC_CORE}`), reSelf: build(`(?: ${ACC_CORE})?`) };+ // Sentences are matched with a leading space, so a pattern may open with the account. An account-first+ // pattern never takes the page itself implicitly: its subject must be written.+ const re = build(` ${ACC_CORE}`);+ return { kind, re, reSelf: template.startsWith('{ACC}') ? re : build(`(?: ${ACC_CORE})?`) };}const PATTERNS: Pattern[] = [@@ -181,6 +185,8 @@ const PATTERNS: Pattern[] = [pattern('takeover', `{ACC} (?:is now|now is|becomes|became|will become|will now be) ${P('o')}'s(?: account)?`),pattern('takeover', `{ACC} (?:is now|will now be|will be) (?:owned|run|handled|managed|covered|led) by {O}`),pattern('takeover', `{O} now (?:owns|runs|handles|manages|covers|leads){ACC}`),+ pattern('takeover', `{O} (?:will|is going to|is set to) (?:now )?(?:own|run|handle|cover|lead|manage)(?: the)?{ACC}`),+ pattern('join', `{O} (?:started|starts|is starting|will start|began|begins|will begin)(?: on| with| covering| working on)?(?: the)?{ACC}`),pattern('join', `{O} (?:joins|joined|is joining|will join)(?: the)?{ACC}`),pattern('join', `{O} (?:co-owns|will co-own|is co-owning|also covers|will also cover|is also covering)(?: the)?{ACC}`),pattern('end', `{O} (?:rolls|roll|rolled|is rolling|will roll|rolling) off{ACC}`),@@ -189,7 +195,7 @@ const PATTERNS: Pattern[] = [pattern('end', `{O}(?:'s)? last day (?:on|with|for|covering|running|handling){ACC} (?:is|was|will be) {D2}`),pattern('end', `{O} (?:leaves|left|is leaving|will leave){ACC}`),pattern('end', `{O} (?:hands|handed|is handing|will hand|has handed) off{ACC}(?! (?:off |over )?to )`),- pattern('ongoing', `{O} (?:owns|runs|handles|manages|covers|leads|is running|is handling|is managing|is covering|is leading|is on|still owns|still runs|still handles|still covers|has)(?: the)?{ACC}`),+ pattern('ongoing', `{O} (?:owns|runs|handles|manages|covers|leads|is running|is handling|is managing|is covering|is leading|is on|still owns|still runs|still handles|still covers|has run|has owned|has handled|has covered|has led|has managed|has had|has)(?: the)?{ACC}`),pattern('ongoing', `{O} is (?:the |our )?{ROLE} (?:for|on|of|over)${' '}${ACC_CORE}`),pattern('ongoing', `{ACC} is (?:owned|run|handled|managed|covered|led|looked after) by {O}`),pattern('ongoing', `{ACC} is ${P('o')}'s(?: account)?`),@@ -197,6 +203,7 @@ const PATTERNS: Pattern[] = [];const LABEL_RE = new RegExp(`^(?:(?:the )?⟦A(?<acc>\\d+)⟧ )?(?<prev>previous |former |prior |past )?(?:account |primary |current )?(?:owner|lead|manager|ae|csm|rep|am|account owner|account lead|account manager)s?(?: \\(.*?\\))? ?[:=–-] ?${P('o')}`);+const HANDOFF_LABEL_RE = new RegExp(`\\b(?:outgoing|previous|old|former)(?: owner)?:? ${P('from')},? (?:and |→ |-> )?(?:incoming|new)(?: owner)?:? ${P('o')}`);const NEGATION_RE = /\b(?:not|never)\b|n't\b/;const HYPOTHETICAL_RE = /\b(?:might|may|could|would|should|if|whether|considering|consider|proposal|proposed|propose|proposing|maybe|perhaps|tentatively|possibly|potentially|thinking about|plan to|planning to|plans to|hope to|hoping to|want to|wants to|suggest|suggested|suggesting|recommend|recommended|option)\b/;const CORRECTION_RE = /\b(?:correction|correcting|to correct|clarification|to clarify|misspoke|was wrong|were wrong|was incorrect|is incorrect|was a mistake|in error|by mistake|mistakenly|erroneously|actually|retract(?:ing|ed)?|disregard)\b|(?:^|,|—|–|\(| -| and) ?not (?:to )?⟦P|rather than ⟦P|instead of ⟦P/;@@ -207,12 +214,16 @@ function splitSentences(line: string): string[] {return line.split(/(?<=[.!?])\s+(?=[A-Z"'(\[⟦]|$)/).map(s => s.trim()).filter(Boolean);}-function chooseDate(norm: Normalized, matchStart: number, exclude: Set<number>): FoundDate | null {- const all = norm.dates.map((d, i) => ({ d, i, pos: norm.datePos[i] ?? -1 })).filter(x => !exclude.has(x.i) && x.pos >= 0);+const START_CUE_RE = /(?:since|starting|beginning|effective|effective as of|as of|from)(?: on)? $/;++function chooseDate(norm: Normalized, matchStart: number): { date: FoundDate; start: boolean } | null {+ const all = norm.dates.map((d, i) => ({ d, i, pos: norm.datePos[i] ?? -1 })).filter(x => x.pos >= 0);if (!all.length) return null;- const cue = all.filter(x => CUE_LED_RE.test(norm.n.slice(Math.max(0, x.pos - 24), x.pos)));+ const before = (x: { pos: number }) => norm.n.slice(Math.max(0, x.pos - 24), x.pos);+ const cue = all.filter(x => CUE_LED_RE.test(before(x)));const pick = (xs: typeof all) => xs.find(x => x.pos >= matchStart) ?? xs[xs.length - 1];- return (cue.length ? pick(cue) : all.find(x => x.pos >= matchStart) ?? all[all.length - 1])!.d;+ const chosen = (cue.length ? pick(cue) : all.find(x => x.pos >= matchStart) ?? all[all.length - 1])!;+ return { date: chosen.d, start: START_CUE_RE.test(before(chosen)) };}function tableRows(lines: CueLine[]): Array<{ line: number; cells: Record<string, string>; pairs: string[] }> {@@ -246,9 +257,24 @@ export function parseStatements(cues: CueLine[], ctx: ParseContext): Statement[]const sentences: Array<{ line: number; text: string; label: boolean }> = [];for (const row of tableRows(cues)) {if (row.pairs.length) { for (const p of row.pairs) sentences.push({ line: row.line, text: p, label: true }); continue; }+ const account = col(row.cells, /^(?:account|client|customer|company|account name|name)$/);const owner = col(row.cells, /\b(?:owner|lead|ae|csm|manager|rep|am)\b/);+ const incoming = col(row.cells, /^(?:incoming|incoming owner|new owner)$/);+ if (!owner && incoming) {+ const outgoing = col(row.cells, /^(?:outgoing|outgoing owner|previous owner|old owner)$/);+ const when = col(row.cells, /^(?:effective|effective date|date|as of|start|start date)$/);+ const acctSlug = account ? findNames(account, ctx.accounts)[0]?.entry.slug : ctx.selfAccount;+ const person = (cell: string | undefined) => (cell && !/^\(.*\)$/.test(cell)+ ? findNames(cell, ctx.persons)[0]?.entry.title ?? cell.match(RUN_RE)?.map(trimNameRun).find(Boolean) : undefined);+ const to = person(incoming);+ const date = when ? findDates(when, ctx.page.date)[0]?.iso ?? null : null;+ if (!acctSlug || !to) continue;+ const from = person(outgoing);+ out.push({ ...base, kind: 'takeover', owner: to, ...(from ? { from } : {}), account: acctSlug, date: date ?? ctx.page.date, stated: !!date,+ line: row.line, text: Object.values(row.cells).join(' | ') });+ continue;+ }if (!owner) continue;- const account = col(row.cells, /^(?:account|client|customer|company|account name|name)$/);const startCell = col(row.cells, /^(?:start|start date|from|since|began|effective|effective date|owner since)$/);const endCell = col(row.cells, /^(?:end|end date|until|to|through|ended)$/);const acctSlug = account ? findNames(account, ctx.accounts)[0]?.entry.slug : ctx.selfAccount;@@ -263,34 +289,83 @@ export function parseStatements(cues: CueLine[], ctx: ParseContext): Statement[]else if (end) out.push({ ...base, kind: 'stint', owner: person, account: acctSlug, date: end, start: null, end, stated: true, line: row.line, text });else if (ctx.page.date) out.push({ ...base, kind: 'ongoing', owner: person, account: acctSlug, date: ctx.page.date, stated: false, line: row.line, text });}+ const pageAccounts = new Set<string>();for (const l of cues) {if (l.text.trimStart().startsWith('|')) continue;- for (const s of splitSentences(cleanLine(l.text))) sentences.push({ line: l.line, text: s, label: false });+ for (const s of splitSentences(speakerFirstPerson(cleanLine(l.text)))) sentences.push({ line: l.line, text: s, label: false });+ for (const m of findNames(l.text, ctx.accounts)) pageAccounts.add(m.entry.slug);+ }+ const context = ctx.selfAccount ?? (pageAccounts.size === 1 ? [...pageAccounts][0]! : null);+ for (const s of sentences) {+ const lineAccounts = [...new Set(findNames(cues.find(c => c.line === s.line)?.text ?? '', ctx.accounts).map(m => m.entry.slug))];+ out.push(...parseSentence(s.text, s.line, ctx, lineAccounts.length === 1 ? lineAccounts[0]! : context));}- for (const s of sentences) out.push(...parseSentence(s.text, s.line, ctx));return out;}-function parseSentence(sentence: string, line: number, ctx: ParseContext): Statement[] {+const SPEAKER_RE = /^\s*(?:\[[^\]]*\]\s*)?([A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?(?: [A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?){0,2}):\s+(.*)$/;++/** A chat line "[time] Name: I'm taking X" speaks for Name: its first-person subject becomes the speaker. */+function speakerFirstPerson(line: string): string {+ const m = SPEAKER_RE.exec(line);+ if (!m) return line;+ const speaker = trimNameRun(m[1]!);+ if (!speaker || speaker !== m[1]) return line;+ const text = m[2]!;+ if (!/(?:^|[.!?,;]\s+)I(?:'m|'ll|'ve| am| will| have| was|\b)/.test(text)) return line;+ return text+ .replace(/(^|[.!?,;]\s+)I'm\b/g, `$1${speaker} is`).replace(/(^|[.!?,;]\s+)I am\b/g, `$1${speaker} is`)+ .replace(/(^|[.!?,;]\s+)I'll\b/g, `$1${speaker} will`).replace(/(^|[.!?,;]\s+)I've\b/g, `$1${speaker} has`)+ .replace(/(^|[.!?,;]\s+)I\b/g, `$1${speaker}`);+}++function parseSentence(sentence: string, line: number, ctx: ParseContext, context: string | null): Statement[] {if (sentence.endsWith('?')) return [];const norm = normalize(sentence, ctx);const { n } = norm;if (!n.includes('⟦P')) return [];+ if (!NEGATION_RE.test(n) && !HYPOTHETICAL_RE.test(n)) {+ const handoff = HANDOFF_LABEL_RE.exec(n);+ const account = /⟦A(\d+)⟧/.exec(n)?.[1];+ const target = account !== undefined ? norm.accounts[Number(account)]! : context;+ if (handoff?.groups && target) {+ const chosen = chooseDate(norm, handoff.index);+ return [{ page_id: ctx.page.id, slug: ctx.page.slug, recorded: ctx.page.date, line, text: sentence, kind: 'takeover',+ owner: norm.persons[Number(handoff.groups.o)]!, from: norm.persons[Number(handoff.groups.from)]!, account: target,+ date: chosen ? chosen.date.iso : RELATIVE_DATE_RE.test(sentence) ? null : ctx.page.date, stated: !!chosen }];+ }+ }+ const real = matchSentence(norm, sentence, line, ctx, context);+ if (real.length || norm.persons.length < 2) return real;+ // An account with no page still holds its owner's phrases: a multi-word name in the account position becomes a+ // page-less account (`pseudo:<name>`) that only competes in ambiguity (contract line 9) and never receives a link.+ const pseudo: Statement[] = [];+ norm.persons.forEach((name, k) => {+ if (!name.includes(' ') || k > 3) return;+ const variant: Normalized = { ...norm, accounts: [...norm.accounts, `pseudo:${name.toLowerCase()}`],+ n: norm.n.replaceAll(`⟦P${k}⟧`, `⟦A${norm.accounts.length}⟧`) };+ for (const s of matchSentence(variant, sentence, line, { ...ctx, selfAccount: null }, null)) if (s.owner !== name && s.kind !== 'correction') pseudo.push(s);+ });+ return pseudo;+}++function matchSentence(norm: Normalized, sentence: string, line: number, ctx: ParseContext, context: string | null): Statement[] {+ const { n } = norm;const base = { page_id: ctx.page.id, slug: ctx.page.slug, recorded: ctx.page.date, line, text: sentence };const accountOf = (g: string | undefined) => (g === undefined ? ctx.selfAccount : norm.accounts[Number(g)] ?? null);const undated = RELATIVE_DATE_RE.test(sentence);- const dated = (found: FoundDate | null): { date: string | null; stated: boolean } =>- found ? { date: found.iso, stated: true } : { date: undated ? null : ctx.page.date, stated: false };+ const dated = (found: { date: FoundDate } | null): { date: string | null; stated: boolean } =>+ found ? { date: found.date.iso, stated: true } : { date: undated ? null : ctx.page.date, stated: false };const wrong = new Set<number>();if (CORRECTION_RE.test(n)) for (const re of WRONG_RES) for (const m of n.matchAll(re)) wrong.add(Number(m[1]));if (wrong.size) {const right = norm.persons.findIndex((_, i) => !wrong.has(i));const acc = /⟦A(\d+)⟧/.exec(n)?.[1];- const account = acc !== undefined ? norm.accounts[Number(acc)]! : ctx.selfAccount;- if (!account) return [{ ...base, kind: 'correction', owner: right >= 0 ? norm.persons[right]! : null, wrong: norm.persons[[...wrong][0]!]!, account: '', ...dated(chooseDate(norm, 0, new Set())) }];+ const account = acc !== undefined ? norm.accounts[Number(acc)]! : context;+ if (!account) return [{ ...base, kind: 'correction', owner: right >= 0 ? norm.persons[right]! : null, wrong: norm.persons[[...wrong][0]!]!, account: '', ...dated(chooseDate(norm, 0)) }];return [...wrong].map(w => ({ ...base, kind: 'correction' as const, owner: right >= 0 ? norm.persons[right]! : null, wrong: norm.persons[w]!, account,- ...dated(chooseDate(norm, 0, new Set())) }));+ ...dated(chooseDate(norm, 0)) }));}if (NEGATION_RE.test(n) || HYPOTHETICAL_RE.test(n)) return [];@@ -314,8 +389,8 @@ function parseSentence(sentence: string, line: number, ctx: ParseContext): Stateconst used: Array<[number, number]> = [];for (const p of PATTERNS) {const re = ctx.selfAccount ? p.reSelf : p.re;- for (const m of n.matchAll(new RegExp(re.source, 'g'))) {- const s = m.index!;+ for (const m of ` ${n}`.matchAll(new RegExp(re.source, 'g'))) {+ const s = Math.max(0, m.index! - 1);const e = s + m[0].length;if (used.some(([a, b]) => s < b && e > a)) continue;const g = m.groups ?? {};@@ -332,12 +407,12 @@ function parseSentence(sentence: string, line: number, ctx: ParseContext): State}if (p.kind === 'join' && d1) { out.push({ ...base, kind: 'join', owner, account, date: d1.iso, stated: true }); continue; }if (p.kind === 'end' && d2) { out.push({ ...base, kind: 'end', owner, account, date: d2.last, stated: true }); continue; }- const when = dated(chooseDate(norm, s, new Set()));- out.push({ ...base, kind: p.kind, owner, ...(from && from !== owner ? { from } : {}), account, ...when });+ const chosen = chooseDate(norm, s);+ const when = dated(chosen);+ // An ongoing statement with a start cue ("as of", "since", "effective") dates the start of the stint.+ const kind = p.kind === 'ongoing' && chosen?.start ? 'join' : p.kind;+ out.push({ ...base, kind, owner, ...(from && from !== owner ? { from } : {}), account, ...when });}}return out;}--/** The predecessor's last day for a takeover starting on `day`. */-export function dayBefore(day: string): string { return addDays(day, -1); }diff --git a/src/core/mentions/stale.ts b/src/core/mentions/stale.tsindex c152beee9f..b77d494add 100644--- a/src/core/mentions/stale.ts+++ b/src/core/mentions/stale.ts@@ -63,5 +63,6 @@ export function mentionJsonFields(r: MentionPassResult): Record<string, unknown>mention_pages: r.pages, mention_links_created: r.created, mention_links_removed: r.removed,mention_alias_pages: r.aliasPages, mention_due_remaining: r.remaining, mention_state: r.state,...(r.error ? { mention_error: r.error } : {}),+ ...(r.ownerPhrases ? { owner_phrases: r.ownerPhrases } : {}),};}diff --git a/src/core/search/entity-anchor.ts b/src/core/search/entity-anchor.tsindex d716a56b44..871f328a19 100644--- a/src/core/search/entity-anchor.ts+++ b/src/core/search/entity-anchor.ts@@ -24,6 +24,7 @@ import { isFactEntityPage } from '../entities/resolve.ts';import { pageReadFilter } from './read-policy-sql.ts';import { containsTokenRun, isTitleMentionedInQuery, tokenizeTitle } from './title-match.ts';import { enforceTokenBudget } from './token-budget.ts';+import { rankingLinkSql } from '../mentions/owner-phrase/ranking.ts';export const ENTITY_ANCHORING_KEY = 'search.entity_anchoring';/** Anchored pages read per entity (the entity page is extra). */@@ -42,7 +43,7 @@ export async function entityAnchoredPages(engine: BrainEngine, sourceId: string,const rows = await engine.executeRaw<{ id: number; slug: string }>(`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug <> $2AND p.type NOT IN ('question', 'synthesis') AND NOT (p.frontmatter ? '${PINNED_QUESTION_MARKER}')- AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer)))+ AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer AND ${rankingLinkSql('l')})))ORDER BY COALESCE(p.effective_date, p.updated_at) DESC, p.id DESC LIMIT ${limit}`,[sourceId, entitySlug, pattern, entity?.id ?? null]);return { entity: entity ? { id: Number(entity.id), slug: entitySlug } : null, pages: rows.map(r => ({ id: Number(r.id), slug: r.slug })) };diff --git a/src/core/search/provenance-demotion.ts b/src/core/search/provenance-demotion.tsindex 6e046290ed..6a2ea868eb 100644--- a/src/core/search/provenance-demotion.ts+++ b/src/core/search/provenance-demotion.ts@@ -23,6 +23,7 @@ import type { BrainEngine } from '../engine.ts';import type { SearchResult } from '../types.ts';import { parseFactsFence } from '../facts-fence.ts';import { resolveQueryEntity } from './alias-fanout.ts';+import { rankingLinkSql } from '../mentions/owner-phrase/ranking.ts';export const GENERATED_FACTOR = 0.5;@@ -60,7 +61,7 @@ export async function applyGeneratedDemotion(engine: BrainEngine, list: SearchReconst targetIds = targets.map(t => Number(t.id));if (!targetIds.length) return;const linking = new Set((await engine.executeRaw<{ id: number }>(- `SELECT DISTINCT from_page_id AS id FROM links WHERE from_page_id = ANY($1::int[]) AND to_page_id = ANY($2::int[])`,+ `SELECT DISTINCT l.from_page_id AS id FROM links l WHERE l.from_page_id = ANY($1::int[]) AND l.to_page_id = ANY($2::int[]) AND ${rankingLinkSql('l')}`,[ids, targetIds])).map(r => Number(r.id)));const primaryPresent = list.some(r => !generatedIds.has(r.page_id) && (targetIds.includes(r.page_id) || linking.has(r.page_id)));if (!primaryPresent) return;diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsindex a2537dac63..f51e9bad7e 100644--- a/src/core/search/read-enrichment.ts+++ b/src/core/search/read-enrichment.ts@@ -3,6 +3,7 @@ import { unverifiedExtractionFragment } from '../extraction-review.ts';import { currentTextProjectionFilter, protectedBodyFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';import { relationshipFilterSql } from '../link-validity.ts';+import { rankingLinkSql } from '../mentions/owner-phrase/ranking.ts';/** Narrow query dependency shared by both engines. */export type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;@@ -281,7 +282,7 @@ export async function readAdjacencyBoosts(query: ReadQuery, ids: number[], scopeFROM links l JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULLJOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULLWHERE l.from_page_id = ANY(${idArray}) AND l.to_page_id = ANY(${idArray})- AND ${from} AND ${to} AND ${origin}+ AND ${from} AND ${to} AND ${origin} AND ${rankingLinkSql('l')}GROUP BY l.to_page_id HAVING COUNT(DISTINCT l.from_page_id) >= 1`, params);return new Map(rows.map(row => [Number(row.to_page_id), { hits: Number(row.hits), cross_source_hits: Number(row.cross_source_hits) }]));}diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 8c672fb8a2..e4f3e8db93 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -39,6 +39,7 @@ import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';import { factEntitySlugs } from '../mentions/siblings.ts';+import { readKnownAs, type KnownAs } from '../mentions/owner-phrase/known-as.ts';const EDGE_CAP = 10;const OPEN_THREADS_CAP = 3;@@ -121,6 +122,8 @@ export interface EntityCard {identity_excerpt?: CardIdentity['identity_excerpt'];/** Pages whose qualifying lines did not fit the excerpt budget. */identity_excerpt_omitted?: string[];+ /** Owners of this account with their owner-phrase validity windows (`mentions.owner_phrases`). `entity` verb only. */+ known_as?: KnownAs;/** What `aka` covers and which names to search before a history or as-of answer. `entity` verb only. */alias_guidance?: CardIdentity['alias_guidance'];/** #5575 A6 (additive): the entity page's trust tier and short write origin. */@@ -325,7 +328,8 @@ export async function buildEntityCard(const card = await assembleCard(engine, sourceId, best.row, opts.remote, excludePrivate, opts.eligibility ?? {});if (opts.includeReferences) {Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes),- await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));+ await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }),+ await readKnownAs(engine, sourceId, best.row.slug, { excludePrivate }));}return {found: true,diff --git a/test/owner-phrase-rules.test.ts b/test/owner-phrase-rules.test.tsnew file mode 100644index 0000000000..17ca2d6b67--- /dev/null+++ b/test/owner-phrase-rules.test.ts@@ -0,0 +1,231 @@+/**+ * Owner phrases, the pure rules (docs/guides/owner-phrases.md, contract lines+ * 1-10): page scan, statement grammar, window assembly and phrase resolution.+ * One test row per contract line, on a general (non-contract) corpus of+ * team updates, tickets, chat and notes.+ *+ * Protects: handoffs ending the predecessor the day before, inclusive bounds,+ * advance announcements, overlapping and open-ended stints, unknown starts,+ * corrections voiding a stint, temporal filtering before ambiguity, refusal+ * of two accounts sharing a descriptor, a phrase with no owner, non-owner and+ * personal possessives, fallback page dates, belated notes whose readings+ * disagree, agent-written pages and page-less accounts. Regression: a parser+ * that links a phrase outside its owner's window, or that links when two+ * accounts match.+ */+import { describe, expect, test } from 'bun:test';+import { tokenizeTitle } from '../src/core/by-mention.ts';+import { findDates } from '../src/core/mentions/owner-phrase/dates.ts';+import { scanPage, type ScanInput } from '../src/core/mentions/owner-phrase/scan.ts';+import { buildNameIndex, parseStatements, type Statement } from '../src/core/mentions/owner-phrase/statements.ts';+import { accountDescriptors, buildWindows, ownerMatches, resolvePhrase, type OwnerWindow } from '../src/core/mentions/owner-phrase/windows.ts';++const ACCOUNTS = ['Acme Example Freight', 'Widget Example Health', 'Orbit Example Labs', 'Nimbus Example Freight'];+const slugOf = (t: string) => `companies/${t.toLowerCase().replace(/ /g, '-')}`;+const accounts = buildNameIndex(ACCOUNTS.map(t => ({ slug: slugOf(t), title: t, tokens: tokenizeTitle(t) })));+const persons = buildNameIndex([{ slug: 'people/rowan-example', title: 'Rowan Example', tokens: tokenizeTitle('Rowan Example') }]);+const descriptorSets = new Map(ACCOUNTS.map(t => [slugOf(t), accountDescriptors([t], [])]));+const descriptorAccounts = new Map<string, Set<string>>();+for (const [slug, set] of descriptorSets) for (const d of set) descriptorAccounts.set(d, new Set([...(descriptorAccounts.get(d) ?? []), slug]));+const descriptorsOf = (g: string) => descriptorSets.get(g) ?? accountDescriptors([g.replace(/^pseudo:/, '')], []);++let nextId = 1;+function page(slug: string, body: string, opts: Partial<ScanInput> & { date?: string | null } = {}) {+ const input: ScanInput = { slug, type: opts.type ?? 'note', title: opts.title ?? slug, compiled_truth: body, timeline: '', frontmatter: opts.frontmatter ?? {},+ effective_date: opts.date === undefined ? '2025-03-10' : opts.date, effective_date_source: opts.date === null ? 'fallback' : 'date' };+ return { slug, id: nextId++, scan: scanPage(input) };+}+function statementsOf(p: ReturnType<typeof page>, selfAccount: string | null = null): Statement[] {+ return parseStatements(p.scan.cues, { page: { id: p.id, slug: p.slug, date: p.scan.date, agent: p.scan.agent }, selfAccount, accounts, persons, descriptorAccounts });+}+const brief = (s: Statement[]) => s.map(x => [x.kind, x.owner, x.from ?? null, x.account, x.date]);+const windowsOf = (...pages: Array<ReturnType<typeof page> | [ReturnType<typeof page>, string]>) =>+ buildWindows(pages.flatMap(p => Array.isArray(p) ? statementsOf(p[0], p[1]) : statementsOf(p)), s => s);+const span = (w: OwnerWindow[]) => w.map(x => `${x.group.split('/')[1]} ${x.owner} ${x.from ?? '?'}..${x.to ?? 'open'}${x.startKnown ? '' : ' (start unknown)'}`).sort();+const resolve = (w: OwnerWindow[], owner: string, descriptor: string, date: string | null, readings: string[] = []) =>+ resolvePhrase({ owner, descriptor }, date, readings, w, descriptorsOf);++describe('line 1-3: scan, statements and dates are separate inputs', () => {+ test('a page scan keeps cue lines, owner phrases and its own date; a fallback date is no date', () => {+ const p = page('notes/n1', "Quill Example takes over Acme Example Freight from Rowan Example on April 1.\nQuill's freight account wants a rate review.");+ expect(p.scan.date).toBe('2025-03-10');+ expect(p.scan.cues.map(c => c.line)).toEqual([1]);+ expect(p.scan.hits).toEqual([{ owner: 'Quill', descriptor: 'freight', noun: 'account', line: 2, surface: "Quill's freight account" }]);+ expect(page('notes/n2', 'x', { date: null }).scan.date).toBeNull();+ });++ test('owner phrase forms: possessive, book, full name, "the X account Y runs"; plural and personal accounts are not phrases', () => {+ const hits = page('notes/n3', [+ "Ask about Quill Example's freight account.", "Rowan's health book is quiet.", 'The labs account Quill handles renewed.',+ "Quill's freight accounts are busy.", "Rowan's health account at the benefits portal needs a login.",+ ].join('\n')).scan.hits.map(h => `${h.owner}/${h.descriptor}/${h.noun}`);+ expect(hits).toEqual(['Quill Example/freight/account', 'Rowan/health/book', 'Quill/labs/account']);+ });++ test('dates: ISO, written, month-only and year-less dates take the nearest year', () => {+ expect(findDates('on 2025-04-01, April 2, 2025, 3 May 2025, and March 2025', null).map(d => [d.iso, d.last]))+ .toEqual([['2025-04-01', '2025-04-01'], ['2025-04-02', '2025-04-02'], ['2025-05-03', '2025-05-03'], ['2025-03-01', '2025-03-31']]);+ expect(findDates('starting January 5', '2024-12-20')[0]!.iso).toBe('2025-01-05');+ });+});++describe('line 2: the statement grammar', () => {+ test('takeover forms name the new owner, the predecessor and the date', () => {+ const p = page('updates/u1', [+ 'Starting April 1, Quill Example takes over Acme Example Freight from Rowan Example.',+ 'Widget Example Health moves from Rowan Example to Quill Example, effective March 1.',+ 'Rowan Example hands Orbit Example Labs to Quill Example on 2025-05-01.',+ ].join('\n'));+ expect(brief(statementsOf(p))).toEqual([+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Acme Example Freight'), '2025-04-01'],+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Widget Example Health'), '2025-03-01'],+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Orbit Example Labs'), '2025-05-01'],+ ]);+ });++ test('ongoing, join, end and stint forms; a start cue dates the start', () => {+ const p = page('updates/u2', [+ 'Quill Example owns Acme Example Freight.',+ 'Rowan Example owns the Widget Example Health relationship as of February 1.',+ 'Quill Example started on Orbit Example Labs on June 15.',+ 'Rowan Example rolls off Orbit Example Labs on 2025-06-30.',+ 'Rowan Example ran Nimbus Example Freight from 2024-01-01 to 2024-12-31.',+ ].join('\n'));+ expect(brief(statementsOf(p))).toEqual([+ ['ongoing', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-03-10'],+ ['join', 'Rowan Example', null, slugOf('Widget Example Health'), '2025-02-01'],+ ['join', 'Quill Example', null, slugOf('Orbit Example Labs'), '2025-06-15'],+ ['end', 'Rowan Example', null, slugOf('Orbit Example Labs'), '2025-06-30'],+ ['stint', 'Rowan Example', null, slugOf('Nimbus Example Freight'), '2024-01-01'],+ ]);+ });++ test('negated, hypothetical, questioned and relative-dated sentences set nothing', () => {+ const p = page('notes/n4', [+ 'Quill Example did not take over Acme Example Freight.',+ 'Quill Example might take over Acme Example Freight.',+ 'Will Quill Example take over Acme Example Freight?',+ 'Next week Quill Example takes over Acme Example Freight.',+ ].join('\n'));+ const s = statementsOf(p);+ expect(s.filter(x => x.date)).toEqual([]);+ });++ test('labels and tables: an account page label, an owner table and a handoff table', () => {+ const acct = page(slugOf('Acme Example Freight'), 'Account owner: Quill Example (since 2025-01-15)\nSegment: logistics', { type: 'company' });+ expect(brief(statementsOf(acct, slugOf('Acme Example Freight')))).toEqual([['takeover', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-01-15']]);+ expect(acct.scan.descriptors).toEqual(['logistics']);+ const table = page('meetings/m1', [+ '| Account | Owner | Start | End |', '|---|---|---|---|', '| Orbit Example Labs | Rowan Example | 2024-02-01 | 2024-09-30 |', '',+ '| Account | Outgoing | Incoming | Effective |', '|---|---|---|---|', '| Widget Example Health | Rowan Example | Quill Example | 2025-04-01 |',+ ].join('\n'));+ expect(brief(statementsOf(table))).toEqual([+ ['stint', 'Rowan Example', null, slugOf('Orbit Example Labs'), '2024-02-01'],+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Widget Example Health'), '2025-04-01'],+ ]);+ });++ test('a chat speaker speaks for the first person; a ticket owner label on a non-account page is not an account owner', () => {+ const chat = page('chat/c1', "[09:14] Quill Example: I'm picking up Acme Example Freight starting today", { type: 'chat' });+ expect(brief(statementsOf(chat))).toEqual([['takeover', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-03-10']]);+ expect(statementsOf(page('tickets/t1', 'Owner: Rowan Example\nCustomer: Acme Example Freight', { type: 'ticket' }))).toEqual([]);+ });++ test('line 4: an agent-written page sets no window; its owner phrases still scan', () => {+ const p = page('notes/agent-1', "Quill Example owns Orbit Example Labs. Quill's labs account is fine.", { type: 'agent-note' });+ expect(p.scan.agent).toBe(true);+ expect(statementsOf(p)).toEqual([]);+ expect(p.scan.hits.length).toBe(1);+ });+});++describe('lines 5-6: window assembly', () => {+ test('a handoff ends the predecessor the day before; an advance announcement works; bounds are inclusive', () => {+ const w = windowsOf(page('mail/a', 'From May 1, Quill Example takes over Acme Example Freight from Rowan Example.', { date: '2025-04-15' }));+ expect(span(w)).toEqual(['acme-example-freight quill example 2025-05-01..open', 'acme-example-freight rowan example ?..2025-04-30 (start unknown)']);+ expect(resolve(w, 'Rowan', 'freight', '2025-04-30')).toMatchObject({ linked: true });+ expect(resolve(w, 'Rowan', 'freight', '2025-05-01')).toMatchObject({ linked: false, reason: 'outside_window' });+ expect(resolve(w, 'Quill', 'freight', '2025-05-01')).toMatchObject({ linked: true });+ expect(resolve(w, 'Quill', 'freight', '2025-04-30')).toMatchObject({ linked: false, reason: 'outside_window' });+ });++ test('a join overlaps; an explicit end closes on its own day; an open stint runs on', () => {+ const w = windowsOf(+ [page(slugOf('Orbit Example Labs'), 'Account manager: Rowan Example, 2024-06-01 to 2025-06-30.', { type: 'company' }), slugOf('Orbit Example Labs')],+ page('notes/b', 'Quill Example started on Orbit Example Labs on June 15.', { date: '2025-07-08' }));+ expect(span(w)).toEqual(['orbit-example-labs quill example 2025-06-15..open', 'orbit-example-labs rowan example 2024-06-01..2025-06-30']);+ });++ test('an ongoing statement with no start opens after the latest earlier stint; a contradicting one is ignored', () => {+ const w = windowsOf(+ page('notes/c1', 'Rowan Example ran Acme Example Freight from 2024-01-01 to 2024-06-30.', { date: '2024-07-01' }),+ page('notes/c2', 'Quill Example owns Acme Example Freight.', { date: '2024-09-01' }),+ page('notes/c3', 'Rowan Example handles Acme Example Freight.', { date: '2024-10-01' }));+ expect(span(w)).toEqual(['acme-example-freight quill example 2024-07-01..open (start unknown)', 'acme-example-freight rowan example 2024-01-01..2024-06-30']);+ });++ test('line 5: a correction voids the wrong stint and starts the right owner on its date; mentions between both dates do not link to the wrong owner', () => {+ const w = windowsOf(+ page('mail/h', 'Widget Example Health moves from Rowan Example to Quill Example, effective March 1.', { date: '2025-03-03' }),+ page('mail/c', 'Correction: Widget Example Health went to Orbit Person, not Quill. Thanks.', { date: '2025-03-07' }));+ expect(span(w)).toEqual(['widget-example-health orbit person 2025-03-01..open', 'widget-example-health rowan example ?..2025-02-28 (start unknown)']);+ expect(resolve(w, 'Quill', 'health', '2025-03-05')).toMatchObject({ linked: false, reason: 'no_owner' });+ expect(resolve(w, 'Orbit', 'health', '2025-03-05')).toMatchObject({ linked: true });+ });++ test('identity groups merge stints named on sibling pages', () => {+ const groups = new Map([[slugOf('Acme Example Freight'), 'g'], [slugOf('Nimbus Example Freight'), 'g']]);+ const w = buildWindows([+ ...statementsOf(page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.')),+ ...statementsOf(page('b', 'Quill Example rolls off Nimbus Example Freight on 2025-02-01.')),+ ], s => groups.get(s) ?? s);+ expect(w.map(x => [x.group, x.from, x.to, x.accounts])).toEqual([['g', '2025-01-01', '2025-02-01', [slugOf('Acme Example Freight'), slugOf('Nimbus Example Freight')]]]);+ });+});++describe('lines 7-10: resolution', () => {+ test('descriptors are name words without suffixes plus declared ones', () => {+ expect([...accountDescriptors(['CRM record: Acme Example Freight Inc'], ['logistics'])].sort()).toEqual(['acme', 'example', 'freight', 'logistics']);+ });++ test('owner matching: one word matches a first name, two words the full name', () => {+ expect(ownerMatches('Quill', { owner: 'quill example' })).toBe(true);+ expect(ownerMatches('Quill Example', { owner: 'quill example' })).toBe(true);+ expect(ownerMatches('Quill Other', { owner: 'quill example' })).toBe(false);+ });++ test('temporal candidates first, then ambiguity: two freight accounts are ambiguous only once one owner holds both', () => {+ const w = windowsOf(+ page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.'),+ page('b', 'Rowan Example owns Nimbus Example Freight.', { date: '2025-01-01' }),+ page('c', 'Nimbus Example Freight moves from Rowan Example to Quill Example on 2025-06-01.'));+ expect(resolve(w, 'Quill', 'freight', '2025-03-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });+ expect(resolve(w, 'Quill', 'freight', '2025-07-01')).toMatchObject({ linked: false, reason: 'ambiguous' });+ expect(resolve(w, 'Quill', 'acme', '2025-07-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });+ });++ test('a phrase with no owner, a non-owner possessive and no page date never link', () => {+ const w = windowsOf(page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.'));+ expect(resolve(w, 'Juniper', 'freight', '2025-03-01')).toMatchObject({ linked: false, reason: 'no_owner' });+ expect(resolve(w, 'Quill', 'robotics', '2025-03-01')).toMatchObject({ linked: false, reason: 'no_owner' });+ expect(resolve(w, 'Quill', 'freight', null)).toMatchObject({ linked: false, reason: 'no_page_date' });+ });++ test('line 10: a belated note links only when both readings agree', () => {+ const w = windowsOf(page('a', 'Starting 2025-05-01, Quill Example takes over Acme Example Freight from Rowan Example.'));+ const note = page('notes/belated', "Belated note on the April 20 call: Rowan's freight account asked for a refund.", { date: '2025-05-10' });+ expect(note.scan.readings).toEqual(['2025-04-20']);+ expect(resolve(w, 'Rowan', 'freight', note.scan.date, note.scan.readings)).toMatchObject({ linked: false, reason: 'outside_window' });+ expect(resolve(w, 'Quill', 'freight', note.scan.date, note.scan.readings)).toMatchObject({ linked: false, reason: 'readings_disagree' });+ expect(resolve(w, 'Quill', 'freight', '2025-05-10', ['2025-05-03'])).toMatchObject({ linked: true });+ });++ test('a page-less account still competes for its owner\'s phrases and is never a link target', () => {+ const w = windowsOf(+ page('a', 'Quill Example owns Acme Example Freight.', { date: '2025-01-01' }),+ page('b', 'As of July 1, Quill Example will own Harbor Placeholder Freight in addition to her current book.', { date: '2025-06-20' }));+ expect(w.map(x => x.group).sort()).toEqual([slugOf('Acme Example Freight'), 'pseudo:harbor placeholder freight']);+ expect(resolve(w, 'Quill', 'freight', '2025-03-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });+ expect(resolve(w, 'Quill', 'freight', '2025-08-01')).toMatchObject({ linked: false, reason: 'ambiguous' });+ });+});