Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

feat(agents): add Fast, Balanced and Thorough quality presets to the Agent Council (#309)

Rufus58ba2ec105b9
diff --git a/packages/core/openexecutive/agents/presets.py b/packages/core/openexecutive/agents/presets.py
new file mode 100644
index 00000000..76487070
--- /dev/null
+++ b/packages/core/openexecutive/agents/presets.py
@@ -0,0 +1,249 @@
+"""Quality presets for the Agent Council: Fast, Balanced and Thorough.
+
+A preset sets the model and deep-reasoning flag of every agent at once. It
+is not stored anywhere: applying one writes ordinary per-agent overrides
+(``agents.overrides.set_override`` / ``clear_override``), so history,
+rollback and later per-agent edits keep working, and the active preset is
+worked out from those overrides when the Council asks.
+
+Presets change quality only. They never cap spend.
+
+Model names are resolved at request time against the install's model
+allowlist (``providers.allowed_models_for``), taking the first preferred
+model the install can serve. A preset whose model this install can't reach
+is reported as unavailable rather than silently picking something else.
+
+This module is pure: callers pass each agent's defaults and current
+overrides in as ``AgentState`` and apply the returned ``AgentWrite`` list.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+
+from openexecutive.agents.overrides import EXECUTIVE_AGENT_ID
+from openexecutive.providers import model_supports_deep_reasoning
+
+PresetId = Literal["fast", "balanced", "thorough"]
+
+PRESET_IDS: tuple[PresetId, ...] = ("fast", "balanced", "thorough")
+# Order ``preset_status`` tries presets in; Balanced first so it wins ties.
+_STATUS_ORDER: tuple[PresetId, ...] = ("balanced", "fast", "thorough")
+
+# Specialists in SPECIALIST_REGISTRY that answer no user question directly.
+# Every other registered specialist, plus the Executive, is a "core" agent.
+_INTERNAL_SPECIALISTS = frozenset({"triage"})
+
+# Preferred models, best first. The first one the install allows wins.
+_FAST_MODELS: tuple[str, ...] = ("claude-haiku-4-5",)
+_THOROUGH_MODELS: tuple[str, ...] = ("claude-opus-5-5", "claude-opus-5")
+
+
+@dataclass(frozen=True)
+class PresetSpec:
+ id: PresetId
+ label: str
+ description: str
+
+
+PRESETS: dict[PresetId, PresetSpec] = {
+ "fast": PresetSpec(
+ id="fast",
+ label="Fast",
+ description=(
+ "A small, fast model for every agent, with deep reasoning off. "
+ "Quickest answers."
+ ),
+ ),
+ "balanced": PresetSpec(
+ id="balanced",
+ label="Balanced",
+ description="Each agent's built-in model and deep-reasoning setting.",
+ ),
+ "thorough": PresetSpec(
+ id="thorough",
+ label="Thorough",
+ description=(
+ "The largest model for the Executive and the specialists, with "
+ "deep reasoning on where the model supports it. Background "
+ "helpers keep their built-in settings."
+ ),
+ ),
+}
+
+
+@dataclass(frozen=True)
+class AgentState:
+ """One agent's defaults and current overrides (None = no override)."""
+
+ agent_id: str
+ model_default: str
+ deep_default: bool
+ model_override: str | None
+ deep_override: bool | None
+ # Whether the agent's own calls honour the deep-reasoning flag. The
+ # Executive's turn never sends thinking fields, so a preset leaves its
+ # flag alone.
+ uses_deep_reasoning: bool = True
+
+ @property
+ def model(self) -> str:
+ return self.model_override if self.model_override is not None else self.model_default
+
+ @property
+ def deep(self) -> bool:
+ return self.deep_override if self.deep_override is not None else self.deep_default
+
+
+@dataclass(frozen=True)
+class AgentTarget:
+ model: str
+ deep: bool
+
+
+@dataclass(frozen=True)
+class AgentWrite:
+ """Override values to store so the agent matches its preset target.
+
+ ``None`` clears the field back to the agent's default.
+ """
+
+ agent_id: str
+ model: str | None
+ deep: bool | None
+
+
+def is_core_agent(agent_id: str, specialist_ids: set[str]) -> bool:
+ """The Executive and the domain specialists a user would recognise."""
+ if agent_id == EXECUTIVE_AGENT_ID:
+ return True
+ return agent_id in specialist_ids and agent_id not in _INTERNAL_SPECIALISTS
+
+
+def _first_allowed(preferred: tuple[str, ...], allowed: list[str]) -> str | None:
+ allowed_set = set(allowed)
+ return next((m for m in preferred if m in allowed_set), None)
+
+
+def preset_model(preset_id: PresetId, allowed: list[str]) -> str | None:
+ """The model a preset moves agents to, or None when it keeps defaults
+ (Balanced) or when the install allows none of its preferred models."""
+ if preset_id == "fast":
+ return _first_allowed(_FAST_MODELS, allowed)
+ if preset_id == "thorough":
+ return _first_allowed(_THOROUGH_MODELS, allowed)
+ return None
+
+
+def preset_available(preset_id: PresetId, allowed: list[str]) -> bool:
+ return preset_id == "balanced" or preset_model(preset_id, allowed) is not None
+
+
+def target_for(
+ preset_id: PresetId, agent: AgentState, *, core: bool, allowed: list[str]
+) -> AgentTarget:
+ """What ``agent`` should run on under ``preset_id``.
+
+ Raises ``ValueError`` when the preset is unavailable on this install.
+ """
+ default = AgentTarget(model=agent.model_default, deep=agent.deep_default)
+ if preset_id == "balanced":
+ return default
+ model = preset_model(preset_id, allowed)
+ if model is None:
+ raise ValueError(f"Preset {preset_id!r} is not available on this install")
+ if preset_id == "fast":
+ deep = False if agent.uses_deep_reasoning else agent.deep_default
+ return AgentTarget(model=model, deep=deep)
+ # Thorough: core agents move up; background helpers keep their defaults.
+ if not core:
+ return default
+ deep = (
+ model_supports_deep_reasoning(model)
+ if agent.uses_deep_reasoning
+ else agent.deep_default
+ )
+ return AgentTarget(model=model, deep=deep)
+
+
+def matches(agent: AgentState, target: AgentTarget) -> bool:
+ return agent.model == target.model and agent.deep == target.deep
+
+
+def writes_for(
+ preset_id: PresetId,
+ agents: list[AgentState],
+ *,
+ specialist_ids: set[str],
+ allowed: list[str],
+) -> list[AgentWrite]:
+ """Override writes that bring every agent onto ``preset_id``.
+
+ Agents already on their target are left out, so applying the active
+ preset again writes nothing. A field whose target equals the agent's
+ default is cleared rather than stored, so Balanced leaves no model or
+ deep-reasoning override behind.
+ """
+ out: list[AgentWrite] = []
+ for agent in agents:
+ target = target_for(
+ preset_id,
+ agent,
+ core=is_core_agent(agent.agent_id, specialist_ids),
+ allowed=allowed,
+ )
+ if matches(agent, target):
+ continue
+ out.append(
+ AgentWrite(
+ agent_id=agent.agent_id,
+ model=None if target.model == agent.model_default else target.model,
+ deep=None if target.deep == agent.deep_default else target.deep,
+ )
+ )
+ return out
+
+
+@dataclass(frozen=True)
+class PresetStatus:
+ """Which preset the council is on.
+
+ ``active`` is the preset every agent matches, or None ("Custom").
+ ``base`` is the available preset the most agents match (Balanced on a
+ tie), and ``custom_agents`` lists the agents that differ from it.
+ """
+
+ active: PresetId | None
+ base: PresetId
+ custom_agents: list[str]
+
+
+def preset_status(
+ agents: list[AgentState], *, specialist_ids: set[str], allowed: list[str]
+) -> PresetStatus:
+ best: tuple[int, PresetId, list[str]] | None = None
+ for preset_id in _STATUS_ORDER:
+ if not preset_available(preset_id, allowed):
+ continue
+ diverging = [
+ a.agent_id
+ for a in agents
+ if not matches(
+ a,
+ target_for(
+ preset_id,
+ a,
+ core=is_core_agent(a.agent_id, specialist_ids),
+ allowed=allowed,
+ ),
+ )
+ ]
+ if best is None or len(diverging) < best[0]:
+ best = (len(diverging), preset_id, diverging)
+ assert best is not None # Balanced is always available.
+ _, base, diverging = best
+ return PresetStatus(
+ active=base if not diverging else None,
+ base=base,
+ custom_agents=diverging,
+ )
diff --git a/packages/core/openexecutive/api/routes/agents.py b/packages/core/openexecutive/api/routes/agents.py
index 8fdd2f6a..779a8759 100644
--- a/packages/core/openexecutive/api/routes/agents.py
+++ b/packages/core/openexecutive/api/routes/agents.py
@@ -18,6 +18,16 @@ from openexecutive.agents.overrides import (
rollback_to,
set_override,
)
+from openexecutive.agents.presets import (
+ PRESET_IDS,
+ PRESETS,
+ AgentState,
+ PresetId,
+ preset_available,
+ preset_model,
+ preset_status,
+ writes_for,
+)
from openexecutive.audit.usage import log_model_usage
logger = logging.getLogger(__name__)
@@ -387,6 +397,135 @@ def _is_known_agent(agent_id: str) -> bool:
return agent_id == EXECUTIVE_ID or agent_id in _agent_registry()
+class QualityPreset(BaseModel):
+ id: PresetId
+ label: str
+ description: str
+ # False when this install allows none of the preset's models.
+ available: bool
+ # The model the preset moves agents to on this install; null for
+ # Balanced (each agent keeps its own default) or when unavailable.
+ model: str | None = None
+
+
+class QualityPresets(BaseModel):
+ presets: list[QualityPreset]
+ # The preset every agent matches, or null when the council is "Custom".
+ active: PresetId | None
+ # The preset most agents match, and the agents that differ from it.
+ base: PresetId
+ custom_agents: list[str]
+
+
+# Agents whose calls never send thinking fields, so a preset leaves their
+# deep-reasoning flag alone.
+_NO_DEEP_REASONING = frozenset({EXECUTIVE_ID, "utility_fast"})
+
+
+def _agent_states() -> list[AgentState]:
+ states: list[AgentState] = []
+ for name, agent in _agent_registry().items():
+ ov = get_override(name)
+ if name == EXECUTIVE_ID:
+ model_default = _ExecutiveDefaults.model()
+ deep_default = _ExecutiveDefaults.use_deep_reasoning
+ else:
+ model_default = agent.model
+ deep_default = agent.use_deep_reasoning
+ states.append(
+ AgentState(
+ agent_id=name,
+ model_default=model_default,
+ deep_default=deep_default,
+ model_override=ov.model if ov is not None else None,
+ deep_override=ov.use_deep_reasoning if ov is not None else None,
+ uses_deep_reasoning=name not in _NO_DEEP_REASONING,
+ )
+ )
+ return states
+
+
+def _specialist_ids() -> set[str]:
+ from openexecutive.orchestrator.router import SPECIALIST_REGISTRY
+
+ return set(SPECIALIST_REGISTRY)
+
+
+def _quality_presets() -> QualityPresets:
+ allowed = _allowed()
+ status_ = preset_status(
+ _agent_states(), specialist_ids=_specialist_ids(), allowed=allowed
+ )
+ return QualityPresets(
+ presets=[
+ QualityPreset(
+ id=pid,
+ label=PRESETS[pid].label,
+ description=PRESETS[pid].description,
+ available=preset_available(pid, allowed),
+ model=preset_model(pid, allowed),
+ )
+ for pid in PRESET_IDS
+ ],
+ active=status_.active,
+ base=status_.base,
+ custom_agents=status_.custom_agents,
+ )
+
+
[email protected]("/agents/presets", response_model=QualityPresets)
+def list_presets() -> QualityPresets:
+ """Fast, Balanced and Thorough, resolved against this install's model
+ allowlist, plus which one the council is on."""
+ return _quality_presets()
+
+
[email protected]("/agents/presets/{preset_id}", response_model=QualityPresets)
+def apply_preset(preset_id: str) -> QualityPresets:
+ """Move every agent onto a preset by writing ordinary overrides.
+
+ Only the model and deep-reasoning fields change; prompts, roles, voice
+ and instructions stay as they are. Each agent that changes gets one
+ history row, so a single agent can be rolled back on its own. An
+ override left with nothing in it is removed, so Balanced returns an
+ untouched agent to its plain defaults.
+ """
+ if preset_id not in PRESETS:
+ raise HTTPException(status_code=404, detail="Unknown preset")
+ pid: PresetId = PRESETS[preset_id].id
+ allowed = _allowed()
+ if not preset_available(pid, allowed):
+ raise HTTPException(
+ status_code=409,
+ detail=f"The {PRESETS[pid].label} preset needs a model this install doesn't offer",
+ )
+ for write in writes_for(
+ pid, _agent_states(), specialist_ids=_specialist_ids(), allowed=allowed
+ ):
+ ov = get_override(write.agent_id)
+ keeps_other_fields = ov is not None and any(
+ v is not None
+ for v in (
+ ov.prompt,
+ ov.role,
+ ov.voice_persona_slug,
+ ov.research_focus,
+ ov.instructions,
+ )
+ )
+ if write.model is None and write.deep is None and not keeps_other_fields:
+ clear_override(write.agent_id)
+ continue
+ set_override(
+ write.agent_id,
+ model=write.model,
+ use_deep_reasoning=write.deep,
+ model_set=True,
+ deep_set=True,
+ )
+ return _quality_presets()
+
+
@router.get("/agents", response_model=list[AgentMeta])
async def list_agents() -> list[AgentMeta]:
# Executive is rendered first so the Council UI puts it at the top of
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 43b9919d..b57ab337 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -466,6 +466,25 @@ providers:
instructions keep the agent on the built-in prompt, so prompt upgrades
still reach it. PATCH /agents/{id} and /test accept ``instructions``
(max 4,000 chars; blank clears it).
+ quality_presets: |
+ The Council's Quality choice (agents/presets.py) sets every agent's model
+ and deep-reasoning flag at once. Fast: a small model (claude-haiku-4-5)
+ for every agent, deep reasoning off. Balanced: each agent's built-in
+ defaults. Thorough: the largest allowed model (claude-opus-5-5, then
+ claude-opus-5) for the Executive and the domain specialists, deep
+ reasoning on where model_supports_deep_reasoning allows; triage and the
+ Council-only helpers keep their defaults. Presets change quality only and
+ never cap spend. Models resolve at request time against
+ providers.allowed_models_for; a preset none of whose models the install
+ allows is reported unavailable (POST returns 409) instead of picking
+ something else. There is no preset table: POST /agents/presets/{id}
+ writes ordinary agent_overrides rows (model and use_deep_reasoning only,
+ leaving prompt, role, voice and instructions alone), one history row per
+ agent that changes, clearing a field whose target equals the default and
+ deleting a row left empty. GET /agents/presets works out the active
+ preset from the overrides: ``active`` when every agent matches,
+ otherwise null ("Custom") with ``base`` (the preset most agents match,
+ Balanced on a tie) and ``custom_agents`` (the agents that differ).
per_specialist_research_focus: |
Each consult-routable specialist (cso, cfo, cmo, coo, chro, cpo, gc) has a
Council-editable ``research_focus`` override — the per-domain scope tail
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index b450d1fa..e9ab713d 100644
--- a/packages/core/openexecutive/architecture/prebuilt/agents.json
+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json
@@ -1,7 +1,7 @@
{
"section_id": "agents",
"title": "Agent Council",
- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own Gmail; it never sends. It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own Gmail; it never sends. It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
"mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo / sales<br/>board_comms / triage\"]\n Mode{{\"Team or solo<br/>(persona + tools per turn)\"}} --> Exec\n Exec -->|\"ghostwrite_email (Act as me)\"| Gw[\"ghostwriter<br/>(tool-less, not a Council agent)\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Mode compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external\n class Gw compute",
- "generated_at": "2026-10-01T15:38:41Z"
+ "generated_at": "2026-10-01T16:28:49Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index f1f44905..e51bd3a8 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). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. 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`, `POST /chat/stop` | 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. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\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. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). |\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`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `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. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command}}`, where `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their Gmail isn't connected, Google refuses it or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the header itself is trusted from whoever holds the shared secret, the UI proxy, as on every principal-only route). Every change writes a private audit row. |\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, and by source — the part of the system that made the calls — including server-side web-search counts). Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own Gmail (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|notion}/sync`, `GET /documents/{drive\\|notion}`, `GET /documents/{drive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|notion}/{id}` returns the stored text for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (both syncs hold a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\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). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\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`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only: `GET /workflows/runs` and `GET /workflows/runs/{run_id}` read stored runs under their existing rules. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). The principal's own peer memory — drawn from all their conversations, contacts included — is shown to the principal only: anyone else's overview omits that entry (and its conclusions from `conclusion_total`), and their `/conclusions` request for the principal is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\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). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. 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`, `POST /chat/stop` | 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. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\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. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). |\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`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `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. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command}}`, where `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their Gmail isn't connected, Google refuses it or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the header itself is trusted from whoever holds the shared secret, the UI proxy, as on every principal-only route). Every change writes a private audit row. |\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, and by source — the part of the system that made the calls — including server-side web-search counts). Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own Gmail (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|notion}/sync`, `GET /documents/{drive\\|notion}`, `GET /documents/{drive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|notion}/{id}` returns the stored text for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (both syncs hold a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\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). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\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`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only: `GET /workflows/runs` and `GET /workflows/runs/{run_id}` read stored runs under their existing rules. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). The principal's own peer memory — drawn from all their conversations, contacts included — is shown to the principal only: anyone else's overview omits that entry (and its conclusions from `conclusion_total`), and their `/conclusions` request for the principal is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\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-10-01T15:45:00Z"
+ "generated_at": "2026-10-01T16:28:49Z"
}
diff --git a/packages/core/tests/unit/test_agent_presets.py b/packages/core/tests/unit/test_agent_presets.py
new file mode 100644
index 00000000..022ce0d5
--- /dev/null
+++ b/packages/core/tests/unit/test_agent_presets.py
@@ -0,0 +1,192 @@
+"""Quality presets: resolution against the allowlist, "Custom" detection and
+the override writes behind POST /agents/presets/{id}."""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
+
+from openexecutive.agents import overrides as ov_mod # noqa: E402
+from openexecutive.agents.presets import ( # noqa: E402
+ AgentState,
+ preset_available,
+ preset_model,
+ preset_status,
+ target_for,
+ writes_for,
+)
+from openexecutive.api.routes import agents as agents_route # noqa: E402
+
+FULL = ["claude-fable-5-1", "claude-opus-5-5", "claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5"]
+SPECIALISTS = {"cfo", "triage"}
+
+
+def _agents() -> list[AgentState]:
+ return [
+ AgentState("executive", "claude-sonnet-5", False, None, None, uses_deep_reasoning=False),
+ AgentState("cfo", "claude-opus-5", True, None, None),
+ AgentState("triage", "claude-sonnet-5", False, None, None),
+ AgentState("utility_fast", "claude-haiku-4-5", False, None, None, uses_deep_reasoning=False),
+ ]
+
+
+# --- pure resolution -------------------------------------------------------
+
+
+def test_preset_models_resolve_against_full_allowlist() -> None:
+ assert preset_model("fast", FULL) == "claude-haiku-4-5"
+ assert preset_model("thorough", FULL) == "claude-opus-5-5"
+ assert preset_model("balanced", FULL) is None
+
+
+def test_thorough_falls_back_to_next_allowed_model() -> None:
+ reduced = ["claude-opus-5", "claude-sonnet-5"]
+ assert preset_model("thorough", reduced) == "claude-opus-5"
+ assert preset_available("thorough", reduced)
+ # No small model allowed: Fast can't be offered.
+ assert not preset_available("fast", reduced)
+
+
+def test_local_only_install_offers_only_balanced() -> None:
+ local = ["llama3:8b"]
+ assert preset_available("balanced", local)
+ assert not preset_available("fast", local)
+ assert not preset_available("thorough", local)
+ with pytest.raises(ValueError):
+ target_for("fast", _agents()[1], core=True, allowed=local)
+
+
+def test_thorough_moves_core_agents_only() -> None:
+ agents = {a.agent_id: a for a in _agents()}
+ cfo = target_for("thorough", agents["cfo"], core=True, allowed=FULL)
+ assert (cfo.model, cfo.deep) == ("claude-opus-5-5", True)
+ # The Executive never sends thinking fields, so its flag stays put.
+ exe = target_for("thorough", agents["executive"], core=True, allowed=FULL)
+ assert (exe.model, exe.deep) == ("claude-opus-5-5", False)
+ tri = target_for("thorough", agents["triage"], core=False, allowed=FULL)
+ assert (tri.model, tri.deep) == ("claude-sonnet-5", False)
+
+
+def test_fast_turns_deep_reasoning_off() -> None:
+ cfo = target_for("fast", _agents()[1], core=True, allowed=FULL)
+ assert (cfo.model, cfo.deep) == ("claude-haiku-4-5", False)
+
+
+def test_writes_store_only_what_differs_from_defaults() -> None:
+ writes = {w.agent_id: w for w in writes_for("fast", _agents(), specialist_ids=SPECIALISTS, allowed=FULL)}
+ # utility_fast already runs Haiku: nothing to write.
+ assert "utility_fast" not in writes
+ assert (writes["cfo"].model, writes["cfo"].deep) == ("claude-haiku-4-5", False)
+ # Deep reasoning is already off by default for triage, so it isn't stored.
+ assert (writes["triage"].model, writes["triage"].deep) == ("claude-haiku-4-5", None)
+
+
+def test_balanced_on_fresh_install_writes_nothing() -> None:
+ assert writes_for("balanced", _agents(), specialist_ids=SPECIALISTS, allowed=FULL) == []
+
+
+def test_status_is_balanced_on_fresh_install() -> None:
+ st = preset_status(_agents(), specialist_ids=SPECIALISTS, allowed=FULL)
+ assert (st.active, st.base, st.custom_agents) == ("balanced", "balanced", [])
+
+
+def test_status_reports_custom_agents() -> None:
+ agents = _agents()
+ agents[1] = AgentState("cfo", "claude-opus-5", True, "claude-sonnet-5", None)
+ st = preset_status(agents, specialist_ids=SPECIALISTS, allowed=FULL)
+ assert st.active is None
+ assert st.base == "balanced"
+ assert st.custom_agents == ["cfo"]
+
+
+# --- HTTP ------------------------------------------------------------------
+
+
+def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ db = tmp_path / "agents.db"
+ monkeypatch.setattr(ov_mod, "DB_PATH", db)
+ ov_mod.invalidate_cache()
+ app = FastAPI()
+ app.include_router(agents_route.router)
+ yield TestClient(app)
+ ov_mod.invalidate_cache()
+
+
+def test_get_presets_on_fresh_install(client: TestClient) -> None:
+ res = client.get("/agents/presets")
+ assert res.status_code == 200
+ body = res.json()
+ assert [p["id"] for p in body["presets"]] == ["fast", "balanced", "thorough"]
+ assert all(p["available"] for p in body["presets"])
+ assert body["active"] == "balanced"
+ assert body["custom_agents"] == []
+
+
+def test_apply_thorough_then_balanced_round_trips(client: TestClient) -> None:
+ res = client.post("/agents/presets/thorough")
+ assert res.status_code == 200
+ assert res.json()["active"] == "thorough"
+ cfo = client.get("/agents/cfo").json()
+ assert cfo["model"] == "claude-opus-5-5"
+ assert cfo["deep_reasoning"] is True
+ # Background helpers keep their defaults under Thorough.
+ assert client.get("/agents/triage").json()["has_override"] is False
+
+ res = client.post("/agents/presets/balanced")
+ assert res.json()["active"] == "balanced"
+ # Overrides that only held the preset's model are removed entirely.
+ agents = client.get("/agents").json()
+ assert all(a["has_override"] is False for a in agents)
+
+
+def test_apply_preset_writes_one_history_row_per_agent(client: TestClient) -> None:
+ client.patch("/agents/cfo", json={"instructions": "Prefer tables."})
+ client.post("/agents/presets/fast")
+ history = client.get("/agents/cfo/history").json()
+ # The instructions-only row was snapshotted once by the preset.
+ assert len(history) == 1
+ assert history[0]["instructions"] == "Prefer tables."
+ assert history[0]["model"] is None
+ detail = client.get("/agents/cfo").json()
+ assert detail["model"] == "claude-haiku-4-5"
+ assert detail["instructions"] == "Prefer tables." # untouched
+
+ # Balanced keeps the row because it still holds instructions.
+ client.post("/agents/presets/balanced")
+ detail = client.get("/agents/cfo").json()
+ assert detail["has_override"] is True
+ assert detail["overridden_fields"] == ["instructions"]
+
+
+def test_reapplying_active_preset_writes_nothing(client: TestClient) -> None:
+ client.post("/agents/presets/fast")
+ before = len(client.get("/agents/cfo/history").json())
+ client.post("/agents/presets/fast")
+ assert len(client.get("/agents/cfo/history").json()) == before
+
+
+def test_one_agent_edit_marks_it_custom(client: TestClient) -> None:
+ client.post("/agents/presets/fast")
+ client.patch("/agents/cso", json={"model": "claude-sonnet-5"})
+ body = client.get("/agents/presets").json()
+ assert body["active"] is None
+ assert body["base"] == "fast"
+ assert body["custom_agents"] == ["cso"]
+
+
+def test_unknown_preset_404(client: TestClient) -> None:
+ assert client.post("/agents/presets/cheapest").status_code == 404
+
+
+def test_unavailable_preset_409(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(agents_route, "_allowed", lambda agent_id=None: ["claude-sonnet-5"])
+ body = client.get("/agents/presets").json()
+ avail = {p["id"]: p["available"] for p in body["presets"]}
+ assert avail == {"fast": False, "balanced": True, "thorough": False}
+ assert client.post("/agents/presets/fast").status_code == 409
diff --git a/packages/core/tests/unit/test_pr_checks.py b/packages/core/tests/unit/test_pr_checks.py
index 6c4918ce..c30ba4e8 100644
--- a/packages/core/tests/unit/test_pr_checks.py
+++ b/packages/core/tests/unit/test_pr_checks.py
@@ -122,11 +122,38 @@ def test_no_stubs_ignores_docs_and_exempt_files() -> None:
# --- eval-scenarios ----------------------------------------------------------
+_SALES_AGENT = {PKG + "agents/sales.py": ["class SalesAgent(BaseAgent):", ' name = "sales"']}
+
+
def test_eval_scenarios_required_for_new_agent() -> None:
added = {PKG + "agents/sales.py"}
- assert _level(pr_checks.check_eval_scenarios, added=added) == "FAIL"
+ lines = _SALES_AGENT
+ assert _level(pr_checks.check_eval_scenarios, added=added, added_lines=lines) == "FAIL"
changed = {PKG + "evals/_scenarios/sales_001.yaml"}
- assert _level(pr_checks.check_eval_scenarios, changed=changed, added=added) == "PASS"
+ assert (
+ _level(pr_checks.check_eval_scenarios, changed=changed, added=added, added_lines=lines)
+ == "PASS"
+ )
+
+
+ "lines",
+ [
+ ["class FooAgent(", " BaseAgent,", "):", ' name = "foo"'],
+ ["class FooAgent(SalesAgent):", ' name = "foo"'],
+ ],
+ ids=["wrapped-bases", "subclass-of-an-agent"],
+)
+def test_eval_scenarios_required_for_any_agent_class_header(lines: list[str]) -> None:
+ added = {PKG + "agents/foo.py"}
+ level = _level(pr_checks.check_eval_scenarios, added=added, added_lines={PKG + "agents/foo.py": lines})
+ assert level == "FAIL"
+
+
+def test_eval_scenarios_not_required_for_new_helper_module() -> None:
+ added = {PKG + "agents/presets.py"}
+ lines = {PKG + "agents/presets.py": ["class PresetSpec:", "def target_for(agent: BaseAgent):"]}
+ assert _level(pr_checks.check_eval_scenarios, added=added, added_lines=lines) == "PASS"
def test_eval_scenarios_required_for_domain_prompt_change() -> None:
@@ -297,7 +324,7 @@ def test_collect_and_main_against_a_real_repo(
slack.write_text("x = 1\ny = 2 # TODO\n") # uncommitted edit
new = repo / PKG / "agents" / "sales.py"
new.parent.mkdir(parents=True)
- new.write_text("z = 3\n") # untracked file
+ new.write_text("class SalesAgent(BaseAgent):\n z = 3\n") # untracked file
monkeypatch.chdir(repo)
monkeypatch.delenv("PR_BODY", raising=False)
diff --git a/packages/ui/src/app/council/page.tsx b/packages/ui/src/app/council/page.tsx
index 0a14a20a..118ef939 100644
--- a/packages/ui/src/app/council/page.tsx
+++ b/packages/ui/src/app/council/page.tsx
@@ -9,6 +9,9 @@ import {
Persona,
ModelOption,
PersonaMeta,
+ QualityPresetId,
+ QualityPresets,
+ applyQualityPreset,
createPersona,
deletePersona,
getAgentDetail,
@@ -17,6 +20,7 @@ import {
listAgentModelOptions,
listAgents,
listPersonas,
+ listQualityPresets,
patchAgent,
resetAgent,
resetPersona,
@@ -119,6 +123,9 @@ export default function CouncilPage() {
const [history, setHistory] = useState<AgentHistoryEntry[]>([]);
const [historyOpen, setHistoryOpen] = useState(false);
+ const [presets, setPresets] = useState<QualityPresets | null>(null);
+ const [applyingPreset, setApplyingPreset] = useState<QualityPresetId | null>(null);
+
const [saving, setSaving] = useState(false);
const [resetting, setResetting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -140,6 +147,8 @@ export default function CouncilPage() {
const [newPersonaBody, setNewPersonaBody] = useState("");
const refreshAgents = useCallback(async () => {
+ // Any agent change can move the council on or off a preset.
+ listQualityPresets().then(setPresets).catch(() => {});
try {
const list = await listAgents();
setAgents(list);
@@ -282,6 +291,32 @@ export default function CouncilPage() {
}
};
+ const handleApplyPreset = async (id: QualityPresetId) => {
+ const preset = presets?.presets.find((p) => p.id === id);
+ if (!preset) return;
+ if (
+ !window.confirm(
+ `Switch every agent to ${preset.label}? This changes each agent's model and deep reasoning; ` +
+ "prompts and instructions stay as they are, and earlier settings move to history."
+ )
+ )
+ return;
+ setApplyingPreset(id);
+ setError(null);
+ try {
+ setPresets(await applyQualityPreset(id));
+ await refreshAgents();
+ if (selected) await loadDetail(selected);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Failed to apply preset");
+ } finally {
+ setApplyingPreset(null);
+ }
+ };
+
+ const customAgents = new Set(presets?.custom_agents ?? []);
+ const basePresetLabel = presets?.presets.find((p) => p.id === presets.base)?.label;
+
const handleReset = async () => {
if (!selected) return;
if (!window.confirm("Reset this agent to defaults? Current override will move to history.")) return;
@@ -364,6 +399,14 @@ export default function CouncilPage() {
</span>
<span className="block truncate text-fg-muted">{a.role}</span>
</span>
+ {customAgents.has(a.name) && (
+ <span
+ className="mt-0.5 text-[9px] uppercase tracking-widest px-1 rounded bg-surface-overlay text-fg-subtle"
+ title={`Differs from the ${basePresetLabel ?? ""} preset`}
+ >
+ Custom
+ </span>
+ )}
</button>
))}
</nav>
@@ -386,6 +429,56 @@ export default function CouncilPage() {
</div>
)}
+ {presets && (
+ <section className="rounded-xl border border-line bg-surface px-6 py-5 space-y-3">
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-semibold text-fg">Quality</h2>
+ {presets.active === null && (
+ <span
+ className="text-[10px] uppercase tracking-widest px-2 py-1 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20"
+ title={`${presets.custom_agents.length} agent(s) differ from ${basePresetLabel ?? "the preset"}`}
+ >
+ Custom
+ </span>
+ )}
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
+ {presets.presets.map((p) => {
+ const current = presets.active === p.id;
+ const base = presets.active === null && presets.base === p.id;
+ return (
+ <button
+ key={p.id}
+ onClick={() => handleApplyPreset(p.id)}
+ disabled={!p.available || current || applyingPreset !== null}
+ aria-pressed={current}
+ title={p.available ? undefined : "This install offers none of this preset's models"}
+ className={`text-left rounded-lg border px-3 py-2 transition-colors disabled:cursor-not-allowed ${
+ current
+ ? "border-indigo-500/40 bg-indigo-500/10"
+ : base
+ ? "border-indigo-500/20 border-dashed"
+ : "border-line hover:border-line-strong"
+ } ${p.available ? "" : "opacity-40"}`}
+ >
+ <span className="block text-sm font-medium text-fg">
+ {applyingPreset === p.id ? "Applying…" : p.label}
+ </span>
+ <span className="block text-xs text-fg-muted mt-0.5">{p.description}</span>
+ {p.model && (
+ <span className="block text-[10px] text-fg-subtle mt-1 font-mono">{p.model}</span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-[11px] text-fg-subtle">
+ A preset sets every agent&apos;s model and deep reasoning at once. Changing one agent
+ below marks it Custom; each agent keeps its own history.
+ </p>
+ </section>
+ )}
+
{detail && draft ? (
<div className="space-y-6">
<div className="rounded-xl border border-line bg-surface px-6 py-5 space-y-4">
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index bc6df252..035ddf59 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -2702,6 +2702,44 @@ export async function testAgent(
return res.json();
}
+// Quality presets (Fast / Balanced / Thorough). Mirrors QualityPresets in
+// api/routes/agents.py. A preset is applied as ordinary per-agent
+// overrides, so `active` is null ("Custom") once any agent is changed on
+// its own; `custom_agents` lists the agents that differ from `base`.
+export type QualityPresetId = "fast" | "balanced" | "thorough";
+
+export interface QualityPreset {
+ id: QualityPresetId;
+ label: string;
+ description: string;
+ available: boolean;
+ model: string | null;
+}
+
+export interface QualityPresets {
+ presets: QualityPreset[];
+ active: QualityPresetId | null;
+ base: QualityPresetId;
+ custom_agents: string[];
+}
+
+export async function listQualityPresets(): Promise<QualityPresets> {
+ const res = await fetch(`${API_BASE}/agents/presets`);
+ if (!res.ok) throw new Error("Failed to load quality presets");
+ return res.json();
+}
+
+export async function applyQualityPreset(id: QualityPresetId): Promise<QualityPresets> {
+ const res = await fetch(`${API_BASE}/agents/presets/${encodeURIComponent(id)}`, {
+ method: "POST",
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error((err as { detail?: string }).detail ?? "Failed to apply preset");
+ }
+ return res.json();
+}
+
// One allowlisted model, grouped for the Council's Provider → Model picker.
// Mirrors ModelOption in api/routes/agents.py. `route` says which backend
// actually serves the id (it mirrors providers.registry.get_provider).
diff --git a/scripts/pr_checks.py b/scripts/pr_checks.py
index c57965cf..552ba53c 100644
--- a/scripts/pr_checks.py
+++ b/scripts/pr_checks.py
@@ -213,9 +213,20 @@ def check_no_stubs(c: Change) -> Result:
return Result("no-stubs", "PASS", "no stub markers added")
+# A class whose bases name an agent class (BaseAgent, or another agent such
+# as SalesAgent), with the base list possibly wrapped over several lines.
+_AGENT_CLASS_RE = re.compile(r"^class\s+\w+\s*\([^)]*\b\w*Agent\b", re.MULTILINE)
+
+
def check_eval_scenarios(c: Change) -> Result:
+ # A new public module under agents/ counts as a new agent only when it
+ # subclasses BaseAgent; a helper module beside the agents (overrides,
+ # presets) needs no eval scenario.
new_agent = any(
- p.startswith(AGENTS) and p.endswith(".py") and not p.rsplit("/", 1)[-1].startswith("_")
+ p.startswith(AGENTS)
+ and p.endswith(".py")
+ and not p.rsplit("/", 1)[-1].startswith("_")
+ and _AGENT_CLASS_RE.search("\n".join(c.added_lines.get(p, []))) is not None
for p in c.added
)
prompt_change = DOMAIN_PROMPTS in c.changed