Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Revert "Remove F5 owner phrases from Part 1: failed the preregistered d1b gate"

garrytan3391a72d7847
diff --git a/TODOS.md b/TODOS.md
index 29e6b9b12e..43c64cf616 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -4,7 +4,7 @@
Context: gbrain-evals `docs/plans/2026-10-07-cat40-hard-fix/PLAN.md`; this wave fixes document retrieval only.
-- [ ] **P1 — Owner-phrase resolution with validity windows (deferred F1.3, C4).** **What:** references like "Dana Example's freight account" depend on who owned the account on that date; no extractor produces owner or handoff facts from page text. **Design:** the card gains `known_as` rows with each owner phrase's validity window, and the mention index links documents that use the phrase inside the window. **Gate:** ship only after a measured design: on development data, the share of needed owner-phrase documents an agent sees rises and no Cat 40 family regresses against the wave's development round. **First attempt (F5, removed before the Part 1 merge):** owner-phrase windows, `owner_phrase` mention links and card `known_as` rows failed the preregistered d1b gate: the agent saw no more of the needed owner-phrase documents (+0.2 pp, interval −3.3 to +3.6; gbrain-evals `docs/benchmarks/2026-10-13-cat40-dev-d1b/`). Control already finds 81% of them through search, and F5 surfaced documents only through F1 records in the all-on arm. A next design has to reach the remaining documents search misses. **Effort:** L. **Priority:** P1.
+- [ ] **P1 — Owner-phrase resolution with validity windows (deferred F1.3, C4).** **What:** references like "Dana Example's freight account" depend on who owned the account on that date; no extractor produces owner or handoff facts from page text. **Design:** the card gains `known_as` rows with each owner phrase's validity window, and the mention index links documents that use the phrase inside the window. **Gate:** ship only after a measured design: on development data, the share of needed owner-phrase documents an agent sees rises and no Cat 40 family regresses against the wave's development round. **Effort:** L. **Priority:** P1.
- [ ] **P1 — H5 merge-chain recall.** **What:** recall should follow "A now uses B's discount code" redirections to B's current value, and corrections of B. **Gate:** H5 completions on development data at or above the fs arm. **Effort:** M. **Priority:** P1.
- [ ] **P2 — Notice hygiene for unattended agents.** **What:** first-run ask and coaching notices ride on every session's tool results (498 results in the held-out run). **Gate:** share of tool results carrying notices drops with no loss in safety-notice delivery, measured on a Cat 40 development run. **Effort:** M. **Priority:** P2.
- [ ] **P3 — Opt-in LLM alias extraction.** **What:** names declared only in free prose without a cue ("we just say Copper Fox") are not parsed; the card excerpt shows them. **Fix:** an opt-in, spend-gated extractor that proposes aliases with their source line. **Gate:** precision on a labeled real-brain sample at a Wilson 95% lower bound of 85% or more. **Effort:** M. **Priority:** P3.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index a3828eb35c..191873afe3 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.
- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.
-- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.
+- `src/core/link-ranking-policy.ts` — the link ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `NON_RANKING_LINK_KINDS` (`owner_phrase`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer; owner-phrase invariance in `test/owner-phrase-pass.test.ts`.
- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index d6a3d2350c..a4f197e216 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -11,6 +11,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. Stored aliases and card identity lines read declarations with `anchored: true` (a cue must attach to the page itself; search's per-result `aliasDeclarations` scan reads them all). `titleSubject` (text after the last `: `), `declarationsIn` (each declaration with its line: prose cues, label and value lines and table rows whose label names an alias field (also a label opening a later sentence of a line, alias noun within its first two words, at most 7 words), the quoted-only "calls it" cue, a quoted defined term right after the page's own name; a capture is a quoted name or a run of up to 4 capitalized or code tokens ending at punctuation, a lowercase word or the line end, rejected on a possessive, a run of only common words or a cue after a relational noun; linear in the line length), `declaredNames` (its post-filtered names, shared with search's `aliasDeclarations`), `deriveEntityAliases(page, {multiword, deny})` (subject `origin='subject'`, declarations `origin='declared'` with their lines, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`; `mentions.alias_deny` and frontmatter `alias_deny` reject as `denied`). `aliasRejection`: under 4 characters (unless a short code the page declares for itself: a declaration marked `selfCode`), a generic word, or the first word of the page's own multi-word name. Rejections are returned with their line for explain. Tests: `test/mentions-policy-aliases.test.ts`.
- `src/core/mentions/short-codes.ts` — `isShortCode` (2-3 letters or digits with a capital, not in `SHORT_CODE_STOPLIST` of common capitals and business acronyms, compared upper-cased). `declarationsIn` marks a short code `selfCode` when an alias label or an `also called` / `a.k.a.` / `known as` / `short for` cue declares it in a sentence naming nothing before the cue but the page (empty, a pronoun or an own name); `aliasRejection` lets it through and `by-mention.ts` keeps a `declared`, `case_sensitive` short code in the gazetteer, matched only as written. Leaf module (aliases.ts imports by-mention.ts). Tests: `test/mentions-policy-aliases.test.ts`, `test/mentions-pass.test.ts`.
- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list, `mentions.alias_deny`, `mentions.multiword_aliases`, `mentions.sibling_merge`) marks every page due and recounts `pending`; the status row's `policy_fingerprint` carries the extractor versions its count reflects after the hash (`<hash>;v<mention>.<alias>`, `INDEX_VERSION_STAMP`), and a stamp that differs from the binary's recounts `pending` once (version-behind pages are already due, so nothing is invalidated); `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, `pending` (`countIndexDuePages`: mention-due pages plus linkable entity pages whose derived aliases are behind their content or `ALIAS_DERIVATION_VERSION`, counted when the source finishes or the deadline stops it) and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-coverage-version.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.
+- `src/core/mentions/owner-phrase/` — owner-phrase resolution with validity windows behind `mentions.owner_phrases` (default off; contract: [owner phrases](../../guides/owner-phrases.md)). `scan.ts` stores per page (`owner_phrase_page_state`, keyed by `knowledge_revision` and `OWNER_PHRASE_SCAN_VERSION`) the cue lines, owner phrases, declared descriptors, the non-fallback page date and the belated-note readings; `dates.ts` parses written dates; `statements.ts` turns cue lines into dated takeover/join/ongoing/end/stint/correction statements (agent-written pages set none); `windows.ts` applies corrections, assembles per-identity-group windows with inclusive bounds and resolves a phrase (temporal candidates first, then ambiguity refusal, readings must agree). `pass.ts` `runOwnerPhrasePass`, called per source from `runMentionPass` after the plain reconcile, rebuilds windows into `owner_phrase_windows` (generation bumps only when the window hash changes; a window whose evidence includes a private page records `private_page_id`) and diffs `link_source='mentions'`, `link_kind='owner_phrase'` links under `pg_advisory_xact_lock`, storing a private evidence page as `origin_page_id`; a page pair another link covers gets none, and a plain mention displaces the row (`mentions/pass.ts`). Key off removes rows, windows, scans and status once. `known-as.ts` is the card's bounded `known_as` read (10 rows plus total, private windows hidden from untrusted readers) and its keyset continuation, served as `get_backlinks` `group: "known_as"` (`ops/backlinks-paged.ts`). Owner-phrase links are non-ranking through `link-ranking-policy.ts` (`NON_RANKING_LINK_KINDS`). `sample.ts` derives the links the pass would store without writes (in-memory scans fed to `buildOwnerPhraseModel`) and implements sampling rule v1, the labeling TSV and the Wilson bound for `scripts/owner-phrase-sample.ts`. Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/owner-phrase-sample.test.ts`, `test/e2e/owner-phrase-parity.test.ts`.
- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (index-due pages per source, as `countIndexDuePages` counts them, and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.
- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. F3: `pageStatusValue` (string, trimmed, at most `PAGE_STATUS_MAX_CHARS` 40) is the one `page_status` rule; `readPageStatusByRef` reads it by `(source_id, slug)` in one statement (private pages hidden from untrusted callers, quarantined pages unless allowed) for `readReferrerPage {pageStatus}`, `get_backlinks` link rows and `context_pack` cards and newer-mention rows. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
index 5c7859ddf0..2053749e50 100644
--- a/docs/guides/entity-recall.md
+++ b/docs/guides/entity-recall.md
@@ -187,6 +187,7 @@ with its reason, and the identity-sibling decision.
|---|---|---|
| `mentions.auto_link` | `true` | `false` removes mention links and derived names on the next sweep; `true` relinks everything on the next sweep. `auto_link=false` also turns it off. |
| `mentions.newer_on_cards` | `true` | `context_pack` cards list up to 8 pages that mention the entity and are dated after the entity's own page, newest first, each with its date, slug, title and the `referenced_by` preview (2,000 characters per card, 6,000 per pack, under the same read policy as the `entity` card). `false` leaves them off. |
+| `mentions.owner_phrases` | `false` | Owner-phrase resolution: the mention pass links a document that says "<owner>'s <descriptor> account" to the account its owner held on the document's date, as `link_kind='owner_phrase'` mention rows, and the `entity` card lists `known_as` windows. Read when the mention pass runs; turning it off removes the rows on the next pass. See [owner phrases](owner-phrases.md). |
| `mentions.entity_types` | none | `+type` adds a linkable type, `-type` removes one (person, company, organization and entity always stay). |
| `mentions.ignore` | none | Names never linked, comma-separated or a JSON array. |
| `mentions.exclude_slugs` | none | Pages never linked by any of their names (title or alias), comma-separated or a JSON array of slugs. Use it for an entity whose name is also a common word, such as a person titled 인하 against "로 인하여" ("due to"). The next sweep removes mention links already written to the page. |
diff --git a/docs/guides/owner-phrases.md b/docs/guides/owner-phrases.md
new file mode 100644
index 0000000000..93d88edfe7
--- /dev/null
+++ b/docs/guides/owner-phrases.md
@@ -0,0 +1,202 @@
+# 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`. Owner-phrase links never change search scores. Most ranking
+readers already skip mention links (backlink counts, relational chain hops and
+typed degree, salience inbound counts). The three that count every link
+(adjacency boosts, entity anchoring and generated-page demotion) skip
+`link_kind='owner_phrase'` through the shared ranking policy
+(`rankingLinkSql`, `src/core/link-ranking-policy.ts`), so a brain's final scores are
+the same with the key on or off. 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", "B will own /
+ is going to own / is set to own X", and the label line "Outgoing A,
+ incoming B";
+ - join: "B joins X", "B has owned X since <date>", "B starts / started /
+ began on (with, covering) X". A join adds an owner without ending anyone
+ else's stint;
+ - ongoing: "B owns / runs / handles / covers / leads X", "B has run / has
+ owned / has handled 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, or Outgoing / Incoming / Effective
+ columns (a handoff). A parenthesized cell is a note, not a value.
+
+ An adverb after the owner ("actually", "officially", "formally", "also",
+ "already", "effectively") does not change the form. In a chat line
+ ("[09:14] Name: I'm picking up X"), first-person words mean the speaker.
+
+ 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. An implicit account is the page itself on an
+ account page, else the one account named on the statement's line, else the
+ one account named across the page's ownership lines; with two or more, an
+ implicit statement sets nothing. A form that begins with the account ("X
+ moves from A to B") never takes the page implicitly. An account named in a
+ statement that has no page competes in ambiguity (line 9) but is never
+ stored or linked. 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. An ongoing
+ statement whose date follows a start cue ("since", "starting", "as of",
+ "effective", "from") is a join from that 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`, `descriptor`, `region` and `territory` labels or
+ frontmatter keys. A label counts at the start of a line or after a
+ sentence boundary ("Account: X. Industry: food. Region: EMEA.").
+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 is the
+ whole run between the possessive and the noun, one to three words. It
+ matches an account when the run is one of the account's descriptors, or
+ when every word of the run is a word of its descriptors ("EMEA software"
+ for an account with region EMEA and industry software). 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. The card shows at most
+ 10 `known_as` rows, newest window first, with the `total`. When rows <
+ total, `known_as.next` is an executable `get_backlinks` call with
+ `group: "known_as"` and a cursor that returns the rest in the same order.
+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. Parsed statements are cached
+ per page under a key of the rules version and the source's account and
+ person names, so a pass reparses only edited pages (or every page after a
+ name change). A pass that scanned nothing skips the rebuild when its
+ inputs hash (rules, names, entity pages, pack, scanned pages and the
+ source's other links) is unchanged.
+
+Every pass reports `links`, `documents`, `unresolved`, `ambiguous` and
+`windows` under `mentions.owner_phrases` in `gbrain extract --stale --json`.
+
+## Precision sample
+
+Before the key's default can change, a labeled sample of derived links from a
+real brain must show precision at a Wilson 95% lower bound of 0.85 or more
+(at least 57 of 60 correct, or 92 of 100). `scripts/owner-phrase-sample.ts`
+draws that sample without writing anything:
+
+- It derives the windows and links the pass would store, inside a `READ ONLY`
+ transaction, with no model or network calls. The key can stay off.
+- Sampling rule v1, fixed before any sample is drawn: one population row per
+ (document, account page) link; rows are ranked by
+ sha256(`owner-phrase-sample-v1`, seed, document slug, account slug) and the
+ first `--n` (default 100) are taken. The same brain and seed give the same
+ sample.
+- Fewer than 22 derivable links is a refusal (exit 3); nothing is written.
+- The TSV goes only to the path given with `--out` (mode 0600; an existing file
+ needs `--force`). Columns: `id`, `doc_slug`, `phrase`, `line_excerpt`,
+ `account`, `window`, `evidence_page`, `label`. stdout carries counts only.
+
+From a checkout of the branch, against a copy of a PGLite brain or a live
+Postgres brain:
+
+```bash
+cd ~/gbrain-f5 && bun install
+cp -a "$(jq -r .database_path ~/.gbrain/config.json)" /tmp/brain-f5-copy # PGLite only; copy while nothing writes
+bun scripts/owner-phrase-sample.ts --pglite /tmp/brain-f5-copy --source all --seed "<seed>" --n 100 --out ~/f5-sample.tsv
+# Postgres brain: omit --pglite; the script reads ~/.gbrain/config.json
+# label each row y (the document means that account) or n in the label column, then:
+bun scripts/owner-phrase-sample.ts --score ~/f5-sample.tsv
+```
+
+`--score` prints the labeled, correct and wrong counts and the Wilson 95%
+lower bound. The TSV stays with the owner; only the counts and the bound are
+published.
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 4fd946fb5b..4785964808 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -59,6 +59,7 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/eval/longmemeval/evidence-packet.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/locomo.ts', reason: 'script-reachable' },
{ path: 'src/core/write-gate-scan.ts', reason: 'script-reachable' },
+ { path: 'src/core/mentions/owner-phrase/sample.ts', reason: 'script-reachable' },
{ path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },
{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },
{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index e408a69ea0..bd82bf7cdd 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -67,3 +67,4 @@ test/e2e/fts-cjk-boundary-postgres.test.ts
test/e2e/oauth-client-registered-via-postgres.test.ts
test/e2e/oauth-owner-consent-source-postgres.test.ts
test/e2e/entity-names-parity-postgres.test.ts
+test/e2e/owner-phrase-parity.test.ts
diff --git a/scripts/owner-phrase-sample.ts b/scripts/owner-phrase-sample.ts
new file mode 100644
index 0000000000..6c27c45d7f
--- /dev/null
+++ b/scripts/owner-phrase-sample.ts
@@ -0,0 +1,93 @@
+#!/usr/bin/env bun
+/**
+ * Owner-phrase precision sample (docs/guides/owner-phrases.md, "Precision
+ * sample"). Read-only: derives the owner-phrase windows and links the pass
+ * would store for one source of the configured brain (or a PGLite copy given
+ * with --pglite), inside a READ ONLY transaction, with no model or network
+ * calls, then writes a labeling TSV of a reproducible sample to the path the
+ * operator names. stdout carries counts only, never page names or text.
+ *
+ * bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>|all] [--n 100] [--pglite <dir>] [--force]
+ *
+ * `--source all` derives every source and samples the union (slugs are
+ * written as <source>:<slug>).
+ * bun scripts/owner-phrase-sample.ts --score <labeled.tsv>
+ *
+ * Exit codes: 0 written (or scored), 1 usage or runtime error, 3 refused
+ * (fewer than 22 derivable links, or --out exists without --force).
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { loadConfig, toEngineConfig } from '../src/core/config.ts';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { EngineConfig } from '../src/core/types.ts';
+import {
+ deriveOwnerPhraseLinks, lineExcerpt, sampleLinks, scoreLabels, toTsv, SAMPLE_DEFAULT_SIZE, SAMPLE_MIN_POPULATION, SAMPLE_RULE, type DerivedLink,
+} from '../src/core/mentions/owner-phrase/sample.ts';
+
+const USAGE = 'usage: bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>|all] [--n 100] [--pglite <dir>] [--force]\n'
+ + ' bun scripts/owner-phrase-sample.ts --score <labeled.tsv>';
+const args = process.argv.slice(2);
+const flag = (name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
+const fail = (code: number, message: string): never => { console.error(message); process.exit(code); };
+
+if (flag('--score')) {
+ console.log(JSON.stringify({ rule: SAMPLE_RULE, ...scoreLabels(readFileSync(flag('--score')!, 'utf8')) }));
+ process.exit(0);
+}
+const out = flag('--out');
+const seed = flag('--seed');
+if (!out || !seed) fail(1, USAGE);
+const n = Number(flag('--n') ?? SAMPLE_DEFAULT_SIZE);
+if (!Number.isInteger(n) || n < 1) fail(1, `--n must be a positive integer\n${USAGE}`);
+if (existsSync(out!) && !args.includes('--force')) fail(3, 'refused: --out already exists; pass --force to replace it');
+const sourceId = flag('--source') ?? 'default';
+
+let engineConfig: EngineConfig;
+if (flag('--pglite')) engineConfig = { engine: 'pglite', database_path: flag('--pglite') } as EngineConfig;
+else {
+ const config = loadConfig();
+ if (!config) fail(1, 'No GBrain config found. Pass --pglite <brain directory copy>, or run from a machine with a configured brain.');
+ engineConfig = toEngineConfig(config!);
+}
+const engine = await createEngine(engineConfig);
+await engine.connect(engineConfig);
+let code = 0;
+try {
+ const result = await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ const sources = sourceId === 'all' ? (await tx.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id) : [sourceId];
+ const derived = { links: [] as Array<DerivedLink & { source: string }>, pages: 0, windows: 0, unresolved: 0, ambiguous: 0 };
+ for (const source of sources) {
+ const d = await deriveOwnerPhraseLinks(tx, source);
+ derived.links.push(...d.links.map(l => sources.length > 1 ? { ...l, source, doc: `${source}:${l.doc}`, account: `${source}:${l.account}` } : { ...l, source }));
+ derived.pages += d.pages; derived.windows += d.windows; derived.unresolved += d.unresolved; derived.ambiguous += d.ambiguous;
+ }
+ if (derived.links.length < SAMPLE_MIN_POPULATION) return { refused: true as const, derived };
+ const sample = sampleLinks(derived.links, seed!, n) as Array<DerivedLink & { source: string }>;
+ const rows = [];
+ for (const s of sample) {
+ const slug = sources.length > 1 ? s.doc.slice(s.source.length + 1) : s.doc;
+ const [page] = await tx.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null }>(
+ 'SELECT title, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [s.source, slug]);
+ rows.push({ ...s, excerpt: page ? lineExcerpt(page, s.line) : '' });
+ }
+ return { refused: false as const, derived, rows };
+ });
+ const counts = { rule: SAMPLE_RULE, seed_sha256: createHash('sha256').update(seed!).digest('hex').slice(0, 16), source: sourceId,
+ pages: result.derived.pages, windows: result.derived.windows, population: result.derived.links.length,
+ unresolved: result.derived.unresolved, ambiguous: result.derived.ambiguous };
+ if (result.refused) {
+ console.log(JSON.stringify({ ...counts, refused: `fewer than ${SAMPLE_MIN_POPULATION} owner-phrase links derivable; no sample written` }));
+ code = 3;
+ } else {
+ writeFileSync(out!, toTsv(result.rows), { mode: 0o600 });
+ console.log(JSON.stringify({ ...counts, sample: result.rows.length, out }));
+ }
+} catch (error) {
+ console.error(`owner-phrase sample failed: ${error instanceof Error ? error.message : String(error)}`);
+ code = 1;
+} finally {
+ await engine.disconnect();
+}
+process.exit(code);
diff --git a/src/core/config.ts b/src/core/config.ts
index e3a317d898..15898e009b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1661,7 +1661,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked, pages never linked (#5829),
// aliases never derived, multi-word declared aliases, identity siblings; search's alias fan-out cap and generated-page demotion.
'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'mentions.exclude_slugs', 'mentions.alias_deny', 'mentions.multiword_aliases',
- 'mentions.sibling_merge', 'search.alias_fanout_max', 'search.demote_generated',
+ 'mentions.sibling_merge', 'search.alias_fanout_max', 'search.demote_generated', 'mentions.owner_phrases',
// #4987: the write-path timeline extractor's off switch (read by
// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`
// works without --force, as the compiled-truth guide documents.
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 0d7ffe681c..d98061ce60 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 statements statements_key', 'cues hits statements'],
+ ['owner_phrase_status', 'out_of_scope', 'no_memory_text', 'source_id state window_hash inputs_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/link-ranking-policy.ts b/src/core/link-ranking-policy.ts
index a6db96b20d..6df3ab3d91 100644
--- a/src/core/link-ranking-policy.ts
+++ b/src/core/link-ranking-policy.ts
@@ -12,6 +12,10 @@
* connection count that picks a canonical entity, generated-page demotion and
* entity anchoring.
*
+ * Owner-phrase links (`link_kind = 'owner_phrase'`, mentions/owner-phrase/)
+ * are non-ranking the same way: a brain's final scores are the same with
+ * `mentions.owner_phrases` on or off.
+ *
* The policy lives in code, not in a schema pack field, so a pack that
* declares one of these types loads on any gbrain. Contract:
* docs/guides/temporal-edges.md ("Amendments: the amends link").
@@ -20,6 +24,9 @@
/** Link types that take no part in ranking. */
export const NON_RANKING_LINK_TYPES: readonly string[] = Object.freeze(['amends']);
+/** Link kinds that take no part in ranking, whatever their type. */
+export const NON_RANKING_LINK_KINDS: readonly string[] = Object.freeze(['owner_phrase']);
+
/** True when edges of this type may feed a ranking signal. */
export function linkTypeRanks(linkType: string): boolean {
return !NON_RANKING_LINK_TYPES.includes(linkType);
@@ -31,5 +38,6 @@ export function linkTypeRanks(linkType: string): boolean {
* the fragment composes into statements with any parameter numbering.
*/
export function rankingLinkSql(alias: string): string {
- return `${alias}.link_type <> ALL(ARRAY[${NON_RANKING_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`;
+ return `(${alias}.link_type <> ALL(ARRAY[${NON_RANKING_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`
+ + ` AND COALESCE(${alias}.link_kind, '') <> ALL(ARRAY[${NON_RANKING_LINK_KINDS.map(k => `'${k}'`).join(', ')}]::text[]))`;
}
diff --git a/src/core/mentions/owner-phrase/dates.ts b/src/core/mentions/owner-phrase/dates.ts
new file mode 100644
index 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/known-as.ts b/src/core/mentions/owner-phrase/known-as.ts
new file mode 100644
index 0000000000..693675c40b
--- /dev/null
+++ b/src/core/mentions/owner-phrase/known-as.ts
@@ -0,0 +1,94 @@
+/**
+ * The entity card's `known_as` rows: each owner of an account with the
+ * validity window of its owner phrase ("<owner>'s <descriptor> account"),
+ * read from `owner_phrase_windows`. The card shows KNOWN_AS_MAX rows with the
+ * total; when rows < total it carries a `next` continuation through the
+ * card's existing mechanism: `get_backlinks` with `group: "known_as"` and a
+ * keyset cursor, ordered newest window first by (start, owner, account group,
+ * end), so the continuation reproduces the card's order exactly. Untrusted
+ * readers never see a window whose evidence includes a private page. Owner
+ * phrases are never aliases: they stay out of `aka`, `page_aliases` and search
+ * alias fan-out. The card read is fail-soft (a read error returns nothing).
+ */
+
+import type { BrainEngine } from '../../engine.ts';
+import { PAGE_DEFAULT_LIMIT } from '../referrers.ts';
+
+export const KNOWN_AS_MAX = 10;
+
+export interface KnownAsRow {
+ owner: string;
+ /** The words an owner phrase may use for this account ("freight" in "Alice's freight account"). */
+ descriptors: string[];
+ /** Inclusive first day, or null when the start is unknown and unbounded. */
+ from: string | null;
+ /** Inclusive last day, or null while the stint is open. */
+ to: string | null;
+ start_known: boolean;
+ evidence: Array<{ slug: string; line: number; kind: string }>;
+}
+
+export interface KnownAsNext { tool: 'get_backlinks'; arguments: Record<string, unknown>; requires_surface?: 'starter' }
+export interface KnownAs { rows: KnownAsRow[]; total: number; next?: KnownAsNext }
+
+type Key = [string, string, string, string];
+const NO_START = '0001-01-01';
+const NO_END = '9999-12-31';
+
+export function encodeKnownAsCursor(key: Key): string {
+ return Buffer.from(JSON.stringify(['known_as', ...key])).toString('base64url');
+}
+
+export function decodeKnownAsCursor(cursor: string): Key | null {
+ try {
+ const v = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
+ if (Array.isArray(v) && v.length === 5 && v[0] === 'known_as' && v.slice(1).every(x => typeof x === 'string')) return v.slice(1) as Key;
+ } catch { /* invalid */ }
+ return null;
+}
+
+/** One page of an account's windows, newest first; `cursor` continues after the last row. */
+export async function readKnownAsPage(engine: BrainEngine, sourceId: string, slug: string,
+ opts: { excludePrivate: boolean; limit: number; after?: Key | null }): Promise<{ rows: KnownAsRow[]; total: number; cursor: string | null }> {
+ const params: unknown[] = [sourceId, slug, opts.limit];
+ const scope = `source_id = $1 AND (group_key = $2 OR $2 = ANY(account_slugs))${opts.excludePrivate ? ' AND private_page_id IS NULL' : ''}`;
+ let keyset = '';
+ if (opts.after) {
+ params.push(...opts.after);
+ keyset = `AND (d < $4 OR (d = $4 AND (owner_key COLLATE "C", group_key COLLATE "C", e) > ($5, $6, $7)))`;
+ }
+ const rows = await engine.executeRaw<{ owner_name: string; owner_key: string; group_key: string; descriptors: string[]; f: string | null; t: string | null;
+ d: string; e: string; start_known: boolean; evidence: unknown; total: number; remaining: number }>(
+ `SELECT w.*, count(*) OVER ()::int AS remaining FROM (
+ SELECT owner_name, owner_key, group_key, descriptors, valid_from::text AS f, valid_to::text AS t,
+ COALESCE(valid_from::text, '${NO_START}') AS d, COALESCE(valid_to::text, '${NO_END}') AS e, start_known, evidence,
+ count(*) OVER ()::int AS total
+ FROM owner_phrase_windows WHERE ${scope}) w
+ WHERE TRUE ${keyset}
+ ORDER BY d DESC, owner_key COLLATE "C", group_key COLLATE "C", e LIMIT $3`, params);
+ const total = rows.length ? Number(rows[0]!.total)
+ : Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM owner_phrase_windows WHERE ${scope}`, [sourceId, slug]))[0]?.n ?? 0);
+ const out = rows.map(r => {
+ const evidence = (typeof r.evidence === 'string' ? JSON.parse(r.evidence) : r.evidence) as Array<{ slug: string; line: number; kind: string }>;
+ return { owner: r.owner_name, descriptors: r.descriptors ?? [], from: r.f, to: r.t, start_known: r.start_known,
+ evidence: evidence.map(e => ({ slug: e.slug, line: e.line, kind: e.kind })) };
+ });
+ const last = rows[rows.length - 1];
+ const more = last != null && Number(last.remaining) > rows.length;
+ return { rows: out, total, cursor: more ? encodeKnownAsCursor([last.d, last.owner_key, last.group_key, last.e]) : null };
+}
+
+export async function readKnownAs(engine: BrainEngine, sourceId: string, slug: string,
+ opts: { excludePrivate: boolean; surfaceCeiling?: string }): Promise<{ known_as?: KnownAs }> {
+ try {
+ const page = await readKnownAsPage(engine, sourceId, slug, { excludePrivate: opts.excludePrivate, limit: KNOWN_AS_MAX });
+ if (!page.rows.length) return {};
+ const next: KnownAsNext | undefined = page.rows.length < page.total && page.cursor ? {
+ tool: 'get_backlinks', arguments: { slug, source_id: sourceId, group: 'known_as', limit: PAGE_DEFAULT_LIMIT, cursor: page.cursor },
+ ...(opts.surfaceCeiling === 'verbs' ? { requires_surface: 'starter' as const } : {}),
+ } : undefined;
+ return { known_as: { rows: page.rows, total: page.total, ...(next ? { next } : {}) } };
+ } catch {
+ return {};
+ }
+}
diff --git a/src/core/mentions/owner-phrase/pass.ts b/src/core/mentions/owner-phrase/pass.ts
new file mode 100644
index 0000000000..40f927c82f
--- /dev/null
+++ b/src/core/mentions/owner-phrase/pass.ts
@@ -0,0 +1,422 @@
+/**
+ * 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, OWNER_PHRASE_RULES_VERSION, type NameEntry, type Statement } from './statements.ts';
+import { accountDescriptors, buildWindows, resolvePhrase, windowsByFirstName, type OwnerWindow } from './windows.ts';
+
+export const OWNER_PHRASE_KEY = 'mentions.owner_phrases';
+/** Group key prefix of an account named in a statement that has no page (statements.ts); never stored or linked. */
+const PAGELESS = 'pseudo:';
+const isPageless = (slug: string) => slug.startsWith(PAGELESS);
+const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);
+const SCAN_BATCH = 500;
+
+/** 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;
+ statements?: unknown; statements_key?: string | null }
+
+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,
+ statements = NULL, statements_key = NULL, 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[]; line: number; windows: OwnerWindow[] }>;
+ /** Statements parsed this build (pages whose cached statements were missing or keyed to other name inputs), to store under `key`. */
+ statementCache: { key: string; writes: Array<{ page_id: number; statements: Statement[] }> };
+ counters: Omit<OwnerPhraseCounters, 'links' | 'documents' | 'windows'>;
+}
+
+/** One page's scan as the model reads it (`owner_phrase_page_state`, or computed in memory by a dry run). */
+export type OwnerPhraseState = StateRow;
+
+/** Statements, windows and resolved links of one source from its stored scans, or from `states` when given (no writes). */
+export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>,
+ states?: OwnerPhraseState[]): 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);
+
+ 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, s.statements, s.statements_key
+ 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 nameKey = (entries: NameEntry[]) => entries.map(e => [e.slug, e.tokens, e.caseTokens ?? null]).sort((a, b) => String(a[0]).localeCompare(String(b[0])) || JSON.stringify(a).localeCompare(JSON.stringify(b)));
+ const statementsKey = createHash('sha256').update(JSON.stringify([OWNER_PHRASE_RULES_VERSION, nameKey(accountEntries), nameKey(personEntries), [...accountSlugs].sort(),
+ [...descriptorAccounts].map(([d, gs]) => [d, [...gs].sort()]).sort((a, b) => String(a[0]).localeCompare(String(b[0])))])).digest('hex').slice(0, 16);
+ const statements: Statement[] = [];
+ const writes: OwnerPhraseModel['statementCache']['writes'] = [];
+ for (const s of states) {
+ const cues = json<CueLine[]>(s.cues);
+ if (!cues.length) continue;
+ if (s.statements_key === statementsKey && s.statements != null) { statements.push(...json<Statement[]>(s.statements)); continue; }
+ const parsed = 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,
+ });
+ statements.push(...parsed);
+ writes.push({ page_id: Number(s.page_id), statements: parsed });
+ }
+ const windows = buildWindows(statements, groupOf);
+ const descriptorsOf = (g: string) => descriptors.get(g) ?? (isPageless(g) ? accountDescriptors([g.slice(PAGELESS.length)], []) : new Set<string>());
+ const candidatesFor = windowsByFirstName(windows);
+
+ 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 ?? [], candidatesFor(hit.owner), descriptorsOf);
+ if (r.linked && r.accounts.every(isPageless)) { counters.unresolved++; continue; }
+ if (!r.linked) {
+ if (r.reason === 'ambiguous' || r.reason === 'readings_disagree') counters.ambiguous++;
+ else counters.unresolved++;
+ 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, line: hit.line, windows: r.windows });
+ }
+ }
+ }
+ return { windows: windows.filter(w => !isPageless(w.group)), descriptors, links, counters, statementCache: { key: statementsKey, writes } };
+}
+
+/**
+ * Everything a pass reads besides page scans that are due: the rules version,
+ * the source's linkable names, its entity pages, the pack and sibling policy,
+ * the set of live scanned pages and the source's other links (a pair another
+ * link covers gets no owner-phrase link). A pass that scanned nothing and finds the
+ * same hash skips the rebuild (its stored windows and links are current).
+ */
+async function inputsHash(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>): Promise<string> {
+ const names: unknown[] = [];
+ for (const bucket of opts.gazetteer.values()) for (const e of bucket) if (e.source_id === opts.sourceId) names.push([e.slug, e.title, e.tokens, e.caseTokens ?? null, e.matchText ?? null]);
+ names.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
+ const [sig] = await engine.executeRaw<{ e: string; s: string; l: string }>(
+ `SELECT (SELECT count(*) || ':' || COALESCE(sum(id), 0) || ':' || COALESCE(max(updated_at)::text, '') FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])) AS e,
+ (SELECT count(*) || ':' || COALESCE(sum(s.page_id), 0) || ':' || COALESCE(max(s.scanned_at)::text, '') 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) AS s,
+ (SELECT count(*) || ':' || COALESCE(max(l.id), 0) FROM links l JOIN pages f ON f.id = l.from_page_id
+ WHERE f.source_id = $1 AND l.link_kind IS DISTINCT FROM 'owner_phrase') AS l`, [opts.sourceId, opts.types]);
+ return createHash('sha256').update(JSON.stringify([OWNER_PHRASE_RULES_VERSION, OWNER_PHRASE_SCAN_VERSION, opts.types, names, sig?.e, sig?.s, sig?.l,
+ opts.policy.siblingMerge, opts.pack ?? null])).digest('hex').slice(0, 16);
+}
+
+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 inputs = await inputsHash(engine, opts);
+ if (!scan.scanned) {
+ const [prev] = await engine.executeRaw<{ state: string; inputs_hash: string | null; links: number; documents: number; unresolved: number; ambiguous: number; windows: number }>(
+ 'SELECT state, inputs_hash, links, documents, unresolved, ambiguous, windows FROM owner_phrase_status WHERE source_id = $1', [sourceId]);
+ if (prev?.state === 'complete' && prev.inputs_hash === inputs) {
+ return { ...result, links: Number(prev.links), documents: Number(prev.documents), unresolved: Number(prev.unresolved),
+ ambiguous: Number(prev.ambiguous), windows: Number(prev.windows) };
+ }
+ }
+ 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 };
+ if (model.statementCache.writes.length) {
+ await executeRawJsonb(tx,
+ `UPDATE owner_phrase_page_state s SET statements = x.statements, statements_key = $1
+ FROM jsonb_to_recordset(($2::jsonb)->'rows') AS x(page_id int, statements jsonb) WHERE s.page_id = x.page_id`,
+ [model.statementCache.key], [{ rows: model.statementCache.writes }]);
+ }
+ 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, inputs_hash, windows, links, documents, unresolved, ambiguous, last_pass_at, error, updated_at)
+ VALUES ($1, 'complete', $2, $3, $9, $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, inputs_hash = EXCLUDED.inputs_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, inputs]);
+ 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/sample.ts b/src/core/mentions/owner-phrase/sample.ts
new file mode 100644
index 0000000000..abddb291b4
--- /dev/null
+++ b/src/core/mentions/owner-phrase/sample.ts
@@ -0,0 +1,142 @@
+/**
+ * Owner phrases, read-only: derive the windows and links the pass would store
+ * for one source without writing anything, and draw a reproducible labeling
+ * sample of those links for the precision check (docs/guides/owner-phrases.md,
+ * "Precision sample").
+ *
+ * `deriveOwnerPhraseLinks` scans every live page in memory with the same
+ * scanner, statement grammar, window assembly and resolution as the pass, then
+ * drops the pairs the pass would not store (a pair another link already
+ * covers) and keeps one link per page pair, exactly as the pass does. It reads
+ * pages, links, aliases and config only. Callers that need a guarantee run it
+ * inside a read-only transaction (scripts/owner-phrase-sample.ts does).
+ *
+ * Sampling rule v1, fixed before any sample is drawn: the population is every
+ * derived link, one per (document, account page); each is ranked by
+ * sha256("owner-phrase-sample-v1", seed, document slug, account slug) and the
+ * first n are taken (all of them when fewer than n exist). The same brain and
+ * seed always give the same sample. Fewer than SAMPLE_MIN_POPULATION links is a
+ * refusal: the precision bar cannot be met or missed on so few.
+ */
+
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../../engine.ts';
+import { buildGazetteer } from '../../by-mention.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../policy.ts';
+import { scanPage } from './scan.ts';
+import { buildOwnerPhraseModel, type OwnerPhraseState } from './pass.ts';
+
+export const SAMPLE_RULE = 'owner-phrase-sample-v1';
+export const SAMPLE_MIN_POPULATION = 22;
+export const SAMPLE_DEFAULT_SIZE = 100;
+const SCAN_BATCH = 1000;
+const EXCERPT_MAX = 300;
+
+export interface DerivedLink {
+ doc: string;
+ account: string;
+ phrase: string;
+ line: number;
+ /** Owner and inclusive bounds of each window the phrase resolved through. */
+ windows: Array<{ owner: string; from: string | null; to: string | null }>;
+ /** Evidence pages of those windows with their lines. */
+ evidence: Array<{ slug: string; line: number }>;
+}
+
+export interface Derivation { links: DerivedLink[]; windows: number; pages: number; unresolved: number; ambiguous: number }
+
+/** The links the owner-phrase pass would store for `sourceId`, derived without writes. */
+export async function deriveOwnerPhraseLinks(engine: BrainEngine, sourceId: string): Promise<Derivation> {
+ const policy = await readMentionPolicy(engine);
+ const pack = await loadSourcePack(engine, sourceId, { strict: true });
+ const gazetteer = await buildGazetteer(engine, { policy, strict: true });
+ const states: OwnerPhraseState[] = [];
+ let after = 0;
+ let pages = 0;
+ for (;;) {
+ const rows = await engine.executeRaw<{ id: number; slug: string; type: string | null; title: string | null; compiled_truth: string | null;
+ timeline: string | null; frontmatter: unknown; effective_date: unknown; effective_date_source: string | null }>(
+ `SELECT id, slug, type, title, compiled_truth, timeline, frontmatter, effective_date, effective_date_source FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND id > $2 ORDER BY id LIMIT $3`, [sourceId, after, SCAN_BATCH]);
+ if (!rows.length) break;
+ after = Number(rows[rows.length - 1]!.id);
+ pages += rows.length;
+ for (const p of rows) {
+ const frontmatter = (typeof p.frontmatter === 'string' ? JSON.parse(p.frontmatter) : p.frontmatter) as Record<string, unknown> | null;
+ const scan = scanPage({ ...p, frontmatter });
+ if (!scan.cues.length && !scan.hits.length && !scan.descriptors.length) continue;
+ states.push({ page_id: Number(p.id), slug: p.slug, page_date: scan.date, readings: scan.readings, agent: scan.agent,
+ cues: scan.cues, descriptors: scan.descriptors, hits: scan.hits });
+ }
+ }
+ const model = await buildOwnerPhraseModel(engine, { sourceId, gazetteer, types: linkableTypesFor(pack, policy), pack, policy }, states);
+ const fromIds = [...new Set(model.links.map(l => l.from_id))];
+ const covered = new Set(fromIds.length ? (await engine.executeRaw<{ f: number; t: string }>(
+ `SELECT l.from_page_id AS f, t.slug AS t FROM links l JOIN pages t ON t.id = l.to_page_id
+ WHERE l.from_page_id = ANY($1::int[]) AND t.source_id = $2 AND l.link_kind IS DISTINCT FROM 'owner_phrase'`, [fromIds, sourceId]))
+ .map(r => `${r.f}\0${r.t}`) : []);
+ const slugById = new Map(states.map(s => [s.page_id, s.slug]));
+ const seen = new Set<string>();
+ const links: DerivedLink[] = [];
+ for (const l of model.links) {
+ const key = `${l.from_id}\0${l.to_slug}`;
+ if (covered.has(key) || seen.has(key)) continue;
+ seen.add(key);
+ const windows = l.windows.filter(w => w.accounts.includes(l.to_slug) || w.group === l.to_slug);
+ const shown = windows.length ? windows : l.windows;
+ links.push({
+ doc: l.from_slug, account: l.to_slug, phrase: l.context, line: l.line,
+ windows: shown.map(w => ({ owner: w.ownerName, from: w.from, to: w.to })),
+ evidence: [...new Map(shown.flatMap(w => w.evidence).map(e => [`${e.page_id}:${e.line}`, { slug: slugById.get(e.page_id) ?? e.slug, line: e.line }])).values()],
+ });
+ }
+ links.sort((a, b) => a.doc.localeCompare(b.doc) || a.account.localeCompare(b.account));
+ return { links, windows: model.windows.length, pages, unresolved: model.counters.unresolved, ambiguous: model.counters.ambiguous };
+}
+
+/** Rule v1: rank by sha256(rule, seed, doc, account), take the first n. */
+export function sampleLinks(links: DerivedLink[], seed: string, n: number): DerivedLink[] {
+ const rank = (l: DerivedLink) => createHash('sha256').update([SAMPLE_RULE, seed, l.doc, l.account].join('\0')).digest('hex');
+ return links.map(l => ({ l, r: rank(l) })).sort((a, b) => (a.r < b.r ? -1 : a.r > b.r ? 1 : 0)).slice(0, n).map(x => x.l);
+}
+
+/** The line a phrase sits on (line 0 is the title), cut to EXCERPT_MAX characters. */
+export function lineExcerpt(page: { title: string | null; compiled_truth: string | null; timeline: string | null }, line: number): string {
+ if (line === 0) return (page.title ?? '').slice(0, EXCERPT_MAX);
+ const lines = `${page.compiled_truth ?? ''}${page.timeline ? `\n${page.timeline}` : ''}`.split('\n');
+ return (lines[line - 1] ?? '').trim().slice(0, EXCERPT_MAX);
+}
+
+export const TSV_COLUMNS = ['id', 'doc_slug', 'phrase', 'line_excerpt', 'account', 'window', 'evidence_page', 'label'] as const;
+const cell = (v: string) => v.replace(/[\t\r\n]+/g, ' ');
+
+export function toTsv(rows: Array<DerivedLink & { excerpt: string }>): string {
+ const body = rows.map((r, i) => [String(i + 1), r.doc, r.phrase, r.excerpt, r.account,
+ r.windows.map(w => `${w.owner} ${w.from ?? '?'}..${w.to ?? 'open'}`).join('; '),
+ r.evidence.map(e => `${e.slug}#L${e.line}`).join('; '), ''].map(cell).join('\t'));
+ return [TSV_COLUMNS.join('\t'), ...body].join('\n') + '\n';
+}
+
+/** Wilson score interval lower bound at 95% (z = 1.96). */
+export function wilsonLower(correct: number, n: number): number {
+ if (n === 0) return 0;
+ const z = 1.96;
+ const p = correct / n;
+ return (p + z * z / (2 * n) - z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))) / (1 + z * z / n);
+}
+
+/** Counts of a labeled TSV (`label` column: y / n; anything else is unlabeled). */
+export function scoreLabels(tsv: string): { labeled: number; correct: number; wrong: number; unlabeled: number; wilson_lower_95: number } {
+ const [head, ...rows] = tsv.split('\n').filter(l => l.trim());
+ const at = head!.split('\t').indexOf('label');
+ if (at < 0) throw new Error('the TSV has no label column');
+ let correct = 0; let wrong = 0; let unlabeled = 0;
+ for (const r of rows) {
+ const v = (r.split('\t')[at] ?? '').trim().toLowerCase();
+ if (v === 'y' || v === 'yes' || v === '1') correct++;
+ else if (v === 'n' || v === 'no' || v === '0') wrong++;
+ else unlabeled++;
+ }
+ const labeled = correct + wrong;
+ return { labeled, correct, wrong, unlabeled, wilson_lower_95: Number(wilsonLower(correct, labeled).toFixed(4)) };
+}
diff --git a/src/core/mentions/owner-phrase/scan.ts b/src/core/mentions/owner-phrase/scan.ts
new file mode 100644
index 0000000000..127def4f82
--- /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 = 2;
+
+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|ing)?|pick(?:s|ed|ing)? up|assum(?:es?|ed|ing)|replac(?:es|ed|ing)|roll(?:s|ed|ing)? off|step(?:s|ped|ping)? (?:away|back|down|off)|no longer|last day|joins?|joined|joining|start(?:s|ed|ing)? (?:on|with|covering)|beg[ia]ns? (?:on|with|covering)|began (?:on|with|covering)|will (?:own|run|handle|cover|lead|manage)|incoming|outgoing|since|until|through|correction|correcting|clarification|actually|rather than|instead of|misspoke|mistake|wrong|incorrect|ae|csm|rep|point person|goes to|went to|book)\b/i;
+const OWNER_COLUMN_RE = /\b(?:owner|lead|ae|csm|manager|rep|am|incoming|outgoing)\b/i;
+const AGENT_TYPE_RE = /(?:^|[-_\s/])agent(?:$|[-_\s/])/i;
+
+/** Personal and benefit accounts: a sentence about them holds no owner phrase (contract line 8). */
+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&-]*){0,2}`;
+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
+ is was are were be been being do does did can will would has have had shall must am`.split(/\s+/).filter(Boolean));
+
+/** Leading and trailing stop words of a capitalized run removed; empty when nothing is left. */
+export function trimNameRun(run: string): string {
+ 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*(?:[-*]\s*)?(?:\*\*)?(?:segment|industry|vertical|sector|category|line of business|business line|descriptor|region|territory)(?:\*\*)?\s*:\s*(?:\*\*)?([^|;,.()]+)/gi;
+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', 'region', 'territory']) {
+ 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) {
+ for (const label of raw.matchAll(DESCRIPTOR_LABEL_RE)) { 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.ts
new file mode 100644
index 0000000000..0e2205968f
--- /dev/null
+++ b/src/core/mentions/owner-phrase/statements.ts
@@ -0,0 +1,421 @@
+/**
+ * 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, findDates, type FoundDate } from './dates.ts';
+import { NAME_STOPWORDS, trimNameRun, type CueLine } from './scan.ts';
+
+/** Bump when the statement grammar changes: cached statements keyed to another version are reparsed. */
+export const OWNER_PHRASE_RULES_VERSION = 1;
+
+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')})?`;
+const ADV = '(?:(?:actually|officially|formally|also|already|effectively) )?';
+
+interface Pattern { kind: StatementKind; re: RegExp; reSelf: RegExp }
+
+function pattern(kind: StatementKind, template: string): Pattern {
+ const build = (acc: string) => new RegExp(template.replaceAll('{ACC}', acc).replaceAll('{O} ', `${P('o')} ${ADV}`).replaceAll('{O}', P('o')).replaceAll('{F}', P('from'))
+ .replaceAll('{FROM}', FROM).replaceAll('{ROLE}', ROLE).replaceAll('{D1}', D('d1')).replaceAll('{D2}', D('d2')));
+ // Sentences are matched with a leading space, so a pattern may open with the account. An account-first
+ // pattern never takes the page itself implicitly: its subject must be written.
+ const re = build(` ${ACC_CORE}`);
+ return { kind, re, reSelf: template.startsWith('{ACC}') ? re : build(`(?: ${ACC_CORE})?`) };
+}
+
+const PATTERNS: Pattern[] = [
+ 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('takeover', `{O} (?:will|is going to|is set to) (?:now )?(?:own|run|handle|cover|lead|manage)(?: the)?{ACC}`),
+ pattern('join', `{O} (?:started|starts|is starting|will start|began|begins|will begin)(?: on| with| covering| working on)?(?: the)?{ACC}`),
+ pattern('join', `{O} (?:joins|joined|is joining|will join)(?: the)?{ACC}`),
+ pattern('join', `{O} (?:co-owns|will co-own|is co-owning|also covers|will also cover|is also covering)(?: the)?{ACC}`),
+ pattern('end', `{O} (?:rolls|roll|rolled|is rolling|will roll|rolling) off{ACC}`),
+ 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 run|has owned|has handled|has covered|has led|has managed|has had|has)(?: the)?{ACC}`),
+ pattern('ongoing', `{O} is (?:the |our )?{ROLE} (?:for|on|of|over)${' '}${ACC_CORE}`),
+ pattern('ongoing', `{ACC} is (?:owned|run|handled|managed|covered|led|looked after) by {O}`),
+ pattern('ongoing', `{ACC} is ${P('o')}'s(?: account)?`),
+ 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 HANDOFF_LABEL_RE = new RegExp(`\\b(?:outgoing|previous|old|former)(?: owner)?:? ${P('from')},? (?:and |→ |-> )?(?:incoming|new)(?: owner)?:? ${P('o')}`);
+const NEGATION_RE = /\b(?:not|never)\b|n't\b/;
+const HYPOTHETICAL_RE = /\b(?:might|may|could|would|should|if|whether|considering|consider|proposal|proposed|propose|proposing|maybe|perhaps|tentatively|possibly|potentially|thinking about|plan to|planning to|plans to|hope to|hoping to|want to|wants to|suggest|suggested|suggesting|recommend|recommended|option)\b/;
+const CORRECTION_RE = /\b(?:correction|correcting|to correct|clarification|to clarify|misspoke|was wrong|were wrong|was incorrect|is incorrect|was a mistake|in error|by mistake|mistakenly|erroneously|actually|retract(?:ing|ed)?|disregard)\b|(?:^|,|—|–|\(| -| and) ?not (?:to )?⟦P|rather than ⟦P|instead of ⟦P/;
+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);
+}
+
+const START_CUE_RE = /(?:since|starting|beginning|effective|effective as of|as of|from)(?: on)? $/;
+
+function chooseDate(norm: Normalized, matchStart: number): { date: FoundDate; start: boolean } | null {
+ const all = norm.dates.map((d, i) => ({ d, i, pos: norm.datePos[i] ?? -1 })).filter(x => x.pos >= 0);
+ if (!all.length) return null;
+ const before = (x: { pos: number }) => norm.n.slice(Math.max(0, x.pos - 24), x.pos);
+ const cue = all.filter(x => CUE_LED_RE.test(before(x)));
+ const pick = (xs: typeof all) => xs.find(x => x.pos >= matchStart) ?? xs[xs.length - 1];
+ const chosen = (cue.length ? pick(cue) : all.find(x => x.pos >= matchStart) ?? all[all.length - 1])!;
+ return { date: chosen.d, start: START_CUE_RE.test(before(chosen)) };
+}
+
+function tableRows(lines: CueLine[]): Array<{ line: number; cells: Record<string, string>; pairs: string[] }> {
+ 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 account = col(row.cells, /^(?:account|client|customer|company|account name|name)$/);
+ const owner = col(row.cells, /\b(?:owner|lead|ae|csm|manager|rep|am)\b/);
+ const incoming = col(row.cells, /^(?:incoming|incoming owner|new owner)$/);
+ if (!owner && incoming) {
+ const outgoing = col(row.cells, /^(?:outgoing|outgoing owner|previous owner|old owner)$/);
+ const when = col(row.cells, /^(?:effective|effective date|date|as of|start|start date)$/);
+ const acctSlug = account ? findNames(account, ctx.accounts)[0]?.entry.slug : ctx.selfAccount;
+ const person = (cell: string | undefined) => (cell && !/^\(.*\)$/.test(cell)
+ ? findNames(cell, ctx.persons)[0]?.entry.title ?? cell.match(RUN_RE)?.map(trimNameRun).find(Boolean) : undefined);
+ const to = person(incoming);
+ const date = when ? findDates(when, ctx.page.date)[0]?.iso ?? null : null;
+ if (!acctSlug || !to) continue;
+ const from = person(outgoing);
+ out.push({ ...base, kind: 'takeover', owner: to, ...(from ? { from } : {}), account: acctSlug, date: date ?? ctx.page.date, stated: !!date,
+ line: row.line, text: Object.values(row.cells).join(' | ') });
+ continue;
+ }
+ if (!owner) continue;
+ const 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 });
+ }
+ const pageAccounts = new Set<string>();
+ for (const l of cues) {
+ if (l.text.trimStart().startsWith('|')) continue;
+ for (const s of splitSentences(speakerFirstPerson(cleanLine(l.text)))) sentences.push({ line: l.line, text: s, label: false });
+ for (const m of findNames(l.text, ctx.accounts)) pageAccounts.add(m.entry.slug);
+ }
+ const context = ctx.selfAccount ?? (pageAccounts.size === 1 ? [...pageAccounts][0]! : null);
+ for (const s of sentences) {
+ const lineAccounts = [...new Set(findNames(cues.find(c => c.line === s.line)?.text ?? '', ctx.accounts).map(m => m.entry.slug))];
+ out.push(...parseSentence(s.text, s.line, ctx, lineAccounts.length === 1 ? lineAccounts[0]! : context));
+ }
+ return out;
+}
+
+const SPEAKER_RE = /^\s*(?:\[[^\]]*\]\s*)?([A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?(?: [A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?){0,2}):\s+(.*)$/;
+
+/** A chat line "[time] Name: I'm taking X" speaks for Name: its first-person subject becomes the speaker. */
+function speakerFirstPerson(line: string): string {
+ const m = SPEAKER_RE.exec(line);
+ if (!m) return line;
+ const speaker = trimNameRun(m[1]!);
+ if (!speaker || speaker !== m[1]) return line;
+ const text = m[2]!;
+ if (!/(?:^|[.!?,;]\s+)I(?:'m|'ll|'ve| am| will| have| was|\b)/.test(text)) return line;
+ return text
+ .replace(/(^|[.!?,;]\s+)I'm\b/g, `$1${speaker} is`).replace(/(^|[.!?,;]\s+)I am\b/g, `$1${speaker} is`)
+ .replace(/(^|[.!?,;]\s+)I'll\b/g, `$1${speaker} will`).replace(/(^|[.!?,;]\s+)I've\b/g, `$1${speaker} has`)
+ .replace(/(^|[.!?,;]\s+)I\b/g, `$1${speaker}`);
+}
+
+function parseSentence(sentence: string, line: number, ctx: ParseContext, context: string | null): Statement[] {
+ if (sentence.endsWith('?')) return [];
+ const norm = normalize(sentence, ctx);
+ const { n } = norm;
+ if (!n.includes('⟦P')) return [];
+ if (!NEGATION_RE.test(n) && !HYPOTHETICAL_RE.test(n)) {
+ const handoff = HANDOFF_LABEL_RE.exec(n);
+ const account = /⟦A(\d+)⟧/.exec(n)?.[1];
+ const target = account !== undefined ? norm.accounts[Number(account)]! : context;
+ if (handoff?.groups && target) {
+ const chosen = chooseDate(norm, handoff.index);
+ return [{ page_id: ctx.page.id, slug: ctx.page.slug, recorded: ctx.page.date, line, text: sentence, kind: 'takeover',
+ owner: norm.persons[Number(handoff.groups.o)]!, from: norm.persons[Number(handoff.groups.from)]!, account: target,
+ date: chosen ? chosen.date.iso : RELATIVE_DATE_RE.test(sentence) ? null : ctx.page.date, stated: !!chosen }];
+ }
+ }
+ const real = matchSentence(norm, sentence, line, ctx, context);
+ if (real.length || norm.persons.length < 2) return real;
+ // An account with no page still holds its owner's phrases: a multi-word name in the account position becomes a
+ // page-less account (`pseudo:<name>`) that only competes in ambiguity (contract line 9) and never receives a link.
+ const pseudo: Statement[] = [];
+ norm.persons.forEach((name, k) => {
+ if (!name.includes(' ') || k > 3) return;
+ const variant: Normalized = { ...norm, accounts: [...norm.accounts, `pseudo:${name.toLowerCase()}`],
+ n: norm.n.replaceAll(`⟦P${k}⟧`, `⟦A${norm.accounts.length}⟧`) };
+ for (const s of matchSentence(variant, sentence, line, { ...ctx, selfAccount: null }, null)) if (s.owner !== name && s.kind !== 'correction') pseudo.push(s);
+ });
+ return pseudo;
+}
+
+function matchSentence(norm: Normalized, sentence: string, line: number, ctx: ParseContext, context: string | null): Statement[] {
+ const { n } = norm;
+ const base = { page_id: ctx.page.id, slug: ctx.page.slug, recorded: ctx.page.date, line, text: sentence };
+ const accountOf = (g: string | undefined) => (g === undefined ? ctx.selfAccount : norm.accounts[Number(g)] ?? null);
+ const undated = RELATIVE_DATE_RE.test(sentence);
+ const dated = (found: { date: FoundDate } | null): { date: string | null; stated: boolean } =>
+ found ? { date: found.date.iso, stated: true } : { date: undated ? null : ctx.page.date, stated: false };
+
+ const wrong = new Set<number>();
+ if (CORRECTION_RE.test(n)) for (const re of WRONG_RES) for (const m of n.matchAll(re)) wrong.add(Number(m[1]));
+ if (wrong.size) {
+ const right = norm.persons.findIndex((_, i) => !wrong.has(i));
+ const acc = /⟦A(\d+)⟧/.exec(n)?.[1];
+ const account = acc !== undefined ? norm.accounts[Number(acc)]! : context;
+ if (!account) return [{ ...base, kind: 'correction', owner: right >= 0 ? norm.persons[right]! : null, wrong: norm.persons[[...wrong][0]!]!, account: '', ...dated(chooseDate(norm, 0)) }];
+ return [...wrong].map(w => ({ ...base, kind: 'correction' as const, owner: right >= 0 ? norm.persons[right]! : null, wrong: norm.persons[w]!, account,
+ ...dated(chooseDate(norm, 0)) }));
+ }
+ 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 = Math.max(0, m.index! - 1);
+ const e = s + m[0].length;
+ if (used.some(([a, b]) => s < b && e > a)) continue;
+ const g = m.groups ?? {};
+ 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 chosen = chooseDate(norm, s);
+ const when = dated(chosen);
+ // An ongoing statement with a start cue ("as of", "since", "effective") dates the start of the stint.
+ const kind = p.kind === 'ongoing' && chosen?.start ? 'join' : p.kind;
+ out.push({ ...base, kind, owner, ...(from && from !== owner ? { from } : {}), account, ...when });
+ }
+ }
+ return out;
+}
diff --git a/src/core/mentions/owner-phrase/windows.ts b/src/core/mentions/owner-phrase/windows.ts
new file mode 100644
index 0000000000..4dc5974b90
--- /dev/null
+++ b/src/core/mentions/owner-phrase/windows.ts
@@ -0,0 +1,239 @@
+/**
+ * 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(' ');
+}
+
+/** A descriptor run matches an account when the whole run is one of its descriptors, or every word of the run is a word of its descriptors ("EMEA software" with region EMEA and industry software). */
+export function descriptorMatches(descriptors: ReadonlySet<string>, run: string): boolean {
+ if (descriptors.has(run)) return true;
+ const words = run.split(' ');
+ if (words.length < 2) return false;
+ let known = descriptorWords.get(descriptors);
+ if (!known) { known = new Set([...descriptors].flatMap(d => d.split(' '))); descriptorWords.set(descriptors, known); }
+ return words.every(w => known.has(w));
+}
+const descriptorWords = new WeakMap<ReadonlySet<string>, Set<string>>();
+
+/** Windows keyed by the owner's first name: every window `ownerMatches` can accept for a surface shares its first word. */
+export function windowsByFirstName(windows: OwnerWindow[]): (surface: string) => OwnerWindow[] {
+ const index = new Map<string, OwnerWindow[]>();
+ for (const w of windows) {
+ const key = w.owner.split(/\s+/)[0]!;
+ const list = index.get(key);
+ if (list) list.push(w); else index.set(key, [w]);
+ }
+ return surface => index.get(surface.toLowerCase().split(/\s+/)[0]!) ?? [];
+}
+
+/** 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) && descriptorMatches(descriptorsOf(w.group), 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.ts
index 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<s
return 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_phrase
FROM 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: MentionPassOpts
const 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: MentionPassOpts
return { ...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/mentions/stale.ts b/src/core/mentions/stale.ts
index c152beee9f..b77d494add 100644
--- a/src/core/mentions/stale.ts
+++ b/src/core/mentions/stale.ts
@@ -63,5 +63,6 @@ export function mentionJsonFields(r: MentionPassResult): Record<string, unknown>
mention_pages: r.pages, mention_links_created: r.created, mention_links_removed: r.removed,
mention_alias_pages: r.aliasPages, mention_due_remaining: r.remaining, mention_state: r.state,
...(r.error ? { mention_error: r.error } : {}),
+ ...(r.ownerPhrases ? { owner_phrases: r.ownerPhrases } : {}),
};
}
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 7cd950c179..8a9899d432 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -1639,10 +1639,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"group": {
"type": "string",
- "enum": [
- "page"
- ],
- "description": "Per page."
+ "description": "page or known_as."
},
"limit": {
"type": "number",
diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.ts
index a7352d463b..c40a099f99 100644
--- a/src/core/ops/backlinks-paged.ts
+++ b/src/core/ops/backlinks-paged.ts
@@ -7,7 +7,8 @@
* `{rows, total, truncated, cursor, coverage}`: one row per referring page,
* newest first by `(date DESC, source_id, slug)`, read through the same
* helper as the entity card's `referenced_by`, so a card group's `next` call
- * continues it exactly.
+ * continues it exactly. `group: "known_as"` pages the card's owner windows
+ * (`known_as.next`) with the same `{rows, total, truncated, cursor}` shape.
*/
import { opError, type OperationContext } from './contract.ts';
@@ -18,6 +19,7 @@ import {
canonicalRecordTypes, decodeCursor, readPageStatusByRef, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,
} from '../mentions/referrers.ts';
import { mentionCoverageNotice, readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';
+import { decodeKnownAsCursor, readKnownAsPage, type KnownAsRow } from '../mentions/owner-phrase/known-as.ts';
import { readEntityReferencesConfig, readRowPageStatus } from '../entity-references-config.ts';
export interface BacklinkPage {
@@ -82,9 +84,10 @@ async function assertKnownType(ctx: OperationContext, scope: ReferrerScope, type
* `group: "page"`: one page of referring pages. A slug with no live page in
* scope answers like an empty read (no rows, total 0).
*/
-export async function readBacklinkPage(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<BacklinkPage> {
+export async function readBacklinkPage(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<BacklinkPage | KnownAsPage> {
+ if (p.group === 'known_as') return readKnownAsGroup(ctx, p, policy);
if (p.group !== 'page') {
- throw opError('invalid_params', `get_backlinks: group must be "page".`, 'Pass group: "page" for one row per referring page, or omit group for link rows.');
+ throw opError('invalid_params', `get_backlinks: group must be "page" or "known_as".`, 'Pass group: "page" for one row per referring page, group: "known_as" for the card\'s owner windows, or omit group for link rows.');
}
const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;
const cursor = p.cursor === undefined ? null : decodeCursor(String(p.cursor));
@@ -122,6 +125,28 @@ export async function withLinkPageStatus(ctx: OperationContext, policy: () => Pr
});
}
+export interface KnownAsPage { rows: KnownAsRow[]; total: number; truncated: boolean; cursor: string | null }
+
+/**
+ * `group: "known_as"`: one page of the entity card's owner windows
+ * (mentions/owner-phrase/known-as.ts), continuing a card's `known_as.next`.
+ * A slug with no live page in scope answers like an empty read.
+ */
+async function readKnownAsGroup(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<KnownAsPage> {
+ if (p.type !== undefined) {
+ throw opError('invalid_params', 'get_backlinks: type does not apply to group: "known_as".', 'Omit type with group: "known_as".');
+ }
+ const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;
+ const after = p.cursor === undefined ? null : decodeKnownAsCursor(String(p.cursor));
+ if (p.cursor !== undefined && !after) {
+ throw opError('invalid_params', 'get_backlinks: cursor is not one this tool returned.', 'Pass the cursor from the previous known_as response unchanged, or omit it to start from the newest window.');
+ }
+ const sourceId = await targetSource(ctx, String(p.slug), await scopeSources(ctx, policy));
+ if (!sourceId) return { rows: [], total: 0, truncated: false, cursor: null };
+ const page = await readKnownAsPage(ctx.engine, sourceId, String(p.slug), { excludePrivate: policy.excludePrivate === true, limit, after });
+ return { rows: page.rows, total: page.total, truncated: page.cursor !== null, cursor: page.cursor };
+}
+
/**
* Array mode with `type` and/or `limit`: today's link rows, filtered by the
* referring page's type and cut at `limit` (a cut is reported with a
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 7a9912f3ab..c4b81b82cd 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -405,7 +405,7 @@ const get_backlinks: Operation = {
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
type: { type: 'string', description: 'Referrer type.' },
- group: { type: 'string', enum: ['page'], description: 'Per page.' },
+ group: { type: 'string', description: 'page or known_as.' },
limit: { type: 'number', description: 'Max 500.' },
cursor: { type: 'string', description: 'Paging.' },
},
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 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.ts
index a97d414068..d08a5e787d 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -204,7 +204,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.ts
index cdbb16a1fd..d7a9cffe12 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -531,7 +531,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
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 115c3b3e46..a73fbd1589 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 = 242;
+export const LATEST_SCHEMA_VERSION = 243;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 5d10baa3ff..f2257d86ff 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -243,6 +243,7 @@ import { v239 } from './v239-extract-rollup-halt-reasons.ts';
import { v240 } from './v240-pages-name-lookup-indexes.ts';
import { v241 } from './v241-persistence-request-slug-intent-index.ts';
import { v242 } from './v242-extract-atoms-partial-input.ts';
+import { v243 } from './v243-owner-phrase-windows.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -484,4 +485,5 @@ export const MIGRATIONS: Migration[] = [
v240,
v241,
v242,
+ v243,
];
diff --git a/src/core/schema-migrations/v243-owner-phrase-windows.ts b/src/core/schema-migrations/v243-owner-phrase-windows.ts
new file mode 100644
index 0000000000..cf1e6417df
--- /dev/null
+++ b/src/core/schema-migrations/v243-owner-phrase-windows.ts
@@ -0,0 +1,89 @@
+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 v243: Migration = {
+ version: 243,
+ 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,
+ statements JSONB,
+ statements_key TEXT,
+ scanned_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ ALTER TABLE owner_phrase_page_state ADD COLUMN IF NOT EXISTS statements JSONB;
+ ALTER TABLE owner_phrase_page_state ADD COLUMN IF NOT EXISTS statements_key TEXT;
+ 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,
+ inputs_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()
+ );
+ ALTER TABLE owner_phrase_status ADD COLUMN IF NOT EXISTS inputs_hash TEXT;
+ 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/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 9b6331ac62..b9e273d911 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -41,6 +41,7 @@ import { readRowReferences, referencesUnavailableNotice, type RecordGroupView, t
import type { Notice } from '../agent-output.ts';
import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';
import { factEntitySlugs } from '../mentions/siblings.ts';
+import { readKnownAs, type KnownAs } from '../mentions/owner-phrase/known-as.ts';
const EDGE_CAP = 10;
const OPEN_THREADS_CAP = 3;
@@ -134,6 +135,8 @@ export interface EntityCard {
identity_excerpt?: CardIdentity['identity_excerpt'];
/** Pages whose qualifying lines did not fit the excerpt budget. */
identity_excerpt_omitted?: string[];
+ /** Owners of this account with their owner-phrase validity windows (`mentions.owner_phrases`). `entity` verb only. */
+ known_as?: KnownAs;
/** What `aka` covers and which names to search before a history or as-of answer. `entity` verb only. */
alias_guidance?: CardIdentity['alias_guidance'];
/** #5575 A6 (additive): the entity page's trust tier and short write origin. */
@@ -387,7 +390,8 @@ export async function buildEntityCard(
const card = await assembleCard(engine, sourceId, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});
if (opts.includeReferences) {
Object.assign(card, await cardReferences(engine, sourceId, row, opts, scope.excludePrivate, scope.entityTypes),
- await readCardIdentity(engine, sourceId, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));
+ await readCardIdentity(engine, sourceId, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }),
+ await readKnownAs(engine, sourceId, row.slug, { excludePrivate: scope.excludePrivate, surfaceCeiling: opts.surfaceCeiling }));
await attachCardRecords(engine, sourceId, card, opts, scope.excludePrivate);
}
return {
diff --git a/src/schema.sql b/src/schema.sql
index daa15be985..f86b448cc9 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -527,7 +527,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
diff --git a/test/amends-link.test.ts b/test/amends-link.test.ts
index 2d75a6690d..6d669a4c3d 100644
--- a/test/amends-link.test.ts
+++ b/test/amends-link.test.ts
@@ -10,7 +10,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { setPackRelationSemantics } from '../src/core/link-validity.ts';
-import { linkTypeRanks, NON_RANKING_LINK_TYPES, rankingLinkSql } from '../src/core/link-ranking-policy.ts';
+import { linkTypeRanks, NON_RANKING_LINK_KINDS, NON_RANKING_LINK_TYPES, rankingLinkSql } from '../src/core/link-ranking-policy.ts';
import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
import { INVARIANCE_ROWS, amendmentsVersusReplacement, databaseToday, frontmatterRecordsSince, futureAmendsStayVisible,
runInvarianceRow, useExamplePack } from './helpers/amends-ranking-scenarios.ts';
@@ -27,12 +27,13 @@ afterAll(async () => { await engine.disconnect(); resetGateway(); setPackRelatio
beforeEach(async () => { await resetPgliteState(engine); configureGateway({ env: {} } as never); setPackRelationSemantics(new Map()); });
describe('ranking participation policy', () => {
- test('amends is the non-ranking link type; the SQL predicate inlines it', () => {
+ test('amends is the non-ranking link type and owner_phrase the non-ranking link kind; the SQL predicate inlines both', () => {
expect(NON_RANKING_LINK_TYPES).toEqual(['amends']);
+ expect(NON_RANKING_LINK_KINDS).toEqual(['owner_phrase']);
expect(linkTypeRanks('amends')).toBe(false);
expect(linkTypeRanks('supersedes')).toBe(true);
expect(linkTypeRanks('mentions')).toBe(true);
- expect(rankingLinkSql('l')).toBe(`l.link_type <> ALL(ARRAY['amends']::text[])`);
+ expect(rankingLinkSql('l')).toBe(`(l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[]))`);
});
test('the bundled example pack is a valid manifest declaring amends as an event mapped from frontmatter', () => {
diff --git a/test/e2e/owner-phrase-parity.test.ts b/test/e2e/owner-phrase-parity.test.ts
new file mode 100644
index 0000000000..057045af58
--- /dev/null
+++ b/test/e2e/owner-phrase-parity.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Owner phrases: PGLite and Postgres parity (docs/guides/owner-phrases.md).
+ *
+ * Protects: the v243 migration (link_kind CHECK accepting 'owner_phrase',
+ * the windowed tables) and the owner-phrase pass producing the same windows,
+ * links, counters, visibility, `known_as` rows and their get_backlinks
+ * continuation on both engines, plus a
+ * correction, a deletion, disable, and two passes racing over a real
+ * connection pool on Postgres (the advisory lock serializes publication).
+ * Regression: an engine-specific SQL difference in the jsonb batch writes,
+ * the date casts or the visibility predicate.
+ *
+ * Gated by DATABASE_URL (skips without it); the PGLite half always runs.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { buildGazetteer } from '../../src/core/by-mention.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../../src/core/mentions/policy.ts';
+import { runOwnerPhrasePass } from '../../src/core/mentions/owner-phrase/pass.ts';
+import { ACME, NIMBUS, doc, knownAsContinuation, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from '../helpers/owner-phrase-brain.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const SKIP_PG = !hasDatabase();
+const describeBoth = SKIP_PG ? describe.skip : describe;
+
+async function lifecycle(engine: BrainEngine) {
+ const policy = await readMentionPolicy(engine);
+ const pack = await loadSourcePack(engine, 'default', { strict: true });
+ const opts = { sourceId: 'default', gazetteer: await buildGazetteer(engine, { policy, strict: true }), types: linkableTypesFor(pack, policy), pack, policy, enabled: true, deadline: Infinity };
+ await doc(engine, 'updates/acme-correction', 'Correction: Acme Example Freight went to Juniper Example, not Quill.', { date: '2025-04-17' });
+ await sweepOwnerPhrases(engine);
+ const corrected = { links: await ownerPhraseLinks(engine), windows: await windowRows(engine) };
+ await doc(engine, 'notes/new-call', "Juniper's freight account called about a claim.", { date: '2025-04-02' });
+ const raced = await Promise.all([runOwnerPhrasePass(engine, opts), runOwnerPhrasePass(engine, opts)]);
+ const afterRace = await ownerPhraseLinks(engine);
+ await engine.softDeletePage('updates/acme-correction');
+ await engine.softDeletePage('updates/acme-handoff');
+ await sweepOwnerPhrases(engine);
+ const deleted = await ownerPhraseLinks(engine);
+ await engine.setConfig('mentions.owner_phrases', 'false');
+ const disabled = await sweepOwnerPhrases(engine);
+ return { corrected, raced: raced.map(r => [r.state, r.created]).sort(), afterRace, deleted, disabled: { state: disabled?.state, links: await ownerPhraseLinks(engine), windows: await windowRows(engine) } };
+}
+
+async function checkConstraint(engine: BrainEngine) {
+ const [[a], [b]] = await Promise.all(['notes/undated', ACME].map(s => engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [s])));
+ const insert = (kind: string) => engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, link_kind) VALUES ($1, $2, 'probe', 'mentions', $3)`, [a!.id, b!.id, kind]);
+ await insert('owner_phrase');
+ await engine.executeRaw(`DELETE FROM links WHERE link_type = 'probe'`);
+ return insert('bogus').then(() => 'accepted', () => 'refused');
+}
+
+let pglite: PGLiteEngine;
+let pgliteSnap: Awaited<ReturnType<typeof ownerPhraseSnapshot>>;
+let pgliteLife: Awaited<ReturnType<typeof lifecycle>>;
+let pgliteKnownAs: Awaited<ReturnType<typeof knownAsContinuation>>;
+beforeAll(async () => {
+ pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ await seedOwnerPhraseBrain(pglite);
+ pgliteSnap = await ownerPhraseSnapshot(pglite);
+ pgliteKnownAs = await knownAsContinuation(pglite);
+ pgliteLife = await lifecycle(pglite);
+}, 180_000);
+afterAll(async () => { await pglite.disconnect(); });
+
+describe('owner phrases (PGLite half)', () => {
+ test('links, correction, race, deletion and disable produce the expected rows', () => {
+ expect(pgliteSnap.trusted).toHaveLength(4);
+ expect(pgliteLife.corrected.links).not.toContain(`notes/renewal -> ${ACME}`);
+ expect(pgliteLife.raced).toEqual([['complete', 0], ['complete', 1]]);
+ expect(pgliteLife.afterRace).toContain(`notes/new-call -> ${NIMBUS}`);
+ expect(pgliteLife.deleted.filter(l => l.endsWith(ACME))).toEqual([]);
+ expect(pgliteLife.disabled).toEqual({ state: 'off', links: [], windows: [] });
+ expect(pgliteKnownAs.trusted.followed).toEqual(pgliteKnownAs.trusted.all);
+ expect(pgliteKnownAs.trusted).toMatchObject({ total: 14, shown: 10 });
+ });
+});
+
+describeBoth('owner phrases (Postgres parity)', () => {
+ let pg: BrainEngine;
+ beforeAll(async () => { pg = await setupDB(); }, 180_000);
+ afterAll(async () => { await teardownDB(); });
+
+ test('the CHECK accepts owner_phrase and refuses unknown kinds', async () => {
+ await seedOwnerPhraseBrain(pg);
+ expect(await checkConstraint(pg)).toBe('refused');
+ });
+
+ test('windows, links, counters, visibility and known_as match PGLite', async () => {
+ expect(await ownerPhraseSnapshot(pg)).toEqual(pgliteSnap);
+ });
+
+ test('the known_as continuation (card next followed through get_backlinks) matches PGLite', async () => {
+ expect(await knownAsContinuation(pg)).toEqual(pgliteKnownAs);
+ });
+
+ test('correction, a pooled race, deletion and disable match PGLite', async () => {
+ expect(await lifecycle(pg)).toEqual(pgliteLife);
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 206ea38690..e675dcd013 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -124,7 +124,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -201,6 +201,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -673,6 +682,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1150,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1328,6 +1352,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2509,6 +2534,61 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 83b5c7544c..18bb2063db 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -124,7 +124,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -201,6 +201,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -673,6 +682,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1150,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1328,6 +1352,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2509,6 +2534,61 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index b0cc907cf9..656851cc1e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -124,7 +124,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -201,6 +201,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -673,6 +682,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1128,6 +1146,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1324,6 +1348,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2505,6 +2530,61 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index c7ea240aa5..a4f4f170c3 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -85,7 +85,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 4d86b21e99..b5af133c0a 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -85,7 +85,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index ceb41a12f0..3362907bf7 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -85,7 +85,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 02e9e35d56..f05f7b34ac 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -98,7 +98,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 547a9ac20e..2d82abdab2 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -127,7 +127,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -205,6 +205,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -680,6 +689,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1154,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1330,6 +1354,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2521,6 +2546,61 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 8c543fe2ba..80b7c443a0 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -127,7 +127,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -205,6 +205,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -680,6 +689,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1154,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1330,6 +1354,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2521,6 +2546,61 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 501a895dec..0bda9272d9 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -127,7 +127,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -205,6 +205,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -680,6 +689,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1150,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1326,6 +1350,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2517,6 +2542,61 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 5a9b903fc2..162db9385a 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 231878,
- "stdoutSha256": "b1d2ef871d92ce9360a547ac5cc1651136a6eb12a96799fcdd317459870690b9",
+ "stdoutBytes": 231834,
+ "stdoutSha256": "eef0626406fb696b8e89167e34df89c6c823e47532257c0a9701f992e73860d1",
"toolNames": [
"remember",
"entity",
@@ -1990,10 +1990,7 @@
"type": "string"
},
"group": {
- "description": "Per page.",
- "enum": [
- "page"
- ],
+ "description": "page or known_as.",
"type": "string"
},
"limit": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 7c25f59bf4..11918451a2 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -523,7 +523,7 @@
},
{
"category": "ops",
- "message": "RLS enabled on 134/134 public tables",
+ "message": "RLS enabled on 137/137 public tables",
"name": "rls",
"status": "ok"
},
@@ -3608,7 +3608,7 @@
},
{
"category": "ops",
- "message": "RLS enabled on 134/134 public tables",
+ "message": "RLS enabled on 137/137 public tables",
"name": "rls",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 4ea9b6df0a..3d7170d9ef 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -507,7 +507,7 @@
},
{
"category": "ops",
- "message": "RLS enabled on 134/134 public tables",
+ "message": "RLS enabled on 137/137 public tables",
"name": "rls",
"status": "ok"
},
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 4b531812c4..8cc43586fe 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 237,
+ "count": 238,
"gaps": [
17,
18,
@@ -54,7 +54,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 242,
+ "latest": 243,
"records": [
{
"handler": {
@@ -3684,6 +3684,19 @@
"transaction": "absent",
"verify": "absent",
"version": 242
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "owner_phrase_windows",
+ "sql": {
+ "length": 3030,
+ "sha256": "791a738685eaace24e8758e42eb2d76556157a4a20a2cc6545554249dd63b2a8"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 243
}
],
"versions": [
@@ -3923,7 +3936,8 @@
239,
240,
241,
- 242
+ 242,
+ 243
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 8723216ee8..1eabe5a28c 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -124,7 +124,7 @@
"links.links_assertion_tense_check": "c CHECK (((assertion_tense IS NULL) OR (assertion_tense = ANY (ARRAY['present'::text, 'past'::text]))))",
"links.links_from_page_id_fkey": "f FOREIGN KEY (from_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"links.links_from_to_type_source_origin_unique": "u UNIQUE NULLS NOT DISTINCT (from_page_id, to_page_id, link_type, link_source, origin_page_id)",
- "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text]))))",
+ "links.links_link_kind_check": "c CHECK (((link_kind IS NULL) OR (link_kind = ANY (ARRAY['plain'::text, 'typed_ner'::text, 'owner_phrase'::text]))))",
"links.links_link_source_check": "c CHECK (((link_source IS NULL) OR ((link_source ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'::text) AND (char_length(link_source) <= 64))))",
"links.links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE SET NULL",
"links.links_pkey": "p PRIMARY KEY (id)",
@@ -201,6 +201,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "owner_phrase_page_state.owner_phrase_page_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "owner_phrase_page_state.owner_phrase_page_state_pkey": "p PRIMARY KEY (page_id)",
+ "owner_phrase_page_state.owner_phrase_page_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_pkey": "p PRIMARY KEY (source_id)",
+ "owner_phrase_status.owner_phrase_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "owner_phrase_status.owner_phrase_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'failed'::text])))",
+ "owner_phrase_windows.owner_phrase_windows_pkey": "p PRIMARY KEY (id)",
+ "owner_phrase_windows.owner_phrase_windows_private_page_id_fkey": "f FOREIGN KEY (private_page_id) REFERENCES pages(id) ON DELETE SET NULL",
+ "owner_phrase_windows.owner_phrase_windows_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
@@ -673,6 +682,15 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "owner_phrase_page_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "owner_phrase_windows": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1150,12 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "owner_phrase_page_state_pkey": "CREATE UNIQUE INDEX owner_phrase_page_state_pkey ON public.owner_phrase_page_state USING btree (page_id)",
+ "owner_phrase_page_state_source_idx": "CREATE INDEX owner_phrase_page_state_source_idx ON public.owner_phrase_page_state USING btree (source_id)",
+ "owner_phrase_status_pkey": "CREATE UNIQUE INDEX owner_phrase_status_pkey ON public.owner_phrase_status USING btree (source_id)",
+ "owner_phrase_windows_accounts_idx": "CREATE INDEX owner_phrase_windows_accounts_idx ON public.owner_phrase_windows USING gin (account_slugs)",
+ "owner_phrase_windows_group_idx": "CREATE INDEX owner_phrase_windows_group_idx ON public.owner_phrase_windows USING btree (source_id, group_key)",
+ "owner_phrase_windows_pkey": "CREATE UNIQUE INDEX owner_phrase_windows_pkey ON public.owner_phrase_windows USING btree (id)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
@@ -1328,6 +1352,7 @@
"minion_self_fix_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=minion_self_fix_log.id",
"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id",
"open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",
+ "owner_phrase_windows_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=owner_phrase_windows.id",
"page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",
"page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-",
"page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id",
@@ -2509,6 +2534,61 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "owner_phrase_page_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 revision uuid/uuid NULL",
+ "4 version integer/int4 NOT NULL",
+ "5 page_date date/date NULL",
+ "6 readings ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "7 agent boolean/bool NOT NULL DEFAULT false",
+ "8 cues jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "9 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "10 hits jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "11 statements jsonb/jsonb NULL",
+ "12 statements_key text/text NULL",
+ "13 scanned_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 state text/text NOT NULL",
+ "3 generation bigint/int8 NOT NULL DEFAULT 0",
+ "4 window_hash text/text NULL",
+ "5 inputs_hash text/text NULL",
+ "6 windows integer/int4 NOT NULL DEFAULT 0",
+ "7 links integer/int4 NOT NULL DEFAULT 0",
+ "8 documents integer/int4 NOT NULL DEFAULT 0",
+ "9 unresolved integer/int4 NOT NULL DEFAULT 0",
+ "10 ambiguous integer/int4 NOT NULL DEFAULT 0",
+ "11 last_pass_at timestamp with time zone/timestamptz NULL",
+ "12 error text/text NULL",
+ "13 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "owner_phrase_windows": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('owner_phrase_windows_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 group_key text/text NOT NULL",
+ "4 account_slugs ARRAY/_text NOT NULL",
+ "5 owner_key text/text NOT NULL",
+ "6 owner_name text/text NOT NULL",
+ "7 descriptors ARRAY/_text NOT NULL DEFAULT '{}'::text[]",
+ "8 valid_from date/date NULL",
+ "9 valid_to date/date NULL",
+ "10 start_known boolean/bool NOT NULL",
+ "11 evidence jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
+ "12 evidence_page_ids ARRAY/_int4 NOT NULL DEFAULT '{}'::integer[]",
+ "13 private_page_id integer/int4 NULL",
+ "14 generation bigint/int8 NOT NULL DEFAULT 0"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_aliases": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('page_aliases_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/sql-text/salience.json b/test/fixtures/goldens/sql-text/salience.json
index 346c3d1604..076824acb7 100644
--- a/test/fixtures/goldens/sql-text/salience.json
+++ b/test/fixtures/goldens/sql-text/salience.json
@@ -222,8 +222,8 @@
"number",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",
- "textSha256": "1a1f91975382b6f97f2ba8119b0a344c48a2383f19a21040b553657652875f01"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",
+ "textSha256": "8f368d9866c4bd7b414151d634cb32c6fed8eabd78b1b6035aceb3b7830874b9"
}
],
"sourceId": [
@@ -235,8 +235,8 @@
"string",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",
- "textSha256": "ac911efc9ff41921e9ebdde94bd01d861d022f72ccedac6417eea9de315b2dfc"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",
+ "textSha256": "fe012403bd78fc3b31f4a2875a65e71043d262483467dbaebbf4d1d612dcdf27"
}
],
"sourceIds+reenrich": [
@@ -249,8 +249,8 @@
"string",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",
- "textSha256": "01b82217b92b0982f9570e78247e7c39ab1925fde627edf063923526b895d9e6"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",
+ "textSha256": "388baaace733ea685b8b4b0678c589ccdb5e1b8b7618f154bdca53a17381ee8a"
}
]
},
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 0f2618f67c..0546a285b2 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 122, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 125, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/owner-phrase-brain.ts b/test/helpers/owner-phrase-brain.ts
new file mode 100644
index 0000000000..9f5d64d87c
--- /dev/null
+++ b/test/helpers/owner-phrase-brain.ts
@@ -0,0 +1,133 @@
+/**
+ * Owner-phrase test corpus (docs/guides/owner-phrases.md): a small general
+ * brain of account pages, people, dated team updates and call notes that
+ * name accounts only by "<owner>'s <descriptor> account". Shared by the
+ * PGLite DB test and the Postgres parity test so both engines run the same
+ * rows. Placeholder names only.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { setCliOptions } from '../../src/core/cli-options.ts';
+import { extractStaleFromDB } from '../../src/commands/extract.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
+import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';
+import { privateLinkOriginFilterFragment, privatePagesFilterFragment } from '../../src/core/search/private-visibility.ts';
+import type { PageType } from '../../src/core/types.ts';
+
+export const ACME = 'companies/acme-example-freight';
+export const NIMBUS = 'companies/nimbus-example-freight';
+export const WIDGET = 'companies/widget-example-health';
+
+export async function doc(engine: BrainEngine, slug: string, body: string, opts: { type?: string; date?: string; title?: string; private?: boolean } = {}): Promise<void> {
+ const frontmatter: Record<string, unknown> = { ...(opts.date ? { date: opts.date } : {}), ...(opts.private ? { visibility: 'private' } : {}) };
+ await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type: (opts.type ?? 'note') as PageType, title: opts.title ?? slug, tags: [] }),
+ { noEmbed: true, forceRechunk: true });
+}
+
+export async function seedOwnerPhraseBrain(engine: BrainEngine, opts: { enabled?: boolean } = {}): Promise<void> {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ if (opts.enabled !== false) await engine.setConfig('mentions.owner_phrases', 'true');
+ await doc(engine, 'people/quill-example', 'Account manager.', { type: 'person', title: 'Quill Example' });
+ await doc(engine, 'people/rowan-example', 'Account manager.', { type: 'person', title: 'Rowan Example' });
+ await doc(engine, 'people/juniper-example', 'Account manager.', { type: 'person', title: 'Juniper Example' });
+ await doc(engine, ACME, 'Segment: logistics', { type: 'company', title: 'Acme Example Freight' });
+ await doc(engine, NIMBUS, 'Segment: logistics', { type: 'company', title: 'Nimbus Example Freight' });
+ await doc(engine, WIDGET, 'Segment: benefits', { type: 'company', title: 'Widget Example Health' });
+ // Advance handoff: Rowan's stint ends April 30, Quill's starts May 1.
+ await doc(engine, 'updates/acme-handoff', 'From May 1, Quill Example takes over Acme Example Freight from Rowan Example.', { date: '2025-04-15' });
+ await doc(engine, 'notes/rate-review', "Rowan's freight account asked for a rate review.", { date: '2025-04-20' });
+ await doc(engine, 'notes/rate-followup', "Rowan's freight account asked again about the rate review.", { date: '2025-05-10' });
+ await doc(engine, 'notes/renewal', "Quill's freight account renewed for two years.", { date: '2025-05-12' });
+ // A second freight account: Juniper owns it, then hands it to Quill on June 1.
+ await doc(engine, 'updates/nimbus-owner', 'Juniper Example owns Nimbus Example Freight.', { date: '2025-01-01' });
+ await doc(engine, 'updates/nimbus-handoff', 'Nimbus Example Freight moves from Juniper Example to Quill Example on 2025-06-01.', { date: '2025-05-20' });
+ await doc(engine, 'notes/escalation', "Quill's freight account escalated a missed pickup.", { date: '2025-07-01' });
+ await doc(engine, 'notes/juniper-call', "Juniper's freight account asked about invoices.", { date: '2025-03-03' });
+ // No page date: never linked.
+ await doc(engine, 'notes/undated', "Quill's freight account wants a call.");
+ // Evidence only on a private page: owner-trusted reads see the link, untrusted reads do not.
+ await doc(engine, 'updates/widget-handoff', 'Widget Example Health moves from Rowan Example to Quill Example, effective February 1.', { date: '2025-01-25', private: true });
+ await doc(engine, 'notes/benefits-call', "Quill's health account asked about billing.", { date: '2025-03-01' });
+ // An agent-written page sets no window.
+ await doc(engine, 'notes/agent-guess', 'Juniper Example owns Widget Example Health.', { type: 'agent-note', date: '2025-02-10' });
+ await doc(engine, 'notes/juniper-health', "Juniper's health account sent a contract.", { date: '2025-03-05' });
+}
+
+export async function sweepOwnerPhrases(engine: BrainEngine) {
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+ const r = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ return r.mentions?.ownerPhrases;
+}
+
+/** `doc -> account` for every owner-phrase link; `remote` applies the untrusted visibility predicate. */
+export async function ownerPhraseLinks(engine: BrainEngine, remote = false): Promise<string[]> {
+ const rows = await engine.executeRaw<{ f: string; t: string }>(
+ `SELECT f.slug AS f, t.slug AS t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_source = 'mentions' AND l.link_kind = 'owner_phrase'
+ ${remote ? `AND ${privateLinkOriginFilterFragment('l')} AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')}` : ''}
+ ORDER BY 1, 2`);
+ return rows.map(r => `${r.f} -> ${r.t}`);
+}
+
+export async function windowRows(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ g: string; o: string; f: string | null; t: string | null; p: number | null }>(
+ `SELECT group_key AS g, owner_name AS o, valid_from::text AS f, valid_to::text AS t, private_page_id AS p FROM owner_phrase_windows ORDER BY 1, 2, 3`);
+ return rows.map(r => `${r.g} ${r.o} ${r.f ?? '?'}..${r.t ?? 'open'}${r.p == null ? '' : ' (private)'}`);
+}
+
+export async function ownerPhraseSnapshot(engine: BrainEngine) {
+ const counters = await sweepOwnerPhrases(engine);
+ const card = async (remote: boolean) => (await buildEntityCard(engine, 'default', 'Widget Example Health', { remote, includeReferences: true })).card?.known_as;
+ const [status] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT state, windows, links, documents, unresolved, ambiguous FROM owner_phrase_status WHERE source_id = $1', ['default']);
+ return {
+ counters: counters && { state: counters.state, links: counters.links, documents: counters.documents, unresolved: counters.unresolved, ambiguous: counters.ambiguous, windows: counters.windows },
+ status: status && Object.fromEntries(Object.entries(status).map(([k, v]) => [k, typeof v === 'string' ? v : Number(v)])),
+ trusted: await ownerPhraseLinks(engine),
+ remote: await ownerPhraseLinks(engine, true),
+ windows: await windowRows(engine),
+ knownAsTrusted: (await card(false))?.rows.map(r => `${r.owner} ${r.from ?? '?'}..${r.to ?? 'open'}`),
+ knownAsRemote: (await card(true))?.rows.map(r => `${r.owner} ${r.from ?? '?'}..${r.to ?? 'open'}`) ?? [],
+ };
+}
+
+/**
+ * Twelve dated stints on one account (more than the card's 10 `known_as` rows),
+ * then the card and its `known_as.next` continuation followed to the end
+ * through `get_backlinks`. Returns owners in served order per reader.
+ */
+export async function knownAsContinuation(engine: BrainEngine) {
+ const { dispatchToolCall } = await import('../../src/mcp/dispatch.ts');
+ const names = ['Alder', 'Birch', 'Cedar', 'Dogwood', 'Elm', 'Fir', 'Ginkgo', 'Hazel', 'Ivy', 'Kauri', 'Linden', 'Maple'];
+ await doc(engine, 'companies/orbit-example-labs', 'Segment: research', { type: 'company', title: 'Orbit Example Labs' });
+ await doc(engine, 'meetings/orbit-history', ['| Account | Owner | Start | End |', '|---|---|---|---|',
+ ...names.map((n, i) => `| Orbit Example Labs | ${n} Example | ${2010 + i}-01-01 | ${2010 + i}-12-31 |`)].join('\n'), { date: '2024-01-05' });
+ await doc(engine, 'notes/orbit-private', 'Orbit Example Labs moves from Maple Example to Quill Example, effective 2023-02-01.', { date: '2023-01-20', private: true });
+ await sweepOwnerPhrases(engine);
+ const config = { engine: 'pglite' };
+ const local = { remote: false, sourceId: 'default', config };
+ const remote = { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'], config };
+ const call = async (op: string, args: Record<string, unknown>, ctx: Record<string, unknown>) => {
+ const r = await dispatchToolCall(engine, op, args, ctx as never);
+ return r.isError ? { error: r.content[0]!.text } : JSON.parse(r.content[0]!.text);
+ };
+ const follow = async (ctx: Record<string, unknown>) => {
+ const card = (await call('entity', { name: 'Orbit Example Labs' }, ctx)).card.known_as;
+ const owners: string[] = card.rows.map((r: { owner: string }) => r.owner);
+ const pages: number[] = [];
+ let next = card.next?.arguments ? { ...card.next.arguments, limit: 1 } : null;
+ while (next) {
+ const page = await call('get_backlinks', next, ctx);
+ pages.push(page.rows.length);
+ owners.push(...page.rows.map((r: { owner: string }) => r.owner));
+ next = page.cursor ? { ...next, cursor: page.cursor } : null;
+ }
+ const all = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', limit: 500 }, ctx);
+ return { total: card.total, shown: card.rows.length, next: card.next ? { tool: card.next.tool, group: card.next.arguments.group, requires_surface: card.next.requires_surface ?? null } : null,
+ followed: owners, pages, all: all.rows.map((r: { owner: string }) => r.owner), allTotal: all.total, truncated: all.truncated };
+ };
+ const verbs = (await call('entity', { name: 'Orbit Example Labs' }, { ...remote, surfaceCeiling: 'verbs' })).card.known_as.next?.requires_surface ?? null;
+ const badCursor = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', cursor: 'nope' }, local);
+ const withType = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', type: 'note' }, local);
+ return { trusted: await follow(local), remote: await follow(remote), verbs, badCursor: 'error' in badCursor, withType: 'error' in withType };
+}
diff --git a/test/owner-phrase-pass.test.ts b/test/owner-phrase-pass.test.ts
new file mode 100644
index 0000000000..dc012efc06
--- /dev/null
+++ b/test/owner-phrase-pass.test.ts
@@ -0,0 +1,236 @@
+/**
+ * Owner phrases, the stored pass on PGLite (docs/guides/owner-phrases.md):
+ * migration, windows, linking inside and outside windows, ambiguity refusal,
+ * visibility, corrections, deletion, enable/disable, concurrency, the policy
+ * fingerprint and final-score invariance across every link-counting ranking
+ * consumer.
+ *
+ * Protects: owner-phrase links stored as `link_source='mentions'`,
+ * `link_kind='owner_phrase'` only while `mentions.owner_phrases` is on; a
+ * window change alone relinking unedited documents; private-only evidence
+ * never reaching untrusted reads (links and `known_as`); plain mention links,
+ * policy fingerprints and final ranking scores unchanged by the key.
+ * Regression: an owner phrase linked outside its window or to one of two
+ * matching accounts, or an owner-phrase link that moves a search score.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { policyFingerprint } from '../src/core/mentions/pass.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../src/core/mentions/policy.ts';
+import { buildGazetteer } from '../src/core/by-mention.ts';
+import { runOwnerPhrasePass } from '../src/core/mentions/owner-phrase/pass.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+import { entityAnchoredPages } from '../src/core/search/entity-anchor.ts';
+import { applyGeneratedDemotion } from '../src/core/search/provenance-demotion.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { ACME, NIMBUS, WIDGET, doc, knownAsContinuation, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from './helpers/owner-phrase-brain.ts';
+
+let engine: PGLiteEngine;
+let snap: Awaited<ReturnType<typeof ownerPhraseSnapshot>>;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedOwnerPhraseBrain(engine);
+ snap = await ownerPhraseSnapshot(engine);
+}, 180_000);
+afterAll(async () => { await engine.disconnect(); });
+
+const plainLinks = async () => (await engine.executeRaw<{ f: string; t: string; k: string | null }>(
+ `SELECT f.slug AS f, t.slug AS t, l.link_kind AS k FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_kind IS DISTINCT FROM 'owner_phrase' ORDER BY 1, 2, 3`)).map(r => `${r.f} -> ${r.t} ${r.k ?? ''}`);
+const idOf = async (slug: string) => Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]))[0]!.id);
+
+describe('migration', () => {
+ test('the link_kind CHECK accepts owner_phrase and still refuses unknown kinds', async () => {
+ const [a, b] = [await idOf('notes/undated'), await idOf(ACME)];
+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, link_kind) VALUES ($1, $2, 'probe', 'mentions', 'owner_phrase')`, [a, b]);
+ await engine.executeRaw(`DELETE FROM links WHERE link_type = 'probe'`);
+ await expect(engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, link_kind) VALUES ($1, $2, 'probe', 'mentions', 'bogus')`, [a, b])).rejects.toThrow();
+ const tables = (await engine.executeRaw<{ t: string }>(`SELECT table_name AS t FROM information_schema.tables WHERE table_name LIKE 'owner_phrase_%' ORDER BY 1`)).map(r => r.t);
+ expect(tables).toEqual(['owner_phrase_page_state', 'owner_phrase_status', 'owner_phrase_windows']);
+ });
+});
+
+describe('windows and links', () => {
+ test('windows: an advance handoff, an ongoing owner with an unknown start, private evidence marked', () => {
+ expect(snap.windows).toEqual([
+ `${ACME} Quill Example 2025-05-01..open`, `${ACME} Rowan Example ?..2025-04-30`,
+ `${NIMBUS} Juniper Example ?..2025-05-31`, `${NIMBUS} Quill Example 2025-06-01..open`,
+ `${WIDGET} Quill Example 2025-02-01..open (private)`, `${WIDGET} Rowan Example ?..2025-01-31 (private)`,
+ ]);
+ });
+
+ test('a phrase links inside its owner window only; two matching accounts, no page date, an agent-only window and no owner never link', () => {
+ expect(snap.trusted).toEqual([`notes/benefits-call -> ${WIDGET}`, `notes/juniper-call -> ${NIMBUS}`, `notes/rate-review -> ${ACME}`, `notes/renewal -> ${ACME}`]);
+ for (const absent of ['notes/rate-followup', 'notes/escalation', 'notes/undated', 'notes/juniper-health']) expect(snap.trusted.join('\n')).not.toContain(absent);
+ });
+
+ test('the firing counter reports links, documents, unresolved and ambiguous phrases, and the status row matches', () => {
+ expect(snap.counters).toEqual({ state: 'complete', links: 4, documents: 4, unresolved: 3, ambiguous: 1, windows: 6 });
+ expect(snap.status).toEqual({ state: 'complete', windows: 6, links: 4, documents: 4, unresolved: 3, ambiguous: 1 });
+ });
+
+ test('visibility: a link whose only evidence is private, and its known_as window, are hidden from untrusted reads', () => {
+ expect(snap.remote).toEqual(snap.trusted.filter(l => !l.startsWith('notes/benefits-call')));
+ expect(snap.knownAsTrusted).toEqual(['Quill Example 2025-02-01..open', 'Rowan Example ?..2025-01-31']);
+ expect(snap.knownAsRemote).toEqual([]);
+ });
+
+ test('owner-phrase links reach the card through referenced_by, and owner phrases never become aliases', async () => {
+ const card = (await buildEntityCard(engine, 'default', 'Acme Example Freight', { remote: true, includeReferences: true })).card!;
+ expect(card.referenced_by!.flatMap(g => g.rows.map(r => r.slug)).sort()).toEqual(['notes/rate-review', 'notes/renewal', 'updates/acme-handoff']);
+ expect(card.known_as!.rows.map(r => r.owner)).toEqual(['Quill Example', 'Rowan Example']);
+ expect(card.aka ?? []).not.toEqual(expect.arrayContaining([expect.stringMatching(/freight account/i)]));
+ const aliases = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_aliases WHERE alias_norm LIKE '%account%'`);
+ expect(Number(aliases[0]!.n)).toBe(0);
+ });
+
+ test('a rerun with nothing changed writes nothing; parsed statements are cached under one key; an edited page or a stale key is reparsed', async () => {
+ const r = await sweepOwnerPhrases(engine);
+ expect(r).toMatchObject({ state: 'complete', created: 0, removed: 0, links: 4, unresolved: 3, ambiguous: 1, windows: 6 });
+ const keys = async () => (await engine.executeRaw<{ slug: string; k: string | null }>(
+ `SELECT p.slug, s.statements_key AS k FROM owner_phrase_page_state s JOIN pages p ON p.id = s.page_id WHERE jsonb_array_length(s.cues) > 0 ORDER BY 1`));
+ const before = await keys();
+ expect(before.length).toBeGreaterThan(3);
+ expect(new Set(before.map(k => k.k)).size).toBe(1);
+ expect(before[0]!.k).not.toBeNull();
+ const [status] = await engine.executeRaw<{ inputs_hash: string | null }>('SELECT inputs_hash FROM owner_phrase_status');
+ expect(status!.inputs_hash).not.toBeNull();
+ await doc(engine, 'updates/nimbus-owner', 'Juniper Example owns Nimbus Example Freight. Renewal is on track.', { date: '2025-01-01' });
+ await engine.executeRaw(`UPDATE owner_phrase_page_state SET statements_key = 'stale' WHERE page_id <> (SELECT id FROM pages WHERE slug = 'updates/nimbus-owner') AND statements_key IS NOT NULL`);
+ await sweepOwnerPhrases(engine);
+ expect(new Set((await keys()).map(k => k.k))).toEqual(new Set([before[0]!.k]));
+ expect(await ownerPhraseLinks(engine)).toEqual(snap.trusted);
+ });
+
+ test('a link another producer adds for a linked pair replaces the owner-phrase row on the next pass, with no page edited', async () => {
+ const [[f], [t]] = await Promise.all(['notes/renewal', ACME].map(slug => engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug])));
+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source) VALUES ($1, $2, 'mentions', 'manual')`, [f!.id, t!.id]);
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).not.toContain(`notes/renewal -> ${ACME}`);
+ await engine.executeRaw(`DELETE FROM links WHERE link_source = 'manual'`);
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual(snap.trusted);
+ });
+});
+
+describe('policy fingerprint', () => {
+ test('the key off leaves every existing fingerprint unchanged; on changes it', async () => {
+ const policy = await readMentionPolicy(engine);
+ const types = ['company', 'person'];
+ const legacy = createHash('sha256').update(JSON.stringify({
+ types, crossSource: false, ignore: [...policy.ignore].map(n => n.toLowerCase()).sort(),
+ aliasDeny: [...policy.aliasDeny].map(n => n.toLowerCase()).sort(), multiword: policy.multiwordAliases, siblings: policy.siblingMerge,
+ })).digest('hex').slice(0, 16);
+ expect(policyFingerprint(types, false, policy)).toBe(legacy);
+ expect(policyFingerprint(types, false, policy, false)).toBe(legacy);
+ expect(policyFingerprint(types, false, policy, true)).not.toBe(legacy);
+ });
+});
+
+describe('final-score invariance', () => {
+ async function readers() {
+ const slugs = ['notes/rate-review', 'notes/renewal', 'notes/benefits-call', 'notes/juniper-call', 'notes/generated-summary', ACME, NIMBUS, WIDGET];
+ const ids = await Promise.all(slugs.map(idOf));
+ const bySlug = <V>(m: Map<number, V>) => Object.fromEntries(slugs.map((s, i) => [s, m.get(ids[i]!)]).filter(([, v]) => v !== undefined));
+ const refs = ['notes/rate-review', ACME, NIMBUS, WIDGET].map(slug => ({ slug, source_id: 'default' }));
+ const pool = (): SearchResult[] => [ids[4]!, ids[5]!].map((page_id, i) => ({ page_id, slug: i ? ACME : 'notes/generated-summary', score: 1 - i * 0.1 }) as unknown as SearchResult);
+ const demoted = pool();
+ await applyGeneratedDemotion(engine, demoted, 'Acme Example Freight renewal', { sourceId: 'default' });
+ return {
+ backlinks: bySlug(await engine.getBacklinkCounts(ids)),
+ adjacency: bySlug(await engine.getAdjacencyBoosts(ids)),
+ salience: [...(await engine.getSalienceScores(refs)).entries()].sort(),
+ chain: (await engine.relationalChainHop([ids[5]!], { linkTypes: ['mentions'], toward: 'subject', subjectTypes: [], objectTypes: [], degreeLinkTypes: ['mentions'], neighborCap: 10 })).length,
+ anchored: (await entityAnchoredPages(engine, 'default', ACME)).pages.map(p => p.slug).sort(),
+ demotion: demoted.map(r => `${r.slug}:${r.score}`),
+ plain: await plainLinks(),
+ };
+ }
+
+ test('every link-counting consumer gives the same result with the key on and off, including threshold crossings', async () => {
+ await doc(engine, 'notes/generated-summary', "Quill's freight account renewed; summary of the week.", { date: '2025-05-13' });
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"dream_generated": true}'::jsonb WHERE slug = 'notes/generated-summary'`);
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toContain(`notes/generated-summary -> ${ACME}`);
+ const on = await readers();
+ // Threshold crossings a counted owner-phrase link would cause: a first backlink, a first adjacency hit, an anchored page, a demotion.
+ expect(on.backlinks[ACME] ?? 0).toBe(0);
+ expect(on.adjacency).toEqual({});
+ expect(on.anchored).not.toContain('notes/rate-review');
+ expect(on.demotion).toEqual(['notes/generated-summary:1', `${ACME}:0.9`]);
+
+ await engine.setConfig('mentions.owner_phrases', 'false');
+ const off = await sweepOwnerPhrases(engine);
+ expect(off).toMatchObject({ state: 'off', removed: 5 });
+ expect(await ownerPhraseLinks(engine)).toEqual([]);
+ expect(await readers()).toEqual(on);
+ });
+
+ test('disable cleared windows, scans and status; re-enable restores the same links', async () => {
+ expect(await windowRows(engine)).toEqual([]);
+ const left = await engine.executeRaw<{ n: number }>('SELECT (SELECT count(*) FROM owner_phrase_page_state) + (SELECT count(*) FROM owner_phrase_status) AS n');
+ expect(Number(left[0]!.n)).toBe(0);
+ await engine.setConfig('mentions.owner_phrases', 'true');
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual([...snap.trusted, `notes/generated-summary -> ${ACME}`].sort());
+ });
+});
+
+describe('known_as continuation', () => {
+ test('rows < total carries a get_backlinks group:"known_as" next that continues the card in order to the end; private windows stay hidden from untrusted reads', async () => {
+ const r = await knownAsContinuation(engine);
+ const owners = ['Quill Example', 'Maple Example', 'Linden Example', 'Kauri Example', 'Ivy Example', 'Hazel Example', 'Ginkgo Example', 'Fir Example',
+ 'Dogwood Example', 'Elm Example', 'Cedar Example', 'Birch Example', 'Alder Example'];
+ // 12 table stints, Quill's private takeover and Maple's private predecessor window ending the day before it.
+ expect(r.trusted).toMatchObject({ total: 14, shown: 10, next: { tool: 'get_backlinks', group: 'known_as', requires_surface: null }, allTotal: 14, truncated: false });
+ expect(r.trusted.all.slice(0, 3)).toEqual(['Quill Example', 'Maple Example', 'Maple Example']);
+ expect(r.trusted.followed).toEqual(r.trusted.all);
+ expect(r.trusted.pages).toEqual([1, 1, 1, 1]);
+ expect(r.remote).toMatchObject({ total: 12, shown: 10, allTotal: 12 });
+ expect(r.remote.followed).toEqual(r.remote.all);
+ expect(r.remote.all).not.toContain('Quill Example');
+ expect(new Set(r.trusted.all)).toEqual(new Set(owners));
+ expect(r.verbs).toBe('starter');
+ expect([r.badCursor, r.withType]).toEqual([true, true]);
+ });
+});
+
+describe('invalidation', () => {
+ test('a correction ends the wrong stint and relinks documents that were not edited; the generation advances', async () => {
+ const before = Number((await engine.executeRaw<{ g: string }>('SELECT generation::text AS g FROM owner_phrase_status'))[0]!.g);
+ await doc(engine, 'updates/acme-correction', 'Correction: Acme Example Freight went to Juniper Example, not Quill.', { date: '2025-04-17' });
+ await sweepOwnerPhrases(engine);
+ const links = await ownerPhraseLinks(engine);
+ expect(links).not.toContain(`notes/renewal -> ${ACME}`);
+ expect(links).toContain(`notes/rate-review -> ${ACME}`);
+ expect(await windowRows(engine)).toContain(`${ACME} Juniper Example 2025-05-01..open`);
+ expect(Number((await engine.executeRaw<{ g: string }>('SELECT generation::text AS g FROM owner_phrase_status'))[0]!.g)).toBe(before + 1);
+ });
+
+ test('deleting the only statement removes the windows and links it supported', async () => {
+ await engine.softDeletePage('updates/acme-correction');
+ await engine.softDeletePage('updates/acme-handoff');
+ await sweepOwnerPhrases(engine);
+ const links = await ownerPhraseLinks(engine);
+ expect(links.filter(l => l.endsWith(ACME))).toEqual([]);
+ expect((await windowRows(engine)).filter(w => w.startsWith(ACME))).toEqual([]);
+ });
+
+ test('two concurrent passes publish one consistent link set; a pass out of time stays pending and writes nothing', async () => {
+ const policy = await readMentionPolicy(engine);
+ const sequential = await ownerPhraseLinks(engine);
+ await doc(engine, 'notes/new-call', "Juniper's freight account called about a claim.", { date: '2025-04-02' });
+ const pack = await loadSourcePack(engine, 'default', { strict: true });
+ const opts = { sourceId: 'default', gazetteer: await buildGazetteer(engine, { policy, strict: true }), types: linkableTypesFor(pack, policy), pack, policy, enabled: true };
+ expect(await runOwnerPhrasePass(engine, { ...opts, deadline: Date.now() - 1 })).toMatchObject({ state: 'pending', created: 0, removed: 0 });
+ expect(await ownerPhraseLinks(engine)).toEqual(sequential);
+ const [a, b] = await Promise.all([runOwnerPhrasePass(engine, { ...opts, deadline: Infinity }), runOwnerPhrasePass(engine, { ...opts, deadline: Infinity })]);
+ expect([a.state, b.state]).toEqual(['complete', 'complete']);
+ expect(a.created + b.created).toBe(1);
+ expect(await ownerPhraseLinks(engine)).toEqual([...sequential, `notes/new-call -> ${NIMBUS}`].sort());
+ });
+});
diff --git a/test/owner-phrase-rules.test.ts b/test/owner-phrase-rules.test.ts
new file mode 100644
index 0000000000..b5834ce629
--- /dev/null
+++ b/test/owner-phrase-rules.test.ts
@@ -0,0 +1,243 @@
+/**
+ * Owner phrases, the pure rules (docs/guides/owner-phrases.md, contract lines
+ * 1-10): page scan, statement grammar, window assembly and phrase resolution.
+ * One test row per contract line, on a general (non-contract) corpus of
+ * team updates, tickets, chat and notes.
+ *
+ * Protects: handoffs ending the predecessor the day before, inclusive bounds,
+ * advance announcements, overlapping and open-ended stints, unknown starts,
+ * corrections voiding a stint, temporal filtering before ambiguity, refusal
+ * of two accounts sharing a descriptor, a phrase with no owner, non-owner and
+ * personal possessives, fallback page dates, belated notes whose readings
+ * disagree, agent-written pages and page-less accounts. Regression: a parser
+ * that links a phrase outside its owner's window, or that links when two
+ * accounts match.
+ */
+import { describe, expect, test } from 'bun:test';
+import { tokenizeTitle } from '../src/core/by-mention.ts';
+import { findDates } from '../src/core/mentions/owner-phrase/dates.ts';
+import { scanPage, type ScanInput } from '../src/core/mentions/owner-phrase/scan.ts';
+import { buildNameIndex, parseStatements, type Statement } from '../src/core/mentions/owner-phrase/statements.ts';
+import { accountDescriptors, buildWindows, descriptorMatches, ownerMatches, resolvePhrase, type OwnerWindow } from '../src/core/mentions/owner-phrase/windows.ts';
+
+const ACCOUNTS = ['Acme Example Freight', 'Widget Example Health', 'Orbit Example Labs', 'Nimbus Example Freight'];
+const slugOf = (t: string) => `companies/${t.toLowerCase().replace(/ /g, '-')}`;
+const accounts = buildNameIndex(ACCOUNTS.map(t => ({ slug: slugOf(t), title: t, tokens: tokenizeTitle(t) })));
+const persons = buildNameIndex([{ slug: 'people/rowan-example', title: 'Rowan Example', tokens: tokenizeTitle('Rowan Example') }]);
+const descriptorSets = new Map(ACCOUNTS.map(t => [slugOf(t), accountDescriptors([t], [])]));
+const descriptorAccounts = new Map<string, Set<string>>();
+for (const [slug, set] of descriptorSets) for (const d of set) descriptorAccounts.set(d, new Set([...(descriptorAccounts.get(d) ?? []), slug]));
+const descriptorsOf = (g: string) => descriptorSets.get(g) ?? accountDescriptors([g.replace(/^pseudo:/, '')], []);
+
+let nextId = 1;
+function page(slug: string, body: string, opts: Partial<ScanInput> & { date?: string | null } = {}) {
+ const input: ScanInput = { slug, type: opts.type ?? 'note', title: opts.title ?? slug, compiled_truth: body, timeline: '', frontmatter: opts.frontmatter ?? {},
+ effective_date: opts.date === undefined ? '2025-03-10' : opts.date, effective_date_source: opts.date === null ? 'fallback' : 'date' };
+ return { slug, id: nextId++, scan: scanPage(input) };
+}
+function statementsOf(p: ReturnType<typeof page>, selfAccount: string | null = null): Statement[] {
+ return parseStatements(p.scan.cues, { page: { id: p.id, slug: p.slug, date: p.scan.date, agent: p.scan.agent }, selfAccount, accounts, persons, descriptorAccounts });
+}
+const brief = (s: Statement[]) => s.map(x => [x.kind, x.owner, x.from ?? null, x.account, x.date]);
+const windowsOf = (...pages: Array<ReturnType<typeof page> | [ReturnType<typeof page>, string]>) =>
+ buildWindows(pages.flatMap(p => Array.isArray(p) ? statementsOf(p[0], p[1]) : statementsOf(p)), s => s);
+const span = (w: OwnerWindow[]) => w.map(x => `${x.group.split('/')[1]} ${x.owner} ${x.from ?? '?'}..${x.to ?? 'open'}${x.startKnown ? '' : ' (start unknown)'}`).sort();
+const resolve = (w: OwnerWindow[], owner: string, descriptor: string, date: string | null, readings: string[] = []) =>
+ resolvePhrase({ owner, descriptor }, date, readings, w, descriptorsOf);
+
+describe('line 1-3: scan, statements and dates are separate inputs', () => {
+ test('a page scan keeps cue lines, owner phrases and its own date; a fallback date is no date', () => {
+ const p = page('notes/n1', "Quill Example takes over Acme Example Freight from Rowan Example on April 1.\nQuill's freight account wants a rate review.");
+ expect(p.scan.date).toBe('2025-03-10');
+ expect(p.scan.cues.map(c => c.line)).toEqual([1]);
+ expect(p.scan.hits).toEqual([{ owner: 'Quill', descriptor: 'freight', noun: 'account', line: 2, surface: "Quill's freight account" }]);
+ expect(page('notes/n2', 'x', { date: null }).scan.date).toBeNull();
+ });
+
+ test('owner phrase forms: possessive, book, full name, "the X account Y runs"; plural and personal accounts are not phrases', () => {
+ const hits = page('notes/n3', [
+ "Ask about Quill Example's freight account.", "Rowan's health book is quiet.", 'The labs account Quill handles renewed.',
+ "Quill's freight accounts are busy.", "Rowan's health account at the benefits portal needs a login.",
+ ].join('\n')).scan.hits.map(h => `${h.owner}/${h.descriptor}/${h.noun}`);
+ expect(hits).toEqual(['Quill Example/freight/account', 'Rowan/health/book', 'Quill/labs/account']);
+ });
+
+ test('dates: ISO, written, month-only and year-less dates take the nearest year', () => {
+ expect(findDates('on 2025-04-01, April 2, 2025, 3 May 2025, and March 2025', null).map(d => [d.iso, d.last]))
+ .toEqual([['2025-04-01', '2025-04-01'], ['2025-04-02', '2025-04-02'], ['2025-05-03', '2025-05-03'], ['2025-03-01', '2025-03-31']]);
+ expect(findDates('starting January 5', '2024-12-20')[0]!.iso).toBe('2025-01-05');
+ });
+});
+
+describe('line 2: the statement grammar', () => {
+ test('takeover forms name the new owner, the predecessor and the date', () => {
+ const p = page('updates/u1', [
+ 'Starting April 1, Quill Example takes over Acme Example Freight from Rowan Example.',
+ 'Widget Example Health moves from Rowan Example to Quill Example, effective March 1.',
+ 'Rowan Example hands Orbit Example Labs to Quill Example on 2025-05-01.',
+ ].join('\n'));
+ expect(brief(statementsOf(p))).toEqual([
+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Acme Example Freight'), '2025-04-01'],
+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Widget Example Health'), '2025-03-01'],
+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Orbit Example Labs'), '2025-05-01'],
+ ]);
+ });
+
+ test('ongoing, join, end and stint forms; a start cue dates the start', () => {
+ const p = page('updates/u2', [
+ 'Quill Example owns Acme Example Freight.',
+ 'Rowan Example owns the Widget Example Health relationship as of February 1.',
+ 'Quill Example started on Orbit Example Labs on June 15.',
+ 'Rowan Example rolls off Orbit Example Labs on 2025-06-30.',
+ 'Rowan Example ran Nimbus Example Freight from 2024-01-01 to 2024-12-31.',
+ ].join('\n'));
+ expect(brief(statementsOf(p))).toEqual([
+ ['ongoing', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-03-10'],
+ ['join', 'Rowan Example', null, slugOf('Widget Example Health'), '2025-02-01'],
+ ['join', 'Quill Example', null, slugOf('Orbit Example Labs'), '2025-06-15'],
+ ['end', 'Rowan Example', null, slugOf('Orbit Example Labs'), '2025-06-30'],
+ ['stint', 'Rowan Example', null, slugOf('Nimbus Example Freight'), '2024-01-01'],
+ ]);
+ });
+
+ test('negated, hypothetical, questioned and relative-dated sentences set nothing', () => {
+ const p = page('notes/n4', [
+ 'Quill Example did not take over Acme Example Freight.',
+ 'Quill Example might take over Acme Example Freight.',
+ 'Will Quill Example take over Acme Example Freight?',
+ 'Next week Quill Example takes over Acme Example Freight.',
+ ].join('\n'));
+ const s = statementsOf(p);
+ expect(s.filter(x => x.date)).toEqual([]);
+ });
+
+ test('labels and tables: an account page label, an owner table and a handoff table', () => {
+ const acct = page(slugOf('Acme Example Freight'), 'Account owner: Quill Example (since 2025-01-15)\nSegment: logistics', { type: 'company' });
+ expect(brief(statementsOf(acct, slugOf('Acme Example Freight')))).toEqual([['takeover', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-01-15']]);
+ expect(acct.scan.descriptors).toEqual(['logistics']);
+ const table = page('meetings/m1', [
+ '| Account | Owner | Start | End |', '|---|---|---|---|', '| Orbit Example Labs | Rowan Example | 2024-02-01 | 2024-09-30 |', '',
+ '| Account | Outgoing | Incoming | Effective |', '|---|---|---|---|', '| Widget Example Health | Rowan Example | Quill Example | 2025-04-01 |',
+ ].join('\n'));
+ expect(brief(statementsOf(table))).toEqual([
+ ['stint', 'Rowan Example', null, slugOf('Orbit Example Labs'), '2024-02-01'],
+ ['takeover', 'Quill Example', 'Rowan Example', slugOf('Widget Example Health'), '2025-04-01'],
+ ]);
+ });
+
+ test('a chat speaker speaks for the first person; a ticket owner label on a non-account page is not an account owner', () => {
+ const chat = page('chat/c1', "[09:14] Quill Example: I'm picking up Acme Example Freight starting today", { type: 'chat' });
+ expect(brief(statementsOf(chat))).toEqual([['takeover', 'Quill Example', null, slugOf('Acme Example Freight'), '2025-03-10']]);
+ expect(statementsOf(page('tickets/t1', 'Owner: Rowan Example\nCustomer: Acme Example Freight', { type: 'ticket' }))).toEqual([]);
+ });
+
+ test('line 4: an agent-written page sets no window; its owner phrases still scan', () => {
+ const p = page('notes/agent-1', "Quill Example owns Orbit Example Labs. Quill's labs account is fine.", { type: 'agent-note' });
+ expect(p.scan.agent).toBe(true);
+ expect(statementsOf(p)).toEqual([]);
+ expect(p.scan.hits.length).toBe(1);
+ });
+});
+
+describe('lines 5-6: window assembly', () => {
+ test('a handoff ends the predecessor the day before; an advance announcement works; bounds are inclusive', () => {
+ const w = windowsOf(page('mail/a', 'From May 1, Quill Example takes over Acme Example Freight from Rowan Example.', { date: '2025-04-15' }));
+ expect(span(w)).toEqual(['acme-example-freight quill example 2025-05-01..open', 'acme-example-freight rowan example ?..2025-04-30 (start unknown)']);
+ expect(resolve(w, 'Rowan', 'freight', '2025-04-30')).toMatchObject({ linked: true });
+ expect(resolve(w, 'Rowan', 'freight', '2025-05-01')).toMatchObject({ linked: false, reason: 'outside_window' });
+ expect(resolve(w, 'Quill', 'freight', '2025-05-01')).toMatchObject({ linked: true });
+ expect(resolve(w, 'Quill', 'freight', '2025-04-30')).toMatchObject({ linked: false, reason: 'outside_window' });
+ });
+
+ test('a join overlaps; an explicit end closes on its own day; an open stint runs on', () => {
+ const w = windowsOf(
+ [page(slugOf('Orbit Example Labs'), 'Account manager: Rowan Example, 2024-06-01 to 2025-06-30.', { type: 'company' }), slugOf('Orbit Example Labs')],
+ page('notes/b', 'Quill Example started on Orbit Example Labs on June 15.', { date: '2025-07-08' }));
+ expect(span(w)).toEqual(['orbit-example-labs quill example 2025-06-15..open', 'orbit-example-labs rowan example 2024-06-01..2025-06-30']);
+ });
+
+ test('an ongoing statement with no start opens after the latest earlier stint; a contradicting one is ignored', () => {
+ const w = windowsOf(
+ page('notes/c1', 'Rowan Example ran Acme Example Freight from 2024-01-01 to 2024-06-30.', { date: '2024-07-01' }),
+ page('notes/c2', 'Quill Example owns Acme Example Freight.', { date: '2024-09-01' }),
+ page('notes/c3', 'Rowan Example handles Acme Example Freight.', { date: '2024-10-01' }));
+ expect(span(w)).toEqual(['acme-example-freight quill example 2024-07-01..open (start unknown)', 'acme-example-freight rowan example 2024-01-01..2024-06-30']);
+ });
+
+ test('line 5: a correction voids the wrong stint and starts the right owner on its date; mentions between both dates do not link to the wrong owner', () => {
+ const w = windowsOf(
+ page('mail/h', 'Widget Example Health moves from Rowan Example to Quill Example, effective March 1.', { date: '2025-03-03' }),
+ page('mail/c', 'Correction: Widget Example Health went to Orbit Person, not Quill. Thanks.', { date: '2025-03-07' }));
+ expect(span(w)).toEqual(['widget-example-health orbit person 2025-03-01..open', 'widget-example-health rowan example ?..2025-02-28 (start unknown)']);
+ expect(resolve(w, 'Quill', 'health', '2025-03-05')).toMatchObject({ linked: false, reason: 'no_owner' });
+ expect(resolve(w, 'Orbit', 'health', '2025-03-05')).toMatchObject({ linked: true });
+ });
+
+ test('identity groups merge stints named on sibling pages', () => {
+ const groups = new Map([[slugOf('Acme Example Freight'), 'g'], [slugOf('Nimbus Example Freight'), 'g']]);
+ const w = buildWindows([
+ ...statementsOf(page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.')),
+ ...statementsOf(page('b', 'Quill Example rolls off Nimbus Example Freight on 2025-02-01.')),
+ ], s => groups.get(s) ?? s);
+ expect(w.map(x => [x.group, x.from, x.to, x.accounts])).toEqual([['g', '2025-01-01', '2025-02-01', [slugOf('Acme Example Freight'), slugOf('Nimbus Example Freight')]]]);
+ });
+});
+
+describe('lines 7-10: resolution', () => {
+ test('descriptors are name words without suffixes plus declared ones', () => {
+ expect([...accountDescriptors(['CRM record: Acme Example Freight Inc'], ['logistics'])].sort()).toEqual(['acme', 'example', 'freight', 'logistics']);
+ });
+
+ test('a descriptor run of up to three words matches when it is one descriptor or every word is a descriptor word; labels count after a sentence boundary', () => {
+ const set = new Set(['freight', 'north america', 'emea']);
+ expect(descriptorMatches(set, 'freight')).toBe(true);
+ expect(descriptorMatches(set, 'emea freight')).toBe(true);
+ expect(descriptorMatches(set, 'north america freight')).toBe(true);
+ expect(descriptorMatches(set, 'new freight')).toBe(false);
+ expect(descriptorMatches(set, 'america')).toBe(false);
+ const acct = page(slugOf('Orbit Example Labs'), 'Account: Orbit Example Labs. Industry: robotics. Region: EMEA.', { type: 'company' });
+ expect(acct.scan.descriptors).toEqual(['emea', 'robotics']);
+ expect(page('notes/n5', "Quill Example's North America robotics account renewed.").scan.hits.map(h => h.descriptor)).toEqual(['north america robotics']);
+ });
+
+ test('owner matching: one word matches a first name, two words the full name', () => {
+ expect(ownerMatches('Quill', { owner: 'quill example' })).toBe(true);
+ expect(ownerMatches('Quill Example', { owner: 'quill example' })).toBe(true);
+ expect(ownerMatches('Quill Other', { owner: 'quill example' })).toBe(false);
+ });
+
+ test('temporal candidates first, then ambiguity: two freight accounts are ambiguous only once one owner holds both', () => {
+ const w = windowsOf(
+ page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.'),
+ page('b', 'Rowan Example owns Nimbus Example Freight.', { date: '2025-01-01' }),
+ page('c', 'Nimbus Example Freight moves from Rowan Example to Quill Example on 2025-06-01.'));
+ expect(resolve(w, 'Quill', 'freight', '2025-03-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });
+ expect(resolve(w, 'Quill', 'freight', '2025-07-01')).toMatchObject({ linked: false, reason: 'ambiguous' });
+ expect(resolve(w, 'Quill', 'acme', '2025-07-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });
+ });
+
+ test('a phrase with no owner, a non-owner possessive and no page date never link', () => {
+ const w = windowsOf(page('a', 'Quill Example takes over Acme Example Freight on 2025-01-01.'));
+ expect(resolve(w, 'Juniper', 'freight', '2025-03-01')).toMatchObject({ linked: false, reason: 'no_owner' });
+ expect(resolve(w, 'Quill', 'robotics', '2025-03-01')).toMatchObject({ linked: false, reason: 'no_owner' });
+ expect(resolve(w, 'Quill', 'freight', null)).toMatchObject({ linked: false, reason: 'no_page_date' });
+ });
+
+ test('line 10: a belated note links only when both readings agree', () => {
+ const w = windowsOf(page('a', 'Starting 2025-05-01, Quill Example takes over Acme Example Freight from Rowan Example.'));
+ const note = page('notes/belated', "Belated note on the April 20 call: Rowan's freight account asked for a refund.", { date: '2025-05-10' });
+ expect(note.scan.readings).toEqual(['2025-04-20']);
+ expect(resolve(w, 'Rowan', 'freight', note.scan.date, note.scan.readings)).toMatchObject({ linked: false, reason: 'outside_window' });
+ expect(resolve(w, 'Quill', 'freight', note.scan.date, note.scan.readings)).toMatchObject({ linked: false, reason: 'readings_disagree' });
+ expect(resolve(w, 'Quill', 'freight', '2025-05-10', ['2025-05-03'])).toMatchObject({ linked: true });
+ });
+
+ test('a page-less account still competes for its owner\'s phrases and is never a link target', () => {
+ const w = windowsOf(
+ page('a', 'Quill Example owns Acme Example Freight.', { date: '2025-01-01' }),
+ page('b', 'As of July 1, Quill Example will own Harbor Placeholder Freight in addition to her current book.', { date: '2025-06-20' }));
+ expect(w.map(x => x.group).sort()).toEqual([slugOf('Acme Example Freight'), 'pseudo:harbor placeholder freight']);
+ expect(resolve(w, 'Quill', 'freight', '2025-03-01')).toMatchObject({ linked: true, group: slugOf('Acme Example Freight') });
+ expect(resolve(w, 'Quill', 'freight', '2025-08-01')).toMatchObject({ linked: false, reason: 'ambiguous' });
+ });
+});
diff --git a/test/owner-phrase-sample.test.ts b/test/owner-phrase-sample.test.ts
new file mode 100644
index 0000000000..901ae50678
--- /dev/null
+++ b/test/owner-phrase-sample.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Owner-phrase precision sample (scripts/owner-phrase-sample.ts,
+ * mentions/owner-phrase/sample.ts): the read-only derivation, sampling rule
+ * v1, the labeling TSV and the Wilson bound.
+ *
+ * Protects: the dry run deriving exactly the links the stored pass would
+ * write, without writing (it runs inside a READ ONLY transaction and leaves
+ * every table unchanged, with `mentions.owner_phrases` off); a sample
+ * reproducible from the operator's seed; the refusal below 22 links; stdout
+ * carrying counts only. Regression: a sampler that differs from the pass, a
+ * sample that changes between runs, or a log line naming a page.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { deriveOwnerPhraseLinks, sampleLinks, scoreLabels, toTsv, wilsonLower, SAMPLE_MIN_POPULATION, TSV_COLUMNS } from '../src/core/mentions/owner-phrase/sample.ts';
+import { doc, ownerPhraseLinks, seedOwnerPhraseBrain, sweepOwnerPhrases } from './helpers/owner-phrase-brain.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'owner-phrase-sample-'));
+const brainPath = join(dir, 'brain.pglite');
+let engine: PGLiteEngine;
+
+async function counts(e: PGLiteEngine) {
+ const [r] = await e.executeRaw<Record<string, number>>(`SELECT (SELECT count(*) FROM links)::int AS links, (SELECT count(*) FROM owner_phrase_windows)::int AS windows,
+ (SELECT count(*) FROM owner_phrase_page_state)::int AS states, (SELECT count(*) FROM owner_phrase_status)::int AS status, (SELECT count(*) FROM config)::int AS config`);
+ return r;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: brainPath } as never);
+ await engine.initSchema();
+ await seedOwnerPhraseBrain(engine, { enabled: false });
+ for (let i = 1; i <= 24; i++) {
+ await doc(engine, `notes/call-${String(i).padStart(2, '0')}`, `Call recap: Quill's freight account asked about lane ${i}.`, { date: `2025-05-${String(i + 1).padStart(2, '0')}` });
+ }
+ await sweepOwnerPhrases(engine);
+ await engine.executeRaw("INSERT INTO sources(id, name) VALUES('small-example', 'small-example') ON CONFLICT DO NOTHING");
+ await doc(engine, 'notes/small', "Quill's freight account called.", { date: '2025-06-02' });
+ await engine.executeRaw("UPDATE pages SET source_id = 'small-example' WHERE slug = 'notes/small'");
+}, 180_000);
+afterAll(async () => { await engine.disconnect().catch(() => {}); rmSync(dir, { recursive: true, force: true }); });
+
+describe('read-only derivation', () => {
+ let derivedPairs: string[];
+ test('derives inside a READ ONLY transaction with the key off and writes nothing', async () => {
+ const before = await counts(engine);
+ const derived = await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ return deriveOwnerPhraseLinks(tx, 'default');
+ });
+ expect(await counts(engine)).toEqual(before);
+ expect(before).toMatchObject({ windows: 0, states: 0, status: 0 });
+ expect(derived.links.length).toBe(28);
+ expect(derived.windows).toBe(6);
+ derivedPairs = derived.links.map(l => `${l.doc} -> ${l.account}`);
+ const renewal = derived.links.find(l => l.doc === 'notes/renewal')!;
+ expect(renewal).toMatchObject({ phrase: "Quill's freight account", line: 1, windows: [{ owner: 'Quill Example', from: '2025-05-01', to: null }],
+ evidence: [{ slug: 'updates/acme-handoff', line: 1 }] });
+ });
+
+ test('the derived links are exactly the links the stored pass writes once the key is on', async () => {
+ await engine.setConfig('mentions.owner_phrases', 'true');
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual([...derivedPairs].sort());
+ await engine.setConfig('mentions.owner_phrases', 'false');
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual([]);
+ });
+});
+
+describe('sampling rule v1, TSV and scoring', () => {
+ test('a seed reproduces the sample; another seed reorders it; n caps it', async () => {
+ const { links } = await deriveOwnerPhraseLinks(engine, 'default');
+ const a = sampleLinks(links, 'seed-a', 10).map(l => l.doc);
+ expect(sampleLinks(links, 'seed-a', 10).map(l => l.doc)).toEqual(a);
+ expect(sampleLinks(links, 'seed-b', 10).map(l => l.doc)).not.toEqual(a);
+ expect(sampleLinks(links, 'seed-a', 100)).toHaveLength(links.length);
+ expect(sampleLinks([...links].reverse(), 'seed-a', 10).map(l => l.doc)).toEqual(a);
+ });
+
+ test('the TSV has the labeling columns and one row per sampled link; labels score with a Wilson 95% lower bound', async () => {
+ const { links } = await deriveOwnerPhraseLinks(engine, 'default');
+ const tsv = toTsv(sampleLinks(links, 's', 3).map(l => ({ ...l, excerpt: 'line\twith tab' })));
+ const rows = tsv.split('\n').filter(Boolean).map(r => r.split('\t'));
+ expect(rows[0]).toEqual([...TSV_COLUMNS]);
+ expect(rows.slice(1).every(r => r.length === TSV_COLUMNS.length && r[3] === 'line with tab')).toBe(true);
+ const labeled = [rows[0]!.join('\t'), ...rows.slice(1).map((r, i) => [...r.slice(0, 7), i === 2 ? 'n' : 'y'].join('\t'))].join('\n');
+ expect(scoreLabels(labeled)).toMatchObject({ labeled: 3, correct: 2, wrong: 1, unlabeled: 0 });
+ expect(wilsonLower(57, 60)).toBeGreaterThanOrEqual(0.85);
+ expect(wilsonLower(56, 60)).toBeLessThan(0.85);
+ expect(wilsonLower(92, 100)).toBeGreaterThanOrEqual(0.85);
+ expect(wilsonLower(91, 100)).toBeLessThan(0.85);
+ });
+});
+
+describe('scripts/owner-phrase-sample.ts', () => {
+ const run = (args: string[]) => Bun.spawnSync(['bun', 'scripts/owner-phrase-sample.ts', '--pglite', brainPath, ...args], { cwd: join(import.meta.dir, '..'), env: { ...process.env, GBRAIN_HOME: dir } });
+
+ test('writes the sample to the named path; stdout names no page; a repeat with the same seed is byte-identical', async () => {
+ await engine.disconnect();
+ const out = join(dir, 'sample.tsv');
+ const first = run(['--out', out, '--seed', 'operator-seed', '--n', '25']);
+ expect(first.exitCode).toBe(0);
+ const stdout = first.stdout.toString() + first.stderr.toString();
+ const summary = JSON.parse(first.stdout.toString().trim().split('\n').at(-1)!);
+ expect(summary).toMatchObject({ rule: 'owner-phrase-sample-v1', population: 28, sample: 25, windows: 6 });
+ expect(stdout).not.toMatch(/notes\/|companies\/|Quill|Rowan|Juniper|freight/);
+ const tsv = readFileSync(out, 'utf8');
+ expect(tsv.trim().split('\n')).toHaveLength(26);
+ expect(run(['--out', out, '--seed', 'operator-seed', '--n', '25']).exitCode).toBe(3);
+ expect(run(['--out', out, '--seed', 'operator-seed', '--n', '25', '--force']).exitCode).toBe(0);
+ expect(readFileSync(out, 'utf8')).toBe(tsv);
+ const all = run(['--out', join(dir, 'all.tsv'), '--seed', 'operator-seed', '--n', '25', '--source', 'all']);
+ expect(all.exitCode).toBe(0);
+ expect(JSON.parse(all.stdout.toString().trim().split('\n').at(-1)!)).toMatchObject({ population: 28, sample: 25 });
+ }, 120_000);
+
+ test(`refuses below ${SAMPLE_MIN_POPULATION} links and writes nothing`, async () => {
+ const out = join(dir, 'small.tsv');
+ const r = run(['--out', out, '--seed', 'x', '--source', 'small-example']);
+ expect(r.exitCode).toBe(3);
+ expect(JSON.parse(r.stdout.toString().trim().split('\n').at(-1)!)).toMatchObject({ population: 0 });
+ expect(() => readFileSync(out)).toThrow();
+ }, 120_000);
+});
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index 9fc3242bb4..20cfd0b786 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -1115,6 +1115,12 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// doctor reader probes for the column on older brains.
'pages.links_attendance_blocked_revision',
'pages.links_attendance_blocked_at',
+ // Owner phrases (v243): migration-only tables created with these columns in
+ // the same migration; the ADD COLUMN IF NOT EXISTS lines only widen tables an
+ // unreleased build created earlier. No schema blob references them.
+ 'owner_phrase_page_state.statements',
+ 'owner_phrase_page_state.statements_key',
+ 'owner_phrase_status.inputs_hash',
]);
test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {