Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mentions): owner-phrase resolution with validity windows (F5), rules frozen before the transfer set
garrytan59df7ad28df9
diff --git a/docs/guides/owner-phrases.md b/docs/guides/owner-phrases.mdnew file mode 100644index 0000000000..7f3f3069be--- /dev/null+++ b/docs/guides/owner-phrases.md@@ -0,0 +1,134 @@+# Owner phrases: "alice-example's freight account"++Company text often names an account by who owns it: "Alice's freight account",+"the health book Charlie handles". Which account that means depends on the date,+because accounts change hands. With owner phrases on, the mention index works+out each owner's validity window from ownership and handoff statements in page+text. It then links a document that uses an owner phrase to the account its+owner held on the document's date.++**Say to your agent:** *"Turn on owner-phrase linking so notes that say 'Alice's freight account' link to the right account."*+**Say to your agent:** *"Who owned the acme-example account in March, and which phrases point at it?"*++```bash+gbrain config set mentions.owner_phrases true # off by default+gbrain extract --stale --catch-up # builds windows and links+gbrain entity "Acme Example Freight" # the card lists known_as rows+```++`mentions.owner_phrases` takes effect when the mention pass runs: when a brain+or benchmark slot is built, or on the next `gbrain extract --stale`. A read-time+config change does nothing until the pass runs. When the key is on, it is part+of the mention policy fingerprint stored on each source's `mention_index_status`+row (and in slot receipts that copy it). When the key is off, the fingerprint+is the same as on a brain that never had the key. Turning it off removes every+owner-phrase link, window and page state on the next pass.++## What gets linked++A link is stored as an ordinary mention: `link_source='mentions'`,+`link_kind='owner_phrase'`, `link_type='mentions'`, with the phrase as written+in `context`. Ranking readers ignore mention links, so owner-phrase links never+change search scores. Graph traversal, `get_backlinks` and the entity card's+`referenced_by` see them the same way they see plain mentions. A page pair that+another link already connects gets no owner-phrase link. A plain mention found+later replaces the owner-phrase row.++## Resolution contract (v1, deterministic, no model calls)++The rules below are general to any brain. Each line is covered by a test row in+`test/owner-phrase-*.test.ts`.++1. **Inputs are kept apart.** Ownership statements come from one place, account+ descriptors from another and the document's date from a third. A statement+ never supplies a descriptor, and a phrase never creates a window.+2. **Ownership statements.** Sentences on any page type (not only entity pages)+ in the title, compiled truth or timeline. They have one of these forms:+ - takeover: "B takes over / inherits / picks up / assumes X", "X moves / is+ handed / is reassigned (from A) to B", "A hands X (off) to B", "B replaces A+ on X", "B is now / becomes the owner (lead, AE, CSM) for X";+ - join: "B joins X", "B has owned X since <date>". A join adds an owner+ without ending anyone else's stint;+ - ongoing: "B owns / runs / handles / covers / leads X", "B is the owner of+ X", "X is owned by B", "X is B's account", and on an account page the label+ lines `Owner:`, `Account owner:`, `Account lead:` and the same frontmatter+ keys;+ - end: "A rolls off / steps away from / leaves / is no longer on X", "A's+ last day on X is <date>";+ - stint: "A ran X from <date> to <date>", "A ran X until <date>";+ - tables whose header names an account column and an owner column, with+ optional start and end columns.++ X is an account: a linkable entity page that is not a person, named by its+ title or alias, by "the <descriptor> account" when exactly one account has+ that descriptor, or implicitly as the page itself on an account page.+ Negated sentences, questions and hypothetical sentences ("might", "if",+ "considering", "proposed") are not statements.+3. **Statement dates.** A date written in the sentence wins. Cue-led dates+ ("starting", "effective", "as of", "from", "on") come first, then the first+ date after the verb, then the last date before it. A day-month date without+ a year takes the year that puts it nearest the page date. With no date in+ the sentence, the statement takes the page's own date. Only a non-fallback+ page date counts (`effective_date_source` other than `fallback`). A relative+ date with no written date ("next week", "soon") makes the statement+ undated. An undated statement sets no window.+4. **Agent-written pages are not evidence.** Statements on a page whose type+ has the word `agent`, or whose frontmatter `author_kind`/`written_by` is+ `agent`, set no window. Owner phrases on those pages still resolve.+5. **Corrections void a stint.** A sentence with a correction cue+ ("correction", "was wrong", "actually", "not B", "rather than B", "instead+ of B") that names a wrong owner voids that owner's takeover, join or ongoing+ statements for the account, as recorded up to the correction. If it names the+ right owner, that owner takes over on the voided statement's date (or on+ the date the correction states). The previous owner's end is kept. A+ correction that names no account uses the page's only account.+6. **Window assembly.** Per identity group (an account page and its identity+ siblings, `mentions/siblings.ts`), statements are applied in date order.+ A takeover starts the new owner on day D and ends every other open stint+ (only the named predecessor's for "from A") on D−1. A predecessor named+ by "from A" who had no stint gets one ending on D−1, with an unknown+ start. An end statement ends the stint on its date. Bounds are inclusive+ calendar days. An open end runs until a later statement closes it. An+ ongoing statement on day D with no covering stint opens one with an+ unknown start. The window then begins the day after the latest earlier stint+ on the account ends, or has no lower bound. An ongoing statement that+ contradicts another owner's covering stint is ignored.+7. **Descriptors.** An account's descriptors are the words of its title and+ aliases (without corporate suffixes such as Inc, LLC, Co or Group), plus+ declared descriptors on the account page: "X is our <d> account", "known+ internally as the <d> account", and the `segment`, `industry`, `vertical`,+ `sector`, `category` and `descriptor` labels or frontmatter keys.+8. **Owner phrases.** "<Name>'s <d> account" (also book, client, customer,+ relationship, portfolio, book of business) and "the <d> account (that) <Name>+ runs / handles / owns / manages / covers / leads". The descriptor must be+ the whole run between the possessive and the noun. A plural noun, a name+ that is itself an account or company, and a sentence about personal or+ benefit accounts (benefits, HSA, FSA, 401k, payroll, bank, login, password)+ are not owner phrases. A one-word name matches an owner by first name, a+ longer name by the full name.+9. **Temporal candidates first, then ambiguity.** For the document's date, the+ candidates are windows whose owner matches, whose account has the+ descriptor and that cover the date. One identity group links. Two or more+ groups are ambiguous and refused. None is unresolved.+10. **Document dates and belated notes.** A document links only with a+ non-fallback page date. When the document also cites another date for+ itself, both readings must resolve to the same account or nothing links.+ The cited dates are a differing frontmatter `event_date` or `date`, a+ leading slug date, a `Date:`/`Sent:`/`Recorded:` label, or "notes from /+ recap of / written on <date>".+11. **Windows are stored apart.** Windows live in `owner_phrase_windows`, never+ in `page_aliases`, the `aka` list or search alias fan-out. Each row keeps+ its evidence (page, line, statement kind, date). Per-page scan results live+ in `owner_phrase_page_state`.+12. **Visibility.** A link whose window evidence includes a private page stores+ that page as `origin_page_id`. Remote and world-scope readers apply the+ link-origin privacy check and do not see the link. Trusted local reads do.+ `known_as` rows on the card follow the same rule.+13. **Invalidation.** A page is rescanned when its content revision or the+ owner-phrase version changes. Windows are rebuilt from every page's stored+ statements on each pass, and links are diffed against them. So a window+ change alone relinks exactly the documents it affects, and a deleted or+ edited evidence page withdraws its windows.++Every pass reports `links`, `documents`, `unresolved`, `ambiguous` and+`windows` under `mentions.owner_phrases` in `gbrain extract --stale --json`.diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 0d7ffe681c..7acdec8515 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -103,6 +103,9 @@ const ROWS: readonly Row[] = [['op_checkpoint_paths', 'out_of_scope', 'no_memory_text', 'op fingerprint path'],['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],+ ['owner_phrase_page_state', 'out_of_scope', 'probed_reported', 'source_id readings cues descriptors hits', 'cues hits'],+ ['owner_phrase_status', 'out_of_scope', 'no_memory_text', 'source_id state window_hash error'],+ ['owner_phrase_windows', 'out_of_scope', 'probed_reported', 'source_id group_key account_slugs owner_key owner_name descriptors evidence evidence_page_ids', 'owner_name evidence'],['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],diff --git a/src/core/mentions/owner-phrase/dates.ts b/src/core/mentions/owner-phrase/dates.tsnew file mode 100644index 0000000000..71beae2a5b--- /dev/null+++ b/src/core/mentions/owner-phrase/dates.ts@@ -0,0 +1,104 @@+/**+ * Calendar dates written in sentences, for owner-phrase windows. Dates are+ * ISO day strings (`YYYY-MM-DD`), so they compare as strings. Pure.+ */++const MONTHS: Record<string, number> = {+ jan: 1, january: 1, feb: 2, february: 2, mar: 3, march: 3, apr: 4, april: 4, may: 5, jun: 6, june: 6,+ jul: 7, july: 7, aug: 8, august: 8, sep: 9, sept: 9, september: 9, oct: 10, october: 10,+ nov: 11, november: 11, dec: 12, december: 12,+};+const MONTH = '(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sept?(?:ember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)';+const ORD = '(?:st|nd|rd|th)?';++export interface FoundDate {+ iso: string;+ /** Last day of the month for a month-only date ("March 2025"); equal to `iso` otherwise. */+ last: string;+ index: number;+ end: number;+}++function pad(n: number): string { return String(n).padStart(2, '0'); }++function valid(y: number, m: number, d: number): string | null {+ if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1) return null;+ const date = new Date(Date.UTC(y, m - 1, d));+ return date.getUTCMonth() === m - 1 ? `${y}-${pad(m)}-${pad(d)}` : null;+}++function lastOfMonth(y: number, m: number): string {+ return `${y}-${pad(m)}-${pad(new Date(Date.UTC(y, m, 0)).getUTCDate())}`;+}++export function addDays(iso: string, days: number): string {+ const d = new Date(`${iso}T00:00:00Z`);+ d.setUTCDate(d.getUTCDate() + days);+ return d.toISOString().slice(0, 10);+}++/** The year that puts month/day nearest `ref` (a day string), else null without a reference. */+function nearestYear(m: number, d: number, ref: string | null): number | null {+ if (!ref) return null;+ const refYear = Number(ref.slice(0, 4));+ let best: { y: number; gap: number } | null = null;+ for (const y of [refYear - 1, refYear, refYear + 1]) {+ const iso = valid(y, m, d);+ if (!iso) continue;+ const gap = Math.abs(Date.parse(`${iso}T00:00:00Z`) - Date.parse(`${ref}T00:00:00Z`));+ if (!best || gap < best.gap) best = { y, gap };+ }+ return best?.y ?? null;+}++const DATE_RE = new RegExp([+ String.raw`\b(\d{4})-(\d{2})-(\d{2})\b`,+ String.raw`\b(\d{1,2})/(\d{1,2})/(\d{4})\b`,+ String.raw`\b(${MONTH})\.? (\d{1,2})${ORD}(?:,? (\d{4}))?\b`,+ String.raw`\b(\d{1,2})${ORD} (?:of )?(${MONTH})\.?(?:,? (\d{4}))?\b`,+ String.raw`\b(${MONTH})\.?,? (\d{4})\b`,+].join('|'), 'gi');++/** Every written calendar date in `text`, in order. `ref` (a day string) supplies a missing year. */+export function findDates(text: string, ref: string | null): FoundDate[] {+ const out: FoundDate[] = [];+ for (const m of text.matchAll(DATE_RE)) {+ let iso: string | null = null;+ let last: string | null = null;+ if (m[1]) iso = valid(Number(m[1]), Number(m[2]), Number(m[3]));+ else if (m[4]) iso = valid(Number(m[6]), Number(m[4]), Number(m[5]));+ else if (m[7]) {+ const mo = MONTHS[m[7].toLowerCase().replace(/\.$/, '')]!;+ const day = Number(m[8]);+ const y = m[9] ? Number(m[9]) : nearestYear(mo, day, ref);+ iso = y == null ? null : valid(y, mo, day);+ } else if (m[10]) {+ const mo = MONTHS[m[11]!.toLowerCase()]!;+ const day = Number(m[10]);+ const y = m[12] ? Number(m[12]) : nearestYear(mo, day, ref);+ iso = y == null ? null : valid(y, mo, day);+ } else if (m[13]) {+ const mo = MONTHS[m[13].toLowerCase()]!;+ const y = Number(m[14]);+ iso = valid(y, mo, 1);+ last = iso ? lastOfMonth(y, mo) : null;+ }+ if (!iso) continue;+ out.push({ iso, last: last ?? iso, index: m.index!, end: m.index! + m[0].length });+ }+ return out;+}++/** Relative time expressions that make a sentence's own date unknowable without a written date. */+export const RELATIVE_DATE_RE = /\b(?:tomorrow|yesterday|soon|shortly|next (?:week|month|quarter|year|monday|tuesday|wednesday|thursday|friday)|last (?:week|month|quarter)|this coming \w+|(?:later|earlier) this (?:week|month|quarter|year)|in (?:a|one|two|three|four|a few|\d+) (?:days?|weeks?|months?)|end of (?:the )?(?:week|month|quarter|year)|eo[mqy])\b/i;++/** A page date string (`YYYY-MM-DD`) from a stored timestamp, or null. */+export function dayOf(value: unknown): string | null {+ if (value == null) return null;+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString().slice(0, 10);+ const s = String(value);+ const m = /^(\d{4}-\d{2}-\d{2})/.exec(s);+ if (m) return m[1]!;+ const t = Date.parse(s);+ return Number.isNaN(t) ? null : new Date(t).toISOString().slice(0, 10);+}diff --git a/src/core/mentions/owner-phrase/pass.ts b/src/core/mentions/owner-phrase/pass.tsnew file mode 100644index 0000000000..e0a4fb309f--- /dev/null+++ b/src/core/mentions/owner-phrase/pass.ts@@ -0,0 +1,366 @@+/**+ * Owner phrases, the pass (docs/guides/owner-phrases.md). Runs inside the+ * mention pass (`mentions/pass.ts`) per source, after the plain reconcile, with+ * the gazetteer that pass built:+ *+ * 1. Off (`mentions.owner_phrases` unset or false, or mention linking off):+ * owner-phrase links, windows, page state and status of the source go+ * once, and the pages that held those links are marked mention-due so the+ * plain reconcile can claim the pair.+ * 2. Scan: pages whose content revision or OWNER_PHRASE_SCAN_VERSION differ+ * from their `owner_phrase_page_state` row are scanned (`scan.ts`).+ * 3. Build: statements are parsed from every stored scan against the current+ * names (`statements.ts`), windows are assembled per identity group and+ * every stored owner phrase is resolved (`windows.ts`).+ * 4. Publish, in one transaction under the source's advisory lock, only when+ * no page of the source changed since its scan: windows are replaced when+ * their hash changed, owner-phrase links are diffed (a pair another link+ * already connects gets none), and the status row records the counters.+ * A link whose window evidence includes a private page stores that page+ * as `origin_page_id`, so untrusted readers' link-origin check hides it.+ */++import { createHash } from 'node:crypto';+import type { BrainEngine, LinkBatchInput } from '../../engine.ts';+import type { Gazetteer } from '../../by-mention.ts';+import { executeRawJsonb } from '../../sql-query.ts';+import { privatePagesFilterFragment } from '../../search/private-visibility.ts';+import { normalizeAlias } from '../../search/alias-normalize.ts';+import { canonicalTypeOf, type MentionPolicy, type PackTypes } from '../policy.ts';+import { siblingVerdict } from '../siblings.ts';+import { titleName } from '../aliases.ts';+import { OWNER_PHRASE_SCAN_VERSION, scanPage, type CueLine, type PhraseHit } from './scan.ts';+import { buildNameIndex, findNames, parseStatements, type NameEntry, type Statement } from './statements.ts';+import { accountDescriptors, buildWindows, resolvePhrase, type OwnerWindow } from './windows.ts';++export const OWNER_PHRASE_KEY = 'mentions.owner_phrases';+const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);+const SCAN_BATCH = 500;++/** The build-time switch; off unless set to a true value. */+export async function readOwnerPhrasesEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ const value = await engine.getConfig(OWNER_PHRASE_KEY).catch(() => null);+ return value != null && TRUE_VALUES.has(value.trim().toLowerCase());+}++export interface OwnerPhraseCounters {+ /** Owner-phrase links stored after the pass. */+ links: number;+ /** Documents holding at least one owner-phrase link. */+ documents: number;+ /** Phrases with no owner window covering the document's date (or no owner at all, or no page date). */+ unresolved: number;+ /** Phrases refused because two or more accounts matched, or the document's readings disagreed. */+ ambiguous: number;+ windows: number;+}++export interface OwnerPhrasePassResult extends OwnerPhraseCounters {+ state: 'off' | 'complete' | 'pending' | 'failed';+ scanned: number;+ created: number;+ removed: number;+ error?: string;+}++export interface OwnerPhrasePassOpts {+ sourceId: string;+ gazetteer: Gazetteer;+ types: string[];+ pack: PackTypes | null;+ policy: MentionPolicy;+ enabled: boolean;+ deadline: number;+ signal?: AbortSignal;+}++interface EntityRow { id: number; slug: string; type: string | null; title: string | null; identity: string | null }+interface StateRow { page_id: number; slug: string; page_date: string | null; readings: string[]; agent: boolean; cues: unknown; descriptors: string[]; hits: unknown }++function json<T>(value: unknown): T {+ return (typeof value === 'string' ? JSON.parse(value) : value) as T;+}++function emptyResult(state: OwnerPhrasePassResult['state']): OwnerPhrasePassResult {+ return { state, scanned: 0, created: 0, removed: 0, links: 0, documents: 0, unresolved: 0, ambiguous: 0, windows: 0 };+}++/** Remove every owner-phrase row of one source; the pages that held links become mention-due. */+async function disableSource(engine: BrainEngine, sourceId: string): Promise<number> {+ return engine.transaction(async tx => {+ const rows = await tx.executeRaw<{ id: number; from_page_id: number }>(+ `DELETE FROM links l USING pages f WHERE f.id = l.from_page_id AND f.source_id = $1 AND l.link_kind = 'owner_phrase'+ RETURNING l.id, l.from_page_id`, [sourceId]);+ if (rows.length) {+ await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL WHERE page_id = ANY($1::int[])',+ [[...new Set(rows.map(r => Number(r.from_page_id)))]]);+ }+ await tx.executeRaw('DELETE FROM owner_phrase_windows WHERE source_id = $1', [sourceId]);+ await tx.executeRaw('DELETE FROM owner_phrase_page_state WHERE source_id = $1', [sourceId]);+ await tx.executeRaw('DELETE FROM owner_phrase_status WHERE source_id = $1', [sourceId]);+ return rows.length;+ });+}++async function scanDuePages(engine: BrainEngine, sourceId: string, deadline: number, signal?: AbortSignal): Promise<{ scanned: number; done: boolean }> {+ let scanned = 0;+ let after = 0;+ for (;;) {+ signal?.throwIfAborted();+ if (Date.now() > deadline) return { scanned, done: false };+ const pages = await engine.executeRaw<{ id: number; slug: string; type: string | null; title: string | null; compiled_truth: string | null;+ timeline: string | null; frontmatter: Record<string, unknown> | null; effective_date: unknown; effective_date_source: string | null; revision: string }>(+ `SELECT p.id, p.slug, p.type, p.title, p.compiled_truth, p.timeline, p.frontmatter, p.effective_date, p.effective_date_source,+ p.knowledge_revision::text AS revision+ FROM pages p LEFT JOIN owner_phrase_page_state s ON s.page_id = p.id+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.id > $2+ AND (s.page_id IS NULL OR s.revision IS DISTINCT FROM p.knowledge_revision OR s.version IS DISTINCT FROM $3)+ ORDER BY p.id LIMIT $4`, [sourceId, after, OWNER_PHRASE_SCAN_VERSION, SCAN_BATCH]);+ if (!pages.length) return { scanned, done: true };+ after = Number(pages[pages.length - 1]!.id);+ const rows = pages.map(p => {+ const scan = scanPage({ ...p, frontmatter: json<Record<string, unknown> | null>(p.frontmatter) });+ return { id: Number(p.id), rev: p.revision, page_date: scan.date, readings: scan.readings, agent: scan.agent, cues: scan.cues,+ descriptors: scan.descriptors, hits: scan.hits };+ });+ await executeRawJsonb(engine,+ `INSERT INTO owner_phrase_page_state (page_id, source_id, revision, version, page_date, readings, agent, cues, descriptors, hits, scanned_at)+ SELECT x.id, $1, x.rev::uuid, $2, x.page_date::date, ARRAY(SELECT jsonb_array_elements_text(x.readings)), x.agent, x.cues,+ ARRAY(SELECT jsonb_array_elements_text(x.descriptors)), x.hits, now()+ FROM jsonb_to_recordset(($3::jsonb)->'rows') AS x(id int, rev text, page_date text, readings jsonb, agent boolean, cues jsonb, descriptors jsonb, hits jsonb)+ ON CONFLICT (page_id) DO UPDATE SET revision = EXCLUDED.revision, version = EXCLUDED.version, page_date = EXCLUDED.page_date,+ readings = EXCLUDED.readings, agent = EXCLUDED.agent, cues = EXCLUDED.cues, descriptors = EXCLUDED.descriptors, hits = EXCLUDED.hits,+ scanned_at = EXCLUDED.scanned_at`,+ [sourceId, OWNER_PHRASE_SCAN_VERSION], [{ rows }]);+ scanned += rows.length;+ }+}++/** Identity groups among account pages (contract line 6): the lowest slug of a sibling group, else the page's own slug. */+function groupAccounts(accounts: EntityRow[], pack: PackTypes | null, policy: MentionPolicy): Map<string, string> {+ const bySubject = new Map<string, EntityRow[]>();+ for (const a of accounts) {+ const subject = normalizeAlias(titleName(a.title ?? ''));+ if (!subject) continue;+ const list = bySubject.get(subject) ?? [];+ list.push(a);+ bySubject.set(subject, list);+ }+ const out = new Map<string, string>(accounts.map(a => [a.slug, a.slug]));+ for (const members of bySubject.values()) {+ if (members.length < 2) continue;+ if (siblingVerdict(members, pack, policy) !== 'group') continue;+ const key = members.map(m => m.slug).sort()[0]!;+ for (const m of members) out.set(m.slug, key);+ }+ return out;+}++export interface OwnerPhraseModel {+ windows: OwnerWindow[];+ descriptors: Map<string, Set<string>>;+ links: Array<{ from_id: number; from_slug: string; to_slug: string; context: string; evidence: number[] }>;+ counters: Omit<OwnerPhraseCounters, 'links' | 'documents' | 'windows'>;+}++/** Statements, windows and resolved links of one source from its stored scans (no writes). */+export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>): Promise<OwnerPhraseModel> {+ const { sourceId } = opts;+ const entities = await engine.executeRaw<EntityRow>(+ `SELECT id, slug, type, title, frontmatter->>'identity' AS identity FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])`, [sourceId, opts.types]);+ const isPerson = (t: string | null) => canonicalTypeOf(t, opts.pack) === 'person';+ const accounts = entities.filter(e => !isPerson(e.type));+ const accountSlugs = new Set(accounts.map(a => a.slug));+ const personSlugs = new Set(entities.filter(e => isPerson(e.type)).map(e => e.slug));+ const groups = groupAccounts(accounts, opts.pack, opts.policy);+ const groupOf = (slug: string) => groups.get(slug) ?? slug;+ const accountEntries: NameEntry[] = [];+ const personEntries: NameEntry[] = [];+ const names = new Map<string, string[]>();+ for (const bucket of opts.gazetteer.values()) {+ for (const e of bucket) {+ if (e.source_id !== sourceId) continue;+ const entry: NameEntry = { slug: e.slug, title: e.title, tokens: e.tokens, ...(e.caseTokens ? { caseTokens: e.caseTokens } : {}) };+ if (accountSlugs.has(e.slug)) {+ accountEntries.push(entry);+ names.set(e.slug, [...(names.get(e.slug) ?? []), e.matchText ?? e.title]);+ } else if (personSlugs.has(e.slug)) personEntries.push(entry);+ }+ }+ for (const a of accounts) if (!names.has(a.slug) && a.title) names.set(a.slug, [a.title]);+ const accountIndex = buildNameIndex(accountEntries);+ const personIndex = buildNameIndex(personEntries);++ const states = await engine.executeRaw<StateRow>(+ `SELECT s.page_id, p.slug, s.page_date::text AS page_date, s.readings, s.agent, s.cues, s.descriptors, s.hits+ FROM owner_phrase_page_state s JOIN pages p ON p.id = s.page_id+ WHERE s.source_id = $1 AND p.deleted_at IS NULL+ AND (jsonb_array_length(s.cues) > 0 OR jsonb_array_length(s.hits) > 0 OR cardinality(s.descriptors) > 0)+ ORDER BY s.page_id`, [sourceId]);++ const descriptors = new Map<string, Set<string>>();+ const declared = new Map(states.filter(s => accountSlugs.has(s.slug)).map(s => [s.slug, s.descriptors ?? []]));+ for (const a of accounts) {+ const set = accountDescriptors(names.get(a.slug) ?? [], declared.get(a.slug) ?? []);+ const g = groupOf(a.slug);+ descriptors.set(g, new Set([...(descriptors.get(g) ?? []), ...set]));+ }+ const descriptorGroups = new Map<string, Set<string>>();+ for (const [g, set] of descriptors) for (const d of set) descriptorGroups.set(d, new Set([...(descriptorGroups.get(d) ?? []), g]));+ const descriptorAccounts = new Map<string, Set<string>>([...descriptorGroups].map(([d, gs]) => [d, gs.size === 1 ? new Set([[...gs][0]!]) : new Set(gs)]));++ const statements: Statement[] = [];+ for (const s of states) {+ const cues = json<CueLine[]>(s.cues);+ if (!cues.length) continue;+ statements.push(...parseStatements(cues, {+ page: { id: Number(s.page_id), slug: s.slug, date: s.page_date, agent: s.agent },+ selfAccount: accountSlugs.has(s.slug) ? s.slug : null,+ accounts: accountIndex, persons: personIndex, descriptorAccounts,+ }));+ }+ const windows = buildWindows(statements, groupOf);+ const descriptorsOf = (g: string) => descriptors.get(g) ?? new Set<string>();++ const links: OwnerPhraseModel['links'] = [];+ const counters = { unresolved: 0, ambiguous: 0 };+ for (const s of states) {+ const hits = json<PhraseHit[]>(s.hits);+ if (!hits.length) continue;+ const seen = new Set<string>();+ for (const hit of hits) {+ const 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) {+ if (r.reason === 'ambiguous' || r.reason === 'readings_disagree') counters.ambiguous++;+ else counters.unresolved++;+ continue;+ }+ const evidence = [...new Set(r.windows.flatMap(w => w.evidence.map(e => e.page_id)))].sort((a, b) => a - b);+ for (const to of r.accounts) {+ if (to === s.slug || seen.has(to)) continue;+ seen.add(to);+ links.push({ from_id: Number(s.page_id), from_slug: s.slug, to_slug: to, context: hit.surface, evidence });+ }+ }+ }+ return { windows, descriptors, links, counters };+}++function windowsHash(windows: OwnerWindow[], privateIds: Set<number>): string {+ const rows = windows.map(w => [w.group, w.accounts, w.owner, w.ownerName, w.from, w.to, w.startKnown,+ w.evidence.map(e => [e.page_id, e.line, e.kind, e.date]), w.evidence.filter(e => privateIds.has(e.page_id)).map(e => e.page_id)]);+ return createHash('sha256').update(JSON.stringify(rows)).digest('hex').slice(0, 16);+}++/** Run the owner-phrase pass for one source. Never throws for a build failure: it writes nothing and returns `failed`. */+export async function runOwnerPhrasePass(engine: BrainEngine, opts: OwnerPhrasePassOpts): Promise<OwnerPhrasePassResult> {+ const { sourceId } = opts;+ if (!opts.enabled) {+ const [had] = await engine.executeRaw<{ n: number }>(+ `SELECT (SELECT count(*) FROM owner_phrase_status WHERE source_id = $1)+ + (SELECT count(*) FROM owner_phrase_page_state WHERE source_id = $1)::int AS n`, [sourceId]);+ if (!Number(had?.n ?? 0)) {+ const [links] = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM links l JOIN pages f ON f.id = l.from_page_id WHERE f.source_id = $1 AND l.link_kind = 'owner_phrase'`, [sourceId]);+ if (!Number(links?.n ?? 0)) return emptyResult('off');+ }+ return { ...emptyResult('off'), removed: await disableSource(engine, sourceId) };+ }+ const result = emptyResult('complete');+ try {+ const scan = await scanDuePages(engine, sourceId, opts.deadline, opts.signal);+ result.scanned = scan.scanned;+ if (!scan.done) return { ...result, state: 'pending' };+ const model = await buildOwnerPhraseModel(engine, opts);+ result.unresolved = model.counters.unresolved;+ result.ambiguous = model.counters.ambiguous;+ result.windows = model.windows.length;+ const evidenceIds = [...new Set(model.windows.flatMap(w => w.evidence.map(e => e.page_id)))];+ return await engine.transaction(async tx => {+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [`gbrain:owner-phrase:${sourceId}`]);+ const [due] = await tx.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages p LEFT JOIN owner_phrase_page_state s ON s.page_id = p.id+ WHERE p.source_id = $1 AND p.deleted_at IS NULL+ AND (s.page_id IS NULL OR s.revision IS DISTINCT FROM p.knowledge_revision OR s.version IS DISTINCT FROM $2)`,+ [sourceId, OWNER_PHRASE_SCAN_VERSION]);+ if (Number(due?.n ?? 0) > 0) return { ...result, state: 'pending' as const };+ const privateIds = new Set(evidenceIds.length ? (await tx.executeRaw<{ id: number }>(+ `SELECT p.id FROM pages p WHERE p.id = ANY($1::int[]) AND NOT ${privatePagesFilterFragment('p')}`, [evidenceIds])).map(r => Number(r.id)) : []);+ const hash = windowsHash(model.windows, privateIds);+ const [status] = await tx.executeRaw<{ window_hash: string | null; generation: string }>(+ 'SELECT window_hash, generation::text AS generation FROM owner_phrase_status WHERE source_id = $1', [sourceId]);+ const generation = Number(status?.generation ?? 0) + (status?.window_hash === hash ? 0 : 1);+ if (status?.window_hash !== hash) {+ await tx.executeRaw('DELETE FROM owner_phrase_windows WHERE source_id = $1', [sourceId]);+ if (model.windows.length) {+ const rows = model.windows.map(w => ({+ group_key: w.group, account_slugs: w.accounts, owner_key: w.owner, owner_name: w.ownerName,+ descriptors: [...(model.descriptors.get(w.group) ?? [])].sort(), valid_from: w.from, valid_to: w.to, start_known: w.startKnown,+ evidence: w.evidence, evidence_page_ids: [...new Set(w.evidence.map(e => e.page_id))].sort((a, b) => a - b),+ private_page_id: w.evidence.map(e => e.page_id).filter(id => privateIds.has(id)).sort((a, b) => a - b)[0] ?? null,+ }));+ await executeRawJsonb(tx,+ `INSERT INTO owner_phrase_windows (source_id, group_key, account_slugs, owner_key, owner_name, descriptors, valid_from, valid_to,+ start_known, evidence, evidence_page_ids, private_page_id, generation)+ SELECT $1, x.group_key, ARRAY(SELECT jsonb_array_elements_text(x.account_slugs)), x.owner_key, x.owner_name,+ ARRAY(SELECT jsonb_array_elements_text(x.descriptors)), x.valid_from::date, x.valid_to::date, x.start_known, x.evidence,+ ARRAY(SELECT (jsonb_array_elements_text(x.evidence_page_ids))::int), x.private_page_id, $2+ FROM jsonb_to_recordset(($3::jsonb)->'rows') AS x(group_key text, account_slugs jsonb, owner_key text, owner_name text, descriptors jsonb,+ valid_from text, valid_to text, start_known boolean, evidence jsonb, evidence_page_ids jsonb, private_page_id int)`,+ [sourceId, generation], [{ rows }]);+ }+ }+ const existing = await tx.executeRaw<{ id: number; from_page_id: number; to_slug: string; origin_page_id: number | null; context: string; kind: string | null }>(+ `SELECT l.id, l.from_page_id, t.slug AS to_slug, l.origin_page_id, l.context, l.link_kind AS kind+ FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.source_id = $1 AND t.source_id = $1 AND l.from_page_id = ANY($2::int[])`,+ [sourceId, [...new Set([...model.links.map(l => l.from_id),+ ...(await tx.executeRaw<{ id: number }>(`SELECT DISTINCT l.from_page_id AS id FROM links l JOIN pages f ON f.id = l.from_page_id+ WHERE f.source_id = $1 AND l.link_kind = 'owner_phrase'`, [sourceId])).map(r => Number(r.id))])]]);+ const covered = new Set(existing.filter(r => r.kind !== 'owner_phrase').map(r => `${r.from_page_id}\0${r.to_slug}`));+ const slugById = new Map<number, string>();+ if (privateIds.size) for (const r of await tx.executeRaw<{ id: number; slug: string }>('SELECT id, slug FROM pages WHERE id = ANY($1::int[])', [[...privateIds]])) slugById.set(Number(r.id), r.slug);+ const want = new Map<string, { link: OwnerPhraseModel['links'][number]; origin: number | null }>();+ for (const l of model.links) {+ const key = `${l.from_id}\0${l.to_slug}`;+ if (covered.has(key) || want.has(key)) continue;+ want.set(key, { link: l, origin: l.evidence.find(id => privateIds.has(id)) ?? null });+ }+ const current = existing.filter(r => r.kind === 'owner_phrase');+ const keep = new Set<string>();+ const drop: number[] = [];+ for (const r of current) {+ const key = `${r.from_page_id}\0${r.to_slug}`;+ const w = want.get(key);+ if (w && !keep.has(key) && (r.origin_page_id == null ? null : Number(r.origin_page_id)) === w.origin && r.context === w.link.context) keep.add(key);+ else drop.push(Number(r.id));+ }+ if (drop.length) await tx.executeRaw('DELETE FROM links WHERE id = ANY($1::int[])', [drop]);+ const add: LinkBatchInput[] = [...want].filter(([key]) => !keep.has(key)).map(([, w]) => ({+ from_slug: w.link.from_slug, to_slug: w.link.to_slug, link_type: 'mentions', link_source: 'mentions', link_kind: 'owner_phrase',+ context: w.link.context, from_source_id: sourceId, to_source_id: sourceId,+ ...(w.origin != null ? { origin_slug: slugById.get(w.origin)!, origin_source_id: sourceId } : {}),+ }));+ const created = add.length ? await tx.addLinksBatch(add, { auditSite: 'extract.mentions' }) : 0; // gbrain-allow-direct-insert: owner-phrase pass — reconciling write of its own owner_phrase rows+ const documents = new Set([...want.values()].map(w => w.link.from_id)).size;+ await tx.executeRaw(+ `INSERT INTO owner_phrase_status (source_id, state, generation, window_hash, windows, links, documents, unresolved, ambiguous, last_pass_at, error, updated_at)+ VALUES ($1, 'complete', $2, $3, $4, $5, $6, $7, $8, now(), NULL, now())+ ON CONFLICT (source_id) DO UPDATE SET state = 'complete', generation = EXCLUDED.generation, window_hash = EXCLUDED.window_hash,+ windows = EXCLUDED.windows, links = EXCLUDED.links, documents = EXCLUDED.documents, unresolved = EXCLUDED.unresolved,+ ambiguous = EXCLUDED.ambiguous, last_pass_at = EXCLUDED.last_pass_at, error = NULL, updated_at = now()`,+ [sourceId, generation, hash, model.windows.length, want.size, documents, result.unresolved, result.ambiguous]);+ return { ...result, created, removed: drop.length, links: want.size, documents };+ });+ } catch (error) {+ if (opts.signal?.aborted) throw error;+ const message = error instanceof Error ? error.message : String(error);+ await engine.executeRaw(+ `INSERT INTO owner_phrase_status (source_id, state, error, updated_at) VALUES ($1, 'failed', $2, now())+ ON CONFLICT (source_id) DO UPDATE SET state = 'failed', error = EXCLUDED.error, updated_at = now()`, [sourceId, message]).catch(() => {});+ return { ...result, state: 'failed', error: message };+ }+}diff --git a/src/core/mentions/owner-phrase/scan.ts b/src/core/mentions/owner-phrase/scan.tsnew file mode 100644index 0000000000..210a882b41--- /dev/null+++ b/src/core/mentions/owner-phrase/scan.ts@@ -0,0 +1,220 @@+/**+ * Owner phrases, the per-page scan. Gazetteer-independent and pure: what a+ * page's own text says, stored per content revision in+ * `owner_phrase_page_state` and parsed against the current gazetteer when+ * windows are built (`statements.ts`), so a new entity page never forces a+ * rescan of every page.+ *+ * A scan keeps four things:+ * - cue lines: lines that may hold an ownership statement (a cue verb or+ * role noun, a correction cue, or a table whose header names an owner+ * column), with their 1-based line number;+ * - descriptor declarations the page makes about itself ("X is our freight+ * account", `Segment: freight`), used only if the page is an account;+ * - owner phrases ("Alice's freight account", "the freight book Alice+ * runs") with the owner surface, descriptor and line;+ * - the page's date readings: its own non-fallback date plus any other date+ * the page cites for itself (contract line 10).+ */++import { findDates, dayOf } from './dates.ts';++/** Bump to rescan every page's owner-phrase state once (scanner behavior change). */+export const OWNER_PHRASE_SCAN_VERSION = 1;++export interface CueLine { line: number; text: string }+export interface PhraseHit { owner: string; descriptor: string; noun: string; line: number; surface: string }+export interface PageScan {+ cues: CueLine[];+ descriptors: string[];+ hits: PhraseHit[];+ /** The page's own date (non-fallback) or null. */+ date: string | null;+ /** Other dates the page cites for itself, each different from `date`. */+ readings: string[];+ /** Statements on this page set no window (agent-written page). */+ agent: boolean;+}++export interface ScanInput {+ slug: string;+ type: string | null;+ title: string | null;+ compiled_truth: string | null;+ timeline: string | null;+ frontmatter: Record<string, unknown> | null;+ effective_date: unknown;+ 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 AGENT_TYPE_RE = /(?:^|[-_\s/])agent(?:$|[-_\s/])/i;++/** Personal and benefit accounts: a sentence about them holds no owner phrase (contract line 8). */+export const PERSONAL_ACCOUNT_RE = /\b(?:benefits?|hsa|fsa|401\(?k\)?|payroll|pension|retirement|savings|checking|bank|banking|login|log-in|password|username|e-?mail account|expense account|personal|reimbursements?|open enrollment|enrollment)\b/i;++const NAME = String.raw`[A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?`;+const NAME_RUN = String.raw`${NAME}(?: ${NAME}){0,2}`;+const DESC = String.raw`[A-Za-z][A-Za-z0-9&-]*(?: [A-Za-z][A-Za-z0-9&-]*)?`;+const NOUN = '(?:book of business|account|book|client|customer|relationship|portfolio)';+const POSSESSIVE_RE = new RegExp(String.raw`(?<![\w'’])(${NAME_RUN})['’]s (${DESC}) (${NOUN})(?![\w-])`, 'g');+const RUNS_RE = new RegExp(String.raw`\b[Tt]he (${DESC}) (account|book|client|customer|relationship) (?:that |which )?(${NAME_RUN}) (?:runs|handles|owns|manages|covers|leads|looks after|is running|is handling|is managing|is covering|is leading|has been running|runs point on)\b`, 'g');++/** Capitalized words that open sentences or labels and never name a person. */+export const NAME_STOPWORDS: ReadonlySet<string> = new Set(`a an the this that these those it its we our us i you your he she they their his her him them+ hi hello hey thanks thank dear please note notes update updates correction clarification fyi re fwd subject from to cc bcc date sent+ starting effective as on in at by for with after before since until through beginning also and but so then now today tomorrow yesterday+ next last per owner owners account accounts lead team status summary recap action item items agenda attendees meeting call ticket project+ handoff handover transition background context decision decisions belated actually going heads quick just reminder welcome congrats+ mr ms mrs dr csm ae am vp ceo cto cfo coo sales ops support customer success q1 q2 q3 q4 effective monday tuesday wednesday thursday+ friday saturday sunday january february march april may june july august september october november december jan feb mar apr jun jul aug+ sep 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));++/** Leading and trailing stop words of a capitalized run removed; empty when nothing is left. */+export function trimNameRun(run: string): string {+ const words = run.split(' ');+ while (words.length && NAME_STOPWORDS.has(words[0]!.toLowerCase())) words.shift();+ while (words.length && NAME_STOPWORDS.has(words[words.length - 1]!.toLowerCase())) words.pop();+ return words.join(' ');+}++function isAgentAuthored(type: string | null, fm: Record<string, unknown>): boolean {+ if (type && AGENT_TYPE_RE.test(type)) return true;+ for (const key of ['author_kind', 'written_by', 'author_type']) {+ const v = fm[key];+ if (typeof v === 'string' && v.trim().toLowerCase() === 'agent') return true;+ }+ return false;+}++const DESCRIPTOR_LABEL_RE = /^\s*(?:[-*]\s*)?(?:\*\*)?(?:segment|industry|vertical|sector|category|line of business|business line|descriptor)(?:\*\*)?\s*:\s*(?:\*\*)?([^|;,.()]+)/i;+const DESCRIPTOR_DECL_RES = [+ /\b(?:is|as) (?:our|the|a|an) ((?:[a-z][a-z0-9&-]*)(?: [a-z][a-z0-9&-]*)?) (?:account|client|customer)\b/gi,+ /\bknown (?:internally )?as the ((?:[a-z][a-z0-9&-]*)(?: [a-z][a-z0-9&-]*)?) (?:account|client|customer|book)\b/gi,+ /\b(?:we|everyone|people|the team) calls? (?:it|them|this) the ((?:[a-z][a-z0-9&-]*)(?: [a-z][a-z0-9&-]*)?) (?:account|client|customer|book)\b/gi,+];+const DESCRIPTOR_FILLER = new Set(['main', 'primary', 'key', 'big', 'biggest', 'largest', 'top', 'new', 'old', 'first', 'only', 'best', 'oldest',+ 'newest', 'own', 'other', 'strategic', 'favorite', 'favourite', 'current', 'former', 'next', 'last', 'same', 'whole', 'entire']);++function cleanDescriptor(raw: string): string | null {+ const words = raw.trim().toLowerCase().split(/\s+/).filter(Boolean);+ while (words.length && DESCRIPTOR_FILLER.has(words[0]!)) words.shift();+ if (!words.length || words.length > 2) return null;+ return words.join(' ');+}++function frontmatterDescriptors(fm: Record<string, unknown>): string[] {+ const out: string[] = [];+ for (const key of ['segment', 'industry', 'vertical', 'sector', 'category', 'descriptor', 'line_of_business']) {+ const v = fm[key];+ for (const item of Array.isArray(v) ? v : [v]) {+ if (typeof item !== 'string') continue;+ const d = cleanDescriptor(item.split(/[,;/]/)[0] ?? '');+ if (d) out.push(d);+ }+ }+ return out;+}++const OWNER_FRONTMATTER_KEYS = ['owner', 'account_owner', 'account_lead', 'account_manager', 'csm', 'ae'];++const READING_LABEL_RE = /^\s*(?:[-*]\s*)?(?:\*\*)?(?:date|sent|recorded|written|meeting date|call date|date of (?:call|meeting|visit))(?:\*\*)?\s*:/i;+const READING_PHRASE_RE = /\b(?:notes?|recap|summary|minutes|write-?up|debrief)(?: from| of| for| on)(?: the| our| my| this)?(?: \w+)?(?: call| meeting| sync| visit| review| session)?(?: on| from| of)? *$|\b(?:written|recorded|logged|filed)(?: up)?(?: on| late on)? *$/i;+const EVENT_REF_BEFORE_RE = /\b(?:the|our|that) *$/i;+const READING_TAIL_RE = /^(?:'s)? ?(?:call|meeting|sync|visit|review|session|check-in|discussion)\b/i;++/** Other dates the page cites for itself (contract line 10), each different from `date`. */+function citedReadings(slug: string, fm: Record<string, unknown>, lines: string[], date: string | null): string[] {+ const out = new Set<string>();+ for (const key of ['event_date', 'date']) {+ const d = dayOf(fm[key]);+ if (d && /^\d{4}-\d{2}-\d{2}$/.test(d)) out.add(d);+ }+ const base = slug.split('/').pop() ?? '';+ const slugDate = /^(\d{4}-\d{2}-\d{2})/.exec(base)?.[1];+ if (slugDate) out.add(slugDate);+ for (const raw of lines) {+ const label = READING_LABEL_RE.exec(raw);+ if (label) {+ const d = findDates(raw.slice(label[0].length), date)[0];+ if (d) out.add(d.iso);+ continue;+ }+ const belated = /\bbelated\b/i.test(raw);+ for (const d of findDates(raw, date)) {+ if (d.last !== d.iso) continue;+ const before = raw.slice(Math.max(0, d.index - 60), d.index);+ const eventRef = EVENT_REF_BEFORE_RE.test(before) && READING_TAIL_RE.test(raw.slice(d.end).trimStart());+ if (belated || eventRef || READING_PHRASE_RE.test(before)) out.add(d.iso);+ }+ }+ if (date) out.delete(date);+ return [...out].sort();+}++function phraseHits(lines: string[]): PhraseHit[] {+ const out: PhraseHit[] = [];+ lines.forEach((raw, i) => {+ if (!raw.includes("'") && !raw.includes('’') && !/\b[Tt]he\b/.test(raw)) return;+ for (const sentence of raw.split(/(?<=[.!?])\s+/)) {+ if (PERSONAL_ACCOUNT_RE.test(sentence)) continue;+ for (const m of sentence.matchAll(POSSESSIVE_RE)) {+ const owner = trimNameRun(m[1]!);+ if (!owner) continue;+ out.push({ owner, descriptor: m[2]!.toLowerCase(), noun: m[3]!.toLowerCase(), line: i + 1, surface: m[0] });+ }+ for (const m of sentence.matchAll(RUNS_RE)) {+ const owner = trimNameRun(m[3]!);+ if (!owner) continue;+ out.push({ owner, descriptor: m[1]!.toLowerCase(), noun: m[2]!.toLowerCase(), line: i + 1, surface: m[0] });+ }+ }+ });+ return out;+}++function cueLines(lines: string[]): CueLine[] {+ const out: CueLine[] = [];+ let tableKeep = false;+ lines.forEach((raw, i) => {+ const isTable = raw.trimStart().startsWith('|');+ if (isTable) {+ if (!tableKeep && !/^\s*\|[\s:|-]+\|?\s*$/.test(raw)) tableKeep = OWNER_COLUMN_RE.test(raw) || CUE_RE.test(raw);+ if (tableKeep) out.push({ line: i + 1, text: raw });+ return;+ }+ tableKeep = false;+ if (CUE_RE.test(raw)) out.push({ line: i + 1, text: raw });+ });+ return out;+}++/** Scan one page. Lines are numbered within `compiled_truth`, then `timeline` continues the count; the title is line 0. */+export function scanPage(page: ScanInput): PageScan {+ const fm = page.frontmatter ?? {};+ const body = `${page.compiled_truth ?? ''}${page.timeline ? `\n${page.timeline}` : ''}`;+ const lines = body.split('\n');+ const date = page.effective_date_source && page.effective_date_source !== 'fallback' ? dayOf(page.effective_date) : null;+ const cues = cueLines(lines);+ for (const key of OWNER_FRONTMATTER_KEYS) {+ const v = fm[key];+ for (const item of Array.isArray(v) ? v : [v]) if (typeof item === 'string' && item.trim()) cues.push({ line: 0, text: `Owner: ${item.trim()}` });+ }+ const descriptors = new Set(frontmatterDescriptors(fm));+ for (const raw of lines) {+ const label = DESCRIPTOR_LABEL_RE.exec(raw);+ if (label) { const d = cleanDescriptor(label[1]!); if (d) descriptors.add(d); }+ for (const re of DESCRIPTOR_DECL_RES) for (const m of raw.matchAll(re)) { const d = cleanDescriptor(m[1]!); if (d) descriptors.add(d); }+ }+ const titleHits = page.title ? phraseHits([page.title]).map(h => ({ ...h, line: 0 })) : [];+ return {+ cues,+ descriptors: [...descriptors].sort(),+ hits: [...titleHits, ...phraseHits(lines)],+ date,+ readings: date ? citedReadings(page.slug, fm, lines, date) : [],+ agent: isAgentAuthored(page.type, fm),+ };+}diff --git a/src/core/mentions/owner-phrase/statements.ts b/src/core/mentions/owner-phrase/statements.tsnew file mode 100644index 0000000000..a67473d4ea--- /dev/null+++ b/src/core/mentions/owner-phrase/statements.ts@@ -0,0 +1,343 @@+/**+ * Owner phrases: ownership statements parsed from a page's cue lines against+ * the current entity names (contract lines 2-5). Pure: the caller supplies+ * the account and person name indexes built from the gazetteer.+ *+ * A sentence is normalized before matching: account names, person names and+ * dates become placeholders (`⟦A0⟧`, `⟦P0⟧`, `⟦D0⟧`) and the rest is lower-cased,+ * so one small grammar of takeover, join, ongoing, end, stint and correction+ * forms covers any account and any person.+ */++import { tokenizeForScan } from '../../by-mention.ts';+import { RELATIVE_DATE_RE, addDays, findDates, type FoundDate } from './dates.ts';+import { NAME_STOPWORDS, trimNameRun, type CueLine } from './scan.ts';++export type StatementKind = 'takeover' | 'join' | 'ongoing' | 'end' | 'stint' | 'correction';++export interface Statement {+ kind: StatementKind;+ /** The new, current or ending owner as written (null on a correction that names no right owner). */+ owner: string | null;+ /** The predecessor named by "from A" / "A hands X to B" / "B replaces A". */+ from?: string;+ /** The owner a correction says was wrong. */+ wrong?: string;+ account: string;+ /** Effective day: start for takeover/join, the day an ongoing statement holds, the last day for end. */+ date: string | null;+ /** For stints: the first and last day (either may be null). */+ start?: string | null;+ end?: string | null;+ /** The date was written in the sentence (not the page's own date). */+ stated: boolean;+ /** Recording page and line. */+ page_id: number;+ slug: string;+ /** The recording page's own date. */+ recorded: string | null;+ line: number;+ text: string;+}++export interface NameEntry { slug: string; title: string; tokens: string[]; caseTokens?: string[] }+/** Names keyed by lowercase first token, longest first within a bucket. */+export type NameIndex = Map<string, NameEntry[]>;++export function buildNameIndex(entries: NameEntry[]): NameIndex {+ const index: NameIndex = new Map();+ for (const e of entries) {+ if (!e.tokens.length) continue;+ const bucket = index.get(e.tokens[0]!) ?? [];+ bucket.push(e);+ index.set(e.tokens[0]!, bucket);+ }+ for (const bucket of index.values()) bucket.sort((a, b) => b.tokens.length - a.tokens.length || a.slug.localeCompare(b.slug));+ return index;+}++interface Span { start: number; end: number; kind: 'A' | 'P' | 'D'; value: string }++/** Every non-overlapping name of `index` in `text` (maximal munch), as character spans. */+export function findNames(text: string, index: NameIndex): Array<{ start: number; end: number; entry: NameEntry }> {+ const tokens = tokenizeForScan(text);+ const out: Array<{ start: number; end: number; entry: NameEntry }> = [];+ for (let i = 0; i < tokens.length;) {+ const bucket = index.get(tokens[i]!.text);+ let hit: NameEntry | undefined;+ if (bucket) {+ hit = bucket.find(e => e.tokens.length <= tokens.length - i && e.tokens.every((t, k) => tokens[i + k]!.text === t+ && (!e.caseTokens || text.slice(tokens[i + k]!.offset, tokens[i + k]!.offset + tokens[i + k]!.length).normalize('NFC') === e.caseTokens[k])));+ }+ if (!hit) { i++; continue; }+ const last = tokens[i + hit.tokens.length - 1]!;+ out.push({ start: tokens[i]!.offset, end: last.offset + last.length, entry: hit });+ i += hit.tokens.length;+ }+ return out;+}++export interface ParseContext {+ page: { id: number; slug: string; date: string | null; agent: boolean };+ /** The page's own slug when it is an account page. */+ selfAccount: string | null;+ accounts: NameIndex;+ persons: NameIndex;+ /** Descriptor → account slugs that have it (for "the <d> account"). */+ descriptorAccounts: Map<string, Set<string>>;+}++const RUN_RE = /[A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?(?: [A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?){0,2}/g;++function cleanLine(raw: string): string {+ return raw+ .replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2')+ .replace(/\[\[([^\]]+)\]\]/g, '$1')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/[*_`]{1,3}/g, '')+ .replace(/[’‘]/g, "'")+ .replace(/^\s*(?:>\s*)+/, '')+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '');+}++interface Normalized { n: string; accounts: string[]; persons: string[]; dates: FoundDate[]; datePos: number[] }++function normalize(sentence: string, ctx: ParseContext): Normalized {+ const spans: Span[] = [];+ const taken = (s: number, e: number) => spans.some(x => s < x.end && e > x.start);+ for (const m of findNames(sentence, ctx.accounts)) if (!taken(m.start, m.end)) spans.push({ start: m.start, end: m.end, kind: 'A', value: m.entry.slug });+ for (const d of findDates(sentence, ctx.page.date)) if (!taken(d.index, d.end)) spans.push({ start: d.index, end: d.end, kind: 'D', value: JSON.stringify(d) });+ for (const m of findNames(sentence, ctx.persons)) if (!taken(m.start, m.end)) spans.push({ start: m.start, end: m.end, kind: 'P', value: m.entry.title });+ for (const m of sentence.matchAll(RUN_RE)) {+ const raw = m[0];+ const trimmed = trimNameRun(raw);+ if (!trimmed) continue;+ const start = m.index! + raw.indexOf(trimmed);+ const end = start + trimmed.length;+ if (taken(start, end)) continue;+ if (trimmed.split(' ').every(w => NAME_STOPWORDS.has(w.toLowerCase()))) continue;+ spans.push({ start, end, kind: 'P', value: trimmed });+ }+ spans.sort((a, b) => a.start - b.start);+ const accounts: string[] = [];+ const persons: string[] = [];+ const dates: FoundDate[] = [];+ const datePos: number[] = [];+ let n = '';+ let at = 0;+ for (const s of spans) {+ n += sentence.slice(at, s.start).toLowerCase();+ if (s.kind === 'A') { n += `⟦A${accounts.length}⟧`; accounts.push(s.value); }+ else if (s.kind === 'P') { n += `⟦P${persons.length}⟧`; persons.push(s.value); }+ else { datePos.push(n.length); n += `⟦D${dates.length}⟧`; dates.push(JSON.parse(s.value) as FoundDate); }+ at = s.end;+ }+ n += sentence.slice(at).toLowerCase();+ n = n.replace(/\s+/g, ' ').trim();+ // "the <descriptor> account" names an account when exactly one account has that descriptor.+ n = n.replace(/\bthe ([a-z][a-z0-9&-]*(?: [a-z][a-z0-9&-]*)?) (account|relationship|client|customer|book)\b/g, (whole, d: string) => {+ const owners = ctx.descriptorAccounts.get(d);+ if (!owners || owners.size !== 1) return whole;+ accounts.push([...owners][0]!);+ return `⟦A${accounts.length - 1}⟧`;+ });+ if (ctx.selfAccount) {+ n = n.replace(/\b(?:this|our|the) (?:account|relationship|client|customer)\b(?! ⟦)/g, () => {+ accounts.push(ctx.selfAccount!);+ return `⟦A${accounts.length - 1}⟧`;+ });+ }+ // Recompute date placeholder positions after the substitutions.+ datePos.length = 0;+ for (const m of n.matchAll(/⟦D(\d+)⟧/g)) datePos[Number(m[1])] = m.index!;+ return { n, accounts, persons, dates, datePos };+}++const P = (g: string) => `⟦P(?<${g}>\\d+)⟧`;+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')})?`;++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'))+ .replaceAll('{FROM}', FROM).replaceAll('{ROLE}', ROLE).replaceAll('{D1}', D('d1')).replaceAll('{D2}', D('d2')));+ return { kind, re: build(` ${ACC_CORE}`), reSelf: build(`(?: ${ACC_CORE})?`) };+}++const PATTERNS: Pattern[] = [+ pattern('stint', `{O} (?:ran|owned|managed|handled|covered|led|was on|had|ran point on|worked)(?: on)?{ACC},? (?:from|between) {D1} ?(?:to|until|through|thru|and|-|–|—) ?{D2}`),+ pattern('stint', `{O} (?:ran|owned|managed|handled|covered|led|was on|had|worked)(?: on)?{ACC},? (?:until|through|thru|till) {D2}`),+ pattern('join', `{O} (?:has |have |had )?(?:owned|run|handled|managed|covered|led|been on|been running|been the {ROLE} (?:for|on|of))(?: the)?{ACC} since {D1}`),+ pattern('takeover', `{O} (?:will |is going to |is set to |is slated to |is about to |is scheduled to )?(?:officially )?(?:take|takes|took|taking|is taking|has taken|have taken|will be taking) over(?: as (?:the )?(?:new )?{ROLE}(?: (?:of|for|on))?| ownership of| responsibility for| coverage of)?{ACC}{FROM}`),+ pattern('takeover', `{O} (?:will |is going to )?(?:inherits?|inherited|picks? up|picked up|is picking up|assumes?|assumed|is assuming)(?: ownership of| responsibility for| coverage of)?{ACC}{FROM}`),+ pattern('takeover', `{ACC} (?:is |was |has been |will be |gets |got |is being |are )?(?:officially )?(?:re)?(?:assigned|handed off|handed over|handed|passed|passes|transferred|transfers|moved|moving|moves|transitioned|transitioning|transitions|goes|went|going|switches|switched|shifts|shifted)(?: over| across)?(?: from ${P('from')})? to {O}`),+ pattern('takeover', `{F} (?:will |is going to )?(?:hands|hand|handed|is handing|has handed|passes|pass|passed|is passing|transfers|transfer|transferred|is transferring|is transitioning|transitions|transitioned)(?: off| over)?{ACC}(?: off| over)? to {O}`),+ pattern('takeover', `(?:moving|handing|passing|transferring|reassigning|assigning|transitioning|giving)(?: off| over)?{ACC}(?: over)?(?: from ${P('from')})? to {O}`),+ pattern('takeover', `{O} (?:replaces|replaced|is replacing|will replace) {F}(?: as (?:the )?{ROLE})? (?:on|for)${' '}${ACC_CORE}`),+ pattern('takeover', `{O} (?:is now|now is|becomes|became|will become|has become|is becoming|will be|is taking over as) (?:the )?(?:new )?{ROLE} (?:for|on|of|over)${' '}${ACC_CORE}`),+ 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('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}`),+ pattern('end', `{O} (?:steps|step|stepped|is stepping|will step) (?:away|back|down|off)(?: from)?{ACC}`),+ pattern('end', `{O} (?:is|was|will be|are) no longer (?:on|covering|handling|running|managing|leading|responsible for|working on|owning|the {ROLE} (?:for|on|of))(?: the)?{ACC}`),+ 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} 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)?`),+ pattern('ongoing', `{ACC} (?:account )?(?:owner|lead|manager|ae|csm|rep) is {O}`),+];++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 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/;+const WRONG_RES = [/(?:\bnot|rather than|instead of) (?:to )?⟦P(\d+)⟧/g, /⟦P(\d+)⟧ (?:did not|didn't|does not|doesn't|never|will not|won't|is not|isn't|was not|wasn't)\b/g];+const CUE_LED_RE = /(?:starting|effective|as of|beginning|begins|starts|from|on|effective on|effective as of)(?: on)? $/;++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);+ 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 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;+}++function tableRows(lines: CueLine[]): Array<{ line: number; cells: Record<string, string>; pairs: string[] }> {+ const out: Array<{ line: number; cells: Record<string, string>; pairs: string[] }> = [];+ let header: string[] | null = null;+ let prev = -2;+ for (const l of lines) {+ if (!l.text.trimStart().startsWith('|')) { header = null; continue; }+ const cells = l.text.trim().replace(/^\||\|$/g, '').split('|').map(c => cleanLine(c).trim());+ if (l.line !== prev + 1) header = null;+ prev = l.line;+ if (cells.every(c => /^:?-{2,}:?$/.test(c) || c === '')) continue;+ if (!header) { header = cells.map(c => c.toLowerCase()); continue; }+ const record: Record<string, string> = {};+ header.forEach((h, i) => { record[h] = cells[i] ?? ''; });+ out.push({ line: l.line, cells: record, pairs: header.length === 2 ? [`${cells[0] ?? ''}: ${cells[1] ?? ''}`] : [] });+ }+ return out;+}++function col(cells: Record<string, string>, re: RegExp): string | undefined {+ const key = Object.keys(cells).find(k => re.test(k));+ return key === undefined ? undefined : cells[key];+}++/** Every ownership statement on one page (agent-written pages return none). */+export function parseStatements(cues: CueLine[], ctx: ParseContext): Statement[] {+ if (ctx.page.agent) return [];+ const out: Statement[] = [];+ const base = { page_id: ctx.page.id, slug: ctx.page.slug, recorded: ctx.page.date };+ 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 owner = col(row.cells, /\b(?:owner|lead|ae|csm|manager|rep|am)\b/);+ 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;+ const person = findNames(owner, ctx.persons)[0]?.entry.title ?? owner.match(RUN_RE)?.map(trimNameRun).find(Boolean);+ if (!acctSlug || !person) continue;+ const start = startCell ? findDates(startCell, ctx.page.date)[0]?.iso ?? null : null;+ const endDate = endCell ? findDates(endCell, ctx.page.date)[0] : undefined;+ const end = endDate ? endDate.last : null;+ const text = Object.values(row.cells).join(' | ');+ if (start && end) out.push({ ...base, kind: 'stint', owner: person, account: acctSlug, date: start, start, end, stated: true, line: row.line, text });+ else if (start) out.push({ ...base, kind: 'takeover', owner: person, account: acctSlug, date: start, stated: true, line: row.line, text });+ 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 });+ }+ 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 sentences) out.push(...parseSentence(s.text, s.line, ctx));+ return out;+}++function parseSentence(sentence: string, line: number, ctx: ParseContext): Statement[] {+ if (sentence.endsWith('?')) return [];+ const norm = normalize(sentence, ctx);+ const { n } = norm;+ if (!n.includes('⟦P')) return [];+ 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 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())) }];+ 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())) }));+ }+ if (NEGATION_RE.test(n) || HYPOTHETICAL_RE.test(n)) return [];++ const label = LABEL_RE.exec(n);+ if (label?.groups) {+ const account = accountOf(label.groups.acc);+ if (!account) return [];+ const owner = norm.persons[Number(label.groups.o)]!;+ const rest = n.slice(label.index + label[0].length);+ const restDates = [...rest.matchAll(/⟦D(\d+)⟧/g)].map(m => norm.dates[Number(m[1])]!);+ const sinceCue = /\b(?:since|from|starting|as of|effective)\b/.test(rest);+ const untilCue = /\b(?:until|through|thru|till|to)\b/.test(rest);+ if (restDates.length >= 2) return [{ ...base, kind: 'stint', owner, account, date: restDates[0]!.iso, start: restDates[0]!.iso, end: restDates[1]!.last, stated: true }];+ if (restDates.length === 1 && (untilCue || label.groups.prev)) return [{ ...base, kind: 'stint', owner, account, date: restDates[0]!.last, start: null, end: restDates[0]!.last, stated: true }];+ if (label.groups.prev) return [];+ if (restDates.length === 1 && sinceCue) return [{ ...base, kind: 'takeover', owner, account, date: restDates[0]!.iso, stated: true }];+ return [{ ...base, kind: 'ongoing', owner, account, ...dated(null) }];+ }++ const out: Statement[] = [];+ const 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!;+ const e = s + m[0].length;+ if (used.some(([a, b]) => s < b && e > a)) continue;+ const g = m.groups ?? {};+ const account = accountOf(g.acc);+ if (!account || g.o === undefined) continue;+ used.push([s, e]);+ const owner = norm.persons[Number(g.o)]!;+ const from = g.from !== undefined ? norm.persons[Number(g.from)] : undefined;+ const d1 = g.d1 !== undefined ? norm.dates[Number(g.d1)]! : null;+ const d2 = g.d2 !== undefined ? norm.dates[Number(g.d2)]! : null;+ if (p.kind === 'stint') {+ out.push({ ...base, kind: 'stint', owner, account, date: d1?.iso ?? d2!.last, start: d1?.iso ?? null, end: d2!.last, stated: true });+ continue;+ }+ 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 });+ }+ }+ 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/owner-phrase/windows.ts b/src/core/mentions/owner-phrase/windows.tsnew file mode 100644index 0000000000..0d6649fa2c--- /dev/null+++ b/src/core/mentions/owner-phrase/windows.ts@@ -0,0 +1,217 @@+/**+ * Owner phrases: validity windows from ownership statements, and the+ * resolution of an owner phrase against them (contract lines 5, 6, 8-10).+ * Pure and deterministic.+ */++import { addDays } from './dates.ts';+import type { Statement } from './statements.ts';+import type { PhraseHit } from './scan.ts';++export interface Evidence { page_id: number; slug: string; line: number; kind: Statement['kind'] | 'implied'; date: string | null }++export interface OwnerWindow {+ group: string;+ /** Account pages the evidence names (members of `group`). */+ accounts: string[];+ /** Normalized owner key (lower-case full name when known). */+ owner: string;+ ownerName: string;+ /** Inclusive first day; null = no lower bound. */+ from: string | null;+ /** Inclusive last day; null = open-ended. */+ to: string | null;+ startKnown: boolean;+ evidence: Evidence[];+}++interface Stint {+ owner: string;+ ownerName: string;+ start: string | null;+ startKnown: boolean;+ bound: string | null;+ end: string | null;+ implicitEnd: boolean;+ accounts: Set<string>;+ evidence: Evidence[];+}++/** Owner surfaces → canonical keys: a one-word surface maps to the one full name it starts, when exactly one does. */+export function ownerKeys(surfaces: Iterable<string>): Map<string, { key: string; name: string }> {+ const all = [...new Set(surfaces)];+ const full = all.filter(s => s.includes(' '));+ const out = new Map<string, { key: string; name: string }>();+ for (const s of all) {+ if (!s.includes(' ')) {+ const firsts = [...new Set(full.filter(f => f.split(' ')[0]!.toLowerCase() === s.toLowerCase()).map(f => f.toLowerCase()))];+ if (firsts.length === 1) { out.set(s, { key: firsts[0]!, name: full.find(f => f.toLowerCase() === firsts[0])! }); continue; }+ }+ out.set(s, { key: s.toLowerCase(), name: s });+ }+ return out;+}++const KIND_ORDER: Record<string, number> = { stint: 0, correction: 0, ongoing: 1, join: 2, takeover: 3, end: 4 };++function evidenceOf(s: Statement, kind?: Evidence['kind']): Evidence {+ return { page_id: s.page_id, slug: s.slug, line: s.line, kind: kind ?? s.kind, date: s.date };+}++/** Corrections void the wrong owner's takeover/join/ongoing statements recorded up to the correction (contract line 5). */+export function applyCorrections(statements: Statement[], groupOf: (slug: string) => string): Statement[] {+ const corrections = statements.filter(s => s.kind === 'correction' && s.account);+ const voided = new Set<Statement>();+ const added: Statement[] = [];+ const keys = ownerKeys(statements.flatMap(s => [s.owner, s.from, s.wrong].filter((x): x is string => !!x)));+ const key = (name: string | null | undefined) => (name ? keys.get(name)?.key ?? name.toLowerCase() : null);+ for (const c of corrections) {+ const group = groupOf(c.account);+ const hits = statements.filter(s => s !== c && !voided.has(s) && (s.kind === 'takeover' || s.kind === 'join' || s.kind === 'ongoing')+ && groupOf(s.account) === group && key(s.owner) === key(c.wrong)+ && (s.recorded == null || c.recorded == null || s.recorded <= c.recorded));+ for (const h of hits) voided.add(h);+ if (!c.owner) continue;+ const anchor = c.stated ? c.date : hits.map(h => h.date).filter((d): d is string => !!d).sort()[0] ?? c.date;+ if (!anchor) continue;+ const from = hits.find(h => h.from)?.from;+ added.push({ ...c, kind: hits.some(h => h.kind !== 'ongoing') ? 'takeover' : 'ongoing', owner: c.owner, date: anchor, ...(from ? { from } : {}), wrong: undefined });+ }+ return [...statements.filter(s => s.kind !== 'correction' && !voided.has(s)), ...added];+}++/** Windows for every identity group from valid (dated) statements. */+export function buildWindows(statements: Statement[], groupOf: (slug: string) => string): OwnerWindow[] {+ const applied = applyCorrections(statements, groupOf).filter(s => s.date && s.owner && s.account);+ const keys = ownerKeys(applied.flatMap(s => [s.owner, s.from].filter((x): x is string => !!x)));+ const byGroup = new Map<string, Statement[]>();+ for (const s of applied) {+ const g = groupOf(s.account);+ const list = byGroup.get(g) ?? [];+ list.push(s);+ byGroup.set(g, list);+ }+ const out: OwnerWindow[] = [];+ for (const [group, list] of [...byGroup].sort((a, b) => a[0].localeCompare(b[0]))) {+ list.sort((a, b) => a.date!.localeCompare(b.date!) || KIND_ORDER[a.kind]! - KIND_ORDER[b.kind]!+ || (a.recorded ?? '').localeCompare(b.recorded ?? '') || a.page_id - b.page_id || a.line - b.line);+ const stints: Stint[] = [];+ const id = (name: string) => keys.get(name) ?? { key: name.toLowerCase(), name };+ const latestEndBefore = (day: string): string | null => {+ const ends = stints.map(s => s.end).filter((e): e is string => !!e && e < day).sort();+ return ends.length ? addDays(ends[ends.length - 1]!, 1) : null;+ };+ const covering = (owner: string | null, day: string) => stints.filter(s => (owner == null || s.owner === owner)+ && (s.start ?? s.bound ?? '0000-00-00') <= day && (s.end == null || day <= s.end));+ const newStint = (name: string, start: string | null, end: string | null, s: Statement, day: string): Stint => {+ const o = id(name);+ const stint: Stint = { owner: o.key, ownerName: o.name, start, startKnown: start != null, bound: start == null ? latestEndBefore(day) : null,+ end, implicitEnd: false, accounts: new Set([s.account]), evidence: [] };+ stints.push(stint);+ return stint;+ };+ const cite = (stint: Stint, s: Statement, kind?: Evidence['kind']) => {+ stint.accounts.add(s.account);+ if (!stint.evidence.some(e => e.page_id === s.page_id && e.line === s.line)) stint.evidence.push(evidenceOf(s, kind));+ };+ for (const s of list) {+ const day = s.date!;+ const o = id(s.owner!);+ if (s.kind === 'stint') {+ const start = s.start ?? null;+ const end = s.end ?? null;+ const overlap = stints.find(x => x.owner === o.key && (x.end == null || start == null || start <= x.end)+ && ((x.start ?? x.bound ?? '0000-00-00') <= (end ?? '9999-12-31')));+ if (overlap) {+ if (start && (overlap.start == null || start < overlap.start)) { overlap.start = start; overlap.startKnown = true; }+ if (end && (overlap.end == null || overlap.implicitEnd || end > overlap.end)) { overlap.end = end; overlap.implicitEnd = false; }+ cite(overlap, s);+ } else cite(newStint(s.owner!, start, end, s, end ?? day), s);+ continue;+ }+ if (s.kind === 'end') {+ const mine = stints.filter(x => x.owner === o.key && (x.start ?? x.bound ?? '0000-00-00') <= day).pop();+ if (mine && (mine.end == null || mine.implicitEnd)) { mine.end = day; mine.implicitEnd = false; cite(mine, s); }+ else if (mine && mine.end != null && mine.end >= day) cite(mine, s);+ else if (!mine) cite(newStint(s.owner!, null, day, s, day), s);+ continue;+ }+ if (s.kind === 'ongoing') {+ const mine = covering(o.key, day)[0];+ if (mine) { cite(mine, s); continue; }+ if (covering(null, day).length) continue;+ cite(newStint(s.owner!, null, null, s, day), s);+ continue;+ }+ if (s.kind === 'takeover') {+ const prevDay = addDays(day, -1);+ const fromKey = s.from ? id(s.from).key : null;+ for (const x of stints) {+ if (x.owner === o.key || x.end != null) continue;+ if (fromKey && x.owner !== fromKey) continue;+ if ((x.start ?? x.bound ?? '0000-00-00') > prevDay) continue;+ x.end = prevDay;+ x.implicitEnd = true;+ cite(x, s, 'implied');+ }+ if (fromKey && !covering(fromKey, prevDay).length) {+ const pred = newStint(s.from!, null, prevDay, s, prevDay);+ pred.implicitEnd = true;+ cite(pred, s, 'implied');+ }+ }+ const mine = covering(o.key, day)[0];+ if (mine) cite(mine, s);+ else cite(newStint(s.owner!, day, null, s, day), s);+ }+ for (const x of stints) {+ out.push({ group, accounts: [...x.accounts].sort(), owner: x.owner, ownerName: x.ownerName, from: x.start ?? x.bound,+ to: x.end, startKnown: x.startKnown, evidence: x.evidence });+ }+ }+ return out;+}++export type Resolution =+ | { linked: true; group: string; accounts: string[]; windows: OwnerWindow[] }+ | { linked: false; reason: 'no_page_date' | 'no_owner' | 'outside_window' | 'ambiguous' | 'readings_disagree' };++/** Whether a phrase's owner surface names a window's owner (one word: first name; longer: the full name). */+export function ownerMatches(surface: string, window: Pick<OwnerWindow, 'owner'>): boolean {+ const s = surface.toLowerCase().split(/\s+/);+ const w = window.owner.split(/\s+/);+ if (s.length === 1 || w.length === 1) return s[0] === w[0];+ return s.join(' ') === w.join(' ');+}++/** Resolve one owner phrase on a document dated `date` (plus its other readings) against the windows (contract lines 9-10). */+export function resolvePhrase(hit: Pick<PhraseHit, 'owner' | 'descriptor'>, date: string | null, readings: string[],+ windows: OwnerWindow[], descriptorsOf: (group: string) => ReadonlySet<string>): Resolution {+ if (!date) return { linked: false, reason: 'no_page_date' };+ const owned = windows.filter(w => ownerMatches(hit.owner, w) && descriptorsOf(w.group).has(hit.descriptor));+ if (!owned.length) return { linked: false, reason: 'no_owner' };+ let chosen: string | null = null;+ let chosenWindows: OwnerWindow[] = [];+ for (const day of [date, ...readings]) {+ const live = owned.filter(w => (w.from == null || w.from <= day) && (w.to == null || day <= w.to));+ const groups = [...new Set(live.map(w => w.group))];+ if (!groups.length) return { linked: false, reason: day === date ? 'outside_window' : 'readings_disagree' };+ if (groups.length > 1) return { linked: false, reason: 'ambiguous' };+ if (chosen && chosen !== groups[0]) return { linked: false, reason: 'readings_disagree' };+ if (!chosen) { chosen = groups[0]!; chosenWindows = live; }+ }+ return { linked: true, group: chosen!, accounts: [...new Set(chosenWindows.flatMap(w => w.accounts))].sort(), windows: chosenWindows };+}++const NAME_SUFFIXES = new Set(['inc', 'llc', 'ltd', 'co', 'corp', 'corporation', 'company', 'group', 'holdings', 'plc', 'gmbh', 'sa', 'ag', 'lp', 'llp',+ 'the', 'and', 'of', 'account', 'accounts', 'client', 'customer']);++/** An account's descriptors: words of its names without corporate suffixes, plus declared descriptors (contract line 7). */+export function accountDescriptors(names: string[], declared: string[]): Set<string> {+ const out = new Set<string>(declared.map(d => d.toLowerCase()));+ for (const name of names) {+ const subject = name.includes(': ') ? name.slice(name.lastIndexOf(': ') + 2) : name;+ for (const w of subject.toLowerCase().split(/[^\p{L}\p{N}&-]+/u)) if (w.length >= 2 && !NAME_SUFFIXES.has(w) && !/^\d+$/.test(w)) out.add(w);+ }+ return out;+}diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 0711b7771f..25fbe5d362 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -54,6 +54,7 @@ import { normalizeAliasList } from '../search/alias-normalize.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { readOwnerPhrasesEnabled, runOwnerPhrasePass, type OwnerPhrasePassResult } from './owner-phrase/pass.ts';/** Bump to rescan every page's mentions once (gazetteer or scanner behavior change). */export const MENTION_EXTRACTOR_VERSION = 5;@@ -79,6 +80,8 @@ export interface MentionPassResult {remaining: number;state: MentionState;error?: string;+ /** Owner-phrase pass (`mentions.owner_phrases`), summed over sources; absent when it is off and had nothing to remove. */+ ownerPhrases?: OwnerPhrasePassResult;}export interface MentionPassOpts {@@ -135,13 +138,25 @@ async function sourcesInScope(engine: BrainEngine, sourceId?: string): Promise<sreturn rows.map(r => r.id);}-function policyFingerprint(types: string[], crossSource: boolean, policy: MentionPolicy): string {+/** `ownerPhrases` enters the hash only when on, so a brain without the key keeps its fingerprint. */+export function policyFingerprint(types: string[], crossSource: boolean, policy: MentionPolicy, ownerPhrases = false): string {return createHash('sha256').update(JSON.stringify({types, crossSource, ignore: [...policy.ignore].map(n => n.toLowerCase()).sort(),aliasDeny: [...policy.aliasDeny].map(n => n.toLowerCase()).sort(), multiword: policy.multiwordAliases, siblings: policy.siblingMerge,+ ...(ownerPhrases ? { ownerPhrases: true } : {}),})).digest('hex').slice(0, 16);}+function addOwnerPhrases(result: MentionPassResult, r: OwnerPhrasePassResult): void {+ if (r.state === 'off' && !r.removed) return;+ const sum = result.ownerPhrases;+ if (!sum) { result.ownerPhrases = { ...r }; return; }+ const rank = { failed: 3, pending: 2, complete: 1, off: 0 } as const;+ for (const k of ['scanned', 'created', 'removed', 'links', 'documents', 'unresolved', 'ambiguous', 'windows'] as const) sum[k] += r[k];+ if (rank[r.state] > rank[sum.state]) sum.state = r.state;+ if (r.error) sum.error = r.error;+}+async function writeStatus(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, patch: {state: MentionState; pending?: number; error?: string | null; lastPassAt?: string | null; bumpGeneration?: boolean; fingerprint?: string | null;}): Promise<void> {@@ -447,21 +462,26 @@ async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer:[pages.map(p => p.id)])).map(r => [Number(r.id), r.revision]));const fresh = pages.filter(p => current.get(Number(p.id)) === p.revision);if (!fresh.length) return { fresh: 0, created: 0, removed: 0 };- const rows = await tx.executeRaw<{ id: number; from_page_id: number; to_slug: string; to_source_id: string; plain: boolean }>(+ const rows = await tx.executeRaw<{ id: number; from_page_id: number; to_slug: string; to_source_id: string; plain: boolean; owner_phrase: boolean }>(`SELECT l.id, l.from_page_id, t.slug AS to_slug, t.source_id AS to_source_id,- (l.link_source = 'mentions' AND (l.link_kind IS NULL OR l.link_kind = 'plain')) AS plain+ (l.link_source = 'mentions' AND (l.link_kind IS NULL OR l.link_kind = 'plain')) AS plain,+ (l.link_kind = 'owner_phrase') AS owner_phraseFROM links l JOIN pages t ON t.id = l.to_page_id WHERE l.from_page_id = ANY($1::int[])`,[fresh.map(p => p.id)]);const existing = rows.filter(r => r.plain);// One link per page pair: a pair another producer already links (markdown, frontmatter, typed_ner, manual) gets no plain mention.// A cross-source mention is also covered by an explicit link to the same slug in any source (the resolver may pick another twin).- const covered = new Set(rows.filter(r => !r.plain).flatMap(r => [`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`, `${r.from_page_id}\0*\0${r.to_slug}`]));+ // Owner-phrase rows cover nothing: a plain mention of the same pair replaces them (owner-phrase/pass.ts then skips the pair).+ const covered = new Set(rows.filter(r => !r.plain && !r.owner_phrase).flatMap(r => [`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`, `${r.from_page_id}\0*\0${r.to_slug}`]));const pageSource = new Map(fresh.map(p => [Number(p.id), p.source_id]));const want = new Set(fresh.flatMap(p => (found.get(Number(p.id)) ?? []).filter(m => !covered.has(`${p.id}\0${m.source_id}\0${m.slug}`) && !(m.source_id !== pageSource.get(Number(p.id)) && covered.has(`${p.id}\0*\0${m.slug}`))).map(m => `${p.id}\0${m.source_id}\0${m.slug}`)));const have = new Set(existing.map(r => `${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`));const drop = existing.filter(r => !want.has(`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`)).map(r => Number(r.id));+ const displaced = rows.filter(r => r.owner_phrase && want.has(`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`)+ && !have.has(`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`)).map(r => Number(r.id));+ if (displaced.length) await tx.executeRaw('DELETE FROM links WHERE id = ANY($1::int[])', [displaced]);if (drop.length) await tx.executeRaw('DELETE FROM links WHERE id = ANY($1::int[])', [drop]);const add: LinkBatchInput[] = fresh.flatMap(p => (found.get(Number(p.id)) ?? []).filter(m => want.has(`${p.id}\0${m.source_id}\0${m.slug}`) && !have.has(`${p.id}\0${m.source_id}\0${m.slug}`))@@ -494,9 +514,13 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOptsconst deadline = opts.deadline ?? Infinity;const passStart = new Date().toISOString();const policy = await readMentionPolicy(engine);+ const ownerPhrases = await readOwnerPhrasesEnabled(engine);const sources = await sourcesInScope(engine, opts.sourceId);const managed = await managedPersistenceEnabled(engine);if (!policy.enabled) {+ for (const sourceId of sources) {+ addOwnerPhrases(result, await runOwnerPhrasePass(engine, { sourceId, gazetteer: new Map(), types: [], pack: null, policy, enabled: false, deadline }));+ }const status = new Map((await engine.executeRaw<{ source_id: string; state: string }>('SELECT source_id, state FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources])).map(r => [r.source_id, r.state]));for (const sourceId of sources) {@@ -508,9 +532,13 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts}const allowCrossSource = await isCrossSourceLinksEnabled(engine);const types = new Map<string, string[]>();+ const packs = new Map<string, PackTypes | null>();let gazetteer: Gazetteer;try {- for (const sourceId of sources) types.set(sourceId, linkableTypesFor(await loadSourcePack(engine, sourceId, { strict: true }), policy));+ for (const sourceId of sources) {+ packs.set(sourceId, await loadSourcePack(engine, sourceId, { strict: true }));+ types.set(sourceId, linkableTypesFor(packs.get(sourceId)!, policy));+ }gazetteer = await buildGazetteer(engine, { policy, strict: true });} catch (error) {const message = error instanceof Error ? error.message : String(error);@@ -518,7 +546,7 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOptsreturn { ...result, state: 'failed', error: message, remaining: await countMentionDuePages(engine, opts.sourceId) };}const allSources = allowCrossSource ? (await sourcesInScope(engine)) : [];- const fingerprints = new Map<string, string>(sources.map(s => [s, policyFingerprint(types.get(s)!, allowCrossSource, policy)]));+ const fingerprints = new Map<string, string>(sources.map(s => [s, policyFingerprint(types.get(s)!, allowCrossSource, policy, ownerPhrases)]));const stored = new Map((await engine.executeRaw<{ source_id: string; policy_fingerprint: string | null }>('SELECT source_id, policy_fingerprint FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources])).map(r => [r.source_id, r.policy_fingerprint]));@@ -551,6 +579,8 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts}for (const sourceId of sources) {await reconcileSource(engine, sourceId, gazetteer, allowCrossSource ? allSources : [sourceId], allowCrossSource, opts, deadline, result);+ addOwnerPhrases(result, await runOwnerPhrasePass(engine, { sourceId, gazetteer, types: types.get(sourceId)!, pack: packs.get(sourceId) ?? null,+ policy, enabled: ownerPhrases, deadline, signal: opts.signal }));const pending = await countIndexDuePages(engine, sourceId, types.get(sourceId)!);result.remaining += pending;await writeStatus(engine, sourceId, { state: pending > 0 ? 'pending' : 'complete', pending, error: null, lastPassAt: passStart });diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex c2834fa565..7f236522aa 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -102,6 +102,9 @@ export const GRADUATION_INVENTORY: Inventory = {carry('op_checkpoint_paths', 'operational', 'Resumable operation checkpoints.'),carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),carry('open_loops', 'user_data', 'Open loops and their status.'),+ carry('owner_phrase_page_state', 'operational', 'Owner phrases: per-page scan watermark; without it every page is rescanned once.'),+ carry('owner_phrase_status', 'operational', 'Owner phrases: per-source pass state and firing counters.'),+ carry('owner_phrase_windows', 'operational', 'Owner phrases: validity windows rebuilt from page statements on every pass.'),carry('page_aliases', 'user_data', 'Page aliases.'),carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 0daa221e71..12b4ad2b29 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -202,7 +202,7 @@ CREATE TABLE IF NOT EXISTS links (link_type TEXT NOT NULL DEFAULT '',context TEXT NOT NULL DEFAULT '',link_source TEXT CHECK (link_source IS NULL OR (link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*\$' AND char_length(link_source) <= 64)),- link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner')),+ link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner', 'owner_phrase')),origin_page_id INTEGER REFERENCES pages(id) ON DELETE SET NULL,origin_field TEXT,resolution_type TEXT CHECK (resolution_type IS NULL OR resolution_type IN ('qualified', 'unqualified')),diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex e59fc584fa..f5e85a64ed 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -528,7 +528,9 @@ CREATE TABLE IF NOT EXISTS links (-- Codex finding #12 design: keep link_source stable; add link_kind-- so callers can distinguish without breaking existing mentions queries.-- NULL = legacy / unknown / pre-v98 row (semantically 'plain').- link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner')),+ -- 'owner_phrase': a document naming an account by its owner phrase inside+ -- the owner's validity window (src/core/mentions/owner-phrase/).+ link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner', 'owner_phrase')),origin_page_id INTEGER REFERENCES pages(id) ON DELETE SET NULL,origin_field TEXT,-- v0.18.0 Step 4: 'qualified' when the link was written asdiff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 2f887f8c54..e5b395aed4 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 239;+export const LATEST_SCHEMA_VERSION = 240;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex f2297d1e85..4baa6470cc 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -240,6 +240,7 @@ import { v236 } from './v236-open-loops-counterparty-source.ts';import { v237 } from './v237-facts-question-recall-indexes.ts';import { v238 } from './v238-persistence-client-request-id.ts';import { v239 } from './v239-extract-rollup-halt-reasons.ts';+import { v240 } from './v240-owner-phrase-windows.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -478,4 +479,5 @@ export const MIGRATIONS: Migration[] = [v237,v238,v239,+ v240,];diff --git a/src/core/schema-migrations/v240-owner-phrase-windows.ts b/src/core/schema-migrations/v240-owner-phrase-windows.tsnew file mode 100644index 0000000000..dd2bc26e13--- /dev/null+++ b/src/core/schema-migrations/v240-owner-phrase-windows.ts@@ -0,0 +1,83 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Owner phrases (src/core/mentions/owner-phrase/, docs/guides/owner-phrases.md):+// - links.link_kind widens to 'owner_phrase': owner-phrase links stay+// link_source='mentions', so every ranking reader that excludes mentions+// excludes them too. The CHECK is replaced under its default name+// (links_link_kind_check, the name both the v101 column add and the+// fresh-install inline CHECK get); existing rows satisfy the wider list.+// - owner_phrase_page_state: per page, the content revision and scan version+// its cue lines, self-declared descriptors, owner phrases and date readings+// were scanned at.+// - owner_phrase_windows: one row per (identity group, owner) stint with its+// inclusive bounds and evidence pages; never page_aliases.+// - owner_phrase_status: one row per source (state, generation, window hash,+// firing counters).+// Off by default (`mentions.owner_phrases`); the tables stay empty until the+// mention pass runs with the key on.+export const v240: Migration = {+ version: 240,+ name: 'owner_phrase_windows',+ idempotent: true,+ sql: `+ ALTER TABLE links DROP CONSTRAINT IF EXISTS links_link_kind_check;+ ALTER TABLE links ADD CONSTRAINT links_link_kind_check+ CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner', 'owner_phrase'));+ CREATE TABLE IF NOT EXISTS owner_phrase_page_state (+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ revision UUID,+ version INTEGER NOT NULL,+ page_date DATE,+ readings TEXT[] NOT NULL DEFAULT '{}',+ agent BOOLEAN NOT NULL DEFAULT false,+ cues JSONB NOT NULL DEFAULT '[]'::jsonb,+ descriptors TEXT[] NOT NULL DEFAULT '{}',+ hits JSONB NOT NULL DEFAULT '[]'::jsonb,+ scanned_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ CREATE INDEX IF NOT EXISTS owner_phrase_page_state_source_idx ON owner_phrase_page_state (source_id);+ CREATE TABLE IF NOT EXISTS owner_phrase_windows (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ group_key TEXT NOT NULL,+ account_slugs TEXT[] NOT NULL,+ owner_key TEXT NOT NULL,+ owner_name TEXT NOT NULL,+ descriptors TEXT[] NOT NULL DEFAULT '{}',+ valid_from DATE,+ valid_to DATE,+ start_known BOOLEAN NOT NULL,+ evidence JSONB NOT NULL DEFAULT '[]'::jsonb,+ evidence_page_ids INTEGER[] NOT NULL DEFAULT '{}',+ private_page_id INTEGER REFERENCES pages(id) ON DELETE SET NULL,+ generation BIGINT NOT NULL DEFAULT 0+ );+ CREATE INDEX IF NOT EXISTS owner_phrase_windows_group_idx ON owner_phrase_windows (source_id, group_key);+ CREATE INDEX IF NOT EXISTS owner_phrase_windows_accounts_idx ON owner_phrase_windows USING GIN (account_slugs);+ CREATE TABLE IF NOT EXISTS owner_phrase_status (+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,+ state TEXT NOT NULL CHECK (state IN ('complete','pending','failed')),+ generation BIGINT NOT NULL DEFAULT 0,+ window_hash TEXT,+ windows INTEGER NOT NULL DEFAULT 0,+ links INTEGER NOT NULL DEFAULT 0,+ documents INTEGER NOT NULL DEFAULT 0,+ unresolved INTEGER NOT NULL DEFAULT 0,+ ambiguous INTEGER NOT NULL DEFAULT 0,+ last_pass_at TIMESTAMPTZ,+ error TEXT,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THEN+ ALTER TABLE owner_phrase_page_state ENABLE ROW LEVEL SECURITY;+ ALTER TABLE owner_phrase_windows ENABLE ROW LEVEL SECURITY;+ ALTER TABLE owner_phrase_status ENABLE ROW LEVEL SECURITY;+ END IF;+ END $rls$;+ `,+};diff --git a/src/schema.sql b/src/schema.sqlindex dd1d2724de..a09e62d5c7 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -524,7 +524,9 @@ CREATE TABLE IF NOT EXISTS links (-- Codex finding #12 design: keep link_source stable; add link_kind-- so callers can distinguish without breaking existing mentions queries.-- NULL = legacy / unknown / pre-v98 row (semantically 'plain').- link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner')),+ -- 'owner_phrase': a document naming an account by its owner phrase inside+ -- the owner's validity window (src/core/mentions/owner-phrase/).+ link_kind TEXT CHECK (link_kind IS NULL OR link_kind IN ('plain', 'typed_ner', 'owner_phrase')),origin_page_id INTEGER REFERENCES pages(id) ON DELETE SET NULL,origin_field TEXT,-- v0.18.0 Step 4: 'qualified' when the link was written as