AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(watchlist): harden entity parsing and finding auto-link after adversarial review
Rufus8963901a35b6
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 103a1624..9d166a8d 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1382,13 +1382,25 @@ external_monitoring:- grounding vocabulary = company name + competitive_landscape.primary_competitors+ profile.vendors + profile.tickers + active initiative titles +strategic_priorities.current_year + each department's `watched_entities`.- Named-entity lists are PARSED (watch_policy.entity_names): only the- name(s) before " — " / " - " / ":" ground, "A / B" yields both names, and- a parenthesised ticker ("Tesla (TSLA)") becomes a ticker term of its own;- the free-text description is dropped (it hid short names such as BYD- inside a sentence and would have made "global" BYD's own-source word).+ Named-entity lists are PARSED (watch_policy.entity_names, input+ whitespace-collapsed and capped at 256 chars): only the name(s) before+ an em/en dash (any spacing), " - ", ":" or ";" ground, "A / B" yields+ both names, a parenthesised group that is ONE ticker-shaped token+ ("Tesla (TSLA)", "BYD (1211.HK)", not "(US, EU)" nor ordinary+ abbreviations such as US/EV/IT/NOW) becomes a ticker term, and+ parenthesised hosts ("Brex (brex.com, status.brex.com)") PIN the+ entity's own domains. A bare URL / host entry grounds as its site label+ with the host pinned. The description is dropped (it hid short names+ such as BYD inside a sentence and would have made "global" BYD's+ own-source word); parenthesised brand names ("Alphabet (Google)") are+ not aliases — list them as entries. profile.tickers are taken as typed.Short names (BYD, GM, Kia, AWS) match as whole words because a- vocabulary term of any length is a distinctive token.+ vocabulary term of any length is a distinctive token; a TICKER term+ grounds only when it IS the entity ("US" never grounds "US Foods").+ Own source with pinned domains: only those sites (a look-alike such as+ gm.co.ke, which carries the same site label, no longer qualifies);+ without pinned domains the site label must be the entity's leading+ name, as before — pin domains for any short-named entity.(kind department_entity, strong) + each department's charter scopephrases and goal key results (kind department_scope, suggestion-only)(+ existing watch labels, which only corroborate). The entity MUST@@ -1430,12 +1442,16 @@ external_monitoring:"1211.HK" is two words once normalized) or is the named entity. A strongfinding cannot be borrowed for an unrelated page.- `finding_index` is REQUIRED in the propose_watch schema and the pass's- RULES say so; when the model still omits it (three dev runs on Haiku- and Sonnet omitted it on every proposal), apply_proposals auto-links the- first finding that concerns the source by the same test- (watch_policy.auto_link_finding) and records "linked to finding #N by- its cited source" as the first reason. A proposal nothing cites is- still rejected as having no evidence.+ RULES say so; when the model still omits it, or cites a finding that+ does not concern the source (three dev runs on Haiku and Sonnet omitted+ it on every proposal), apply_proposals links the finding that best+ concerns the source by the same test the score uses+ (watch_policy.auto_link_finding: with the entity term classify would+ use; ranked by citing the target's site / naming the ticker, then+ citing the entity's own site, confidence, verification, order) and+ records "linked to finding #N, which concerns this source" as the+ first reason. The caller's proposal is not mutated. A proposal nothing+ cites is still rejected as having no evidence.- direct add at score >= 4 with the mandatory match AND the entity's OWNsource AND a linked finding that concerns this source (company dataplus a decision mention can reach the bar alone; nothing goes live ondiff --git a/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json b/packages/core/openexecutive/architecture/prebuilt/external_monitoring.jsonindex 29f5e2ba..10f0bdfe 100644--- a/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json+++ b/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json@@ -1,7 +1,7 @@{"section_id": "external_monitoring","title": "External Monitoring",- "markdown": "`openexecutive.monitoring` watches the outside world on a heartbeat and turns detected changes into briefing proposals via the same alert pipeline that handles inbound email and Slack.\n\nThe `external_monitor_scan` heartbeat (`__internal__` channel, default every 5 min) walks `list_watchlist(enabled_only=True)`, skipping rows fresher than their per-source cadence floor. For each due row it fires a read-only source adapter resolved from `_REGISTRY` by `signal_type`:\n\n- `vendor_status` — Statuspage Atom/RSS incident feeds (AWS, Stripe, GitHub, …). Reads each incident's current status out of the entry body, parses `<updated>` into `published_at`, and keys its dedup on `(entry id, <updated>)`; a **seeding** source (see below).\n- `rss` — generic Atom/RSS via feedparser (changelogs, layoffs.fyi, filings). Parses each entry's `<pubDate>`/`<updated>` into `published_at`; a **seeding** source (see below).\n- `stock` — Yahoo Finance chart endpoint; fires on `abs_change_pct_gte` moves.\n- `page_watch` — change-detection on a feed-less page. Fetches via the keyless httpx fetcher by default, or via xcrawl's scrape API when the row carries `config.fetch = \"xcrawl\"` — so JS-rendered / bot-blocked pages that publish no RSS (most modern news / marketing sites) are still monitorable.\n- `edgar` and the BILLED `query` web-search adapter.\n\nEach `Signal` is trigger-filtered, severity-clamped to the row's `[floor, ceiling]`, and INSERTed into `external_signals` where `UNIQUE(dedup_key)` drops replays. Survivors pass a suppression cascade (`baseline` → `stale` → `dry_run` → `below_floor` → capture-time relevance enrichment → promote), then `promote_signal_to_alert` builds an `AlertEvent` handed to `alerts.pipeline.schedule_evaluation` and surfaced as a `/today` proposal.\n\nEvery signal carries two timestamps that are never conflated: `captured_at` (when the monitor first saw it) and `published_at` (when the upstream says it happened — RSS `<pubDate>`, EDGAR filing date; null for `stock`, `page_watch`, `query`). Two freshness gates run first in the cascade, before anything that costs an LLM call. **Baseline:** the first poll that returns entries for a row whose adapter declares `seed_on_first_poll` (`rss`, `edgar`) records every entry already in the feed — trigger misses included, so the first entry that ever matches a keyword is news and a later, wider trigger can't resurface old ones — as `suppressed_baseline`, promotes nothing, and stamps `watchlist.baselined_at`, so a new watch reports what changes from now on instead of replaying the feed's back-catalogue (the same idea as `page_watch`'s first-observation baseline). It is keyed on `baselined_at` rather than `last_polled_at`, so a failed first fetch can't forfeit it; the claim and the recording are one transaction (a compare-and-swap on the stamp plus the rows, all-or-nothing), so of two overlapping scans exactly one records the back-catalogue and a failure part-way leaves nothing behind to replay; the other scan promotes only entries dated after that stamp (undated entries count as baseline, since the feed controls the date; entries dated more than a few minutes past its own clock are deferred rather than recorded); and baseline rows don't count against `max_signals_per_scan`, so a large feed can't be half-baselined. `vendor_status` used to sit outside both gates for a structural reason: its dedup key was `sha256(slug, entry id)`, and an incident's id never changes across its updates, so any suppressed insert muted that incident for good. Keying on `(entry id, <updated>)` instead (issue #90) makes a suppression cost one *state* of an incident rather than the incident, so both gates now apply to vendor feeds too — and an incident moving Investigating → Resolved mints a new key and surfaces, while re-polling an unchanged feed still dedups. Because a history feed's archive is mostly incidents resolved months ago, the adapter also carves live news out of its own baseline: it reads each incident's current status from the entry body (Statuspage renders the newest update first as `<strong>Resolved</strong>` / `Investigating` / `Monitoring` / … — the body is parsed by a real HTML parser, off the event loop, and the reading is deliberately asymmetric: any sign that the incident is over closes it, wherever it appears, while only a marked-up label can say it is still open. Working out which update is newest turned out to be something tag soup cannot be trusted to express, and every attempt reported a long-resolved incident as live) and exempts the ones still OPEN via the optional `promote_on_baseline` hook, so a watch added during an outage reports that outage on its first poll while the resolved archive is recorded as `suppressed_baseline`. An unrecognised status counts as closed — a vendor changing feed format must not be able to promote its whole archive at HIGH, and nothing is lost, since the next `<updated>` bump surfaces normally. An exempt entry must still pass the row's trigger filter (one that misses stays in the baseline, so widening a trigger later cannot resurface it) and is still judged by the stale gate below: the exemption buys an entry past the baseline, never past its own timestamp, because \"this is live\" is a reading of vendor-controlled markup and an entry the feed dates outside the age window is not news whatever that reading says. **Stale:** a signal whose `published_at` is older than `EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS` (default 7; `0` disables) at capture time is recorded as `suppressed_stale` and never promoted — a January article a feed resurfaces in September is not September news. An entry dated more than `EXTERNAL_MONITOR_MAX_FUTURE_SKEW_HOURS` ahead (default 24; `0` disables; `config_json.max_future_skew_hours` overrides it per row for calendar or maintenance feeds that legitimately date entries ahead) is deferred instead: skipped for the tick and not recorded (recording would burn its dedup key and let a feed mute an announcement for good by post-dating it), with one aggregated `external_signal_deferred` audit row per poll — carrying each held-back entry's summary and link, and emitted even if the poll later raises — then judged normally once the date passes. Inside the window, the alert body handed to triage carries `Published:` and `Discovered:` lines so the item is judged on when it happened. Adapters prefer a plausible date key over one more than a day in the future (and keep the future value when every key is implausible, so the pipeline defers it rather than waving an undated entry through), and the alert body collapses whitespace in the summary so no source can forge its own labeled body line.\n\nThe `query` adapter is a special case: it emits every web hit flat-LOW (it can't judge materiality per-hit), so for query signals enrichment runs BEFORE the floor gate and `_grade_query_severity` regrades from the relevance read (≥0.8 HIGH, ≥0.5 MEDIUM, else LOW). Without this, any query watch item with a `severity_floor` above LOW would suppress every hit — which is what left the Monitoring section empty even while standing queries were returning material findings.\n\nWhich lane a proposal lands in is decided by `briefing.ranking.categorize`: an unrouted, low/medium signal from a monitoring source (`stock`, `vendor_status`, `rss`, `query`, `edgar`, `page_watch`, or any `external:*` topic tag) is `monitoring` (the collapsible Monitoring section); a routed or high/urgent one is `action` (the \"Needs you\" queue). The triage prompt's External Signals rule covers all six source kinds so it trusts the source and emits the `external:*` tags that drive this split.\n\nThe watchlist is editable from chat (`add_watchlist_entry`, `tune_watchlist_entry`) and HTTP (`/watchlist`); the `executive_research` workflow proposes what to watch through a deterministic policy (next section). Because that workflow is LLM-driven and historically proposed feed URLs it never verified (most were dead — 404 / 403 / not-actually-a-feed), every `rss` target is validated at insert time (`monitoring.target_validation`): a URL that fetches and parses as a feed is kept; a public page that isn't a feed is converted to a scrape-backed `page_watch` when xcrawl can read it, otherwise rejected (HTTP 422 / tool error); SSRF-blocked or unparseable URLs are rejected outright and never handed to xcrawl. Non-`rss` types insert unchanged with no network I/O.\n\n### One watch, one card — and dismissals teach the watch\n\n`promote_signal_to_alert` stamps the `AlertEvent` with `dedup_hint=\"watch:<slug>\"`, which `alerts.pipeline` uses as the *alert* dedup key. A repeat from the same watch coalesces into the open card (`occurrence_count`, `last_seen_at`, severity max) rather than minting another, and re-pings only when severity rose into high/urgent — so a ticker that stays over its threshold or an incident that keeps updating no longer produces a new \"Needs you\" item every day. The signal-level `dedup_key` (stock's UTC-date bucket, vendor_status's `<updated>`) is untouched, so every observation still lands in `external_signals`. Dismissing a watch-sourced alert calls `store.record_dismissal(slug)` (`dismiss_count += 1`, `trust_score = max(0.2, trust × 0.8)`); approving calls `record_confirmation` (+0.05). `trust_score` discounts the briefing ranking and is shown to the Executive's alert review as evidence, alongside the newer signals for that watch (a \"Resolved\" incident state, a reversed move) that let it close the card with evidence.\n\n### What the research pass may put on the watchlist\n\nEvery watchlist row carries an `origin`: `manual` (the principal, via UI/API), `executive` (the chat tool acting on a request), `research` (the research pass added it on its own) or `research_proposed` (a pending suggestion). The `executive_research` workflow's watchlist pass no longer calls `add_watchlist_entry`; its only tool is `propose_watch` (slug, signal_type, target, `grounding_entity`, `rationale`, `certainty`), and `monitoring.research.watch_policy` decides what happens to each proposal from company data, not from the model's confidence in itself:\n\n- **Direct add** — the row lands live, `origin=research`, with quiet defaults the model cannot loosen (daily cadence — hourly for `vendor_status`, weekly for `page_watch`/`query` — `severity_floor=medium`, a keyword trigger of material-event words + the current-year priority terms for `rss` / `query` only — never for `page_watch`, whose summary is just \"page changed\" and would never match, and never the entity's own name, which appears in every feed entry's label and would fire on everything — and `abs_change_pct_gte=5` for stocks). Requires the `grounding_entity` to name an external entity in company data — the company itself, a `competitive_landscape.primary_competitors` entry, one of the profile's `vendors` / `tickers`, or an entity a department lists under its **watched entities** (each list entry is parsed to its name: \"Tesla (TSLA) — Model Y is the benchmark\" grounds as `Tesla` plus the ticker `TSLA`, \"GM / Chevrolet (…)\" as both names; the description after the dash never becomes a term, and short names such as BYD or GM match as whole words) (an initiative title, a current-year priority, a department's charter-scope phrase or a goal's key result also grounds a proposal, but only ever to a suggestion: they are bags of common words a planted finding can echo) — *and* a score ≥ 4 on a fixed ledger: +2 entity in company data (mandatory), +1 entity already watched under another source, +1 target is the entity's own source (for stock/edgar the grounding entity must be the ticker itself; a URL whose site label — `acme` in `status.acme.com` / `acme.co.uk`, never a subdomain or TLD — is the entity's leading name or all its words run together, never a generic trailing word; or a primary-source host such as sec.gov), +1 finding confidence high, +1 verification confirmed, +1 cross-specialist consensus (the three finding points count only when the cited finding concerns this source: a URL target must share its site with one of the finding's cited URLs, a ticker must appear in its text — a strong finding cannot be borrowed for an unrelated page), +1 the entity (a company-data term, never a bare watch label) is named in one of the ten most recent episodic decisions from the last 90 days — the whole term, or every distinctive word of it, as whole words — ±1 from the policy's own approval history for that `(signal_type, grounding kind)` once it has ≥5 samples. A direct add is further reserved for the entity's **own** source (its ticker, its site, its status page): a well-corroborated third-party page about a competitor is the principal's call. It also always needs a linked finding that cites the source — company data plus a decision mention can reach the score bar alone, but nothing goes live on hearsay. The model's `certainty` can only downgrade a direct add to a suggestion; a `query` watch is always a suggestion. At most `WATCHLIST_RESEARCH_MAX_DIRECT_ADDS` (2) per run. When one term appears in several sources the strongest kind wins (company > competitor > vendor > ticker > department entity > initiative > priority > department scope > watch label); a term that came from a department carries the department along even when a stronger profile kind wins, so a profile vendor that Finance also lists stays a vendor and still routes to Finance.\n- **Linked finding.** `finding_index` is required on `propose_watch` and the pass is told so; when the model omits it anyway, the policy links the first finding that concerns the source (a cited URL on the target's site, or the ticker / entity named in its text) and says so in the first reason. A proposal that no finding cites is rejected as having no evidence.\n- **Suggestion** — anything that validates, has a linked finding and scores at least 1 but misses the bar is inserted in `dry_run` (polls and records signals, never alerts) with `origin=research_proposed` and the rationale in `notes`, at most `WATCHLIST_RESEARCH_MAX_PROPOSALS` (2) per run. `/watchlist` shows them in a \"Suggested by the Executive\" section with Approve (`POST /watchlist/{slug}/approve` → `active`, `origin=research`) and Decline (`POST /watchlist/{slug}/decline` with a reason: `not_relevant` blacklists the entity, `wrong_source` blacklists only this target, `too_noisy` keeps the source live with `severity_floor=high` — the one way a suggestion goes live without an approve — and counts as a decline for calibration). A suggestion nobody reviews within `WATCHLIST_PROPOSAL_TTL_DAYS` (14) is removed. The morning brief mentions the pending count in one line; a `watchlist_suggestions` alert nudges only once ≥3 suggestions have waited ≥7 days — one card for the whole pile (an open card is refreshed in place; a dismissed one is not re-minted until the next ISO week), so acting on a suggestion never spawns another nudge.\n- **Routed to a department** — a watch grounded in a department's term (or whose entity a recent decision recorded for that department names) is inserted with `route_to_department` and `route_to_person_id` set to the department and its head at insert time. `_signal_to_alert_event` now maps both onto the `AlertEvent` for every watch (`routed_to_person_id`, `department=<slug>` — a tag hint, deliberately not the `channel` field triage reads as a team room), so the alerts it raises queue on the head's `/today` (as action items, since routed alerts are never hidden in Monitoring) and carry the `department:<slug>` tag instead of landing in the principal's unrouted queue. Suggestions in a department's area are put in front of its head, not the principal: after each run, one \"Watch suggestions for <Department>\" card per department is filed through `propose_via_alert` (routed to the head, or the principal when there is no head; an open card is refreshed in place and an acknowledged one is not re-minted until the next ISO week), and the principal's pile-up nudge counts only suggestions that reached no head — the principal's own and those of a department without a head — so none can become invisible. `/watchlist` labels routed rows \"for: <department>\".\n- **Reject** — an invalid target, a second watch on the same site + signal type (disabled rows included), a declined target or entity, nothing vouching for it (no linked finding, score 0), the enabled-watch ceiling `WATCHLIST_MAX_ENABLED` (40; suggestions poll too, so the ceiling stops them as well), or a spent budget. Every decision is audited (`watchlist_research_added` / `_suggested` / `_rejected`) with the score and reasons; the stamp also lives in the row's `config_json._policy` so approve/decline/auto-disable can attribute the outcome.\n\n**Declines are remembered and enforced.** `watchlist_declines` is keyed by the normalized target (upper-cased ticker; URL with `https` forced, `www.` dropped, host and path lower-cased, query, fragment and trailing slash removed; free-text queries case- and whitespace-folded). A `not_relevant` decline also blacklists the *entity*: any later proposal whose `grounding_entity` names it is refused whatever the target. An explicit decline — the Decline button, \"Stop watching…\" on a research-added card, `remove_watchlist_entry` or `DELETE /watchlist/{slug}` on a research-origin row — is permanent; an unreviewed expiry may be re-proposed once after 90 days. The `propose_watch` handler refuses a declined target or entity before anything is fetched, so a new slug cannot route around a decline (URL keys also fold percent-encoding, dot segments and a trailing host dot); the list is also rendered to the model as DECLINED. The routing pass that runs before the watchlist pass has no watchlist write tools at all (`add_watchlist_entry`, `tune_watchlist_entry`, `remove_watchlist_entry` are withheld from synthesis), and `tune_watchlist_entry` accepts only `notes` on a pending suggestion — never `mode` / `enabled` (only the principal's approve or decline moves one out of review) nor cadence / floor / trigger (it goes live with the quiet defaults policy gave it). Every URL-typed target (`rss`, `vendor_status`, `page_watch`) is checked against the SSRF guard at insert time, and a suggestion's `source_url` link is kept only when it is a public http(s) URL.\n\n**The policy learns from outcomes.** Approve, decline, expiry and auto-disable write `watchlist_policy_outcomes` rows keyed by `(signal_type, grounding kind, specialist)`; the pass renders the tallies (\"stock watches grounded in a competitor: 4 approved / 1 declined\"; \"proposals from cso: …\") and the score ledger reads them. The research turn also shows each existing watch's `origin`, `fired_count`, `dismiss_count` and `trust_score`.\n\n**Research watches retire themselves.** The scheduler's 15-minute sweep (`watch_policy.sweep`, alongside the alert expiry sweep) disables a `research`-origin watch — audited as `watchlist_auto_disabled`, re-enable from `/watchlist` — when it fired ≥5 alerts of which ≥2 were dismissed and trust ≤ 0.5, or after 3 consecutive poll failures (silence is deliberately not a rule: an unchanged page or a healthy vendor is a working watch); the retired target is also recorded as a 90-day decline so the next run cannot re-add it under a new slug with fresh counters (a disabled row already counts as \"same source watched\"). Approve, decline and expiry are compare-and-act on \"still pending\", so a concurrent approve always wins over a decline or the sweep. Direct adds and auto-disables appear in the brief's \"handled overnight\" block as `watching` / `stopped_watching`. The research skip-if-unchanged fingerprint hashes only enabled, `active` rows, so approving or declining a suggestion never triggers a fresh 7-specialist run.\n\n### Invariants\n\n- Adapters are read-only — they never write upstream and never auto-execute.\n- Every `Signal` carries a deterministic `dedup_key` and a mandatory `provenance_url`.\n- Fetches are SSRF-guarded and bounded by `external_monitor_max_fetch_bytes`; xcrawl scrape (off by default, gated by `XCRAWL_ENABLED` + `XCRAWL_API_KEY`) is the one path that delegates the fetch to an external API.\n- Suppressed signals are still persisted so audits show the full picture.\n- A repeat from the same watch never becomes a second open card: the alert-level `watch:<slug>` key coalesces it, and only a severity escalation re-dispatches.\n- The research model never writes the watchlist: it proposes, deterministic policy adds (only when grounded in company data) or suggests, and a target the principal declined is refused at the handler.",+ "markdown": "`openexecutive.monitoring` watches the outside world on a heartbeat and turns detected changes into briefing proposals via the same alert pipeline that handles inbound email and Slack.\n\nThe `external_monitor_scan` heartbeat (`__internal__` channel, default every 5 min) walks `list_watchlist(enabled_only=True)`, skipping rows fresher than their per-source cadence floor. For each due row it fires a read-only source adapter resolved from `_REGISTRY` by `signal_type`:\n\n- `vendor_status` — Statuspage Atom/RSS incident feeds (AWS, Stripe, GitHub, …). Reads each incident's current status out of the entry body, parses `<updated>` into `published_at`, and keys its dedup on `(entry id, <updated>)`; a **seeding** source (see below).\n- `rss` — generic Atom/RSS via feedparser (changelogs, layoffs.fyi, filings). Parses each entry's `<pubDate>`/`<updated>` into `published_at`; a **seeding** source (see below).\n- `stock` — Yahoo Finance chart endpoint; fires on `abs_change_pct_gte` moves.\n- `page_watch` — change-detection on a feed-less page. Fetches via the keyless httpx fetcher by default, or via xcrawl's scrape API when the row carries `config.fetch = \"xcrawl\"` — so JS-rendered / bot-blocked pages that publish no RSS (most modern news / marketing sites) are still monitorable.\n- `edgar` and the BILLED `query` web-search adapter.\n\nEach `Signal` is trigger-filtered, severity-clamped to the row's `[floor, ceiling]`, and INSERTed into `external_signals` where `UNIQUE(dedup_key)` drops replays. Survivors pass a suppression cascade (`baseline` → `stale` → `dry_run` → `below_floor` → capture-time relevance enrichment → promote), then `promote_signal_to_alert` builds an `AlertEvent` handed to `alerts.pipeline.schedule_evaluation` and surfaced as a `/today` proposal.\n\nEvery signal carries two timestamps that are never conflated: `captured_at` (when the monitor first saw it) and `published_at` (when the upstream says it happened — RSS `<pubDate>`, EDGAR filing date; null for `stock`, `page_watch`, `query`). Two freshness gates run first in the cascade, before anything that costs an LLM call. **Baseline:** the first poll that returns entries for a row whose adapter declares `seed_on_first_poll` (`rss`, `edgar`) records every entry already in the feed — trigger misses included, so the first entry that ever matches a keyword is news and a later, wider trigger can't resurface old ones — as `suppressed_baseline`, promotes nothing, and stamps `watchlist.baselined_at`, so a new watch reports what changes from now on instead of replaying the feed's back-catalogue (the same idea as `page_watch`'s first-observation baseline). It is keyed on `baselined_at` rather than `last_polled_at`, so a failed first fetch can't forfeit it; the claim and the recording are one transaction (a compare-and-swap on the stamp plus the rows, all-or-nothing), so of two overlapping scans exactly one records the back-catalogue and a failure part-way leaves nothing behind to replay; the other scan promotes only entries dated after that stamp (undated entries count as baseline, since the feed controls the date; entries dated more than a few minutes past its own clock are deferred rather than recorded); and baseline rows don't count against `max_signals_per_scan`, so a large feed can't be half-baselined. `vendor_status` used to sit outside both gates for a structural reason: its dedup key was `sha256(slug, entry id)`, and an incident's id never changes across its updates, so any suppressed insert muted that incident for good. Keying on `(entry id, <updated>)` instead (issue #90) makes a suppression cost one *state* of an incident rather than the incident, so both gates now apply to vendor feeds too — and an incident moving Investigating → Resolved mints a new key and surfaces, while re-polling an unchanged feed still dedups. Because a history feed's archive is mostly incidents resolved months ago, the adapter also carves live news out of its own baseline: it reads each incident's current status from the entry body (Statuspage renders the newest update first as `<strong>Resolved</strong>` / `Investigating` / `Monitoring` / … — the body is parsed by a real HTML parser, off the event loop, and the reading is deliberately asymmetric: any sign that the incident is over closes it, wherever it appears, while only a marked-up label can say it is still open. Working out which update is newest turned out to be something tag soup cannot be trusted to express, and every attempt reported a long-resolved incident as live) and exempts the ones still OPEN via the optional `promote_on_baseline` hook, so a watch added during an outage reports that outage on its first poll while the resolved archive is recorded as `suppressed_baseline`. An unrecognised status counts as closed — a vendor changing feed format must not be able to promote its whole archive at HIGH, and nothing is lost, since the next `<updated>` bump surfaces normally. An exempt entry must still pass the row's trigger filter (one that misses stays in the baseline, so widening a trigger later cannot resurface it) and is still judged by the stale gate below: the exemption buys an entry past the baseline, never past its own timestamp, because \"this is live\" is a reading of vendor-controlled markup and an entry the feed dates outside the age window is not news whatever that reading says. **Stale:** a signal whose `published_at` is older than `EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS` (default 7; `0` disables) at capture time is recorded as `suppressed_stale` and never promoted — a January article a feed resurfaces in September is not September news. An entry dated more than `EXTERNAL_MONITOR_MAX_FUTURE_SKEW_HOURS` ahead (default 24; `0` disables; `config_json.max_future_skew_hours` overrides it per row for calendar or maintenance feeds that legitimately date entries ahead) is deferred instead: skipped for the tick and not recorded (recording would burn its dedup key and let a feed mute an announcement for good by post-dating it), with one aggregated `external_signal_deferred` audit row per poll — carrying each held-back entry's summary and link, and emitted even if the poll later raises — then judged normally once the date passes. Inside the window, the alert body handed to triage carries `Published:` and `Discovered:` lines so the item is judged on when it happened. Adapters prefer a plausible date key over one more than a day in the future (and keep the future value when every key is implausible, so the pipeline defers it rather than waving an undated entry through), and the alert body collapses whitespace in the summary so no source can forge its own labeled body line.\n\nThe `query` adapter is a special case: it emits every web hit flat-LOW (it can't judge materiality per-hit), so for query signals enrichment runs BEFORE the floor gate and `_grade_query_severity` regrades from the relevance read (≥0.8 HIGH, ≥0.5 MEDIUM, else LOW). Without this, any query watch item with a `severity_floor` above LOW would suppress every hit — which is what left the Monitoring section empty even while standing queries were returning material findings.\n\nWhich lane a proposal lands in is decided by `briefing.ranking.categorize`: an unrouted, low/medium signal from a monitoring source (`stock`, `vendor_status`, `rss`, `query`, `edgar`, `page_watch`, or any `external:*` topic tag) is `monitoring` (the collapsible Monitoring section); a routed or high/urgent one is `action` (the \"Needs you\" queue). The triage prompt's External Signals rule covers all six source kinds so it trusts the source and emits the `external:*` tags that drive this split.\n\nThe watchlist is editable from chat (`add_watchlist_entry`, `tune_watchlist_entry`) and HTTP (`/watchlist`); the `executive_research` workflow proposes what to watch through a deterministic policy (next section). Because that workflow is LLM-driven and historically proposed feed URLs it never verified (most were dead — 404 / 403 / not-actually-a-feed), every `rss` target is validated at insert time (`monitoring.target_validation`): a URL that fetches and parses as a feed is kept; a public page that isn't a feed is converted to a scrape-backed `page_watch` when xcrawl can read it, otherwise rejected (HTTP 422 / tool error); SSRF-blocked or unparseable URLs are rejected outright and never handed to xcrawl. Non-`rss` types insert unchanged with no network I/O.\n\n### One watch, one card — and dismissals teach the watch\n\n`promote_signal_to_alert` stamps the `AlertEvent` with `dedup_hint=\"watch:<slug>\"`, which `alerts.pipeline` uses as the *alert* dedup key. A repeat from the same watch coalesces into the open card (`occurrence_count`, `last_seen_at`, severity max) rather than minting another, and re-pings only when severity rose into high/urgent — so a ticker that stays over its threshold or an incident that keeps updating no longer produces a new \"Needs you\" item every day. The signal-level `dedup_key` (stock's UTC-date bucket, vendor_status's `<updated>`) is untouched, so every observation still lands in `external_signals`. Dismissing a watch-sourced alert calls `store.record_dismissal(slug)` (`dismiss_count += 1`, `trust_score = max(0.2, trust × 0.8)`); approving calls `record_confirmation` (+0.05). `trust_score` discounts the briefing ranking and is shown to the Executive's alert review as evidence, alongside the newer signals for that watch (a \"Resolved\" incident state, a reversed move) that let it close the card with evidence.\n\n### What the research pass may put on the watchlist\n\nEvery watchlist row carries an `origin`: `manual` (the principal, via UI/API), `executive` (the chat tool acting on a request), `research` (the research pass added it on its own) or `research_proposed` (a pending suggestion). The `executive_research` workflow's watchlist pass no longer calls `add_watchlist_entry`; its only tool is `propose_watch` (slug, signal_type, target, `grounding_entity`, `rationale`, `certainty`), and `monitoring.research.watch_policy` decides what happens to each proposal from company data, not from the model's confidence in itself:\n\n- **Direct add** — the row lands live, `origin=research`, with quiet defaults the model cannot loosen (daily cadence — hourly for `vendor_status`, weekly for `page_watch`/`query` — `severity_floor=medium`, a keyword trigger of material-event words + the current-year priority terms for `rss` / `query` only — never for `page_watch`, whose summary is just \"page changed\" and would never match, and never the entity's own name, which appears in every feed entry's label and would fire on everything — and `abs_change_pct_gte=5` for stocks). Requires the `grounding_entity` to name an external entity in company data — the company itself, a `competitive_landscape.primary_competitors` entry, one of the profile's `vendors` / `tickers`, or an entity a department lists under its **watched entities** (each list entry is parsed to its name: \"Tesla (TSLA) — Model Y is the benchmark\" grounds as `Tesla` plus the ticker `TSLA`, \"GM / Chevrolet (…)\" as both names, and \"Brex (brex.com)\" pins Brex's own domains so only those sites count as its own source; the description after the dash never becomes a term, short names such as BYD or GM match as whole words, and a ticker grounds only as itself) (an initiative title, a current-year priority, a department's charter-scope phrase or a goal's key result also grounds a proposal, but only ever to a suggestion: they are bags of common words a planted finding can echo) — *and* a score ≥ 4 on a fixed ledger: +2 entity in company data (mandatory), +1 entity already watched under another source, +1 target is the entity's own source (for stock/edgar the grounding entity must be the ticker itself; a URL whose site label — `acme` in `status.acme.com` / `acme.co.uk`, never a subdomain or TLD — is the entity's leading name or all its words run together, never a generic trailing word; or a primary-source host such as sec.gov), +1 finding confidence high, +1 verification confirmed, +1 cross-specialist consensus (the three finding points count only when the cited finding concerns this source: a URL target must share its site with one of the finding's cited URLs, a ticker must appear in its text — a strong finding cannot be borrowed for an unrelated page), +1 the entity (a company-data term, never a bare watch label) is named in one of the ten most recent episodic decisions from the last 90 days — the whole term, or every distinctive word of it, as whole words — ±1 from the policy's own approval history for that `(signal_type, grounding kind)` once it has ≥5 samples. A direct add is further reserved for the entity's **own** source (its ticker, its site, its status page): a well-corroborated third-party page about a competitor is the principal's call. It also always needs a linked finding that cites the source — company data plus a decision mention can reach the score bar alone, but nothing goes live on hearsay. The model's `certainty` can only downgrade a direct add to a suggestion; a `query` watch is always a suggestion. At most `WATCHLIST_RESEARCH_MAX_DIRECT_ADDS` (2) per run. When one term appears in several sources the strongest kind wins (company > competitor > vendor > ticker > department entity > initiative > priority > department scope > watch label); a term that came from a department carries the department along even when a stronger profile kind wins, so a profile vendor that Finance also lists stays a vendor and still routes to Finance.\n- **Linked finding.** `finding_index` is required on `propose_watch` and the pass is told so; when the model omits it anyway, or cites a finding that does not concern the source, the policy links the finding that best does (a cited URL on the target's site or the ticker named in its text outranks a mere mention of the entity; then the entity's own site, confidence, verification) and says so in the first reason. A proposal that no finding cites is rejected as having no evidence.\n- **Suggestion** — anything that validates, has a linked finding and scores at least 1 but misses the bar is inserted in `dry_run` (polls and records signals, never alerts) with `origin=research_proposed` and the rationale in `notes`, at most `WATCHLIST_RESEARCH_MAX_PROPOSALS` (2) per run. `/watchlist` shows them in a \"Suggested by the Executive\" section with Approve (`POST /watchlist/{slug}/approve` → `active`, `origin=research`) and Decline (`POST /watchlist/{slug}/decline` with a reason: `not_relevant` blacklists the entity, `wrong_source` blacklists only this target, `too_noisy` keeps the source live with `severity_floor=high` — the one way a suggestion goes live without an approve — and counts as a decline for calibration). A suggestion nobody reviews within `WATCHLIST_PROPOSAL_TTL_DAYS` (14) is removed. The morning brief mentions the pending count in one line; a `watchlist_suggestions` alert nudges only once ≥3 suggestions have waited ≥7 days — one card for the whole pile (an open card is refreshed in place; a dismissed one is not re-minted until the next ISO week), so acting on a suggestion never spawns another nudge.\n- **Routed to a department** — a watch grounded in a department's term (or whose entity a recent decision recorded for that department names) is inserted with `route_to_department` and `route_to_person_id` set to the department and its head at insert time. `_signal_to_alert_event` now maps both onto the `AlertEvent` for every watch (`routed_to_person_id`, `department=<slug>` — a tag hint, deliberately not the `channel` field triage reads as a team room), so the alerts it raises queue on the head's `/today` (as action items, since routed alerts are never hidden in Monitoring) and carry the `department:<slug>` tag instead of landing in the principal's unrouted queue. Suggestions in a department's area are put in front of its head, not the principal: after each run, one \"Watch suggestions for <Department>\" card per department is filed through `propose_via_alert` (routed to the head, or the principal when there is no head; an open card is refreshed in place and an acknowledged one is not re-minted until the next ISO week), and the principal's pile-up nudge counts only suggestions that reached no head — the principal's own and those of a department without a head — so none can become invisible. `/watchlist` labels routed rows \"for: <department>\".\n- **Reject** — an invalid target, a second watch on the same site + signal type (disabled rows included), a declined target or entity, nothing vouching for it (no linked finding, score 0), the enabled-watch ceiling `WATCHLIST_MAX_ENABLED` (40; suggestions poll too, so the ceiling stops them as well), or a spent budget. Every decision is audited (`watchlist_research_added` / `_suggested` / `_rejected`) with the score and reasons; the stamp also lives in the row's `config_json._policy` so approve/decline/auto-disable can attribute the outcome.\n\n**Declines are remembered and enforced.** `watchlist_declines` is keyed by the normalized target (upper-cased ticker; URL with `https` forced, `www.` dropped, host and path lower-cased, query, fragment and trailing slash removed; free-text queries case- and whitespace-folded). A `not_relevant` decline also blacklists the *entity*: any later proposal whose `grounding_entity` names it is refused whatever the target. An explicit decline — the Decline button, \"Stop watching…\" on a research-added card, `remove_watchlist_entry` or `DELETE /watchlist/{slug}` on a research-origin row — is permanent; an unreviewed expiry may be re-proposed once after 90 days. The `propose_watch` handler refuses a declined target or entity before anything is fetched, so a new slug cannot route around a decline (URL keys also fold percent-encoding, dot segments and a trailing host dot); the list is also rendered to the model as DECLINED. The routing pass that runs before the watchlist pass has no watchlist write tools at all (`add_watchlist_entry`, `tune_watchlist_entry`, `remove_watchlist_entry` are withheld from synthesis), and `tune_watchlist_entry` accepts only `notes` on a pending suggestion — never `mode` / `enabled` (only the principal's approve or decline moves one out of review) nor cadence / floor / trigger (it goes live with the quiet defaults policy gave it). Every URL-typed target (`rss`, `vendor_status`, `page_watch`) is checked against the SSRF guard at insert time, and a suggestion's `source_url` link is kept only when it is a public http(s) URL.\n\n**The policy learns from outcomes.** Approve, decline, expiry and auto-disable write `watchlist_policy_outcomes` rows keyed by `(signal_type, grounding kind, specialist)`; the pass renders the tallies (\"stock watches grounded in a competitor: 4 approved / 1 declined\"; \"proposals from cso: …\") and the score ledger reads them. The research turn also shows each existing watch's `origin`, `fired_count`, `dismiss_count` and `trust_score`.\n\n**Research watches retire themselves.** The scheduler's 15-minute sweep (`watch_policy.sweep`, alongside the alert expiry sweep) disables a `research`-origin watch — audited as `watchlist_auto_disabled`, re-enable from `/watchlist` — when it fired ≥5 alerts of which ≥2 were dismissed and trust ≤ 0.5, or after 3 consecutive poll failures (silence is deliberately not a rule: an unchanged page or a healthy vendor is a working watch); the retired target is also recorded as a 90-day decline so the next run cannot re-add it under a new slug with fresh counters (a disabled row already counts as \"same source watched\"). Approve, decline and expiry are compare-and-act on \"still pending\", so a concurrent approve always wins over a decline or the sweep. Direct adds and auto-disables appear in the brief's \"handled overnight\" block as `watching` / `stopped_watching`. The research skip-if-unchanged fingerprint hashes only enabled, `active` rows, so approving or declining a suggestion never triggers a fresh 7-specialist run.\n\n### Invariants\n\n- Adapters are read-only — they never write upstream and never auto-execute.\n- Every `Signal` carries a deterministic `dedup_key` and a mandatory `provenance_url`.\n- Fetches are SSRF-guarded and bounded by `external_monitor_max_fetch_bytes`; xcrawl scrape (off by default, gated by `XCRAWL_ENABLED` + `XCRAWL_API_KEY`) is the one path that delegates the fetch to an external API.\n- Suppressed signals are still persisted so audits show the full picture.\n- A repeat from the same watch never becomes a second open card: the alert-level `watch:<slug>` key coalesces it, and only a severity escalation re-dispatches.\n- The research model never writes the watchlist: it proposes, deterministic policy adds (only when grounded in company data) or suggests, and a target the principal declined is refused at the handler.","mermaid": "flowchart TD\n ADD[\"add (chat tool / POST /watchlist / research)\"]\n VAL[\"target_validation: rss feed? → keep / convert→page_watch(xcrawl) / reject\"]\n WL[(\"watchlist\")]\n HB[\"external_monitor_scan heartbeat (~5 min)\"]\n AD[\"read-only adapters: vendor_status / rss / stock / query / edgar / page_watch (httpx | xcrawl)\"]\n SIG[(\"external_signals UNIQUE(dedup_key)\")]\n ENRICH[\"capture-time enrichment<br/>(relevance score + why_it_matters)\"]\n PROMO[\"promote_signal_to_alert\"]\n PIPE[\"alert pipeline (triage)\"]\n TODAY[\"/today proposals\"]\n ADD --> VAL\n VAL -->|\"insert valid rows\"| WL\n HB -->|\"walk enabled rows\"| WL\n WL -->|\"poll due rows\"| AD\n AD -->|\"emit Signal\"| SIG\n SIG -->|\"baseline / stale / dry_run / floor gates\"| ENRICH\n ENRICH -->|\"≥ relevance floor\"| PROMO\n PROMO --> PIPE\n PIPE --> TODAY\n class HB hot\n class WL storage\n class VAL compute\n class AD external\n class SIG storage\n class ENRICH compute\n class PROMO compute\n class PIPE compute\n class TODAY entry\n class ADD compute","generated_at": "2026-09-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/monitoring/research/watch_policy.py b/packages/core/openexecutive/monitoring/research/watch_policy.pyindex 98984eb4..c6980a38 100644--- a/packages/core/openexecutive/monitoring/research/watch_policy.py+++ b/packages/core/openexecutive/monitoring/research/watch_policy.py@@ -238,11 +238,15 @@ class PolicySettings:class VocabEntry(NamedTuple):- """One grounding-vocabulary value: the term's kind and, when the term- came from (or is also claimed by) a department, that department's slug."""+ """One grounding-vocabulary value: the term's kind, the department that+ supplied or also claims it, and the entity's own domains when the+ profile / department entry names them ("Brex (brex.com)"). With+ domains pinned, only those sites are the entity's own source; without,+ the site label has to be the entity's name."""kind: strdepartment: str = ""+ domains: tuple[str, ...] = ()class DepartmentRef(NamedTuple):@@ -297,31 +301,96 @@ def _norm(term: str) -> str:# bag of common words that would both hide the name (short names such as BYD# never match inside a sentence) and poison own-source checks ("global" in# "BYD — global cost leader" would make global.com BYD's own site).-_ENTRY_SPLIT_RE = re.compile(r"\s+[—–-]\s+|[:;]")-_PAREN_RE = re.compile(r"\(([^)]*)\)")-_TICKER_RE = re.compile(r"^(?:[A-Z]{1,5}(?:\.[A-Z]{1,3})?|\d{3,6}\.[A-Z]{2,3})$")+# Em/en dashes split regardless of spacing (typography varies); a plain+# hyphen only when spaced, so "Mercedes-Benz" and "T-Mobile" survive.+_ENTRY_SPLIT_RE = re.compile(r"\s*[—–]\s*| - |[:;]")+_PAREN_RE = re.compile(r"\(([^()]*)\)")+_TICKER_RE = re.compile(r"^(?:[A-Z]{2,5}(?:\.[A-Z]{1,3})?|\d{3,6}\.[A-Z]{2,3})$")+_DOMAIN_RE = re.compile(r"^(?:[a-z0-9-]+\.)+[a-z]{2,}$")+_URL_RE = re.compile(r"^(?:https?://)?((?:[a-z0-9-]+\.)+[a-z]{2,})(?:[/?#].*)?$", re.IGNORECASE)+# Upper-case words that appear in parentheses in ordinary profile prose and+# are not tickers. A parenthesised token is a ticker only when it is alone+# in its group and not one of these; the profile's own `tickers` list is+# taken as-is.+_NOT_TICKERS: frozenset[str] = frozenset({+ "US", "USA", "EU", "UK", "EV", "EVS", "AI", "ML", "IT", "HR", "PR", "IR", "IP", "ALL", "NOW",+ "NEW", "OEM", "OEMS", "LFP", "NMC", "EMEA", "APAC", "LATAM", "CEO", "CFO", "COO", "CTO", "CMO",+ "CPO", "CHRO", "GC", "IPO", "ESG", "API", "SAAS", "B2B", "B2C", "SMB", "SME", "TCO", "ROI",+ "KPI", "OKR", "GTM", "R2", "R3", "C1", "C2", "Q1", "Q2", "Q3", "Q4", "FY", "YOY", "QOQ",+})+# Profile entries are free text; bound what the parser looks at so a+# pathological value cannot stall the scheduler tick.+_MAX_ENTRY_CHARS = 256++class ParsedEntity(NamedTuple):+ names: list[str]+ tickers: list[str]+ domains: list[str]-def entity_names(raw: str) -> tuple[list[str], list[str]]:- """``(names, tickers)`` parsed from one profile / department entry.- "Tesla (TSLA) — Model Y is the benchmark" → (["Tesla"], ["TSLA"]);- "GM / Chevrolet (Equinox EV, Blazer EV) — direct competitor" →- (["GM", "Chevrolet"], []); "Stripe" → (["Stripe"], [])."""- text = str(raw or "").strip()+def _strip_parens(text: str) -> tuple[str, list[str]]:+ """Remove parenthesised groups (innermost first, a few levels deep) and+ return the bare text plus the groups' contents."""+ groups: list[str] = []+ for _ in range(3):+ found = _PAREN_RE.findall(text)+ if not found:+ break+ groups.extend(found)+ text = _PAREN_RE.sub(" ", text)+ return text, groups+++def entity_names(raw: str) -> ParsedEntity:+ """``(names, tickers, domains)`` parsed from one profile / department entry.++ "Tesla (TSLA) — Model Y is the benchmark" → names ["Tesla"], tickers+ ["TSLA"]; "GM / Chevrolet (Equinox EV, Blazer EV) — direct competitor" →+ names ["GM", "Chevrolet"]; "Brex (brex.com, status.brex.com)" → names+ ["Brex"], domains ["brex.com", "status.brex.com"]; a bare URL or host+ ("https://status.stripe.com") → names ["stripe"], domains+ ["status.stripe.com"]; "Stripe" → ["Stripe"].++ A parenthesised group counts as a ticker only when it is a single+ ticker-shaped token (2–5 letters, or a numeric exchange code) that is not+ an ordinary abbreviation ("US", "EV", "IT") — a list of product names in+ parentheses is never a ticker. Domains are any dotted host in a group.+ Parenthesised brand names ("Alphabet (Google)") are NOT aliases: list+ them as entries of their own."""+ text = " ".join(str(raw or "").split())[:_MAX_ENTRY_CHARS]if not text:- return [], []- head = _ENTRY_SPLIT_RE.split(text, maxsplit=1)[0]+ return ParsedEntity([], [], [])+ url = _URL_RE.match(text)+ # A URL, or a bare lower-case host ("status.stripe.com"); an upper-case+ # dotted symbol ("1211.HK") is a ticker, handled by the caller.+ if url and ("://" in text or "/" in text or (" " not in text and text == text.lower())):+ host = url.group(1).lower()+ label = _site_label(host)+ return ParsedEntity([label] if label else [], [], [host])+ bare, groups = _strip_parens(text)+ head = _ENTRY_SPLIT_RE.split(bare, maxsplit=1)[0]tickers: list[str] = []- for group in _PAREN_RE.findall(head):- for part in re.split(r"[,/]", group):- candidate = part.strip()- if _TICKER_RE.match(candidate) and candidate not in tickers:+ domains: list[str] = []+ for group in groups:+ parts = [part.strip() for part in re.split(r"[,/;]", group) if part.strip()]+ for part in parts:+ # A dotted token with lower-case letters is a host; an+ # upper-case one ("1211.HK", "MBG.DE") is an exchange ticker.+ if part != part.upper() and _DOMAIN_RE.match(part.lower()) and part.lower() not in domains:+ domains.append(part.lower())+ if len(parts) == 1:+ candidate = parts[0].upper()+ if (+ (parts[0] == parts[0].upper() or "." not in parts[0])+ and _TICKER_RE.match(candidate)+ and candidate not in _NOT_TICKERS+ and candidate not in tickers+ ):tickers.append(candidate)- bare = _PAREN_RE.sub(" ", head)- names = [n.strip(" ,") for n in re.split(r"\s*/\s*", bare)]+ names = [n.strip(" ,") for n in head.split("/")]names = [n for n in names if len(_norm(n)) >= 2]- return names, tickers+ return ParsedEntity(names, tickers, domains)def grounding_vocabulary(@@ -345,18 +414,19 @@ def grounding_vocabulary(the first one seen keeps it."""vocab: Vocabulary = {}- def add(term: str, kind: str, department: str = "") -> None:+ def add(term: str, kind: str, department: str = "", domains: tuple[str, ...] = ()) -> None:n = _norm(term)if len(n) < 2:returncurrent = vocab.get(n)if current is None:- vocab[n] = VocabEntry(kind, department)+ vocab[n] = VocabEntry(kind, department, domains)return+ merged = current.domains + tuple(d for d in domains if d not in current.domains)if _KIND_RANK[kind] > _KIND_RANK[current.kind]:- vocab[n] = VocabEntry(kind, department or current.department)+ vocab[n] = VocabEntry(kind, department or current.department, merged)else:- vocab[n] = VocabEntry(current.kind, current.department or department)+ vocab[n] = VocabEntry(current.kind, current.department or department, merged)for item in existing:for label_key in ("display_name", "feed_label", "vendor_label", "label"):@@ -372,18 +442,20 @@ def grounding_vocabulary(add(str(getattr(i, "title", "") or ""), KIND_INITIATIVE)def add_entity(raw: str, kind: str, department: str = "") -> None:# Named-entity lists: only the parsed name(s) ground; a parenthesised- # ticker is a ticker term of its own.- names, tickers = entity_names(raw)- for name in names:- add(name, kind, department)- for ticker in tickers:+ # ticker is a ticker term of its own; parenthesised domains pin the+ # entity's own sites.+ parsed = entity_names(raw)+ for name in parsed.names:+ add(name, kind, department, tuple(parsed.domains))+ for ticker in parsed.tickers:add(ticker, KIND_TICKER, department)if profile is not None:for p in list(getattr(getattr(profile, "strategic_priorities", None), "current_year", []) or []):add(str(p), KIND_PRIORITY)for t in list(getattr(profile, "tickers", []) or []):- add_entity(str(t), KIND_TICKER)+ # The tickers list is symbols as typed; nothing to parse.+ add(str(t).strip().upper(), KIND_TICKER)for v in list(getattr(profile, "vendors", []) or []):add_entity(str(v), KIND_VENDOR)for c in list(getattr(getattr(profile, "competitive_landscape", None), "primary_competitors", []) or []):@@ -488,8 +560,8 @@ def _entry(value: Any) -> VocabEntry:or a :class:`VocabEntry`."""if isinstance(value, VocabEntry):return value- if isinstance(value, tuple) and len(value) == 2:- return VocabEntry(str(value[0]), str(value[1] or ""))+ if isinstance(value, tuple) and 2 <= len(value) <= 3:+ return VocabEntry(str(value[0]), str(value[1] or ""), tuple(value[2]) if len(value) == 3 else ())return VocabEntry(str(value), "")@@ -525,6 +597,10 @@ def match_vocab(entity: str, vocabulary: dict[str, Any]) -> tuple[str, VocabEntrreturn bestfor term, value in vocabulary.items():entry = _entry(value)+ if entry.kind == KIND_TICKER and term != n:+ # A ticker symbol grounds only when it IS the entity ("US" is+ # not "US Foods", "IT" is not "IT Brew").+ continueterm_tokens = _distinctive_tokens(term, vocabulary)if not term_tokens or not (term_tokens <= tokens or tokens <= term_tokens):continue@@ -580,7 +656,7 @@ def entity_declined(entity: str, declines: list[Any]) -> bool:# Exact, or a one-word declined name ("BYD") as a whole word of the# entity ("BYD Auto") and vice versa — short names have no# distinctive tokens, so the token rule below cannot see them.- if dn == n or (" " not in dn and dn in n.split()) or (" " not in n and n in dn.split()):+ if dn == n or (" " not in dn and dn not in _STOPWORDS and dn in n.split()):return Trued_tokens = {t for t in dn.split() if t not in _STOPWORDS and len(t) >= _MIN_PARTIAL_TOKEN}if tokens and d_tokens and (d_tokens <= tokens or tokens <= d_tokens):@@ -606,6 +682,17 @@ def _is_own_source(proposal: WatchProposal, entity_term: str, vocabulary: dict[sreturn Falseif host in PRIMARY_SOURCE_HOSTS or any(host.endswith("." + h) for h in PRIMARY_SOURCE_HOSTS):return True+ # When the profile / department pins the entity's domains ("GM+ # (gm.com)"), only those sites are its own source: a look-alike+ # registration such as gm.co.ke does not qualify however well it+ # imitates the entity.+ entry_value = vocabulary.get(entity_term)+ pinned = _entry(entry_value).domains if entry_value is not None else ()+ if pinned:+ return any(+ host == registrable_domain("https://" + d) or host == d+ for d in pinned+ )# Only the site's own label counts ("acme" in status.acme.com / acme.co.uk);# subdomain labels and the TLD never do, so "api" or ".cloud" cannot# make an unrelated host look like the entity's. And the label must be@@ -656,7 +743,8 @@ def _finding_supports()if proposal.signal_type in (SOURCE_KIND_STOCK, SOURCE_KIND_EDGAR):# Phrase containment: a dotted ticker normalizes to two words.- return f" {_norm(proposal.target)} " in f" {text} " or names_entity+ target_phrase = _norm(proposal.target)+ return bool(target_phrase) and f" {target_phrase} " in f" {text} " or names_entityif proposal.signal_type == SOURCE_KIND_QUERY:return names_entity# A URL target must share its site with a cited URL: a finding that@@ -895,20 +983,52 @@ def _policy_stamp(decision: Decision, proposal: WatchProposal, finding: Research}+_CONFIDENCE_RANK = {"high": 2, "medium": 1, "low": 0}++def auto_link_finding(proposal: WatchProposal, findings: list[ResearchFinding], ctx: PolicyContext,) -> int | None:- """Index of the first finding that concerns this proposal's source (a- cited URL on the target's site; for a ticker or query, the ticker or- the grounding entity named in its text), for a proposal the model filed- without a ``finding_index``. The link is the same test the score uses,- so it can never lend a proposal a finding the score would not honour."""+ """Index of the finding that best concerns this proposal's source, for a+ proposal the model filed without a usable ``finding_index``.++ Candidates pass the same test the score uses (:func:`_finding_supports`+ with the entity term :func:`classify` would use), so the link can never+ lend a proposal a finding the score would not honour. Among candidates,+ one that cites the target's site or names the ticker outranks one that+ only names the entity, then higher confidence, then verification, then+ the earlier finding — so the evidence URL stamped on the row is the+ source's own, not an unrelated company's."""match = match_vocab(proposal.grounding_entity, ctx.vocabulary)- entity_term = match[0] if match else _norm(proposal.grounding_entity)+ entity_term = match[0] if match else ""+ target_phrase = _norm(proposal.target)+ host = registrable_domain(proposal.target)+ entity_labels = set(_name_tokens(entity_term, ctx.vocabulary)) | {target_phrase.replace(" ", "")}+ best: tuple[tuple[int, int, int, int, int], int] | None = Nonefor index, finding in enumerate(findings):- if _finding_supports(proposal, finding, entity_term, ctx.vocabulary):- return index- return None+ if not _finding_supports(proposal, finding, entity_term, ctx.vocabulary):+ continue+ text = _norm(f"{finding.title} {finding.summary}")+ cites_source = int(+ bool(host) and any(registrable_domain(u) == host for u in finding.relevant_urls)+ or bool(target_phrase) and f" {target_phrase} " in f" {text} "+ )+ # A finding whose own citations sit on the entity's site (acme.com+ # for ACME) outranks one that names it from a rival's page, so the+ # evidence link stamped on the row is the entity's, not a stranger's.+ cites_entity_site = int(any(+ _site_label(registrable_domain(u)) in entity_labels for u in finding.relevant_urls+ ))+ key = (+ cites_source,+ cites_entity_site,+ _CONFIDENCE_RANK.get(finding.confidence, 0),+ int(finding.verification == "confirmed"),+ -index,+ )+ if best is None or key > best[0]:+ best = (key, index)+ return best[1] if best else Nonedef policy_stamp_of(item: WatchlistItem) -> dict[str, Any]:@@ -948,14 +1068,22 @@ def apply_proposals(seen_targets.add(proposal.normalized_target)linked_note = ""- if finding is None:- # The model routinely omits finding_index; the finding that- # cites this source is still the evidence, so link it.+ cited_term = match_vocab(proposal.grounding_entity, ctx.vocabulary)+ if finding is None or not _finding_supports(+ proposal, finding, cited_term[0] if cited_term else "", ctx.vocabulary,+ ):+ # The model routinely omits finding_index, or guesses one that+ # does not concern this source; the finding that does is still+ # the evidence, so link it (a copy: the caller's proposal is+ # left as filed).auto_index = auto_link_finding(proposal, findings, ctx)if auto_index is not None:+ given = proposal.finding_indexfinding = findings[auto_index]- proposal.finding_index = auto_index- linked_note = f"linked to finding #{auto_index + 1} by its cited source"+ proposal = dataclasses.replace(proposal, finding_index=auto_index)+ linked_note = f"linked to finding #{auto_index + 1}, which concerns this source"+ if given is not None:+ linked_note += f" (the cited #{given + 1} did not)"decision = classify(proposal, finding, ctx)if linked_note:diff --git a/packages/core/tests/unit/test_watch_policy.py b/packages/core/tests/unit/test_watch_policy.pyindex d931d59b..d32deaaa 100644--- a/packages/core/tests/unit/test_watch_policy.py+++ b/packages/core/tests/unit/test_watch_policy.py@@ -921,13 +921,29 @@ def test_nudge_counts_only_suggestions_no_head_received(db: Path) -> None:def test_entity_names_parse_profile_entries() -> None:- assert wp.entity_names("Tesla (TSLA) — Model Y is the volume benchmark") == (["Tesla"], ["TSLA"])- assert wp.entity_names("GM / Chevrolet (Equinox EV, Blazer EV) — direct competitor") == (["GM", "Chevrolet"], [])- assert wp.entity_names("BYD — global cost leader; tariff-gated out of the US") == (["BYD"], [])- assert wp.entity_names("Hyundai / Kia (Ioniq 5, EV6, EV9) - strong value") == (["Hyundai", "Kia"], [])- assert wp.entity_names("Rivian (RIVN, 1211.HK)") == (["Rivian"], ["RIVN", "1211.HK"])- assert wp.entity_names("Stripe: payments") == (["Stripe"], [])- assert wp.entity_names(" ") == ([], [])+ assert wp.entity_names("Tesla (TSLA) — Model Y is the volume benchmark") == (["Tesla"], ["TSLA"], [])+ assert wp.entity_names("GM / Chevrolet (Equinox EV, Blazer EV) — direct competitor") == (["GM", "Chevrolet"], [], [])+ assert wp.entity_names("BYD — global cost leader; tariff-gated out of the US") == (["BYD"], [], [])+ assert wp.entity_names("Hyundai / Kia (Ioniq 5, EV6, EV9) - strong value") == (["Hyundai", "Kia"], [], [])+ assert wp.entity_names("BYD (1211.HK)") == (["BYD"], ["1211.HK"], [])+ assert wp.entity_names("Stripe: payments") == (["Stripe"], [], [])+ assert wp.entity_names("Brex (brex.com, status.brex.com) — expense cards") == (["Brex"], [], ["brex.com", "status.brex.com"])+ # A parenthesised list, or a product name, is never a ticker; hyphenated+ # names survive; whitespace and length are bounded.+ assert wp.entity_names("Apple (IOS, MAC) — CarPlay") == (["Apple"], [], [])+ assert wp.entity_names("Mercedes-Benz (MBG.DE)") == (["Mercedes-Benz"], ["MBG.DE"], [])+ assert wp.entity_names("Acme" + " " * 100000 + "Corp — x").names == ["Acme Corp"]+ assert wp.entity_names(" ") == ([], [], [])+ # Dashes without spaces still split; ordinary abbreviations are not+ # tickers; lower-case tickers are upper-cased; a URL entry grounds as its+ # site label with the host pinned; nested parentheses are stripped.+ assert wp.entity_names("Tesla (TSLA)—Model Y is the volume benchmark") == (["Tesla"], ["TSLA"], [])+ assert wp.entity_names("Stripe (US, EU) — payments").tickers == []+ assert wp.entity_names("Gartner (IT) — research").tickers == []+ assert wp.entity_names("Tesla (tsla)") == (["Tesla"], ["TSLA"], [])+ assert wp.entity_names("https://status.stripe.com") == (["stripe"], [], ["status.stripe.com"])+ assert wp.entity_names("GM (Chevrolet (EV) brand)") == (["GM"], [], [])+ assert wp.entity_names("Stripe (stripe.com/blog; payments)").names == ["Stripe"]def _descriptive_profile() -> CompanyProfile:@@ -957,6 +973,10 @@ def test_descriptive_profile_entries_ground_by_name_only() -> None:assert wp.match_entity("BYD Auto", vocab) == ("byd", wp.KIND_COMPETITOR)assert wp.match_entity("GM", vocab) == ("gm", wp.KIND_COMPETITOR)assert wp.match_entity("General Motors", vocab) is None # a different name is not a match+ # A ticker grounds only as itself: never as part of a longer name.+ assert wp.match_entity("TSLA", vocab) == ("tsla", wp.KIND_TICKER)+ assert wp.match_entity("TSLA Holdings", vocab) is None+ assert wp.match_entity("1211.HK", vocab) == ("1211 hk", wp.KIND_TICKER)def test_short_names_get_own_source_and_finding_support() -> None:@@ -968,6 +988,19 @@ def test_short_names_get_own_source_and_finding_support() -> None:p = _proposal(slug="rss-byd", target="https://www.byd.com/news/feed", grounding_entity="BYD")d = wp.classify(p, f, ctx)assert d.tier == wp.TIER_DIRECT and "target is the entity's own source" in d.reasons+ # A look-alike registration carries the same site label, so it passes the+ # label rule — pinning the entity's domains in the profile closes that.+ look_alike = _proposal(slug="rss-byd-fake", target="https://byd.co.ke/feed", grounding_entity="BYD")+ fake_f = f.model_copy(update={"relevant_urls": ["https://byd.co.ke/news"]})+ assert wp.classify(look_alike, fake_f, ctx).tier == wp.TIER_DIRECT+ pinned = CompanyProfile.model_validate({+ "name": "X", "competitive_landscape": {"primary_competitors": ["BYD (byd.com) — cost leader"]},+ })+ pinned_ctx = wp.PolicyContext(vocabulary=wp.grounding_vocabulary(pinned, [], []), priority_terms=[], existing=[])+ assert pinned_ctx.vocabulary["byd"].domains == ("byd.com",)+ fake_d = wp.classify(look_alike, fake_f, pinned_ctx)+ assert fake_d.tier == wp.TIER_SUGGEST and "target is the entity's own source" not in fake_d.reasons+ assert wp.classify(p, f, pinned_ctx).tier == wp.TIER_DIRECT# A dotted ticker: own source when grounded as the ticker, and named in# text as a phrase.f2 = _finding(title="BYD (1211.HK) slides", summary="1211.HK fell 6% on 2026-09-05.", relevant_urls=[])@@ -987,6 +1020,10 @@ def test_short_names_get_own_source_and_finding_support() -> None:assert not wp.named_in_decision("byd auto", SimpleNamespace(summary="Watch BYD pricing"), vocab)assert wp.entity_declined("BYD Auto", [SimpleNamespace(reason="not_relevant", entity="BYD")])assert not wp.entity_declined("Rivian", [SimpleNamespace(reason="not_relevant", entity="BYD")])+ # A generic declined word never blocks, and a longer declined name does+ # not block the short profile name inside it.+ assert not wp.entity_declined("Acme Data Systems", [SimpleNamespace(reason="not_relevant", entity="data")])+ assert not wp.entity_declined("GM", [SimpleNamespace(reason="not_relevant", entity="GM Financial")])def test_proposal_without_finding_index_is_linked_to_the_citing_finding(db: Path) -> None:@@ -1005,9 +1042,41 @@ def test_proposal_without_finding_index_is_linked_to_the_citing_finding(db: Pathnowhere = _proposal(slug="rss-else", target="https://elsewhere.com/feed", grounding_entity="Acme Corp",finding_index=None)assert wp.auto_link_finding(nowhere, findings, ctx) is None- out = wp.apply_proposals([unlinked, nowhere], findings, ctx, db_path=db)- assert [o["outcome"] for o in out] == ["added", "rejected"]+ # A guessed index that does not concern the source is repaired too.+ wrong = _proposal(finding_index=0)+ out = wp.apply_proposals([unlinked, nowhere, wrong], findings, ctx, db_path=db)+ assert [o["outcome"] for o in out] == ["added", "rejected", "rejected"] # 3rd: same source as 1st+ assert "duplicate target" in out[2]["result_preview"]row = ms.get_watchlist_item_by_slug("rss-acme-blog", db_path=db)assert row is not None- assert wp.policy_stamp_of(row)["reasons"][0] == "linked to finding #2 by its cited source"+ assert wp.policy_stamp_of(row)["reasons"][0] == "linked to finding #2, which concerns this source"assert wp.policy_stamp_of(row)["specialist"] == "cso"+ assert wp.policy_stamp_of(row)["source_url"] == "https://www.acme.com/blog/pricing"+ assert unlinked.finding_index is None # the caller's proposal is left as filed+ repaired = wp.apply_proposals([_proposal(slug="rss-acme-2", target="https://acme.com/news/feed",+ finding_index=0)], findings, ctx, db_path=db)+ assert repaired[0]["outcome"] == "added"+ row2 = ms.get_watchlist_item_by_slug("rss-acme-2", db_path=db)+ assert row2 is not None and wp.policy_stamp_of(row2)["reasons"][0].endswith("(the cited #1 did not)")+++def test_auto_link_prefers_the_finding_that_cites_the_source() -> None:+ ctx = _ctx()+ findings = [+ _finding(title="Globex beats, Acme called a laggard", summary="Acme lags Globex; Initech too.",+ relevant_urls=["https://globex.com/ir/q3"], verification="confirmed",+ source_specialist="cfo,cso"),+ _finding(title="Acme Q3", summary="ACME reported Q3.", relevant_urls=["https://acme.com/ir/q3"],+ confidence="medium"),+ ]+ stock = _proposal(slug="stock-acme", signal_type="stock", target="ACME", grounding_entity="ACME",+ finding_index=None)+ assert wp.auto_link_finding(stock, findings, ctx) == 1 # names the ticker, not just the entity+ feed = _proposal(slug="rss-acme-ir", target="https://acme.com/ir/feed", grounding_entity="Acme Corp",+ finding_index=None)+ assert wp.auto_link_finding(feed, findings, ctx) == 1 # cites the site+ # An entity outside company data never links by name (classify would+ # not honour it either); a cited site still does.+ stranger = _proposal(slug="stock-intc", signal_type="stock", target="INTC", grounding_entity="Initech Holdings",+ finding_index=None)+ assert wp.auto_link_finding(stranger, findings, ctx) is None