AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(watchlist): ground research watches in departments and recent decisions; route to department heads
Rufus85fc364a3089
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02753d00..44f59091 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- **Research watch policy grounds in departments and recent decisions, and+ routes to department heads.** Departments gain a `watched_entities` list+ (`PATCH /departments/{slug}`, edited one per line on the department page).+ Named there, an entity is strong grounding for the research watch policy —+ like a profile vendor or ticker — so a proposal about it can be added on+ its own, and the watch is inserted with `route_to_department` /+ `route_to_person_id` (the head). Those columns now actually route: every+ watch alert carries the department's head and a `department:<slug>` tag,+ so it queues on the head's briefing instead of the principal's. Charter+ scope phrases and goal key results ground suggestions only. Suggestions in+ a department's area go to its head as one "Watch suggestions for+ <Department>" card per run (refreshed in place, re-issued weekly after it+ is handled; the principal when the department has no head), and the+ principal's pile-up nudge counts only their own. The ten most recent+ episodic decisions from the last 90 days are rendered to the research+ council and add a point to a proposal whose entity they name (with the+ decision's department as a routing hint). The research fingerprint tracks+ department watch interests and the decisions that name a known entity, so+ a new watched entity or a relevant decision triggers the next scan.+ `/watchlist` shows "for: <department>" on routed rows.- **Research watchlist policy — grounded watches go straight in, uncertainones become suggestions.** The research council's watchlist pass no longeradds watches itself; its only tool is `propose_watch`, and deterministicdiff --git a/packages/core/openexecutive/api/routes/departments.py b/packages/core/openexecutive/api/routes/departments.pyindex e5880574..fa0e7e33 100644--- a/packages/core/openexecutive/api/routes/departments.py+++ b/packages/core/openexecutive/api/routes/departments.py@@ -14,7 +14,7 @@ from __future__ import annotationsimport loggingfrom fastapi import APIRouter, HTTPException, Response, status-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validatorfrom openexecutive.departments import registry, storefrom openexecutive.departments.models import (@@ -73,6 +73,29 @@ class DepartmentPatch(BaseModel):slack_channel_id: str | None = Nonediscord_channel_id: str | None = Nonetelegram_chat_id: str | None = None+ # Named external entities the department wants watched (strong grounding+ # for the research watch policy). Sending `[]` clears the list.+ watched_entities: list[str] | None = Field(default=None, max_length=50)++ @field_validator("watched_entities")+ @classmethod+ def _clean_watched_entities(cls, value: list[str] | None) -> list[str] | None:+ if value is None:+ return None+ cleaned: list[str] = []+ seen: set[str] = set()+ for raw in value:+ name = " ".join(raw.split())+ if not name:+ continue+ if len(name) > 128:+ raise ValueError("watched entity names must be 128 characters or fewer")+ key = name.casefold()+ if key in seen:+ continue+ seen.add(key)+ cleaned.append(name)+ return cleanedclass GoalCreate(BaseModel):@@ -177,6 +200,7 @@ def patch_department(slug: str, patch: DepartmentPatch) -> DepartmentState:slack_channel_id=patch.slack_channel_id if "slack_channel_id" in raw else _UNSET,discord_channel_id=patch.discord_channel_id if "discord_channel_id" in raw else _UNSET,telegram_chat_id=patch.telegram_chat_id if "telegram_chat_id" in raw else _UNSET,+ watched_entities=patch.watched_entities,)registry.invalidate()return _must_get(slug)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 509f6ca7..53c29d39 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1040,6 +1040,20 @@ departments:completeness: openexecutive.departments.completeness — measures how much of a department's required state is filled in (used by the Getting Started checklist).prompt_block: openexecutive.departments.prompt_block.render_org_block — produces the cached org block in system block 1.charters_dir: openexecutive.departments.charters — per-department playbooks loaded into the head persona.+ watched_entities: |+ `DepartmentConfig.watched_entities: list[str]` — external entities+ (vendors under evaluation, competitors in the department's lane,+ tickers) the department wants monitored. Column+ `watched_entities_json TEXT NOT NULL DEFAULT '[]'`, added additively by+ `_migrate_add_watched_entities_column` (same PRAGMA-guarded pattern as+ the channel columns); a corrupt value reads back as []. PATCH+ /departments/{slug} accepts `watched_entities` (<= 50 items, each+ whitespace-collapsed, <= 128 chars, case-insensitive de-duplicated;+ `[]` clears). Edited on /departments/{slug} ("Watched entities", one+ per line). The research watch policy treats each as a strong+ `department_entity` grounding term tagged with the department, so a+ proposal about one can be added directly and is routed to the+ department and its head — see research_watch_policy.channels: |Each department can optionally configure `slack_channel_id`,`discord_channel_id`, and `telegram_chat_id` on its row. When set,@@ -1367,11 +1381,24 @@ external_monitoring:finding_index). `monitoring.research.watch_policy` decides deterministically:- grounding vocabulary = company name + competitive_landscape.primary_competitors+ profile.vendors + profile.tickers + active initiative titles +- strategic_priorities.current_year (+ existing watch labels, which only- corroborate). The entity MUST match a company-data term for a direct add.+ strategic_priorities.current_year + each department's `watched_entities`+ (kind department_entity, strong) + each department's charter scope+ phrases and goal key results (kind department_scope, suggestion-only)+ (+ existing watch labels, which only corroborate). The entity MUST+ match a company-data term for a direct add. Every vocabulary value is+ a VocabEntry(kind, department): terms that came from a department carry+ its slug, and a profile term a department also lists keeps the profile+ kind but gains the department (stronger kind wins, department is kept).- vocabulary precedence when a term appears in several sources:- company > competitor > vendor > ticker > initiative > priority > watch.+ company > competitor > department_entity > vendor > ticker > initiative+ > priority > department_scope > watch.Partial (token) matching ignores stopwords and tokens < 4 chars.+ - episodic decisions: the run loads the 10 most recent `decisions` rows+ from the last 90 days (watch_policy.recent_decisions); a proposal whose+ matched entity is named in one scores +1 ("named in a recent+ decision"), and when the term has no department but the decision was+ recorded for one, that department becomes the routing hint. Decisions+ are rendered to every specialist as RECENT DECISIONS (user turn).- score ledger: +2 entity in company data (mandatory), +1 entity alreadywatched under another source, +1 target is the entity's own source (forstock/edgar the grounding entity IS the ticker / a URL whose SITE LABEL —@@ -1385,8 +1412,9 @@ external_monitoring:URL; a ticker/query target appears in the finding text or is the namedentity. A strong finding cannot be borrowed for an unrelated page.- direct add at score >= 4 with the mandatory match AND the entity's OWN- source AND a strong kind (company / competitor / vendor / ticker —- initiative- or priority-grounded proposals are suggestions at most); model+ source AND a strong kind (company / competitor / vendor / ticker /+ department_entity — initiative-, priority- or department_scope-grounded+ proposals are suggestions at most); model`certainty` can only downgrade; `query` never direct; a suggestion needsa linked finding and score >= 1 (SUGGEST_THRESHOLD) — nothing vouchingfor it is rejected; at or above WATCHLIST_MAX_ENABLED (40) enabled rows@@ -1406,9 +1434,27 @@ external_monitoring:not_relevant decline on an ungrounded suggestion still blacklists it.- direct → mode=active, origin=research; suggestion → mode=dry_run,origin=research_proposed; rationale in `notes`; policy stamp (entity,- grounding_kind, specialist, score, reasons, source_url) in+ grounding_kind, department, specialist, score, reasons, source_url) inconfig_json._policy. Reject: invalid target, same site + signal_typealready watched, declined target, spent budget.+ - routing: a department-grounded row is inserted with+ route_to_department=<slug> and route_to_person_id=<the department's+ head at insert time> (a later head change does not re-route existing+ rows). monitoring.pipeline._signal_to_alert_event maps these onto the+ AlertEvent (routed_to_person_id, channel="department:<slug>") for EVERY+ watch, manual ones included, so alerts.pipeline routes the alert to the+ head and tags it department:<slug> and it queues on the head's /today.+ - department head approval: after the apply loop, suggestions are grouped+ by department and ONE "Watch suggestions for <Title>" card per+ department is filed via departments.authority.propose_via_alert+ (source=authority_gate, routed to the head, or to the principal when+ the department has no head; tags department:<slug>, person:<id>,+ watchlist). propose_via_alert's new `external_id_suffix` (the ISO week)+ makes the card recurring: an open card is refreshed in place+ (coalesce_alert), an acknowledged one is not re-minted until the next+ week. The principal's pile-up nudge counts only suggestions with no+ route_to_department. /watchlist shows "for: <department>" on routed+ suggestion and research cards. Approve/decline stay identity-free.- declines (`watchlist_declines`, keyed by normalized target — httpsforced, www. dropped, host/path lower-cased, query/fragment/trailingslash removed): explicit (Decline button, "Stop watching…",@@ -1446,6 +1492,11 @@ external_monitoring:suggestion never spawns another nudge.- the research state fingerprint hashes only enabled + active rows, soapproving / declining a suggestion never triggers a fresh research run.+ It also hashes each department's watched_entities / charter scope /+ goal key results, and the recent decisions whose summary names a+ vocabulary term (only those: the chat extractor writes decisions+ freely, and one naming nothing the policy knows cannot change what+ the policy would do).- surfaces: /watchlist "Suggested by the Executive" (Approve / Decline…with reason), "Added by the Executive · rationale" on research cardswith "Stop watching…", the morning brief's HANDLED block (watching /diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 1a56464a..19599727 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |","mermaid": null,- "generated_at": "2026-09-12T10:44:45.779442+00:00"+ "generated_at": "2026-09-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json b/packages/core/openexecutive/architecture/prebuilt/external_monitoring.jsonindex 3c650425..cab9c230 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, or one of the profile's `vendors` / `tickers` (an initiative title or a current-year priority 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; 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 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. 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 > initiative > priority > watch label).\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- **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** (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; 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 is named in one of the ten most recent episodic decisions from the last 90 days, ±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. 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 > department entity > vendor > ticker > 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 competitor that Finance also lists still routes to Finance.\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`, `channel=\"department:<slug>\"`), so the alerts it raises queue on the head's `/today` 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 with no department. `/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-12T11:14:44.757524+00:00"+ "generated_at": "2026-09-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex 9f5cf2d4..fdb0ce37 100644--- a/packages/core/openexecutive/architecture/prebuilt/org.json+++ b/packages/core/openexecutive/architecture/prebuilt/org.json@@ -1,7 +1,7 @@{"section_id": "org","title": "Org Structure (Departments & People)",- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\n### Authority gate\nEach department declares an `AuthorityLevel`: `propose_only` routes scheduled actions through an approval workflow (`wait_for_human`); `auto_execute` (autonomous) fires directly. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`: `propose_only` routes scheduled actions through an approval workflow (`wait_for_human`); `auto_execute` (autonomous) fires directly. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",- "generated_at": "2026-06-01T00:00:00+00:00"+ "generated_at": "2026-09-12T12:03:38.574978+00:00"}diff --git a/packages/core/openexecutive/departments/authority.py b/packages/core/openexecutive/departments/authority.pyindex 46c1ab3b..06633c19 100644--- a/packages/core/openexecutive/departments/authority.py+++ b/packages/core/openexecutive/departments/authority.py@@ -171,6 +171,8 @@ def propose_via_alert(body: str,suggested_action: str = "",extra_tags: list[str] | None = None,+ *,+ external_id_suffix: str = "",) -> int | None:"""Persist a proposal as an alert routed to a specific Person.@@ -180,19 +182,31 @@ def propose_via_alert(and future resolvers can filter/match without parsing the body;``extra_tags`` lets a caller carry the originating alert's tags (e.g.a ``comp`` / ``legal`` marker) onto the proposal.++ ``external_id_suffix`` turns the card into a recurring one: an open+ (unread) card with the same dedup key is refreshed in place with the new+ body instead of a second row being inserted, and once the person has+ acted on it a fresh card is minted only when the suffix changes (callers+ pass e.g. the ISO week). Without a suffix the proposal is one-shot and a+ repeat with the same summary is suppressed for good."""- from openexecutive.alerts.store import insert_alert+ from openexecutive.alerts.store import coalesce_alert, insert_alerttopic_tags = [f"department:{department_slug}", f"person:{person_id}"]for tag in extra_tags or []:if tag not in topic_tags:topic_tags.append(tag)dedup_key = f"proposal:{department_slug}:{person_id}:{summary[:60]}"+ external_id = f"{dedup_key}:{external_id_suffix}" if external_id_suffix else dedup_keytry:+ if external_id_suffix and coalesce_alert(+ source="authority_gate", dedup_key=dedup_key, severity="medium", body=body,+ ):+ return Nonereturn insert_alert(source="authority_gate",- external_id=dedup_key,+ external_id=external_id,severity="medium",headline=summary,body=body,diff --git a/packages/core/openexecutive/departments/models.py b/packages/core/openexecutive/departments/models.pyindex 27ae2078..0375092b 100644--- a/packages/core/openexecutive/departments/models.py+++ b/packages/core/openexecutive/departments/models.py@@ -94,6 +94,13 @@ class DepartmentConfig(BaseModel):slack_channel_id: str | None = Nonediscord_channel_id: str | None = Nonetelegram_chat_id: str | None = None+ # Named external entities this department wants monitored (vendors it+ # is evaluating, competitors in its lane, tickers it tracks). The+ # research watch policy treats these as strong grounding — like the+ # company profile's `vendors` / `tickers` — so a proposal about one of+ # them can be added to the watchlist directly and routed to this+ # department (and its head) instead of waiting on the principal.+ watched_entities: list[str] = Field(default_factory=list)class DepartmentState(BaseModel):diff --git a/packages/core/openexecutive/departments/store.py b/packages/core/openexecutive/departments/store.pyindex f6f32758..fca1f639 100644--- a/packages/core/openexecutive/departments/store.py+++ b/packages/core/openexecutive/departments/store.py@@ -140,6 +140,7 @@ def initialize_db(db_path: Path | None = None) -> None:_migrate_specialist_key_nullable(conn)_migrate_add_channel_columns(conn)_migrate_add_last_reviewed_at_column(conn)+ _migrate_add_watched_entities_column(conn)def _migrate_add_last_reviewed_at_column(conn: sqlite3.Connection) -> None:@@ -186,6 +187,28 @@ def _migrate_add_channel_columns(conn: sqlite3.Connection) -> None:raise+def _migrate_add_watched_entities_column(conn: sqlite3.Connection) -> None:+ """Add `watched_entities_json` to `departments` if missing.++ A JSON list of external entity names the department wants the research+ watch policy to treat as strong grounding (see+ `monitoring/research/watch_policy.grounding_vocabulary`). Additive+ ALTER pattern mirrors `_migrate_add_channel_columns`; the NOT NULL+ DEFAULT '[]' keeps `_row_to_config` free of a null branch.+ """+ existing = {row["name"] for row in conn.execute("PRAGMA table_info(departments)")}+ if "watched_entities_json" in existing:+ return+ try:+ conn.execute(+ "ALTER TABLE departments ADD COLUMN watched_entities_json "+ "TEXT NOT NULL DEFAULT '[]'"+ )+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise++def _migrate_okrs_to_goals(conn: sqlite3.Connection) -> None:"""Rename department_okrs → department_goals; add period_type column.@@ -323,6 +346,10 @@ def _row_to_config(row: sqlite3.Row) -> DepartmentConfig:return row[name]except (IndexError, KeyError):return None+ try:+ watched = json.loads(_opt_col("watched_entities_json") or "[]") or []+ except (ValueError, TypeError):+ watched = []return DepartmentConfig(slug=row["slug"],title=row["title"],@@ -341,6 +368,10 @@ def _row_to_config(row: sqlite3.Row) -> DepartmentConfig:slack_channel_id=_opt_col("slack_channel_id"),discord_channel_id=_opt_col("discord_channel_id"),telegram_chat_id=_opt_col("telegram_chat_id"),+ watched_entities=(+ [str(e) for e in watched if isinstance(e, str) and e.strip()]+ if isinstance(watched, list) else []+ ),)@@ -514,6 +545,7 @@ def update_department(slack_channel_id: str | None | object = _UNSET,discord_channel_id: str | None | object = _UNSET,telegram_chat_id: str | None | object = _UNSET,+ watched_entities: list[str] | None = None,db_path: Path | None = None,) -> bool:"""Partial update. Returns True if a row was modified.@@ -552,6 +584,8 @@ def update_department(fields.append(("discord_channel_id", discord_channel_id))if telegram_chat_id is not _UNSET:fields.append(("telegram_chat_id", telegram_chat_id))+ if watched_entities is not None:+ fields.append(("watched_entities_json", json.dumps(list(watched_entities))))if not fields:# Nothing to update; confirm the row exists so the route can 404.return get_department(slug, db_path) is not Nonediff --git a/packages/core/openexecutive/monitoring/pipeline.py b/packages/core/openexecutive/monitoring/pipeline.pyindex dc270406..904f3489 100644--- a/packages/core/openexecutive/monitoring/pipeline.py+++ b/packages/core/openexecutive/monitoring/pipeline.py@@ -278,6 +278,13 @@ def _signal_to_alert_event(# into the existing card (alerts.pipeline) while the signal-level# dedup_key keeps every observation in external_signals.dedup_hint=f"watch:{item.slug}",+ # A watch that belongs to a department (set by the research policy+ # from the department's watched entities, or by hand) sends its+ # alerts to that department's head and tags them department:<slug>+ # (alerts.pipeline reads both), so they queue on the head's /today+ # instead of the principal's.+ routed_to_person_id=item.route_to_person_id,+ channel=f"department:{item.route_to_department}" if item.route_to_department else None,)diff --git a/packages/core/openexecutive/monitoring/research/scheduler.py b/packages/core/openexecutive/monitoring/research/scheduler.pyindex ae3baa13..d828b90b 100644--- a/packages/core/openexecutive/monitoring/research/scheduler.py+++ b/packages/core/openexecutive/monitoring/research/scheduler.py@@ -75,9 +75,17 @@ def compute_research_state_hash(db_path: Path | None = None) -> str:"""Hash the inputs the research workflow reads.The inputs are: the company profile's prompt-form text, the- titles + statuses of every active initiative, and the slug+target- list of every enabled, ACTIVE watchlist row. A change to any of these- invalidates the prior research; everything else is irrelevant.+ titles + statuses of every active initiative, the slug+target list of+ every enabled, ACTIVE watchlist row, each department's watched+ entities / charter scope / goal key results, and the recent episodic+ decisions that name something in the grounding vocabulary. A change+ to any of these invalidates the prior research; everything else is+ irrelevant.++ Only *matching* decisions count: the chat memory extractor writes+ decisions freely, and one that names nothing the policy knows cannot+ change what the policy would do, so it must not trigger a 7-specialist+ re-run.Dry-run rows are excluded on purpose: the research pass files its ownsuggestions as dry-run rows, and the principal approving or declining@@ -144,6 +152,36 @@ def compute_research_state_hash(db_path: Path | None = None) -> str:logger.exception("research.scheduler: watchlist load failed")parts.append("WATCHLIST_ERROR")+ departments: list = []+ try:+ from openexecutive.departments.store import list_departments++ departments = list(list_departments())+ parts.append("DEPARTMENTS:")+ for state in sorted(departments, key=lambda d: d.config.slug):+ parts.append(+ f"{state.config.slug}::"+ + "|".join(state.config.watched_entities)+ + "::" + "|".join(state.config.charter.scope)+ + "::" + "|".join(g.key_result for g in state.goals)+ )+ except Exception:+ logger.exception("research.scheduler: departments load failed")+ parts.append("DEPARTMENTS_ERROR")++ try:+ from openexecutive.monitoring.research import watch_policy++ vocabulary = watch_policy.grounding_vocabulary(profile, [], [], departments)+ parts.append("DECISIONS:")+ for decision in watch_policy.recent_decisions(db_path=db_path):+ summary = str(getattr(decision, "summary", "") or "")+ if any(watch_policy.named_in_decision(term, decision) for term in vocabulary):+ parts.append(f"{getattr(decision, 'id', '')}::{summary[:120]}")+ except Exception:+ logger.exception("research.scheduler: decisions load failed")+ parts.append("DECISIONS_ERROR")+digest = hashlib.sha256("\n".join(parts).encode()).hexdigest()return digestdiff --git a/packages/core/openexecutive/monitoring/research/watch_policy.py b/packages/core/openexecutive/monitoring/research/watch_policy.pyindex 9bdee33a..afa595dd 100644--- a/packages/core/openexecutive/monitoring/research/watch_policy.py+++ b/packages/core/openexecutive/monitoring/research/watch_policy.py@@ -12,12 +12,20 @@ Two tiers:- **direct** — added live, quietly (daily cadence, medium floor, keywordtrigger). Requires the grounding entity to be *in company data* (a named- competitor / vendor / ticker / initiative / priority / the company itself)- plus enough corroboration (see :func:`classify`). This is the "high- likelihood, worth watching — just add it" case.+ competitor / vendor / ticker / initiative / priority / the company itself,+ or an entity a department lists under its watched entities) plus enough+ corroboration (see :func:`classify`). This is the "high likelihood, worth+ watching — just add it" case.- **suggest** — inserted in ``dry_run`` (polls, never alerts) with- ``origin=research_proposed``; the principal approves or declines it on- ``/watchlist``. This is the "not sure" case.+ ``origin=research_proposed``; the principal — or, when the grounding term+ belongs to a department, that department's head — approves or declines+ it on ``/watchlist``. This is the "not sure" case.++Company data is more than the static profile: a department's watched+entities, charter scope and goals, and the entities named in recent+episodic decisions all feed the grounding vocabulary, and a term that came+from a department carries that department along so the watch (and every+alert it raises) is routed to it.A proposal with nothing vouching for it (no linked finding, score 0), onefor a source already watched, one past the enabled-watch ceiling or the@@ -33,7 +41,7 @@ import refrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom pathlib import Path-from typing import Any+from typing import Any, NamedTuplefrom openexecutive.alerts.models import AlertSeverityfrom openexecutive.audit import log_event as audit_log@@ -101,22 +109,33 @@ KIND_VENDOR = "vendor"KIND_TICKER = "ticker"KIND_INITIATIVE = "initiative"KIND_PRIORITY = "priority"+# A department's explicit `watched_entities` list: a named external entity,+# like a profile vendor, so it may ground a direct add.+KIND_DEPARTMENT_ENTITY = "department_entity"+# A department's charter scope phrase or goal key result: free text, so it+# grounds suggestions only (like a priority).+KIND_DEPARTMENT_SCOPE = "department_scope"KIND_WATCH = "watch" # already watched (label/target) — corroborates, never groundsGROUNDING_KINDS: frozenset[str] = frozenset({KIND_COMPANY, KIND_COMPETITOR, KIND_VENDOR, KIND_TICKER, KIND_INITIATIVE, KIND_PRIORITY,+ KIND_DEPARTMENT_ENTITY, KIND_DEPARTMENT_SCOPE,})# Kinds that name an external ENTITY the company deals with. Only these can# ground a direct add: an initiative title or a priority sentence is company# data too, but it is a bag of common words ("growth", "platform") that a# planted finding can echo, so a watch grounded only in one is a suggestion.STRONG_GROUNDING_KINDS: frozenset[str] = frozenset({- KIND_COMPANY, KIND_COMPETITOR, KIND_VENDOR, KIND_TICKER,+ KIND_COMPANY, KIND_COMPETITOR, KIND_VENDOR, KIND_TICKER, KIND_DEPARTMENT_ENTITY,})# When one term appears in several sources the strongest kind wins._KIND_RANK: dict[str, int] = {- KIND_COMPANY: 7, KIND_COMPETITOR: 6, KIND_VENDOR: 5, KIND_TICKER: 4,- KIND_INITIATIVE: 3, KIND_PRIORITY: 2, KIND_WATCH: 1,+ KIND_COMPANY: 9, KIND_COMPETITOR: 8, KIND_DEPARTMENT_ENTITY: 7, KIND_VENDOR: 6,+ KIND_TICKER: 5, KIND_INITIATIVE: 4, KIND_PRIORITY: 3, KIND_DEPARTMENT_SCOPE: 2,+ KIND_WATCH: 1,}+# Recent decisions are consulted this far back, and only this many.+DECISION_LOOKBACK_DAYS = 90+DECISION_LIMIT = 10# Material-event words every research feed trigger carries, so a competitor# blog surfaces "we raised / we launched / pricing" and not every post.@@ -162,6 +181,9 @@ _POLL_HISTORY_TO_READ = 10_NUDGE_MIN_PENDING = 3_NUDGE_MIN_AGE_DAYS = 7NUDGE_ALERT_SOURCE = "watchlist_suggestions"+# Department-routed suggestions go to the department head as one card per+# department per run (see _notify_department_heads).+DEPARTMENT_CARD_MAX_LINES = 10# --------------------------------------------------------------------- #@@ -211,16 +233,39 @@ class PolicySettings:return cls()+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."""++ kind: str+ department: str = ""+++class DepartmentRef(NamedTuple):+ """What the policy needs to know about a department for routing."""++ title: str+ head_person_id: int | None = None+++Vocabulary = dict[str, VocabEntry]++@dataclassclass PolicyContext:"""Everything classify() needs, gathered once per run."""- vocabulary: dict[str, str] # normalized term -> kind+ vocabulary: Vocabulary # normalized term -> (kind, department slug)priority_terms: list[str]existing: list[WatchlistItem]outcome_counts: dict[tuple[str, str], dict[str, int]] = field(default_factory=dict)settings: PolicySettings = field(default_factory=PolicySettings)now: datetime = field(default_factory=lambda: datetime.now(UTC))+ # slug -> (title, head person id); routing targets for department terms.+ departments: dict[str, DepartmentRef] = field(default_factory=dict)+ # Recent episodic decisions (memory.episodic.Decision or anything with+ # ``summary`` / ``department`` attributes), newest first.+ recent_decisions: list[Any] = field(default_factory=list)@dataclass@@ -230,6 +275,8 @@ class Decision:entity: strgrounding_kind: strreasons: list[str]+ # Department the watch is routed to ("" = the principal's).+ department: str = ""# --------------------------------------------------------------------- #@@ -245,18 +292,30 @@ def grounding_vocabulary(profile: Any,initiatives: list[Any],existing: list[WatchlistItem],-) -> dict[str, str]:- """Normalized term → kind. Company-data kinds win over ``watch`` when a- term appears in both (a competitor that is already watched still grounds- a new watch on a *different* source of theirs)."""- vocab: dict[str, str] = {}-- def add(term: str, kind: str) -> None:+ departments: list[Any] | None = None,+) -> Vocabulary:+ """Normalized term → :class:`VocabEntry`. Company-data kinds win over+ ``watch`` when a term appears in both (a competitor that is already+ watched still grounds a new watch on a *different* source of theirs).++ ``departments`` are ``DepartmentState`` rows: each watched entity is a+ ``department_entity`` term and each charter-scope phrase / goal key+ result a ``department_scope`` term, all tagged with the department's+ slug. When a term is both a profile kind and a department's, the+ stronger kind wins but the department is kept — a profile competitor+ that Finance also lists stays a ``competitor`` and routes to Finance."""+ vocab: Vocabulary = {}++ def add(term: str, kind: str, department: str = "") -> None:n = _norm(term)if len(n) < 2:return- if n not in vocab or _KIND_RANK[kind] > _KIND_RANK[vocab[n]]:- vocab[n] = kind+ current = vocab.get(n)+ if current is None:+ vocab[n] = VocabEntry(kind, department)+ return+ best_kind = kind if _KIND_RANK[kind] > _KIND_RANK[current.kind] else current.kind+ vocab[n] = VocabEntry(best_kind, current.department or department)for item in existing:for label_key in ("display_name", "feed_label", "vendor_label", "label"):@@ -280,9 +339,60 @@ def grounding_vocabulary(for c in list(getattr(getattr(profile, "competitive_landscape", None), "primary_competitors", []) or []):add(str(c), KIND_COMPETITOR)add(str(getattr(profile, "name", "") or ""), KIND_COMPANY)+ for state in departments or []:+ config = getattr(state, "config", None)+ slug = str(getattr(config, "slug", "") or "")+ if not slug:+ continue+ for entity in list(getattr(config, "watched_entities", []) or []):+ add(str(entity), KIND_DEPARTMENT_ENTITY, slug)+ charter = getattr(config, "charter", None)+ for phrase in list(getattr(charter, "scope", []) or []):+ add(str(phrase), KIND_DEPARTMENT_SCOPE, slug)+ for goal in list(getattr(state, "goals", []) or []):+ add(str(getattr(goal, "key_result", "") or ""), KIND_DEPARTMENT_SCOPE, slug)return vocab+def recent_decisions(+ now: datetime | None = None, *, db_path: Path | None = None,+) -> list[Any]:+ """Episodic decisions from the last :data:`DECISION_LOOKBACK_DAYS`+ days, newest first, at most :data:`DECISION_LIMIT`. Never raises."""+ try:+ from openexecutive.memory.episodic import get_recent_decisions++ rows = get_recent_decisions(limit=DECISION_LIMIT, db_path=db_path)+ except Exception:+ logger.debug("watch_policy: recent decisions unavailable", exc_info=True)+ return []+ now = now or datetime.now(UTC)+ cutoff = now - timedelta(days=DECISION_LOOKBACK_DAYS)+ out: list[Any] = []+ for row in rows:+ ts = _parse(str(getattr(row, "timestamp", "") or ""))+ if ts is not None and ts < cutoff:+ continue+ out.append(row)+ return out+++def department_refs(departments: list[Any] | None) -> dict[str, DepartmentRef]:+ """``slug → DepartmentRef`` for :attr:`PolicyContext.departments`."""+ refs: dict[str, DepartmentRef] = {}+ for state in departments or []:+ config = getattr(state, "config", None)+ slug = str(getattr(config, "slug", "") or "")+ if not slug:+ continue+ head = getattr(config, "head_person_id", None)+ refs[slug] = DepartmentRef(+ title=str(getattr(config, "title", "") or slug),+ head_person_id=int(head) if isinstance(head, int) else None,+ )+ return refs++def priority_terms(profile: Any) -> list[str]:"""Distinctive words from the current-year priorities (feed triggers)."""out: list[str] = []@@ -293,7 +403,7 @@ def priority_terms(profile: Any) -> list[str]:return out[:6]-def _distinctive_tokens(text: str, vocabulary: dict[str, str] | None = None) -> set[str]:+def _distinctive_tokens(text: str, vocabulary: dict[str, Any] | None = None) -> set[str]:"""Tokens that may carry a partial match: not stopwords, and either longenough or a whole vocabulary term in their own right (short names suchas IBM, AWS, SAP)."""@@ -304,16 +414,34 @@ def _distinctive_tokens(text: str, vocabulary: dict[str, str] | None = None) ->}-def match_entity(entity: str, vocabulary: dict[str, str]) -> tuple[str, str] | None:+def _entry(value: Any) -> VocabEntry:+ """Coerce a vocabulary value: a plain kind string (legacy / test dicts)+ 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 ""))+ return VocabEntry(str(value), "")+++def match_entity(entity: str, vocabulary: dict[str, Any]) -> tuple[str, str] | None:"""``(term, kind)`` for the vocabulary term the entity names, else None.Token containment both ways, so "Acme Corp" matches "Acme" and "Acme"matches "Acme Corp"; single-token matches must be a whole token."""+ hit = match_vocab(entity, vocabulary)+ return (hit[0], hit[1].kind) if hit else None+++def match_vocab(entity: str, vocabulary: dict[str, Any]) -> tuple[str, VocabEntry] | None:+ """``(term, VocabEntry)`` for the vocabulary term the entity names, else+ None — :func:`match_entity` with the department kept."""n = _norm(entity)if len(n) < 2:return None- exact = vocabulary.get(n)- if exact is not None and exact != KIND_WATCH:+ exact_value = vocabulary.get(n)+ exact = _entry(exact_value) if exact_value is not None else None+ if exact is not None and exact.kind != KIND_WATCH:return n, exact# Partial matching only on distinctive tokens: no stopwords, nothing# shorter than _MIN_PARTIAL_TOKEN unless the token is itself a whole@@ -323,21 +451,36 @@ def match_entity(entity: str, vocabulary: dict[str, str]) -> tuple[str, str] | Ntokens = _distinctive_tokens(n, vocabulary)# An exact hit on a watch label is only the fallback: a company-data term# that contains (or is contained by) the entity still wins.- best: tuple[str, str] | None = (n, exact) if exact is not None else None+ best: tuple[str, VocabEntry] | None = (n, exact) if exact is not None else Noneif not tokens:return best- for term, kind in vocabulary.items():+ for term, value in vocabulary.items():+ entry = _entry(value)term_tokens = _distinctive_tokens(term, vocabulary)if not term_tokens or not (term_tokens <= tokens or tokens <= term_tokens):continue# Prefer a company-data kind over a watch label, then the longer term.- if best is None or (best[1] == KIND_WATCH and kind != KIND_WATCH) or (- best[1] == kind and len(term) > len(best[0])+ if best is None or (best[1].kind == KIND_WATCH and entry.kind != KIND_WATCH) or (+ best[1].kind == entry.kind and len(term) > len(best[0])):- best = (term, kind)+ best = (term, entry)return best+def named_in_decision(entity_term: str, decision: Any) -> bool:+ """Does a recent episodic decision name this entity? Whole-term+ containment, or a distinctive token of the term as a whole word."""+ text = _norm(str(getattr(decision, "summary", "") or ""))+ if not entity_term or not text:+ return False+ if f" {entity_term} " in f" {text} ":+ return True+ entity_tokens = {+ t for t in entity_term.split() if len(t) >= _MIN_PARTIAL_TOKEN and t not in _STOPWORDS+ }+ return bool(entity_tokens & set(text.split()))++def entity_declined(entity: str, declines: list[Any]) -> bool:"""True when the principal declined this entity as *not relevant* (thereason that blacklists the company/topic, not just one source)."""@@ -364,7 +507,7 @@ def entity_declined(entity: str, declines: list[Any]) -> bool:# --------------------------------------------------------------------- #-def _is_own_source(proposal: WatchProposal, entity_term: str, vocabulary: dict[str, str]) -> bool:+def _is_own_source(proposal: WatchProposal, entity_term: str, vocabulary: dict[str, Any]) -> bool:"""The target is the entity's own primary source: its ticker forstock/edgar, its own domain for a URL, or an allowlisted primary host."""if proposal.signal_type in (SOURCE_KIND_STOCK, SOURCE_KIND_EDGAR):@@ -469,29 +612,55 @@ def classify(+1 finding confidence is high+1 finding verification is 'confirmed'+1 cross-specialist consensus on the finding+ +1 the entity is named in a recent episodic decision±1 policy history for (signal_type, grounding kind) at >=5 samplesFinding points count only when the cited finding concerns this source(shares its site with a cited URL, or names the entity). Direct at>= DIRECT_THRESHOLD with the mandatory entity match, only for theentity's OWN source, and only when the entity is a named competitor /- vendor / ticker / the company (STRONG_GROUNDING_KINDS); the model's own- ``certainty`` can only downgrade. ``query`` is never direct.+ vendor / ticker / the company / a department's watched entity+ (STRONG_GROUNDING_KINDS); the model's own ``certainty`` can only+ downgrade. ``query`` is never direct.++ The decision carries a ``department`` when the matched term belongs to+ one (or, failing that, when the decision that names the entity does):+ the watch and its alerts are routed there instead of to the principal."""reasons: list[str] = []score = 0- match = match_entity(proposal.grounding_entity, ctx.vocabulary)- entity_term, kind = (match if match else ("", ""))+ match = match_vocab(proposal.grounding_entity, ctx.vocabulary)+ entity_term, entry = (match if match else ("", VocabEntry("", "")))+ kind, department = entry.kind, entry.departmentgrounded = kind in GROUNDING_KINDSif grounded:score += 2- reasons.append(f"entity '{proposal.grounding_entity}' is a company {kind}")+ what = (+ f"a {ctx.departments[department].title if department in ctx.departments else department} "+ f"{'watched entity' if kind == KIND_DEPARTMENT_ENTITY else 'scope item'}"+ if kind in (KIND_DEPARTMENT_ENTITY, KIND_DEPARTMENT_SCOPE) and department+ else f"a company {kind}"+ )+ reasons.append(f"entity '{proposal.grounding_entity}' is {what}")elif kind == KIND_WATCH:score += 1reasons.append(f"entity '{proposal.grounding_entity}' matches an existing watch")else:reasons.append(f"entity '{proposal.grounding_entity}' is not in company data")+ if entity_term:+ for recent in ctx.recent_decisions:+ if not named_in_decision(entity_term, recent):+ continue+ score += 1+ reasons.append("named in a recent decision")+ # A decision made for a department is a routing hint when the+ # term itself has none.+ decided_for = str(getattr(recent, "department", "") or "")+ if not department and decided_for in ctx.departments:+ department = decided_for+ break+own_source = bool(entity_term) and _is_own_source(proposal, entity_term, ctx.vocabulary)if own_source:score += 1@@ -519,7 +688,7 @@ def classify(if _same_source_already_watched(proposal, ctx.existing):reasons.append("same source already watched")- return Decision(TIER_REJECT, score, entity_term, kind, reasons)+ return Decision(TIER_REJECT, score, entity_term, kind, reasons, department)enabled_count = sum(1 for i in ctx.existing if i.enabled)if enabled_count >= ctx.settings.max_enabled:@@ -527,12 +696,12 @@ def classify(# it would latch: every run would add polling rows and no proposal# could ever be direct again.reasons.append(f"watchlist at its ceiling ({enabled_count} enabled)")- return Decision(TIER_REJECT, score, entity_term, kind, reasons)+ return Decision(TIER_REJECT, score, entity_term, kind, reasons, department)if finding is None or score < SUGGEST_THRESHOLD:# Nothing vouches for it: no linked finding, or neither company data# nor evidence scored a point. Not worth the principal's time.reasons.append("no evidence to put in front of the principal")- return Decision(TIER_REJECT, score, entity_term, kind, reasons)+ return Decision(TIER_REJECT, score, entity_term, kind, reasons, department)tier = TIER_SUGGESTif grounded and score >= DIRECT_THRESHOLD:@@ -548,11 +717,14 @@ def classify(reasons.append("not the entity's own source")if tier == TIER_DIRECT and kind not in STRONG_GROUNDING_KINDS:tier = TIER_SUGGEST- reasons.append(f"grounded only in a {kind} — needs a named competitor, vendor or ticker")+ reasons.append(+ f"grounded only in a {kind} — needs a named competitor, vendor, ticker "+ "or department watched entity"+ )if tier == TIER_DIRECT and proposal.certainty != "confident":tier = TIER_SUGGESTreasons.append("model marked it unsure")- return Decision(tier, score, entity_term, kind, reasons)+ return Decision(tier, score, entity_term, kind, reasons, department)# --------------------------------------------------------------------- #@@ -613,6 +785,7 @@ def _policy_stamp(decision: Decision, proposal: WatchProposal, finding: Research# blacklists the entity the model named."entity": decision.entity or _norm(proposal.grounding_entity),"grounding_kind": decision.grounding_kind,+ "department": decision.department,"specialist": (finding.source_specialist if finding else ""),"score": decision.score,"reasons": decision.reasons[:6],@@ -639,6 +812,7 @@ def apply_proposals(direct_left = max(0, ctx.settings.max_direct_adds)suggest_left = max(0, ctx.settings.max_suggestions)seen_targets: set[str] = set()+ suggested_by_dept: dict[str, list[WatchlistItem]] = {}# Rows inserted earlier in this loop must count as "already watched" for# later proposals; work on a copy so the caller's context is untouched.live_existing = list(ctx.existing)@@ -678,6 +852,10 @@ def apply_proposals(config = dict(proposal.config)config["_policy"] = _policy_stamp(decision, proposal, finding)is_direct = decision.tier == TIER_DIRECT+ # A department-grounded watch is the department's: its alerts go to+ # the head (as of now — the head at insert time; a later head change+ # does not re-route existing rows) and its suggestion card too.+ dept_ref = ctx.departments.get(decision.department) if decision.department else Nonetry:new_id = ms.insert_watchlist_item(slug=proposal.slug,@@ -689,6 +867,8 @@ def apply_proposals(severity_floor=floor,severity_ceiling=AlertSeverity.URGENT,route_to_specialist=proposal.route_to_specialist,+ route_to_department=decision.department if dept_ref else "",+ route_to_person_id=dept_ref.head_person_id if dept_ref else None,mode=MODE_ACTIVE if is_direct else MODE_DRY_RUN,notes=proposal.rationale[:500],origin=ORIGIN_RESEARCH if is_direct else ORIGIN_RESEARCH_PROPOSED,@@ -730,9 +910,68 @@ def apply_proposals(proposal, "suggested",f"suggested for approval (score {decision.score}; {decision.reasons[-1] if decision.reasons else ''})",))+ if dept_ref is not None and inserted is not None:+ suggested_by_dept.setdefault(decision.department, []).append(inserted)+ _notify_department_heads(suggested_by_dept, ctx)return summaries+def _notify_department_heads(+ suggested: dict[str, list[WatchlistItem]], ctx: PolicyContext,+) -> int:+ """One "watch suggestions" card per department whose head should+ review the suggestions this run filed for it — routed to the head, or+ to the principal when the department has no head. Weekly-keyed and+ coalesced (see ``propose_via_alert``) so re-runs refresh an open card+ and never re-mint one the head already handled. Returns cards filed."""+ if not suggested:+ return 0+ from openexecutive.departments.authority import propose_via_alert++ year, week, _ = ctx.now.isocalendar()+ suffix = f"{year}-W{week:02d}"+ filed = 0+ for slug, items in suggested.items():+ ref = ctx.departments.get(slug)+ if ref is None:+ continue+ person_id = ref.head_person_id+ if person_id is None:+ try:+ from openexecutive.people.registry import get_principal++ principal = get_principal()+ person_id = int(principal.id) if principal and principal.id is not None else None+ except Exception:+ logger.debug("watch_policy: principal lookup failed", exc_info=True)+ if person_id is None:+ continue+ lines = [+ f"- {i.slug} ({i.signal_type}) — {i.notes or i.target}"[:200]+ for i in items[:DEPARTMENT_CARD_MAX_LINES]+ ]+ body = (+ f"The Executive suggested these sources for {ref.title} to monitor and "+ "is not sure enough to add them on its own. Approve or decline them "+ "on the Watch list page.\n\n" + "\n".join(lines)+ )+ try:+ alert_id = propose_via_alert(+ slug, person_id,+ summary=f"Watch suggestions for {ref.title}",+ body=body,+ suggested_action="Review the suggestions on /watchlist",+ extra_tags=["watchlist"],+ external_id_suffix=suffix,+ )+ except Exception:+ logger.exception("watch_policy: department card failed for %s", slug)+ continue+ if alert_id:+ filed += 1+ return filed++def _summary(proposal: WatchProposal, outcome: str, detail: str) -> dict[str, Any]:return {"tool": "propose_watch",@@ -893,7 +1132,11 @@ def _auto_disable(now: datetime, db_path: Path | None) -> int:def _nudge_if_piled_up(now: datetime, db_path: Path | None) -> int:- pending = ms.list_pending_suggestions(db_path=db_path)+ # Department-routed suggestions were put in front of their head when+ # they were filed; the pile-up nudge is for the principal's own.+ pending = [+ i for i in ms.list_pending_suggestions(db_path=db_path) if not i.route_to_department+ ]if len(pending) < _NUDGE_MIN_PENDING:return 0created = _parse(pending[0].created_at)@@ -950,18 +1193,26 @@ __all__ = ["TIER_REJECT","TIER_SUGGEST","STRONG_GROUNDING_KINDS",+ "DECISION_LIMIT",+ "DECISION_LOOKBACK_DAYS","Decision",+ "DepartmentRef","PolicyContext","PolicySettings",+ "VocabEntry","WatchProposal","apply_proposals","classify",+ "department_refs","entity_declined","grounding_vocabulary","match_entity",+ "match_vocab",+ "named_in_decision","policy_stamp_of","priority_terms","quiet_defaults",+ "recent_decisions","record_outcome_for","sweep",]diff --git a/packages/core/openexecutive/workflows/executive_research.py b/packages/core/openexecutive/workflows/executive_research.pyindex 5a690575..540369a0 100644--- a/packages/core/openexecutive/workflows/executive_research.py+++ b/packages/core/openexecutive/workflows/executive_research.py@@ -242,7 +242,8 @@ def _build_watchlist_system(max_direct: int, max_suggest: int) -> str:"## WHAT BELONGS ON THE WATCHLIST\n\n""An ongoing, externally-observable source tied to a NAMED company ""entity — a competitor, vendor, ticker or initiative from the company "- "context — that we'd want flagged when it next changes: a public "+ "context, or an entity a department watches or a recent decision "+ "names — that we'd want flagged when it next changes: a public ""competitor's ticker or filings, a vendor's status page, a competitor's ""own blog / changelog feed. A one-off event already fully known is NOT ""watchlist material; the *ongoing source* behind it might be. "@@ -402,11 +403,26 @@ class ExecutiveResearchWorkflow(Workflow):logger.exception("research: list_watchlist failed")existing_watchlist = []+ # Departments (watched entities, scope, goals) and recent decisions+ # are current company intent the static profile lacks; both feed+ # the watch policy's grounding and routing.+ try:+ from openexecutive.departments.store import list_departments++ departments = list(list_departments())+ except Exception:+ logger.exception("research: list_departments failed")+ departments = []+ from openexecutive.monitoring.research.watch_policy import recent_decisions++ decisions = recent_decisions()+research_context = _render_research_context(profile=profile,initiatives=initiatives,existing_watchlist=existing_watchlist,note=inputs.note,+ decisions=decisions,)yield WorkflowEvent(@@ -415,7 +431,8 @@ class ExecutiveResearchWorkflow(Workflow):summary=(f"profile_loaded={profile is not None and not profile.is_empty()} "f"initiatives={len(initiatives)} "- f"existing_watchlist={len(existing_watchlist)}"+ f"existing_watchlist={len(existing_watchlist)} "+ f"departments={len(departments)} decisions={len(decisions)}"),)@@ -591,6 +608,7 @@ class ExecutiveResearchWorkflow(Workflow):watchlist_calls = await _watchlist_analysis_loop(deduped, existing_watchlist,profile=profile, initiatives=initiatives,+ departments=departments, decisions=decisions,)except Exception:logger.exception("research: watchlist-analysis pass failed")@@ -897,6 +915,8 @@ async def _watchlist_analysis_loop(*,profile: Any = None,initiatives: list[Any] | None = None,+ departments: list[Any] | None = None,+ decisions: list[Any] | None = None,) -> list[dict[str, Any]]:"""Dedicated forward-looking pass: the model PROPOSES sources to monitorvia ``propose_watch``; ``watch_policy.apply_proposals`` then decides,@@ -951,6 +971,7 @@ async def _watchlist_analysis_loop(findings, existing_watchlist,declines=declines, outcome_counts=outcome_counts,specialist_counts=specialist_counts,+ departments=departments,),},]@@ -1035,12 +1056,14 @@ async def _watchlist_analysis_loop(ctx = watch_policy.PolicyContext(vocabulary=watch_policy.grounding_vocabulary(- profile, list(initiatives or []), list(existing_watchlist),+ profile, list(initiatives or []), list(existing_watchlist), list(departments or []),),priority_terms=watch_policy.priority_terms(profile),existing=list(existing_watchlist),outcome_counts=outcome_counts,settings=policy_settings,+ departments=watch_policy.department_refs(departments),+ recent_decisions=list(decisions or []),)decided = watch_policy.apply_proposals(proposals, findings, ctx)return refused + decided@@ -1088,6 +1111,7 @@ def _render_research_context(initiatives: list[Any],existing_watchlist: list[Any],note: str,+ decisions: list[Any] | None = None,) -> str:"""Build the user-turn block passed to every specialist call."""from datetime import UTC, datetime, timedelta@@ -1146,6 +1170,22 @@ def _render_research_context(parts.append(f"- {slug} [{signal_type}] target={target}")parts.append("")+ if decisions:+ # What the company recently decided is the freshest statement of+ # what matters; the static profile lags it by design.+ parts.append("RECENT DECISIONS:")+ for d in decisions[:10]:+ summary = str(getattr(d, "summary", "") or "").strip()+ if not summary:+ continue+ when = str(getattr(d, "timestamp", "") or "")[:10]+ dept = str(getattr(d, "department", "") or "")+ line = f"- {when}" if when else "-"+ if dept:+ line += f" [{dept}]"+ parts.append(f"{line}: {summary[:160]}")+ parts.append("")+parts.append("Research within your domain and emit findings via the ""`emit_research_findings` tool. Use web_search to FIND and "@@ -1237,10 +1277,12 @@ def _render_watchlist_turn(declines: list[Any] | None = None,outcome_counts: dict[tuple[str, str], dict[str, int]] | None = None,specialist_counts: dict[str, dict[str, int]] | None = None,+ departments: list[Any] | None = None,) -> str:"""User-turn for the watchlist-analysis pass: the findings (with URLs),the current watchlist with its trust record, targets the principal- declined, and how the policy's past guesses turned out."""+ declined, what each department has asked to watch, and how the+ policy's past guesses turned out."""parts: list[str] = ["FINDINGS FROM THIS RESEARCH RUN:\n"]for i, f in enumerate(findings, start=1):block = (@@ -1312,6 +1354,20 @@ def _render_watchlist_turn(parts.append("\nHOW PAST PROPOSALS TURNED OUT:")parts.extend(history_lines[:12])+ interest_lines: list[str] = []+ for state in departments or []:+ config = getattr(state, "config", None)+ slug = getattr(config, "slug", "")+ entities = [str(e) for e in (getattr(config, "watched_entities", None) or []) if str(e).strip()]+ if slug and entities:+ interest_lines.append(f"- {slug}: {', '.join(entities[:20])}")+ if interest_lines:+ parts.append(+ "\nDEPARTMENT WATCH INTERESTS (entities a department asked to have "+ "watched — ground a proposal about one in that entity):"+ )+ parts.extend(interest_lines[:20])+parts.append("\nDecide which ongoing sources are worth monitoring and call ""propose_watch for each — real ticker/feed targets only, preferring "diff --git a/packages/core/tests/unit/test_authority_gate.py b/packages/core/tests/unit/test_authority_gate.pyindex c8fab2b4..c6eed3b5 100644--- a/packages/core/tests/unit/test_authority_gate.py+++ b/packages/core/tests/unit/test_authority_gate.py@@ -251,3 +251,29 @@ def test_propose_via_alert_dedup() -> None:assert first is not Nonesecond = propose_via_alert("finance", cfo_id, "Same summary", "body")assert second is None # duplicate suppressed+++def test_propose_via_alert_suffix_coalesces_then_reissues() -> None:+ """With an external_id_suffix the card is recurring: an open one is+ refreshed in place, an acknowledged one is left alone until the suffix+ changes."""+ from openexecutive.alerts import store as alert_store++ _set_dept_level("finance", AuthorityLevel.PROPOSE_ONLY)+ cfo_id = people_store.upsert_person(full_name="Sarah")++ first = propose_via_alert("finance", cfo_id, "Watch suggestions", "body one",+ external_id_suffix="2026-W37")+ assert first is not None+ # Open card: refreshed, no new row.+ assert propose_via_alert("finance", cfo_id, "Watch suggestions", "body two",+ external_id_suffix="2026-W37") is None+ refreshed = alert_store.get_alert(first)+ assert refreshed is not None and refreshed.body == "body two" and refreshed.occurrence_count == 2+ # Acknowledged: same week stays quiet, next week mints a new card.+ alert_store.set_status(first, "acknowledged")+ assert propose_via_alert("finance", cfo_id, "Watch suggestions", "body three",+ external_id_suffix="2026-W37") is None+ nxt = propose_via_alert("finance", cfo_id, "Watch suggestions", "body four",+ external_id_suffix="2026-W38")+ assert nxt is not None and nxt != firstdiff --git a/packages/core/tests/unit/test_departments_route.py b/packages/core/tests/unit/test_departments_route.pyindex 9420c3cf..5b8b5446 100644--- a/packages/core/tests/unit/test_departments_route.py+++ b/packages/core/tests/unit/test_departments_route.py@@ -81,6 +81,20 @@ def test_patch_rejects_invalid_authority(client: TestClient) -> None:assert resp.status_code == 422+def test_patch_watched_entities_cleans_and_validates(client: TestClient) -> None:+ resp = client.patch(+ "/departments/finance",+ json={"watched_entities": [" Brex ", "brex", "", "Stripe Inc"]},+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["config"]["watched_entities"] == ["Brex", "Stripe Inc"]+ # Omitting the field leaves it alone; sending [] clears it.+ assert client.patch("/departments/finance", json={"headcount": 2}).json()["config"]["watched_entities"] == ["Brex", "Stripe Inc"]+ assert client.patch("/departments/finance", json={"watched_entities": []}).json()["config"]["watched_entities"] == []+ assert client.patch("/departments/finance", json={"watched_entities": ["x" * 129]}).status_code == 422+ assert client.patch("/departments/finance", json={"watched_entities": [f"e{i}" for i in range(51)]}).status_code == 422++def test_patch_unknown_department(client: TestClient) -> None:resp = client.patch("/departments/nope", json={"headcount": 1})assert resp.status_code == 404diff --git a/packages/core/tests/unit/test_departments_store.py b/packages/core/tests/unit/test_departments_store.pyindex 25a443ee..070321de 100644--- a/packages/core/tests/unit/test_departments_store.py+++ b/packages/core/tests/unit/test_departments_store.py@@ -163,6 +163,31 @@ def test_update_department_partial(db: Path) -> None:assert state.budget_usd == 12_500.0+def test_watched_entities_round_trip_and_migration(db: Path) -> None:+ import sqlite3++ store.seed_default_departments()+ state = store.get_department("finance")+ assert state is not None and state.config.watched_entities == []+ assert store.update_department("finance", watched_entities=["Brex", "Stripe"]) is True+ state = store.get_department("finance")+ assert state is not None and state.config.watched_entities == ["Brex", "Stripe"]+ # Other fields untouched; an update without the field leaves it alone.+ store.update_department("finance", headcount=3)+ state = store.get_department("finance")+ assert state is not None and state.config.watched_entities == ["Brex", "Stripe"]+ assert store.update_department("finance", watched_entities=[]) is True+ state = store.get_department("finance")+ assert state is not None and state.config.watched_entities == []+ # Re-running the migration on a migrated DB is a no-op, and a corrupt+ # column value reads back as an empty list rather than failing the read.+ store.initialize_db()+ with sqlite3.connect(db) as conn:+ conn.execute("UPDATE departments SET watched_entities_json = 'nope' WHERE slug = 'finance'")+ state = store.get_department("finance")+ assert state is not None and state.config.watched_entities == []++def test_get_department_returns_none_for_unknown(db: Path) -> None:store.seed_default_departments()assert store.get_department("does-not-exist") is Nonediff --git a/packages/core/tests/unit/test_executive_research_scheduler.py b/packages/core/tests/unit/test_executive_research_scheduler.pyindex e71e044e..f8b370e1 100644--- a/packages/core/tests/unit/test_executive_research_scheduler.py+++ b/packages/core/tests/unit/test_executive_research_scheduler.py@@ -25,6 +25,10 @@ def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:monitoring_store.initialize_db(db_path)monkeypatch.setattr("openexecutive.people.store.DB_PATH", db_path)initialize_people_db(db_path)+ monkeypatch.setattr("openexecutive.departments.store.DB_PATH", db_path)+ from openexecutive.departments import store as dept_store++ dept_store.initialize_db(db_path)audit_db = AuditLogger(db_path=db_path)audit_db.initialize_db()set_audit_logger(audit_db)@@ -67,6 +71,39 @@ def test_state_hash_ignores_suggestions_and_disabled_rows(db: Path) -> None:assert research_scheduler.compute_research_state_hash(db_path=db) == before+def test_state_hash_tracks_department_watch_interests(db: Path) -> None:+ from openexecutive.departments import store as dept_store++ dept_store.seed_default_departments(db)+ before = research_scheduler.compute_research_state_hash(db_path=db)+ dept_store.update_department("finance", watched_entities=["Brex"], db_path=db)+ after = research_scheduler.compute_research_state_hash(db_path=db)+ assert before != after+++def test_state_hash_moves_only_for_decisions_that_name_known_entities(+ db: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.departments import store as dept_store+ from openexecutive.memory.company_profile import CompanyProfile+ from openexecutive.memory.episodic import store_decision++ profile = CompanyProfile.model_validate({"name": "Sente Labs", "vendors": ["Stripe"]})+ monkeypatch.setattr(+ "openexecutive.onboarding.profile_builder.load_or_create_profile", lambda: profile,+ )+ dept_store.seed_default_departments(db)+ dept_store.update_department("finance", watched_entities=["Brex"], db_path=db)+ before = research_scheduler.compute_research_state_hash(db_path=db)+ store_decision("ops", "Hire two SDRs in Q4", db_path=db)+ assert research_scheduler.compute_research_state_hash(db_path=db) == before+ store_decision("finance", "Evaluate Brex for expense cards", db_path=db)+ after = research_scheduler.compute_research_state_hash(db_path=db)+ assert after != before+ store_decision("finance", "Move Stripe to annual billing", db_path=db)+ assert research_scheduler.compute_research_state_hash(db_path=db) not in (before, after)++def test_state_hash_changes_when_initiative_added(db: Path) -> None:from openexecutive.memory.episodic import store_initiativediff --git a/packages/core/tests/unit/test_executive_research_watchlist.py b/packages/core/tests/unit/test_executive_research_watchlist.pyindex bd89a72e..3e052cf0 100644--- a/packages/core/tests/unit/test_executive_research_watchlist.py+++ b/packages/core/tests/unit/test_executive_research_watchlist.py@@ -43,10 +43,23 @@ def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:db_path = tmp_path / "test_research.db"monkeypatch.setattr("openexecutive.memory.episodic.DB_PATH", db_path)monkeypatch.setattr("openexecutive.alerts.store.DB_PATH", db_path)+ monkeypatch.setattr("openexecutive.departments.store.DB_PATH", db_path)+ monkeypatch.setattr("openexecutive.people.store.DB_PATH", db_path)initialize_episodic_db(db_path)initialize_alerts_db(db_path)monitoring_store.initialize_db(db_path)- return db_path+ from openexecutive.departments import registry as dept_registry+ from openexecutive.departments import store as dept_store+ from openexecutive.people import registry as people_registry+ from openexecutive.people import store as people_store++ dept_store.initialize_db(db_path)+ people_store.initialize_db(db_path)+ dept_registry.invalidate()+ people_registry.invalidate()+ yield db_path+ dept_registry.invalidate()+ people_registry.invalidate()def _finding(title: str = "TSLA: Tesla cut prices", url: str = "https://example.com/feed.xml") -> ResearchFinding:@@ -238,6 +251,59 @@ def test_watchlist_turn_renders_trust_declines_and_history(db: Path) -> None:assert "stock watches grounded in a competitor: 4 approved / 1 declined or dropped" in textassert "proposals from cso: 2 approved / 1 declined or dropped" in textassert "propose_watch" in text+ assert "DEPARTMENT WATCH INTERESTS" not in text+++def test_watchlist_turn_lists_department_interests() -> None:+ from types import SimpleNamespace++ finance = SimpleNamespace(config=SimpleNamespace(slug="finance", watched_entities=["Brex", "Stripe"]))+ empty = SimpleNamespace(config=SimpleNamespace(slug="ops", watched_entities=[]))+ text = er._render_watchlist_turn([_finding()], [], departments=[finance, empty])+ assert "DEPARTMENT WATCH INTERESTS" in text and "- finance: Brex, Stripe" in text+ assert "- ops" not in text+++def test_research_context_renders_recent_decisions() -> None:+ from types import SimpleNamespace++ decisions = [+ SimpleNamespace(summary="Evaluate Brex for expense cards", department="finance",+ timestamp="2026-09-01T10:00:00+00:00"),+ SimpleNamespace(summary="", department="", timestamp=""),+ ]+ text = er._render_research_context(+ profile=_profile(), initiatives=[], existing_watchlist=[], note="", decisions=decisions,+ )+ assert "RECENT DECISIONS:" in text+ assert "- 2026-09-01 [finance]: Evaluate Brex for expense cards" in text+ without = er._render_research_context(profile=_profile(), initiatives=[], existing_watchlist=[], note="")+ assert "RECENT DECISIONS" not in without+++async def test_watchlist_pass_routes_department_grounded_watch(+ db: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from openexecutive.departments import store as dept_store+ from openexecutive.people import store as people_store++ dept_store.seed_default_departments(db)+ head = people_store.upsert_person(full_name="Sarah", department_slugs=["finance"])+ dept_store.update_department("finance", watched_entities=["Brex"], head_person_id=head, db_path=db)+ _stub_provider(monkeypatch, [+ _resp([_propose("vendor-brex", "vendor_status", "https://status.brex.com", entity="Brex")]),+ _resp([]),+ ])+ finding = _finding(title="Brex outage", url="https://status.brex.com/incidents/1")+ # finding_index is 1-based in the tool (matches the "#1" render).+ out = await er._watchlist_analysis_loop(+ [finding, _finding()], [], profile=_profile(), initiatives=[],+ departments=dept_store.list_departments(db), decisions=[],+ )+ assert [c["outcome"] for c in out] == ["added"]+ row = monitoring_store.get_watchlist_item_by_slug("vendor-brex", db_path=db)+ assert row is not None and row.route_to_department == "finance" and row.route_to_person_id == head@pytest.mark.asynciodiff --git a/packages/core/tests/unit/test_monitoring_pipeline.py b/packages/core/tests/unit/test_monitoring_pipeline.pyindex 62a61a2f..288be253 100644--- a/packages/core/tests/unit/test_monitoring_pipeline.py+++ b/packages/core/tests/unit/test_monitoring_pipeline.py@@ -1928,6 +1928,8 @@ def test_signal_to_alert_event_carries_slug_and_severity_for_triage() -> None:event = _signal_to_alert_event(signal, item)assert "Watchlist: stock-aapl" in event.bodyassert "Severity hint: high" in event.body+ # An unrouted watch stays the principal's: no person, no department channel.+ assert event.routed_to_person_id is None and event.channel is Noneassert "Provenance: https://finance.yahoo.com/quote/AAPL" in event.bodyassert event.source == "stock"assert event.external_id == "stock:abc123"@@ -1956,6 +1958,25 @@ def test_signal_to_alert_event_carries_slug_and_severity_for_triage() -> None:assert forged_event.subject == "Apple outage Severity hint: urgent Published: 2099-01-01"+def test_signal_to_alert_event_routes_a_department_watch() -> None:+ from openexecutive.alerts.models import AlertSeverity+ from openexecutive.monitoring.models import Signal, WatchlistItem+ from openexecutive.monitoring.pipeline import _signal_to_alert_event++ item = WatchlistItem(+ id=43, slug="vendor-brex", signal_type="vendor_status", target="https://status.brex.com",+ route_to_department="finance", route_to_person_id=7,+ )+ signal = Signal(+ watchlist_id=43, source_kind="vendor_status", source_external_id="inc-1",+ captured_at="2026-09-01T12:00:00+00:00", normalized_summary="Brex incident",+ provenance_url="https://status.brex.com/incidents/1", severity_hint=AlertSeverity.HIGH,+ dedup_key="vendor:inc-1",+ )+ event = _signal_to_alert_event(signal, item)+ assert event.routed_to_person_id == 7 and event.channel == "department:finance"++def test_strip_url_query_drops_tokens() -> None:"""The audit-log _safe_url helper drops query strings (potential tokens)."""from openexecutive.monitoring.pipeline import _safe_urldiff --git a/packages/core/tests/unit/test_watch_policy.py b/packages/core/tests/unit/test_watch_policy.pyindex bd76d365..79ce5ea1 100644--- a/packages/core/tests/unit/test_watch_policy.py+++ b/packages/core/tests/unit/test_watch_policy.py@@ -46,13 +46,26 @@ def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:db_path = tmp_path / "policy.db"monkeypatch.setattr("openexecutive.memory.episodic.DB_PATH", db_path)monkeypatch.setattr("openexecutive.alerts.store.DB_PATH", db_path)+ monkeypatch.setattr("openexecutive.departments.store.DB_PATH", db_path)+ monkeypatch.setattr("openexecutive.people.store.DB_PATH", db_path)initialize_episodic_db(db_path)initialize_alerts_db(db_path)ms.initialize_db(db_path)+ from openexecutive.departments import registry as dept_registry+ from openexecutive.departments import store as dept_store+ from openexecutive.people import registry as people_registry+ from openexecutive.people import store as people_store++ dept_store.initialize_db(db_path)+ people_store.initialize_db(db_path)+ dept_registry.invalidate()+ people_registry.invalidate()audit = AuditLogger(db_path=db_path)audit.initialize_db()set_audit_logger(audit)- return db_path+ yield db_path+ dept_registry.invalidate()+ people_registry.invalidate()def _profile() -> CompanyProfile:@@ -114,12 +127,13 @@ def test_vocabulary_covers_profile_initiatives_and_watch_labels(db: Path) -> Nonvocab = wp.grounding_vocabulary(_profile(), [SimpleNamespace(title="Launch Helios API")], ms.list_watchlist(db_path=db),)- assert vocab["sente labs"] == wp.KIND_COMPANY- assert vocab["acme corp"] == wp.KIND_COMPETITOR- assert vocab["stripe"] == wp.KIND_VENDOR- assert vocab["acme"] == wp.KIND_TICKER- assert vocab["launch helios api"] == wp.KIND_INITIATIVE- assert vocab["hubspot"] == wp.KIND_WATCH and vocab["hubs"] == wp.KIND_WATCH+ assert vocab["sente labs"].kind == wp.KIND_COMPANY+ assert vocab["acme corp"].kind == wp.KIND_COMPETITOR+ assert vocab["stripe"].kind == wp.KIND_VENDOR+ assert vocab["acme"].kind == wp.KIND_TICKER+ assert vocab["launch helios api"].kind == wp.KIND_INITIATIVE+ assert vocab["hubspot"].kind == wp.KIND_WATCH and vocab["hubs"].kind == wp.KIND_WATCH+ assert all(entry.department == "" for entry in vocab.values())def test_match_entity_is_token_based_and_prefers_company_data() -> None:@@ -269,7 +283,7 @@ def test_own_source_uses_the_site_label_only() -> None:def test_vocabulary_prefers_the_strongest_kind() -> None:profile = CompanyProfile.model_validate({"name": "Acme", "vendors": ["Acme"], "tickers": ["ACME"]})vocab = wp.grounding_vocabulary(profile, [SimpleNamespace(title="Acme")], [])- assert vocab["acme"] == wp.KIND_COMPANY+ assert vocab["acme"].kind == wp.KIND_COMPANYdef test_history_adjusts_only_with_enough_samples() -> None:@@ -575,7 +589,7 @@ def test_vocabulary_from_url_targets_uses_the_site_label(db: Path) -> None:ms.insert_watchlist_item(slug="vendor-stripe", signal_type="vendor_status",target="https://status.stripe.com/history.atom", db_path=db)vocab = wp.grounding_vocabulary(CompanyProfile(name="X"), [], ms.list_watchlist(db_path=db))- assert vocab.get("stripe") == wp.KIND_WATCH+ assert vocab["stripe"].kind == wp.KIND_WATCHassert not any(t.startswith("https") for t in vocab)assert wp.match_entity("Status Labs", vocab) is None@@ -641,3 +655,203 @@ def test_insert_failure_is_reported_without_exception_text(db: Path, monkeypatchout = wp.apply_proposals([_proposal()], [_finding()], _ctx(), db_path=db)assert out[0]["outcome"] == "rejected" and "see server log" in out[0]["result_preview"]assert "/secret/path" not in out[0]["result_preview"]+++# --------------------------------------------------------------------- #+# Departments + episodic decisions+# --------------------------------------------------------------------- #+++def _department(slug: str, title: str, *, watched: list[str] | None = None,+ scope: list[str] | None = None, head: int | None = None,+ goals: list[str] | None = None) -> SimpleNamespace:+ return SimpleNamespace(+ config=SimpleNamespace(+ slug=slug, title=title, head_person_id=head,+ watched_entities=list(watched or []),+ charter=SimpleNamespace(scope=list(scope or [])),+ ),+ goals=[SimpleNamespace(key_result=g) for g in (goals or [])],+ )+++def _finance(head: int | None = 7) -> SimpleNamespace:+ return _department(+ "finance", "Finance", watched=["Brex"], scope=["Expense card programs"],+ goals=["Close the books in 5 days"], head=head,+ )+++def _dept_ctx(*departments: Any, existing: list[Any] | None = None, **kw: Any) -> wp.PolicyContext:+ profile = _profile()+ departments = departments or (_finance(),)+ existing = existing or []+ return wp.PolicyContext(+ vocabulary=wp.grounding_vocabulary(profile, [], existing, list(departments)),+ priority_terms=wp.priority_terms(profile),+ existing=existing,+ departments=wp.department_refs(list(departments)),+ **kw,+ )+++def _brex_finding(**kw: Any) -> ResearchFinding:+ return _finding(+ title="Brex outage", summary="Brex card authorizations failed for 2h on 2026-09-01.",+ relevant_urls=["https://status.brex.com/incidents/1"], source_specialist="cfo", **kw,+ )+++def _brex_proposal(**kw: Any) -> wp.WatchProposal:+ return _proposal(+ slug="vendor-brex", signal_type="vendor_status", target="https://status.brex.com",+ grounding_entity="Brex", rationale="Finance is on Brex cards", **kw,+ )+++def test_department_vocabulary_kinds_and_department_merge() -> None:+ finance = _department("finance", "Finance", watched=["Brex", "Acme Corp"],+ scope=["Expense card programs"], goals=["Close the books in 5 days"])+ vocab = wp.grounding_vocabulary(_profile(), [], [], [finance])+ assert vocab["brex"] == wp.VocabEntry(wp.KIND_DEPARTMENT_ENTITY, "finance")+ assert vocab["expense card programs"] == wp.VocabEntry(wp.KIND_DEPARTMENT_SCOPE, "finance")+ assert vocab["close the books in 5 days"].kind == wp.KIND_DEPARTMENT_SCOPE+ # A profile competitor that Finance also lists keeps the stronger kind+ # and still routes to Finance.+ assert vocab["acme corp"] == wp.VocabEntry(wp.KIND_COMPETITOR, "finance")+ # Legacy plain-kind dicts still match.+ assert wp.match_entity("Brex Inc", vocab) == ("brex", wp.KIND_DEPARTMENT_ENTITY)+ assert wp.match_entity("Brex", {"brex": wp.KIND_VENDOR}) == ("brex", wp.KIND_VENDOR)+ assert wp.department_refs([_finance(head=7)]) == {"finance": wp.DepartmentRef("Finance", 7)}+++def test_department_watched_entity_grounds_a_direct_add_and_routes(db: Path) -> None:+ d = wp.classify(_brex_proposal(), _brex_finding(), _dept_ctx())+ assert d.tier == wp.TIER_DIRECT and d.grounding_kind == wp.KIND_DEPARTMENT_ENTITY+ assert d.department == "finance" and "Finance watched entity" in d.reasons[0]+ out = wp.apply_proposals([_brex_proposal()], [_brex_finding()], _dept_ctx(), db_path=db)+ assert [o["outcome"] for o in out] == ["added"]+ row = ms.get_watchlist_item_by_slug("vendor-brex", db_path=db)+ assert row is not None and row.mode == MODE_ACTIVE+ assert row.route_to_department == "finance" and row.route_to_person_id == 7+ assert wp.policy_stamp_of(row)["department"] == "finance"+++def test_department_scope_grounding_is_suggestion_only(db: Path) -> None:+ p = _proposal(slug="rss-expense", signal_type="rss", target="https://expensecards.example/feed",+ grounding_entity="Expense card programs")+ f = _finding(title="Expense card programs shift", summary="New expense card programs launched.",+ relevant_urls=["https://expensecards.example/feed"], verification="confirmed",+ source_specialist="cfo,coo")+ d = wp.classify(p, f, _dept_ctx())+ assert d.tier == wp.TIER_SUGGEST and d.department == "finance"+ assert d.grounding_kind == wp.KIND_DEPARTMENT_SCOPE and "Finance scope item" in d.reasons[0]+ # Even on its own source a scope item cannot be direct.+ own = _proposal(slug="rss-programs", signal_type="rss", target="https://programs.example/feed",+ grounding_entity="Expense card programs")+ own_f = _finding(title="programs", summary="s", relevant_urls=["https://programs.example/feed"],+ verification="confirmed", source_specialist="cfo,coo")+ own_d = wp.classify(own, own_f, _dept_ctx())+ assert own_d.tier == wp.TIER_SUGGEST and any("grounded only in a department_scope" in r for r in own_d.reasons)+ out = wp.apply_proposals([p], [f], _dept_ctx(), db_path=db)+ assert out[0]["outcome"] == "suggested"+ row = ms.get_watchlist_item_by_slug("rss-expense", db_path=db)+ assert row is not None and row.mode == MODE_DRY_RUN and row.route_to_department == "finance"+++def test_recent_decision_adds_a_point_and_a_routing_hint() -> None:+ decided = SimpleNamespace(summary="Evaluate Stripe as the EU payments vendor",+ department="finance", timestamp="2026-09-01T00:00:00+00:00")+ p = _proposal(slug="vendor-stripe", signal_type="vendor_status", target="https://status.stripe.com",+ grounding_entity="Stripe")+ f = _finding(title="Stripe incident", summary="Stripe API errors on 2026-09-01.",+ relevant_urls=["https://status.stripe.com/"], confidence="medium")+ base = wp.classify(p, f, _dept_ctx())+ with_decision = wp.classify(p, f, _dept_ctx(recent_decisions=[decided]))+ assert with_decision.score == base.score + 1 and "named in a recent decision" in with_decision.reasons+ # Stripe is a profile vendor with no department; the decision's is used.+ assert base.department == "" and with_decision.department == "finance"+ # A decision for an unknown department is not a routing hint, and one+ # that names nothing relevant scores nothing.+ other = SimpleNamespace(summary="Move Stripe to annual billing", department="ops", timestamp="")+ assert wp.classify(p, f, _dept_ctx(recent_decisions=[other])).department == ""+ unrelated = SimpleNamespace(summary="Hire two SDRs in Q4", department="finance", timestamp="")+ assert wp.classify(p, f, _dept_ctx(recent_decisions=[unrelated])).score == base.score+ assert wp.named_in_decision("acme corp", SimpleNamespace(summary="Acme Corp pricing review"))+ assert not wp.named_in_decision("acme corp", SimpleNamespace(summary="The corp retreat"))+++def test_recent_decisions_apply_the_lookback(db: Path) -> None:+ from openexecutive.memory.episodic import store_decision++ store_decision("finance", "Evaluate Brex for expense cards", db_path=db)+ store_decision("ops", "Retire the old CRM", db_path=db)+ import sqlite3++ with sqlite3.connect(db) as conn:+ conn.execute("UPDATE decisions SET timestamp = ? WHERE summary = 'Retire the old CRM'",+ ((datetime.now(UTC) - timedelta(days=120)).isoformat(),))+ rows = wp.recent_decisions(db_path=db)+ assert [r.summary for r in rows] == ["Evaluate Brex for expense cards"]+++def test_department_head_gets_one_card_per_run_coalesced_weekly(db: Path) -> None:+ from openexecutive.alerts.store import list_alerts, set_status+ from openexecutive.people import store as people_store++ head = people_store.upsert_person(full_name="Sarah", department_slugs=["finance"])+ finance = _finance(head=head)++ def _run(slug: str, now: datetime) -> None:+ p = _proposal(slug=slug, signal_type="rss", target=f"https://{slug}.example/feed",+ grounding_entity="Expense card programs")+ f = _finding(title="Expense card programs", summary="expense card programs news",+ relevant_urls=[f"https://{slug}.example/feed"])+ wp.apply_proposals([p], [f], _dept_ctx(finance, now=now), db_path=db)++ now = datetime(2026, 9, 8, 9, tzinfo=UTC)+ _run("rss-a", now)+ cards = [a for a in list_alerts(limit=20, db_path=db) if a.source == "authority_gate"]+ assert len(cards) == 1 and cards[0].routed_to_person_id == head+ assert cards[0].headline == "Watch suggestions for Finance" and "rss-a" in cards[0].body+ assert "department:finance" in cards[0].topic_tags and "watchlist" in cards[0].topic_tags+ # Same week again: the open card is refreshed, not duplicated.+ _run("rss-b", now + timedelta(days=1))+ cards = [a for a in list_alerts(limit=20, db_path=db) if a.source == "authority_gate"]+ assert len(cards) == 1 and "rss-b" in cards[0].body+ # Once the head acted on it, nothing more this week ...+ set_status(cards[0].id, "acknowledged", db_path=db)+ _run("rss-c", now + timedelta(days=2))+ assert len([a for a in list_alerts(limit=20, db_path=db) if a.source == "authority_gate"]) == 1+ # ... and a fresh card next week.+ _run("rss-d", now + timedelta(days=7))+ assert len([a for a in list_alerts(limit=20, db_path=db) if a.source == "authority_gate"]) == 2+++def test_department_card_falls_back_to_the_principal(db: Path) -> None:+ from openexecutive.alerts.store import list_alerts+ from openexecutive.people import store as people_store++ principal = people_store.upsert_person(full_name="Jo", is_principal=True)+ p = _proposal(slug="rss-x", signal_type="rss", target="https://x.example/feed",+ grounding_entity="Expense card programs")+ f = _finding(title="Expense card programs", summary="s", relevant_urls=["https://x.example/feed"])+ wp.apply_proposals([p], [f], _dept_ctx(_finance(head=None)), db_path=db)+ cards = [a for a in list_alerts(limit=20, db_path=db) if a.source == "authority_gate"]+ assert len(cards) == 1 and cards[0].routed_to_person_id == principal+ row = ms.get_watchlist_item_by_slug("rss-x", db_path=db)+ assert row is not None and row.route_to_department == "finance" and row.route_to_person_id is None+++def test_nudge_counts_only_the_principals_suggestions(db: Path) -> None:+ from openexecutive.alerts.store import list_alerts++ for i in range(3):+ ms.insert_watchlist_item(+ slug=f"rss-d{i}", signal_type="rss", target=f"https://d{i}.com/feed",+ mode=MODE_DRY_RUN, origin=ORIGIN_RESEARCH_PROPOSED, route_to_department="finance",+ db_path=db,+ )+ _backdate(db, f"rss-d{i}", 8)+ assert wp.sweep(datetime.now(UTC), db_path=db)["nudged"] == 0+ assert not [a for a in list_alerts(limit=10, db_path=db) if a.source == wp.NUDGE_ALERT_SOURCE]diff --git a/packages/ui/src/app/departments/[slug]/page.tsx b/packages/ui/src/app/departments/[slug]/page.tsxindex dce836c7..debd20e8 100644--- a/packages/ui/src/app/departments/[slug]/page.tsx+++ b/packages/ui/src/app/departments/[slug]/page.tsx@@ -445,6 +445,8 @@ export default function DepartmentDetailPage() {slack_channel_id: "",discord_channel_id: "",telegram_chat_id: "",+ // One entity per line in the textarea; split + trimmed on save.+ watched_entities: "",});const [savingSettings, setSavingSettings] = useState(false);const [settingsErr, setSettingsErr] = useState<string | null>(null);@@ -503,6 +505,7 @@ export default function DepartmentDetailPage() {slack_channel_id: d.config.slack_channel_id ?? "",discord_channel_id: d.config.discord_channel_id ?? "",telegram_chat_id: d.config.telegram_chat_id ?? "",+ watched_entities: (d.config.watched_entities ?? []).join("\n"),});}if (isInitial && d.config.head_person_id != null) {@@ -572,6 +575,11 @@ export default function DepartmentDetailPage() {slack_channel_id: settingsForm.slack_channel_id.trim() || null,discord_channel_id: settingsForm.discord_channel_id.trim() || null,telegram_chat_id: settingsForm.telegram_chat_id.trim() || null,+ // Always sent: an emptied textarea clears the list.+ watched_entities: settingsForm.watched_entities+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0),});setDept(updated);setEditingSettings(false);@@ -621,6 +629,7 @@ export default function DepartmentDetailPage() {slack_channel_id: dept.config.slack_channel_id ?? "",discord_channel_id: dept.config.discord_channel_id ?? "",telegram_chat_id: dept.config.telegram_chat_id ?? "",+ watched_entities: (dept.config.watched_entities ?? []).join("\n"),});setSettingsErr(null);}@@ -846,6 +855,28 @@ export default function DepartmentDetailPage() {</div></section>+ {/* Card 5: Watched entities — strong grounding for the research watch policy */}+ <section className="rounded-xl border border-line bg-surface-elevated px-4 py-4">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-fg-muted mb-1">Watched entities</h3>+ <p className="text-[10px] text-fg-muted mb-3">+ Vendors, competitors or tickers this department cares about, one per line. Named here,+ the Executive will start watching their status pages, filings and feeds on its own and+ route what it finds to this department and its head.+ </p>+ <label className="text-xs text-fg-muted flex flex-col gap-1">+ Watched entities (one per line)+ <textarea+ value={settingsForm.watched_entities}+ onChange={(e) =>+ setSettingsForm((f) => ({ ...f, watched_entities: e.target.value }))+ }+ rows={4}+ placeholder={"Brex\nStripe\nACME"}+ className="px-2 py-1.5 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"+ />+ </label>+ </section>+{settingsErr && <p className="text-xs text-rose-300">{settingsErr}</p>}<buttondisabled={savingSettings}@@ -879,6 +910,9 @@ export default function DepartmentDetailPage() {...(dept.config.slack_channel_id ? [["Slack channel", dept.config.slack_channel_id]] : []),...(dept.config.discord_channel_id ? [["Discord channel", dept.config.discord_channel_id]] : []),...(dept.config.telegram_chat_id ? [["Telegram chat", dept.config.telegram_chat_id]] : []),+ ...((dept.config.watched_entities ?? []).length > 0+ ? [["Watched entities", (dept.config.watched_entities ?? []).join(", ")]]+ : []),].map(([label, value]) => (<div key={label} className="flex items-start gap-3 py-2"><div className="w-36 flex-shrink-0 text-xs text-fg-muted pt-0.5">{label}</div>diff --git a/packages/ui/src/app/watchlist/page.tsx b/packages/ui/src/app/watchlist/page.tsxindex fc8438b6..52ab6980 100644--- a/packages/ui/src/app/watchlist/page.tsx+++ b/packages/ui/src/app/watchlist/page.tsx@@ -8,6 +8,7 @@ import {createWatchlistItem,declineWatchSuggestion,deleteWatchlistItem,+ listDepartments,listWatchlist,patchWatchlistItem,type WatchDeclineReason,@@ -151,11 +152,13 @@ function SuggestionCard({busy,onApprove,onDecline,+ departmentTitle,}: {item: WatchlistItem;busy: boolean;onApprove: (slug: string) => void;onDecline: (slug: string, reason: WatchDeclineReason) => void;+ departmentTitle?: string;}) {const stamp = policyStamp(item);return (@@ -176,6 +179,11 @@ function SuggestionCard({{item.notes && <p className="text-xs text-fg mt-2">{item.notes}</p>}<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-fg-muted mt-2">{stamp.entity && <span>about: {stamp.entity}</span>}+ {item.route_to_department && (+ <span title="This department's head was asked to review it">+ for: {departmentTitle ?? item.route_to_department}+ </span>+ )}<span>suggested {formatRelTime(item.created_at)} ago</span><span>seen in shadow: {item.fired_count} signal{item.fired_count === 1 ? "" : "s"}</span>{stamp.source_url && (@@ -204,11 +212,13 @@ function WatchCard({onToggle,toggleBusy,onStopWatching,+ departmentTitle,}: {item: WatchlistItem;onToggle: (slug: string, enabled: boolean) => void;toggleBusy: boolean;onStopWatching?: (slug: string, reason: WatchDeclineReason) => void;+ departmentTitle?: string;}) {const isResearch = item.origin === "research";const stamp = policyStamp(item);@@ -234,6 +244,7 @@ function WatchCard({<p className="text-[11px] text-fg-muted mb-2"><span className="text-indigo-300">Added by the Executive</span>{stamp.entity ? ` · about ${stamp.entity}` : ""}+ {item.route_to_department ? ` · for ${departmentTitle ?? item.route_to_department}` : ""}{item.notes ? ` · ${item.notes}` : ""}</p>)}@@ -502,6 +513,8 @@ export default function WatchlistPage() {const [showAdd, setShowAdd] = useState(false);const [busySlugs, setBusySlugs] = useState<Set<string>>(new Set());const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});+ // slug → title for the "for: <department>" label on routed watches.+ const [departmentTitles, setDepartmentTitles] = useState<Record<string, string>>({});const toggleCollapsed = (key: string) =>setCollapsed((c) => ({ ...c, [key]: !c[key] }));@@ -544,6 +557,11 @@ export default function WatchlistPage() {useEffect(() => {refresh();+ listDepartments()+ .then((states) =>+ setDepartmentTitles(Object.fromEntries(states.map((d) => [d.config.slug, d.config.title]))),+ )+ .catch(() => {});}, []);function markBusy(slug: string, busy: boolean) {@@ -702,6 +720,7 @@ export default function WatchlistPage() {busy={busySlugs.has(item.slug)}onApprove={approve}onDecline={decline}+ departmentTitle={departmentTitles[item.route_to_department]}/>))}</div>@@ -742,6 +761,7 @@ export default function WatchlistPage() {onToggle={toggle}toggleBusy={busySlugs.has(item.slug)}onStopWatching={stopWatching}+ departmentTitle={departmentTitles[item.route_to_department]}/>))}</div>diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 426d052f..b6773691 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1870,6 +1870,10 @@ export interface DepartmentConfig {slack_channel_id: string | null;discord_channel_id: string | null;telegram_chat_id: string | null;+ // Named external entities this department wants monitored. The research+ // watch policy treats them as strong grounding: a proposal about one can+ // be added to the watch list on its own and is routed to this department.+ watched_entities: string[];}export type PeriodType = "week" | "month" | "quarter" | "year" | "ongoing";@@ -1924,6 +1928,7 @@ export interface DepartmentPatch {slack_channel_id?: string | null;discord_channel_id?: string | null;telegram_chat_id?: string | null;+ watched_entities?: string[];}export async function updateDepartment(slug: string, patch: DepartmentPatch): Promise<DepartmentState> {