AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(research): give the research run its own controls and a calmer cadence
Rufusbc8a08e4bbaa
diff --git a/.env.example b/.env.exampleindex eb338637..6fda9804 100644--- a/.env.example+++ b/.env.example@@ -254,9 +254,18 @@ PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED=true# Stop re-chasing the same stalled item forever (delivered nudges per item;# 0 disables the cap).NUDGE_MAX_PER_SCOPE=3+# Research council cadence: the periodic run is considered every+# WATCHLIST_RESEARCH_INTERVAL_MINUTES and skipped when nothing changed.+WATCHLIST_RESEARCH_INTERVAL_MINUTES=360# Force a research-council re-run at most this often when internal state is# unchanged (was daily; a daily forced run re-filed the same findings).WATCHLIST_RESEARCH_MAX_STALENESS_HOURS=168+# Web searches each research specialist may run per run (separate from+# WEB_SEARCH_MAX_USES, which chat and standing queries use).+RESEARCH_WEB_SEARCH_MAX_USES=3+# Specialists the research run fans out to (comma-separated slugs from+# cso, cfo, cmo, coo, chro, cpo, gc). Empty = all seven.+# RESEARCH_SPECIALISTS=cso,cfo,coo# Research watchlist policy: the research pass only proposes watches. A# proposal grounded in company data (a named competitor / vendor / ticker /# initiative) and corroborated is added on its own, quietly (at mostdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a43cf254..5d7f2620 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -112,6 +112,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0specialists were never told and their grounding rule dropped them. Theper-specialist finding cap is enforced in the tool schema and theparser, not only in prompt text.+- **The research run has its own controls.** `RESEARCH_WEB_SEARCH_MAX_USES`+ (default 3) caps searches per specialist independently of the chat knob;+ `RESEARCH_SPECIALISTS` picks which of the seven specialists run; the+ routing pass can no longer start a workflow (`run_workflow` is withheld,+ `suggest_workflow` remains); the periodic run's default interval moves+ from 120 to 360 minutes.### Removed- **The xcrawl scrape service and everything that depended on it.** Thediff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex fb871a8d..601ff4d1 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1164,7 +1164,7 @@ scheduler:- "principal_brief_eod — same shape as morning_brief, fires once per day at `PRINCIPAL_BRIEF_EOD_TIME` (default 18:00 UTC). Runs `end_of_day_digest` workflow. Both brief kinds bypass the per-channel anti-spam guards because the principal is by definition deliverable (channel_ref=`principal`, channel=`__internal__` triggers the workflow run rather than a direct send)."- "executive_reflection — Shift 5 recurring row. Seeded alongside the principal briefs (idempotent via `_has_pending_brief`), default 07:30 UTC, override via `PRINCIPAL_REFLECTION_TIME`. The scheduler runs `_run_executive_reflection`: invokes the `executive_reflection` workflow, stores the artifact via `complete_run`, audits the outcome, then chains the next occurrence — same crash-survival pattern as principal briefs. Unlike the briefs, the artifact is NOT delivered to the principal — the morning brief that fires 30 minutes later surfaces what reflection decided via the existing /today/activity rail."- "external_monitor_scan — heartbeat owned by the external-condition monitoring layer. Default every 5 min via EXTERNAL_MONITOR_SCAN_INTERVAL_MINUTES. The runner calls `monitoring.pipeline.run_external_monitor_scan()` which walks enabled watchlist rows whose `last_polled_at` is stale enough, fires the matching adapter (vendor_status, rss, stock, the billed standing-query `query` adapter, the `edgar` SEC-filings adapter, and the stateful `page_watch` change-detector), enriches promotable signals with capture-time relevance, writes `external_signals` rows, and promotes qualifying signals into the alerts pipeline. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`external_monitor`). Chains the next tick via `enqueue_next_external_monitor_scan` after firing — same idempotent / crash-resilient pattern as `nudge_scan`."- - "watchlist_research_scan — periodic cron for the executive_research workflow (default every 120 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 168 — weekly; a daily forced run re-derived the same findings from unchanged state and re-filed them as fresh alerts every morning) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) PROPOSES ongoing monitors via `propose_watch`; deterministic policy (`monitoring.research.watch_policy`, see external_monitoring) adds a proposal on its own only when it is grounded in company data and corroborated, files the rest as dry-run suggestions the principal approves on /watchlist, and refuses declined targets; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."+ - "watchlist_research_scan — periodic cron for the executive_research workflow (default every 360 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 168 — weekly; a daily forced run re-derived the same findings from unchanged state and re-filed them as fresh alerts every morning) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) PROPOSES ongoing monitors via `propose_watch`; deterministic policy (`monitoring.research.watch_policy`, see external_monitoring) adds a proposal on its own only when it is grounded in company data and corroborated, files the rest as dry-run suggestions the principal approves on /watchlist, and refuses declined targets; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."- "notion_sync_scan — optional heartbeat (NOTION_SYNC_ENABLED, default off) that incrementally re-indexes Notion pages shared with an internal integration into the isolated `notion_wiki` collection (NOT COMPANY — synced pages are multi-writer and unreviewed). Interval NOTION_SYNC_INTERVAL_MINUTES (default 60). Caps ingest per tick via NOTION_MAX_PAGES_PER_SCAN; overflow is retried and the watermark does not advance past failed or uningested pages. Each tick reconciles: un-shared/deleted pages have files + chunks purged. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`notion_sync`). Chains the next tick via enqueue_next_notion_sync_scan. See knowledge.collections NOTION_WIKI."channel_routing: |The delivery channel is stored ON the scheduled_actions row itself@@ -1533,7 +1533,8 @@ external_monitoring:DECLINED outcome for calibration). Tool-supplied reasons outside theexplicit set fall back to not_relevant.- isolation: the routing/synthesis pass has NO watchlist write tools- (add/tune/remove are in _SYNTHESIS_EXCLUDED_TOOLS), so every watch a+ (add/tune/remove are in _SYNTHESIS_EXCLUDED_TOOLS, as are+ run_executive_research, run_workflow and send_company_broadcast), so every watch aresearch run creates goes through the policy; tune_watchlist_entryaccepts only notes on a pending suggestion (approve/decline move it;its quiet defaults cannot be loosened while it waits); URL-typed@@ -1918,6 +1919,18 @@ external_monitoring:(3) three ways: the prompt says so, the tool schema carries`maxItems`, and `_extract_findings` keeps the first N for aprovider that does not enforce the schema.+ Controls: the fan-out's web_search tool takes its `max_uses` from+ `RESEARCH_WEB_SEARCH_MAX_USES` (default 3) — separate from the+ chat / query knob `WEB_SEARCH_MAX_USES`, because here it is+ multiplied by the number of specialists; `RESEARCH_SPECIALISTS`+ (comma-separated slugs, empty = all seven) filters the fan-out via+ `active_research_specialists` (unknown slugs are logged and+ dropped; an all-unknown value runs every specialist). The tool is+ the basic `web_search_20250305` variant on purpose: it is accepted+ by every Claude model the Council can pin as the research model+ (the newer dynamic-filtering variant and the web_fetch server tool+ are not — web fetch is unavailable on Opus 5 — and a research run+ must not fail on a model switch).The research turn's model + deep-reasoning are controlled by the`research` virtual Council agent (get_research_model() /get_research_use_deep_reasoning(): Council override → `RESEARCH_MODEL`@@ -1977,7 +1990,7 @@ external_monitoring:triggers:- "Manual chat — the principal asks 'what should we look into?'; the Executive calls the `run_executive_research` chat tool. The tool runs the workflow, which both researches AND routes; the chat tool returns the structured summary so the Executive can describe to the principal what it researched and what it did with each finding."- "Onboarding completion — when the wizard finishes (build_and_save_profile fires), `api/routes/onboarding._fire_post_onboarding_research` schedules the workflow as a background task. The workflow's synthesis step fires whatever routing tools it deems necessary (DMs to heads, briefing alert, watchlist additions) — the wrapper just runs the workflow with a wall-clock ceiling and creates / completes the workflow_run row."- - "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 120 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 168, i.e. weekly) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) proposes ongoing monitors via `propose_watch`; `monitoring.research.watch_policy` decides per proposal — direct add (grounded in company data: competitor / vendor / ticker / initiative / priority, score >= 4 on a fixed ledger, quiet defaults) vs dry-run suggestion for the principal vs reject — and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."+ - "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 360 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 168, i.e. weekly) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) proposes ongoing monitors via `propose_watch`; `monitoring.research.watch_policy` decides per proposal — direct add (grounded in company data: competitor / vendor / ticker / initiative / priority, score >= 4 on a fixed ledger, quiet defaults) vs dry-run suggestion for the principal vs reject — and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."skip_if_unchanged: |The periodic cron handler (`monitoring.research.scheduler.run_watchlist_research_scan`)computes a sha256 over (`CompanyProfile.to_prompt_block()`,@@ -1989,7 +2002,7 @@ external_monitoring:workflow, then audit with the new hash so the next tick canshort-circuit. Persistent profile-load failures fall back to astatic `"error:profile"` sentinel so a broken profile doesn't- burn 7 specialist calls every 2h.+ burn 7 specialist calls every 6h.The `state_hash` stored on a successful run is recomputed *after*the workflow finishes, NOT the pre-run hash used for the skipdiff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex adeed577..68adbcb5 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -459,6 +459,19 @@ class Settings(BaseSettings):# bulk of the value at a fraction of the search spend. Raise via# WEB_SEARCH_MAX_USES for deeper digs.web_search_max_uses: int = Field(2, alias="WEB_SEARCH_MAX_USES")+ # Searches per specialist in the executive_research fan-out. Separate+ # from the chat knob above because the fan-out multiplies it by the+ # number of specialists (seven by default), and every search adds+ # results that each later pass re-reads.+ research_web_search_max_uses: int = Field(+ 3, alias="RESEARCH_WEB_SEARCH_MAX_USES"+ )+ # Which specialists the research fan-out runs (comma-separated slugs+ # from cso, cfo, cmo, coo, chro, cpo, gc). Empty = all seven. Unknown+ # slugs are logged and skipped.+ research_specialists: Annotated[list[str], NoDecode] = Field(+ default_factory=list, alias="RESEARCH_SPECIALISTS"+ )web_search_allowed_domains: Annotated[list[str], NoDecode] = Field(default_factory=list, alias="WEB_SEARCH_ALLOWED_DOMAINS")@@ -467,7 +480,8 @@ class Settings(BaseSettings):)@field_validator(- "web_search_allowed_domains", "web_search_blocked_domains", mode="before"+ "web_search_allowed_domains", "web_search_blocked_domains",+ "research_specialists", mode="before",)@classmethoddef _parse_domain_list(cls, v: Any) -> list[str]:@@ -485,6 +499,8 @@ class Settings(BaseSettings):)if self.web_search_max_uses < 1:raise ValueError("WEB_SEARCH_MAX_USES must be >= 1")+ if self.research_web_search_max_uses < 1:+ raise ValueError("RESEARCH_WEB_SEARCH_MAX_USES must be >= 1")return self# Base URL of the UI, used when the Executive composes deep links@@ -675,7 +691,7 @@ class Settings(BaseSettings):True, alias="WATCHLIST_RESEARCH_ENABLED")watchlist_research_interval_minutes: int = Field(- 120, alias="WATCHLIST_RESEARCH_INTERVAL_MINUTES"+ 360, alias="WATCHLIST_RESEARCH_INTERVAL_MINUTES")# Staleness floor: even when the skip-if-unchanged fingerprint matches,# force a fresh research run once this many hours have elapsed since thediff --git a/packages/core/openexecutive/monitoring/research/scheduler.py b/packages/core/openexecutive/monitoring/research/scheduler.pyindex 4d055b9c..3f41942d 100644--- a/packages/core/openexecutive/monitoring/research/scheduler.py+++ b/packages/core/openexecutive/monitoring/research/scheduler.py@@ -2,7 +2,7 @@PR-D wired the workflow to two triggers (manual chat tool, onboardingcompletion). PR-E adds a third: a cron tick that re-runs the workflow-every ``watchlist_research_interval_minutes`` (default 120). The cost+every ``watchlist_research_interval_minutes`` (default 360). The costshape of a research run is real — 7 LLM calls × web_search — so eachtick first computes a fingerprint of the inputs the workflow reads(company profile, active initiatives, existing watchlist slugs) anddiff --git a/packages/core/openexecutive/monitoring/research/specialist_research.py b/packages/core/openexecutive/monitoring/research/specialist_research.pyindex 218d76c3..5128ee0a 100644--- a/packages/core/openexecutive/monitoring/research/specialist_research.py+++ b/packages/core/openexecutive/monitoring/research/specialist_research.py@@ -11,6 +11,7 @@ import loggingfrom typing import Anyfrom openexecutive.agents.base import BaseAgent+from openexecutive.config import get_settingsfrom openexecutive.monitoring.research.models import ResearchFindingfrom openexecutive.monitoring.research.prompts import (PER_SPECIALIST_FINDING_CAP,@@ -46,7 +47,11 @@ async def research_one_specialist()tools: list[dict[str, Any]] = [EMIT_RESEARCH_FINDINGS_TOOL]- web_search = build_web_search_tool()+ # The research fan-out has its own search cap: the shared chat knob is+ # multiplied by the number of specialists here.+ web_search = build_web_search_tool(+ max_uses=get_settings().research_web_search_max_uses,+ )if web_search is not None:tools.append(web_search)diff --git a/packages/core/openexecutive/orchestrator/web_search_tool.py b/packages/core/openexecutive/orchestrator/web_search_tool.pyindex 182396be..78f5d666 100644--- a/packages/core/openexecutive/orchestrator/web_search_tool.py+++ b/packages/core/openexecutive/orchestrator/web_search_tool.py@@ -20,11 +20,13 @@ from openexecutive.config import get_settingsWEB_SEARCH_TOOL_NAME = "web_search"-def build_web_search_tool() -> dict[str, Any] | None:+def build_web_search_tool(*, max_uses: int | None = None) -> dict[str, Any] | None:"""Return the Anthropic web_search tool dict, or None when disabled.Read at tool-list assembly time (per turn) so toggling the env var- without a restart takes effect on the next turn.+ without a restart takes effect on the next turn. ``max_uses`` overrides+ the shared ``WEB_SEARCH_MAX_USES`` knob for callers with their own+ (the research fan-out uses ``RESEARCH_WEB_SEARCH_MAX_USES``)."""settings = get_settings()if not settings.enable_web_search:@@ -33,7 +35,7 @@ def build_web_search_tool() -> dict[str, Any] | None:tool: dict[str, Any] = {"type": "web_search_20250305","name": WEB_SEARCH_TOOL_NAME,- "max_uses": settings.web_search_max_uses,+ "max_uses": max_uses if max_uses is not None else settings.web_search_max_uses,}if settings.web_search_allowed_domains:tool["allowed_domains"] = settings.web_search_allowed_domainsdiff --git a/packages/core/openexecutive/workflows/executive_research.py b/packages/core/openexecutive/workflows/executive_research.pyindex 7347733a..ee8d4ece 100644--- a/packages/core/openexecutive/workflows/executive_research.py+++ b/packages/core/openexecutive/workflows/executive_research.py@@ -70,6 +70,26 @@ RESEARCH_SPECIALISTS: tuple[str, ...] = ("cso", "cfo", "cmo", "coo", "chro", "cpo", "gc",)++def active_research_specialists() -> tuple[str, ...]:+ """The specialists this run fans out to: ``RESEARCH_SPECIALISTS``+ filtered by the ``RESEARCH_SPECIALISTS`` setting when it is set.+ Unknown slugs are logged and dropped; an empty or all-unknown setting+ means every specialist, so a typo cannot silently run nothing."""+ from openexecutive.config import get_settings++ wanted = [s.strip().lower() for s in get_settings().research_specialists if s.strip()]+ if not wanted:+ return RESEARCH_SPECIALISTS+ unknown = [s for s in wanted if s not in RESEARCH_SPECIALISTS]+ if unknown:+ logger.warning(+ "research: RESEARCH_SPECIALISTS names unknown specialist(s) %s — ignored",+ ", ".join(unknown),+ )+ chosen = tuple(s for s in RESEARCH_SPECIALISTS if s in wanted)+ return chosen or RESEARCH_SPECIALISTS+# Synthesis loop budget. A real routing run needs at least three turns:# (1) look recipients up (lookup_person), (2) fire the resolved DMs /# alerts, (3) emit the wrap-up summary. Two iterations starved that@@ -454,8 +474,9 @@ class ExecutiveResearchWorkflow(Workflow):)return slug, [], str(exc)[:200]+ specialists = active_research_specialists()results = await asyncio.gather(- *(_run_one(s) for s in RESEARCH_SPECIALISTS),+ *(_run_one(s) for s in specialists),return_exceptions=True,)@@ -464,8 +485,8 @@ class ExecutiveResearchWorkflow(Workflow):for idx, item in enumerate(results):if isinstance(item, BaseException):fallback_slug = (- RESEARCH_SPECIALISTS[idx]- if idx < len(RESEARCH_SPECIALISTS)+ specialists[idx]+ if idx < len(specialists)else f"unknown-{idx}")findings_by_specialist[fallback_slug] = []@@ -1038,6 +1059,10 @@ async def _watchlist_analysis_loop(# misfiring run blasting noise to the entire team._SYNTHESIS_EXCLUDED_TOOLS = frozenset({"run_executive_research",+ # Starting another workflow from inside the routing pass is the same+ # recursion risk in a different coat: a finding can suggest a workflow+ # (suggest_workflow) for a human to start, never start one itself.+ "run_workflow","send_company_broadcast",# Watchlist writes are withheld from the routing pass: every watch the# research run creates must go through the dedicated watchlist pass anddiff --git a/packages/core/tests/unit/test_research_controls.py b/packages/core/tests/unit/test_research_controls.pynew file mode 100644index 00000000..1caee24a--- /dev/null+++ b/packages/core/tests/unit/test_research_controls.py@@ -0,0 +1,86 @@+"""Unit tests for the research run's own controls: its web-search cap,+the specialist filter, the withheld workflow-start tool, and the periodic+cadence default."""+from __future__ import annotations++import os++import pytest++from openexecutive.config import get_settings+from openexecutive.orchestrator.web_search_tool import build_web_search_tool+from openexecutive.workflows import executive_research as er++_ENV = (+ "ENABLE_WEB_SEARCH",+ "WEB_SEARCH_MAX_USES",+ "RESEARCH_WEB_SEARCH_MAX_USES",+ "RESEARCH_SPECIALISTS",+ "WATCHLIST_RESEARCH_INTERVAL_MINUTES",+)++[email protected](autouse=True)+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:+ for key in _ENV:+ monkeypatch.delenv(key, raising=False)+++def test_defaults_are_reasonable() -> None:+ s = get_settings()+ assert s.research_web_search_max_uses == 3+ assert s.research_specialists == []+ assert s.watchlist_research_interval_minutes == 360+++def test_research_search_cap_is_independent_of_the_chat_knob(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("ENABLE_WEB_SEARCH", "true")+ monkeypatch.setenv("WEB_SEARCH_MAX_USES", "8")+ monkeypatch.setenv("RESEARCH_WEB_SEARCH_MAX_USES", "2")+ chat_tool = build_web_search_tool()+ research_tool = build_web_search_tool(max_uses=get_settings().research_web_search_max_uses)+ assert chat_tool is not None and chat_tool["max_uses"] == 8+ assert research_tool is not None and research_tool["max_uses"] == 2+ assert research_tool["type"] == "web_search_20250305"+++def test_research_search_cap_rejects_zero(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("RESEARCH_WEB_SEARCH_MAX_USES", "0")+ with pytest.raises(ValueError):+ get_settings()+++def test_specialist_filter_parses_and_keeps_registry_order(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("RESEARCH_SPECIALISTS", " coo, CSO ,cfo ")+ assert get_settings().research_specialists == ["coo", "CSO", "cfo"]+ assert er.active_research_specialists() == ("cso", "cfo", "coo")+++def test_specialist_filter_drops_unknown_and_never_runs_nothing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("RESEARCH_SPECIALISTS", "cfo,ceo")+ assert er.active_research_specialists() == ("cfo",)+ monkeypatch.setenv("RESEARCH_SPECIALISTS", "ceo,cto")+ assert er.active_research_specialists() == er.RESEARCH_SPECIALISTS+ monkeypatch.setenv("RESEARCH_SPECIALISTS", "")+ assert er.active_research_specialists() == er.RESEARCH_SPECIALISTS+++def test_routing_pass_cannot_start_a_workflow() -> None:+ assert "run_workflow" in er._SYNTHESIS_EXCLUDED_TOOLS+ assert "run_executive_research" in er._SYNTHESIS_EXCLUDED_TOOLS+ # Suggesting one for a human to start is still allowed.+ assert "suggest_workflow" not in er._SYNTHESIS_EXCLUDED_TOOLS+++def test_env_example_documents_the_controls() -> None:+ root = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")+ with open(os.path.join(root, ".env.example"), encoding="utf-8") as fh:+ text = fh.read()+ for key in ("RESEARCH_WEB_SEARCH_MAX_USES", "RESEARCH_SPECIALISTS", "WATCHLIST_RESEARCH_INTERVAL_MINUTES"):+ assert key in textdiff --git a/packages/core/tests/unit/test_research_focus_prompt.py b/packages/core/tests/unit/test_research_focus_prompt.pyindex 7097f79a..3c1f6e07 100644--- a/packages/core/tests/unit/test_research_focus_prompt.py+++ b/packages/core/tests/unit/test_research_focus_prompt.py@@ -71,10 +71,38 @@ def test_specialist_research_passes_resolved_knobs(agent = SimpleNamespace(analyze_with_tools=AsyncMock(side_effect=fake_analyze_with_tools))# Web search off so the tool list is deterministic.- monkeypatch.setattr(sr, "build_web_search_tool", lambda: None)+ monkeypatch.setattr(sr, "build_web_search_tool", lambda **_kw: None)asyncio.run(sr.research_one_specialist("cso", agent, "CONTEXT"))assert captured["model_override"] == "claude-cheap-research"assert captured["deep_reasoning_override"] is Falseassert "## TASK: RESEARCH FINDINGS" in captured["system_addendum"]+++def test_specialist_research_uses_the_research_search_cap(+ isolated_db: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The fan-out's web_search tool is capped by RESEARCH_WEB_SEARCH_MAX_USES,+ not the chat knob — the chat value is multiplied by seven here."""+ from openexecutive.monitoring.research import specialist_research as sr++ monkeypatch.setenv("WEB_SEARCH_MAX_USES", "8")+ monkeypatch.setenv("RESEARCH_WEB_SEARCH_MAX_USES", "2")+ seen: dict = {}++ def fake_build(**kwargs: object) -> dict:+ seen.update(kwargs)+ return {"type": "web_search_20250305", "name": "web_search", **kwargs}++ monkeypatch.setattr(sr, "build_web_search_tool", fake_build)+ tools_seen: dict = {}++ async def fake_analyze_with_tools(user_content: str, **kwargs: object) -> object:+ tools_seen.update(kwargs)+ return SimpleNamespace(content=[])++ agent = SimpleNamespace(analyze_with_tools=AsyncMock(side_effect=fake_analyze_with_tools))+ asyncio.run(sr.research_one_specialist("cfo", agent, "CONTEXT"))+ assert seen == {"max_uses": 2}+ assert any(t.get("name") == "web_search" and t.get("max_uses") == 2 for t in tools_seen["tools"])